Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- flutter/engine/src/flutter/shell/platform/android/context/BUILD.gnAdded+26
- flutter/engine/src/flutter/shell/platform/android/context/android_context.ccAdded+47
- flutter/engine/src/flutter/shell/platform/android/context/android_context.hAdded+86
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/BUILD.gnAdded+55
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.ccAdded+277
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.hAdded+154
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.ccAdded+269
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.hAdded+152
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_unittests.ccAdded+1082
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.ccAdded+134
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.hAdded+118
- flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool_unittests.ccAdded+353
- flutter/engine/src/flutter/shell/platform/android/io/flutter/Build.javaAdded+47
- flutter/engine/src/flutter/shell/platform/android/io/flutter/BuildConfig.javaAdded+19
- flutter/engine/src/flutter/shell/platform/android/io/flutter/FlutterInjector.javaAdded+185
- flutter/engine/src/flutter/shell/platform/android/io/flutter/Log.javaAdded+104
- flutter/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterApplication.javaAdded+18
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ActivityLifecycleListener.javaAdded+9
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BasicMessageChannel.javaAdded+275
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryCodec.javaAdded+66
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.javaAdded+205
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ErrorLogResult.javaAdded+45
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/EventChannel.javaAdded+274
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterException.javaAdded+25
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.javaAdded+63
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.javaAdded+122
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONUtil.javaAdded+108
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.javaAdded+39
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.javaAdded+102
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodChannel.javaAdded+293
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.javaAdded+92
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.javaAdded+75
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.javaAdded+460
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.javaAdded+135
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringCodec.javaAdded+57
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/FlutterTextUtils.javaAdded+319
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.javaAdded+205
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.javaAdded+595
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ListenableEditingState.javaAdded+296
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ScribePlugin.javaAdded+106
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/SpellCheckPlugin.javaAdded+183
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextEditingDelta.javaAdded+132
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.javaAdded+852
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/localization/LocalizationPlugin.javaAdded+208
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.javaAdded+136
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/AccessibilityEventsDelegate.javaAdded+61
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.javaAdded+139
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformOverlayView.javaAdded+49
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformPlugin.javaAdded+626
- flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformView.javaAdded+81
1234567891011121314151617181920212223242526# Copyright 2013 The Flutter 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" ] }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// Copyright 2013 The Flutter 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<GrDirectContext>& main_context) { main_context_ = main_context;}
sk_sp<GrDirectContext> AndroidContext::GetMainSkiaContext() const { return main_context_;}
std::shared_ptr<impeller::Context> AndroidContext::GetImpellerContext() const { return impeller_context_;}
void AndroidContext::SetImpellerContext( const std::shared_ptr<impeller::Context>& context) { impeller_context_ = context;}
} // namespace flutter1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586// Copyright 2013 The Flutter Authors. All rights reserved.// 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<GrDirectContext>& 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<GrDirectContext> GetMainSkiaContext() const;
//---------------------------------------------------------------------------- /// @brief Accessor for the Impeller context associated with /// AndroidSurfaces and the raster thread. /// std::shared_ptr<impeller::Context> 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<impeller::Context>& context);
private: const AndroidRenderingAPI rendering_api_;
// This is the Skia context used for on-screen rendering. sk_sp<GrDirectContext> main_context_;
std::shared_ptr<impeller::Context> impeller_context_;
FML_DISALLOW_COPY_AND_ASSIGN(AndroidContext);};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_CONTEXT_ANDROID_CONTEXT_H_12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Copyright 2013 The Flutter 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", ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277// Copyright 2013 The Flutter 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<PlatformViewAndroidJNI> jni_facade, std::shared_ptr<AndroidSurfaceFactory> 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<SurfacePool>(/*use_new_surface_methods=*/false)), task_runners_(task_runners) {}
// |ExternalViewEmbedder|void AndroidExternalViewEmbedder::PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<EmbeddedViewParams> params) { TRACE_EVENT0("flutter", "AndroidExternalViewEmbedder::PrerollCompositeEmbeddedView");
SkRect view_bounds = SkRect::Make(frame_size_); std::unique_ptr<EmbedderViewSlice> view; view = std::make_unique<DisplayListEmbedderViewSlice>(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<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> 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<int64_t, SkRect> view_rects; for (auto platform_id : composition_order_) { view_rects[platform_id] = GetViewRect(platform_id); }
std::unordered_map<int64_t, SkRect> 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<int64_t, SkRect>::const_iterator overlay = overlay_layers.find(view_id); if (overlay == overlay_layers.end()) { continue; } std::unique_ptr<SurfaceFrame> frame = CreateSurfaceIfNeeded(context, // view_id, // slices_.at(view_id).get(), // overlay->second // ); if (should_submit_current_frame) { frame->Submit(); } }}
// |ExternalViewEmbedder|std::unique_ptr<SurfaceFrame>AndroidExternalViewEmbedder::CreateSurfaceIfNeeded(GrDirectContext* context, int64_t view_id, EmbedderViewSlice* slice, const SkRect& rect) { std::shared_ptr<OverlayLayer> layer = surface_pool_->GetLayer( context, android_context_, jni_facade_, surface_factory_);
std::unique_ptr<SurfaceFrame> 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<fml::RasterThreadMerger>& 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<fml::RasterThreadMerger>& 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<fml::RasterThreadMerger>& 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154// Copyright 2013 The Flutter Authors. All rights reserved.// 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 <unordered_map>
#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<PlatformViewAndroidJNI> jni_facade, std::shared_ptr<AndroidSurfaceFactory> surface_factory, const TaskRunners& task_runners);
// |ExternalViewEmbedder| void PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<flutter::EmbeddedViewParams> params) override;
// |ExternalViewEmbedder| DlCanvas* CompositeEmbeddedView(int64_t view_id) override;
// |ExternalViewEmbedder| void SubmitFlutterView( int64_t flutter_view_id, GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> frame) override;
// |ExternalViewEmbedder| PostPrerollResult PostPrerollAction( const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override;
// |ExternalViewEmbedder| DlCanvas* GetRootCanvas() override;
// |ExternalViewEmbedder| void BeginFrame(GrDirectContext* context, const fml::RefPtr<fml::RasterThreadMerger>& 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<fml::RasterThreadMerger>& 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<PlatformViewAndroidJNI> jni_facade_;
// Allows to create surfaces. const std::shared_ptr<AndroidSurfaceFactory> surface_factory_;
// Holds surfaces. Allows to recycle surfaces or allocate new ones. const std::unique_ptr<SurfacePool> 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<int64_t> 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<int64_t, std::unique_ptr<EmbedderViewSlice>> slices_;
// The params for a platform view, which contains the size, position and // mutation stack. std::unordered_map<int64_t, EmbeddedViewParams> 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<SurfaceFrame> 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_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269// Copyright 2013 The Flutter 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<PlatformViewAndroidJNI> jni_facade, std::shared_ptr<AndroidSurfaceFactory> 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<SurfacePool>(/*use_new_surface_methods=*/true)), task_runners_(task_runners) {}
// |ExternalViewEmbedder|void AndroidExternalViewEmbedder2::PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<EmbeddedViewParams> params) { TRACE_EVENT0("flutter", "AndroidExternalViewEmbedder2::PrerollCompositeEmbeddedView");
SkRect view_bounds = SkRect::Make(frame_size_); std::unique_ptr<EmbedderViewSlice> view; view = std::make_unique<DisplayListEmbedderViewSlice>(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<int64_t, EmbeddedViewParams>& 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<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> 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<int64_t, SkRect> view_rects; for (auto platform_id : composition_order_) { view_rects[platform_id] = GetViewRect(platform_id, view_params_); }
std::unordered_map<int64_t, SkRect> 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<fml::CountDownLatch> latch = std::make_shared<fml::CountDownLatch>(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<SurfaceFrame> 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<int64_t, SkRect>::const_iterator overlay = overlay_layers.find(view_id);
if (overlay == overlay_layers.end()) { continue; } if (overlay_frame == nullptr) { std::shared_ptr<OverlayLayer> 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<fml::RasterThreadMerger>& 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<fml::RasterThreadMerger>& 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<fml::RasterThreadMerger>& 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152// Copyright 2013 The Flutter Authors. All rights reserved.// 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 <unordered_map>
#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<PlatformViewAndroidJNI> jni_facade, std::shared_ptr<AndroidSurfaceFactory> surface_factory, const TaskRunners& task_runners);
// |ExternalViewEmbedder| void PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<flutter::EmbeddedViewParams> params) override;
// |ExternalViewEmbedder| DlCanvas* CompositeEmbeddedView(int64_t view_id) override;
// |ExternalViewEmbedder| void SubmitFlutterView( int64_t flutter_view_id, GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> frame) override;
// |ExternalViewEmbedder| PostPrerollResult PostPrerollAction( const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override;
// |ExternalViewEmbedder| DlCanvas* GetRootCanvas() override;
// |ExternalViewEmbedder| void BeginFrame(GrDirectContext* context, const fml::RefPtr<fml::RasterThreadMerger>& 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<fml::RasterThreadMerger>& 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<int64_t, EmbeddedViewParams>& 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<PlatformViewAndroidJNI> jni_facade_;
// Allows to create surfaces. const std::shared_ptr<AndroidSurfaceFactory> surface_factory_;
// Holds surfaces. Allows to recycle surfaces or allocate new ones. const std::unique_ptr<SurfacePool> 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<int64_t> 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<int64_t, std::unique_ptr<EmbedderViewSlice>> slices_;
// The params for a platform view, which contains the size, position and // mutation stack. std::unordered_map<int64_t, EmbeddedViewParams> 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_12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082// Copyright 2013 The Flutter 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 <memory>
#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<std::unique_ptr<AndroidSurface>(void)>; explicit TestAndroidSurfaceFactory(TestSurfaceProducer&& surface_producer) { surface_producer_ = surface_producer; }
~TestAndroidSurfaceFactory() override = default;
std::unique_ptr<AndroidSurface> CreateSurface() override { return surface_producer_(); }
private: TestSurfaceProducer surface_producer_;};
class SurfaceMock : public Surface { public: MOCK_METHOD(bool, IsValid, (), (override));
MOCK_METHOD(std::unique_ptr<SurfaceFrame>, AcquireFrame, (const SkISize& size), (override));
MOCK_METHOD(SkMatrix, GetRootTransformation, (), (const, override));
MOCK_METHOD(GrDirectContext*, GetContext, (), (override));
MOCK_METHOD(std::unique_ptr<GLContextResult>, MakeRenderContextCurrent, (), (override));};
fml::RefPtr<fml::RasterThreadMerger> 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<fml::RasterThreadMerger>(platform_queue_id, platform_queue_id); } auto rasterizer_queue_id = rasterizer_thread->GetTaskRunner()->GetTaskQueueId(); return fml::MakeRefCounted<fml::RasterThreadMerger>(platform_queue_id, rasterizer_queue_id);}
fml::RefPtr<fml::RasterThreadMerger> 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<fml::RasterThreadMerger>(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<AndroidExternalViewEmbedder>( android_context, nullptr, nullptr, GetTaskRunnersForFixture());
ASSERT_EQ(nullptr, embedder->CompositeEmbeddedView(0)); embedder->PrerollCompositeEmbeddedView( 0, std::make_unique<EmbeddedViewParams>()); ASSERT_NE(nullptr, embedder->CompositeEmbeddedView(0));
ASSERT_EQ(nullptr, embedder->CompositeEmbeddedView(1)); embedder->PrerollCompositeEmbeddedView( 1, std::make_unique<EmbeddedViewParams>()); ASSERT_NE(nullptr, embedder->CompositeEmbeddedView(1));}
TEST(AndroidExternalViewEmbedder, CancelFrame) { auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( android_context, nullptr, nullptr, GetTaskRunnersForFixture());
embedder->PrerollCompositeEmbeddedView( 0, std::make_unique<EmbeddedViewParams>()); embedder->CancelFrame();
ASSERT_EQ(embedder->CompositeEmbeddedView(0), nullptr);}
TEST(AndroidExternalViewEmbedder, RasterizerRunsOnPlatformThread) { auto jni_mock = std::make_shared<JNIMock>(); auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( 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<EmbeddedViewParams>());
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<JNIMock>(); auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( 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<JNIMock>();
auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( 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<EmbeddedViewParams>(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<JNIMock>();
auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( 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<EmbeddedViewParams>( 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<EmbeddedViewParams>( 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<JNIMock>(); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto gr_context = GrDirectContext::MakeMock(nullptr); auto frame_size = SkISize::Make(1000, 1000); SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context, window, frame_size, framebuffer_info]() { auto surface_frame_1 = std::make_unique<SurfaceFrame>( 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<SurfaceFrame>( 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<SurfaceMock>(); 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<AndroidSurfaceMock>(); 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<AndroidExternalViewEmbedder>( *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<SurfaceFrame>( 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<EmbeddedViewParams>( 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<PlatformViewAndroidJNI::OverlayMetadata>( 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<SurfaceFrame>( 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<EmbeddedViewParams>( 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<SurfaceFrame>( 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<JNIMock>(); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto gr_context = GrDirectContext::MakeMock(nullptr); auto frame_size = SkISize::Make(1000, 1000); SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context, window, frame_size, framebuffer_info]() { auto surface_frame_1 = std::make_unique<SurfaceFrame>( 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<SurfaceMock>(); 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<AndroidSurfaceMock>(); 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<AndroidExternalViewEmbedder>( *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<EmbeddedViewParams>(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<EmbeddedViewParams>(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<PlatformViewAndroidJNI::OverlayMetadata>( 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<SurfaceFrame>( 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<JNIMock>(); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto gr_context = GrDirectContext::MakeMock(nullptr); auto frame_size = SkISize::Make(1000, 1000); SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context, window, frame_size, framebuffer_info]() { auto surface_frame_1 = std::make_unique<SurfaceFrame>( 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<SurfaceMock>(); 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<AndroidSurfaceMock>(); 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<AndroidExternalViewEmbedder>( *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<EmbeddedViewParams>(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<EmbeddedViewParams>(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<PlatformViewAndroidJNI::OverlayMetadata>( 1, window); });
EXPECT_CALL(*jni_mock, FlutterViewDisplayOverlaySurface(1, 25, 25, 80, 150)) .Times(2);
auto surface_frame = std::make_unique<SurfaceFrame>( 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<JNIMock>(); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto gr_context = GrDirectContext::MakeMock(nullptr); auto frame_size = SkISize::Make(1000, 1000); SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context, window, frame_size, framebuffer_info]() { auto surface_frame_1 = std::make_unique<SurfaceFrame>( 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<SurfaceMock>(); 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<AndroidSurfaceMock>(); 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<AndroidExternalViewEmbedder>( *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<EmbeddedViewParams>(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<SurfaceFrame>( 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<JNIMock>();
auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( 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<JNIMock>();
auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto gr_context = GrDirectContext::MakeMock(nullptr); auto frame_size = SkISize::Make(1000, 1000); SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context, window, frame_size, framebuffer_info]() { auto surface_frame_1 = std::make_unique<SurfaceFrame>( 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<SurfaceMock>(); EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) .WillOnce(Return(ByMove(std::move(surface_frame_1))));
auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<AndroidExternalViewEmbedder>( *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<EmbeddedViewParams>( 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<PlatformViewAndroidJNI::OverlayMetadata>( 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<SurfaceFrame>( 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<JNIMock>(); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto gr_context = GrDirectContext::MakeMock(nullptr); auto frame_size = SkISize::Make(1000, 1000); SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context, window, frame_size, framebuffer_info]() { auto surface_frame_1 = std::make_unique<SurfaceFrame>( 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<SurfaceMock>(); EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) .WillOnce(Return(ByMove(std::move(surface_frame_1))));
auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<AndroidExternalViewEmbedder>( *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<EmbeddedViewParams>( 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<PlatformViewAndroidJNI::OverlayMetadata>( 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<SurfaceFrame>( 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<JNIMock>(); auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( android_context, jni_mock, nullptr, GetTaskRunnersForFixture()); ASSERT_TRUE(embedder->SupportsDynamicThreadMerging());}
TEST(AndroidExternalViewEmbedder, DisableThreadMerger) { auto jni_mock = std::make_shared<JNIMock>(); auto android_context = AndroidContext(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( 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<EmbeddedViewParams>());
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<JNIMock>(); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto gr_context = GrDirectContext::MakeMock(nullptr); auto frame_size = SkISize::Make(1000, 1000); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context, window, frame_size]() { SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_frame_1 = std::make_unique<SurfaceFrame>( 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<SurfaceMock>(); EXPECT_CALL(*surface_mock, AcquireFrame(frame_size)) .WillOnce(Return(ByMove(std::move(surface_frame_1))));
auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<AndroidExternalViewEmbedder>( *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<EmbeddedViewParams>( 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<PlatformViewAndroidJNI::OverlayMetadata>( 0, window))));
SurfaceFrame::FramebufferInfo framebuffer_info; auto surface_frame = std::make_unique<SurfaceFrame>( 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<JNIMock>(); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto embedder = std::make_unique<AndroidExternalViewEmbedder>( *android_context, jni_mock, nullptr, GetTaskRunnersForFixture());
EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(0); embedder->Teardown();}
} // namespace testing} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134// Copyright 2013 The Flutter 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 <utility>
namespace flutter {
OverlayLayer::OverlayLayer(int id, std::unique_ptr<AndroidSurface> android_surface, std::unique_ptr<Surface> 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<OverlayLayer> SurfacePool::GetLayer( GrDirectContext* gr_context, const AndroidContext& android_context, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade, const std::shared_ptr<AndroidSurfaceFactory>& 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<intptr_t>(gr_context); // Allocate a new surface if there isn't one available. if (available_layer_index_ >= layers_.size()) { std::unique_ptr<AndroidSurface> 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<PlatformViewAndroidJNI::OverlayMetadata> 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> surface = android_surface->CreateGPUSurface(gr_context);
std::shared_ptr<OverlayLayer> layer = std::make_shared<OverlayLayer>(java_metadata->id, // std::move(android_surface), // std::move(surface) // ); layer->gr_context_key = gr_context_key; layers_.push_back(layer); }
std::shared_ptr<OverlayLayer> 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> 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<PlatformViewAndroidJNI>& jni_facade) { std::lock_guard lock(mutex_); DestroyLayersLocked(jni_facade);}
void SurfacePool::DestroyLayersLocked( const std::shared_ptr<PlatformViewAndroidJNI>& 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<std::shared_ptr<OverlayLayer>> SurfacePool::GetUnusedLayers() { std::lock_guard lock(mutex_); std::vector<std::shared_ptr<OverlayLayer>> 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 flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118// Copyright 2013 The Flutter Authors. All rights reserved.// 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 <mutex>
#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<AndroidSurface> android_surface, std::unique_ptr<Surface> surface);
~OverlayLayer();
// A unique id to identify the overlay when it gets recycled. const int id;
// A GPU surface. const std::unique_ptr<AndroidSurface> android_surface;
// A GPU surface. This may change when the overlay is recycled. std::unique_ptr<Surface> 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<OverlayLayer> GetLayer( GrDirectContext* gr_context, const AndroidContext& android_context, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade, const std::shared_ptr<AndroidSurfaceFactory>& surface_factory);
// Gets the layers in the pool that aren't currently used. // This method doesn't mark the layers as unused. std::vector<std::shared_ptr<OverlayLayer>> 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<PlatformViewAndroidJNI>& 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<std::shared_ptr<OverlayLayer>> 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<PlatformViewAndroidJNI>& jni_facade);};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_EXTERNAL_VIEW_EMBEDDER_SURFACE_POOL_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353// Copyright 2013 The Flutter 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 <memory>#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<std::unique_ptr<AndroidSurface>(void)>; explicit TestAndroidSurfaceFactory(TestSurfaceProducer&& surface_producer) { surface_producer_ = surface_producer; }
~TestAndroidSurfaceFactory() override = default;
std::unique_ptr<AndroidSurface> CreateSurface() override { return surface_producer_(); }
private: TestSurfaceProducer surface_producer_;};
TEST(SurfacePool, GetLayerAllocateOneLayer) { auto pool = std::make_unique<SurfacePool>(/*use_new_surface_methods=*/false);
auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window))));
auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<intptr_t>(gr_context.get()), layer->gr_context_key);}
TEST(SurfacePool, GetUnusedLayers) { auto pool = std::make_unique<SurfacePool>(/*use_new_surface_methods=*/false);
auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window))));
auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<SurfacePool>(/*use_new_surface_methods=*/false);
auto gr_context_1 = GrDirectContext::MakeMock(nullptr); auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window))));
auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto gr_context_2 = GrDirectContext::MakeMock(nullptr); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context_1, gr_context_2, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); // 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<intptr_t>(gr_context_2.get()), layer_1->gr_context_key); ASSERT_EQ(reinterpret_cast<intptr_t>(gr_context_2.get()), layer_2->gr_context_key);}
TEST(SurfacePool, GetLayerAllocateTwoLayers) { auto pool = std::make_unique<SurfacePool>(/*use_new_surface_methods=*/false);
auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .Times(2) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window)))) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 1, window))));
auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<SurfacePool>(/*use_new_surface_methods=*/true); auto jni_mock = std::make_shared<JNIMock>();
EXPECT_CALL(*jni_mock, destroyOverlaySurface2()).Times(0); pool->DestroyLayers(jni_mock);
auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, createOverlaySurface2()) .Times(1) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window))));
auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<SurfacePool>(/*use_new_surface_methods=*/false); auto jni_mock = std::make_shared<JNIMock>();
EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(0); pool->DestroyLayers(jni_mock);
auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .Times(1) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window))));
auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<SurfacePool>(/*use_new_surface_methods=*/false); auto jni_mock = std::make_shared<JNIMock>();
auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr);
auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<PlatformViewAndroidJNI::OverlayMetadata>( 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<PlatformViewAndroidJNI::OverlayMetadata>( 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<SurfacePool>(/*use_new_surface_methods=*/true); auto jni_mock = std::make_shared<JNIMock>();
auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware);
auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr);
auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); 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<PlatformViewAndroidJNI::OverlayMetadata>( 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<PlatformViewAndroidJNI::OverlayMetadata>( 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 flutter1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// Copyright 2013 The Flutter 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; }}12345678910111213141516171819// Copyright 2013 The Flutter 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.pypackage 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;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185// Copyright 2013 The Flutter 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. * * <p>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}. * * <p>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. * * <p>Once you access it, you can no longer change the values injected. * * <p>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)}. * * <p>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. * * <p>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); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104// Copyright 2013 The Flutter 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. * * <p>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); }}123456789101112131415161718// Copyright 2013 The Flutter 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. * * <p>For more information on the removal of Flutter's v1 Android embedding, see: * https://docs.flutter.dev/release/breaking-changes/v1-android-embedding. */@Deprecatedpublic class FlutterApplication extends Application {}123456789// Copyright 2013 The Flutter 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();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275// Copyright 2013 The Flutter 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. * * <p>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 <a * href="https://api.flutter.dev/flutter/services/BasicMessageChannel-class.html">BasicMessageChannel</a> * 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. * * <p>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<T> { 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<T> 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<T> 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<T> 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. * * <p>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<T> 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. * * <p>Overrides any existing handler registration for (the name of) this channel. * * <p>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<T> 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<T> {
/** * Handles the specified message received from Flutter. * * <p>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. * * <p>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. * * <p>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<T> 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<T> { /** * 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<T> callback;
private IncomingReplyHandler(@NonNull Reply<T> 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<T> handler;
private IncomingMessageHandler(@NonNull MessageHandler<T> handler) { this.handler = handler; }
@Override public void onMessage(@Nullable ByteBuffer message, @NonNull final BinaryReply callback) { try { handler.onMessage( codec.decodeMessage(message), new Reply<T>() { @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); } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566// Copyright 2013 The Flutter 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. * * <p>This codec is guaranteed to be compatible with the corresponding <a * href="https://api.flutter.dev/flutter/services/BinaryCodec-class.html">BinaryCodec</a> on the * Dart side. These parts of the Flutter SDK are evolved synchronously. * * <p>On the Dart side, messages are represented using {@code ByteData}. */public final class BinaryCodec implements MessageCodec<ByteBuffer> { // 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; } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205// Copyright 2013 The Flutter 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 <a * href="https://api.flutter.dev/flutter/services/BinaryMessages-class.html">BinaryMessages</a> to * participate. * * <p>{@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. * * <p>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. * * <p>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. * * <p>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. * * <p>{@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. * * <p>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. * * <p>Registration overwrites any previous registration for the same channel name. Use a null * handler to deregister. * * <p>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. * * <p>Registration overwrites any previous registration for the same channel name. Use a null * handler to deregister. * * <p>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. * * <p>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. * * <p>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. * * <p>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. * * <p>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); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445// Copyright 2013 The Flutter 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"); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274// Copyright 2013 The Flutter 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. * * <p>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 <a * href="https://api.flutter.dev/flutter/services/EventChannel-class.html">EventChannel</a> * 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. * * <p>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. * * <p>Overrides any existing handler registration for (the name of) this channel. * * <p>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. * * <p>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. * * <p>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. * * <p>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. * * <p>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<EventSink> 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); } } }}12345678910111213141516171819202122232425// Copyright 2013 The Flutter 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; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263// Copyright 2013 The Flutter 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. * * <p>This codec is guaranteed to be compatible with the corresponding <a * href="https://api.flutter.dev/flutter/services/JSONMessageCodec-class.html">JSONMessageCodec</a> * on the Dart side. These parts of the Flutter SDK are evolved synchronously. * * <p>Supports the same Java values as {@link JSONObject#wrap(Object)}. * * <p>On the Dart side, JSON messages are handled by the JSON facilities of the <a * href="https://api.dartlang.org/stable/dart-convert/JSON-constant.html">dart:convert</a> package. */public final class JSONMessageCodec implements MessageCodec<Object> { // 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); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122// Copyright 2013 The Flutter 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. * * <p>This codec is guaranteed to be compatible with the corresponding <a * href="https://api.flutter.dev/flutter/services/JSONMethodCodec-class.html">JSONMethodCodec</a> on * the Dart side. These parts of the Flutter SDK are evolved synchronously. * * <p>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; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108package 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<Object> 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<String, Object> map = new HashMap<>(); JSONObject jsonObject = (JSONObject) o; Iterator<String> 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; }}123456789101112131415161718192021222324252627282930313233343536373839// Copyright 2013 The Flutter 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. * * <p>Both operations throw {@link IllegalArgumentException}, if conversion fails. */public interface MessageCodec<T> { /** * 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. * * <p><b>Warning:</b> 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);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102// Copyright 2013 The Flutter 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. * * <p>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 <T> the intended type of the arguments. * @return the arguments with static type T */ @SuppressWarnings("unchecked") @Nullable public <T> 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 <T> 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> 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(); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293// Copyright 2013 The Flutter 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. * * <p>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 <a * href="https://api.flutter.dev/flutter/services/MethodChannel-class.html">MethodChannel</a> * 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. * * <p>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. * * <p>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. * * <p>Overrides any existing handler registration for (the name of) this channel. * * <p>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 <a * href="https://api.flutter.dev/flutter/services/MissingPluginException-class.html">MissingPluginException</a> * on the Dart side, unless an <a * href="https://api.flutter.dev/flutter/services/OptionalMethodChannel-class.html">OptionalMethodChannel</a> * 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. * * <p>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()}. * * <p>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. * * <p>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 <a * href="https://github.com/flutter/flutter/wiki/The-Engine-architecture#threading">Threading in * the Flutter Engine</a>. * * @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. * * <p>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))); } } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192// Copyright 2013 The Flutter 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. * * <p>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}. * * <p>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);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// Copyright 2013 The Flutter 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); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460// Copyright 2013 The Flutter 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. * * <p>This codec is guaranteed to be compatible with the corresponding <a * href="https://api.flutter.dev/flutter/services/StandardMessageCodec-class.html">StandardMessageCodec</a> * on the Dart side. These parts of the Flutter SDK are evolved synchronously. * * <p>Supported messages are acyclic values of these forms: * * <ul> * <li>null * <li>Booleans * <li>Bytes, Shorts, Integers, Longs * <li>BigIntegers (see below) * <li>Floats, Doubles * <li>Strings * <li>byte[], int[], long[], float[], double[] * <li>Lists of supported values * <li>Maps with supported keys and values * </ul> * * <p>On the Dart side, these values are represented as follows: * * <ul> * <li>null: null * <li>Boolean: bool * <li>Byte, Short, Integer, Long: int * <li>Float, Double: double * <li>String: String * <li>byte[]: Uint8List * <li>int[]: Int32List * <li>long[]: Int64List * <li>float[]: Float32List * <li>double[]: Float64List * <li>List: List * <li>Map: Map * </ul> * * <p>BigIntegers are represented in Dart as strings with the hexadecimal representation of the * integer's value. * * <p>To extend the codec, overwrite the writeValue and readValueOfType methods. */public class StandardMessageCodec implements MessageCodec<Object> { 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. * * <p>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. * * <p>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<Object> 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<Object, Object> 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; } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135// Copyright 2013 The Flutter 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. * * <p>This codec is guaranteed to be compatible with the corresponding <a * href="https://api.flutter.dev/flutter/services/StandardMethodCodec-class.html">StandardMethodCodec</a> * on the Dart side. These parts of the Flutter SDK are evolved synchronously. * * <p>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"); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657// Copyright 2013 The Flutter 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. * * <p>This codec is guaranteed to be compatible with the corresponding <a * href="https://api.flutter.dev/flutter/services/StringCodec-class.html">StringCodec</a> on the * Dart side. These parts of the Flutter SDK are evolved synchronously. */public final class StringCodec implements MessageCodec<String> { 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); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319// Copyright 2013 The Flutter 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 <a target="_new" * href="https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android10-s3-release/core/java/android/text/method/BaseKeyListener.java#111">https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android10-s3-release/core/java/android/text/method/BaseKeyListener.java#111</a> */ 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 <a target="_new" * href="https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android10-s3-release/core/java/android/text/method/BaseKeyListener.java#111">https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android10-s3-release/core/java/android/text/method/BaseKeyListener.java#111</a> */ 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; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205// Copyright 2013 The Flutter 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"})@Keepclass 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<WindowInsetsAnimation> 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); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595// Copyright 2013 The Flutter 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<String, Object> 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 -------}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296// Copyright 2013 The Flutter 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<EditingStateWatcher> mListeners = new ArrayList<>(); private ArrayList<EditingStateWatcher> mPendingListeners = new ArrayList<>(); private ArrayList<TextEditingDelta> 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<TextEditingDelta> extractBatchTextEditingDeltas() { ArrayList<TextEditingDelta> currentBatchDeltas = new ArrayList<TextEditingDelta>(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()); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106// Copyright 2013 The Flutter 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. * * <p>The plugin handles requests for scribe sent by the {@link * io.flutter.embedding.engine.systemchannels.ScribeChannel}. * * <p>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. * * <p>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}. * * <p>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. * * <p>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. * * <p>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. * * <p>Differs from isStylusHandwritingAvailable in that it can be called from any API level * without throwing an error. * * <p>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(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183// Copyright 2013 The Flutter 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. * * <p>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}. * * <p>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}. * * <p>Spell check results are encoded as dictionaries with a format that looks like * * <pre>{@code * { * startIndex: 0, * endIndex: 5, * suggestions: [hello, ...] * } * }</pre> * * where there may be up to 5 suggestions. */ @Override public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] results) { if (results.length == 0) { pendingResult.success(new ArrayList<HashMap<String, Object>>()); pendingResult = null; return; }
ArrayList<HashMap<String, Object>> spellCheckerSuggestionSpans = new ArrayList<HashMap<String, Object>>(); SentenceSuggestionsInfo spellCheckResults = results[0]; if (spellCheckResults == null) { pendingResult.success(new ArrayList<HashMap<String, Object>>()); 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<String, Object> spellCheckerSuggestionSpan = new HashMap<String, Object>(); int start = spellCheckResults.getOffsetAt(i); int end = start + spellCheckResults.getLengthAt(i);
spellCheckerSuggestionSpan.put(START_INDEX_KEY, start); spellCheckerSuggestionSpan.put(END_INDEX_KEY, end);
ArrayList<String> suggestions = new ArrayList<String>(); 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. }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132// Copyright 2013 The Flutter 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; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852// Copyright 2013 The Flutter 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<TextInputChannel.Configuration> 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. * * <p>The current input connection instance is cached and any following call to @{link * createInputConnection} returns the cached connection until unlockPlatformViewInputConnection is * called. * * <p>This is a no-op if the current input target isn't a platform view. * * <p>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. * * <p>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. * * <p>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. * * <p>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<TextEditingDelta> 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<AutofillValue> 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<String, TextInputChannel.TextEditState> 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 -------}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208// Copyright 2013 The Flutter 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. * * <p>FlutterEngine must be non-null when this method is invoked. */ @SuppressWarnings("deprecation") @Nullable public Locale resolveNativeLocale(@Nullable List<Locale> 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<Locale.LanguageRange> 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. * * <p>FlutterEngine must be non-null when this method is invoked. */ @SuppressWarnings("deprecation") public void sendLocalesToFlutter(@NonNull Configuration config) { List<Locale> 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); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136// Copyright 2013 The Flutter 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. * * <p>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<String, Integer>() { 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. * * <p>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. * * <p>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<String, Integer> systemCursorConstants;
/** * Delegate interface for requesting the system to display a pointer icon object. * * <p>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}. * * <p>If typeis not recognized, returns the default pointer icon. * * <p>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. * * <p>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); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061// Copyright 2013 The Flutter 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. * * <p>This is a no-op if there is no accessibility delegate set. * * <p>This is used by embedded platform views to propagate accessibility events from their view * hierarchy to the accessibility bridge. * * <p>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; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139package 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(); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// Copyright 2013 The Flutter 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); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626// Copyright 2013 The Flutter 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. * * <p>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<PlatformChannel.SystemUiOverlay> 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}. * * <p>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<PlatformChannel.SystemUiOverlay> 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}. * * <p>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)); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081// Copyright 2013 The Flutter 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}. * * <p>This means that our associated {@link io.flutter.embedding.engine.FlutterEngine} can now * render a UI and interact with the user. * * <p>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}. * * <p>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. * * <p>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. * * <p>The {@link PlatformView} object is unusable after this method is called. * * <p>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. * * <p>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. * * <p>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. * * <p>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() {}}flutter/engine/src/flutter/shell/platform/android/context/BUILD.gnAdded+26
flutter/engine/src/flutter/shell/platform/android/context/android_context.ccAdded+47
flutter/engine/src/flutter/shell/platform/android/context/android_context.hAdded+86
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/BUILD.gnAdded+55
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.ccAdded+277
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.hAdded+154
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.ccAdded+269
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.hAdded+152
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_unittests.ccAdded+1082
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.ccAdded+134
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool.hAdded+118
flutter/engine/src/flutter/shell/platform/android/external_view_embedder/surface_pool_unittests.ccAdded+353
flutter/engine/src/flutter/shell/platform/android/io/flutter/Build.javaAdded+47
flutter/engine/src/flutter/shell/platform/android/io/flutter/BuildConfig.javaAdded+19
flutter/engine/src/flutter/shell/platform/android/io/flutter/FlutterInjector.javaAdded+185
flutter/engine/src/flutter/shell/platform/android/io/flutter/Log.javaAdded+104
flutter/engine/src/flutter/shell/platform/android/io/flutter/app/FlutterApplication.javaAdded+18
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ActivityLifecycleListener.javaAdded+9
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BasicMessageChannel.javaAdded+275
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryCodec.javaAdded+66
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessenger.javaAdded+205
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/ErrorLogResult.javaAdded+45
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/EventChannel.javaAdded+274
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterException.javaAdded+25
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.javaAdded+63
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.javaAdded+122
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONUtil.javaAdded+108
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.javaAdded+39
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.javaAdded+102
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodChannel.javaAdded+293
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.javaAdded+92
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/PluginRegistry.javaAdded+75
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.javaAdded+460
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.javaAdded+135
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringCodec.javaAdded+57
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/FlutterTextUtils.javaAdded+319
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.javaAdded+205
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.javaAdded+595
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ListenableEditingState.javaAdded+296
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/ScribePlugin.javaAdded+106
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/SpellCheckPlugin.javaAdded+183
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextEditingDelta.javaAdded+132
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.javaAdded+852
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/localization/LocalizationPlugin.javaAdded+208
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.javaAdded+136
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/AccessibilityEventsDelegate.javaAdded+61
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.javaAdded+139
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformOverlayView.javaAdded+49
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformPlugin.javaAdded+626
flutter/engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformView.javaAdded+81