text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter 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/runtime/dart_vm_initializer.h" #include <atomic> #include "flutter/fml/logging.h" #include "flutter/fml/synchronization/shared_mutex.h" #include "flutter/fml/trace_event.h" #include "flutter/lib/ui/ui_dart_state.h" #include "flutter/lib/ui/window/platform_configuration.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/logging/dart_error.h" #include "dart_timestamp_provider.h" namespace { // Tracks whether Dart has been initialized and if it is safe to call Dart // APIs. static std::atomic<bool> gDartInitialized; void LogUnhandledException(Dart_Handle exception_handle, Dart_Handle stack_trace_handle) { const std::string error = tonic::StdStringFromDart(Dart_ToString(exception_handle)); const std::string stack_trace = tonic::StdStringFromDart(Dart_ToString(stack_trace_handle)); auto state = flutter::UIDartState::Current(); if (state && state->unhandled_exception_callback()) { auto callback = state->unhandled_exception_callback(); if (callback(error, stack_trace)) { return; } } // Either the exception handler was not set or it could not handle the // error, just log the exception. FML_LOG(ERROR) << "Unhandled Exception: " << error << std::endl << stack_trace; } void ReportUnhandledException(Dart_Handle exception_handle, Dart_Handle stack_trace_handle) { // Hooks.dart will call the error handler on PlatformDispatcher if it is // not null. If it is null, returns false, fall into the !handled branch // below and log. // If it is not null, defer to the return value of that closure // to determine whether to report via logging. bool handled = false; auto state = flutter::UIDartState::Current(); if (!state || !state->platform_configuration()) { LogUnhandledException(exception_handle, stack_trace_handle); return; } auto on_error = state->platform_configuration()->on_error(); if (on_error) { FML_DCHECK(!Dart_IsNull(on_error)); Dart_Handle args[2]; args[0] = exception_handle; args[1] = stack_trace_handle; Dart_Handle on_error_result = Dart_InvokeClosure(on_error, 2, args); // An exception was thrown by the exception handler. if (Dart_IsError(on_error_result)) { LogUnhandledException(Dart_ErrorGetException(on_error_result), Dart_ErrorGetStackTrace(on_error_result)); handled = false; } else { handled = tonic::DartConverter<bool>::FromDart(on_error_result); } if (!handled) { LogUnhandledException(exception_handle, stack_trace_handle); } } } } // namespace void DartVMInitializer::Initialize(Dart_InitializeParams* params, bool enable_timeline_event_handler, bool trace_systrace) { FML_DCHECK(!gDartInitialized); char* error = Dart_Initialize(params); if (error) { FML_LOG(FATAL) << "Error while initializing the Dart VM: " << error; ::free(error); } else { gDartInitialized = true; } if (enable_timeline_event_handler) { if (!trace_systrace) { // Systrace on all platforms except Fuchsia ignores the timestamp provided // here. On Android in particular, calls to get the system clock show up // in profiles. // Fuchsia does not use the TraceSetTimelineMicrosSource. fml::tracing::TraceSetTimelineMicrosSource(Dart_TimelineGetMicros); } else { fml::tracing::TraceSetTimelineMicrosSource( []() -> int64_t { return -1; }); } fml::tracing::TraceSetTimelineEventHandler(LogDartTimelineEvent); } fml::TimePoint::SetClockSource(flutter::DartTimelineTicksSinceEpoch); tonic::SetUnhandledExceptionReporter(&ReportUnhandledException); } void DartVMInitializer::Cleanup() { FML_DCHECK(gDartInitialized); // Dart_RecordTimelineEvent is unsafe during a concurrent call to Dart_Cleanup // because Dart_Cleanup will destroy the timeline recorder. Clear the // initialized flag so that future calls to LogDartTimelineEvent will not // call Dart_RecordTimelineEvent. // // Note that this is inherently racy. If a thread sees that gDartInitialized // is set and proceeds to call Dart_RecordTimelineEvent shortly before another // thread calls Dart_Cleanup, then the Dart_RecordTimelineEvent call may crash // if Dart_Cleanup deletes the timeline before Dart_RecordTimelineEvent // completes. In practice this is unlikely because Dart_Cleanup does // significant other work before deleting the timeline. // // The engine can not safely guard Dart_Cleanup and LogDartTimelineEvent with // a lock due to the risk of deadlocks. Dart_Cleanup waits for various // Dart-owned threads to shut down. If one of those threads invokes an engine // callback that calls LogDartTimelineEvent while the Dart_Cleanup thread owns // the lock, then Dart_Cleanup would deadlock. gDartInitialized = false; char* error = Dart_Cleanup(); if (error) { FML_LOG(FATAL) << "Error while cleaning up the Dart VM: " << error; ::free(error); } } void DartVMInitializer::LogDartTimelineEvent(const char* label, int64_t timestamp0, int64_t timestamp1_or_async_id, intptr_t flow_id_count, const int64_t* flow_ids, Dart_Timeline_Event_Type type, intptr_t argument_count, const char** argument_names, const char** argument_values) { if (gDartInitialized) { Dart_RecordTimelineEvent(label, timestamp0, timestamp1_or_async_id, flow_id_count, flow_ids, type, argument_count, argument_names, argument_values); } }
engine/runtime/dart_vm_initializer.cc/0
{ "file_path": "engine/runtime/dart_vm_initializer.cc", "repo_id": "engine", "token_count": 2442 }
339
// Copyright 2013 The Flutter 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/runtime/platform_isolate_manager.h" #include "flutter/runtime/dart_isolate.h" namespace flutter { bool PlatformIsolateManager::HasShutdown() { // TODO(flutter/flutter#136314): Assert that we're on the platform thread. std::scoped_lock lock(lock_); return is_shutdown_; } bool PlatformIsolateManager::HasShutdownMaybeFalseNegative() { std::scoped_lock lock(lock_); return is_shutdown_; } bool PlatformIsolateManager::RegisterPlatformIsolate(Dart_Isolate isolate) { std::scoped_lock lock(lock_); if (is_shutdown_) { // It's possible shutdown occured while we were trying to aquire the lock. return false; } FML_DCHECK(platform_isolates_.find(isolate) == platform_isolates_.end()); platform_isolates_.insert(isolate); return true; } void PlatformIsolateManager::RemovePlatformIsolate(Dart_Isolate isolate) { // This method is only called by DartIsolate::OnShutdownCallback() during // isolate shutdown. This can happen either during the ordinary platform // isolate shutdown, or during ShutdownPlatformIsolates(). In either case // we're on the platform thread. // TODO(flutter/flutter#136314): Assert that we're on the platform thread. // Need a method that works for ShutdownPlatformIsolates() too. std::scoped_lock lock(lock_); if (is_shutdown_) { // Removal during ShutdownPlatformIsolates. Ignore, to avoid modifying // platform_isolates_ during iteration. FML_DCHECK(platform_isolates_.empty()); return; } FML_DCHECK(platform_isolates_.find(isolate) != platform_isolates_.end()); platform_isolates_.erase(isolate); } void PlatformIsolateManager::ShutdownPlatformIsolates() { // TODO(flutter/flutter#136314): Assert that we're on the platform thread. // There's no current UIDartState here, so platform_isolate.cc's method won't // work. std::scoped_lock lock(lock_); is_shutdown_ = true; std::unordered_set<Dart_Isolate> platform_isolates; std::swap(platform_isolates_, platform_isolates); for (Dart_Isolate isolate : platform_isolates) { Dart_EnterIsolate(isolate); Dart_ShutdownIsolate(); } } bool PlatformIsolateManager::IsRegisteredForTestingOnly(Dart_Isolate isolate) { std::scoped_lock lock(lock_); return platform_isolates_.find(isolate) != platform_isolates_.end(); } } // namespace flutter
engine/runtime/platform_isolate_manager.cc/0
{ "file_path": "engine/runtime/platform_isolate_manager.cc", "repo_id": "engine", "token_count": 796 }
340
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/common/dl_op_spy.h" namespace flutter { bool DlOpSpy::did_draw() { return did_draw_; } void DlOpSpy::setColor(DlColor color) { if (color.isTransparent()) { will_draw_ = false; } else { will_draw_ = true; } } void DlOpSpy::setColorSource(const DlColorSource* source) { if (!source) { return; } const DlColorColorSource* color_source = source->asColor(); if (color_source && color_source->color().isTransparent()) { will_draw_ = false; return; } will_draw_ = true; } void DlOpSpy::save() {} void DlOpSpy::saveLayer(const SkRect& bounds, const SaveLayerOptions options, const DlImageFilter* backdrop) {} void DlOpSpy::restore() {} void DlOpSpy::drawColor(DlColor color, DlBlendMode mode) { did_draw_ |= !color.isTransparent(); } void DlOpSpy::drawPaint() { did_draw_ |= will_draw_; } // TODO(cyanglaz): check whether the shape (line, rect, oval, etc) needs to be // evaluated. https://github.com/flutter/flutter/issues/123803 void DlOpSpy::drawLine(const SkPoint& p0, const SkPoint& p1) { did_draw_ |= will_draw_; } void DlOpSpy::drawRect(const SkRect& rect) { did_draw_ |= will_draw_; } void DlOpSpy::drawOval(const SkRect& bounds) { did_draw_ |= will_draw_; } void DlOpSpy::drawCircle(const SkPoint& center, SkScalar radius) { did_draw_ |= will_draw_; } void DlOpSpy::drawRRect(const SkRRect& rrect) { did_draw_ |= will_draw_; } void DlOpSpy::drawDRRect(const SkRRect& outer, const SkRRect& inner) { did_draw_ |= will_draw_; } void DlOpSpy::drawPath(const SkPath& path) { did_draw_ |= will_draw_; } void DlOpSpy::drawArc(const SkRect& oval_bounds, SkScalar start_degrees, SkScalar sweep_degrees, bool use_center) { did_draw_ |= will_draw_; } void DlOpSpy::drawPoints(PointMode mode, uint32_t count, const SkPoint points[]) { did_draw_ |= will_draw_; } void DlOpSpy::drawVertices(const DlVertices* vertices, DlBlendMode mode) { did_draw_ |= will_draw_; } // In theory, below drawImage methods can produce a transparent screen when a // transparent image is provided. The operation of determine whether an image is // transparent needs examine all the pixels in the image object, which is slow. // Drawing a completely transparent image is not a valid use case, thus, such // case is ignored. void DlOpSpy::drawImage(const sk_sp<DlImage> image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { did_draw_ = true; } void DlOpSpy::drawImageRect(const sk_sp<DlImage> image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint) { did_draw_ = true; } void DlOpSpy::drawImageNine(const sk_sp<DlImage> image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) { did_draw_ = true; } void DlOpSpy::drawAtlas(const sk_sp<DlImage> atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const SkRect* cull_rect, bool render_with_attributes) { did_draw_ = true; } void DlOpSpy::drawDisplayList(const sk_sp<DisplayList> display_list, SkScalar opacity) { if (did_draw_ || opacity == 0) { return; } DlOpSpy receiver; display_list->Dispatch(receiver); did_draw_ |= receiver.did_draw(); } void DlOpSpy::drawTextBlob(const sk_sp<SkTextBlob> blob, SkScalar x, SkScalar y) { did_draw_ |= will_draw_; } void DlOpSpy::drawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y) { did_draw_ |= will_draw_; } void DlOpSpy::drawShadow(const SkPath& path, const DlColor color, const SkScalar elevation, bool transparent_occluder, SkScalar dpr) { did_draw_ |= !color.isTransparent(); } } // namespace flutter
engine/shell/common/dl_op_spy.cc/0
{ "file_path": "engine/shell/common/dl_op_spy.cc", "repo_id": "engine", "token_count": 2332 }
341
// Copyright 2013 The Flutter 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/common/platform_view.h" #include <utility> #include "flutter/fml/make_copyable.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/shell/common/vsync_waiter_fallback.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" namespace flutter { PlatformView::PlatformView(Delegate& delegate, const TaskRunners& task_runners) : delegate_(delegate), task_runners_(task_runners), weak_factory_(this) {} PlatformView::~PlatformView() = default; std::unique_ptr<VsyncWaiter> PlatformView::CreateVSyncWaiter() { FML_DLOG(WARNING) << "This platform does not provide a Vsync waiter implementation. A " "simple timer based fallback is being used."; return std::make_unique<VsyncWaiterFallback>(task_runners_); } void PlatformView::DispatchPlatformMessage( std::unique_ptr<PlatformMessage> message) { delegate_.OnPlatformViewDispatchPlatformMessage(std::move(message)); } void PlatformView::DispatchPointerDataPacket( std::unique_ptr<PointerDataPacket> packet) { delegate_.OnPlatformViewDispatchPointerDataPacket( pointer_data_packet_converter_.Convert(std::move(packet))); } void PlatformView::DispatchSemanticsAction(int32_t node_id, SemanticsAction action, fml::MallocMapping args) { delegate_.OnPlatformViewDispatchSemanticsAction(node_id, action, std::move(args)); } void PlatformView::SetSemanticsEnabled(bool enabled) { delegate_.OnPlatformViewSetSemanticsEnabled(enabled); } void PlatformView::SetAccessibilityFeatures(int32_t flags) { delegate_.OnPlatformViewSetAccessibilityFeatures(flags); } void PlatformView::SetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) { delegate_.OnPlatformViewSetViewportMetrics(view_id, metrics); } void PlatformView::NotifyCreated() { std::unique_ptr<Surface> surface; // Threading: We want to use the platform view on the non-platform thread. // Using the weak pointer is illegal. But, we are going to introduce a latch // so that the platform view is not collected till the surface is obtained. auto* platform_view = this; fml::ManualResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [platform_view, &surface, &latch]() { surface = platform_view->CreateRenderingSurface(); if (surface && !surface->IsValid()) { surface.reset(); } latch.Signal(); }); latch.Wait(); if (!surface) { FML_LOG(ERROR) << "Failed to create platform view rendering surface"; return; } delegate_.OnPlatformViewCreated(std::move(surface)); } void PlatformView::NotifyDestroyed() { delegate_.OnPlatformViewDestroyed(); } void PlatformView::ScheduleFrame() { delegate_.OnPlatformViewScheduleFrame(); } sk_sp<GrDirectContext> PlatformView::CreateResourceContext() const { FML_DLOG(WARNING) << "This platform does not set up the resource " "context on the IO thread for async texture uploads."; return nullptr; } std::shared_ptr<impeller::Context> PlatformView::GetImpellerContext() const { return nullptr; } void PlatformView::ReleaseResourceContext() const {} PointerDataDispatcherMaker PlatformView::GetDispatcherMaker() { return [](DefaultPointerDataDispatcher::Delegate& delegate) { return std::make_unique<DefaultPointerDataDispatcher>(delegate); }; } fml::WeakPtr<PlatformView> PlatformView::GetWeakPtr() const { return weak_factory_.GetWeakPtr(); } void PlatformView::UpdateSemantics( SemanticsNodeUpdates update, // NOLINT(performance-unnecessary-value-param) // NOLINTNEXTLINE(performance-unnecessary-value-param) CustomAccessibilityActionUpdates actions) {} void PlatformView::SendChannelUpdate(const std::string& name, bool listening) {} void PlatformView::HandlePlatformMessage( std::unique_ptr<PlatformMessage> message) { if (auto response = message->response()) { response->CompleteEmpty(); } } void PlatformView::OnPreEngineRestart() const {} void PlatformView::RegisterTexture(std::shared_ptr<flutter::Texture> texture) { delegate_.OnPlatformViewRegisterTexture(std::move(texture)); } void PlatformView::UnregisterTexture(int64_t texture_id) { delegate_.OnPlatformViewUnregisterTexture(texture_id); } void PlatformView::MarkTextureFrameAvailable(int64_t texture_id) { delegate_.OnPlatformViewMarkTextureFrameAvailable(texture_id); } std::unique_ptr<Surface> PlatformView::CreateRenderingSurface() { // We have a default implementation because tests create a platform view but // never a rendering surface. FML_DCHECK(false) << "This platform does not provide a rendering surface but " "it was notified of surface rendering surface creation."; return nullptr; } std::shared_ptr<ExternalViewEmbedder> PlatformView::CreateExternalViewEmbedder() { FML_DLOG(WARNING) << "This platform doesn't support embedding external views."; return nullptr; } void PlatformView::SetNextFrameCallback(const fml::closure& closure) { if (!closure) { return; } delegate_.OnPlatformViewSetNextFrameCallback(closure); } std::unique_ptr<std::vector<std::string>> PlatformView::ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data) { std::unique_ptr<std::vector<std::string>> out = std::make_unique<std::vector<std::string>>(); return out; } void PlatformView::RequestDartDeferredLibrary(intptr_t loading_unit_id) {} void PlatformView::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions) {} void PlatformView::LoadDartDeferredLibraryError( intptr_t loading_unit_id, const std::string error_message, // NOLINT(performance-unnecessary-value-param) bool transient) {} void PlatformView::UpdateAssetResolverByType( std::unique_ptr<AssetResolver> updated_asset_resolver, AssetResolver::AssetResolverType type) { delegate_.UpdateAssetResolverByType(std::move(updated_asset_resolver), type); } std::unique_ptr<SnapshotSurfaceProducer> PlatformView::CreateSnapshotSurfaceProducer() { return nullptr; } std::shared_ptr<PlatformMessageHandler> PlatformView::GetPlatformMessageHandler() const { return nullptr; } const Settings& PlatformView::GetSettings() const { return delegate_.OnPlatformViewGetSettings(); } double PlatformView::GetScaledFontSize(double unscaled_font_size, int configuration_id) const { // Unreachable by default, as most platforms do not support nonlinear scaling // and the Flutter application never invokes this method. FML_UNREACHABLE(); return -1; } } // namespace flutter
engine/shell/common/platform_view.cc/0
{ "file_path": "engine/shell/common/platform_view.cc", "repo_id": "engine", "token_count": 2396 }
342
// Copyright 2013 The Flutter 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/common/shell.h" #include "flutter/benchmarking/benchmarking.h" #include "flutter/fml/logging.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/elf_loader.h" #include "flutter/testing/testing.h" namespace flutter { static void StartupAndShutdownShell(benchmark::State& state, bool measure_startup, bool measure_shutdown) { auto assets_dir = fml::OpenDirectory(testing::GetFixturesPath(), false, fml::FilePermission::kRead); std::unique_ptr<Shell> shell; std::unique_ptr<ThreadHost> thread_host; testing::ELFAOTSymbols aot_symbols; { benchmarking::ScopedPauseTiming pause(state, !measure_startup); Settings settings = {}; settings.task_observer_add = [](intptr_t, const fml::closure&) {}; settings.task_observer_remove = [](intptr_t) {}; if (DartVM::IsRunningPrecompiledCode()) { aot_symbols = testing::LoadELFSymbolFromFixturesIfNeccessary( testing::kDefaultAOTAppELFFileName); FML_CHECK( testing::PrepareSettingsForAOTWithSymbols(settings, aot_symbols)) << "Could not set up settings with AOT symbols."; } else { settings.application_kernels = [&]() { std::vector<std::unique_ptr<const fml::Mapping>> kernel_mappings; kernel_mappings.emplace_back( fml::FileMapping::CreateReadOnly(assets_dir, "kernel_blob.bin")); return kernel_mappings; }; } thread_host = std::make_unique<ThreadHost>(ThreadHost::ThreadHostConfig( "io.flutter.bench.", ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi)); TaskRunners task_runners("test", thread_host->platform_thread->GetTaskRunner(), thread_host->raster_thread->GetTaskRunner(), thread_host->ui_thread->GetTaskRunner(), thread_host->io_thread->GetTaskRunner()); shell = Shell::Create( flutter::PlatformData(), task_runners, settings, [](Shell& shell) { return std::make_unique<PlatformView>(shell, shell.GetTaskRunners()); }, [](Shell& shell) { return std::make_unique<Rasterizer>(shell); }); } FML_CHECK(shell); { // The ui thread could be busy processing tasks after shell created, e.g., // default font manager setup. The measurement of shell shutdown should be // considered after those ui tasks have been done. // // However, if we're measuring the complete time from startup to shutdown, // this time should still be included. benchmarking::ScopedPauseTiming pause( state, !measure_shutdown || !measure_startup); fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask(thread_host->ui_thread->GetTaskRunner(), [&latch]() { latch.Signal(); }); latch.Wait(); } { benchmarking::ScopedPauseTiming pause(state, !measure_shutdown); // Shutdown must occur synchronously on the platform thread. fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( thread_host->platform_thread->GetTaskRunner(), [&shell, &latch]() mutable { shell.reset(); latch.Signal(); }); latch.Wait(); thread_host.reset(); } FML_CHECK(!shell); } static void BM_ShellInitialization(benchmark::State& state) { while (state.KeepRunning()) { StartupAndShutdownShell(state, true, false); } } BENCHMARK(BM_ShellInitialization); static void BM_ShellShutdown(benchmark::State& state) { while (state.KeepRunning()) { StartupAndShutdownShell(state, false, true); } } BENCHMARK(BM_ShellShutdown); static void BM_ShellInitializationAndShutdown(benchmark::State& state) { while (state.KeepRunning()) { StartupAndShutdownShell(state, true, true); } } BENCHMARK(BM_ShellInitializationAndShutdown); } // namespace flutter
engine/shell/common/shell_benchmarks.cc/0
{ "file_path": "engine/shell/common/shell_benchmarks.cc", "repo_id": "engine", "token_count": 1742 }
343
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_VULKAN_H_ #define FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_VULKAN_H_ #include "flutter/shell/common/shell_test_external_view_embedder.h" #include "flutter/shell/common/shell_test_platform_view.h" #include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h" #include "flutter/vulkan/vulkan_application.h" #include "flutter/vulkan/vulkan_device.h" #include "flutter/vulkan/vulkan_skia_proc_table.h" namespace flutter { namespace testing { class ShellTestPlatformViewVulkan : public ShellTestPlatformView { public: ShellTestPlatformViewVulkan(PlatformView::Delegate& delegate, const TaskRunners& task_runners, std::shared_ptr<ShellTestVsyncClock> vsync_clock, CreateVsyncWaiter create_vsync_waiter, std::shared_ptr<ShellTestExternalViewEmbedder> shell_test_external_view_embedder); ~ShellTestPlatformViewVulkan() override; void SimulateVSync() override; private: class OffScreenSurface : public flutter::Surface { public: OffScreenSurface(fml::RefPtr<vulkan::VulkanProcTable> vk, std::shared_ptr<ShellTestExternalViewEmbedder> shell_test_external_view_embedder); ~OffScreenSurface() override; // |Surface| bool IsValid() override; // |Surface| std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override; // |Surface| SkMatrix GetRootTransformation() const override; // |Surface| GrDirectContext* GetContext() override; private: bool valid_ = false; fml::RefPtr<vulkan::VulkanProcTable> vk_; std::shared_ptr<ShellTestExternalViewEmbedder> shell_test_external_view_embedder_; std::unique_ptr<vulkan::VulkanApplication> application_; std::unique_ptr<vulkan::VulkanDevice> logical_device_; sk_sp<skgpu::VulkanMemoryAllocator> memory_allocator_; sk_sp<GrDirectContext> context_; bool CreateSkiaGrContext(); bool CreateSkiaBackendContext(GrVkBackendContext* context); FML_DISALLOW_COPY_AND_ASSIGN(OffScreenSurface); }; CreateVsyncWaiter create_vsync_waiter_; std::shared_ptr<ShellTestVsyncClock> vsync_clock_; fml::RefPtr<vulkan::VulkanProcTable> proc_table_; std::shared_ptr<ShellTestExternalViewEmbedder> shell_test_external_view_embedder_; // |PlatformView| std::unique_ptr<Surface> CreateRenderingSurface() override; // |PlatformView| std::shared_ptr<ExternalViewEmbedder> CreateExternalViewEmbedder() override; // |PlatformView| std::unique_ptr<VsyncWaiter> CreateVSyncWaiter() override; // |PlatformView| PointerDataDispatcherMaker GetDispatcherMaker() override; FML_DISALLOW_COPY_AND_ASSIGN(ShellTestPlatformViewVulkan); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_COMMON_SHELL_TEST_PLATFORM_VIEW_VULKAN_H_
engine/shell/common/shell_test_platform_view_vulkan.h/0
{ "file_path": "engine/shell/common/shell_test_platform_view_vulkan.h", "repo_id": "engine", "token_count": 1245 }
344
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/common/variable_refresh_rate_display.h" #include "flutter/fml/logging.h" static double GetInitialRefreshRate( const std::weak_ptr<flutter::VariableRefreshRateReporter>& refresh_rate_reporter) { if (auto reporter = refresh_rate_reporter.lock()) { return reporter->GetRefreshRate(); } return 0; } namespace flutter { VariableRefreshRateDisplay::VariableRefreshRateDisplay( DisplayId display_id, const std::weak_ptr<VariableRefreshRateReporter>& refresh_rate_reporter, double width, double height, double device_pixel_ratio) : Display(display_id, GetInitialRefreshRate(refresh_rate_reporter), width, height, device_pixel_ratio), refresh_rate_reporter_(refresh_rate_reporter) {} double VariableRefreshRateDisplay::GetRefreshRate() const { return GetInitialRefreshRate(refresh_rate_reporter_); } } // namespace flutter
engine/shell/common/variable_refresh_rate_display.cc/0
{ "file_path": "engine/shell/common/variable_refresh_rate_display.cc", "repo_id": "engine", "token_count": 406 }
345
// Copyright 2013 The Flutter 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/gpu/gpu_surface_gl_impeller.h" #include "flutter/fml/make_copyable.h" #include "impeller/display_list/dl_dispatcher.h" #include "impeller/renderer/backend/gles/surface_gles.h" #include "impeller/renderer/renderer.h" #include "impeller/typographer/backends/skia/typographer_context_skia.h" namespace flutter { GPUSurfaceGLImpeller::GPUSurfaceGLImpeller( GPUSurfaceGLDelegate* delegate, std::shared_ptr<impeller::Context> context, bool render_to_surface) : weak_factory_(this) { if (delegate == nullptr) { return; } if (!context || !context->IsValid()) { return; } auto renderer = std::make_shared<impeller::Renderer>(context); if (!renderer->IsValid()) { return; } auto aiks_context = std::make_shared<impeller::AiksContext>( context, impeller::TypographerContextSkia::Make()); if (!aiks_context->IsValid()) { return; } delegate_ = delegate; impeller_context_ = std::move(context); render_to_surface_ = render_to_surface; impeller_renderer_ = std::move(renderer); aiks_context_ = std::move(aiks_context); is_valid_ = true; } // |Surface| GPUSurfaceGLImpeller::~GPUSurfaceGLImpeller() = default; // |Surface| bool GPUSurfaceGLImpeller::IsValid() { return is_valid_; } // |Surface| std::unique_ptr<SurfaceFrame> GPUSurfaceGLImpeller::AcquireFrame( const SkISize& size) { if (!IsValid()) { FML_LOG(ERROR) << "OpenGL surface was invalid."; return nullptr; } auto swap_callback = [weak = weak_factory_.GetWeakPtr(), delegate = delegate_]() -> bool { if (weak) { GLPresentInfo present_info = { .fbo_id = 0u, .frame_damage = std::nullopt, // TODO (https://github.com/flutter/flutter/issues/105597): wire-up // presentation time to impeller backend. .presentation_time = std::nullopt, .buffer_damage = std::nullopt, }; delegate->GLContextPresent(present_info); } return true; }; auto context_switch = delegate_->GLContextMakeCurrent(); if (!context_switch->GetResult()) { FML_LOG(ERROR) << "Could not make the context current to acquire the frame."; return nullptr; } if (!render_to_surface_) { return std::make_unique<SurfaceFrame>( nullptr, SurfaceFrame::FramebufferInfo{.supports_readback = true}, [](const SurfaceFrame& surface_frame, DlCanvas* canvas) { return true; }, size); } GLFrameInfo frame_info = {static_cast<uint32_t>(size.width()), static_cast<uint32_t>(size.height())}; const GLFBOInfo fbo_info = delegate_->GLContextFBO(frame_info); auto surface = impeller::SurfaceGLES::WrapFBO( impeller_context_, // context swap_callback, // swap_callback fbo_info.fbo_id, // fbo impeller::PixelFormat::kR8G8B8A8UNormInt, // color_format impeller::ISize{size.width(), size.height()} // fbo_size ); SurfaceFrame::SubmitCallback submit_callback = fml::MakeCopyable([renderer = impeller_renderer_, // aiks_context = aiks_context_, // surface = std::move(surface) // ](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool { if (!aiks_context) { return false; } auto display_list = surface_frame.BuildDisplayList(); if (!display_list) { FML_LOG(ERROR) << "Could not build display list for surface frame."; return false; } auto cull_rect = surface->GetTargetRenderPassDescriptor().GetRenderTargetSize(); impeller::Rect dl_cull_rect = impeller::Rect::MakeSize(cull_rect); impeller::DlDispatcher impeller_dispatcher(dl_cull_rect); display_list->Dispatch( impeller_dispatcher, SkIRect::MakeWH(cull_rect.width, cull_rect.height)); auto picture = impeller_dispatcher.EndRecordingAsPicture(); return renderer->Render( std::move(surface), fml::MakeCopyable( [aiks_context, picture = std::move(picture)]( impeller::RenderTarget& render_target) -> bool { return aiks_context->Render(picture, render_target, /*reset_host_buffer=*/true); })); }); return std::make_unique<SurfaceFrame>( nullptr, // surface delegate_->GLContextFramebufferInfo(), // framebuffer info submit_callback, // submit callback size, // frame size std::move(context_switch), // context result true // display list fallback ); } // |Surface| SkMatrix GPUSurfaceGLImpeller::GetRootTransformation() const { // This backend does not currently support root surface transformations. Just // return identity. return {}; } // |Surface| GrDirectContext* GPUSurfaceGLImpeller::GetContext() { // Impeller != Skia. return nullptr; } // |Surface| std::unique_ptr<GLContextResult> GPUSurfaceGLImpeller::MakeRenderContextCurrent() { return delegate_->GLContextMakeCurrent(); } // |Surface| bool GPUSurfaceGLImpeller::ClearRenderContext() { return delegate_->GLContextClearCurrent(); } bool GPUSurfaceGLImpeller::AllowsDrawingWhenGpuDisabled() const { return delegate_->AllowsDrawingWhenGpuDisabled(); } // |Surface| bool GPUSurfaceGLImpeller::EnableRasterCache() const { return false; } // |Surface| std::shared_ptr<impeller::AiksContext> GPUSurfaceGLImpeller::GetAiksContext() const { return aiks_context_; } } // namespace flutter
engine/shell/gpu/gpu_surface_gl_impeller.cc/0
{ "file_path": "engine/shell/gpu/gpu_surface_gl_impeller.cc", "repo_id": "engine", "token_count": 2597 }
346
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_H_ #define FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_H_ #include <memory> #include "flutter/flow/surface.h" #include "flutter/fml/macros.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h" #include "flutter/vulkan/vulkan_backbuffer.h" #include "flutter/vulkan/vulkan_native_surface.h" #include "flutter/vulkan/vulkan_window.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief A GPU surface backed by VkImages provided by a /// GPUSurfaceVulkanDelegate. /// class GPUSurfaceVulkan : public Surface { public: //------------------------------------------------------------------------------ /// @brief Create a GPUSurfaceVulkan while letting it reuse an existing /// GrDirectContext. /// GPUSurfaceVulkan(GPUSurfaceVulkanDelegate* delegate, const sk_sp<GrDirectContext>& context, bool render_to_surface); ~GPUSurfaceVulkan() override; // |Surface| bool IsValid() override; // |Surface| std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override; // |Surface| SkMatrix GetRootTransformation() const override; // |Surface| GrDirectContext* GetContext() override; static SkColorType ColorTypeFromFormat(const VkFormat format); private: GPUSurfaceVulkanDelegate* delegate_; sk_sp<GrDirectContext> skia_context_; bool render_to_surface_; fml::WeakPtrFactory<GPUSurfaceVulkan> weak_factory_; sk_sp<SkSurface> CreateSurfaceFromVulkanImage(const VkImage image, const VkFormat format, const SkISize& size); FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceVulkan); }; } // namespace flutter #endif // FLUTTER_SHELL_GPU_GPU_SURFACE_VULKAN_H_
engine/shell/gpu/gpu_surface_vulkan.h/0
{ "file_path": "engine/shell/gpu/gpu_surface_vulkan.h", "repo_id": "engine", "token_count": 834 }
347
// Copyright 2013 The Flutter 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/android_context_vulkan_impeller.h" #include "flutter/fml/paths.h" #include "flutter/impeller/entity/vk/entity_shaders_vk.h" #include "flutter/impeller/entity/vk/framebuffer_blend_shaders_vk.h" #include "flutter/impeller/entity/vk/modern_shaders_vk.h" #include "flutter/impeller/renderer/backend/vulkan/context_vk.h" #if IMPELLER_ENABLE_3D #include "flutter/impeller/scene/shaders/vk/scene_shaders_vk.h" // nogncheck #endif // IMPELLER_ENABLE_3D namespace flutter { static std::shared_ptr<impeller::Context> CreateImpellerContext( const fml::RefPtr<fml::NativeLibrary>& vulkan_dylib, bool enable_vulkan_validation, bool enable_gpu_tracing, bool quiet) { if (!vulkan_dylib) { VALIDATION_LOG << "Could not open the Vulkan dylib."; return nullptr; } std::vector<std::shared_ptr<fml::Mapping>> shader_mappings = { std::make_shared<fml::NonOwnedMapping>(impeller_entity_shaders_vk_data, impeller_entity_shaders_vk_length), std::make_shared<fml::NonOwnedMapping>( impeller_framebuffer_blend_shaders_vk_data, impeller_framebuffer_blend_shaders_vk_length), #if IMPELLER_ENABLE_3D std::make_shared<fml::NonOwnedMapping>(impeller_scene_shaders_vk_data, impeller_scene_shaders_vk_length), #endif std::make_shared<fml::NonOwnedMapping>(impeller_modern_shaders_vk_data, impeller_modern_shaders_vk_length), }; auto instance_proc_addr = vulkan_dylib->ResolveFunction<PFN_vkGetInstanceProcAddr>( "vkGetInstanceProcAddr"); if (!instance_proc_addr.has_value()) { VALIDATION_LOG << "Could not setup Vulkan proc table."; return nullptr; } impeller::ContextVK::Settings settings; settings.proc_address_callback = instance_proc_addr.value(); settings.shader_libraries_data = std::move(shader_mappings); settings.cache_directory = fml::paths::GetCachesDirectory(); settings.enable_validation = enable_vulkan_validation; settings.enable_gpu_tracing = enable_gpu_tracing; auto context = impeller::ContextVK::Create(std::move(settings)); if (!quiet) { if (context && impeller::CapabilitiesVK::Cast(*context->GetCapabilities()) .AreValidationsEnabled()) { FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (Vulkan with " "Validation Layers)."; } else { FML_LOG(IMPORTANT) << "Using the Impeller rendering backend (Vulkan)."; } } return context; } AndroidContextVulkanImpeller::AndroidContextVulkanImpeller( bool enable_validation, bool enable_gpu_tracing, bool quiet) : AndroidContext(AndroidRenderingAPI::kImpellerVulkan), vulkan_dylib_(fml::NativeLibrary::Create("libvulkan.so")) { auto impeller_context = CreateImpellerContext( vulkan_dylib_, enable_validation, enable_gpu_tracing, quiet); SetImpellerContext(impeller_context); is_valid_ = !!impeller_context; } AndroidContextVulkanImpeller::~AndroidContextVulkanImpeller() = default; bool AndroidContextVulkanImpeller::IsValid() const { return is_valid_; } } // namespace flutter
engine/shell/platform/android/android_context_vulkan_impeller.cc/0
{ "file_path": "engine/shell/platform/android/android_context_vulkan_impeller.cc", "repo_id": "engine", "token_count": 1386 }
348
// Copyright 2013 The Flutter 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/android_surface_gl_skia.h" #include <GLES/gl.h> #include <utility> #include "flutter/fml/logging.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/shell/platform/android/android_egl_surface.h" #include "flutter/shell/platform/android/android_shell_holder.h" namespace flutter { namespace { // GL renderer string prefix used by the Android emulator GLES implementation. constexpr char kEmulatorRendererPrefix[] = "Android Emulator OpenGL ES Translator"; } // anonymous namespace AndroidSurfaceGLSkia::AndroidSurfaceGLSkia( const std::shared_ptr<AndroidContextGLSkia>& android_context) : android_context_(android_context), native_window_(nullptr), onscreen_surface_(nullptr), offscreen_surface_(nullptr) { // Acquire the offscreen surface. offscreen_surface_ = android_context_->CreateOffscreenSurface(); if (!offscreen_surface_->IsValid()) { offscreen_surface_ = nullptr; } } AndroidSurfaceGLSkia::~AndroidSurfaceGLSkia() = default; void AndroidSurfaceGLSkia::TeardownOnScreenContext() { // When the onscreen surface is destroyed, the context and the surface // instance should be deleted. Issue: // https://github.com/flutter/flutter/issues/64414 android_context_->ClearCurrent(); onscreen_surface_ = nullptr; } bool AndroidSurfaceGLSkia::IsValid() const { return offscreen_surface_ && android_context_->IsValid(); } std::unique_ptr<Surface> AndroidSurfaceGLSkia::CreateGPUSurface( GrDirectContext* gr_context) { if (gr_context) { return std::make_unique<GPUSurfaceGLSkia>(sk_ref_sp(gr_context), this, true); } else { sk_sp<GrDirectContext> main_skia_context = android_context_->GetMainSkiaContext(); if (!main_skia_context) { main_skia_context = GPUSurfaceGLSkia::MakeGLContext(this); android_context_->SetMainSkiaContext(main_skia_context); } return std::make_unique<GPUSurfaceGLSkia>(main_skia_context, this, true); } } bool AndroidSurfaceGLSkia::OnScreenSurfaceResize(const SkISize& size) { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); FML_DCHECK(native_window_); if (size == onscreen_surface_->GetSize()) { return true; } android_context_->ClearCurrent(); // Ensure the destructor is called since it destroys the `EGLSurface` before // creating a new onscreen surface. onscreen_surface_ = nullptr; onscreen_surface_ = android_context_->CreateOnscreenSurface(native_window_); if (!onscreen_surface_->IsValid()) { FML_LOG(ERROR) << "Unable to create EGL window surface on resize."; return false; } onscreen_surface_->MakeCurrent(); return true; } bool AndroidSurfaceGLSkia::ResourceContextMakeCurrent() { FML_DCHECK(IsValid()); auto status = offscreen_surface_->MakeCurrent(); return status != AndroidEGLSurfaceMakeCurrentStatus::kFailure; } bool AndroidSurfaceGLSkia::ResourceContextClearCurrent() { FML_DCHECK(IsValid()); EGLBoolean result = eglMakeCurrent(eglGetCurrentDisplay(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); return result == EGL_TRUE; } bool AndroidSurfaceGLSkia::SetNativeWindow( fml::RefPtr<AndroidNativeWindow> window) { FML_DCHECK(IsValid()); FML_DCHECK(window); native_window_ = window; // Ensure the destructor is called since it destroys the `EGLSurface` before // creating a new onscreen surface. onscreen_surface_ = nullptr; // Create the onscreen surface. onscreen_surface_ = android_context_->CreateOnscreenSurface(window); if (!onscreen_surface_->IsValid()) { return false; } return true; } std::unique_ptr<GLContextResult> AndroidSurfaceGLSkia::GLContextMakeCurrent() { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); auto status = onscreen_surface_->MakeCurrent(); auto default_context_result = std::make_unique<GLContextDefaultResult>( status != AndroidEGLSurfaceMakeCurrentStatus::kFailure); return std::move(default_context_result); } bool AndroidSurfaceGLSkia::GLContextClearCurrent() { FML_DCHECK(IsValid()); return android_context_->ClearCurrent(); } SurfaceFrame::FramebufferInfo AndroidSurfaceGLSkia::GLContextFramebufferInfo() const { FML_DCHECK(IsValid()); SurfaceFrame::FramebufferInfo res; res.supports_readback = true; res.supports_partial_repaint = onscreen_surface_->SupportsPartialRepaint(); res.existing_damage = onscreen_surface_->InitialDamage(); // Some devices (Pixel2 XL) needs EGL_KHR_partial_update rect aligned to 4, // otherwise there are glitches // (https://github.com/flutter/flutter/issues/97482#) // Larger alignment might also be beneficial for tile base renderers. res.horizontal_clip_alignment = 32; res.vertical_clip_alignment = 32; return res; } void AndroidSurfaceGLSkia::GLContextSetDamageRegion( const std::optional<SkIRect>& region) { FML_DCHECK(IsValid()); onscreen_surface_->SetDamageRegion(region); } bool AndroidSurfaceGLSkia::GLContextPresent(const GLPresentInfo& present_info) { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); if (present_info.presentation_time) { onscreen_surface_->SetPresentationTime(*present_info.presentation_time); } return onscreen_surface_->SwapBuffers(present_info.frame_damage); } GLFBOInfo AndroidSurfaceGLSkia::GLContextFBO(GLFrameInfo frame_info) const { FML_DCHECK(IsValid()); // The default window bound framebuffer on Android. return GLFBOInfo{ .fbo_id = 0, .existing_damage = onscreen_surface_->InitialDamage(), }; } // |GPUSurfaceGLDelegate| sk_sp<const GrGLInterface> AndroidSurfaceGLSkia::GetGLInterface() const { // This is a workaround for a bug in the Android emulator EGL/GLES // implementation. Some versions of the emulator will not update the // GL version string when the process switches to a new EGL context // unless the EGL context is being made current for the first time. // The inaccurate version string will be rejected by Skia when it // tries to build the GrGLInterface. Flutter can work around this // by creating a new context, making it current to force an update // of the version, and then reverting to the previous context. const char* gl_renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); if (gl_renderer && strncmp(gl_renderer, kEmulatorRendererPrefix, strlen(kEmulatorRendererPrefix)) == 0) { EGLContext new_context = android_context_->CreateNewContext(); if (new_context != EGL_NO_CONTEXT) { EGLContext old_context = eglGetCurrentContext(); EGLDisplay display = eglGetCurrentDisplay(); EGLSurface draw_surface = eglGetCurrentSurface(EGL_DRAW); EGLSurface read_surface = eglGetCurrentSurface(EGL_READ); [[maybe_unused]] EGLBoolean result = eglMakeCurrent(display, draw_surface, read_surface, new_context); FML_DCHECK(result == EGL_TRUE); result = eglMakeCurrent(display, draw_surface, read_surface, old_context); FML_DCHECK(result == EGL_TRUE); result = eglDestroyContext(display, new_context); FML_DCHECK(result == EGL_TRUE); } } return GPUSurfaceGLDelegate::GetGLInterface(); } std::unique_ptr<Surface> AndroidSurfaceGLSkia::CreateSnapshotSurface() { if (!onscreen_surface_ || !onscreen_surface_->IsValid()) { onscreen_surface_ = android_context_->CreatePbufferSurface(); } sk_sp<GrDirectContext> main_skia_context = android_context_->GetMainSkiaContext(); if (!main_skia_context) { main_skia_context = GPUSurfaceGLSkia::MakeGLContext(this); android_context_->SetMainSkiaContext(main_skia_context); } return std::make_unique<GPUSurfaceGLSkia>(main_skia_context, this, true); } } // namespace flutter
engine/shell/platform/android/android_surface_gl_skia.cc/0
{ "file_path": "engine/shell/platform/android/android_surface_gl_skia.cc", "repo_id": "engine", "token_count": 2793 }
349
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #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/GrDirectContext.h" namespace flutter { namespace 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(kImplicitViewId, 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(kImplicitViewId, 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(kImplicitViewId, 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; }, /*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; }, /*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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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(kImplicitViewId, frame_size, 1.5); // Add an Android view. MutatorsStack stack1; SkMatrix matrix1; matrix1.setIdentity(); SkMatrix scale = SkMatrix::Scale(1.5, 1.5); SkMatrix trans = SkMatrix::Translate(100, 100); matrix1.setConcat(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>( 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); auto rect_paint = DlPaint(); 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(SkRect::MakeXYWH(0, 0, 50, 50), rect_paint); // This simulates Flutter UI that intersects with the Android view. canvas_1->DrawRect(SkRect::MakeXYWH(50, 50, 200, 200), rect_paint); canvas_1->DrawRect(SkRect::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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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(kImplicitViewId, frame_size, 1.5); // Add an Android view. MutatorsStack stack1; SkMatrix matrix1; matrix1.setIdentity(); SkMatrix scale = SkMatrix::Scale(1.5, 1.5); SkMatrix trans = SkMatrix::Translate(100, 100); matrix1.setConcat(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>( 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); auto rect_paint = DlPaint(); 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(SkRect::MakeXYWH(0, 0, 50, 50), rect_paint); // This simulates Flutter UI that intersects with the Android view. canvas_1->DrawRect(SkRect::MakeXYWH(50, 50, 200, 200), rect_paint); canvas_1->DrawRect(SkRect::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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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; }, /*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(kImplicitViewId, 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( SkRect::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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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; }, /*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(kImplicitViewId, frame_size, 1.5); { // Add first Android view. SkMatrix matrix; MutatorsStack stack; stack.PushTransform(SkMatrix::Translate(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( SkRect::MakeXYWH(25, 25, 80, 150), rect_paint); { // Add second Android view. SkMatrix matrix; MutatorsStack stack; stack.PushTransform(SkMatrix::Translate(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(SkRect::MakeXYWH(25, 25, 80, 50), rect_paint); embedder->CompositeEmbeddedView(1)->DrawRect( SkRect::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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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; }, /*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(kImplicitViewId, frame_size, 1.5); { // Add Android view. SkMatrix matrix; MutatorsStack stack; stack.PushTransform(SkMatrix::Translate(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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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(kImplicitViewId, 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; }, /*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(kImplicitViewId, 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( SkRect::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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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(kImplicitViewId, 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; }, /*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(kImplicitViewId, 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( SkRect::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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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(kImplicitViewId, 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(kImplicitViewId, 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; }, /*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(kImplicitViewId, 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( SkRect::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; }, /*frame_size=*/SkISize::Make(800, 600)); embedder->SubmitFlutterView(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 flutter
engine/shell/platform/android/external_view_embedder/external_view_embedder_unittests.cc/0
{ "file_path": "engine/shell/platform/android/external_view_embedder/external_view_embedder_unittests.cc", "repo_id": "engine", "token_count": 17389 }
350
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/image_lru.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(ImageLRU, CanStoreSingleImage) { auto image = DlImage::Make(nullptr); ImageLRU image_lru; EXPECT_EQ(image_lru.FindImage(1), nullptr); image_lru.AddImage(image, 1); EXPECT_EQ(image_lru.FindImage(1), image); } TEST(ImageLRU, EvictsLRU) { auto image = DlImage::Make(nullptr); ImageLRU image_lru; // Fill up the cache, nothing is removed for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { EXPECT_EQ(image_lru.AddImage(image, i + 1), 0u); } // Confirm each image is in the cache. This should keep the LRU // order the same. for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { EXPECT_EQ(image_lru.FindImage(i + 1), image); } // Insert new image and verify least recently used was removed. EXPECT_EQ(image_lru.AddImage(image, 100), 1u); } TEST(ImageLRU, CanClear) { auto image = DlImage::Make(nullptr); ImageLRU image_lru; // Fill up the cache, nothing is removed for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { EXPECT_EQ(image_lru.AddImage(image, i + 1), 0u); } image_lru.Clear(); // Expect no cache entries. for (auto i = 0u; i < kImageReaderSwapchainSize; i++) { EXPECT_EQ(image_lru.FindImage(i + 1), nullptr); } } } // namespace testing } // namespace flutter
engine/shell/platform/android/image_lru_unittests.cc/0
{ "file_path": "engine/shell/platform/android/image_lru_unittests.cc", "repo_id": "engine", "token_count": 584 }
351
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.android; /** Collection of Flutter launch configuration options. */ // This class is public so that Flutter app developers can reference // BackgroundMode @SuppressWarnings("WeakerAccess") public class FlutterActivityLaunchConfigs { // Meta-data arguments, processed from manifest XML. /* package */ static final String DART_ENTRYPOINT_META_DATA_KEY = "io.flutter.Entrypoint"; /* package */ static final String DART_ENTRYPOINT_URI_META_DATA_KEY = "io.flutter.EntrypointUri"; /* package */ static final String INITIAL_ROUTE_META_DATA_KEY = "io.flutter.InitialRoute"; /* package */ static final String NORMAL_THEME_META_DATA_KEY = "io.flutter.embedding.android.NormalTheme"; /* package */ static final String HANDLE_DEEPLINKING_META_DATA_KEY = "flutter_deeplinking_enabled"; // Intent extra arguments. /* package */ static final String EXTRA_DART_ENTRYPOINT = "dart_entrypoint"; /* package */ static final String EXTRA_INITIAL_ROUTE = "route"; /* package */ static final String EXTRA_BACKGROUND_MODE = "background_mode"; /* package */ static final String EXTRA_CACHED_ENGINE_ID = "cached_engine_id"; /* package */ static final String EXTRA_DART_ENTRYPOINT_ARGS = "dart_entrypoint_args"; /* package */ static final String EXTRA_CACHED_ENGINE_GROUP_ID = "cached_engine_group_id"; /* package */ static final String EXTRA_DESTROY_ENGINE_WITH_ACTIVITY = "destroy_engine_with_activity"; /* package */ static final String EXTRA_ENABLE_STATE_RESTORATION = "enable_state_restoration"; // Default configuration. /* package */ static final String DEFAULT_DART_ENTRYPOINT = "main"; /* package */ static final String DEFAULT_INITIAL_ROUTE = "/"; /* package */ static final String DEFAULT_BACKGROUND_MODE = BackgroundMode.opaque.name(); /** The mode of the background of a Flutter {@code Activity}, either opaque or transparent. */ public enum BackgroundMode { /** Indicates a FlutterActivity with an opaque background. This is the default. */ opaque, /** Indicates a FlutterActivity with a transparent background. */ transparent } private FlutterActivityLaunchConfigs() {} }
engine/shell/platform/android/io/flutter/embedding/android/FlutterActivityLaunchConfigs.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterActivityLaunchConfigs.java", "repo_id": "engine", "token_count": 708 }
352
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.android; /** Render modes for a Flutter UI. */ public enum RenderMode { /** * {@code RenderMode}, which paints a Flutter UI to a {@link android.view.SurfaceView}. This mode * has the best performance, but a Flutter UI in this mode cannot be positioned between 2 other * Android {@code View}s in the z-index, nor can it be animated/transformed. Unless the special * capabilities of a {@link android.graphics.SurfaceTexture} are required, developers should * strongly prefer this render mode. */ surface, /** * {@code RenderMode}, which paints a Flutter UI to a {@link android.graphics.SurfaceTexture}. * This mode is not as performant as {@link #surface}, but a Flutter UI in this mode can be * animated and transformed, as well as positioned in the z-index between 2+ other Android {@code * Views}. Unless the special capabilities of a {@link android.graphics.SurfaceTexture} are * required, developers should strongly prefer the {@link #surface} render mode. */ texture, /** * {@code RenderMode}, which paints Paints a Flutter UI provided by an {@link * android.media.ImageReader} onto a {@link android.graphics.Canvas}. This mode is not as * performant as {@link RenderMode#surface}, but a {@code FlutterView} in this mode can handle * full interactivity with a {@link io.flutter.plugin.platform.PlatformView}. Unless {@link * io.flutter.plugin.platform.PlatformView}s are required developers should strongly prefer the * {@link RenderMode#surface} render mode. */ image }
engine/shell/platform/android/io/flutter/embedding/android/RenderMode.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/RenderMode.java", "repo_id": "engine", "token_count": 500 }
353
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.deferredcomponents; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.os.Build; import android.os.Bundle; import android.util.SparseArray; import android.util.SparseIntArray; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.play.core.splitinstall.SplitInstallException; import com.google.android.play.core.splitinstall.SplitInstallManager; import com.google.android.play.core.splitinstall.SplitInstallManagerFactory; import com.google.android.play.core.splitinstall.SplitInstallRequest; import com.google.android.play.core.splitinstall.SplitInstallSessionState; import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener; import com.google.android.play.core.splitinstall.model.SplitInstallErrorCode; import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus; import io.flutter.Log; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.loader.ApplicationInfoLoader; import io.flutter.embedding.engine.loader.FlutterApplicationInfo; import io.flutter.embedding.engine.systemchannels.DeferredComponentChannel; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; /** * Flutter default implementation of DeferredComponentManager that downloads deferred component from * the Google Play store as a dynamic feature module. */ public class PlayStoreDeferredComponentManager implements DeferredComponentManager { private static final String TAG = "PlayStoreDeferredComponentManager"; public static final String MAPPING_KEY = DeferredComponentManager.class.getName() + ".loadingUnitMapping"; private @NonNull SplitInstallManager splitInstallManager; private @Nullable FlutterJNI flutterJNI; private @Nullable DeferredComponentChannel channel; private @NonNull Context context; private @NonNull FlutterApplicationInfo flutterApplicationInfo; // Each request to install a feature module gets a session ID. These maps associate // the session ID with the loading unit and component name that was requested. private @NonNull SparseArray<String> sessionIdToName; private @NonNull SparseIntArray sessionIdToLoadingUnitId; private @NonNull SparseArray<String> sessionIdToState; private @NonNull Map<String, Integer> nameToSessionId; protected @NonNull SparseArray<String> loadingUnitIdToComponentNames; protected @NonNull SparseArray<String> loadingUnitIdToSharedLibraryNames; private FeatureInstallStateUpdatedListener listener; private class FeatureInstallStateUpdatedListener implements SplitInstallStateUpdatedListener { @SuppressLint("DefaultLocale") public void onStateUpdate(@NonNull SplitInstallSessionState state) { int sessionId = state.sessionId(); if (sessionIdToName.get(sessionId) != null) { switch (state.status()) { case SplitInstallSessionStatus.FAILED: { Log.e( TAG, String.format( "Module \"%s\" (sessionId %d) install failed with: %s", sessionIdToName.get(sessionId), sessionId, state.errorCode())); flutterJNI.deferredComponentInstallFailure( sessionIdToLoadingUnitId.get(sessionId), "Module install failed with " + state.errorCode(), true); if (channel != null) { channel.completeInstallError( sessionIdToName.get(sessionId), "Android Deferred Component failed to install."); } sessionIdToName.delete(sessionId); sessionIdToLoadingUnitId.delete(sessionId); sessionIdToState.put(sessionId, "failed"); break; } case SplitInstallSessionStatus.INSTALLED: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) install successfully.", sessionIdToName.get(sessionId), sessionId)); loadAssets(sessionIdToLoadingUnitId.get(sessionId), sessionIdToName.get(sessionId)); // We only load Dart shared lib for the loading unit id requested. Other loading units // (if present) in the deferred component are not loaded, but can be loaded by // calling again with their loading unit id. If no valid loadingUnitId was included in // the installation request such as for an asset only feature, then we can skip this. if (sessionIdToLoadingUnitId.get(sessionId) > 0) { loadDartLibrary( sessionIdToLoadingUnitId.get(sessionId), sessionIdToName.get(sessionId)); } if (channel != null) { channel.completeInstallSuccess(sessionIdToName.get(sessionId)); } sessionIdToName.delete(sessionId); sessionIdToLoadingUnitId.delete(sessionId); sessionIdToState.put(sessionId, "installed"); break; } case SplitInstallSessionStatus.CANCELED: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) install canceled.", sessionIdToName.get(sessionId), sessionId)); if (channel != null) { channel.completeInstallError( sessionIdToName.get(sessionId), "Android Deferred Component installation canceled."); } sessionIdToName.delete(sessionId); sessionIdToLoadingUnitId.delete(sessionId); sessionIdToState.put(sessionId, "cancelled"); break; } case SplitInstallSessionStatus.CANCELING: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) install canceling.", sessionIdToName.get(sessionId), sessionId)); sessionIdToState.put(sessionId, "canceling"); break; } case SplitInstallSessionStatus.PENDING: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) install pending.", sessionIdToName.get(sessionId), sessionId)); sessionIdToState.put(sessionId, "pending"); break; } case SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) install requires user confirmation.", sessionIdToName.get(sessionId), sessionId)); sessionIdToState.put(sessionId, "requiresUserConfirmation"); break; } case SplitInstallSessionStatus.DOWNLOADING: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) downloading.", sessionIdToName.get(sessionId), sessionId)); sessionIdToState.put(sessionId, "downloading"); break; } case SplitInstallSessionStatus.DOWNLOADED: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) downloaded.", sessionIdToName.get(sessionId), sessionId)); sessionIdToState.put(sessionId, "downloaded"); break; } case SplitInstallSessionStatus.INSTALLING: { Log.d( TAG, String.format( "Module \"%s\" (sessionId %d) installing.", sessionIdToName.get(sessionId), sessionId)); sessionIdToState.put(sessionId, "installing"); break; } default: Log.d(TAG, "Unknown status: " + state.status()); } } } } public PlayStoreDeferredComponentManager( @NonNull Context context, @Nullable FlutterJNI flutterJNI) { this.context = context; this.flutterJNI = flutterJNI; this.flutterApplicationInfo = ApplicationInfoLoader.load(context); splitInstallManager = SplitInstallManagerFactory.create(context); listener = new FeatureInstallStateUpdatedListener(); splitInstallManager.registerListener(listener); sessionIdToName = new SparseArray<>(); sessionIdToLoadingUnitId = new SparseIntArray(); sessionIdToState = new SparseArray<>(); nameToSessionId = new HashMap<>(); loadingUnitIdToComponentNames = new SparseArray<>(); loadingUnitIdToSharedLibraryNames = new SparseArray<>(); initLoadingUnitMappingToComponentNames(); } public void setJNI(@NonNull FlutterJNI flutterJNI) { this.flutterJNI = flutterJNI; } private boolean verifyJNI() { if (flutterJNI == null) { Log.e( TAG, "No FlutterJNI provided. `setJNI` must be called on the DeferredComponentManager before attempting to load dart libraries or invoking with platform channels."); return false; } return true; } public void setDeferredComponentChannel(@NonNull DeferredComponentChannel channel) { this.channel = channel; } @NonNull private ApplicationInfo getApplicationInfo() { try { return context .getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { throw new RuntimeException(e); } } // Obtain and parses the metadata string. An example encoded string is: // // "2:component2,3:component3,4:component1:libcomponent4.so,5:" // // Where loading unit 2 is included in component2, loading unit 3 is // included in component3, and loading unit 4 is included in component1. // An optional third parameter can be added to indicate the name of // the shared library of the loading unit. Loading unit 5 maps to an empty // string, indicating it is included in the base module and no dynamic // feature modules need to be downloaded. private void initLoadingUnitMappingToComponentNames() { String mappingKey = DeferredComponentManager.class.getName() + ".loadingUnitMapping"; ApplicationInfo applicationInfo = getApplicationInfo(); if (applicationInfo != null) { Bundle metaData = applicationInfo.metaData; if (metaData != null) { String rawMappingString = metaData.getString(MAPPING_KEY, null); if (rawMappingString == null) { Log.e( TAG, "No loading unit to dynamic feature module name found. Ensure '" + MAPPING_KEY + "' is defined in the base module's AndroidManifest."); return; } if (rawMappingString.equals("")) { // Asset-only components, so no loading units to map. return; } for (String entry : rawMappingString.split(",")) { // Split with -1 param to include empty string following trailing ":" String[] splitEntry = entry.split(":", -1); int loadingUnitId = Integer.parseInt(splitEntry[0]); loadingUnitIdToComponentNames.put(loadingUnitId, splitEntry[1]); if (splitEntry.length > 2) { loadingUnitIdToSharedLibraryNames.put(loadingUnitId, splitEntry[2]); } } } } } public void installDeferredComponent(int loadingUnitId, @Nullable String componentName) { String resolvedComponentName = componentName != null ? componentName : loadingUnitIdToComponentNames.get(loadingUnitId); if (resolvedComponentName == null) { Log.e( TAG, "Deferred component name was null and could not be resolved from loading unit id."); return; } // Handle a loading unit that is included in the base module that does not need download. if (resolvedComponentName.equals("") && loadingUnitId > 0) { // No need to load assets as base assets are already loaded. loadDartLibrary(loadingUnitId, resolvedComponentName); return; } SplitInstallRequest request = SplitInstallRequest.newBuilder().addModule(resolvedComponentName).build(); splitInstallManager // Submits the request to install the module through the // asynchronous startInstall() task. Your app needs to be // in the foreground to submit the request. .startInstall(request) // Called when the install request is sent successfully. This is different than a successful // install which is handled in FeatureInstallStateUpdatedListener. .addOnSuccessListener( sessionId -> { sessionIdToName.put(sessionId, resolvedComponentName); sessionIdToLoadingUnitId.put(sessionId, loadingUnitId); if (nameToSessionId.containsKey(resolvedComponentName)) { sessionIdToState.remove(nameToSessionId.get(resolvedComponentName)); } nameToSessionId.put(resolvedComponentName, sessionId); sessionIdToState.put(sessionId, "Requested"); }) .addOnFailureListener( exception -> { switch (((SplitInstallException) exception).getErrorCode()) { case SplitInstallErrorCode.NETWORK_ERROR: flutterJNI.deferredComponentInstallFailure( loadingUnitId, "Install of deferred component module \"" + componentName + "\" failed with a network error", true); break; case SplitInstallErrorCode.MODULE_UNAVAILABLE: flutterJNI.deferredComponentInstallFailure( loadingUnitId, "Install of deferred component module \"" + componentName + "\" failed as it is unavailable", false); break; default: flutterJNI.deferredComponentInstallFailure( loadingUnitId, String.format( "Install of deferred component module \"%s\" failed with error %d: %s", componentName, ((SplitInstallException) exception).getErrorCode(), ((SplitInstallException) exception).getMessage()), false); break; } }); } @NonNull public String getDeferredComponentInstallState( int loadingUnitId, @Nullable String componentName) { String resolvedComponentName = componentName != null ? componentName : loadingUnitIdToComponentNames.get(loadingUnitId); if (resolvedComponentName == null) { Log.e( TAG, "Deferred component name was null and could not be resolved from loading unit id."); return "unknown"; } if (!nameToSessionId.containsKey(resolvedComponentName)) { if (splitInstallManager.getInstalledModules().contains(resolvedComponentName)) { return "installedPendingLoad"; } return "unknown"; } int sessionId = nameToSessionId.get(resolvedComponentName); return sessionIdToState.get(sessionId); } public void loadAssets(int loadingUnitId, @NonNull String componentName) { if (!verifyJNI()) { return; } // Since android deferred component asset manager is handled through // context, neither parameter is used here. Assets are stored in // the apk's `assets` directory allowing them to be accessed by // Android's AssetManager directly. try { context = context.createPackageContext(context.getPackageName(), 0); AssetManager assetManager = context.getAssets(); flutterJNI.updateJavaAssetManager(assetManager, flutterApplicationInfo.flutterAssetsDir); } catch (NameNotFoundException e) { throw new RuntimeException(e); } } public void loadDartLibrary(int loadingUnitId, @NonNull String componentName) { if (!verifyJNI()) { return; } // Loading unit must be specified and valid to load a dart library. if (loadingUnitId < 0) { return; } String aotSharedLibraryName = loadingUnitIdToSharedLibraryNames.get(loadingUnitId); if (aotSharedLibraryName == null) { // If the filename is not specified, we use dart's loading unit naming convention. aotSharedLibraryName = flutterApplicationInfo.aotSharedLibraryName + "-" + loadingUnitId + ".part.so"; } // Possible values: armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips, mips64 String abi = Build.SUPPORTED_ABIS[0]; String pathAbi = abi.replace("-", "_"); // abis are represented with underscores in paths. // TODO(garyq): Optimize this apk/file discovery process to use less i/o and be more // performant and robust. // Search directly in APKs first List<String> apkPaths = new ArrayList<>(); // If not found in APKs, we check in extracted native libs for the lib directly. List<String> soPaths = new ArrayList<>(); Queue<File> searchFiles = new LinkedList<>(); // Downloaded modules are stored here searchFiles.add(context.getFilesDir()); // The initial installed apks are provided by `sourceDirs` in ApplicationInfo. // The jniLibs we want are in the splits not the baseDir. These // APKs are only searched as a fallback, as base libs generally do not need // to be fully path referenced. for (String path : context.getApplicationInfo().splitSourceDirs) { searchFiles.add(new File(path)); } while (!searchFiles.isEmpty()) { File file = searchFiles.remove(); if (file != null && file.isDirectory() && file.listFiles() != null) { for (File f : file.listFiles()) { searchFiles.add(f); } continue; } String name = file.getName(); // Special case for "split_config" since android base module non-master apks are // initially installed with the "split_config" prefix/name. if (name.endsWith(".apk") && (name.startsWith(componentName) || name.startsWith("split_config")) && name.contains(pathAbi)) { apkPaths.add(file.getAbsolutePath()); continue; } if (name.equals(aotSharedLibraryName)) { soPaths.add(file.getAbsolutePath()); } } List<String> searchPaths = new ArrayList<>(); // Add the bare filename as the first search path. In some devices, the so // file can be dlopen-ed with just the file name. searchPaths.add(aotSharedLibraryName); for (String path : apkPaths) { searchPaths.add(path + "!lib/" + abi + "/" + aotSharedLibraryName); } for (String path : soPaths) { searchPaths.add(path); } flutterJNI.loadDartDeferredLibrary( loadingUnitId, searchPaths.toArray(new String[searchPaths.size()])); } public boolean uninstallDeferredComponent(int loadingUnitId, @Nullable String componentName) { String resolvedComponentName = componentName != null ? componentName : loadingUnitIdToComponentNames.get(loadingUnitId); if (resolvedComponentName == null) { Log.e( TAG, "Deferred component name was null and could not be resolved from loading unit id."); return false; } List<String> modulesToUninstall = new ArrayList<>(); modulesToUninstall.add(resolvedComponentName); splitInstallManager.deferredUninstall(modulesToUninstall); if (nameToSessionId.get(resolvedComponentName) != null) { sessionIdToState.delete(nameToSessionId.get(resolvedComponentName)); } return true; } public void destroy() { splitInstallManager.unregisterListener(listener); channel = null; flutterJNI = null; } }
engine/shell/platform/android/io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManager.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManager.java", "repo_id": "engine", "token_count": 8404 }
354
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.plugins.contentprovider; import android.content.ContentProvider; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; /** * Control surface through which a {@link ContentProvider} attaches to a {@link * io.flutter.embedding.engine.FlutterEngine}. * * <p>A {@link ContentProvider} that contains a {@link io.flutter.embedding.engine.FlutterEngine} * should coordinate itself with the {@link io.flutter.embedding.engine.FlutterEngine}'s {@code * ContentProviderControlSurface}. */ public interface ContentProviderControlSurface { /** * Call this method from the {@link ContentProvider} that is running the {@link * io.flutter.embedding.engine.FlutterEngine} that is associated with this {@code * ContentProviderControlSurface}. * * <p>Once a {@link ContentProvider} is created, and its associated {@link * io.flutter.embedding.engine.FlutterEngine} is executing Dart code, the {@link ContentProvider} * should invoke this method. At that point the {@link io.flutter.embedding.engine.FlutterEngine} * is considered "attached" to the {@link ContentProvider} and all {@link ContentProviderAware} * plugins are given access to the {@link ContentProvider}. */ void attachToContentProvider( @NonNull ContentProvider contentProvider, @NonNull Lifecycle lifecycle); /** * Call this method from the {@link ContentProvider} that is attached to this {@code * ContentProviderControlSurfaces}'s {@link io.flutter.embedding.engine.FlutterEngine} when the * {@link ContentProvider} is about to be destroyed. * * <p>This method gives each {@link ContentProviderAware} plugin an opportunity to clean up its * references before the {@link ContentProvider is destroyed}. */ void detachFromContentProvider(); }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/contentprovider/ContentProviderControlSurface.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/contentprovider/ContentProviderControlSurface.java", "repo_id": "engine", "token_count": 572 }
355
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.systemchannels; import android.view.KeyEvent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.Log; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.JSONMessageCodec; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; /** * Event message channel for key events to/from the Flutter framework. * * <p>Sends key up/down events to the framework, and receives asynchronous messages from the * framework about whether or not the key was handled. */ public class KeyEventChannel { private static final String TAG = "KeyEventChannel"; /** A handler of incoming key handling messages. */ public interface EventResponseHandler { /** * Called whenever the framework responds that a given key event was handled or not handled by * the framework. * * @param isEventHandled whether the framework decides to handle the event. */ public void onFrameworkResponse(boolean isEventHandled); } /** * A constructor that creates a KeyEventChannel with the default message handler. * * @param binaryMessenger the binary messenger used to send messages on this channel. */ public KeyEventChannel(@NonNull BinaryMessenger binaryMessenger) { this.channel = new BasicMessageChannel<>(binaryMessenger, "flutter/keyevent", JSONMessageCodec.INSTANCE); } @NonNull public final BasicMessageChannel<Object> channel; public void sendFlutterKeyEvent( @NonNull FlutterKeyEvent keyEvent, boolean isKeyUp, @NonNull EventResponseHandler responseHandler) { channel.send(encodeKeyEvent(keyEvent, isKeyUp), createReplyHandler(responseHandler)); } private Map<String, Object> encodeKeyEvent(@NonNull FlutterKeyEvent keyEvent, boolean isKeyUp) { Map<String, Object> message = new HashMap<>(); message.put("type", isKeyUp ? "keyup" : "keydown"); message.put("keymap", "android"); message.put("flags", keyEvent.event.getFlags()); message.put("plainCodePoint", keyEvent.event.getUnicodeChar(0x0)); message.put("codePoint", keyEvent.event.getUnicodeChar()); message.put("keyCode", keyEvent.event.getKeyCode()); message.put("scanCode", keyEvent.event.getScanCode()); message.put("metaState", keyEvent.event.getMetaState()); if (keyEvent.complexCharacter != null) { message.put("character", keyEvent.complexCharacter.toString()); } message.put("source", keyEvent.event.getSource()); message.put("deviceId", keyEvent.event.getDeviceId()); message.put("repeatCount", keyEvent.event.getRepeatCount()); return message; } /** * Creates a reply handler for the given key event. * * @param responseHandler the completion handler to call when the framework responds. */ private static BasicMessageChannel.Reply<Object> createReplyHandler( @NonNull EventResponseHandler responseHandler) { return message -> { boolean isEventHandled = false; try { if (message != null) { final JSONObject annotatedEvent = (JSONObject) message; isEventHandled = annotatedEvent.getBoolean("handled"); } } catch (JSONException e) { Log.e(TAG, "Unable to unpack JSON message: " + e); } responseHandler.onFrameworkResponse(isEventHandled); }; } /** A key event as defined by Flutter. */ public static class FlutterKeyEvent { /** * The Android key event that this Flutter key event was created from. * * <p>This event is used to identify pending events when results are received from the * framework. */ public final KeyEvent event; /** * The character produced by this event, including any combining characters pressed before it. */ @Nullable public final Character complexCharacter; public FlutterKeyEvent(@NonNull KeyEvent androidKeyEvent) { this(androidKeyEvent, null); } public FlutterKeyEvent( @NonNull KeyEvent androidKeyEvent, @Nullable Character complexCharacter) { this.event = androidKeyEvent; this.complexCharacter = complexCharacter; } } }
engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/KeyEventChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/KeyEventChannel.java", "repo_id": "engine", "token_count": 1408 }
356
// Copyright 2013 The Flutter 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; } } }
engine/shell/platform/android/io/flutter/plugin/common/BinaryCodec.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/BinaryCodec.java", "repo_id": "engine", "token_count": 725 }
357
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 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; } }
engine/shell/platform/android/io/flutter/plugin/editing/FlutterTextUtils.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/editing/FlutterTextUtils.java", "repo_id": "engine", "token_count": 4739 }
358
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.platform; import java.util.HashMap; import java.util.Map; class PlatformViewRegistryImpl implements PlatformViewRegistry { PlatformViewRegistryImpl() { viewFactories = new HashMap<>(); } // Maps a platform view type id to its factory. private final Map<String, PlatformViewFactory> viewFactories; @Override public boolean registerViewFactory(String viewTypeId, PlatformViewFactory factory) { if (viewFactories.containsKey(viewTypeId)) return false; viewFactories.put(viewTypeId, factory); return true; } PlatformViewFactory getFactory(String viewTypeId) { return viewFactories.get(viewTypeId); } }
engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistryImpl.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewRegistryImpl.java", "repo_id": "engine", "token_count": 244 }
359
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.util; // TODO(dnfield): remove this if/when we can use appcompat to support it. // java.util.function.Predicate isn't available until API24 public interface Predicate<T> { public abstract boolean test(T t); }
engine/shell/platform/android/io/flutter/util/Predicate.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/util/Predicate.java", "repo_id": "engine", "token_count": 112 }
360
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_JNI_PLATFORM_VIEW_ANDROID_JNI_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_JNI_PLATFORM_VIEW_ANDROID_JNI_H_ #include <utility> #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "flutter/flow/embedded_views.h" #include "flutter/lib/ui/window/platform_message.h" #include "flutter/shell/platform/android/surface/android_native_window.h" #include "third_party/skia/include/core/SkMatrix.h" #if FML_OS_ANDROID #include "flutter/fml/platform/android/scoped_java_ref.h" #endif namespace flutter { #if FML_OS_ANDROID using JavaLocalRef = fml::jni::ScopedJavaLocalRef<jobject>; #else using JavaLocalRef = std::nullptr_t; #endif //------------------------------------------------------------------------------ /// Allows to call Java code running in the JVM from any thread. However, most /// methods can only be called from the platform thread as that is where the /// Java code runs. /// /// This interface must not depend on the Android toolchain directly, so it can /// be used in unit tests compiled with the host toolchain. /// class PlatformViewAndroidJNI { public: virtual ~PlatformViewAndroidJNI(); //---------------------------------------------------------------------------- /// @brief Sends a platform message. The message may be empty. /// virtual void FlutterViewHandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message, int responseId) = 0; //---------------------------------------------------------------------------- /// @brief Responds to a platform message. The data may be a `nullptr`. /// virtual void FlutterViewHandlePlatformMessageResponse( int responseId, std::unique_ptr<fml::Mapping> data) = 0; //---------------------------------------------------------------------------- /// @brief Sends semantics tree updates. /// /// @note Must be called from the platform thread. /// virtual void FlutterViewUpdateSemantics( std::vector<uint8_t> buffer, std::vector<std::string> strings, std::vector<std::vector<uint8_t>> string_attribute_args) = 0; //---------------------------------------------------------------------------- /// @brief Sends new custom accessibility events. /// /// @note Must be called from the platform thread. /// virtual void FlutterViewUpdateCustomAccessibilityActions( std::vector<uint8_t> actions_buffer, std::vector<std::string> strings) = 0; //---------------------------------------------------------------------------- /// @brief Indicates that FlutterView should start painting pixels. /// /// @note Must be called from the platform thread. /// virtual void FlutterViewOnFirstFrame() = 0; //---------------------------------------------------------------------------- /// @brief Indicates that a hot restart is about to happen. /// virtual void FlutterViewOnPreEngineRestart() = 0; //---------------------------------------------------------------------------- /// @brief Attach the SurfaceTexture to the OpenGL ES context that is /// current on the calling thread. /// virtual void SurfaceTextureAttachToGLContext(JavaLocalRef surface_texture, int textureId) = 0; //---------------------------------------------------------------------------- /// @brief Returns true if surface_texture should be updated. /// virtual bool SurfaceTextureShouldUpdate(JavaLocalRef surface_texture) = 0; //---------------------------------------------------------------------------- /// @brief Updates the texture image to the most recent frame from the /// image stream. /// virtual void SurfaceTextureUpdateTexImage(JavaLocalRef surface_texture) = 0; //---------------------------------------------------------------------------- /// @brief Gets the transform matrix from the SurfaceTexture. /// Then, it updates the `transform` matrix, so it fill the canvas /// and preserve the aspect ratio. /// virtual void SurfaceTextureGetTransformMatrix(JavaLocalRef surface_texture, SkMatrix& transform) = 0; //---------------------------------------------------------------------------- /// @brief Detaches a SurfaceTexture from the OpenGL ES context. /// virtual void SurfaceTextureDetachFromGLContext( JavaLocalRef surface_texture) = 0; //---------------------------------------------------------------------------- /// @brief Acquire the latest image available. /// virtual JavaLocalRef ImageProducerTextureEntryAcquireLatestImage( JavaLocalRef image_texture_entry) = 0; //---------------------------------------------------------------------------- /// @brief Grab the HardwareBuffer from image. /// virtual JavaLocalRef ImageGetHardwareBuffer(JavaLocalRef image) = 0; //---------------------------------------------------------------------------- /// @brief Call close on image. /// virtual void ImageClose(JavaLocalRef image) = 0; //---------------------------------------------------------------------------- /// @brief Call close on hardware_buffer. /// virtual void HardwareBufferClose(JavaLocalRef hardware_buffer) = 0; //---------------------------------------------------------------------------- /// @brief Positions and sizes a platform view if using hybrid /// composition. /// /// @note Must be called from the platform thread. /// virtual void FlutterViewOnDisplayPlatformView( int view_id, int x, int y, int width, int height, int viewWidth, int viewHeight, MutatorsStack mutators_stack) = 0; //---------------------------------------------------------------------------- /// @brief Positions and sizes an overlay surface in hybrid composition. /// /// @note Must be called from the platform thread. /// virtual void FlutterViewDisplayOverlaySurface(int surface_id, int x, int y, int width, int height) = 0; //---------------------------------------------------------------------------- /// @brief Initiates a frame if using hybrid composition. /// /// /// @note Must be called from the platform thread. /// virtual void FlutterViewBeginFrame() = 0; //---------------------------------------------------------------------------- /// @brief Indicates that the current frame ended. /// It's used to clean up state. /// /// @note Must be called from the platform thread. /// virtual void FlutterViewEndFrame() = 0; //------------------------------------------------------------------------------ /// The metadata returned from Java which is converted into an |OverlayLayer| /// by |SurfacePool|. /// struct OverlayMetadata { OverlayMetadata(int id, fml::RefPtr<AndroidNativeWindow> window) : id(id), window(std::move(window)){}; ~OverlayMetadata() = default; // A unique id to identify the overlay when it gets recycled. const int id; // Holds a reference to the native window. That is, an `ANativeWindow`, // which is the C counterpart of the `android.view.Surface` object in Java. const fml::RefPtr<AndroidNativeWindow> window; }; //---------------------------------------------------------------------------- /// @brief Instantiates an overlay surface in hybrid composition and /// provides the necessary metadata to operate the surface in C. /// /// @note Must be called from the platform thread. /// virtual std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata> FlutterViewCreateOverlaySurface() = 0; //---------------------------------------------------------------------------- /// @brief Destroys the overlay surfaces. /// /// @note Must be called from the platform thread. /// virtual void FlutterViewDestroyOverlaySurfaces() = 0; //---------------------------------------------------------------------------- /// @brief Computes the locale Android would select. /// virtual std::unique_ptr<std::vector<std::string>> FlutterViewComputePlatformResolvedLocale( std::vector<std::string> supported_locales_data) = 0; virtual double GetDisplayRefreshRate() = 0; virtual double GetDisplayWidth() = 0; virtual double GetDisplayHeight() = 0; virtual double GetDisplayDensity() = 0; virtual bool RequestDartDeferredLibrary(int loading_unit_id) = 0; virtual double FlutterViewGetScaledFontSize(double unscaled_font_size, int configuration_id) const = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_JNI_PLATFORM_VIEW_ANDROID_JNI_H_
engine/shell/platform/android/jni/platform_view_android_jni.h/0
{ "file_path": "engine/shell/platform/android/jni/platform_view_android_jni.h", "repo_id": "engine", "token_count": 2788 }
361
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/surface/android_native_window.h" namespace flutter { AndroidNativeWindow::AndroidNativeWindow(Handle window, bool is_fake_window) : window_(window), is_fake_window_(is_fake_window) {} AndroidNativeWindow::AndroidNativeWindow(Handle window) : AndroidNativeWindow(window, /*is_fake_window=*/false) {} AndroidNativeWindow::~AndroidNativeWindow() { if (window_ != nullptr) { #if FML_OS_ANDROID ANativeWindow_release(window_); window_ = nullptr; #endif // FML_OS_ANDROID } } bool AndroidNativeWindow::IsValid() const { return window_ != nullptr; } AndroidNativeWindow::Handle AndroidNativeWindow::handle() const { return window_; } SkISize AndroidNativeWindow::GetSize() const { #if FML_OS_ANDROID return window_ == nullptr ? SkISize::Make(0, 0) : SkISize::Make(ANativeWindow_getWidth(window_), ANativeWindow_getHeight(window_)); #else // FML_OS_ANDROID return SkISize::Make(0, 0); #endif // FML_OS_ANDROID } } // namespace flutter
engine/shell/platform/android/surface/android_native_window.cc/0
{ "file_path": "engine/shell/platform/android/surface/android_native_window.cc", "repo_id": "engine", "token_count": 458 }
362
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter; import static org.junit.Assert.assertTrue; import android.text.TextUtils; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; /** Basic smoke test verifying that Robolectric is loaded and mocking out Android APIs. */ @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class SmokeTest { @Test public void androidLibraryLoaded() { assertTrue(TextUtils.equals("xyzzy", "xyzzy")); } }
engine/shell/platform/android/test/io/flutter/SmokeTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/SmokeTest.java", "repo_id": "engine", "token_count": 220 }
363
package test.io.flutter.embedding.engine; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources; import android.os.LocaleList; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.FlutterInjector; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterEngine.EngineLifecycleListener; import io.flutter.embedding.engine.FlutterEngineGroup; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.PluginRegistry; import io.flutter.plugin.platform.PlatformViewsController; import io.flutter.plugins.GeneratedPluginRegistrant; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterEngineTest { private final Context ctx = ApplicationProvider.getApplicationContext(); private final Context mockContext = mock(Context.class); @Mock FlutterJNI flutterJNI; boolean jniAttached; @Before public void setUp() { MockitoAnnotations.openMocks(this); Resources mockResources = mock(Resources.class); Configuration mockConfiguration = mock(Configuration.class); doReturn(mockResources).when(mockContext).getResources(); doReturn(mockConfiguration).when(mockResources).getConfiguration(); doReturn(LocaleList.getEmptyLocaleList()).when(mockConfiguration).getLocales(); jniAttached = false; when(flutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { jniAttached = true; return null; } }) .when(flutterJNI) .attachToNative(); GeneratedPluginRegistrant.clearRegisteredEngines(); } @After public void tearDown() { GeneratedPluginRegistrant.clearRegisteredEngines(); // Make sure to not forget to remove the mock exception in the generated plugin registration // mock, or everything subsequent will break. GeneratedPluginRegistrant.pluginRegistrationException = null; } @Test public void itAutomaticallyRegistersPluginsByDefault() { assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); FlutterEngine flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, flutterJNI); List<FlutterEngine> registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); assertEquals(1, registeredEngines.size()); assertEquals(flutterEngine, registeredEngines.get(0)); } @Test public void itUpdatesDisplayMetricsOnConstructionWithActivityContext() { // Needs an activity. ApplicationContext won't work for this. ActivityController<Activity> activityController = Robolectric.buildActivity(Activity.class); FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); when(mockFlutterJNI.isAttached()).thenReturn(true); FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); FlutterEngine flutterEngine = new FlutterEngine(activityController.get(), mockFlutterLoader, mockFlutterJNI); verify(mockFlutterJNI, times(1)) .updateDisplayMetrics(eq(0), any(Float.class), any(Float.class), any(Float.class)); } @Test public void itSendLocalesOnEngineInit() { FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); when(mockFlutterJNI.isAttached()).thenReturn(true); assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); FlutterEngine flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJNI); verify(mockFlutterJNI, times(1)) .dispatchPlatformMessage(eq("flutter/localization"), any(), anyInt(), anyInt()); } // Helps show the root cause of MissingPluginException type errors like // https://github.com/flutter/flutter/issues/78625. @Test public void itCatchesAndDisplaysRegistrationExceptions() { assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); GeneratedPluginRegistrant.pluginRegistrationException = new RuntimeException("I'm a bug in the plugin"); FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); FlutterEngine flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, flutterJNI); List<FlutterEngine> registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); // When it crashes, it doesn't end up registering anything. assertEquals(0, registeredEngines.size()); // Check the logs actually says registration failed, so a subsequent MissingPluginException // isn't mysterious. assertTrue( ShadowLog.getLogsForTag("GeneratedPluginsRegister") .get(0) .msg .contains("Tried to automatically register plugins")); assertEquals( GeneratedPluginRegistrant.pluginRegistrationException, ShadowLog.getLogsForTag("GeneratedPluginsRegister").get(1).throwable.getCause()); GeneratedPluginRegistrant.pluginRegistrationException = null; } @Test public void itDoesNotAutomaticallyRegistersPluginsWhenFlutterLoaderDisablesIt() { assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(false); new FlutterEngine(ctx, mockFlutterLoader, flutterJNI); List<FlutterEngine> registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); assertTrue(registeredEngines.isEmpty()); } @Test public void itDoesNotAutomaticallyRegistersPluginsWhenFlutterEngineDisablesIt() { assertTrue(GeneratedPluginRegistrant.getRegisteredEngines().isEmpty()); FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(true); new FlutterEngine( ctx, mockFlutterLoader, flutterJNI, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); List<FlutterEngine> registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); assertTrue(registeredEngines.isEmpty()); } @Test public void itNotifiesPlatformViewsControllerWhenDevHotRestart() { // Setup test. FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); when(mockFlutterJNI.isAttached()).thenReturn(true); PlatformViewsController platformViewsController = mock(PlatformViewsController.class); ArgumentCaptor<FlutterEngine.EngineLifecycleListener> engineLifecycleListenerArgumentCaptor = ArgumentCaptor.forClass(FlutterEngine.EngineLifecycleListener.class); // Execute behavior under test. new FlutterEngine( ctx, mock(FlutterLoader.class), mockFlutterJNI, platformViewsController, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); // Obtain the EngineLifecycleListener within FlutterEngine that was given to FlutterJNI. verify(mockFlutterJNI) .addEngineLifecycleListener(engineLifecycleListenerArgumentCaptor.capture()); FlutterEngine.EngineLifecycleListener engineLifecycleListener = engineLifecycleListenerArgumentCaptor.getValue(); assertNotNull(engineLifecycleListener); // Simulate a pre-engine restart, AKA hot restart. engineLifecycleListener.onPreEngineRestart(); // Verify that FlutterEngine notified PlatformViewsController of the pre-engine restart, // AKA hot restart. verify(platformViewsController, times(1)).onPreEngineRestart(); } @Test public void itNotifiesPlatformViewsControllerAboutJNILifecycle() { PlatformViewsController platformViewsController = mock(PlatformViewsController.class); // Execute behavior under test. FlutterEngine engine = new FlutterEngine( ctx, mock(FlutterLoader.class), flutterJNI, platformViewsController, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); verify(platformViewsController, times(1)).onAttachedToJNI(); engine.destroy(); verify(platformViewsController, times(1)).onDetachedFromJNI(); } @Test public void itUsesApplicationContext() throws NameNotFoundException { Context packageContext = mock(Context.class); when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); new FlutterEngine( mockContext, mock(FlutterLoader.class), flutterJNI, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); verify(mockContext, atLeast(1)).getApplicationContext(); } @Test public void itUsesPackageContextForAssetManager() throws NameNotFoundException { Context packageContext = mock(Context.class); when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); new FlutterEngine( mockContext, mock(FlutterLoader.class), flutterJNI, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); verify(packageContext, atLeast(1)).getAssets(); verify(mockContext, times(0)).getAssets(); } @Test public void itCanUseFlutterLoaderInjectionViaFlutterInjector() throws NameNotFoundException { FlutterInjector.reset(); FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); FlutterInjector.setInstance( new FlutterInjector.Builder().setFlutterLoader(mockFlutterLoader).build()); Context packageContext = mock(Context.class); when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); new FlutterEngine(mockContext, null, flutterJNI); verify(mockFlutterLoader, times(1)).startInitialization(any()); verify(mockFlutterLoader, times(1)).ensureInitializationComplete(any(), any()); FlutterInjector.reset(); } @Test public void itNotifiesListenersForDestruction() throws NameNotFoundException { Context packageContext = mock(Context.class); when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); FlutterEngine engineUnderTest = new FlutterEngine( mockContext, mock(FlutterLoader.class), flutterJNI, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); EngineLifecycleListener listener = mock(EngineLifecycleListener.class); engineUnderTest.addEngineLifecycleListener(listener); engineUnderTest.destroy(); verify(listener, times(1)).onEngineWillDestroy(); } @Test public void itDoesNotAttachAgainWhenBuiltWithAnAttachedJNI() throws NameNotFoundException { Context packageContext = mock(Context.class); when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); when(flutterJNI.isAttached()).thenReturn(true); FlutterEngine engineUnderTest = new FlutterEngine( mockContext, mock(FlutterLoader.class), flutterJNI, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); verify(flutterJNI, never()).attachToNative(); } @Test public void itComesWithARunningDartExecutorIfJNIIsAlreadyAttached() throws NameNotFoundException { Context packageContext = mock(Context.class); when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); when(flutterJNI.isAttached()).thenReturn(true); FlutterEngine engineUnderTest = new FlutterEngine( mockContext, mock(FlutterLoader.class), flutterJNI, /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false); assertTrue(engineUnderTest.getDartExecutor().isExecutingDart()); } @Test public void passesEngineGroupToPlugins() throws NameNotFoundException { Context packageContext = mock(Context.class); when(mockContext.createPackageContext(any(), anyInt())).thenReturn(packageContext); when(flutterJNI.isAttached()).thenReturn(true); FlutterEngineGroup mockGroup = mock(FlutterEngineGroup.class); FlutterEngine engineUnderTest = new FlutterEngine( mockContext, mock(FlutterLoader.class), flutterJNI, new PlatformViewsController(), /*dartVmArgs=*/ new String[] {}, /*automaticallyRegisterPlugins=*/ false, /*waitForRestorationData=*/ false, mockGroup); PluginRegistry registry = engineUnderTest.getPlugins(); FlutterPlugin mockPlugin = mock(FlutterPlugin.class); ArgumentCaptor<FlutterPlugin.FlutterPluginBinding> pluginBindingCaptor = ArgumentCaptor.forClass(FlutterPlugin.FlutterPluginBinding.class); registry.add(mockPlugin); verify(mockPlugin).onAttachedToEngine(pluginBindingCaptor.capture()); assertNotNull(pluginBindingCaptor.getValue()); assertEquals(mockGroup, pluginBindingCaptor.getValue().getEngineGroup()); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/FlutterEngineTest.java", "repo_id": "engine", "token_count": 5117 }
364
package io.flutter.embedding.engine.systemchannels; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import android.content.res.AssetManager; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; class TestDeferredComponentManager implements DeferredComponentManager { DeferredComponentChannel channel; String componentName; public void setJNI(FlutterJNI flutterJNI) {} public void setDeferredComponentChannel(DeferredComponentChannel channel) { this.channel = channel; } public void installDeferredComponent(int loadingUnitId, String componentName) { this.componentName = componentName; } public void completeInstall() { channel.completeInstallSuccess(componentName); } public String getDeferredComponentInstallState(int loadingUnitId, String componentName) { return "installed"; } public void loadAssets(int loadingUnitId, String componentName) {} public void loadDartLibrary(int loadingUnitId, String componentName) {} public boolean uninstallDeferredComponent(int loadingUnitId, String componentName) { return true; } public void destroy() {} } @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class DeferredComponentChannelTest { @Test public void deferredComponentChannel_installCompletesResults() { MethodChannel rawChannel = mock(MethodChannel.class); FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); TestDeferredComponentManager testDeferredComponentManager = new TestDeferredComponentManager(); DeferredComponentChannel fakeDeferredComponentChannel = new DeferredComponentChannel(dartExecutor); fakeDeferredComponentChannel.setDeferredComponentManager(testDeferredComponentManager); testDeferredComponentManager.setDeferredComponentChannel(fakeDeferredComponentChannel); Map<String, Object> args = new HashMap<>(); args.put("loadingUnitId", -1); args.put("componentName", "hello"); MethodCall methodCall = new MethodCall("installDeferredComponent", args); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult); testDeferredComponentManager.completeInstall(); verify(mockResult).success(null); } @Test public void deferredComponentChannel_installCompletesMultipleResults() { MethodChannel rawChannel = mock(MethodChannel.class); FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); TestDeferredComponentManager testDeferredComponentManager = new TestDeferredComponentManager(); DeferredComponentChannel fakeDeferredComponentChannel = new DeferredComponentChannel(dartExecutor); fakeDeferredComponentChannel.setDeferredComponentManager(testDeferredComponentManager); testDeferredComponentManager.setDeferredComponentChannel(fakeDeferredComponentChannel); Map<String, Object> args = new HashMap<>(); args.put("loadingUnitId", -1); args.put("componentName", "hello"); MethodCall methodCall = new MethodCall("installDeferredComponent", args); MethodChannel.Result mockResult1 = mock(MethodChannel.Result.class); MethodChannel.Result mockResult2 = mock(MethodChannel.Result.class); fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult1); fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult2); testDeferredComponentManager.completeInstall(); verify(mockResult1).success(null); verify(mockResult2).success(null); } @Test public void deferredComponentChannel_getInstallState() { MethodChannel rawChannel = mock(MethodChannel.class); FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); DartExecutor dartExecutor = new DartExecutor(mockFlutterJNI, mock(AssetManager.class)); TestDeferredComponentManager testDeferredComponentManager = new TestDeferredComponentManager(); DeferredComponentChannel fakeDeferredComponentChannel = new DeferredComponentChannel(dartExecutor); fakeDeferredComponentChannel.setDeferredComponentManager(testDeferredComponentManager); testDeferredComponentManager.setDeferredComponentChannel(fakeDeferredComponentChannel); Map<String, Object> args = new HashMap<>(); args.put("loadingUnitId", -1); args.put("componentName", "hello"); MethodCall methodCall = new MethodCall("getDeferredComponentInstallState", args); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); fakeDeferredComponentChannel.parsingMethodHandler.onMethodCall(methodCall, mockResult); testDeferredComponentManager.completeInstall(); verify(mockResult).success("installed"); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/DeferredComponentChannelTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/DeferredComponentChannelTest.java", "repo_id": "engine", "token_count": 1553 }
365
package io.flutter.plugin.editing; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; import android.view.textservice.SentenceSuggestionsInfo; import android.view.textservice.SpellCheckerSession; import android.view.textservice.SuggestionsInfo; import android.view.textservice.TextInfo; import android.view.textservice.TextServicesManager; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.systemchannels.SpellCheckChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.StandardMethodCodec; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @RunWith(AndroidJUnit4.class) public class SpellCheckPluginTest { private static void sendToBinaryMessageHandler( BinaryMessenger.BinaryMessageHandler binaryMessageHandler, String method, Object args) { MethodCall methodCall = new MethodCall(method, args); ByteBuffer encodedMethodCall = StandardMethodCodec.INSTANCE.encodeMethodCall(methodCall); binaryMessageHandler.onMessage( (ByteBuffer) encodedMethodCall.flip(), mock(BinaryMessenger.BinaryReply.class)); } @SuppressWarnings("deprecation") // setMessageHandler is deprecated. @Test public void respondsToSpellCheckChannelMessage() { ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> binaryMessageHandlerCaptor = ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); DartExecutor mockBinaryMessenger = mock(DartExecutor.class); SpellCheckChannel.SpellCheckMethodHandler mockHandler = mock(SpellCheckChannel.SpellCheckMethodHandler.class); SpellCheckChannel spellCheckChannel = new SpellCheckChannel(mockBinaryMessenger); spellCheckChannel.setSpellCheckMethodHandler(mockHandler); verify(mockBinaryMessenger, times(1)) .setMessageHandler(any(String.class), binaryMessageHandlerCaptor.capture()); BinaryMessenger.BinaryMessageHandler binaryMessageHandler = binaryMessageHandlerCaptor.getValue(); sendToBinaryMessageHandler( binaryMessageHandler, "SpellCheck.initiateSpellCheck", Arrays.asList("en-US", "Hello, wrold!")); verify(mockHandler) .initiateSpellCheck(eq("en-US"), eq("Hello, wrold!"), any(MethodChannel.Result.class)); } @Test public void initiateSpellCheckPerformsSpellCheckWhenNoResultPending() { SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); when(fakeTextServicesManager.newSpellCheckerSession( null, new Locale("en", "US"), spellCheckPlugin, true)) .thenReturn(fakeSpellCheckerSession); spellCheckPlugin.initiateSpellCheck("en-US", "Hello, wrold!", mockResult); verify(spellCheckPlugin).performSpellCheck("en-US", "Hello, wrold!"); } @Test public void initiateSpellCheckThrowsErrorWhenResultPending() { SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); MethodChannel.Result mockPendingResult = mock(MethodChannel.Result.class); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); spellCheckPlugin.pendingResult = mockPendingResult; spellCheckPlugin.initiateSpellCheck("en-US", "Hello, wrold!", mockResult); verify(mockResult).error("error", "Previous spell check request still pending.", null); verify(spellCheckPlugin, never()).performSpellCheck("en-US", "Hello, wrold!"); } @Test public void destroyClosesSpellCheckerSessionAndClearsSpellCheckMethodHandler() { Context fakeContext = mock(Context.class); SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); when(fakeContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE)) .thenReturn(fakeTextServicesManager); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); when(fakeTextServicesManager.newSpellCheckerSession( null, new Locale("en", "US"), spellCheckPlugin, true)) .thenReturn(fakeSpellCheckerSession); spellCheckPlugin.performSpellCheck("en-US", "Hello, wrold!"); spellCheckPlugin.destroy(); verify(fakeSpellCheckChannel).setSpellCheckMethodHandler(isNull()); verify(fakeSpellCheckerSession).close(); } @Test public void performSpellCheckSendsRequestToAndroidSpellCheckService() { Context fakeContext = mock(Context.class); SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); when(fakeContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE)) .thenReturn(fakeTextServicesManager); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); Locale english_US = new Locale("en", "US"); when(fakeTextServicesManager.newSpellCheckerSession(null, english_US, spellCheckPlugin, true)) .thenReturn(fakeSpellCheckerSession); int maxSuggestions = 5; ArgumentCaptor<TextInfo[]> textInfosCaptor = ArgumentCaptor.forClass(TextInfo[].class); ArgumentCaptor<Integer> maxSuggestionsCaptor = ArgumentCaptor.forClass(Integer.class); spellCheckPlugin.performSpellCheck("en-US", "Hello, wrold!"); verify(fakeSpellCheckerSession) .getSentenceSuggestions(textInfosCaptor.capture(), maxSuggestionsCaptor.capture()); assertEquals("Hello, wrold!", textInfosCaptor.getValue()[0].getText()); assertEquals(Integer.valueOf(maxSuggestions), maxSuggestionsCaptor.getValue()); } @Test public void performSpellCheckCreatesNewSpellCheckerSession() { Context fakeContext = mock(Context.class); SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); when(fakeContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE)) .thenReturn(fakeTextServicesManager); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); SpellCheckerSession fakeSpellCheckerSession = mock(SpellCheckerSession.class); Locale english_US = new Locale("en", "US"); when(fakeTextServicesManager.newSpellCheckerSession(null, english_US, spellCheckPlugin, true)) .thenReturn(fakeSpellCheckerSession); spellCheckPlugin.performSpellCheck("en-US", "Hello, worl!"); spellCheckPlugin.performSpellCheck("en-US", "Hello, world!"); verify(fakeTextServicesManager, times(1)) .newSpellCheckerSession(null, english_US, spellCheckPlugin, true); } @Test public void onGetSentenceSuggestionsResultsWithSuccessAndNoResultsProperly() { TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); spellCheckPlugin.pendingResult = mockResult; spellCheckPlugin.onGetSentenceSuggestions(new SentenceSuggestionsInfo[] {}); verify(mockResult).success(new ArrayList<HashMap<String, Object>>()); } @Test public void onGetSentenceSuggestionsResultsWithSuccessAndResultsProperly() { TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); spellCheckPlugin.pendingResult = mockResult; spellCheckPlugin.onGetSentenceSuggestions( new SentenceSuggestionsInfo[] { new SentenceSuggestionsInfo( (new SuggestionsInfo[] { new SuggestionsInfo( SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO, new String[] {"world", "word", "old"}) }), new int[] {7}, new int[] {5}) }); ArrayList<HashMap<String, Object>> expectedResults = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put(SpellCheckPlugin.START_INDEX_KEY, 7); expectedResult.put(SpellCheckPlugin.END_INDEX_KEY, 12); expectedResult.put( SpellCheckPlugin.SUGGESTIONS_KEY, new ArrayList<String>(Arrays.asList("world", "word", "old"))); expectedResults.add(expectedResult); verify(mockResult).success(expectedResults); } @Test public void onGetSentenceSuggestionsResultsWithSuccessAndNoResultsWhenSuggestionsAreInvalid() { TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); spellCheckPlugin.pendingResult = mockResult; spellCheckPlugin.onGetSentenceSuggestions( new SentenceSuggestionsInfo[] { new SentenceSuggestionsInfo( (new SuggestionsInfo[] { new SuggestionsInfo( SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO, // This is the suggestion that may be provided by the Samsung spell checker: new String[] {""}) }), new int[] {7}, new int[] {5}) }); verify(mockResult).success(new ArrayList<HashMap<String, Object>>()); } @Test public void onGetSentenceSuggestionsResultsWithSuccessAndNoResultsWhenSuggestionsAreInvalid2() { TextServicesManager fakeTextServicesManager = mock(TextServicesManager.class); SpellCheckChannel fakeSpellCheckChannel = mock(SpellCheckChannel.class); SpellCheckPlugin spellCheckPlugin = spy(new SpellCheckPlugin(fakeTextServicesManager, fakeSpellCheckChannel)); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); spellCheckPlugin.pendingResult = mockResult; spellCheckPlugin.onGetSentenceSuggestions( new SentenceSuggestionsInfo[] { // This "suggestion" may be provided by the Samsung spell checker: null }); verify(mockResult).success(new ArrayList<HashMap<String, Object>>()); } }
engine/shell/platform/android/test/io/flutter/plugin/editing/SpellCheckPluginTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/editing/SpellCheckPluginTest.java", "repo_id": "engine", "token_count": 3975 }
366
package io.flutter.util; import android.view.KeyEvent; // In the test environment, keyEvent.getUnicodeChar throws an exception. This // class works around the exception by hardcoding the returned value. public class FakeKeyEvent extends KeyEvent { public FakeKeyEvent(int action, int keyCode) { super(action, keyCode); } public FakeKeyEvent(int action, int keyCode, char character) { super(action, keyCode); this.character = character; } public FakeKeyEvent( int action, int scancode, int code, int repeat, char character, int metaState) { super(0, 0, action, code, repeat, metaState, 0, scancode); this.character = character; } private char character = 0; public final int getUnicodeChar() { if (getKeyCode() == KeyEvent.KEYCODE_BACK) { return 0; } return character; } }
engine/shell/platform/android/test/io/flutter/util/FakeKeyEvent.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/util/FakeKeyEvent.java", "repo_id": "engine", "token_count": 276 }
367
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "accessibility_bridge.h" #include <functional> #include <utility> #include "flutter/third_party/accessibility/ax/ax_tree_manager_map.h" #include "flutter/third_party/accessibility/ax/ax_tree_update.h" #include "flutter/third_party/accessibility/base/logging.h" namespace flutter { // namespace constexpr int kHasScrollingAction = FlutterSemanticsAction::kFlutterSemanticsActionScrollLeft | FlutterSemanticsAction::kFlutterSemanticsActionScrollRight | FlutterSemanticsAction::kFlutterSemanticsActionScrollUp | FlutterSemanticsAction::kFlutterSemanticsActionScrollDown; // AccessibilityBridge AccessibilityBridge::AccessibilityBridge() : tree_(std::make_unique<ui::AXTree>()) { event_generator_.SetTree(tree_.get()); tree_->AddObserver(static_cast<ui::AXTreeObserver*>(this)); ui::AXTreeData data = tree_->data(); data.tree_id = ui::AXTreeID::CreateNewAXTreeID(); tree_->UpdateData(data); ui::AXTreeManagerMap::GetInstance().AddTreeManager(tree_->GetAXTreeID(), this); } AccessibilityBridge::~AccessibilityBridge() { event_generator_.ReleaseTree(); tree_->RemoveObserver(static_cast<ui::AXTreeObserver*>(this)); } void AccessibilityBridge::AddFlutterSemanticsNodeUpdate( const FlutterSemanticsNode2& node) { pending_semantics_node_updates_[node.id] = FromFlutterSemanticsNode(node); } void AccessibilityBridge::AddFlutterSemanticsCustomActionUpdate( const FlutterSemanticsCustomAction2& action) { pending_semantics_custom_action_updates_[action.id] = FromFlutterSemanticsCustomAction(action); } void AccessibilityBridge::CommitUpdates() { // AXTree cannot move a node in a single update. // This must be split across two updates: // // * Update 1: remove nodes from their old parents. // * Update 2: re-add nodes (including their children) to their new parents. // // First, start by removing nodes if necessary. std::optional<ui::AXTreeUpdate> remove_reparented = CreateRemoveReparentedNodesUpdate(); if (remove_reparented.has_value()) { tree_->Unserialize(remove_reparented.value()); std::string error = tree_->error(); if (!error.empty()) { FML_LOG(ERROR) << "Failed to update ui::AXTree, error: " << error; assert(false); return; } } // Second, apply the pending node updates. This also moves reparented nodes to // their new parents if needed. ui::AXTreeUpdate update{.tree_data = tree_->data()}; // Figure out update order, ui::AXTree only accepts update in tree order, // where parent node must come before the child node in // ui::AXTreeUpdate.nodes. We start with picking a random node and turn the // entire subtree into a list. We pick another node from the remaining update, // and keep doing so until the update map is empty. We then concatenate the // lists in the reversed order, this guarantees parent updates always come // before child updates. If the root is in the update, it is guaranteed to // be the first node of the last list. std::vector<std::vector<SemanticsNode>> results; while (!pending_semantics_node_updates_.empty()) { auto begin = pending_semantics_node_updates_.begin(); SemanticsNode target = begin->second; std::vector<SemanticsNode> sub_tree_list; GetSubTreeList(target, sub_tree_list); results.push_back(sub_tree_list); pending_semantics_node_updates_.erase(begin); } for (size_t i = results.size(); i > 0; i--) { for (const SemanticsNode& node : results[i - 1]) { ConvertFlutterUpdate(node, update); } } // The first update must set the tree's root, which is guaranteed to be the // last list's first node. A tree's root node never changes, though it can be // modified. if (!results.empty() && GetRootAsAXNode()->id() == ui::AXNode::kInvalidAXID) { FML_DCHECK(!results.back().empty()); update.root_id = results.back().front().id; } tree_->Unserialize(update); pending_semantics_node_updates_.clear(); pending_semantics_custom_action_updates_.clear(); std::string error = tree_->error(); if (!error.empty()) { FML_LOG(ERROR) << "Failed to update ui::AXTree, error: " << error; return; } // Handles accessibility events as the result of the semantics update. for (const auto& targeted_event : event_generator_) { auto event_target = GetFlutterPlatformNodeDelegateFromID(targeted_event.node->id()); if (event_target.expired()) { continue; } OnAccessibilityEvent(targeted_event); } event_generator_.ClearEvents(); } std::weak_ptr<FlutterPlatformNodeDelegate> AccessibilityBridge::GetFlutterPlatformNodeDelegateFromID( AccessibilityNodeId id) const { const auto iter = id_wrapper_map_.find(id); if (iter != id_wrapper_map_.end()) { return iter->second; } return std::weak_ptr<FlutterPlatformNodeDelegate>(); } const ui::AXTreeData& AccessibilityBridge::GetAXTreeData() const { return tree_->data(); } const std::vector<ui::AXEventGenerator::TargetedEvent> AccessibilityBridge::GetPendingEvents() const { std::vector<ui::AXEventGenerator::TargetedEvent> result( event_generator_.begin(), event_generator_.end()); return result; } void AccessibilityBridge::OnNodeWillBeDeleted(ui::AXTree* tree, ui::AXNode* node) {} void AccessibilityBridge::OnSubtreeWillBeDeleted(ui::AXTree* tree, ui::AXNode* node) {} void AccessibilityBridge::OnNodeReparented(ui::AXTree* tree, ui::AXNode* node) { } void AccessibilityBridge::OnRoleChanged(ui::AXTree* tree, ui::AXNode* node, ax::mojom::Role old_role, ax::mojom::Role new_role) {} void AccessibilityBridge::OnNodeCreated(ui::AXTree* tree, ui::AXNode* node) { BASE_DCHECK(node); id_wrapper_map_[node->id()] = CreateFlutterPlatformNodeDelegate(); id_wrapper_map_[node->id()]->Init( std::static_pointer_cast<FlutterPlatformNodeDelegate::OwnerBridge>( shared_from_this()), node); } void AccessibilityBridge::OnNodeDeleted(ui::AXTree* tree, AccessibilityNodeId node_id) { BASE_DCHECK(node_id != ui::AXNode::kInvalidAXID); if (id_wrapper_map_.find(node_id) != id_wrapper_map_.end()) { id_wrapper_map_.erase(node_id); } } void AccessibilityBridge::OnAtomicUpdateFinished( ui::AXTree* tree, bool root_changed, const std::vector<ui::AXTreeObserver::Change>& changes) { // The Flutter semantics update does not include child->parent relationship // We have to update the relative bound offset container id here in order // to calculate the screen bound correctly. for (const auto& change : changes) { ui::AXNode* node = change.node; const ui::AXNodeData& data = node->data(); AccessibilityNodeId offset_container_id = -1; if (node->parent()) { offset_container_id = node->parent()->id(); } node->SetLocation(offset_container_id, data.relative_bounds.bounds, data.relative_bounds.transform.get()); } } std::optional<ui::AXTreeUpdate> AccessibilityBridge::CreateRemoveReparentedNodesUpdate() { std::unordered_map<int32_t, ui::AXNodeData> updates; for (const auto& node_update : pending_semantics_node_updates_) { for (int32_t child_id : node_update.second.children_in_traversal_order) { // Skip nodes that don't exist or have a parent in the current tree. ui::AXNode* child = tree_->GetFromId(child_id); if (!child) { continue; } // Flutter's root node should never be reparented. assert(child->parent()); // Skip nodes whose parents are unchanged. if (child->parent()->id() == node_update.second.id) { continue; } // This pending update moves the current child node. // That new child must have a corresponding pending update. assert(pending_semantics_node_updates_.find(child_id) != pending_semantics_node_updates_.end()); // Create an update to remove the child from its previous parent. int32_t parent_id = child->parent()->id(); if (updates.find(parent_id) == updates.end()) { updates[parent_id] = tree_->GetFromId(parent_id)->data(); } ui::AXNodeData* parent = &updates[parent_id]; auto iter = std::find(parent->child_ids.begin(), parent->child_ids.end(), child_id); assert(iter != parent->child_ids.end()); parent->child_ids.erase(iter); } } if (updates.empty()) { return std::nullopt; } ui::AXTreeUpdate update{ .tree_data = tree_->data(), .nodes = std::vector<ui::AXNodeData>(), }; for (std::pair<int32_t, ui::AXNodeData> data : updates) { update.nodes.push_back(std::move(data.second)); } return update; } // Private method. void AccessibilityBridge::GetSubTreeList(const SemanticsNode& target, std::vector<SemanticsNode>& result) { result.push_back(target); for (int32_t child : target.children_in_traversal_order) { auto iter = pending_semantics_node_updates_.find(child); if (iter != pending_semantics_node_updates_.end()) { SemanticsNode node = iter->second; GetSubTreeList(node, result); pending_semantics_node_updates_.erase(iter); } } } void AccessibilityBridge::ConvertFlutterUpdate(const SemanticsNode& node, ui::AXTreeUpdate& tree_update) { ui::AXNodeData node_data; node_data.id = node.id; SetRoleFromFlutterUpdate(node_data, node); SetStateFromFlutterUpdate(node_data, node); SetActionsFromFlutterUpdate(node_data, node); SetBooleanAttributesFromFlutterUpdate(node_data, node); SetIntAttributesFromFlutterUpdate(node_data, node); SetIntListAttributesFromFlutterUpdate(node_data, node); SetStringListAttributesFromFlutterUpdate(node_data, node); SetNameFromFlutterUpdate(node_data, node); SetValueFromFlutterUpdate(node_data, node); SetTooltipFromFlutterUpdate(node_data, node); node_data.relative_bounds.bounds.SetRect(node.rect.left, node.rect.top, node.rect.right - node.rect.left, node.rect.bottom - node.rect.top); node_data.relative_bounds.transform = std::make_unique<gfx::Transform>( node.transform.scaleX, node.transform.skewX, node.transform.transX, 0, node.transform.skewY, node.transform.scaleY, node.transform.transY, 0, node.transform.pers0, node.transform.pers1, node.transform.pers2, 0, 0, 0, 0, 0); for (auto child : node.children_in_traversal_order) { node_data.child_ids.push_back(child); } SetTreeData(node, tree_update); tree_update.nodes.push_back(node_data); } void AccessibilityBridge::SetRoleFromFlutterUpdate(ui::AXNodeData& node_data, const SemanticsNode& node) { FlutterSemanticsFlag flags = node.flags; if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsButton) { node_data.role = ax::mojom::Role::kButton; return; } if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && !(flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly)) { node_data.role = ax::mojom::Role::kTextField; return; } if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsHeader) { node_data.role = ax::mojom::Role::kHeader; return; } if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsImage) { node_data.role = ax::mojom::Role::kImage; return; } if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsLink) { node_data.role = ax::mojom::Role::kLink; return; } if (flags & kFlutterSemanticsFlagIsInMutuallyExclusiveGroup && flags & kFlutterSemanticsFlagHasCheckedState) { node_data.role = ax::mojom::Role::kRadioButton; return; } if (flags & kFlutterSemanticsFlagHasCheckedState) { node_data.role = ax::mojom::Role::kCheckBox; return; } if (flags & kFlutterSemanticsFlagHasToggledState) { node_data.role = ax::mojom::Role::kSwitch; return; } if (flags & kFlutterSemanticsFlagIsSlider) { node_data.role = ax::mojom::Role::kSlider; return; } // If the state cannot be derived from the flutter flags, we fallback to group // or static text. if (node.children_in_traversal_order.empty()) { node_data.role = ax::mojom::Role::kStaticText; } else { node_data.role = ax::mojom::Role::kGroup; } } void AccessibilityBridge::SetStateFromFlutterUpdate(ui::AXNodeData& node_data, const SemanticsNode& node) { FlutterSemanticsFlag flags = node.flags; FlutterSemanticsAction actions = node.actions; if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagHasExpandedState && flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsExpanded) { node_data.AddState(ax::mojom::State::kExpanded); } else if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagHasExpandedState) { node_data.AddState(ax::mojom::State::kCollapsed); } if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly) == 0) { node_data.AddState(ax::mojom::State::kEditable); } if (node_data.role == ax::mojom::Role::kStaticText && (actions & kHasScrollingAction) == 0 && node.value.empty() && node.label.empty() && node.hint.empty()) { node_data.AddState(ax::mojom::State::kIgnored); } else { // kFlutterSemanticsFlagIsFocusable means a keyboard focusable, it is // different from semantics focusable. // TODO(chunhtai): figure out whether something is not semantics focusable. node_data.AddState(ax::mojom::State::kFocusable); } } void AccessibilityBridge::SetActionsFromFlutterUpdate( ui::AXNodeData& node_data, const SemanticsNode& node) { FlutterSemanticsAction actions = node.actions; if (actions & FlutterSemanticsAction::kFlutterSemanticsActionTap) { node_data.AddAction(ax::mojom::Action::kDoDefault); } if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollLeft) { node_data.AddAction(ax::mojom::Action::kScrollLeft); } if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollRight) { node_data.AddAction(ax::mojom::Action::kScrollRight); } if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollUp) { node_data.AddAction(ax::mojom::Action::kScrollUp); } if (actions & FlutterSemanticsAction::kFlutterSemanticsActionScrollDown) { node_data.AddAction(ax::mojom::Action::kScrollDown); } if (actions & FlutterSemanticsAction::kFlutterSemanticsActionIncrease) { node_data.AddAction(ax::mojom::Action::kIncrement); } if (actions & FlutterSemanticsAction::kFlutterSemanticsActionDecrease) { node_data.AddAction(ax::mojom::Action::kDecrement); } // Every node has show on screen action. node_data.AddAction(ax::mojom::Action::kScrollToMakeVisible); if (actions & FlutterSemanticsAction::kFlutterSemanticsActionSetSelection) { node_data.AddAction(ax::mojom::Action::kSetSelection); } if (actions & FlutterSemanticsAction:: kFlutterSemanticsActionDidGainAccessibilityFocus) { node_data.AddAction(ax::mojom::Action::kSetAccessibilityFocus); } if (actions & FlutterSemanticsAction:: kFlutterSemanticsActionDidLoseAccessibilityFocus) { node_data.AddAction(ax::mojom::Action::kClearAccessibilityFocus); } if (actions & FlutterSemanticsAction::kFlutterSemanticsActionCustomAction) { node_data.AddAction(ax::mojom::Action::kCustomAction); } } void AccessibilityBridge::SetBooleanAttributesFromFlutterUpdate( ui::AXNodeData& node_data, const SemanticsNode& node) { FlutterSemanticsAction actions = node.actions; FlutterSemanticsFlag flags = node.flags; node_data.AddBoolAttribute(ax::mojom::BoolAttribute::kScrollable, actions & kHasScrollingAction); node_data.AddBoolAttribute( ax::mojom::BoolAttribute::kClickable, actions & FlutterSemanticsAction::kFlutterSemanticsActionTap); // TODO(chunhtai): figure out if there is a node that does not clip overflow. node_data.AddBoolAttribute(ax::mojom::BoolAttribute::kClipsChildren, !node.children_in_traversal_order.empty()); node_data.AddBoolAttribute( ax::mojom::BoolAttribute::kSelected, flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsSelected); node_data.AddBoolAttribute( ax::mojom::BoolAttribute::kEditableRoot, flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly) == 0); // Mark nodes as line breaking so that screen readers don't // merge all consecutive objects into one. // TODO(schectman): When should a node have this attribute set? // https://github.com/flutter/flutter/issues/118184 node_data.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject, true); } void AccessibilityBridge::SetIntAttributesFromFlutterUpdate( ui::AXNodeData& node_data, const SemanticsNode& node) { FlutterSemanticsFlag flags = node.flags; node_data.AddIntAttribute(ax::mojom::IntAttribute::kTextDirection, node.text_direction); int sel_start = node.text_selection_base; int sel_end = node.text_selection_extent; if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsReadOnly) == 0 && !node.value.empty()) { // By default the text field selection should be at the end. sel_start = sel_start == -1 ? node.value.length() : sel_start; sel_end = sel_end == -1 ? node.value.length() : sel_end; } node_data.AddIntAttribute(ax::mojom::IntAttribute::kTextSelStart, sel_start); node_data.AddIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, sel_end); if (node_data.role == ax::mojom::Role::kRadioButton || node_data.role == ax::mojom::Role::kCheckBox) { node_data.AddIntAttribute( ax::mojom::IntAttribute::kCheckedState, static_cast<int32_t>( flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsCheckStateMixed ? ax::mojom::CheckedState::kMixed : flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsChecked ? ax::mojom::CheckedState::kTrue : ax::mojom::CheckedState::kFalse)); } else if (node_data.role == ax::mojom::Role::kSwitch) { node_data.AddIntAttribute( ax::mojom::IntAttribute::kCheckedState, static_cast<int32_t>( flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsToggled ? ax::mojom::CheckedState::kTrue : ax::mojom::CheckedState::kFalse)); } } void AccessibilityBridge::SetIntListAttributesFromFlutterUpdate( ui::AXNodeData& node_data, const SemanticsNode& node) { FlutterSemanticsAction actions = node.actions; if (actions & FlutterSemanticsAction::kFlutterSemanticsActionCustomAction) { std::vector<int32_t> custom_action_ids; for (size_t i = 0; i < node.custom_accessibility_actions.size(); i++) { custom_action_ids.push_back(node.custom_accessibility_actions[i]); } node_data.AddIntListAttribute(ax::mojom::IntListAttribute::kCustomActionIds, custom_action_ids); } } void AccessibilityBridge::SetStringListAttributesFromFlutterUpdate( ui::AXNodeData& node_data, const SemanticsNode& node) { FlutterSemanticsAction actions = node.actions; if (actions & FlutterSemanticsAction::kFlutterSemanticsActionCustomAction) { std::vector<std::string> custom_action_description; for (size_t i = 0; i < node.custom_accessibility_actions.size(); i++) { auto iter = pending_semantics_custom_action_updates_.find( node.custom_accessibility_actions[i]); BASE_DCHECK(iter != pending_semantics_custom_action_updates_.end()); custom_action_description.push_back(iter->second.label); } node_data.AddStringListAttribute( ax::mojom::StringListAttribute::kCustomActionDescriptions, custom_action_description); } } void AccessibilityBridge::SetNameFromFlutterUpdate(ui::AXNodeData& node_data, const SemanticsNode& node) { node_data.SetName(node.label); } void AccessibilityBridge::SetValueFromFlutterUpdate(ui::AXNodeData& node_data, const SemanticsNode& node) { node_data.SetValue(node.value); } void AccessibilityBridge::SetTooltipFromFlutterUpdate( ui::AXNodeData& node_data, const SemanticsNode& node) { node_data.SetTooltip(node.tooltip); } void AccessibilityBridge::SetTreeData(const SemanticsNode& node, ui::AXTreeUpdate& tree_update) { FlutterSemanticsFlag flags = node.flags; // Set selection of the focused node if: // 1. this text field has a valid selection // 2. this text field doesn't have a valid selection but had selection stored // in the tree. if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField && flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused) { if (node.text_selection_base != -1) { tree_update.tree_data.sel_anchor_object_id = node.id; tree_update.tree_data.sel_anchor_offset = node.text_selection_base; tree_update.tree_data.sel_focus_object_id = node.id; tree_update.tree_data.sel_focus_offset = node.text_selection_extent; tree_update.has_tree_data = true; } else if (tree_update.tree_data.sel_anchor_object_id == node.id) { tree_update.tree_data.sel_anchor_object_id = ui::AXNode::kInvalidAXID; tree_update.tree_data.sel_anchor_offset = -1; tree_update.tree_data.sel_focus_object_id = ui::AXNode::kInvalidAXID; tree_update.tree_data.sel_focus_offset = -1; tree_update.has_tree_data = true; } } if (flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused && tree_update.tree_data.focus_id != node.id) { tree_update.tree_data.focus_id = node.id; tree_update.has_tree_data = true; } else if ((flags & FlutterSemanticsFlag::kFlutterSemanticsFlagIsFocused) == 0 && tree_update.tree_data.focus_id == node.id) { tree_update.tree_data.focus_id = ui::AXNode::kInvalidAXID; tree_update.has_tree_data = true; } } AccessibilityBridge::SemanticsNode AccessibilityBridge::FromFlutterSemanticsNode( const FlutterSemanticsNode2& flutter_node) { SemanticsNode result; result.id = flutter_node.id; result.flags = flutter_node.flags; result.actions = flutter_node.actions; result.text_selection_base = flutter_node.text_selection_base; result.text_selection_extent = flutter_node.text_selection_extent; result.scroll_child_count = flutter_node.scroll_child_count; result.scroll_index = flutter_node.scroll_index; result.scroll_position = flutter_node.scroll_position; result.scroll_extent_max = flutter_node.scroll_extent_max; result.scroll_extent_min = flutter_node.scroll_extent_min; result.elevation = flutter_node.elevation; result.thickness = flutter_node.thickness; if (flutter_node.label) { result.label = std::string(flutter_node.label); } if (flutter_node.hint) { result.hint = std::string(flutter_node.hint); } if (flutter_node.value) { result.value = std::string(flutter_node.value); } if (flutter_node.increased_value) { result.increased_value = std::string(flutter_node.increased_value); } if (flutter_node.decreased_value) { result.decreased_value = std::string(flutter_node.decreased_value); } if (flutter_node.tooltip) { result.tooltip = std::string(flutter_node.tooltip); } result.text_direction = flutter_node.text_direction; result.rect = flutter_node.rect; result.transform = flutter_node.transform; if (flutter_node.child_count > 0) { result.children_in_traversal_order = std::vector<int32_t>( flutter_node.children_in_traversal_order, flutter_node.children_in_traversal_order + flutter_node.child_count); } if (flutter_node.custom_accessibility_actions_count > 0) { result.custom_accessibility_actions = std::vector<int32_t>( flutter_node.custom_accessibility_actions, flutter_node.custom_accessibility_actions + flutter_node.custom_accessibility_actions_count); } return result; } AccessibilityBridge::SemanticsCustomAction AccessibilityBridge::FromFlutterSemanticsCustomAction( const FlutterSemanticsCustomAction2& flutter_custom_action) { SemanticsCustomAction result; result.id = flutter_custom_action.id; result.override_action = flutter_custom_action.override_action; if (flutter_custom_action.label) { result.label = std::string(flutter_custom_action.label); } if (flutter_custom_action.hint) { result.hint = std::string(flutter_custom_action.hint); } return result; } void AccessibilityBridge::SetLastFocusedId(AccessibilityNodeId node_id) { if (last_focused_id_ != node_id) { auto last_focused_child = GetFlutterPlatformNodeDelegateFromID(last_focused_id_); if (!last_focused_child.expired()) { DispatchAccessibilityAction( last_focused_id_, FlutterSemanticsAction:: kFlutterSemanticsActionDidLoseAccessibilityFocus, {}); } last_focused_id_ = node_id; } } AccessibilityNodeId AccessibilityBridge::GetLastFocusedId() { return last_focused_id_; } gfx::NativeViewAccessible AccessibilityBridge::GetNativeAccessibleFromId( AccessibilityNodeId id) { auto platform_node_delegate = GetFlutterPlatformNodeDelegateFromID(id).lock(); if (!platform_node_delegate) { return nullptr; } return platform_node_delegate->GetNativeViewAccessible(); } gfx::RectF AccessibilityBridge::RelativeToGlobalBounds(const ui::AXNode* node, bool& offscreen, bool clip_bounds) { return tree_->RelativeToTreeBounds(node, gfx::RectF(), &offscreen, clip_bounds); } ui::AXNode* AccessibilityBridge::GetNodeFromTree( ui::AXTreeID tree_id, ui::AXNode::AXID node_id) const { return GetNodeFromTree(node_id); } ui::AXNode* AccessibilityBridge::GetNodeFromTree( ui::AXNode::AXID node_id) const { return tree_->GetFromId(node_id); } ui::AXTreeID AccessibilityBridge::GetTreeID() const { return tree_->GetAXTreeID(); } ui::AXTreeID AccessibilityBridge::GetParentTreeID() const { return ui::AXTreeIDUnknown(); } ui::AXNode* AccessibilityBridge::GetRootAsAXNode() const { return tree_->root(); } ui::AXNode* AccessibilityBridge::GetParentNodeFromParentTreeAsAXNode() const { return nullptr; } ui::AXTree* AccessibilityBridge::GetTree() const { return tree_.get(); } ui::AXPlatformNode* AccessibilityBridge::GetPlatformNodeFromTree( const ui::AXNode::AXID node_id) const { auto platform_delegate_weak = GetFlutterPlatformNodeDelegateFromID(node_id); auto platform_delegate = platform_delegate_weak.lock(); if (!platform_delegate) { return nullptr; } return platform_delegate->GetPlatformNode(); } ui::AXPlatformNode* AccessibilityBridge::GetPlatformNodeFromTree( const ui::AXNode& node) const { return GetPlatformNodeFromTree(node.id()); } ui::AXPlatformNodeDelegate* AccessibilityBridge::RootDelegate() const { return GetFlutterPlatformNodeDelegateFromID(GetRootAsAXNode()->id()) .lock() .get(); } } // namespace flutter
engine/shell/platform/common/accessibility_bridge.cc/0
{ "file_path": "engine/shell/platform/common/accessibility_bridge.cc", "repo_id": "engine", "token_count": 10835 }
368
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_ #include <iostream> #include <string> #include <utility> #include "binary_messenger.h" #include "message_codec.h" namespace flutter { namespace internal { // Internal helper functions used by BasicMessageChannel and MethodChannel. // Adjusts the number of messages that will get buffered when sending messages // to channels that aren't fully set up yet. For example, the engine isn't // running yet or the channel's message handler isn't set up on the Dart side // yet. void ResizeChannel(BinaryMessenger* messenger, std::string name, int new_size); // Defines whether the channel should show warning messages when discarding // messages due to overflow. // // When |warns| is false, the channel is expected to overflow and warning // messages will not be shown. void SetChannelWarnsOnOverflow(BinaryMessenger* messenger, std::string name, bool warns); } // namespace internal class EncodableValue; // A message reply callback. // // Used for submitting a reply back to a Flutter message sender. template <typename T> using MessageReply = std::function<void(const T& reply)>; // A handler for receiving a message from the Flutter engine. // // Implementations must asynchronously call reply exactly once with the reply // to the message. template <typename T> using MessageHandler = std::function<void(const T& message, const MessageReply<T>& reply)>; // A channel for communicating with the Flutter engine by sending asynchronous // messages. template <typename T = EncodableValue> class BasicMessageChannel { public: // Creates an instance that sends and receives method calls on the channel // named |name|, encoded with |codec| and dispatched via |messenger|. BasicMessageChannel(BinaryMessenger* messenger, const std::string& name, const MessageCodec<T>* codec) : messenger_(messenger), name_(name), codec_(codec) {} ~BasicMessageChannel() = default; // Prevent copying. BasicMessageChannel(BasicMessageChannel const&) = delete; BasicMessageChannel& operator=(BasicMessageChannel const&) = delete; // Sends a message to the Flutter engine on this channel. void Send(const T& message) { std::unique_ptr<std::vector<uint8_t>> raw_message = codec_->EncodeMessage(message); messenger_->Send(name_, raw_message->data(), raw_message->size()); } // Sends a message to the Flutter engine on this channel expecting a reply. void Send(const T& message, BinaryReply reply) { std::unique_ptr<std::vector<uint8_t>> raw_message = codec_->EncodeMessage(message); messenger_->Send(name_, raw_message->data(), raw_message->size(), std::move(reply)); } // Registers a handler that should be called any time a message is // received on this channel. A null handler will remove any previous handler. // // Note that the BasicMessageChannel does not own the handler, and will not // unregister it on destruction, so the caller is responsible for // unregistering explicitly if it should no longer be called. void SetMessageHandler(const MessageHandler<T>& handler) const { if (!handler) { messenger_->SetMessageHandler(name_, nullptr); return; } const auto* codec = codec_; std::string channel_name = name_; BinaryMessageHandler binary_handler = [handler, codec, channel_name]( const uint8_t* binary_message, const size_t binary_message_size, const BinaryReply& binary_reply) { // Use this channel's codec to decode the message and build a reply // handler. std::unique_ptr<T> message = codec->DecodeMessage(binary_message, binary_message_size); if (!message) { std::cerr << "Unable to decode message on channel " << channel_name << std::endl; binary_reply(nullptr, 0); return; } MessageReply<T> unencoded_reply = [binary_reply, codec](const T& unencoded_response) { auto binary_response = codec->EncodeMessage(unencoded_response); binary_reply(binary_response->data(), binary_response->size()); }; handler(*message, std::move(unencoded_reply)); }; messenger_->SetMessageHandler(name_, std::move(binary_handler)); } // Adjusts the number of messages that will get buffered when sending messages // to channels that aren't fully set up yet. For example, the engine isn't // running yet or the channel's message handler isn't set up on the Dart side // yet. void Resize(int new_size) { internal::ResizeChannel(messenger_, name_, new_size); } // Defines whether the channel should show warning messages when discarding // messages due to overflow. // // When |warns| is false, the channel is expected to overflow and warning // messages will not be shown. void SetWarnsOnOverflow(bool warns) { internal::SetChannelWarnsOnOverflow(messenger_, name_, warns); } private: BinaryMessenger* messenger_; std::string name_; const MessageCodec<T>* codec_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_
engine/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h", "repo_id": "engine", "token_count": 2009 }
369
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRY_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRY_H_ #include <string> #include <flutter_plugin_registrar.h> namespace flutter { // Vends PluginRegistrars for named plugins. // // Plugins are identified by unique string keys, typically the name of the // plugin's main class. class PluginRegistry { public: PluginRegistry() = default; virtual ~PluginRegistry() = default; // Prevent copying. PluginRegistry(PluginRegistry const&) = delete; PluginRegistry& operator=(PluginRegistry const&) = delete; // Returns the FlutterDesktopPluginRegistrarRef to register a plugin with the // given name. // // The name must be unique across the application. virtual FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( const std::string& plugin_name) = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRY_H_
engine/shell/platform/common/client_wrapper/include/flutter/plugin_registry.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/plugin_registry.h", "repo_id": "engine", "token_count": 398 }
370
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/client_wrapper/testing/test_codec_extensions.h" namespace flutter { PointExtensionSerializer::PointExtensionSerializer() = default; PointExtensionSerializer::~PointExtensionSerializer() = default; // static const PointExtensionSerializer& PointExtensionSerializer::GetInstance() { static PointExtensionSerializer sInstance; return sInstance; } EncodableValue PointExtensionSerializer::ReadValueOfType( uint8_t type, ByteStreamReader* stream) const { if (type == kPointType) { int32_t x = stream->ReadInt32(); int32_t y = stream->ReadInt32(); return CustomEncodableValue(Point(x, y)); } return StandardCodecSerializer::ReadValueOfType(type, stream); } void PointExtensionSerializer::WriteValue(const EncodableValue& value, ByteStreamWriter* stream) const { auto custom_value = std::get_if<CustomEncodableValue>(&value); if (!custom_value) { StandardCodecSerializer::WriteValue(value, stream); return; } stream->WriteByte(kPointType); const Point& point = std::any_cast<Point>(*custom_value); stream->WriteInt32(point.x()); stream->WriteInt32(point.y()); } SomeDataExtensionSerializer::SomeDataExtensionSerializer() = default; SomeDataExtensionSerializer::~SomeDataExtensionSerializer() = default; // static const SomeDataExtensionSerializer& SomeDataExtensionSerializer::GetInstance() { static SomeDataExtensionSerializer sInstance; return sInstance; } EncodableValue SomeDataExtensionSerializer::ReadValueOfType( uint8_t type, ByteStreamReader* stream) const { if (type == kSomeDataType) { size_t size = ReadSize(stream); std::vector<uint8_t> data; data.resize(size); stream->ReadBytes(data.data(), size); EncodableValue label = ReadValue(stream); return CustomEncodableValue(SomeData(std::get<std::string>(label), data)); } return StandardCodecSerializer::ReadValueOfType(type, stream); } void SomeDataExtensionSerializer::WriteValue(const EncodableValue& value, ByteStreamWriter* stream) const { auto custom_value = std::get_if<CustomEncodableValue>(&value); if (!custom_value) { StandardCodecSerializer::WriteValue(value, stream); return; } stream->WriteByte(kSomeDataType); const SomeData& some_data = std::any_cast<SomeData>(*custom_value); size_t data_size = some_data.data().size(); WriteSize(data_size, stream); stream->WriteBytes(some_data.data().data(), data_size); WriteValue(EncodableValue(some_data.label()), stream); } } // namespace flutter
engine/shell/platform/common/client_wrapper/testing/test_codec_extensions.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/testing/test_codec_extensions.cc", "repo_id": "engine", "token_count": 955 }
371
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_JSON_MESSAGE_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_JSON_MESSAGE_CODEC_H_ #include <rapidjson/document.h> #include "flutter/shell/platform/common/client_wrapper/include/flutter/message_codec.h" namespace flutter { // A message encoding/decoding mechanism for communications to/from the // Flutter engine via JSON channels. class JsonMessageCodec : public MessageCodec<rapidjson::Document> { public: // Returns the shared instance of the codec. static const JsonMessageCodec& GetInstance(); ~JsonMessageCodec() = default; // Prevent copying. JsonMessageCodec(JsonMessageCodec const&) = delete; JsonMessageCodec& operator=(JsonMessageCodec const&) = delete; protected: // Instances should be obtained via GetInstance. JsonMessageCodec() = default; // |flutter::MessageCodec| std::unique_ptr<rapidjson::Document> DecodeMessageInternal( const uint8_t* binary_message, const size_t message_size) const override; // |flutter::MessageCodec| std::unique_ptr<std::vector<uint8_t>> EncodeMessageInternal( const rapidjson::Document& message) const override; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_JSON_MESSAGE_CODEC_H_
engine/shell/platform/common/json_message_codec.h/0
{ "file_path": "engine/shell/platform/common/json_message_codec.h", "repo_id": "engine", "token_count": 466 }
372
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/text_editing_delta.h" #include "flutter/fml/string_conversion.h" namespace flutter { TextEditingDelta::TextEditingDelta(const std::u16string& text_before_change, const TextRange& range, const std::u16string& text) : old_text_(text_before_change), delta_text_(text), delta_start_(range.start()), delta_end_(range.start() + range.length()) {} TextEditingDelta::TextEditingDelta(const std::string& text_before_change, const TextRange& range, const std::string& text) : old_text_(fml::Utf8ToUtf16(text_before_change)), delta_text_(fml::Utf8ToUtf16(text)), delta_start_(range.start()), delta_end_(range.start() + range.length()) {} TextEditingDelta::TextEditingDelta(const std::u16string& text) : old_text_(text), delta_text_(u""), delta_start_(-1), delta_end_(-1) {} TextEditingDelta::TextEditingDelta(const std::string& text) : old_text_(fml::Utf8ToUtf16(text)), delta_text_(u""), delta_start_(-1), delta_end_(-1) {} } // namespace flutter
engine/shell/platform/common/text_editing_delta.cc/0
{ "file_path": "engine/shell/platform/common/text_editing_delta.cc", "repo_id": "engine", "token_count": 591 }
373
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/common/buffer_conversions.h" #include "flutter/fml/macros.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" namespace flutter { namespace { class NSDataMapping : public fml::Mapping { public: explicit NSDataMapping(NSData* data) : data_([data retain]) {} size_t GetSize() const override { return [data_.get() length]; } const uint8_t* GetMapping() const override { return static_cast<const uint8_t*>([data_.get() bytes]); } bool IsDontNeedSafe() const override { return false; } private: fml::scoped_nsobject<NSData> data_; FML_DISALLOW_COPY_AND_ASSIGN(NSDataMapping); }; } // namespace fml::MallocMapping CopyNSDataToMapping(NSData* data) { const uint8_t* bytes = static_cast<const uint8_t*>(data.bytes); return fml::MallocMapping::Copy(bytes, data.length); } NSData* ConvertMappingToNSData(fml::MallocMapping buffer) { size_t size = buffer.GetSize(); return [NSData dataWithBytesNoCopy:buffer.Release() length:size]; } std::unique_ptr<fml::Mapping> ConvertNSDataToMappingPtr(NSData* data) { return std::make_unique<NSDataMapping>(data); } NSData* CopyMappingPtrToNSData(std::unique_ptr<fml::Mapping> mapping) { return [NSData dataWithBytes:mapping->GetMapping() length:mapping->GetSize()]; } } // namespace flutter
engine/shell/platform/darwin/common/buffer_conversions.mm/0
{ "file_path": "engine/shell/platform/darwin/common/buffer_conversions.mm", "repo_id": "engine", "token_count": 511 }
374
// Copyright 2013 The Flutter 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 <Foundation/Foundation.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" FLUTTER_ASSERT_ARC const NSString* kDefaultAssetPath = @"Frameworks/App.framework/flutter_assets"; static NSString* GetFlutterAssetsPathFromBundle(NSBundle* bundle, NSString* relativeAssetsPath); NSBundle* FLTFrameworkBundleInternal(NSString* flutterFrameworkBundleID, NSURL* searchURL) { NSDirectoryEnumerator<NSURL*>* frameworkEnumerator = [NSFileManager.defaultManager enumeratorAtURL:searchURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsSubdirectoryDescendants | NSDirectoryEnumerationSkipsHiddenFiles // Skip directories where errors are encountered. errorHandler:nil]; for (NSURL* candidate in frameworkEnumerator) { NSBundle* flutterFrameworkBundle = [NSBundle bundleWithURL:candidate]; if ([flutterFrameworkBundle.bundleIdentifier isEqualToString:flutterFrameworkBundleID]) { return flutterFrameworkBundle; } } return nil; } NSBundle* FLTGetApplicationBundle() { NSBundle* mainBundle = NSBundle.mainBundle; // App extension bundle is in <AppName>.app/PlugIns/Extension.appex. if ([mainBundle.bundleURL.pathExtension isEqualToString:@"appex"]) { // Up two levels. return [NSBundle bundleWithURL:mainBundle.bundleURL.URLByDeletingLastPathComponent .URLByDeletingLastPathComponent]; } return mainBundle; } NSBundle* FLTFrameworkBundleWithIdentifier(NSString* flutterFrameworkBundleID) { NSBundle* appBundle = FLTGetApplicationBundle(); NSBundle* flutterFrameworkBundle = FLTFrameworkBundleInternal(flutterFrameworkBundleID, appBundle.privateFrameworksURL); if (flutterFrameworkBundle == nil) { // Fallback to slow implementation. flutterFrameworkBundle = [NSBundle bundleWithIdentifier:flutterFrameworkBundleID]; } if (flutterFrameworkBundle == nil) { flutterFrameworkBundle = NSBundle.mainBundle; } return flutterFrameworkBundle; } NSString* FLTAssetPath(NSBundle* bundle) { return [bundle objectForInfoDictionaryKey:@"FLTAssetsPath"] ?: kDefaultAssetPath; } NSString* FLTAssetsPathFromBundle(NSBundle* bundle) { NSString* relativeAssetsPath = FLTAssetPath(bundle); NSString* flutterAssetsPath = GetFlutterAssetsPathFromBundle(bundle, relativeAssetsPath); if (flutterAssetsPath.length == 0) { flutterAssetsPath = GetFlutterAssetsPathFromBundle(NSBundle.mainBundle, relativeAssetsPath); } return flutterAssetsPath; } static NSString* GetFlutterAssetsPathFromBundle(NSBundle* bundle, NSString* relativeAssetsPath) { // Use the raw path solution so that asset path can be returned from unloaded bundles. // See https://github.com/flutter/engine/pull/46073 NSString* assetsPath = [bundle pathForResource:relativeAssetsPath ofType:nil]; if (assetsPath.length == 0) { // In app extension, using full relative path (kDefaultAssetPath) // returns nil when the app bundle is not loaded. Try to use // the sub folder name, which can successfully return a valid path. assetsPath = [bundle pathForResource:@"flutter_assets" ofType:nil]; } return assetsPath; }
engine/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.mm/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.mm", "repo_id": "engine", "token_count": 1230 }
375
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINEXTERNALTEXTUREMETAL_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINEXTERNALTEXTUREMETAL_H_ #import <Foundation/Foundation.h> #import <Metal/Metal.h> #include "flutter/common/graphics/texture.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkImage.h" @interface FlutterDarwinExternalTextureSkImageWrapper : NSObject + (sk_sp<SkImage>)wrapYUVATexture:(nonnull id<MTLTexture>)yTex UVTex:(nonnull id<MTLTexture>)uvTex YUVColorSpace:(SkYUVColorSpace)colorSpace grContext:(nonnull GrDirectContext*)grContext width:(size_t)width height:(size_t)height; + (sk_sp<SkImage>)wrapRGBATexture:(nonnull id<MTLTexture>)rgbaTex grContext:(nonnull GrDirectContext*)grContext width:(size_t)width height:(size_t)height; @end @interface FlutterDarwinExternalTextureMetal : NSObject - (nullable instancetype)initWithTextureCache:(nonnull CVMetalTextureCacheRef)textureCache textureID:(int64_t)textureID texture:(nonnull NSObject<FlutterTexture>*)texture enableImpeller:(BOOL)enableImpeller; - (void)paintContext:(flutter::Texture::PaintContext&)context bounds:(const SkRect&)bounds freeze:(BOOL)freeze sampling:(const flutter::DlImageSampling)sampling; - (void)onGrContextCreated; - (void)onGrContextDestroyed; - (void)markNewFrameAvailable; - (void)onTextureUnregistered; @property(nonatomic, readonly) int64_t textureID; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINEXTERNALTEXTUREMETAL_H_
engine/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h/0
{ "file_path": "engine/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h", "repo_id": "engine", "token_count": 970 }
376
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterAppDelegate.h" #import "flutter/fml/logging.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterPluginAppLifeCycleDelegate.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate_Test.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h" static NSString* const kUIBackgroundMode = @"UIBackgroundModes"; static NSString* const kRemoteNotificationCapabitiliy = @"remote-notification"; static NSString* const kBackgroundFetchCapatibility = @"fetch"; static NSString* const kRestorationStateAppModificationKey = @"mod-date"; @interface FlutterAppDelegate () @property(nonatomic, copy) FlutterViewController* (^rootFlutterViewControllerGetter)(void); @end @implementation FlutterAppDelegate { FlutterPluginAppLifeCycleDelegate* _lifeCycleDelegate; } - (instancetype)init { if (self = [super init]) { _lifeCycleDelegate = [[FlutterPluginAppLifeCycleDelegate alloc] init]; } return self; } - (void)dealloc { [_lifeCycleDelegate release]; [_rootFlutterViewControllerGetter release]; [_window release]; [super dealloc]; } - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions { return [_lifeCycleDelegate application:application willFinishLaunchingWithOptions:launchOptions]; } - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { return [_lifeCycleDelegate application:application didFinishLaunchingWithOptions:launchOptions]; } // Returns the key window's rootViewController, if it's a FlutterViewController. // Otherwise, returns nil. - (FlutterViewController*)rootFlutterViewController { if (_rootFlutterViewControllerGetter != nil) { return _rootFlutterViewControllerGetter(); } UIViewController* rootViewController = _window.rootViewController; if ([rootViewController isKindOfClass:[FlutterViewController class]]) { return (FlutterViewController*)rootViewController; } return nil; } // Do not remove, some clients may be calling these via `super`. - (void)applicationDidEnterBackground:(UIApplication*)application { } // Do not remove, some clients may be calling these via `super`. - (void)applicationWillEnterForeground:(UIApplication*)application { } // Do not remove, some clients may be calling these via `super`. - (void)applicationWillResignActive:(UIApplication*)application { } // Do not remove, some clients may be calling these via `super`. - (void)applicationDidBecomeActive:(UIApplication*)application { } // Do not remove, some clients may be calling these via `super`. - (void)applicationWillTerminate:(UIApplication*)application { } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - (void)application:(UIApplication*)application didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings { [_lifeCycleDelegate application:application didRegisterUserNotificationSettings:notificationSettings]; } #pragma GCC diagnostic pop - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { [_lifeCycleDelegate application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; } - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error { [_lifeCycleDelegate application:application didFailToRegisterForRemoteNotificationsWithError:error]; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - (void)application:(UIApplication*)application didReceiveLocalNotification:(UILocalNotification*)notification { [_lifeCycleDelegate application:application didReceiveLocalNotification:notification]; } #pragma GCC diagnostic pop - (void)userNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification*)notification withCompletionHandler: (void (^)(UNNotificationPresentationOptions options))completionHandler { if ([_lifeCycleDelegate respondsToSelector:_cmd]) { [_lifeCycleDelegate userNotificationCenter:center willPresentNotification:notification withCompletionHandler:completionHandler]; } } /** * Calls all plugins registered for `UNUserNotificationCenterDelegate` callbacks. */ - (void)userNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse*)response withCompletionHandler:(void (^)(void))completionHandler { if ([_lifeCycleDelegate respondsToSelector:_cmd]) { [_lifeCycleDelegate userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler]; } } - (BOOL)openURL:(NSURL*)url { NSNumber* isDeepLinkingEnabled = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"FlutterDeepLinkingEnabled"]; if (!isDeepLinkingEnabled.boolValue) { // Not set or NO. return NO; } else { FlutterViewController* flutterViewController = [self rootFlutterViewController]; if (flutterViewController) { [flutterViewController.engine waitForFirstFrame:3.0 callback:^(BOOL didTimeout) { if (didTimeout) { FML_LOG(ERROR) << "Timeout waiting for the first frame when launching an URL."; } else { [flutterViewController.engine.navigationChannel invokeMethod:@"pushRouteInformation" arguments:@{ @"location" : url.absoluteString ?: [NSNull null], }]; } }]; return YES; } else { FML_LOG(ERROR) << "Attempting to open an URL without a Flutter RootViewController."; return NO; } } } - (BOOL)application:(UIApplication*)application openURL:(NSURL*)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options { if ([_lifeCycleDelegate application:application openURL:url options:options]) { return YES; } return [self openURL:url]; } - (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url { return [_lifeCycleDelegate application:application handleOpenURL:url]; } - (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation { return [_lifeCycleDelegate application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } - (void)application:(UIApplication*)application performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem completionHandler:(void (^)(BOOL succeeded))completionHandler { [_lifeCycleDelegate application:application performActionForShortcutItem:shortcutItem completionHandler:completionHandler]; } - (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString*)identifier completionHandler:(nonnull void (^)())completionHandler { [_lifeCycleDelegate application:application handleEventsForBackgroundURLSession:identifier completionHandler:completionHandler]; } - (BOOL)application:(UIApplication*)application continueUserActivity:(NSUserActivity*)userActivity restorationHandler: (void (^)(NSArray<id<UIUserActivityRestoring>>* __nullable restorableObjects)) restorationHandler { if ([_lifeCycleDelegate application:application continueUserActivity:userActivity restorationHandler:restorationHandler]) { return YES; } return [self openURL:userActivity.webpageURL]; } #pragma mark - FlutterPluginRegistry methods. All delegating to the rootViewController - (NSObject<FlutterPluginRegistrar>*)registrarForPlugin:(NSString*)pluginKey { FlutterViewController* flutterRootViewController = [self rootFlutterViewController]; if (flutterRootViewController) { return [[flutterRootViewController pluginRegistry] registrarForPlugin:pluginKey]; } return nil; } - (BOOL)hasPlugin:(NSString*)pluginKey { FlutterViewController* flutterRootViewController = [self rootFlutterViewController]; if (flutterRootViewController) { return [[flutterRootViewController pluginRegistry] hasPlugin:pluginKey]; } return false; } - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey { FlutterViewController* flutterRootViewController = [self rootFlutterViewController]; if (flutterRootViewController) { return [[flutterRootViewController pluginRegistry] valuePublishedByPlugin:pluginKey]; } return nil; } #pragma mark - Selectors handling - (void)addApplicationLifeCycleDelegate:(NSObject<FlutterApplicationLifeCycleDelegate>*)delegate { [_lifeCycleDelegate addDelegate:delegate]; } #pragma mark - UIApplicationDelegate method dynamic implementation - (BOOL)respondsToSelector:(SEL)selector { if ([_lifeCycleDelegate isSelectorAddedDynamically:selector]) { return [self delegateRespondsSelectorToPlugins:selector]; } return [super respondsToSelector:selector]; } - (BOOL)delegateRespondsSelectorToPlugins:(SEL)selector { if ([_lifeCycleDelegate hasPluginThatRespondsToSelector:selector]) { return [_lifeCycleDelegate respondsToSelector:selector]; } else { return NO; } } - (id)forwardingTargetForSelector:(SEL)aSelector { if ([_lifeCycleDelegate isSelectorAddedDynamically:aSelector]) { [self logCapabilityConfigurationWarningIfNeeded:aSelector]; return _lifeCycleDelegate; } return [super forwardingTargetForSelector:aSelector]; } // Mimic the logging from Apple when the capability is not set for the selectors. // However the difference is that Apple logs these message when the app launches, we only // log it when the method is invoked. We can possibly also log it when the app launches, but // it will cause an additional scan over all the plugins. - (void)logCapabilityConfigurationWarningIfNeeded:(SEL)selector { NSArray* backgroundModesArray = [[NSBundle mainBundle] objectForInfoDictionaryKey:kUIBackgroundMode]; NSSet* backgroundModesSet = [[[NSSet alloc] initWithArray:backgroundModesArray] autorelease]; if (selector == @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)) { if (![backgroundModesSet containsObject:kRemoteNotificationCapabitiliy]) { NSLog( @"You've implemented -[<UIApplicationDelegate> " @"application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need " @"to add \"remote-notification\" to the list of your supported UIBackgroundModes in your " @"Info.plist."); } } else if (selector == @selector(application:performFetchWithCompletionHandler:)) { if (![backgroundModesSet containsObject:kBackgroundFetchCapatibility]) { NSLog(@"You've implemented -[<UIApplicationDelegate> " @"application:performFetchWithCompletionHandler:], but you still need to add \"fetch\" " @"to the list of your supported UIBackgroundModes in your Info.plist."); } } } #pragma mark - State Restoration - (BOOL)application:(UIApplication*)application shouldSaveApplicationState:(NSCoder*)coder { [coder encodeInt64:self.lastAppModificationTime forKey:kRestorationStateAppModificationKey]; return YES; } - (BOOL)application:(UIApplication*)application shouldRestoreApplicationState:(NSCoder*)coder { int64_t stateDate = [coder decodeInt64ForKey:kRestorationStateAppModificationKey]; return self.lastAppModificationTime == stateDate; } - (BOOL)application:(UIApplication*)application shouldSaveSecureApplicationState:(NSCoder*)coder { [coder encodeInt64:self.lastAppModificationTime forKey:kRestorationStateAppModificationKey]; return YES; } - (BOOL)application:(UIApplication*)application shouldRestoreSecureApplicationState:(NSCoder*)coder { int64_t stateDate = [coder decodeInt64ForKey:kRestorationStateAppModificationKey]; return self.lastAppModificationTime == stateDate; } - (int64_t)lastAppModificationTime { NSDate* fileDate; NSError* error = nil; [[[NSBundle mainBundle] executableURL] getResourceValue:&fileDate forKey:NSURLContentModificationDateKey error:&error]; NSAssert(error == nil, @"Cannot obtain modification date of main bundle: %@", error); return [fileDate timeIntervalSince1970]; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterAppDelegate.mm", "repo_id": "engine", "token_count": 4589 }
377
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define FML_USED_ON_EMBEDDER #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" #include <memory> #include "flutter/common/constants.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/platform/darwin/platform_version.h" #include "flutter/fml/platform/darwin/weak_nsobject.h" #include "flutter/fml/trace_event.h" #include "flutter/runtime/ptrace_check.h" #include "flutter/shell/common/engine.h" #include "flutter/shell/common/platform_view.h" #include "flutter/shell/common/shell.h" #include "flutter/shell/common/switches.h" #include "flutter/shell/common/thread_host.h" #include "flutter/shell/common/variable_refresh_rate_display.h" #import "flutter/shell/platform/darwin/common/command_line.h" #import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartVMServicePublisher.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSpellCheckPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextureRegistryRelay.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h" #import "flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h" #import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/profiler_metrics_ios.h" #import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" #import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" #include "flutter/shell/profiling/sampling_profiler.h" /// Inheriting ThreadConfigurer and use iOS platform thread API to configure the thread priorities /// Using iOS platform thread API to configure thread priority static void IOSPlatformThreadConfigSetter(const fml::Thread::ThreadConfig& config) { // set thread name fml::Thread::SetCurrentThreadName(config); // set thread priority switch (config.priority) { case fml::Thread::ThreadPriority::kBackground: { pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0); [[NSThread currentThread] setThreadPriority:0]; break; } case fml::Thread::ThreadPriority::kNormal: { pthread_set_qos_class_self_np(QOS_CLASS_DEFAULT, 0); [[NSThread currentThread] setThreadPriority:0.5]; break; } case fml::Thread::ThreadPriority::kRaster: case fml::Thread::ThreadPriority::kDisplay: { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); [[NSThread currentThread] setThreadPriority:1.0]; sched_param param; int policy; pthread_t thread = pthread_self(); if (!pthread_getschedparam(thread, &policy, &param)) { param.sched_priority = 50; pthread_setschedparam(thread, policy, &param); } break; } } } #pragma mark - Public exported constants NSString* const FlutterDefaultDartEntrypoint = nil; NSString* const FlutterDefaultInitialRoute = nil; #pragma mark - Internal constants NSString* const kFlutterEngineWillDealloc = @"FlutterEngineWillDealloc"; NSString* const kFlutterKeyDataChannel = @"flutter/keydata"; static constexpr int kNumProfilerSamplesPerSec = 5; @interface FlutterEngineRegistrar : NSObject <FlutterPluginRegistrar> @property(nonatomic, assign) FlutterEngine* flutterEngine; - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine; @end @interface FlutterEngine () <FlutterIndirectScribbleDelegate, FlutterUndoManagerDelegate, FlutterTextInputDelegate, FlutterBinaryMessenger, FlutterTextureRegistry> // Maintains a dictionary of plugin names that have registered with the engine. Used by // FlutterEngineRegistrar to implement a FlutterPluginRegistrar. @property(nonatomic, readonly) NSMutableDictionary* pluginPublications; @property(nonatomic, readonly) NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* registrars; @property(nonatomic, readwrite, copy) NSString* isolateId; @property(nonatomic, copy) NSString* initialRoute; @property(nonatomic, retain) id<NSObject> flutterViewControllerWillDeallocObserver; #pragma mark - Embedder API properties @property(nonatomic, assign) BOOL enableEmbedderAPI; // Function pointers for interacting with the embedder.h API. @property(nonatomic) FlutterEngineProcTable& embedderAPI; @end @implementation FlutterEngine { fml::scoped_nsobject<FlutterDartProject> _dartProject; std::shared_ptr<flutter::ThreadHost> _threadHost; std::unique_ptr<flutter::Shell> _shell; NSString* _labelPrefix; std::unique_ptr<fml::WeakNSObjectFactory<FlutterEngine>> _weakFactory; fml::WeakNSObject<FlutterViewController> _viewController; fml::scoped_nsobject<FlutterDartVMServicePublisher> _publisher; std::shared_ptr<flutter::FlutterPlatformViewsController> _platformViewsController; flutter::IOSRenderingAPI _renderingApi; std::shared_ptr<flutter::ProfilerMetricsIOS> _profiler_metrics; std::shared_ptr<flutter::SamplingProfiler> _profiler; // Channels fml::scoped_nsobject<FlutterPlatformPlugin> _platformPlugin; fml::scoped_nsobject<FlutterTextInputPlugin> _textInputPlugin; fml::scoped_nsobject<FlutterUndoManagerPlugin> _undoManagerPlugin; fml::scoped_nsobject<FlutterSpellCheckPlugin> _spellCheckPlugin; fml::scoped_nsobject<FlutterRestorationPlugin> _restorationPlugin; fml::scoped_nsobject<FlutterMethodChannel> _localizationChannel; fml::scoped_nsobject<FlutterMethodChannel> _navigationChannel; fml::scoped_nsobject<FlutterMethodChannel> _restorationChannel; fml::scoped_nsobject<FlutterMethodChannel> _platformChannel; fml::scoped_nsobject<FlutterMethodChannel> _platformViewsChannel; fml::scoped_nsobject<FlutterMethodChannel> _textInputChannel; fml::scoped_nsobject<FlutterMethodChannel> _undoManagerChannel; fml::scoped_nsobject<FlutterMethodChannel> _scribbleChannel; fml::scoped_nsobject<FlutterMethodChannel> _spellCheckChannel; fml::scoped_nsobject<FlutterBasicMessageChannel> _lifecycleChannel; fml::scoped_nsobject<FlutterBasicMessageChannel> _systemChannel; fml::scoped_nsobject<FlutterBasicMessageChannel> _settingsChannel; fml::scoped_nsobject<FlutterBasicMessageChannel> _keyEventChannel; fml::scoped_nsobject<FlutterMethodChannel> _screenshotChannel; int64_t _nextTextureId; BOOL _allowHeadlessExecution; BOOL _restorationEnabled; FlutterBinaryMessengerRelay* _binaryMessenger; FlutterTextureRegistryRelay* _textureRegistry; std::unique_ptr<flutter::ConnectionCollection> _connections; } - (instancetype)init { return [self initWithName:@"FlutterEngine" project:nil allowHeadlessExecution:YES]; } - (instancetype)initWithName:(NSString*)labelPrefix { return [self initWithName:labelPrefix project:nil allowHeadlessExecution:YES]; } - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project { return [self initWithName:labelPrefix project:project allowHeadlessExecution:YES]; } - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project allowHeadlessExecution:(BOOL)allowHeadlessExecution { return [self initWithName:labelPrefix project:project allowHeadlessExecution:allowHeadlessExecution restorationEnabled:NO]; } - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project allowHeadlessExecution:(BOOL)allowHeadlessExecution restorationEnabled:(BOOL)restorationEnabled { self = [super init]; NSAssert(self, @"Super init cannot be nil"); NSAssert(labelPrefix, @"labelPrefix is required"); _restorationEnabled = restorationEnabled; _allowHeadlessExecution = allowHeadlessExecution; _labelPrefix = [labelPrefix copy]; _weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterEngine>>(self); if (project == nil) { _dartProject.reset([[FlutterDartProject alloc] init]); } else { _dartProject.reset([project retain]); } _enableEmbedderAPI = _dartProject.get().settings.enable_embedder_api; if (_enableEmbedderAPI) { NSLog(@"============== iOS: enable_embedder_api is on =============="); _embedderAPI.struct_size = sizeof(FlutterEngineProcTable); FlutterEngineGetProcAddresses(&_embedderAPI); } if (!EnableTracingIfNecessary([_dartProject.get() settings])) { NSLog( @"Cannot create a FlutterEngine instance in debug mode without Flutter tooling or " @"Xcode.\n\nTo launch in debug mode in iOS 14+, run flutter run from Flutter tools, run " @"from an IDE with a Flutter IDE plugin or run the iOS project from Xcode.\nAlternatively " @"profile and release mode apps can be launched from the home screen."); [self release]; return nil; } _pluginPublications = [[NSMutableDictionary alloc] init]; _registrars = [[NSMutableDictionary alloc] init]; [self recreatePlatformViewController]; _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self]; _textureRegistry = [[FlutterTextureRegistryRelay alloc] initWithParent:self]; _connections.reset(new flutter::ConnectionCollection()); NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(onMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; #if APPLICATION_EXTENSION_API_ONLY if (@available(iOS 13.0, *)) { [self setUpSceneLifecycleNotifications:center]; } else { [self setUpApplicationLifecycleNotifications:center]; } #else [self setUpApplicationLifecycleNotifications:center]; #endif [center addObserver:self selector:@selector(onLocaleUpdated:) name:NSCurrentLocaleDidChangeNotification object:nil]; return self; } - (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) { [center addObserver:self selector:@selector(sceneWillEnterForeground:) name:UISceneWillEnterForegroundNotification object:nil]; [center addObserver:self selector:@selector(sceneDidEnterBackground:) name:UISceneDidEnterBackgroundNotification object:nil]; } - (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center { [center addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; [center addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; } - (void)recreatePlatformViewController { _renderingApi = flutter::GetRenderingAPIForProcess(FlutterView.forceSoftwareRendering); _platformViewsController.reset(new flutter::FlutterPlatformViewsController()); } - (flutter::IOSRenderingAPI)platformViewsRenderingAPI { return _renderingApi; } - (void)dealloc { /// Notify plugins of dealloc. This should happen first in dealloc since the /// plugins may be talking to things like the binaryMessenger. [_pluginPublications enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL* stop) { if ([object respondsToSelector:@selector(detachFromEngineForRegistrar:)]) { NSObject<FlutterPluginRegistrar>* registrar = self.registrars[key]; [object detachFromEngineForRegistrar:registrar]; } }]; [[NSNotificationCenter defaultCenter] postNotificationName:kFlutterEngineWillDealloc object:self userInfo:nil]; // It will be destroyed and invalidate its weak pointers // before any other members are destroyed. _weakFactory.reset(); /// nil out weak references. [_registrars enumerateKeysAndObjectsUsingBlock:^(id key, FlutterEngineRegistrar* registrar, BOOL* stop) { registrar.flutterEngine = nil; }]; [_labelPrefix release]; [_initialRoute release]; [_pluginPublications release]; [_registrars release]; _binaryMessenger.parent = nil; _textureRegistry.parent = nil; [_binaryMessenger release]; [_textureRegistry release]; _textureRegistry = nil; [_isolateId release]; NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; if (_flutterViewControllerWillDeallocObserver) { [center removeObserver:_flutterViewControllerWillDeallocObserver]; [_flutterViewControllerWillDeallocObserver release]; } [center removeObserver:self]; [super dealloc]; } - (flutter::Shell&)shell { FML_DCHECK(_shell); return *_shell; } - (fml::WeakNSObject<FlutterEngine>)getWeakNSObject { return _weakFactory->GetWeakNSObject(); } - (void)updateViewportMetrics:(flutter::ViewportMetrics)viewportMetrics { if (!self.platformView) { return; } self.platformView->SetViewportMetrics(flutter::kFlutterImplicitViewId, viewportMetrics); } - (void)dispatchPointerDataPacket:(std::unique_ptr<flutter::PointerDataPacket>)packet { if (!self.platformView) { return; } self.platformView->DispatchPointerDataPacket(std::move(packet)); } - (fml::WeakPtr<flutter::PlatformView>)platformView { FML_DCHECK(_shell); return _shell->GetPlatformView(); } - (flutter::PlatformViewIOS*)iosPlatformView { FML_DCHECK(_shell); return static_cast<flutter::PlatformViewIOS*>(_shell->GetPlatformView().get()); } - (fml::RefPtr<fml::TaskRunner>)platformTaskRunner { FML_DCHECK(_shell); return _shell->GetTaskRunners().GetPlatformTaskRunner(); } - (fml::RefPtr<fml::TaskRunner>)uiTaskRunner { FML_DCHECK(_shell); return _shell->GetTaskRunners().GetUITaskRunner(); } - (fml::RefPtr<fml::TaskRunner>)rasterTaskRunner { FML_DCHECK(_shell); return _shell->GetTaskRunners().GetRasterTaskRunner(); } - (void)sendKeyEvent:(const FlutterKeyEvent&)event callback:(FlutterKeyEventCallback)callback userData:(void*)userData API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { } else { return; } if (!self.platformView) { return; } const char* character = event.character; flutter::KeyData key_data; key_data.Clear(); key_data.timestamp = (uint64_t)event.timestamp; switch (event.type) { case kFlutterKeyEventTypeUp: key_data.type = flutter::KeyEventType::kUp; break; case kFlutterKeyEventTypeDown: key_data.type = flutter::KeyEventType::kDown; break; case kFlutterKeyEventTypeRepeat: key_data.type = flutter::KeyEventType::kRepeat; break; } key_data.physical = event.physical; key_data.logical = event.logical; key_data.synthesized = event.synthesized; auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character); NSData* message = [NSData dataWithBytes:packet->data().data() length:packet->data().size()]; auto response = ^(NSData* reply) { if (callback == nullptr) { return; } BOOL handled = FALSE; if (reply.length == 1 && *reinterpret_cast<const uint8_t*>(reply.bytes) == 1) { handled = TRUE; } callback(handled, userData); }; [self sendOnChannel:kFlutterKeyDataChannel message:message binaryReply:response]; } - (void)ensureSemanticsEnabled { self.iosPlatformView->SetSemanticsEnabled(true); } - (void)setViewController:(FlutterViewController*)viewController { FML_DCHECK(self.iosPlatformView); _viewController = viewController ? [viewController getWeakNSObject] : fml::WeakNSObject<FlutterViewController>(); self.iosPlatformView->SetOwnerViewController(_viewController); [self maybeSetupPlatformViewChannels]; [self updateDisplays]; _textInputPlugin.get().viewController = viewController; _undoManagerPlugin.get().viewController = viewController; if (viewController) { __block FlutterEngine* blockSelf = self; self.flutterViewControllerWillDeallocObserver = [[NSNotificationCenter defaultCenter] addObserverForName:FlutterViewControllerWillDealloc object:viewController queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification* note) { [blockSelf notifyViewControllerDeallocated]; }]; } else { self.flutterViewControllerWillDeallocObserver = nil; [self notifyLowMemory]; } } - (void)attachView { self.iosPlatformView->attachView(); } - (void)setFlutterViewControllerWillDeallocObserver:(id<NSObject>)observer { if (observer != _flutterViewControllerWillDeallocObserver) { if (_flutterViewControllerWillDeallocObserver) { [[NSNotificationCenter defaultCenter] removeObserver:_flutterViewControllerWillDeallocObserver]; [_flutterViewControllerWillDeallocObserver release]; } _flutterViewControllerWillDeallocObserver = [observer retain]; } } - (void)notifyViewControllerDeallocated { [[self lifecycleChannel] sendMessage:@"AppLifecycleState.detached"]; _textInputPlugin.get().viewController = nil; _undoManagerPlugin.get().viewController = nil; if (!_allowHeadlessExecution) { [self destroyContext]; } else if (_shell) { flutter::PlatformViewIOS* platform_view = [self iosPlatformView]; if (platform_view) { platform_view->SetOwnerViewController({}); } } [_textInputPlugin.get() resetViewResponder]; _viewController.reset(); } - (void)destroyContext { [self resetChannels]; self.isolateId = nil; _shell.reset(); _profiler.reset(); _threadHost.reset(); _platformViewsController.reset(); } - (FlutterViewController*)viewController { if (!_viewController) { return nil; } return _viewController.get(); } - (FlutterPlatformPlugin*)platformPlugin { return _platformPlugin.get(); } - (std::shared_ptr<flutter::FlutterPlatformViewsController>&)platformViewsController { return _platformViewsController; } - (FlutterTextInputPlugin*)textInputPlugin { return _textInputPlugin.get(); } - (FlutterUndoManagerPlugin*)undoManagerPlugin { return _undoManagerPlugin.get(); } - (FlutterRestorationPlugin*)restorationPlugin { return _restorationPlugin.get(); } - (FlutterMethodChannel*)localizationChannel { return _localizationChannel.get(); } - (FlutterMethodChannel*)navigationChannel { return _navigationChannel.get(); } - (FlutterMethodChannel*)restorationChannel { return _restorationChannel.get(); } - (FlutterMethodChannel*)platformChannel { return _platformChannel.get(); } - (FlutterMethodChannel*)textInputChannel { return _textInputChannel.get(); } - (FlutterMethodChannel*)undoManagerChannel { return _undoManagerChannel.get(); } - (FlutterMethodChannel*)scribbleChannel { return _scribbleChannel.get(); } - (FlutterMethodChannel*)spellCheckChannel { return _spellCheckChannel.get(); } - (FlutterBasicMessageChannel*)lifecycleChannel { return _lifecycleChannel.get(); } - (FlutterBasicMessageChannel*)systemChannel { return _systemChannel.get(); } - (FlutterBasicMessageChannel*)settingsChannel { return _settingsChannel.get(); } - (FlutterBasicMessageChannel*)keyEventChannel { return _keyEventChannel.get(); } - (NSURL*)observatoryUrl { return [_publisher.get() url]; } - (NSURL*)vmServiceUrl { return [_publisher.get() url]; } - (void)resetChannels { _localizationChannel.reset(); _navigationChannel.reset(); _restorationChannel.reset(); _platformChannel.reset(); _platformViewsChannel.reset(); _textInputChannel.reset(); _undoManagerChannel.reset(); _scribbleChannel.reset(); _lifecycleChannel.reset(); _systemChannel.reset(); _settingsChannel.reset(); _keyEventChannel.reset(); _spellCheckChannel.reset(); } - (void)startProfiler { FML_DCHECK(!_threadHost->name_prefix.empty()); _profiler_metrics = std::make_shared<flutter::ProfilerMetricsIOS>(); _profiler = std::make_shared<flutter::SamplingProfiler>( _threadHost->name_prefix.c_str(), _threadHost->profiler_thread->GetTaskRunner(), [self]() { return self->_profiler_metrics->GenerateSample(); }, kNumProfilerSamplesPerSec); _profiler->Start(); } // If you add a channel, be sure to also update `resetChannels`. // Channels get a reference to the engine, and therefore need manual // cleanup for proper collection. - (void)setUpChannels { // This will be invoked once the shell is done setting up and the isolate ID // for the UI isolate is available. fml::WeakNSObject<FlutterEngine> weakSelf = [self getWeakNSObject]; [_binaryMessenger setMessageHandlerOnChannel:@"flutter/isolate" binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) { if (weakSelf) { weakSelf.get().isolateId = [[FlutterStringCodec sharedInstance] decode:message]; } }]; _localizationChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/localization" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]); _navigationChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/navigation" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]); if ([_initialRoute length] > 0) { // Flutter isn't ready to receive this method call yet but the channel buffer will cache this. [_navigationChannel invokeMethod:@"setInitialRoute" arguments:_initialRoute]; [_initialRoute release]; _initialRoute = nil; } _restorationChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/restoration" binaryMessenger:self.binaryMessenger codec:[FlutterStandardMethodCodec sharedInstance]]); _platformChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/platform" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]); _platformViewsChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/platform_views" binaryMessenger:self.binaryMessenger codec:[FlutterStandardMethodCodec sharedInstance]]); _textInputChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/textinput" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]); _undoManagerChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/undomanager" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]); _scribbleChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/scribble" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]); _spellCheckChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/spellcheck" binaryMessenger:self.binaryMessenger codec:[FlutterStandardMethodCodec sharedInstance]]); _lifecycleChannel.reset([[FlutterBasicMessageChannel alloc] initWithName:@"flutter/lifecycle" binaryMessenger:self.binaryMessenger codec:[FlutterStringCodec sharedInstance]]); _systemChannel.reset([[FlutterBasicMessageChannel alloc] initWithName:@"flutter/system" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMessageCodec sharedInstance]]); _settingsChannel.reset([[FlutterBasicMessageChannel alloc] initWithName:@"flutter/settings" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMessageCodec sharedInstance]]); _keyEventChannel.reset([[FlutterBasicMessageChannel alloc] initWithName:@"flutter/keyevent" binaryMessenger:self.binaryMessenger codec:[FlutterJSONMessageCodec sharedInstance]]); FlutterTextInputPlugin* textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:self]; _textInputPlugin.reset(textInputPlugin); textInputPlugin.indirectScribbleDelegate = self; [textInputPlugin setUpIndirectScribbleInteraction:self.viewController]; FlutterUndoManagerPlugin* undoManagerPlugin = [[FlutterUndoManagerPlugin alloc] initWithDelegate:self]; _undoManagerPlugin.reset(undoManagerPlugin); _platformPlugin.reset([[FlutterPlatformPlugin alloc] initWithEngine:[self getWeakNSObject]]); _restorationPlugin.reset([[FlutterRestorationPlugin alloc] initWithChannel:_restorationChannel.get() restorationEnabled:_restorationEnabled]); _spellCheckPlugin.reset([[FlutterSpellCheckPlugin alloc] init]); _screenshotChannel.reset([[FlutterMethodChannel alloc] initWithName:@"flutter/screenshot" binaryMessenger:self.binaryMessenger codec:[FlutterStandardMethodCodec sharedInstance]]); [_screenshotChannel.get() setMethodCallHandler:^(FlutterMethodCall* _Nonnull call, FlutterResult _Nonnull result) { if (!(weakSelf.get() && weakSelf.get()->_shell && weakSelf.get()->_shell->IsSetup())) { return result([FlutterError errorWithCode:@"invalid_state" message:@"Requesting screenshot while engine is not running." details:nil]); } flutter::Rasterizer::Screenshot screenshot = [weakSelf.get() screenshot:flutter::Rasterizer::ScreenshotType::SurfaceData base64Encode:NO]; if (!screenshot.data) { return result([FlutterError errorWithCode:@"failure" message:@"Unable to get screenshot." details:nil]); } // TODO(gaaclarke): Find way to eliminate this data copy. NSData* data = [NSData dataWithBytes:screenshot.data->writable_data() length:screenshot.data->size()]; NSString* format = [NSString stringWithUTF8String:screenshot.format.c_str()]; NSNumber* width = @(screenshot.frame_size.fWidth); NSNumber* height = @(screenshot.frame_size.fHeight); return result(@[ width, height, format ?: [NSNull null], data ]); }]; } - (void)maybeSetupPlatformViewChannels { if (_shell && self.shell.IsSetup()) { FlutterPlatformPlugin* platformPlugin = _platformPlugin.get(); [_platformChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { [platformPlugin handleMethodCall:call result:result]; }]; fml::WeakNSObject<FlutterEngine> weakSelf = [self getWeakNSObject]; [_platformViewsChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { if (weakSelf) { weakSelf.get().platformViewsController->OnMethodCall(call, result); } }]; FlutterTextInputPlugin* textInputPlugin = _textInputPlugin.get(); [_textInputChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { [textInputPlugin handleMethodCall:call result:result]; }]; FlutterUndoManagerPlugin* undoManagerPlugin = _undoManagerPlugin.get(); [_undoManagerChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { [undoManagerPlugin handleMethodCall:call result:result]; }]; FlutterSpellCheckPlugin* spellCheckPlugin = _spellCheckPlugin.get(); [_spellCheckChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { [spellCheckPlugin handleMethodCall:call result:result]; }]; } } - (flutter::Rasterizer::Screenshot)screenshot:(flutter::Rasterizer::ScreenshotType)type base64Encode:(bool)base64Encode { return self.shell.Screenshot(type, base64Encode); } - (void)launchEngine:(NSString*)entrypoint libraryURI:(NSString*)libraryOrNil entrypointArgs:(NSArray<NSString*>*)entrypointArgs { // Launch the Dart application with the inferred run configuration. self.shell.RunEngine([_dartProject.get() runConfigurationForEntrypoint:entrypoint libraryOrNil:libraryOrNil entrypointArgs:entrypointArgs]); } - (void)setUpShell:(std::unique_ptr<flutter::Shell>)shell withVMServicePublication:(BOOL)doesVMServicePublication { _shell = std::move(shell); [self setUpChannels]; [self onLocaleUpdated:nil]; [self updateDisplays]; _publisher.reset([[FlutterDartVMServicePublisher alloc] initWithEnableVMServicePublication:doesVMServicePublication]); [self maybeSetupPlatformViewChannels]; _shell->SetGpuAvailability(_isGpuDisabled ? flutter::GpuAvailability::kUnavailable : flutter::GpuAvailability::kAvailable); } + (BOOL)isProfilerEnabled { bool profilerEnabled = false; #if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) || \ (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE) profilerEnabled = true; #endif return profilerEnabled; } + (NSString*)generateThreadLabel:(NSString*)labelPrefix { static size_t s_shellCount = 0; return [NSString stringWithFormat:@"%@.%zu", labelPrefix, ++s_shellCount]; } + (flutter::ThreadHost)makeThreadHost:(NSString*)threadLabel { // The current thread will be used as the platform thread. Ensure that the message loop is // initialized. fml::MessageLoop::EnsureInitializedForCurrentThread(); uint32_t threadHostType = flutter::ThreadHost::Type::kUi | flutter::ThreadHost::Type::kRaster | flutter::ThreadHost::Type::kIo; if ([FlutterEngine isProfilerEnabled]) { threadHostType = threadHostType | flutter::ThreadHost::Type::kProfiler; } flutter::ThreadHost::ThreadHostConfig host_config(threadLabel.UTF8String, threadHostType, IOSPlatformThreadConfigSetter); host_config.ui_config = fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kUi, threadLabel.UTF8String), fml::Thread::ThreadPriority::kDisplay); host_config.raster_config = fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kRaster, threadLabel.UTF8String), fml::Thread::ThreadPriority::kRaster); host_config.io_config = fml::Thread::ThreadConfig(flutter::ThreadHost::ThreadHostConfig::MakeThreadName( flutter::ThreadHost::Type::kIo, threadLabel.UTF8String), fml::Thread::ThreadPriority::kNormal); return (flutter::ThreadHost){host_config}; } static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSString* libraryURI) { if (libraryURI) { FML_DCHECK(entrypoint) << "Must specify entrypoint if specifying library"; settings->advisory_script_entrypoint = entrypoint.UTF8String; settings->advisory_script_uri = libraryURI.UTF8String; } else if (entrypoint) { settings->advisory_script_entrypoint = entrypoint.UTF8String; settings->advisory_script_uri = std::string("main.dart"); } else { settings->advisory_script_entrypoint = std::string("main"); settings->advisory_script_uri = std::string("main.dart"); } } - (BOOL)createShell:(NSString*)entrypoint libraryURI:(NSString*)libraryURI initialRoute:(NSString*)initialRoute { if (_shell != nullptr) { FML_LOG(WARNING) << "This FlutterEngine was already invoked."; return NO; } self.initialRoute = initialRoute; auto settings = [_dartProject.get() settings]; if (initialRoute != nil) { self.initialRoute = initialRoute; } else if (settings.route.empty() == false) { self.initialRoute = [NSString stringWithUTF8String:settings.route.c_str()]; } FlutterView.forceSoftwareRendering = settings.enable_software_rendering; auto platformData = [_dartProject.get() defaultPlatformData]; SetEntryPoint(&settings, entrypoint, libraryURI); NSString* threadLabel = [FlutterEngine generateThreadLabel:_labelPrefix]; _threadHost = std::make_shared<flutter::ThreadHost>(); *_threadHost = [FlutterEngine makeThreadHost:threadLabel]; // Lambda captures by pointers to ObjC objects are fine here because the // create call is synchronous. flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view = [self](flutter::Shell& shell) { [self recreatePlatformViewController]; return std::make_unique<flutter::PlatformViewIOS>( shell, self->_renderingApi, self->_platformViewsController, shell.GetTaskRunners(), shell.GetConcurrentWorkerTaskRunner(), shell.GetIsGpuDisabledSyncSwitch()); }; flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer = [](flutter::Shell& shell) { return std::make_unique<flutter::Rasterizer>(shell); }; flutter::TaskRunners task_runners(threadLabel.UTF8String, // label fml::MessageLoop::GetCurrent().GetTaskRunner(), // platform _threadHost->raster_thread->GetTaskRunner(), // raster _threadHost->ui_thread->GetTaskRunner(), // ui _threadHost->io_thread->GetTaskRunner() // io ); #if APPLICATION_EXTENSION_API_ONLY if (@available(iOS 13.0, *)) { _isGpuDisabled = self.viewController.flutterWindowSceneIfViewLoaded.activationState == UISceneActivationStateBackground; } else { // [UIApplication sharedApplication API is not available for app extension. // We intialize the shell assuming the GPU is required. _isGpuDisabled = NO; } #else _isGpuDisabled = [UIApplication sharedApplication].applicationState == UIApplicationStateBackground; #endif // Create the shell. This is a blocking operation. std::unique_ptr<flutter::Shell> shell = flutter::Shell::Create( /*platform_data=*/platformData, /*task_runners=*/task_runners, /*settings=*/settings, /*on_create_platform_view=*/on_create_platform_view, /*on_create_rasterizer=*/on_create_rasterizer, /*is_gpu_disabled=*/_isGpuDisabled); if (shell == nullptr) { FML_LOG(ERROR) << "Could not start a shell FlutterEngine with entrypoint: " << entrypoint.UTF8String; } else { // TODO(vashworth): Remove once done debugging https://github.com/flutter/flutter/issues/129836 FML_LOG(INFO) << "Enabled VM Service Publication: " << settings.enable_vm_service_publication; [self setUpShell:std::move(shell) withVMServicePublication:settings.enable_vm_service_publication]; if ([FlutterEngine isProfilerEnabled]) { [self startProfiler]; } } return _shell != nullptr; } - (void)updateDisplays { if (!_shell) { // Tests may do this. return; } auto vsync_waiter = _shell->GetVsyncWaiter().lock(); auto vsync_waiter_ios = std::static_pointer_cast<flutter::VsyncWaiterIOS>(vsync_waiter); std::vector<std::unique_ptr<flutter::Display>> displays; auto screen_size = UIScreen.mainScreen.nativeBounds.size; auto scale = UIScreen.mainScreen.scale; displays.push_back(std::make_unique<flutter::VariableRefreshRateDisplay>( 0, vsync_waiter_ios, screen_size.width, screen_size.height, scale)); _shell->OnDisplayUpdates(std::move(displays)); } - (BOOL)run { return [self runWithEntrypoint:FlutterDefaultDartEntrypoint libraryURI:nil initialRoute:FlutterDefaultInitialRoute]; } - (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI { return [self runWithEntrypoint:entrypoint libraryURI:libraryURI initialRoute:FlutterDefaultInitialRoute]; } - (BOOL)runWithEntrypoint:(NSString*)entrypoint { return [self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:FlutterDefaultInitialRoute]; } - (BOOL)runWithEntrypoint:(NSString*)entrypoint initialRoute:(NSString*)initialRoute { return [self runWithEntrypoint:entrypoint libraryURI:nil initialRoute:initialRoute]; } - (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI initialRoute:(NSString*)initialRoute { return [self runWithEntrypoint:entrypoint libraryURI:libraryURI initialRoute:initialRoute entrypointArgs:nil]; } - (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI initialRoute:(NSString*)initialRoute entrypointArgs:(NSArray<NSString*>*)entrypointArgs { if ([self createShell:entrypoint libraryURI:libraryURI initialRoute:initialRoute]) { [self launchEngine:entrypoint libraryURI:libraryURI entrypointArgs:entrypointArgs]; } return _shell != nullptr; } - (void)notifyLowMemory { if (_shell) { _shell->NotifyLowMemoryWarning(); } [_systemChannel sendMessage:@{@"type" : @"memoryPressure"}]; } #pragma mark - Text input delegate - (void)flutterTextInputView:(FlutterTextInputView*)textInputView updateEditingClient:(int)client withState:(NSDictionary*)state { [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingState" arguments:@[ @(client), state ]]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView updateEditingClient:(int)client withState:(NSDictionary*)state withTag:(NSString*)tag { [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingStateWithTag" arguments:@[ @(client), @{tag : state} ]]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView updateEditingClient:(int)client withDelta:(NSDictionary*)delta { [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingStateWithDeltas" arguments:@[ @(client), delta ]]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView updateFloatingCursor:(FlutterFloatingCursorDragState)state withClient:(int)client withPosition:(NSDictionary*)position { NSString* stateString; switch (state) { case FlutterFloatingCursorDragStateStart: stateString = @"FloatingCursorDragState.start"; break; case FlutterFloatingCursorDragStateUpdate: stateString = @"FloatingCursorDragState.update"; break; case FlutterFloatingCursorDragStateEnd: stateString = @"FloatingCursorDragState.end"; break; } [_textInputChannel.get() invokeMethod:@"TextInputClient.updateFloatingCursor" arguments:@[ @(client), stateString, position ]]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView performAction:(FlutterTextInputAction)action withClient:(int)client { NSString* actionString; switch (action) { case FlutterTextInputActionUnspecified: // Where did the term "unspecified" come from? iOS has a "default" and Android // has "unspecified." These 2 terms seem to mean the same thing but we need // to pick just one. "unspecified" was chosen because "default" is often a // reserved word in languages with switch statements (dart, java, etc). actionString = @"TextInputAction.unspecified"; break; case FlutterTextInputActionDone: actionString = @"TextInputAction.done"; break; case FlutterTextInputActionGo: actionString = @"TextInputAction.go"; break; case FlutterTextInputActionSend: actionString = @"TextInputAction.send"; break; case FlutterTextInputActionSearch: actionString = @"TextInputAction.search"; break; case FlutterTextInputActionNext: actionString = @"TextInputAction.next"; break; case FlutterTextInputActionContinue: actionString = @"TextInputAction.continueAction"; break; case FlutterTextInputActionJoin: actionString = @"TextInputAction.join"; break; case FlutterTextInputActionRoute: actionString = @"TextInputAction.route"; break; case FlutterTextInputActionEmergencyCall: actionString = @"TextInputAction.emergencyCall"; break; case FlutterTextInputActionNewline: actionString = @"TextInputAction.newline"; break; } [_textInputChannel.get() invokeMethod:@"TextInputClient.performAction" arguments:@[ @(client), actionString ]]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView showAutocorrectionPromptRectForStart:(NSUInteger)start end:(NSUInteger)end withClient:(int)client { [_textInputChannel.get() invokeMethod:@"TextInputClient.showAutocorrectionPromptRect" arguments:@[ @(client), @(start), @(end) ]]; } #pragma mark - FlutterViewEngineDelegate - (void)flutterTextInputView:(FlutterTextInputView*)textInputView showToolbar:(int)client { // TODO(justinmc): Switch from the TextInputClient to Scribble channel when // the framework has finished transitioning to the Scribble channel. // https://github.com/flutter/flutter/pull/115296 [_textInputChannel.get() invokeMethod:@"TextInputClient.showToolbar" arguments:@[ @(client) ]]; } - (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin focusElement:(UIScribbleElementIdentifier)elementIdentifier atPoint:(CGPoint)referencePoint result:(FlutterResult)callback { // TODO(justinmc): Switch from the TextInputClient to Scribble channel when // the framework has finished transitioning to the Scribble channel. // https://github.com/flutter/flutter/pull/115296 [_textInputChannel.get() invokeMethod:@"TextInputClient.focusElement" arguments:@[ elementIdentifier, @(referencePoint.x), @(referencePoint.y) ] result:callback]; } - (void)flutterTextInputPlugin:(FlutterTextInputPlugin*)textInputPlugin requestElementsInRect:(CGRect)rect result:(FlutterResult)callback { // TODO(justinmc): Switch from the TextInputClient to Scribble channel when // the framework has finished transitioning to the Scribble channel. // https://github.com/flutter/flutter/pull/115296 [_textInputChannel.get() invokeMethod:@"TextInputClient.requestElementsInRect" arguments:@[ @(rect.origin.x), @(rect.origin.y), @(rect.size.width), @(rect.size.height) ] result:callback]; } - (void)flutterTextInputViewScribbleInteractionBegan:(FlutterTextInputView*)textInputView { // TODO(justinmc): Switch from the TextInputClient to Scribble channel when // the framework has finished transitioning to the Scribble channel. // https://github.com/flutter/flutter/pull/115296 [_textInputChannel.get() invokeMethod:@"TextInputClient.scribbleInteractionBegan" arguments:nil]; } - (void)flutterTextInputViewScribbleInteractionFinished:(FlutterTextInputView*)textInputView { // TODO(justinmc): Switch from the TextInputClient to Scribble channel when // the framework has finished transitioning to the Scribble channel. // https://github.com/flutter/flutter/pull/115296 [_textInputChannel.get() invokeMethod:@"TextInputClient.scribbleInteractionFinished" arguments:nil]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView insertTextPlaceholderWithSize:(CGSize)size withClient:(int)client { // TODO(justinmc): Switch from the TextInputClient to Scribble channel when // the framework has finished transitioning to the Scribble channel. // https://github.com/flutter/flutter/pull/115296 [_textInputChannel.get() invokeMethod:@"TextInputClient.insertTextPlaceholder" arguments:@[ @(client), @(size.width), @(size.height) ]]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView removeTextPlaceholder:(int)client { // TODO(justinmc): Switch from the TextInputClient to Scribble channel when // the framework has finished transitioning to the Scribble channel. // https://github.com/flutter/flutter/pull/115296 [_textInputChannel.get() invokeMethod:@"TextInputClient.removeTextPlaceholder" arguments:@[ @(client) ]]; } - (void)flutterTextInputView:(FlutterTextInputView*)textInputView didResignFirstResponderWithTextInputClient:(int)client { // When flutter text input view resign first responder, send a message to // framework to ensure the focus state is correct. This is useful when close // keyboard from platform side. [_textInputChannel.get() invokeMethod:@"TextInputClient.onConnectionClosed" arguments:@[ @(client) ]]; // Platform view's first responder detection logic: // // All text input widgets (e.g. EditableText) are backed by a dummy UITextInput view // in the TextInputPlugin. When this dummy UITextInput view resigns first responder, // check if any platform view becomes first responder. If any platform view becomes // first responder, send a "viewFocused" channel message to inform the framework to un-focus // the previously focused text input. // // Caveat: // 1. This detection logic does not cover the scenario when a platform view becomes // first responder without any flutter text input resigning its first responder status // (e.g. user tapping on platform view first). For now it works fine because the TextInputPlugin // does not track the focused platform view id (which is different from Android implementation). // // 2. This detection logic assumes that all text input widgets are backed by a dummy // UITextInput view in the TextInputPlugin, which may not hold true in the future. // Have to check in the next run loop, because iOS requests the previous first responder to // resign before requesting the next view to become first responder. dispatch_async(dispatch_get_main_queue(), ^(void) { long platform_view_id = self.platformViewsController->FindFirstResponderPlatformViewId(); if (platform_view_id == -1) { return; } [_platformViewsChannel.get() invokeMethod:@"viewFocused" arguments:@(platform_view_id)]; }); } #pragma mark - Undo Manager Delegate - (void)flutterUndoManagerPlugin:(FlutterUndoManagerPlugin*)undoManagerPlugin handleUndoWithDirection:(FlutterUndoRedoDirection)direction { NSString* action = (direction == FlutterUndoRedoDirectionUndo) ? @"undo" : @"redo"; [_undoManagerChannel.get() invokeMethod:@"UndoManagerClient.handleUndo" arguments:@[ action ]]; } #pragma mark - Screenshot Delegate - (flutter::Rasterizer::Screenshot)takeScreenshot:(flutter::Rasterizer::ScreenshotType)type asBase64Encoded:(BOOL)base64Encode { FML_DCHECK(_shell) << "Cannot takeScreenshot without a shell"; return _shell->Screenshot(type, base64Encode); } - (void)flutterViewAccessibilityDidCall { if (self.viewController.view.accessibilityElements == nil) { [self ensureSemanticsEnabled]; } } - (NSObject<FlutterBinaryMessenger>*)binaryMessenger { return _binaryMessenger; } - (NSObject<FlutterTextureRegistry>*)textureRegistry { return _textureRegistry; } // For test only. Ideally we should create a dependency injector for all dependencies and // remove this. - (void)setBinaryMessenger:(FlutterBinaryMessengerRelay*)binaryMessenger { // Discard the previous messenger and keep the new one. if (binaryMessenger != _binaryMessenger) { _binaryMessenger.parent = nil; [_binaryMessenger release]; _binaryMessenger = [binaryMessenger retain]; } } #pragma mark - FlutterBinaryMessenger - (void)sendOnChannel:(NSString*)channel message:(NSData*)message { [self sendOnChannel:channel message:message binaryReply:nil]; } - (void)sendOnChannel:(NSString*)channel message:(NSData*)message binaryReply:(FlutterBinaryReply)callback { NSParameterAssert(channel); NSAssert(_shell && _shell->IsSetup(), @"Sending a message before the FlutterEngine has been run."); fml::RefPtr<flutter::PlatformMessageResponseDarwin> response = (callback == nil) ? nullptr : fml::MakeRefCounted<flutter::PlatformMessageResponseDarwin>( ^(NSData* reply) { callback(reply); }, _shell->GetTaskRunners().GetPlatformTaskRunner()); std::unique_ptr<flutter::PlatformMessage> platformMessage = (message == nil) ? std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response) : std::make_unique<flutter::PlatformMessage>( channel.UTF8String, flutter::CopyNSDataToMapping(message), response); _shell->GetPlatformView()->DispatchPlatformMessage(std::move(platformMessage)); // platformMessage takes ownership of response. // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) } - (NSObject<FlutterTaskQueue>*)makeBackgroundTaskQueue { return flutter::PlatformMessageHandlerIos::MakeBackgroundTaskQueue(); } - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel binaryMessageHandler: (FlutterBinaryMessageHandler)handler { return [self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil]; } - (FlutterBinaryMessengerConnection) setMessageHandlerOnChannel:(NSString*)channel binaryMessageHandler:(FlutterBinaryMessageHandler)handler taskQueue:(NSObject<FlutterTaskQueue>* _Nullable)taskQueue { NSParameterAssert(channel); if (_shell && _shell->IsSetup()) { self.iosPlatformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.UTF8String, handler, taskQueue); return _connections->AquireConnection(channel.UTF8String); } else { NSAssert(!handler, @"Setting a message handler before the FlutterEngine has been run."); // Setting a handler to nil for a channel that has not yet been set up is a no-op. return flutter::ConnectionCollection::MakeErrorConnection(-1); } } - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { if (_shell && _shell->IsSetup()) { std::string channel = _connections->CleanupConnection(connection); if (!channel.empty()) { self.iosPlatformView->GetPlatformMessageHandlerIos()->SetMessageHandler(channel.c_str(), nil, nil); } } } #pragma mark - FlutterTextureRegistry - (int64_t)registerTexture:(NSObject<FlutterTexture>*)texture { int64_t textureId = _nextTextureId++; self.iosPlatformView->RegisterExternalTexture(textureId, texture); return textureId; } - (void)unregisterTexture:(int64_t)textureId { _shell->GetPlatformView()->UnregisterTexture(textureId); } - (void)textureFrameAvailable:(int64_t)textureId { _shell->GetPlatformView()->MarkTextureFrameAvailable(textureId); } - (NSString*)lookupKeyForAsset:(NSString*)asset { return [FlutterDartProject lookupKeyForAsset:asset]; } - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package]; } - (id<FlutterPluginRegistry>)pluginRegistry { return self; } #pragma mark - FlutterPluginRegistry - (NSObject<FlutterPluginRegistrar>*)registrarForPlugin:(NSString*)pluginKey { NSAssert(self.pluginPublications[pluginKey] == nil, @"Duplicate plugin key: %@", pluginKey); self.pluginPublications[pluginKey] = [NSNull null]; FlutterEngineRegistrar* result = [[FlutterEngineRegistrar alloc] initWithPlugin:pluginKey flutterEngine:self]; self.registrars[pluginKey] = result; return [result autorelease]; } - (BOOL)hasPlugin:(NSString*)pluginKey { return _pluginPublications[pluginKey] != nil; } - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey { return _pluginPublications[pluginKey]; } #pragma mark - Notifications #if APPLICATION_EXTENSION_API_ONLY - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { [self flutterWillEnterForeground:notification]; } - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) { [self flutterDidEnterBackground:notification]; } #else - (void)applicationWillEnterForeground:(NSNotification*)notification { [self flutterWillEnterForeground:notification]; } - (void)applicationDidEnterBackground:(NSNotification*)notification { [self flutterDidEnterBackground:notification]; } #endif - (void)flutterWillEnterForeground:(NSNotification*)notification { [self setIsGpuDisabled:NO]; } - (void)flutterDidEnterBackground:(NSNotification*)notification { [self setIsGpuDisabled:YES]; [self notifyLowMemory]; } - (void)onMemoryWarning:(NSNotification*)notification { [self notifyLowMemory]; } - (void)setIsGpuDisabled:(BOOL)value { if (_shell) { _shell->SetGpuAvailability(value ? flutter::GpuAvailability::kUnavailable : flutter::GpuAvailability::kAvailable); } _isGpuDisabled = value; } #pragma mark - Locale updates - (void)onLocaleUpdated:(NSNotification*)notification { // Get and pass the user's preferred locale list to dart:ui. NSMutableArray<NSString*>* localeData = [[[NSMutableArray alloc] init] autorelease]; NSArray<NSString*>* preferredLocales = [NSLocale preferredLanguages]; for (NSString* localeID in preferredLocales) { NSLocale* locale = [[[NSLocale alloc] initWithLocaleIdentifier:localeID] autorelease]; NSString* languageCode = [locale objectForKey:NSLocaleLanguageCode]; NSString* countryCode = [locale objectForKey:NSLocaleCountryCode]; NSString* scriptCode = [locale objectForKey:NSLocaleScriptCode]; NSString* variantCode = [locale objectForKey:NSLocaleVariantCode]; if (!languageCode) { continue; } [localeData addObject:languageCode]; [localeData addObject:(countryCode ? countryCode : @"")]; [localeData addObject:(scriptCode ? scriptCode : @"")]; [localeData addObject:(variantCode ? variantCode : @"")]; } if (localeData.count == 0) { return; } [self.localizationChannel invokeMethod:@"setLocale" arguments:localeData]; } - (void)waitForFirstFrame:(NSTimeInterval)timeout callback:(void (^_Nonnull)(BOOL didTimeout))callback { dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0); dispatch_async(queue, ^{ fml::TimeDelta waitTime = fml::TimeDelta::FromMilliseconds(timeout * 1000); BOOL didTimeout = self.shell.WaitForFirstFrame(waitTime).code() == fml::StatusCode::kDeadlineExceeded; dispatch_async(dispatch_get_main_queue(), ^{ callback(didTimeout); }); }); } - (FlutterEngine*)spawnWithEntrypoint:(/*nullable*/ NSString*)entrypoint libraryURI:(/*nullable*/ NSString*)libraryURI initialRoute:(/*nullable*/ NSString*)initialRoute entrypointArgs:(/*nullable*/ NSArray<NSString*>*)entrypointArgs { NSAssert(_shell, @"Spawning from an engine without a shell (possibly not run)."); FlutterEngine* result = [[FlutterEngine alloc] initWithName:_labelPrefix project:_dartProject.get() allowHeadlessExecution:_allowHeadlessExecution]; flutter::RunConfiguration configuration = [_dartProject.get() runConfigurationForEntrypoint:entrypoint libraryOrNil:libraryURI entrypointArgs:entrypointArgs]; fml::WeakPtr<flutter::PlatformView> platform_view = _shell->GetPlatformView(); FML_DCHECK(platform_view); // Static-cast safe since this class always creates PlatformViewIOS instances. flutter::PlatformViewIOS* ios_platform_view = static_cast<flutter::PlatformViewIOS*>(platform_view.get()); std::shared_ptr<flutter::IOSContext> context = ios_platform_view->GetIosContext(); FML_DCHECK(context); // Lambda captures by pointers to ObjC objects are fine here because the // create call is synchronous. flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view = [result, context](flutter::Shell& shell) { [result recreatePlatformViewController]; return std::make_unique<flutter::PlatformViewIOS>( shell, context, result->_platformViewsController, shell.GetTaskRunners()); }; flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer = [](flutter::Shell& shell) { return std::make_unique<flutter::Rasterizer>(shell); }; std::string cppInitialRoute; if (initialRoute) { cppInitialRoute = [initialRoute UTF8String]; } std::unique_ptr<flutter::Shell> shell = _shell->Spawn( std::move(configuration), cppInitialRoute, on_create_platform_view, on_create_rasterizer); result->_threadHost = _threadHost; result->_profiler = _profiler; result->_profiler_metrics = _profiler_metrics; result->_isGpuDisabled = _isGpuDisabled; [result setUpShell:std::move(shell) withVMServicePublication:NO]; return [result autorelease]; } - (const flutter::ThreadHost&)threadHost { return *_threadHost; } - (FlutterDartProject*)project { return _dartProject.get(); } - (BOOL)isUsingImpeller { return self.project.isImpellerEnabled; } @end @implementation FlutterEngineRegistrar { NSString* _pluginKey; } - (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine { self = [super init]; NSAssert(self, @"Super init cannot be nil"); _pluginKey = [pluginKey copy]; _flutterEngine = flutterEngine; return self; } - (void)dealloc { [_pluginKey release]; [super dealloc]; } - (NSObject<FlutterBinaryMessenger>*)messenger { return _flutterEngine.binaryMessenger; } - (NSObject<FlutterTextureRegistry>*)textures { return _flutterEngine.textureRegistry; } - (void)publish:(NSObject*)value { _flutterEngine.pluginPublications[_pluginKey] = value; } - (void)addMethodCallDelegate:(NSObject<FlutterPlugin>*)delegate channel:(FlutterMethodChannel*)channel { [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { [delegate handleMethodCall:call result:result]; }]; } - (void)addApplicationDelegate:(NSObject<FlutterPlugin>*)delegate NS_EXTENSION_UNAVAILABLE_IOS("Disallowed in plugins used in app extensions") { id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate]; if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifeCycleProvider)]) { id<FlutterAppLifeCycleProvider> lifeCycleProvider = (id<FlutterAppLifeCycleProvider>)appDelegate; [lifeCycleProvider addApplicationLifeCycleDelegate:delegate]; } } - (NSString*)lookupKeyForAsset:(NSString*)asset { return [_flutterEngine lookupKeyForAsset:asset]; } - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package { return [_flutterEngine lookupKeyForAsset:asset fromPackage:package]; } - (void)registerViewFactory:(NSObject<FlutterPlatformViewFactory>*)factory withId:(NSString*)factoryId { [self registerViewFactory:factory withId:factoryId gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; } - (void)registerViewFactory:(NSObject<FlutterPlatformViewFactory>*)factory withId:(NSString*)factoryId gestureRecognizersBlockingPolicy: (FlutterPlatformViewGestureRecognizersBlockingPolicy)gestureRecognizersBlockingPolicy { [_flutterEngine platformViewsController]->RegisterViewFactory(factory, factoryId, gestureRecognizersBlockingPolicy); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm", "repo_id": "engine", "token_count": 23068 }
378
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERMETALLAYER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERMETALLAYER_H_ #import <QuartzCore/QuartzCore.h> /// Drop-in replacement (as far as Flutter is concerned) for CAMetalLayer /// that can present with transaction from a background thread. @interface FlutterMetalLayer : CALayer @property(nullable, retain) id<MTLDevice> device; @property(nullable, readonly) id<MTLDevice> preferredDevice; @property MTLPixelFormat pixelFormat; @property BOOL framebufferOnly; @property CGSize drawableSize; @property BOOL presentsWithTransaction; @property(nullable) CGColorSpaceRef colorspace; @property BOOL wantsExtendedDynamicRangeContent; - (nullable id<CAMetalDrawable>)nextDrawable; /// Returns whether the Metal layer is enabled. /// This is controlled by FLTUseFlutterMetalLayer value in Info.plist. + (BOOL)enabled; @end @protocol MTLCommandBuffer; @protocol FlutterMetalDrawable <CAMetalDrawable> /// In order for FlutterMetalLayer to provide back pressure it must have access /// to the command buffer that is used to render into the drawable to schedule /// a completion handler. /// This method must be called before the command buffer is committed. - (void)flutterPrepareForPresent:(nonnull id<MTLCommandBuffer>)commandBuffer; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERMETALLAYER_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h", "repo_id": "engine", "token_count": 496 }
379
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h" #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #include "flutter/fml/logging.h" FLUTTER_ASSERT_NOT_ARC @interface FlutterRestorationPlugin () @property(nonatomic, copy) FlutterResult pendingRequest; @end @implementation FlutterRestorationPlugin { BOOL _waitForData; BOOL _restorationEnabled; } - (instancetype)initWithChannel:(FlutterMethodChannel*)channel restorationEnabled:(BOOL)restorationEnabled { FML_DCHECK(channel) << "channel must be set"; self = [super init]; if (self) { [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { [self handleMethodCall:call result:result]; }]; _restorationEnabled = restorationEnabled; _waitForData = restorationEnabled; } return self; } - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { if ([[call method] isEqualToString:@"put"]) { NSAssert(self.pendingRequest == nil, @"Cannot put data while a get request is pending."); FlutterStandardTypedData* data = [call arguments]; self.restorationData = [data data]; result(nil); } else if ([[call method] isEqualToString:@"get"]) { if (!_restorationEnabled || !_waitForData) { result([self dataForFramework]); return; } NSAssert(self.pendingRequest == nil, @"There can only be one pending request."); self.pendingRequest = result; } else { result(FlutterMethodNotImplemented); } } - (void)setRestorationData:(NSData*)data { if (data != _restorationData) { [_restorationData release]; _restorationData = [data retain]; } _waitForData = NO; if (self.pendingRequest != nil) { self.pendingRequest([self dataForFramework]); self.pendingRequest = nil; } } - (void)markRestorationComplete { _waitForData = NO; if (self.pendingRequest != nil) { NSAssert(_restorationEnabled, @"No request can be pending when restoration is disabled."); self.pendingRequest([self dataForFramework]); self.pendingRequest = nil; } } - (void)reset { self.pendingRequest = nil; self.restorationData = nil; } - (NSDictionary*)dataForFramework { if (!_restorationEnabled) { return @{@"enabled" : @NO}; } if (self.restorationData == nil) { return @{@"enabled" : @YES}; } return @{ @"enabled" : @YES, @"data" : [FlutterStandardTypedData typedDataWithBytes:self.restorationData] }; } - (void)dealloc { [_restorationData release]; [_pendingRequest release]; [super dealloc]; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.mm", "repo_id": "engine", "token_count": 972 }
380
// Copyright 2013 The Flutter 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 <UIKit/UIKit.h> #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" @interface FlutterUIPressProxy () @property(nonatomic, readonly) UIPress* press; @property(nonatomic, readonly) UIEvent* event; @end @implementation FlutterUIPressProxy - (instancetype)initWithPress:(UIPress*)press withEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) { self = [super init]; if (self) { _press = press; _event = event; } return self; } - (UIPressPhase)phase API_AVAILABLE(ios(13.4)) { return _press.phase; } - (UIKey*)key API_AVAILABLE(ios(13.4)) { return _press.key; } - (UIEventType)type API_AVAILABLE(ios(13.4)) { return _event.type; } - (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) { return _event.timestamp; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm", "repo_id": "engine", "token_count": 362 }
381
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECT_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECT_H_ #import <UIKit/UIKit.h> #include "flutter/fml/macros.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/lib/ui/semantics/semantics_node.h" #import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h" constexpr int32_t kRootNodeId = 0; // This can be arbitrary number as long as it is bigger than 0. constexpr float kScrollExtentMaxForInf = 1000; @class FlutterCustomAccessibilityAction; @class FlutterPlatformViewSemanticsContainer; @class FlutterTouchInterceptingView; /** * A node in the iOS semantics tree. This object is a wrapper over a native accessibiliy * object, which is stored in the property `nativeAccessibility`. In the most case, the * `nativeAccessibility` directly returns this object. Some subclasses such as the * `FlutterScrollableSemanticsObject` creates a native `UIScrollView` as its `nativeAccessibility` * so that it can interact with iOS. */ @interface SemanticsObject : UIAccessibilityElement /** * The globally unique identifier for this node. */ @property(nonatomic, readonly) int32_t uid; /** * The parent of this node in the node tree. Will be nil for the root node and * during transient state changes. */ @property(nonatomic, assign) SemanticsObject* parent; /** * The accessibility bridge that this semantics object is attached to. This * object may use the bridge to access contextual application information. A weak * pointer is used because the platform view owns the accessibility bridge. * If you are referencing this property from an iOS callback, be sure to * use `isAccessibilityBridgeActive` to protect against the case where this * node may be orphaned. */ @property(nonatomic, readonly) fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge; /** * The semantics node used to produce this semantics object. */ @property(nonatomic, readonly) flutter::SemanticsNode node; /** * Whether this semantics object has child semantics objects. */ @property(nonatomic, readonly) BOOL hasChildren; /** * Direct children of this semantics object. Each child's `parent` property must * be equal to this object. */ @property(nonatomic, strong) NSArray<SemanticsObject*>* children; /** * Direct children of this semantics object in hit test order. Each child's `parent` property * must be equal to this object. */ @property(nonatomic, strong) NSArray<SemanticsObject*>* childrenInHitTestOrder; /** * The UIAccessibility that represents this object. * * By default, this return self. Subclasses can override to return different * objects to represent them. For example, FlutterScrollableSemanticsObject[s] * maintain UIScrollView[s] to represent their UIAccessibility[s]. */ @property(nonatomic, readonly) id nativeAccessibility; /** * Due to the fact that VoiceOver may hold onto SemanticObjects even after it shuts down, * there can be situations where the AccessibilityBridge is shutdown, but the SemanticObject * will still be alive. If VoiceOver is turned on again, it may try to access this orphaned * SemanticObject. Methods that are called from the accessiblity framework should use * this to guard against this case by just returning early if its bridge has been shutdown. * * See https://github.com/flutter/flutter/issues/43795 for more information. */ - (BOOL)isAccessibilityBridgeAlive; /** * Updates this semantics object using data from the `node` argument. */ - (void)setSemanticsNode:(const flutter::SemanticsNode*)node NS_REQUIRES_SUPER; - (void)replaceChildAtIndex:(NSInteger)index withChild:(SemanticsObject*)child; - (BOOL)nodeWillCauseLayoutChange:(const flutter::SemanticsNode*)node; - (BOOL)nodeWillCauseScroll:(const flutter::SemanticsNode*)node; - (BOOL)nodeShouldTriggerAnnouncement:(const flutter::SemanticsNode*)node; - (void)collectRoutes:(NSMutableArray<SemanticsObject*>*)edges; - (NSString*)routeName; - (BOOL)onCustomAccessibilityAction:(FlutterCustomAccessibilityAction*)action; /** * Called after accessibility bridge finishes a semantics update. * * Subclasses can override this method if they contain states that can only be * updated once every node in the accessibility tree has finished updating. */ - (void)accessibilityBridgeDidFinishUpdate; #pragma mark - Designated initializers - (instancetype)init __attribute__((unavailable("Use initWithBridge instead"))); - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge uid:(int32_t)uid NS_DESIGNATED_INITIALIZER; @end /** * An implementation of UIAccessibilityCustomAction which also contains the * Flutter uid. */ @interface FlutterCustomAccessibilityAction : UIAccessibilityCustomAction /** * The uid of the action defined by the flutter application. */ @property(nonatomic) int32_t uid; @end /** * The default implementation of `SemanticsObject` for most accessibility elements * in the iOS accessibility tree. * * Use this implementation for nodes that do not need to be expressed via UIKit-specific * protocols (it only implements NSObject). * * See also: * * TextInputSemanticsObject, which implements `UITextInput` protocol to expose * editable text widgets to a11y. */ @interface FlutterSemanticsObject : SemanticsObject @end /** * Designated to act as an accessibility container of a platform view. * * This object does not take any accessibility actions on its own, nor has any accessibility * label/value/trait/hint... on its own. The accessibility data will be handled by the platform * view. * * See also: * * `SemanticsObject` for the other type of semantics objects. * * `FlutterSemanticsObject` for default implementation of `SemanticsObject`. */ @interface FlutterPlatformViewSemanticsContainer : SemanticsObject - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge uid:(int32_t)uid NS_UNAVAILABLE; - (instancetype)initWithBridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge uid:(int32_t)uid platformView:(FlutterTouchInterceptingView*)platformView NS_DESIGNATED_INITIALIZER; @end /// The semantics object for switch buttons. This class creates an UISwitch to interact with the /// iOS. @interface FlutterSwitchSemanticsObject : SemanticsObject @end /// The semantics object for scrollable. This class creates an UIScrollView to interact with the /// iOS. @interface FlutterScrollableSemanticsObject : SemanticsObject @end /** * Represents a semantics object that has children and hence has to be presented to the OS as a * UIAccessibilityContainer. * * The SemanticsObject class cannot implement the UIAccessibilityContainer protocol because an * object that returns YES for isAccessibilityElement cannot also implement * UIAccessibilityContainer. * * With the help of SemanticsObjectContainer, the hierarchy of semantic objects received from * the framework, such as: * * SemanticsObject1 * SemanticsObject2 * SemanticsObject3 * SemanticsObject4 * * is translated into the following hierarchy, which is understood by iOS: * * SemanticsObjectContainer1 * SemanticsObject1 * SemanticsObjectContainer2 * SemanticsObject2 * SemanticsObject3 * SemanticsObject4 * * From Flutter's view of the world (the first tree seen above), we construct iOS's view of the * world (second tree) as follows: We replace each SemanticsObjects that has children with a * SemanticsObjectContainer, which has the original SemanticsObject and its children as children. * * SemanticsObjects have semantic information attached to them which is interpreted by * VoiceOver (they return YES for isAccessibilityElement). The SemanticsObjectContainers are just * there for structure and they don't provide any semantic information to VoiceOver (they return * NO for isAccessibilityElement). */ @interface SemanticsObjectContainer : UIAccessibilityElement - (instancetype)init NS_UNAVAILABLE; + (instancetype)new NS_UNAVAILABLE; - (instancetype)initWithAccessibilityContainer:(id)container NS_UNAVAILABLE; - (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject bridge:(fml::WeakPtr<flutter::AccessibilityBridgeIos>)bridge NS_DESIGNATED_INITIALIZER; @property(nonatomic, weak) SemanticsObject* semanticsObject; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECT_H_
engine/shell/platform/darwin/ios/framework/Source/SemanticsObject.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/SemanticsObject.h", "repo_id": "engine", "token_count": 2576 }
382
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Source/connection_collection.h" namespace flutter { ConnectionCollection::Connection ConnectionCollection::AquireConnection(const std::string& name) { Connection nextConnection = ++counter_; connections_[name] = nextConnection; return nextConnection; } std::string ConnectionCollection::CleanupConnection(ConnectionCollection::Connection connection) { if (connection > 0) { std::string channel; for (auto& keyValue : connections_) { if (keyValue.second == connection) { channel = keyValue.first; break; } } if (channel.length() > 0) { connections_.erase(channel); return channel; } } return ""; } bool ConnectionCollection::IsValidConnection(ConnectionCollection::Connection connection) { return connection > 0; } ConnectionCollection::Connection ConnectionCollection::MakeErrorConnection(int errCode) { if (errCode < 0) { return -1 * errCode; } return errCode; } } // namespace flutter
engine/shell/platform/darwin/ios/framework/Source/connection_collection.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/connection_collection.mm", "repo_id": "engine", "token_count": 364 }
383
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/ios_context_software.h" #include "ios_context.h" namespace flutter { IOSContextSoftware::IOSContextSoftware() : IOSContext(MsaaSampleCount::kNone) {} // |IOSContext| IOSContextSoftware::~IOSContextSoftware() = default; // |IOSContext| sk_sp<GrDirectContext> IOSContextSoftware::CreateResourceContext() { return nullptr; } // |IOSContext| sk_sp<GrDirectContext> IOSContextSoftware::GetMainContext() const { return nullptr; } // |IOSContext| std::unique_ptr<GLContextResult> IOSContextSoftware::MakeCurrent() { // This only makes sense for context that need to be bound to a specific thread. return std::make_unique<GLContextDefaultResult>(false); } // |IOSContext| std::unique_ptr<Texture> IOSContextSoftware::CreateExternalTexture( int64_t texture_id, fml::scoped_nsobject<NSObject<FlutterTexture>> texture) { // Don't use FML for logging as it will contain engine specific details. This is a user facing // message. NSLog(@"Flutter: Attempted to composite external texture sources using the software backend. " @"This backend is only used on simulators. This feature is only available on actual " @"devices where OpenGL or Metal is used for rendering."); // Not supported in this backend. return nullptr; } } // namespace flutter
engine/shell/platform/darwin/ios/ios_context_software.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_context_software.mm", "repo_id": "engine", "token_count": 455 }
384
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_VIEW_IOS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_VIEW_IOS_H_ #include <memory> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/fml/platform/darwin/weak_nsobject.h" #include "flutter/shell/common/platform_view.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" #import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h" #import "flutter/shell/platform/darwin/ios/ios_context.h" #import "flutter/shell/platform/darwin/ios/ios_external_view_embedder.h" #import "flutter/shell/platform/darwin/ios/ios_surface.h" #import "flutter/shell/platform/darwin/ios/platform_message_handler_ios.h" #import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" @class FlutterViewController; namespace flutter { /** * A bridge connecting the platform agnostic shell and the iOS embedding. * * The shell provides and requests for UI related data and this PlatformView subclass fulfills * it with iOS specific capabilities. As an example, the iOS embedding (the `FlutterEngine` and the * `FlutterViewController`) sends pointer data to the shell and receives the shell's request for a * Skia GrDirectContext and supplies it. * * Despite the name "view", this class is unrelated to UIViews on iOS and doesn't have the same * lifecycle. It's a long lived bridge owned by the `FlutterEngine` and can be attached and * detached sequentially to multiple `FlutterViewController`s and `FlutterView`s. */ class PlatformViewIOS final : public PlatformView { public: PlatformViewIOS(PlatformView::Delegate& delegate, const std::shared_ptr<IOSContext>& context, const std::shared_ptr<FlutterPlatformViewsController>& platform_views_controller, const flutter::TaskRunners& task_runners); explicit PlatformViewIOS( PlatformView::Delegate& delegate, IOSRenderingAPI rendering_api, const std::shared_ptr<FlutterPlatformViewsController>& platform_views_controller, const flutter::TaskRunners& task_runners, const std::shared_ptr<fml::ConcurrentTaskRunner>& worker_task_runner, const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch); ~PlatformViewIOS() override; /** * Returns the `FlutterViewController` currently attached to the `FlutterEngine` owning * this PlatformViewIOS. */ fml::WeakNSObject<FlutterViewController> GetOwnerViewController() const; /** * Updates the `FlutterViewController` currently attached to the `FlutterEngine` owning * this PlatformViewIOS. This should be updated when the `FlutterEngine` * is given a new `FlutterViewController`. */ void SetOwnerViewController(const fml::WeakNSObject<FlutterViewController>& owner_controller); /** * Called one time per `FlutterViewController` when the `FlutterViewController`'s * UIView is first loaded. * * Can be used to perform late initialization after `FlutterViewController`'s * init. */ void attachView(); /** * Called through when an external texture such as video or camera is * given to the `FlutterEngine` or `FlutterViewController`. */ void RegisterExternalTexture(int64_t id, NSObject<FlutterTexture>* texture); // |PlatformView| PointerDataDispatcherMaker GetDispatcherMaker() override; // |PlatformView| void SetSemanticsEnabled(bool enabled) override; /** Accessor for the `IOSContext` associated with the platform view. */ const std::shared_ptr<IOSContext>& GetIosContext() { return ios_context_; } std::shared_ptr<PlatformMessageHandlerIos> GetPlatformMessageHandlerIos() const { return platform_message_handler_; } std::shared_ptr<PlatformMessageHandler> GetPlatformMessageHandler() const override { return platform_message_handler_; } private: /// Smart pointer for use with objective-c observers. /// This guarantees we remove the observer. class ScopedObserver { public: ScopedObserver(); ~ScopedObserver(); void reset(id<NSObject> observer); ScopedObserver(const ScopedObserver&) = delete; ScopedObserver& operator=(const ScopedObserver&) = delete; private: id<NSObject> observer_ = nil; }; /// Wrapper that guarantees we communicate clearing Accessibility /// information to Dart. class AccessibilityBridgeManager { public: explicit AccessibilityBridgeManager(const std::function<void(bool)>& set_semantics_enabled); AccessibilityBridgeManager(const std::function<void(bool)>& set_semantics_enabled, AccessibilityBridge* bridge); explicit operator bool() const noexcept { return static_cast<bool>(accessibility_bridge_); } AccessibilityBridge* get() const noexcept { return accessibility_bridge_.get(); } void Set(std::unique_ptr<AccessibilityBridge> bridge); void Clear(); private: FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridgeManager); std::unique_ptr<AccessibilityBridge> accessibility_bridge_; std::function<void(bool)> set_semantics_enabled_; }; fml::WeakNSObject<FlutterViewController> owner_controller_; // Since the `ios_surface_` is created on the platform thread but // used on the raster thread we need to protect it with a mutex. std::mutex ios_surface_mutex_; std::unique_ptr<IOSSurface> ios_surface_; std::shared_ptr<IOSContext> ios_context_; const std::shared_ptr<FlutterPlatformViewsController>& platform_views_controller_; AccessibilityBridgeManager accessibility_bridge_; fml::scoped_nsprotocol<FlutterTextInputPlugin*> text_input_plugin_; ScopedObserver dealloc_view_controller_observer_; std::vector<std::string> platform_resolved_locale_; std::shared_ptr<PlatformMessageHandlerIos> platform_message_handler_; // |PlatformView| void HandlePlatformMessage(std::unique_ptr<flutter::PlatformMessage> message) override; // |PlatformView| std::unique_ptr<Surface> CreateRenderingSurface() override; // |PlatformView| std::shared_ptr<ExternalViewEmbedder> CreateExternalViewEmbedder() override; // |PlatformView| sk_sp<GrDirectContext> CreateResourceContext() const override; // |PlatformView| std::shared_ptr<impeller::Context> GetImpellerContext() const override; // |PlatformView| void SetAccessibilityFeatures(int32_t flags) override; // |PlatformView| void UpdateSemantics(flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) override; // |PlatformView| std::unique_ptr<VsyncWaiter> CreateVSyncWaiter() override; // |PlatformView| void OnPreEngineRestart() const override; // |PlatformView| std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data) override; FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewIOS); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_PLATFORM_VIEW_IOS_H_
engine/shell/platform/darwin/ios/platform_view_ios.h/0
{ "file_path": "engine/shell/platform/darwin/ios/platform_view_ios.h", "repo_id": "engine", "token_count": 2389 }
385
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #include "flutter/shell/platform/embedder/embedder.h" namespace flutter { // Native mac notifications fired. These notifications are not publicly documented. static NSString* const kAccessibilityLoadCompleteNotification = @"AXLoadComplete"; static NSString* const kAccessibilityInvalidStatusChangedNotification = @"AXInvalidStatusChanged"; static NSString* const kAccessibilityLiveRegionCreatedNotification = @"AXLiveRegionCreated"; static NSString* const kAccessibilityLiveRegionChangedNotification = @"AXLiveRegionChanged"; static NSString* const kAccessibilityExpandedChanged = @"AXExpandedChanged"; static NSString* const kAccessibilityMenuItemSelectedNotification = @"AXMenuItemSelected"; AccessibilityBridgeMac::AccessibilityBridgeMac(__weak FlutterEngine* flutter_engine, __weak FlutterViewController* view_controller) : flutter_engine_(flutter_engine), view_controller_(view_controller) {} void AccessibilityBridgeMac::OnAccessibilityEvent( ui::AXEventGenerator::TargetedEvent targeted_event) { if (!view_controller_.viewLoaded || !view_controller_.view.window) { // Don't need to send accessibility events if the there is no view or window. return; } ui::AXNode* ax_node = targeted_event.node; std::vector<AccessibilityBridgeMac::NSAccessibilityEvent> events = MacOSEventsFromAXEvent(targeted_event.event_params.event, *ax_node); for (const AccessibilityBridgeMac::NSAccessibilityEvent& event : events) { if (event.user_info != nil) { DispatchMacOSNotificationWithUserInfo(event.target, event.name, event.user_info); } else { DispatchMacOSNotification(event.target, event.name); } } } std::vector<AccessibilityBridgeMac::NSAccessibilityEvent> AccessibilityBridgeMac::MacOSEventsFromAXEvent(ui::AXEventGenerator::Event event_type, const ui::AXNode& ax_node) const { // Gets the native_node with the node_id. NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); auto platform_node_delegate = GetFlutterPlatformNodeDelegateFromID(ax_node.id()).lock(); NSCAssert(platform_node_delegate, @"Event target must exist in accessibility bridge."); auto mac_platform_node_delegate = std::static_pointer_cast<FlutterPlatformNodeDelegateMac>(platform_node_delegate); gfx::NativeViewAccessible native_node = mac_platform_node_delegate->GetNativeViewAccessible(); std::vector<AccessibilityBridgeMac::NSAccessibilityEvent> events; switch (event_type) { case ui::AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED: if (ax_node.data().role == ax::mojom::Role::kTree) { events.push_back({ .name = NSAccessibilitySelectedRowsChangedNotification, .target = native_node, .user_info = nil, }); } else if (ax_node.data().role == ax::mojom::Role::kTextFieldWithComboBox) { // Even though the selected item in the combo box has changed, don't // post a focus change because this will take the focus out of // the combo box where the user might be typing. events.push_back({ .name = NSAccessibilitySelectedChildrenChangedNotification, .target = native_node, .user_info = nil, }); } // In all other cases, this delegate should post // |NSAccessibilityFocusedUIElementChangedNotification|, but this is // handled elsewhere. break; case ui::AXEventGenerator::Event::LOAD_COMPLETE: events.push_back({ .name = kAccessibilityLoadCompleteNotification, .target = native_node, .user_info = nil, }); break; case ui::AXEventGenerator::Event::INVALID_STATUS_CHANGED: events.push_back({ .name = kAccessibilityInvalidStatusChangedNotification, .target = native_node, .user_info = nil, }); break; case ui::AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED: if (ui::IsTableLike(ax_node.data().role)) { events.push_back({ .name = NSAccessibilitySelectedRowsChangedNotification, .target = native_node, .user_info = nil, }); } else { // VoiceOver does not read anything if selection changes on the // currently focused object, and the focus did not move. Fire a // selection change if the focus did not change. NSAccessibilityElement* native_accessibility_node = (NSAccessibilityElement*)native_node; if (native_accessibility_node.accessibilityFocusedUIElement && ax_node.data().HasState(ax::mojom::State::kMultiselectable) && !HasPendingEvent(ui::AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED) && !HasPendingEvent(ui::AXEventGenerator::Event::FOCUS_CHANGED)) { // Don't fire selected children change, it will sometimes override // announcement of current focus. break; } events.push_back({ .name = NSAccessibilitySelectedChildrenChangedNotification, .target = native_node, .user_info = nil, }); } break; case ui::AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED: { id focused = mac_platform_node_delegate->GetFocus(); if ([focused isKindOfClass:[FlutterTextField class]]) { // If it is a text field, the selection notifications are handled by // the FlutterTextField directly. Only need to make sure it is the // first responder. FlutterTextField* native_text_field = (FlutterTextField*)focused; if (native_text_field == mac_platform_node_delegate->GetFocus()) { [native_text_field startEditing]; } break; } // This event always fires at root events.push_back({ .name = NSAccessibilitySelectedTextChangedNotification, .target = native_node, .user_info = nil, }); // WebKit fires a notification both on the focused object and the page // root. const ui::AXTreeData& tree_data = GetAXTreeData(); int32_t focus = tree_data.focus_id; if (focus == ui::AXNode::kInvalidAXID || focus != tree_data.sel_anchor_object_id) { break; // Just fire a notification on the root. } auto focus_node = GetFlutterPlatformNodeDelegateFromID(focus).lock(); if (!focus_node) { break; // Just fire a notification on the root. } events.push_back({ .name = NSAccessibilitySelectedTextChangedNotification, .target = focus_node->GetNativeViewAccessible(), .user_info = nil, }); break; } case ui::AXEventGenerator::Event::CHECKED_STATE_CHANGED: events.push_back({ .name = NSAccessibilityValueChangedNotification, .target = native_node, .user_info = nil, }); break; case ui::AXEventGenerator::Event::VALUE_CHANGED: { if (ax_node.data().role == ax::mojom::Role::kTextField) { // If it is a text field, the value change notifications are handled by // the FlutterTextField directly. Only need to make sure it is the // first responder. FlutterTextField* native_text_field = (FlutterTextField*)mac_platform_node_delegate->GetNativeViewAccessible(); id focused = mac_platform_node_delegate->GetFocus(); if (!focused || native_text_field == focused) { [native_text_field startEditing]; } break; } events.push_back({ .name = NSAccessibilityValueChangedNotification, .target = native_node, .user_info = nil, }); if (ax_node.data().HasState(ax::mojom::State::kEditable)) { events.push_back({ .name = NSAccessibilityValueChangedNotification, .target = RootDelegate()->GetNativeViewAccessible(), .user_info = nil, }); } break; } case ui::AXEventGenerator::Event::LIVE_REGION_CREATED: events.push_back({ .name = kAccessibilityLiveRegionCreatedNotification, .target = native_node, .user_info = nil, }); break; case ui::AXEventGenerator::Event::ALERT: { events.push_back({ .name = kAccessibilityLiveRegionCreatedNotification, .target = native_node, .user_info = nil, }); // VoiceOver requires a live region changed notification to actually // announce the live region. auto live_region_events = MacOSEventsFromAXEvent(ui::AXEventGenerator::Event::LIVE_REGION_CHANGED, ax_node); events.insert(events.end(), live_region_events.begin(), live_region_events.end()); break; } case ui::AXEventGenerator::Event::LIVE_REGION_CHANGED: { // Uses native VoiceOver support for live regions. events.push_back({ .name = kAccessibilityLiveRegionChangedNotification, .target = native_node, .user_info = nil, }); break; } case ui::AXEventGenerator::Event::ROW_COUNT_CHANGED: events.push_back({ .name = NSAccessibilityRowCountChangedNotification, .target = native_node, .user_info = nil, }); break; case ui::AXEventGenerator::Event::EXPANDED: { NSAccessibilityNotificationName mac_notification; if (ax_node.data().role == ax::mojom::Role::kRow || ax_node.data().role == ax::mojom::Role::kTreeItem) { mac_notification = NSAccessibilityRowExpandedNotification; } else { mac_notification = kAccessibilityExpandedChanged; } events.push_back({ .name = mac_notification, .target = native_node, .user_info = nil, }); break; } case ui::AXEventGenerator::Event::COLLAPSED: { NSAccessibilityNotificationName mac_notification; if (ax_node.data().role == ax::mojom::Role::kRow || ax_node.data().role == ax::mojom::Role::kTreeItem) { mac_notification = NSAccessibilityRowCollapsedNotification; } else { mac_notification = kAccessibilityExpandedChanged; } events.push_back({ .name = mac_notification, .target = native_node, .user_info = nil, }); break; } case ui::AXEventGenerator::Event::MENU_ITEM_SELECTED: events.push_back({ .name = kAccessibilityMenuItemSelectedNotification, .target = native_node, .user_info = nil, }); break; case ui::AXEventGenerator::Event::CHILDREN_CHANGED: { // NSAccessibilityCreatedNotification seems to be the only way to let // Voiceover pick up layout changes. events.push_back({ .name = NSAccessibilityCreatedNotification, .target = view_controller_.view.window, .user_info = nil, }); break; } case ui::AXEventGenerator::Event::SUBTREE_CREATED: case ui::AXEventGenerator::Event::ACCESS_KEY_CHANGED: case ui::AXEventGenerator::Event::ATK_TEXT_OBJECT_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::ATOMIC_CHANGED: case ui::AXEventGenerator::Event::AUTO_COMPLETE_CHANGED: case ui::AXEventGenerator::Event::BUSY_CHANGED: case ui::AXEventGenerator::Event::CONTROLS_CHANGED: case ui::AXEventGenerator::Event::CLASS_NAME_CHANGED: case ui::AXEventGenerator::Event::DESCRIBED_BY_CHANGED: case ui::AXEventGenerator::Event::DESCRIPTION_CHANGED: case ui::AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED: case ui::AXEventGenerator::Event::DROPEFFECT_CHANGED: case ui::AXEventGenerator::Event::ENABLED_CHANGED: case ui::AXEventGenerator::Event::FOCUS_CHANGED: case ui::AXEventGenerator::Event::FLOW_FROM_CHANGED: case ui::AXEventGenerator::Event::FLOW_TO_CHANGED: case ui::AXEventGenerator::Event::GRABBED_CHANGED: case ui::AXEventGenerator::Event::HASPOPUP_CHANGED: case ui::AXEventGenerator::Event::HIERARCHICAL_LEVEL_CHANGED: case ui::AXEventGenerator::Event::IGNORED_CHANGED: case ui::AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED: case ui::AXEventGenerator::Event::KEY_SHORTCUTS_CHANGED: case ui::AXEventGenerator::Event::LABELED_BY_CHANGED: case ui::AXEventGenerator::Event::LANGUAGE_CHANGED: case ui::AXEventGenerator::Event::LAYOUT_INVALIDATED: case ui::AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED: case ui::AXEventGenerator::Event::LIVE_RELEVANT_CHANGED: case ui::AXEventGenerator::Event::LIVE_STATUS_CHANGED: case ui::AXEventGenerator::Event::LOAD_START: case ui::AXEventGenerator::Event::MULTILINE_STATE_CHANGED: case ui::AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED: case ui::AXEventGenerator::Event::NAME_CHANGED: case ui::AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::PLACEHOLDER_CHANGED: case ui::AXEventGenerator::Event::PORTAL_ACTIVATED: case ui::AXEventGenerator::Event::POSITION_IN_SET_CHANGED: case ui::AXEventGenerator::Event::READONLY_CHANGED: case ui::AXEventGenerator::Event::RELATED_NODE_CHANGED: case ui::AXEventGenerator::Event::REQUIRED_STATE_CHANGED: case ui::AXEventGenerator::Event::ROLE_CHANGED: case ui::AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED: case ui::AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED: case ui::AXEventGenerator::Event::SELECTED_CHANGED: case ui::AXEventGenerator::Event::SET_SIZE_CHANGED: case ui::AXEventGenerator::Event::SORT_CHANGED: case ui::AXEventGenerator::Event::STATE_CHANGED: case ui::AXEventGenerator::Event::TEXT_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::VALUE_MAX_CHANGED: case ui::AXEventGenerator::Event::VALUE_MIN_CHANGED: case ui::AXEventGenerator::Event::VALUE_STEP_CHANGED: case ui::AXEventGenerator::Event::WIN_IACCESSIBLE_STATE_CHANGED: // There are some notifications that aren't meaningful on Mac. // It's okay to skip them. break; } return events; } void AccessibilityBridgeMac::DispatchAccessibilityAction(ui::AXNode::AXID target, FlutterSemanticsAction action, fml::MallocMapping data) { NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); NSCAssert(view_controller_.viewLoaded && view_controller_.view.window, @"The accessibility bridge should not receive accessibility actions if the flutter view" @"is not loaded or attached to a NSWindow."); [flutter_engine_ dispatchSemanticsAction:action toTarget:target withData:std::move(data)]; } std::shared_ptr<FlutterPlatformNodeDelegate> AccessibilityBridgeMac::CreateFlutterPlatformNodeDelegate() { return std::make_shared<FlutterPlatformNodeDelegateMac>(weak_from_this(), view_controller_); } // Private method void AccessibilityBridgeMac::DispatchMacOSNotification( gfx::NativeViewAccessible native_node, NSAccessibilityNotificationName mac_notification) { NSCAssert(mac_notification, @"The notification must not be null."); NSCAssert(native_node, @"The notification target must not be null."); NSAccessibilityPostNotification(native_node, mac_notification); } void AccessibilityBridgeMac::DispatchMacOSNotificationWithUserInfo( gfx::NativeViewAccessible native_node, NSAccessibilityNotificationName mac_notification, NSDictionary* user_info) { NSCAssert(mac_notification, @"The notification must not be null."); NSCAssert(native_node, @"The notification target must not be null."); NSCAssert(user_info, @"The notification data must not be null."); NSAccessibilityPostNotificationWithUserInfo(native_node, mac_notification, user_info); } bool AccessibilityBridgeMac::HasPendingEvent(ui::AXEventGenerator::Event event) const { NSCAssert(flutter_engine_, @"Flutter engine should not be deallocated"); std::vector<ui::AXEventGenerator::TargetedEvent> pending_events = GetPendingEvents(); for (const auto& pending_event : GetPendingEvents()) { if (pending_event.event_params.event == event) { return true; } } return false; } } // namespace flutter
engine/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.mm", "repo_id": "engine", "token_count": 6721 }
386
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_ #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterDartProject.h" #import "flutter/shell/platform/darwin/common/framework/Source/FlutterNSBundleUtils.h" #include <string> #include <vector> /** * Provides access to data needed to construct a FlutterProjectArgs for the project. */ @interface FlutterDartProject () /** * The path to the Flutter assets directory. */ @property(nonatomic, readonly, nullable) NSString* assetsPath; /** * The path to the ICU data file. */ @property(nonatomic, readonly, nullable) NSString* ICUDataPath; /** * The callback invoked by the engine in root isolate scope. */ @property(nonatomic, nullable) void (*rootIsolateCreateCallback)(void* _Nullable); /** * Whether the Impeller rendering backend is enabled */ @property(nonatomic, readonly) BOOL enableImpeller; /** * Instead of looking up the assets and ICU data path in the application bundle, this initializer * allows callers to create a Dart project with custom locations specified for the both. */ - (nonnull instancetype)initWithAssetsPath:(nonnull NSString*)assets ICUDataPath:(nonnull NSString*)icuPath NS_DESIGNATED_INITIALIZER; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERDARTPROJECT_INTERNAL_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h", "repo_id": "engine", "token_count": 551 }
387
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h" /** * Processes keyboard events and cooperate with |TextInputPlugin|. * * A keyboard event goes through a few sections, each can choose to handled the * event, and only unhandled events can move to the next section: * * - Pre-filtering: Events during IME are sent to the system immediately. * - Keyboard: Dispatch to the embedder responder and the channel responder * simultaneously. After both responders have responded (asynchronously), the * event is considered handled if either responder handles. * - Text input: Events are sent to |TextInputPlugin| and are handled * synchronously. * - Next responder: Events are sent to the next responder as specified by * |viewDelegate|. */ @interface FlutterKeyboardManager : NSObject /** * Create a keyboard manager. * * The |viewDelegate| is a weak reference, typically implemented by * |FlutterViewController|. */ - (nonnull instancetype)initWithViewDelegate:(nonnull id<FlutterKeyboardViewDelegate>)viewDelegate; /** * Processes a key event. * * Unhandled events will be dispatched to the text input system, and possibly * the next responder afterwards. */ - (void)handleEvent:(nonnull NSEvent*)event; /** * Returns yes if is event currently being redispatched. * * In some instances (i.e. emoji shortcut) the event may be redelivered by cocoa * as key equivalent to FlutterTextInput, in which case it shouldn't be * processed again. */ - (BOOL)isDispatchingKeyEvent:(nonnull NSEvent*)event; /** * Synthesize modifier keys events. * * If needed, synthesize modifier keys up and down events by comparing their * current pressing states with the given modifier flags. */ - (void)syncModifiersIfNeeded:(NSEventModifierFlags)modifierFlags timestamp:(NSTimeInterval)timestamp; /** * Returns the keyboard pressed state. * * Returns the keyboard pressed state. The dictionary contains one entry per * pressed keys, mapping from the logical key to the physical key. */ - (nonnull NSDictionary*)getPressedState; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h", "repo_id": "engine", "token_count": 772 }
388
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWCONTROLLER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWCONTROLLER_H_ #import <Cocoa/Cocoa.h> #import "FlutterChannels.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPlatformViews.h" #include <map> #include <unordered_set> @interface FlutterPlatformViewController : NSViewController @end @interface FlutterPlatformViewController () /** * Creates a platform view of viewType with viewId and arguments passed from * the framework's creationParams constructor parameter. * FlutterResult is updated to contain nil for success or to contain * a FlutterError if there is an error. */ - (void)onCreateWithViewIdentifier:(int64_t)viewId viewType:(nonnull NSString*)viewType arguments:(nullable id)args result:(nonnull FlutterResult)result; /** * Disposes the platform view with `viewId`. * FlutterResult is updated to contain nil for success or a FlutterError if there is an error. */ - (void)onDisposeWithViewID:(int64_t)viewId result:(nonnull FlutterResult)result; /** * Returns the platform view associated with the viewId. */ - (nullable NSView*)platformViewWithID:(int64_t)viewId; /** * Register a view factory by adding an entry into the platformViewFactories map with key factoryId * and value factory. */ - (void)registerViewFactory:(nonnull NSObject<FlutterPlatformViewFactory>*)factory withId:(nonnull NSString*)factoryId; /** * Handles platform view related method calls, for example create, dispose, etc. */ - (void)handleMethodCall:(nonnull FlutterMethodCall*)call result:(nonnull FlutterResult)result; /** * Removes platform views slated to be disposed via method handler calls. */ - (void)disposePlatformViews; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERPLATFORMVIEWCONTROLLER_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h", "repo_id": "engine", "token_count": 741 }
389
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRAR_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRAR_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h" /* * Delegate methods for FlutterTextureRegistrar. */ @protocol FlutterTextureRegistrarDelegate /* * Called by the FlutterTextureRegistrar when a texture is registered. */ - (nonnull FlutterExternalTexture*)onRegisterTexture:(nonnull id<FlutterTexture>)texture; @end /* * Holds the external textures and implements the FlutterTextureRegistry. */ @interface FlutterTextureRegistrar : NSObject <FlutterTextureRegistry> /* * Use `initWithDelegate:engine:` instead. */ - (nullable instancetype)init NS_UNAVAILABLE; /* * Use `initWithDelegate:engine:` instead. */ + (nullable instancetype)new NS_UNAVAILABLE; /* * Initialzes the texture registrar. */ - (nullable instancetype)initWithDelegate:(nonnull id<FlutterTextureRegistrarDelegate>)delegate engine:(nonnull FlutterEngine*)engine NS_DESIGNATED_INITIALIZER; /* * Returns the registered texture with the provided `textureID`. */ - (nullable FlutterExternalTexture*)getTextureWithID:(int64_t)textureID; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERTEXTUREREGISTRAR_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h", "repo_id": "engine", "token_count": 583 }
390
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" namespace flutter::testing { id CreateMockViewController() { { NSString* fixtures = @(testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:project]; id viewControllerMock = OCMPartialMock(viewController); return viewControllerMock; } } } // namespace flutter::testing
engine/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm", "repo_id": "engine", "token_count": 257 }
391
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>FlutterEmbedder</string> <key>CFBundleIdentifier</key> <string>io.flutter.flutter-embedder</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>FlutterEmbedder</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>CFBundleVersion</key> <string>1</string> <key>NSHumanReadableCopyright</key> <string>Copyright 2013 The Flutter Authors. All rights reserved.</string> <key>FlutterEngine</key> <string>{revision}</string> <key>ClangVersion</key> <string>{clang_version}</string> </dict> </plist>
engine/shell/platform/embedder/assets/EmbedderInfo.plist/0
{ "file_path": "engine/shell/platform/embedder/assets/EmbedderInfo.plist", "repo_id": "engine", "token_count": 402 }
392
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/embedder_external_view_embedder.h" #include <cassert> #include <utility> #include "flutter/common/constants.h" #include "flutter/shell/platform/embedder/embedder_layers.h" #include "flutter/shell/platform/embedder/embedder_render_target.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { static const auto kRootViewIdentifier = EmbedderExternalView::ViewIdentifier{}; EmbedderExternalViewEmbedder::EmbedderExternalViewEmbedder( bool avoid_backing_store_cache, const CreateRenderTargetCallback& create_render_target_callback, const PresentCallback& present_callback) : avoid_backing_store_cache_(avoid_backing_store_cache), create_render_target_callback_(create_render_target_callback), present_callback_(present_callback) { FML_DCHECK(create_render_target_callback_); FML_DCHECK(present_callback_); } EmbedderExternalViewEmbedder::~EmbedderExternalViewEmbedder() = default; void EmbedderExternalViewEmbedder::SetSurfaceTransformationCallback( SurfaceTransformationCallback surface_transformation_callback) { surface_transformation_callback_ = std::move(surface_transformation_callback); } SkMatrix EmbedderExternalViewEmbedder::GetSurfaceTransformation() const { if (!surface_transformation_callback_) { return SkMatrix{}; } return surface_transformation_callback_(); } void EmbedderExternalViewEmbedder::Reset() { pending_views_.clear(); composition_order_.clear(); } // |ExternalViewEmbedder| void EmbedderExternalViewEmbedder::CancelFrame() { Reset(); } // |ExternalViewEmbedder| void EmbedderExternalViewEmbedder::BeginFrame( GrDirectContext* context, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {} // |ExternalViewEmbedder| void EmbedderExternalViewEmbedder::PrepareFlutterView( int64_t flutter_view_id, SkISize frame_size, double device_pixel_ratio) { // TODO(dkwingsmt): This class only supports rendering into the implicit // view. Properly support multi-view in the future. // https://github.com/flutter/flutter/issues/135530 item 4 FML_DCHECK(flutter_view_id == kFlutterImplicitViewId); Reset(); pending_frame_size_ = frame_size; pending_device_pixel_ratio_ = device_pixel_ratio; pending_surface_transformation_ = GetSurfaceTransformation(); pending_views_[kRootViewIdentifier] = std::make_unique<EmbedderExternalView>( pending_frame_size_, pending_surface_transformation_); composition_order_.push_back(kRootViewIdentifier); } // |ExternalViewEmbedder| void EmbedderExternalViewEmbedder::PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<EmbeddedViewParams> params) { auto vid = EmbedderExternalView::ViewIdentifier(view_id); FML_DCHECK(pending_views_.count(vid) == 0); pending_views_[vid] = std::make_unique<EmbedderExternalView>( pending_frame_size_, // frame size pending_surface_transformation_, // surface xformation vid, // view identifier std::move(params) // embedded view params ); composition_order_.push_back(vid); } // |ExternalViewEmbedder| DlCanvas* EmbedderExternalViewEmbedder::GetRootCanvas() { auto found = pending_views_.find(kRootViewIdentifier); if (found == pending_views_.end()) { FML_DLOG(WARNING) << "No root canvas could be found. This is extremely unlikely and " "indicates that the external view embedder did not receive the " "notification to begin the frame."; return nullptr; } return found->second->GetCanvas(); } // |ExternalViewEmbedder| DlCanvas* EmbedderExternalViewEmbedder::CompositeEmbeddedView(int64_t view_id) { auto vid = EmbedderExternalView::ViewIdentifier(view_id); auto found = pending_views_.find(vid); if (found == pending_views_.end()) { FML_DCHECK(false) << "Attempted to composite a view that was not " "pre-rolled."; return nullptr; } return found->second->GetCanvas(); } static FlutterBackingStoreConfig MakeBackingStoreConfig( const SkISize& backing_store_size) { FlutterBackingStoreConfig config = {}; config.struct_size = sizeof(config); config.size.width = backing_store_size.width(); config.size.height = backing_store_size.height(); return config; } namespace { struct PlatformView { EmbedderExternalView::ViewIdentifier view_identifier; const EmbeddedViewParams* params; // The frame of the platform view, after clipping, in screen coordinates. SkRect clipped_frame; explicit PlatformView(const EmbedderExternalView* view) { FML_DCHECK(view->HasPlatformView()); view_identifier = view->GetViewIdentifier(); params = view->GetEmbeddedViewParams(); clipped_frame = view->GetEmbeddedViewParams()->finalBoundingRect(); SkMatrix transform; for (auto i = params->mutatorsStack().Begin(); i != params->mutatorsStack().End(); ++i) { const auto& m = *i; switch (m->GetType()) { case kClipRect: { auto rect = transform.mapRect(m->GetRect()); if (!clipped_frame.intersect(rect)) { clipped_frame = SkRect::MakeEmpty(); } break; } case kClipRRect: { auto rect = transform.mapRect(m->GetRRect().getBounds()); if (!clipped_frame.intersect(rect)) { clipped_frame = SkRect::MakeEmpty(); } break; } case kClipPath: { auto rect = transform.mapRect(m->GetPath().getBounds()); if (!clipped_frame.intersect(rect)) { clipped_frame = SkRect::MakeEmpty(); } break; } case kTransform: { transform.preConcat(m->GetMatrix()); break; } case kOpacity: case kBackdropFilter: break; } } } }; /// Each layer will result in a single physical surface that contains Flutter /// contents. It may contain multiple platform views and the slices /// that would be otherwise rendered between these platform views will be /// collapsed into this layer, as long as they do not intersect any of the /// platform views. /// In Z order the Flutter contents of Layer is above the platform views. class Layer { public: /// Returns whether the rectangle intersects any of the platform views of /// this layer. bool IntersectsPlatformView(const SkRect& rect) { for (auto& platform_view : platform_views_) { if (platform_view.clipped_frame.intersects(rect)) { return true; } } return false; } /// Returns whether the region intersects any of the platform views of this /// layer. bool IntersectsPlatformView(const DlRegion& region) { for (auto& platform_view : platform_views_) { if (region.intersects(platform_view.clipped_frame.roundOut())) { return true; } } return false; } /// Returns whether the rectangle intersects any of the Flutter contents of /// this layer. bool IntersectsFlutterContents(const SkRect& rect) { return flutter_contents_region_.intersects(rect.roundOut()); } /// Returns whether the region intersects any of the Flutter contents of this /// layer. bool IntersectsFlutterContents(const DlRegion& region) { return flutter_contents_region_.intersects(region); } /// Adds a platform view to this layer. void AddPlatformView(const PlatformView& platform_view) { platform_views_.push_back(platform_view); } /// Adds Flutter contents to this layer. void AddFlutterContents(EmbedderExternalView* contents, const DlRegion& contents_region) { flutter_contents_.push_back(contents); flutter_contents_region_ = DlRegion::MakeUnion(flutter_contents_region_, contents_region); } bool has_flutter_contents() const { return !flutter_contents_.empty(); } void SetRenderTarget(std::unique_ptr<EmbedderRenderTarget> target) { FML_DCHECK(render_target_ == nullptr); FML_DCHECK(has_flutter_contents()); render_target_ = std::move(target); } /// Renders this layer Flutter contents to the render target previously /// assigned with SetRenderTarget. void RenderFlutterContents() { FML_DCHECK(has_flutter_contents()); if (render_target_) { bool clear_surface = true; for (auto c : flutter_contents_) { c->Render(*render_target_, clear_surface); clear_surface = false; } } } /// Returns platform views for this layer. In Z-order the platform views are /// positioned *below* this layer's Flutter contents. const std::vector<PlatformView>& platform_views() const { return platform_views_; } EmbedderRenderTarget* render_target() { return render_target_.get(); } std::vector<SkIRect> coverage() { return flutter_contents_region_.getRects(); } private: std::vector<PlatformView> platform_views_; std::vector<EmbedderExternalView*> flutter_contents_; DlRegion flutter_contents_region_; std::unique_ptr<EmbedderRenderTarget> render_target_; friend class LayerBuilder; }; /// A layout builder is responsible for building an optimized list of Layers /// from a list of `EmbedderExternalView`s. Single EmbedderExternalView contains /// at most one platform view and at most one layer of Flutter contents /// ('slice'). LayerBuilder is responsible for producing as few Layers from the /// list of EmbedderExternalViews as possible while maintaining identical visual /// result. /// /// Implements https://flutter.dev/go/optimized-platform-view-layers class LayerBuilder { public: explicit LayerBuilder(SkISize frame_size) : frame_size_(frame_size) { layers_.push_back(Layer()); } /// Adds the platform view and/or flutter contents from the /// EmbedderExternalView instance. /// /// This will try to add the content and platform view to an existing layer /// if possible. If not, a new layer will be created. void AddExternalView(EmbedderExternalView* view) { if (view->HasPlatformView()) { PlatformView platform_view(view); AddPlatformView(platform_view); } if (view->HasEngineRenderedContents()) { AddFlutterContents(view); } } /// Prepares the render targets for all layers that have Flutter contents. void PrepareBackingStore( const std::function<std::unique_ptr<EmbedderRenderTarget>( FlutterBackingStoreConfig)>& target_provider) { auto config = MakeBackingStoreConfig(frame_size_); for (auto& layer : layers_) { if (layer.has_flutter_contents()) { layer.SetRenderTarget(target_provider(config)); } } } /// Renders all layers with Flutter contents to their respective render /// targets. void Render() { for (auto& layer : layers_) { if (layer.has_flutter_contents()) { layer.RenderFlutterContents(); } } } /// Populates EmbedderLayers from layer builder's layers. void PushLayers(EmbedderLayers& layers) { for (auto& layer : layers_) { for (auto& view : layer.platform_views()) { auto platform_view_id = view.view_identifier.platform_view_id; if (platform_view_id.has_value()) { layers.PushPlatformViewLayer(platform_view_id.value(), *view.params); } } if (layer.render_target() != nullptr) { layers.PushBackingStoreLayer(layer.render_target()->GetBackingStore(), layer.coverage()); } } } /// Removes the render targets from layers and returns them for collection. std::vector<std::unique_ptr<EmbedderRenderTarget>> ClearAndCollectRenderTargets() { std::vector<std::unique_ptr<EmbedderRenderTarget>> result; for (auto& layer : layers_) { if (layer.render_target() != nullptr) { result.push_back(std::move(layer.render_target_)); } } layers_.clear(); return result; } private: void AddPlatformView(PlatformView view) { GetLayerForPlatformView(view).AddPlatformView(view); } void AddFlutterContents(EmbedderExternalView* contents) { FML_DCHECK(contents->HasEngineRenderedContents()); DlRegion region = contents->GetDlRegion(); GetLayerForFlutterContentsRegion(region).AddFlutterContents(contents, region); } /// Returns the deepest layer to which the platform view can be added. That /// would be (whichever comes first): /// - First layer from back that has platform view that intersects with this /// view /// - Very last layer from back that has surface that doesn't intersect with /// this. That is because layer content renders on top of the platform view. Layer& GetLayerForPlatformView(PlatformView view) { for (auto iter = layers_.rbegin(); iter != layers_.rend(); ++iter) { // This layer has surface that intersects with this view. That means we // went one too far and need the layer before this. if (iter->IntersectsFlutterContents(view.clipped_frame)) { if (iter == layers_.rbegin()) { layers_.emplace_back(); return layers_.back(); } else { --iter; return *iter; } } if (iter->IntersectsPlatformView(view.clipped_frame)) { return *iter; } } return layers_.front(); } /// Finds layer to which the Flutter content can be added. That would /// be first layer from back that has any intersection with this region. Layer& GetLayerForFlutterContentsRegion(const DlRegion& region) { for (auto iter = layers_.rbegin(); iter != layers_.rend(); ++iter) { if (iter->IntersectsPlatformView(region) || iter->IntersectsFlutterContents(region)) { return *iter; } } return layers_.front(); } std::vector<Layer> layers_; SkISize frame_size_; }; }; // namespace void EmbedderExternalViewEmbedder::SubmitFlutterView( GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> frame) { SkRect _rect = SkRect::MakeIWH(pending_frame_size_.width(), pending_frame_size_.height()); pending_surface_transformation_.mapRect(&_rect); LayerBuilder builder(SkISize::Make(_rect.width(), _rect.height())); for (auto view_id : composition_order_) { auto& view = pending_views_[view_id]; builder.AddExternalView(view.get()); } builder.PrepareBackingStore([&](FlutterBackingStoreConfig config) { std::unique_ptr<EmbedderRenderTarget> target; if (!avoid_backing_store_cache_) { target = render_target_cache_.GetRenderTarget( EmbedderExternalView::RenderTargetDescriptor( SkISize{static_cast<int32_t>(config.size.width), static_cast<int32_t>(config.size.height)})); } if (target != nullptr) { return target; } return create_render_target_callback_(context, aiks_context, config); }); // This is where unused render targets will be collected. Control may flow // to the embedder. Here, the embedder has the opportunity to trample on the // OpenGL context. // // For optimum performance, we should tell the render target cache to clear // its unused entries before allocating new ones. This collection step // before allocating new render targets ameliorates peak memory usage within // the frame. But, this causes an issue in a known internal embedder. To // work around this issue while that embedder migrates, collection of render // targets is deferred after the presentation. // // @warning: Embedder may trample on our OpenGL context here. auto deferred_cleanup_render_targets = render_target_cache_.ClearAllRenderTargetsInCache(); // The OpenGL context could have been trampled by the embedder at this point // as it attempted to collect old render targets and create new ones. Tell // Skia to not rely on existing bindings. if (context) { context->resetContext(kAll_GrBackendState); } builder.Render(); // We are going to be transferring control back over to the embedder there // the context may be trampled upon again. Flush all operations to the // underlying rendering API. // // @warning: Embedder may trample on our OpenGL context here. if (context) { context->flushAndSubmit(); } { auto presentation_time_optional = frame->submit_info().presentation_time; uint64_t presentation_time = presentation_time_optional.has_value() ? presentation_time_optional->ToEpochDelta().ToNanoseconds() : 0; // Submit the scribbled layer to the embedder for presentation. // // @warning: Embedder may trample on our OpenGL context here. EmbedderLayers presented_layers( pending_frame_size_, pending_device_pixel_ratio_, pending_surface_transformation_, presentation_time); builder.PushLayers(presented_layers); // TODO(loic-sharma): Currently only supports a single view. // See https://github.com/flutter/flutter/issues/135530. presented_layers.InvokePresentCallback(kFlutterImplicitViewId, present_callback_); } // See why this is necessary in the comment where this collection in // realized. // // @warning: Embedder may trample on our OpenGL context here. deferred_cleanup_render_targets.clear(); auto render_targets = builder.ClearAndCollectRenderTargets(); for (auto& render_target : render_targets) { if (!avoid_backing_store_cache_) { render_target_cache_.CacheRenderTarget(std::move(render_target)); } } frame->Submit(); } } // namespace flutter
engine/shell/platform/embedder/embedder_external_view_embedder.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_external_view_embedder.cc", "repo_id": "engine", "token_count": 6304 }
393
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/embedder_semantics_update.h" namespace flutter { EmbedderSemanticsUpdate::EmbedderSemanticsUpdate( const SemanticsNodeUpdates& nodes, const CustomAccessibilityActionUpdates& actions) { for (const auto& value : nodes) { AddNode(value.second); } for (const auto& value : actions) { AddAction(value.second); } update_ = { .struct_size = sizeof(FlutterSemanticsUpdate), .nodes_count = nodes_.size(), .nodes = nodes_.data(), .custom_actions_count = actions_.size(), .custom_actions = actions_.data(), }; } void EmbedderSemanticsUpdate::AddNode(const SemanticsNode& node) { SkMatrix transform = node.transform.asM33(); FlutterTransformation flutter_transform{ transform.get(SkMatrix::kMScaleX), transform.get(SkMatrix::kMSkewX), transform.get(SkMatrix::kMTransX), transform.get(SkMatrix::kMSkewY), transform.get(SkMatrix::kMScaleY), transform.get(SkMatrix::kMTransY), transform.get(SkMatrix::kMPersp0), transform.get(SkMatrix::kMPersp1), transform.get(SkMatrix::kMPersp2)}; // Do not add new members to FlutterSemanticsNode. // This would break the forward compatibility of FlutterSemanticsUpdate. // All new members must be added to FlutterSemanticsNode2 instead. nodes_.push_back({ sizeof(FlutterSemanticsNode), node.id, static_cast<FlutterSemanticsFlag>(node.flags), static_cast<FlutterSemanticsAction>(node.actions), node.textSelectionBase, node.textSelectionExtent, node.scrollChildren, node.scrollIndex, node.scrollPosition, node.scrollExtentMax, node.scrollExtentMin, node.elevation, node.thickness, node.label.c_str(), node.hint.c_str(), node.value.c_str(), node.increasedValue.c_str(), node.decreasedValue.c_str(), static_cast<FlutterTextDirection>(node.textDirection), FlutterRect{node.rect.fLeft, node.rect.fTop, node.rect.fRight, node.rect.fBottom}, flutter_transform, node.childrenInTraversalOrder.size(), node.childrenInTraversalOrder.data(), node.childrenInHitTestOrder.data(), node.customAccessibilityActions.size(), node.customAccessibilityActions.data(), node.platformViewId, node.tooltip.c_str(), }); } void EmbedderSemanticsUpdate::AddAction( const CustomAccessibilityAction& action) { // Do not add new members to FlutterSemanticsCustomAction. // This would break the forward compatibility of FlutterSemanticsUpdate. // All new members must be added to FlutterSemanticsCustomAction2 instead. actions_.push_back({ sizeof(FlutterSemanticsCustomAction), action.id, static_cast<FlutterSemanticsAction>(action.overrideId), action.label.c_str(), action.hint.c_str(), }); } EmbedderSemanticsUpdate::~EmbedderSemanticsUpdate() {} EmbedderSemanticsUpdate2::EmbedderSemanticsUpdate2( const SemanticsNodeUpdates& nodes, const CustomAccessibilityActionUpdates& actions) { nodes_.reserve(nodes.size()); node_pointers_.reserve(nodes.size()); actions_.reserve(actions.size()); action_pointers_.reserve(actions.size()); for (const auto& value : nodes) { AddNode(value.second); } for (const auto& value : actions) { AddAction(value.second); } for (size_t i = 0; i < nodes_.size(); i++) { node_pointers_.push_back(&nodes_[i]); } for (size_t i = 0; i < actions_.size(); i++) { action_pointers_.push_back(&actions_[i]); } update_ = { .struct_size = sizeof(FlutterSemanticsUpdate2), .node_count = node_pointers_.size(), .nodes = node_pointers_.data(), .custom_action_count = action_pointers_.size(), .custom_actions = action_pointers_.data(), }; } EmbedderSemanticsUpdate2::~EmbedderSemanticsUpdate2() {} void EmbedderSemanticsUpdate2::AddNode(const SemanticsNode& node) { SkMatrix transform = node.transform.asM33(); FlutterTransformation flutter_transform{ transform.get(SkMatrix::kMScaleX), transform.get(SkMatrix::kMSkewX), transform.get(SkMatrix::kMTransX), transform.get(SkMatrix::kMSkewY), transform.get(SkMatrix::kMScaleY), transform.get(SkMatrix::kMTransY), transform.get(SkMatrix::kMPersp0), transform.get(SkMatrix::kMPersp1), transform.get(SkMatrix::kMPersp2)}; auto label_attributes = CreateStringAttributes(node.labelAttributes); auto hint_attributes = CreateStringAttributes(node.hintAttributes); auto value_attributes = CreateStringAttributes(node.valueAttributes); auto increased_value_attributes = CreateStringAttributes(node.increasedValueAttributes); auto decreased_value_attributes = CreateStringAttributes(node.decreasedValueAttributes); nodes_.push_back({ sizeof(FlutterSemanticsNode2), node.id, static_cast<FlutterSemanticsFlag>(node.flags), static_cast<FlutterSemanticsAction>(node.actions), node.textSelectionBase, node.textSelectionExtent, node.scrollChildren, node.scrollIndex, node.scrollPosition, node.scrollExtentMax, node.scrollExtentMin, node.elevation, node.thickness, node.label.c_str(), node.hint.c_str(), node.value.c_str(), node.increasedValue.c_str(), node.decreasedValue.c_str(), static_cast<FlutterTextDirection>(node.textDirection), FlutterRect{node.rect.fLeft, node.rect.fTop, node.rect.fRight, node.rect.fBottom}, flutter_transform, node.childrenInTraversalOrder.size(), node.childrenInTraversalOrder.data(), node.childrenInHitTestOrder.data(), node.customAccessibilityActions.size(), node.customAccessibilityActions.data(), node.platformViewId, node.tooltip.c_str(), label_attributes.count, label_attributes.attributes, hint_attributes.count, hint_attributes.attributes, value_attributes.count, value_attributes.attributes, increased_value_attributes.count, increased_value_attributes.attributes, decreased_value_attributes.count, decreased_value_attributes.attributes, }); } void EmbedderSemanticsUpdate2::AddAction( const CustomAccessibilityAction& action) { actions_.push_back({ sizeof(FlutterSemanticsCustomAction2), action.id, static_cast<FlutterSemanticsAction>(action.overrideId), action.label.c_str(), action.hint.c_str(), }); } EmbedderSemanticsUpdate2::EmbedderStringAttributes EmbedderSemanticsUpdate2::CreateStringAttributes( const StringAttributes& attributes) { // Minimize allocations if attributes are empty. if (attributes.empty()) { return {.count = 0, .attributes = nullptr}; } // Translate the engine attributes to embedder attributes. // The result vector's data is returned by this method. // The result vector will be owned by |node_string_attributes_| // so that the embedder attributes are cleaned up at the end of the // semantics update callback when when the |EmbedderSemanticsUpdate2| // is destroyed. auto result = std::make_unique<std::vector<const FlutterStringAttribute*>>(); result->reserve(attributes.size()); for (const auto& attribute : attributes) { auto embedder_attribute = std::make_unique<FlutterStringAttribute>(); embedder_attribute->struct_size = sizeof(FlutterStringAttribute); embedder_attribute->start = attribute->start; embedder_attribute->end = attribute->end; switch (attribute->type) { case StringAttributeType::kLocale: { std::shared_ptr<flutter::LocaleStringAttribute> locale_attribute = std::static_pointer_cast<flutter::LocaleStringAttribute>(attribute); auto embedder_locale = std::make_unique<FlutterLocaleStringAttribute>(); embedder_locale->struct_size = sizeof(FlutterLocaleStringAttribute); embedder_locale->locale = locale_attribute->locale.c_str(); locale_attributes_.push_back(std::move(embedder_locale)); embedder_attribute->type = FlutterStringAttributeType::kLocale; embedder_attribute->locale = locale_attributes_.back().get(); break; } case flutter::StringAttributeType::kSpellOut: { // All spell out attributes are identical and share a lazily created // instance. if (!spell_out_attribute_) { auto spell_out_attribute_ = std::make_unique<FlutterSpellOutStringAttribute>(); spell_out_attribute_->struct_size = sizeof(FlutterSpellOutStringAttribute); } embedder_attribute->type = FlutterStringAttributeType::kSpellOut; embedder_attribute->spell_out = spell_out_attribute_.get(); break; } } string_attributes_.push_back(std::move(embedder_attribute)); result->push_back(string_attributes_.back().get()); } node_string_attributes_.push_back(std::move(result)); return { .count = node_string_attributes_.back()->size(), .attributes = node_string_attributes_.back()->data(), }; } } // namespace flutter
engine/shell/platform/embedder/embedder_semantics_update.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_semantics_update.cc", "repo_id": "engine", "token_count": 3425 }
394
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_VULKAN_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_VULKAN_H_ #include "flutter/fml/macros.h" #include "flutter/shell/common/context_options.h" #include "flutter/shell/gpu/gpu_surface_vulkan.h" #include "flutter/shell/gpu/gpu_surface_vulkan_delegate.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/embedder_external_view_embedder.h" #include "flutter/shell/platform/embedder/embedder_surface.h" #include "flutter/vulkan/procs/vulkan_proc_table.h" namespace flutter { class EmbedderSurfaceVulkan final : public EmbedderSurface, public GPUSurfaceVulkanDelegate { public: struct VulkanDispatchTable { PFN_vkGetInstanceProcAddr get_instance_proc_address; // required std::function<FlutterVulkanImage(const SkISize& frame_size)> get_next_image; // required std::function<bool(VkImage image, VkFormat format)> present_image; // required }; EmbedderSurfaceVulkan( uint32_t version, VkInstance instance, size_t instance_extension_count, const char** instance_extensions, size_t device_extension_count, const char** device_extensions, VkPhysicalDevice physical_device, VkDevice device, uint32_t queue_family_index, VkQueue queue, const VulkanDispatchTable& vulkan_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder); ~EmbedderSurfaceVulkan() override; // |GPUSurfaceVulkanDelegate| const vulkan::VulkanProcTable& vk() override; // |GPUSurfaceVulkanDelegate| FlutterVulkanImage AcquireImage(const SkISize& size) override; // |GPUSurfaceVulkanDelegate| bool PresentImage(VkImage image, VkFormat format) override; private: bool valid_ = false; fml::RefPtr<vulkan::VulkanProcTable> vk_; vulkan::VulkanDevice device_; VulkanDispatchTable vulkan_dispatch_table_; std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder_; sk_sp<GrDirectContext> main_context_; sk_sp<GrDirectContext> resource_context_; // |EmbedderSurface| bool IsValid() const override; // |EmbedderSurface| std::unique_ptr<Surface> CreateGPUSurface() override; // |EmbedderSurface| sk_sp<GrDirectContext> CreateResourceContext() const override; sk_sp<GrDirectContext> CreateGrContext(VkInstance instance, uint32_t version, size_t instance_extension_count, const char** instance_extensions, size_t device_extension_count, const char** device_extensions, ContextType context_type) const; void* GetInstanceProcAddress(VkInstance instance, const char* proc_name); FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSurfaceVulkan); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_VULKAN_H_
engine/shell/platform/embedder/embedder_surface_vulkan.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_surface_vulkan.h", "repo_id": "engine", "token_count": 1361 }
395
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/platform_view_embedder.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/testing.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <cstring> namespace flutter { namespace testing { namespace { class MockDelegate : public PlatformView::Delegate { MOCK_METHOD(void, OnPlatformViewCreated, (std::unique_ptr<Surface>), (override)); MOCK_METHOD(void, OnPlatformViewDestroyed, (), (override)); MOCK_METHOD(void, OnPlatformViewScheduleFrame, (), (override)); MOCK_METHOD(void, OnPlatformViewSetNextFrameCallback, (const fml::closure& closure), (override)); MOCK_METHOD(void, OnPlatformViewSetViewportMetrics, (int64_t view_id, const ViewportMetrics& metrics), (override)); MOCK_METHOD(void, OnPlatformViewDispatchPlatformMessage, (std::unique_ptr<PlatformMessage> message), (override)); MOCK_METHOD(void, OnPlatformViewDispatchPointerDataPacket, (std::unique_ptr<PointerDataPacket> packet), (override)); MOCK_METHOD(void, OnPlatformViewDispatchSemanticsAction, (int32_t id, SemanticsAction action, fml::MallocMapping args), (override)); MOCK_METHOD(void, OnPlatformViewSetSemanticsEnabled, (bool enabled), (override)); MOCK_METHOD(void, OnPlatformViewSetAccessibilityFeatures, (int32_t flags), (override)); MOCK_METHOD(void, OnPlatformViewRegisterTexture, (std::shared_ptr<Texture> texture), (override)); MOCK_METHOD(void, OnPlatformViewUnregisterTexture, (int64_t texture_id), (override)); MOCK_METHOD(void, OnPlatformViewMarkTextureFrameAvailable, (int64_t texture_id), (override)); MOCK_METHOD(void, LoadDartDeferredLibrary, (intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions), (override)); MOCK_METHOD(void, LoadDartDeferredLibraryError, (intptr_t loading_unit_id, const std::string error_message, bool transient), (override)); MOCK_METHOD(void, UpdateAssetResolverByType, (std::unique_ptr<AssetResolver> updated_asset_resolver, AssetResolver::AssetResolverType type), (override)); MOCK_METHOD(const Settings&, OnPlatformViewGetSettings, (), (const, override)); }; class MockResponse : public PlatformMessageResponse { public: MOCK_METHOD(void, Complete, (std::unique_ptr<fml::Mapping> data), (override)); MOCK_METHOD(void, CompleteEmpty, (), (override)); }; } // namespace TEST(PlatformViewEmbedderTest, HasPlatformMessageHandler) { ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", ThreadHost::Type::kPlatform); flutter::TaskRunners task_runners = flutter::TaskRunners( "HasPlatformMessageHandler", thread_host.platform_thread->GetTaskRunner(), nullptr, nullptr, nullptr); fml::AutoResetWaitableEvent latch; task_runners.GetPlatformTaskRunner()->PostTask([&latch, task_runners] { MockDelegate delegate; EmbedderSurfaceSoftware::SoftwareDispatchTable software_dispatch_table; PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table; std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder; auto embedder = std::make_unique<PlatformViewEmbedder>( delegate, task_runners, software_dispatch_table, platform_dispatch_table, external_view_embedder); ASSERT_TRUE(embedder->GetPlatformMessageHandler()); latch.Signal(); }); latch.Wait(); } TEST(PlatformViewEmbedderTest, Dispatches) { ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", ThreadHost::Type::kPlatform); flutter::TaskRunners task_runners = flutter::TaskRunners( "HasPlatformMessageHandler", thread_host.platform_thread->GetTaskRunner(), nullptr, nullptr, nullptr); bool did_call = false; std::unique_ptr<PlatformViewEmbedder> embedder; { fml::AutoResetWaitableEvent latch; task_runners.GetPlatformTaskRunner()->PostTask([&latch, task_runners, &did_call, &embedder] { MockDelegate delegate; EmbedderSurfaceSoftware::SoftwareDispatchTable software_dispatch_table; PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table; platform_dispatch_table.platform_message_response_callback = [&did_call](std::unique_ptr<PlatformMessage> message) { did_call = true; }; std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder; embedder = std::make_unique<PlatformViewEmbedder>( delegate, task_runners, software_dispatch_table, platform_dispatch_table, external_view_embedder); auto platform_message_handler = embedder->GetPlatformMessageHandler(); fml::RefPtr<PlatformMessageResponse> response = fml::MakeRefCounted<MockResponse>(); std::unique_ptr<PlatformMessage> message = std::make_unique<PlatformMessage>("foo", response); platform_message_handler->HandlePlatformMessage(std::move(message)); latch.Signal(); }); latch.Wait(); } { fml::AutoResetWaitableEvent latch; thread_host.platform_thread->GetTaskRunner()->PostTask([&latch, &embedder] { embedder.reset(); latch.Signal(); }); latch.Wait(); } EXPECT_TRUE(did_call); } TEST(PlatformViewEmbedderTest, DeletionDisabledDispatch) { ThreadHost thread_host("io.flutter.test." + GetCurrentTestName() + ".", ThreadHost::Type::kPlatform); flutter::TaskRunners task_runners = flutter::TaskRunners( "HasPlatformMessageHandler", thread_host.platform_thread->GetTaskRunner(), nullptr, nullptr, nullptr); bool did_call = false; { fml::AutoResetWaitableEvent latch; task_runners.GetPlatformTaskRunner()->PostTask([&latch, task_runners, &did_call] { MockDelegate delegate; EmbedderSurfaceSoftware::SoftwareDispatchTable software_dispatch_table; PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table; platform_dispatch_table.platform_message_response_callback = [&did_call](std::unique_ptr<PlatformMessage> message) { did_call = true; }; std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder; auto embedder = std::make_unique<PlatformViewEmbedder>( delegate, task_runners, software_dispatch_table, platform_dispatch_table, external_view_embedder); auto platform_message_handler = embedder->GetPlatformMessageHandler(); fml::RefPtr<PlatformMessageResponse> response = fml::MakeRefCounted<MockResponse>(); std::unique_ptr<PlatformMessage> message = std::make_unique<PlatformMessage>("foo", response); platform_message_handler->HandlePlatformMessage(std::move(message)); embedder.reset(); latch.Signal(); }); latch.Wait(); } { fml::AutoResetWaitableEvent latch; thread_host.platform_thread->GetTaskRunner()->PostTask( [&latch] { latch.Signal(); }); latch.Wait(); } EXPECT_FALSE(did_call); } } // namespace testing } // namespace flutter
engine/shell/platform/embedder/platform_view_embedder_unittests.cc/0
{ "file_path": "engine/shell/platform/embedder/platform_view_embedder_unittests.cc", "repo_id": "engine", "token_count": 3331 }
396
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_H_ #include <vector> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/tests/embedder_test_backingstore_producer.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { namespace testing { class EmbedderTestCompositor { public: using PlatformViewRendererCallback = std::function<sk_sp<SkImage>(const FlutterLayer& layer, GrDirectContext* context)>; using PresentCallback = std::function<void(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count)>; EmbedderTestCompositor(SkISize surface_size, sk_sp<GrDirectContext> context); virtual ~EmbedderTestCompositor(); void SetBackingStoreProducer( std::unique_ptr<EmbedderTestBackingStoreProducer> backingstore_producer); bool CreateBackingStore(const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out); bool CollectBackingStore(const FlutterBackingStore* backing_store); bool Present(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count); void SetPlatformViewRendererCallback( const PlatformViewRendererCallback& callback); //---------------------------------------------------------------------------- /// @brief Allows tests to install a callback to notify them when the /// entire render tree has been finalized so they can run their /// assertions. /// /// @param[in] next_present_callback The next present callback /// void SetNextPresentCallback(const PresentCallback& next_present_callback); void SetPresentCallback(const PresentCallback& present_callback, bool one_shot); using NextSceneCallback = std::function<void(sk_sp<SkImage> image)>; void SetNextSceneCallback(const NextSceneCallback& next_scene_callback); sk_sp<SkImage> GetLastComposition(); size_t GetPendingBackingStoresCount() const; size_t GetBackingStoresCreatedCount() const; size_t GetBackingStoresCollectedCount() const; void AddOnCreateRenderTargetCallback(const fml::closure& callback); void AddOnCollectRenderTargetCallback(const fml::closure& callback); void AddOnPresentCallback(const fml::closure& callback); sk_sp<GrDirectContext> GetGrContext(); protected: virtual bool UpdateOffscrenComposition(const FlutterLayer** layers, size_t layers_count) = 0; // TODO(gw280): encapsulate these properly for subclasses to use std::unique_ptr<EmbedderTestBackingStoreProducer> backingstore_producer_; const SkISize surface_size_; sk_sp<GrDirectContext> context_; PlatformViewRendererCallback platform_view_renderer_callback_; bool present_callback_is_one_shot_ = false; PresentCallback present_callback_; NextSceneCallback next_scene_callback_; sk_sp<SkImage> last_composition_; size_t backing_stores_created_ = 0; size_t backing_stores_collected_ = 0; std::vector<fml::closure> on_create_render_target_callbacks_; std::vector<fml::closure> on_collect_render_target_callbacks_; std::vector<fml::closure> on_present_callbacks_; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositor); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_H_
engine/shell/platform/embedder/tests/embedder_test_compositor.h/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_compositor.h", "repo_id": "engine", "token_count": 1402 }
397
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_SOFTWARE_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_SOFTWARE_H_ #include "flutter/shell/platform/embedder/tests/embedder_test_context.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { namespace testing { class EmbedderTestContextSoftware : public EmbedderTestContext { public: explicit EmbedderTestContextSoftware(std::string assets_path = ""); ~EmbedderTestContextSoftware() override; size_t GetSurfacePresentCount() const override; // |EmbedderTestContext| EmbedderTestContextType GetContextType() const override; bool Present(const sk_sp<SkImage>& image); protected: virtual void SetupCompositor() override; private: sk_sp<SkSurface> surface_; SkISize surface_size_; size_t software_surface_present_count_ = 0; void SetupSurface(SkISize surface_size) override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextSoftware); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_SOFTWARE_H_
engine/shell/platform/embedder/tests/embedder_test_context_software.h/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_context_software.h", "repo_id": "engine", "token_count": 442 }
398
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "dart-pkg/fuchsia/sdk_ext/fuchsia.h" #include <zircon/syscalls.h> #include <cstdio> #include <cstring> #include <memory> #include <vector> #include "dart-pkg/zircon/sdk_ext/handle.h" #include "dart-pkg/zircon/sdk_ext/natives.h" #include "dart-pkg/zircon/sdk_ext/system.h" #include "flutter/fml/size.h" #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_class_library.h" #include "third_party/tonic/dart_class_provider.h" #include "third_party/tonic/dart_library_natives.h" #include "third_party/tonic/dart_state.h" #include "third_party/tonic/logging/dart_invoke.h" #include "third_party/tonic/typed_data/typed_list.h" using tonic::ToDart; namespace fuchsia { namespace dart { namespace { static tonic::DartLibraryNatives* g_natives; tonic::DartLibraryNatives* InitNatives() { tonic::DartLibraryNatives* natives = new tonic::DartLibraryNatives(); return natives; } #define REGISTER_FUNCTION(name, count) {"" #name, name, count}, #define DECLARE_FUNCTION(name, count) \ extern void name(Dart_NativeArguments args); #define FIDL_NATIVE_LIST(V) V(SetReturnCode, 1) FIDL_NATIVE_LIST(DECLARE_FUNCTION); static struct NativeEntries { const char* name; Dart_NativeFunction function; int argument_count; } Entries[] = {FIDL_NATIVE_LIST(REGISTER_FUNCTION)}; Dart_NativeFunction NativeLookup(Dart_Handle name, int argument_count, bool* auto_setup_scope) { const char* function_name = nullptr; Dart_Handle result = Dart_StringToCString(name, &function_name); if (Dart_IsError(result)) { Dart_PropagateError(result); } FML_DCHECK(function_name != nullptr); FML_DCHECK(auto_setup_scope != nullptr); *auto_setup_scope = true; size_t num_entries = fml::size(Entries); for (size_t i = 0; i < num_entries; ++i) { const struct NativeEntries& entry = Entries[i]; if (!strcmp(function_name, entry.name) && (entry.argument_count == argument_count)) { return entry.function; } } if (!g_natives) g_natives = InitNatives(); return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope); } const uint8_t* NativeSymbol(Dart_NativeFunction native_function) { size_t num_entries = fml::size(Entries); for (size_t i = 0; i < num_entries; ++i) { const struct NativeEntries& entry = Entries[i]; if (entry.function == native_function) { return reinterpret_cast<const uint8_t*>(entry.name); } } if (!g_natives) g_natives = InitNatives(); return g_natives->GetSymbol(native_function); } void SetReturnCode(Dart_NativeArguments arguments) { int64_t return_code; Dart_Handle status = Dart_GetNativeIntegerArgument(arguments, 0, &return_code); if (!tonic::CheckAndHandleError(status)) { tonic::DartState::Current()->SetReturnCode(return_code); } } } // namespace void Initialize(zx::channel directory_request, std::optional<zx::eventpair> view_ref) { zircon::dart::Initialize(); Dart_Handle library = Dart_LookupLibrary(ToDart("dart:fuchsia")); FML_CHECK(!tonic::CheckAndHandleError(library)); Dart_Handle result = Dart_SetNativeResolver( library, fuchsia::dart::NativeLookup, fuchsia::dart::NativeSymbol); FML_CHECK(!tonic::CheckAndHandleError(result)); auto dart_state = tonic::DartState::Current(); std::unique_ptr<tonic::DartClassProvider> fuchsia_class_provider( new tonic::DartClassProvider(dart_state, "dart:fuchsia")); dart_state->class_library().add_provider("fuchsia", std::move(fuchsia_class_provider)); if (directory_request) { result = Dart_SetField( library, ToDart("_outgoingServices"), ToDart(zircon::dart::Handle::Create(std::move(directory_request)))); FML_CHECK(!tonic::CheckAndHandleError(result)); } if (view_ref) { result = Dart_SetField( library, ToDart("_viewRef"), ToDart(zircon::dart::Handle::Create((*view_ref).release()))); FML_CHECK(!tonic::CheckAndHandleError(result)); } } } // namespace dart } // namespace fuchsia
engine/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/fuchsia/sdk_ext/fuchsia.cc", "repo_id": "engine", "token_count": 1734 }
399
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "handle_disposition.h" #include <algorithm> #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_class_library.h" using tonic::ToDart; namespace zircon { namespace dart { IMPLEMENT_WRAPPERTYPEINFO(zircon, HandleDisposition); void HandleDisposition_constructor(Dart_NativeArguments args) { DartCallConstructor(&HandleDisposition::create, args); } fml::RefPtr<HandleDisposition> HandleDisposition::create( zx_handle_op_t operation, fml::RefPtr<dart::Handle> handle, zx_obj_type_t type, zx_rights_t rights) { return fml::MakeRefCounted<HandleDisposition>(operation, handle, type, rights, ZX_OK); } // clang-format: off #define FOR_EACH_STATIC_BINDING(V) V(HandleDisposition, create) #define FOR_EACH_BINDING(V) \ V(HandleDisposition, operation) \ V(HandleDisposition, handle) \ V(HandleDisposition, type) \ V(HandleDisposition, rights) \ V(HandleDisposition, result) // clang-format: on // Tonic is missing a comma. #define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \ DART_REGISTER_NATIVE_STATIC(CLASS, METHOD), FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC) FOR_EACH_BINDING(DART_NATIVE_NO_UI_CHECK_CALLBACK) void HandleDisposition::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({{"HandleDisposition_constructor", HandleDisposition_constructor, 5, true}, FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_) FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } } // namespace dart } // namespace zircon
engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_disposition.cc", "repo_id": "engine", "token_count": 746 }
400
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CLOCK_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CLOCK_H_ #include "macros.h" #include <stdint.h> #ifdef __cplusplus extern "C" { #endif ZIRCON_FFI_EXPORT uint64_t zircon_dart_clock_get_monotonic(); #ifdef __cplusplus } #endif #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CLOCK_H_
engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/clock.h", "repo_id": "engine", "token_count": 241 }
401
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_H_ #include <dart/test/cpp/fidl.h> #include <fuchsia/component/runner/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async/cpp/wait.h> #include <lib/fdio/namespace.h> #include <lib/fidl/cpp/binding.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/fidl/cpp/string.h> #include <lib/sys/cpp/component_context.h> #include <lib/sys/cpp/service_directory.h> #include <lib/vfs/cpp/pseudo_dir.h> #include <lib/zx/timer.h> #include <memory> #include "runtime/dart/utils/mapped_resource.h" #include "third_party/dart/runtime/include/dart_api.h" namespace dart_runner { /// Starts a Dart component written in CFv2. class DartComponentController : public dart::test::Echo, public fuchsia::component::runner::ComponentController { public: DartComponentController( fuchsia::component::runner::ComponentStartInfo start_info, std::shared_ptr<sys::ServiceDirectory> runner_incoming_services, fidl::InterfaceRequest<fuchsia::component::runner::ComponentController> controller); ~DartComponentController() override; /// Sets up the controller. /// /// This should be called before |Run|. bool SetUp(); /// Runs the Dart component in a task, sending the return code back to /// the Fuchsia component controller. /// /// This should be called after |SetUp|. void Run(); private: /// Helper for actually running the Dart main. Returns true if successful, /// false otherwise. bool RunDartMain(); /// Creates and binds the namespace for this component. Returns true if /// successful, false otherwise. bool CreateAndBindNamespace(); bool SetUpFromKernel(); bool SetUpFromAppSnapshot(); bool CreateIsolate(const uint8_t* isolate_snapshot_data, const uint8_t* isolate_snapshot_instructions); // |Echo| void EchoString(fidl::StringPtr value, EchoStringCallback callback) override; // |ComponentController| void Kill() override; void Stop() override; // Idle notification. void MessageEpilogue(Dart_Handle result); void OnIdleTimer(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal* signal); // The loop must be the first declared member so that it gets destroyed after // binding_ which expects the existence of a loop. std::unique_ptr<async::Loop> loop_; std::string label_; std::string url_; std::string data_path_; std::shared_ptr<sys::ServiceDirectory> runner_incoming_services_; std::unique_ptr<sys::ComponentContext> context_; std::unique_ptr<vfs::PseudoDir> dart_outgoing_dir_; fuchsia::io::DirectoryPtr dart_outgoing_dir_ptr_; fidl::InterfaceRequest<fuchsia::io::Directory> dart_outgoing_dir_request_; fuchsia::io::NodePtr dart_outgoing_dir_ptr_to_check_on_open_; fuchsia::component::runner::ComponentStartInfo start_info_; fidl::Binding<fuchsia::component::runner::ComponentController> binding_; fidl::BindingSet<dart::test::Echo> echo_binding_; fdio_ns_t* namespace_ = nullptr; int stdout_fd_ = -1; int stderr_fd_ = -1; dart_utils::ElfSnapshot elf_snapshot_; // AOT snapshot dart_utils::MappedResource isolate_snapshot_data_; // JIT snapshot dart_utils::MappedResource isolate_snapshot_instructions_; // JIT snapshot std::vector<dart_utils::MappedResource> kernel_peices_; Dart_Isolate isolate_; int32_t return_code_ = 0; zx::time idle_start_{0}; zx::timer idle_timer_; async::WaitMethod<DartComponentController, &DartComponentController::OnIdleTimer> idle_wait_{this}; // Disallow copy and assignment. DartComponentController(const DartComponentController&) = delete; DartComponentController& operator=(const DartComponentController&) = delete; }; } // namespace dart_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_COMPONENT_CONTROLLER_H_
engine/shell/platform/fuchsia/dart_runner/dart_component_controller.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/dart_component_controller.h", "repo_id": "engine", "token_count": 1541 }
402
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/tools/fuchsia/dart/dart_component.gni") import("//flutter/tools/fuchsia/dart/dart_library.gni") import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") dart_library("lib") { testonly = true package_name = "dart_echo_server" source_dir = "." sources = [ "main.dart" ] } # Dart component that serves the test Echo FIDL protocol, built using the Dart AOT runner dart_component("aot_component") { testonly = true main_package = "dart_echo_server" manifest = "meta/dart-aot-echo-server.cml" component_name = "dart_aot_echo_server" deps = [ ":lib" ] } # Dart component that serves the test Echo FIDL protocol, built using the Dart AOT runner dart_component("jit_component") { testonly = true main_package = "dart_echo_server" manifest = "meta/dart-jit-echo-server.cml" component_name = "dart_jit_echo_server" deps = [ ":lib" ] } fuchsia_package("aot_echo_package") { testonly = true package_name = "dart_aot_echo_server" deps = [ ":aot_component", # "OOT" copy of the runner used by tests, to avoid conflicting with the # runners in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. "//flutter/shell/platform/fuchsia/dart_runner:oot_dart_aot_runner", ] } fuchsia_package("jit_echo_package") { testonly = true package_name = "dart_jit_echo_server" deps = [ ":jit_component", # "OOT" copy of the runner used by tests, to avoid conflicting with the # runners in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. "//flutter/shell/platform/fuchsia/dart_runner:oot_dart_jit_runner", ] }
engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/BUILD.gn", "repo_id": "engine", "token_count": 701 }
403
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/fuchsia/flutter/accessibility_bridge.h" #include <lib/inspect/cpp/inspector.h> #include <lib/zx/process.h> #include <zircon/status.h> #include <zircon/types.h> #include <algorithm> #include <deque> #include "flutter/fml/logging.h" #include "flutter/lib/ui/semantics/semantics_node.h" #include "../runtime/dart/utils/root_inspect_node.h" namespace flutter_runner { namespace { #if !FLUTTER_RELEASE static constexpr char kTreeDumpInspectRootName[] = "semantic_tree_root"; // Converts flutter semantic node flags to a string representation. std::string NodeFlagsToString(const flutter::SemanticsNode& node) { std::string output; if (node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { output += "kHasCheckedState|"; } if (node.HasFlag(flutter::SemanticsFlags::kHasEnabledState)) { output += "kHasEnabledState|"; } if (node.HasFlag(flutter::SemanticsFlags::kHasImplicitScrolling)) { output += "kHasImplicitScrolling|"; } if (node.HasFlag(flutter::SemanticsFlags::kHasToggledState)) { output += "kHasToggledState|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsButton)) { output += "kIsButton|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsChecked)) { output += "kIsChecked|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsEnabled)) { output += "kIsEnabled|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsFocusable)) { output += "kIsFocusable|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsFocused)) { output += "kIsFocused|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsHeader)) { output += "kIsHeader|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsHidden)) { output += "kIsHidden|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsImage)) { output += "kIsImage|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup)) { output += "kIsInMutuallyExclusiveGroup|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsKeyboardKey)) { output += "kIsKeyboardKey|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsLink)) { output += "kIsLink|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsLiveRegion)) { output += "kIsLiveRegion|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsObscured)) { output += "kIsObscured|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsReadOnly)) { output += "kIsReadOnly|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsSelected)) { output += "kIsSelected|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsSlider)) { output += "kIsSlider|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsTextField)) { output += "kIsTextField|"; } if (node.HasFlag(flutter::SemanticsFlags::kIsToggled)) { output += "kIsToggled|"; } if (node.HasFlag(flutter::SemanticsFlags::kNamesRoute)) { output += "kNamesRoute|"; } if (node.HasFlag(flutter::SemanticsFlags::kScopesRoute)) { output += "kScopesRoute|"; } return output; } // Converts flutter semantic node actions to a string representation. std::string NodeActionsToString(const flutter::SemanticsNode& node) { std::string output; if (node.HasAction(flutter::SemanticsAction::kCopy)) { output += "kCopy|"; } if (node.HasAction(flutter::SemanticsAction::kCustomAction)) { output += "kCustomAction|"; } if (node.HasAction(flutter::SemanticsAction::kCut)) { output += "kCut|"; } if (node.HasAction(flutter::SemanticsAction::kDecrease)) { output += "kDecrease|"; } if (node.HasAction(flutter::SemanticsAction::kDidGainAccessibilityFocus)) { output += "kDidGainAccessibilityFocus|"; } if (node.HasAction(flutter::SemanticsAction::kDidLoseAccessibilityFocus)) { output += "kDidLoseAccessibilityFocus|"; } if (node.HasAction(flutter::SemanticsAction::kDismiss)) { output += "kDismiss|"; } if (node.HasAction(flutter::SemanticsAction::kIncrease)) { output += "kIncrease|"; } if (node.HasAction(flutter::SemanticsAction::kLongPress)) { output += "kLongPress|"; } if (node.HasAction( flutter::SemanticsAction::kMoveCursorBackwardByCharacter)) { output += "kMoveCursorBackwardByCharacter|"; } if (node.HasAction(flutter::SemanticsAction::kMoveCursorBackwardByWord)) { output += "kMoveCursorBackwardByWord|"; } if (node.HasAction(flutter::SemanticsAction::kMoveCursorForwardByCharacter)) { output += "kMoveCursorForwardByCharacter|"; } if (node.HasAction(flutter::SemanticsAction::kMoveCursorForwardByWord)) { output += "kMoveCursorForwardByWord|"; } if (node.HasAction(flutter::SemanticsAction::kPaste)) { output += "kPaste|"; } if (node.HasAction(flutter::SemanticsAction::kScrollDown)) { output += "kScrollDown|"; } if (node.HasAction(flutter::SemanticsAction::kScrollLeft)) { output += "kScrollLeft|"; } if (node.HasAction(flutter::SemanticsAction::kScrollRight)) { output += "kScrollRight|"; } if (node.HasAction(flutter::SemanticsAction::kScrollUp)) { output += "kScrollUp|"; } if (node.HasAction(flutter::SemanticsAction::kSetSelection)) { output += "kSetSelection|"; } if (node.HasAction(flutter::SemanticsAction::kSetText)) { output += "kSetText|"; } if (node.HasAction(flutter::SemanticsAction::kShowOnScreen)) { output += "kShowOnScreen|"; } if (node.HasAction(flutter::SemanticsAction::kTap)) { output += "kTap|"; } return output; } // Returns a string representation of the flutter semantic node absolut // location. std::string NodeLocationToString(const SkRect& rect) { auto min_x = rect.fLeft; auto min_y = rect.fTop; auto max_x = rect.fRight; auto max_y = rect.fBottom; std::string location = "min(" + std::to_string(min_x) + ", " + std::to_string(min_y) + ") max(" + std::to_string(max_x) + ", " + std::to_string(max_y) + ")"; return location; } // Returns a string representation of the node's different types of children. std::string NodeChildrenToString(const flutter::SemanticsNode& node) { std::stringstream output; if (!node.childrenInTraversalOrder.empty()) { output << "children in traversal order:["; for (const auto child_id : node.childrenInTraversalOrder) { output << child_id << ", "; } output << "]\n"; } if (!node.childrenInHitTestOrder.empty()) { output << "children in hit test order:["; for (const auto child_id : node.childrenInHitTestOrder) { output << child_id << ", "; } output << ']'; } return output.str(); } #endif // !FLUTTER_RELEASE } // namespace AccessibilityBridge::AccessibilityBridge( SetSemanticsEnabledCallback set_semantics_enabled_callback, DispatchSemanticsActionCallback dispatch_semantics_action_callback, fuchsia::accessibility::semantics::SemanticsManagerHandle semantics_manager, fuchsia::ui::views::ViewRef view_ref, inspect::Node inspect_node) : set_semantics_enabled_callback_( std::move(set_semantics_enabled_callback)), dispatch_semantics_action_callback_( std::move(dispatch_semantics_action_callback)), binding_(this), fuchsia_semantics_manager_(semantics_manager.Bind()), atomic_updates_(std::make_shared<std::queue<FuchsiaAtomicUpdate>>()), inspect_node_(std::move(inspect_node)) { fuchsia_semantics_manager_.set_error_handler([](zx_status_t status) { FML_LOG(ERROR) << "Flutter cannot connect to SemanticsManager with status: " << zx_status_get_string(status) << "."; }); fuchsia_semantics_manager_->RegisterViewForSemantics( std::move(view_ref), binding_.NewBinding(), tree_ptr_.NewRequest()); #if !FLUTTER_RELEASE // The first argument to |CreateLazyValues| is the name of the lazy node, and // will only be displayed if the callback used to generate the node's content // fails. Therefore, we use an error message for this node name. inspect_node_tree_dump_ = inspect_node_.CreateLazyValues("dump_fail", [this]() { inspect::Inspector inspector; if (auto it = nodes_.find(kRootNodeId); it == nodes_.end()) { inspector.GetRoot().CreateString( "empty_tree", "this semantic tree is empty", &inspector); } else { FillInspectTree( kRootNodeId, /*current_level=*/1, inspector.GetRoot().CreateChild(kTreeDumpInspectRootName), &inspector); } return fpromise::make_ok_promise(std::move(inspector)); }); #endif // !FLUTTER_RELEASE } bool AccessibilityBridge::GetSemanticsEnabled() const { return semantics_enabled_; } void AccessibilityBridge::SetSemanticsEnabled(bool enabled) { semantics_enabled_ = enabled; if (!enabled) { nodes_.clear(); } } fuchsia::ui::gfx::BoundingBox AccessibilityBridge::GetNodeLocation( const flutter::SemanticsNode& node) const { fuchsia::ui::gfx::BoundingBox box; box.min.x = node.rect.fLeft; box.min.y = node.rect.fTop; box.min.z = static_cast<float>(node.elevation); box.max.x = node.rect.fRight; box.max.y = node.rect.fBottom; box.max.z = static_cast<float>(node.thickness); return box; } fuchsia::ui::gfx::mat4 AccessibilityBridge::GetNodeTransform( const flutter::SemanticsNode& node) const { return ConvertSkiaTransformToMat4(node.transform); } fuchsia::ui::gfx::mat4 AccessibilityBridge::ConvertSkiaTransformToMat4( const SkM44 transform) const { fuchsia::ui::gfx::mat4 value; float* m = value.matrix.data(); transform.getColMajor(m); return value; } fuchsia::accessibility::semantics::Attributes AccessibilityBridge::GetNodeAttributes(const flutter::SemanticsNode& node, size_t* added_size) const { fuchsia::accessibility::semantics::Attributes attributes; // TODO(MI4-2531): Don't truncate. if (node.label.size() > fuchsia::accessibility::semantics::MAX_LABEL_SIZE) { attributes.set_label(node.label.substr( 0, fuchsia::accessibility::semantics::MAX_LABEL_SIZE)); *added_size += fuchsia::accessibility::semantics::MAX_LABEL_SIZE; } else { attributes.set_label(node.label); *added_size += node.label.size(); } if (node.tooltip.size() > fuchsia::accessibility::semantics::MAX_LABEL_SIZE) { attributes.set_secondary_label(node.tooltip.substr( 0, fuchsia::accessibility::semantics::MAX_LABEL_SIZE)); *added_size += fuchsia::accessibility::semantics::MAX_LABEL_SIZE; } else { attributes.set_secondary_label(node.tooltip); *added_size += node.tooltip.size(); } if (node.HasFlag(flutter::SemanticsFlags::kIsKeyboardKey)) { attributes.set_is_keyboard_key(true); } return attributes; } fuchsia::accessibility::semantics::States AccessibilityBridge::GetNodeStates( const flutter::SemanticsNode& node, size_t* additional_size) const { fuchsia::accessibility::semantics::States states; (*additional_size) += sizeof(fuchsia::accessibility::semantics::States); // Set checked state. if (!node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { states.set_checked_state( fuchsia::accessibility::semantics::CheckedState::NONE); } else { states.set_checked_state( node.HasFlag(flutter::SemanticsFlags::kIsChecked) ? fuchsia::accessibility::semantics::CheckedState::CHECKED : fuchsia::accessibility::semantics::CheckedState::UNCHECKED); } // Set enabled state. if (node.HasFlag(flutter::SemanticsFlags::kHasEnabledState)) { states.set_enabled_state( node.HasFlag(flutter::SemanticsFlags::kIsEnabled) ? fuchsia::accessibility::semantics::EnabledState::ENABLED : fuchsia::accessibility::semantics::EnabledState::DISABLED); } // Set selected state. states.set_selected(node.HasFlag(flutter::SemanticsFlags::kIsSelected)); // Flutter's definition of a hidden node is different from Fuchsia, so it must // not be set here. // Set value. if (node.value.size() > fuchsia::accessibility::semantics::MAX_VALUE_SIZE) { states.set_value(node.value.substr( 0, fuchsia::accessibility::semantics::MAX_VALUE_SIZE)); (*additional_size) += fuchsia::accessibility::semantics::MAX_VALUE_SIZE; } else { states.set_value(node.value); (*additional_size) += node.value.size(); } // Set toggled state. if (node.HasFlag(flutter::SemanticsFlags::kHasToggledState)) { states.set_toggled_state( node.HasFlag(flutter::SemanticsFlags::kIsToggled) ? fuchsia::accessibility::semantics::ToggledState::ON : fuchsia::accessibility::semantics::ToggledState::OFF); } return states; } std::vector<fuchsia::accessibility::semantics::Action> AccessibilityBridge::GetNodeActions(const flutter::SemanticsNode& node, size_t* additional_size) const { std::vector<fuchsia::accessibility::semantics::Action> node_actions; if (node.HasAction(flutter::SemanticsAction::kTap)) { node_actions.push_back(fuchsia::accessibility::semantics::Action::DEFAULT); } if (node.HasAction(flutter::SemanticsAction::kLongPress)) { node_actions.push_back( fuchsia::accessibility::semantics::Action::SECONDARY); } if (node.HasAction(flutter::SemanticsAction::kShowOnScreen)) { node_actions.push_back( fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN); } if (node.HasAction(flutter::SemanticsAction::kIncrease)) { node_actions.push_back( fuchsia::accessibility::semantics::Action::INCREMENT); } if (node.HasAction(flutter::SemanticsAction::kDecrease)) { node_actions.push_back( fuchsia::accessibility::semantics::Action::DECREMENT); } *additional_size += node_actions.size() * sizeof(fuchsia::accessibility::semantics::Action); return node_actions; } fuchsia::accessibility::semantics::Role AccessibilityBridge::GetNodeRole( const flutter::SemanticsNode& node) const { if (node.HasFlag(flutter::SemanticsFlags::kIsButton)) { return fuchsia::accessibility::semantics::Role::BUTTON; } if (node.HasFlag(flutter::SemanticsFlags::kIsTextField)) { return fuchsia::accessibility::semantics::Role::TEXT_FIELD; } if (node.HasFlag(flutter::SemanticsFlags::kIsLink)) { return fuchsia::accessibility::semantics::Role::LINK; } if (node.HasFlag(flutter::SemanticsFlags::kIsSlider)) { return fuchsia::accessibility::semantics::Role::SLIDER; } if (node.HasFlag(flutter::SemanticsFlags::kIsHeader)) { return fuchsia::accessibility::semantics::Role::HEADER; } if (node.HasFlag(flutter::SemanticsFlags::kIsImage)) { return fuchsia::accessibility::semantics::Role::IMAGE; } // If a flutter node supports the kIncrease or kDecrease actions, it can be // treated as a slider control by assistive technology. This is important // because users have special gestures to deal with sliders, and Fuchsia API // requires nodes that can receive this kind of action to be a slider control. if (node.HasAction(flutter::SemanticsAction::kIncrease) || node.HasAction(flutter::SemanticsAction::kDecrease)) { return fuchsia::accessibility::semantics::Role::SLIDER; } // If a flutter node has a checked state, then we assume it is either a // checkbox or a radio button. We distinguish between checkboxes and // radio buttons based on membership in a mutually exclusive group. if (node.HasFlag(flutter::SemanticsFlags::kHasCheckedState)) { if (node.HasFlag(flutter::SemanticsFlags::kIsInMutuallyExclusiveGroup)) { return fuchsia::accessibility::semantics::Role::RADIO_BUTTON; } else { return fuchsia::accessibility::semantics::Role::CHECK_BOX; } } if (node.HasFlag(flutter::SemanticsFlags::kHasToggledState)) { return fuchsia::accessibility::semantics::Role::TOGGLE_SWITCH; } return fuchsia::accessibility::semantics::Role::UNKNOWN; } std::unordered_set<int32_t> AccessibilityBridge::GetDescendants( int32_t node_id) const { std::unordered_set<int32_t> descendents; std::deque<int32_t> to_process = {node_id}; while (!to_process.empty()) { int32_t id = to_process.front(); to_process.pop_front(); descendents.emplace(id); auto it = nodes_.find(id); if (it != nodes_.end()) { const auto& node = it->second.data; for (const auto& child : node.childrenInHitTestOrder) { if (descendents.find(child) == descendents.end()) { to_process.push_back(child); } else { // This indicates either a cycle or a child with multiple parents. // Flutter should never let this happen, but the engine API does not // explicitly forbid it right now. // TODO(http://fxbug.dev/75905): Crash flutter accessibility bridge // when a cycle in the tree is found. FML_LOG(ERROR) << "Semantics Node " << child << " has already been listed as a child of another " "node, ignoring for parent " << id << "."; } } } } return descendents; } // The only known usage of a negative number for a node ID is in the embedder // API as a sentinel value, which is not expected here. No valid producer of // nodes should give us a negative ID. static uint32_t FlutterIdToFuchsiaId(int32_t flutter_node_id) { FML_DCHECK(flutter_node_id >= 0) << "Unexpectedly received a negative semantics node ID."; return static_cast<uint32_t>(flutter_node_id); } void AccessibilityBridge::PruneUnreachableNodes( FuchsiaAtomicUpdate* atomic_update) { const auto& reachable_nodes = GetDescendants(kRootNodeId); auto iter = nodes_.begin(); while (iter != nodes_.end()) { int32_t id = iter->first; if (reachable_nodes.find(id) == reachable_nodes.end()) { atomic_update->AddNodeDeletion(FlutterIdToFuchsiaId(id)); iter = nodes_.erase(iter); } else { iter++; } } } // TODO(FIDL-718) - remove this, handle the error instead in something like // set_error_handler. static void PrintNodeSizeError(uint32_t node_id) { FML_LOG(ERROR) << "Semantics node with ID " << node_id << " exceeded the maximum FIDL message size and may not " "be delivered to the accessibility manager service."; } void AccessibilityBridge::AddSemanticsNodeUpdate( const flutter::SemanticsNodeUpdates update, float view_pixel_ratio) { if (update.empty()) { return; } FML_DCHECK(nodes_.find(kRootNodeId) != nodes_.end() || update.find(kRootNodeId) != update.end()) << "AccessibilityBridge received an update with out ever getting a root " "node."; FuchsiaAtomicUpdate atomic_update; bool has_root_node_update = false; // TODO(MI4-2498): Actions, Roles, hit test children, additional // flags/states/attr // TODO(MI4-1478): Support for partial updates for nodes > 64kb // e.g. if a node has a long label or more than 64k children. for (const auto& [flutter_node_id, flutter_node] : update) { size_t this_node_size = sizeof(fuchsia::accessibility::semantics::Node); // We handle root update separately in GetRootNodeUpdate. // TODO(chunhtai): remove this special case after we remove the inverse // view pixel ratio transformation in scenic view. // TODO(http://fxbug.dev/75908): Investigate flutter a11y bridge refactor // after removal of the inverse view pixel ratio transformation in scenic // view). if (flutter_node.id == kRootNodeId) { root_flutter_semantics_node_ = flutter_node; has_root_node_update = true; continue; } // Store the nodes for later hit testing and logging. nodes_[flutter_node.id].data = flutter_node; fuchsia::accessibility::semantics::Node fuchsia_node; std::vector<uint32_t> child_ids; // Send the nodes in traversal order, so the manager can figure out // traversal. for (int32_t flutter_child_id : flutter_node.childrenInTraversalOrder) { child_ids.push_back(FlutterIdToFuchsiaId(flutter_child_id)); } // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in // the flutter accessibility bridge. fuchsia_node.set_node_id(flutter_node.id) .set_role(GetNodeRole(flutter_node)) .set_location(GetNodeLocation(flutter_node)) .set_transform(GetNodeTransform(flutter_node)) .set_attributes(GetNodeAttributes(flutter_node, &this_node_size)) .set_states(GetNodeStates(flutter_node, &this_node_size)) .set_actions(GetNodeActions(flutter_node, &this_node_size)) .set_child_ids(child_ids); this_node_size += kNodeIdSize * flutter_node.childrenInTraversalOrder.size(); atomic_update.AddNodeUpdate(std::move(fuchsia_node), this_node_size); } // Handles root node update. if (has_root_node_update || last_seen_view_pixel_ratio_ != view_pixel_ratio) { last_seen_view_pixel_ratio_ = view_pixel_ratio; size_t root_node_size; fuchsia::accessibility::semantics::Node root_update = GetRootNodeUpdate(root_node_size); atomic_update.AddNodeUpdate(std::move(root_update), root_node_size); } PruneUnreachableNodes(&atomic_update); UpdateScreenRects(); atomic_updates_->push(std::move(atomic_update)); if (atomic_updates_->size() == 1) { // There were no commits in the queue, so send this one. Apply(&atomic_updates_->front()); } } fuchsia::accessibility::semantics::Node AccessibilityBridge::GetRootNodeUpdate( size_t& node_size) { fuchsia::accessibility::semantics::Node root_fuchsia_node; std::vector<uint32_t> child_ids; node_size = sizeof(fuchsia::accessibility::semantics::Node); for (int32_t flutter_child_id : root_flutter_semantics_node_.childrenInTraversalOrder) { child_ids.push_back(FlutterIdToFuchsiaId(flutter_child_id)); } // Applies the inverse view pixel ratio transformation to the root node. float inverse_view_pixel_ratio = 1.f / last_seen_view_pixel_ratio_; SkM44 inverse_view_pixel_ratio_transform; inverse_view_pixel_ratio_transform.setScale(inverse_view_pixel_ratio, inverse_view_pixel_ratio, 1.f); SkM44 result = root_flutter_semantics_node_.transform * inverse_view_pixel_ratio_transform; nodes_[root_flutter_semantics_node_.id].data = root_flutter_semantics_node_; // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in // the flutter accessibility bridge. root_fuchsia_node.set_node_id(root_flutter_semantics_node_.id) .set_role(GetNodeRole(root_flutter_semantics_node_)) .set_location(GetNodeLocation(root_flutter_semantics_node_)) .set_transform(ConvertSkiaTransformToMat4(result)) .set_attributes( GetNodeAttributes(root_flutter_semantics_node_, &node_size)) .set_states(GetNodeStates(root_flutter_semantics_node_, &node_size)) .set_actions(GetNodeActions(root_flutter_semantics_node_, &node_size)) .set_child_ids(child_ids); node_size += kNodeIdSize * root_flutter_semantics_node_.childrenInTraversalOrder.size(); return root_fuchsia_node; } void AccessibilityBridge::RequestAnnounce(const std::string message) { fuchsia::accessibility::semantics::SemanticEvent semantic_event; fuchsia::accessibility::semantics::AnnounceEvent announce_event; announce_event.set_message(message); semantic_event.set_announce(std::move(announce_event)); tree_ptr_->SendSemanticEvent(std::move(semantic_event), []() {}); } void AccessibilityBridge::UpdateScreenRects() { std::unordered_set<int32_t> visited_nodes; // The embedder applies a special pixel ratio transform to the root of the // view, and the accessibility bridge applies the inverse of this transform // to the root node. However, this transform is not persisted in the flutter // representation of the root node, so we need to account for it explicitly // here. float inverse_view_pixel_ratio = 1.f / last_seen_view_pixel_ratio_; SkM44 inverse_view_pixel_ratio_transform; inverse_view_pixel_ratio_transform.setScale(inverse_view_pixel_ratio, inverse_view_pixel_ratio, 1.f); UpdateScreenRects(kRootNodeId, inverse_view_pixel_ratio_transform, &visited_nodes); } void AccessibilityBridge::UpdateScreenRects( int32_t node_id, SkM44 parent_transform, std::unordered_set<int32_t>* visited_nodes) { auto it = nodes_.find(node_id); if (it == nodes_.end()) { FML_LOG(ERROR) << "UpdateScreenRects called on unknown node"; return; } auto& node = it->second; const auto& current_transform = parent_transform * node.data.transform; const auto& rect = node.data.rect; SkV4 dst[2] = { current_transform.map(rect.left(), rect.top(), 0, 1), current_transform.map(rect.right(), rect.bottom(), 0, 1), }; node.screen_rect.setLTRB(dst[0].x, dst[0].y, dst[1].x, dst[1].y); node.screen_rect.sort(); visited_nodes->emplace(node_id); for (uint32_t child_id : node.data.childrenInHitTestOrder) { if (visited_nodes->find(child_id) == visited_nodes->end()) { UpdateScreenRects(child_id, current_transform, visited_nodes); } } } std::optional<flutter::SemanticsAction> AccessibilityBridge::GetFlutterSemanticsAction( fuchsia::accessibility::semantics::Action fuchsia_action, uint32_t node_id) { switch (fuchsia_action) { // The default action associated with the element. case fuchsia::accessibility::semantics::Action::DEFAULT: return flutter::SemanticsAction::kTap; // The secondary action associated with the element. This may correspond to // a long press (touchscreens) or right click (mouse). case fuchsia::accessibility::semantics::Action::SECONDARY: return flutter::SemanticsAction::kLongPress; // Set (input/non-accessibility) focus on this element. case fuchsia::accessibility::semantics::Action::SET_FOCUS: FML_LOG(WARNING) << "Unsupported action SET_FOCUS sent for accessibility node " << node_id; return {}; // Set the element's value. case fuchsia::accessibility::semantics::Action::SET_VALUE: FML_LOG(WARNING) << "Unsupported action SET_VALUE sent for accessibility node " << node_id; return {}; // Scroll node to make it visible. case fuchsia::accessibility::semantics::Action::SHOW_ON_SCREEN: return flutter::SemanticsAction::kShowOnScreen; case fuchsia::accessibility::semantics::Action::INCREMENT: return flutter::SemanticsAction::kIncrease; case fuchsia::accessibility::semantics::Action::DECREMENT: return flutter::SemanticsAction::kDecrease; default: FML_LOG(WARNING) << "Unexpected action " << static_cast<int32_t>(fuchsia_action) << " sent for accessibility node " << node_id; return {}; } } // |fuchsia::accessibility::semantics::SemanticListener| void AccessibilityBridge::OnAccessibilityActionRequested( uint32_t node_id, fuchsia::accessibility::semantics::Action action, fuchsia::accessibility::semantics::SemanticListener:: OnAccessibilityActionRequestedCallback callback) { // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in // the flutter accessibility bridge. if (nodes_.find(node_id) == nodes_.end()) { FML_LOG(ERROR) << "Attempted to send accessibility action " << static_cast<int32_t>(action) << " to unknown node id: " << node_id; callback(false); return; } std::optional<flutter::SemanticsAction> flutter_action = GetFlutterSemanticsAction(action, node_id); if (!flutter_action.has_value()) { callback(false); return; } dispatch_semantics_action_callback_(static_cast<int32_t>(node_id), flutter_action.value()); callback(true); } // |fuchsia::accessibility::semantics::SemanticListener| void AccessibilityBridge::HitTest( fuchsia::math::PointF local_point, fuchsia::accessibility::semantics::SemanticListener::HitTestCallback callback) { auto hit_node_id = GetHitNode(kRootNodeId, local_point.x, local_point.y); FML_DCHECK(hit_node_id.has_value()); fuchsia::accessibility::semantics::Hit hit; // TODO(http://fxbug.dev/75910): check the usage of FlutterIdToFuchsiaId in // the flutter accessibility bridge. hit.set_node_id(hit_node_id.value_or(kRootNodeId)); callback(std::move(hit)); } std::optional<int32_t> AccessibilityBridge::GetHitNode(int32_t node_id, float x, float y) { auto it = nodes_.find(node_id); if (it == nodes_.end()) { FML_LOG(ERROR) << "Attempted to hit test unknown node id: " << node_id; return {}; } auto const& node = it->second; if (node.data.flags & static_cast<int32_t>(flutter::SemanticsFlags::kIsHidden) || // !node.screen_rect.contains(x, y)) { return {}; } for (int32_t child_id : node.data.childrenInHitTestOrder) { auto candidate = GetHitNode(child_id, x, y); if (candidate) { return candidate; } } if (IsFocusable(node.data)) { return node_id; } return {}; } bool AccessibilityBridge::IsFocusable( const flutter::SemanticsNode& node) const { if (node.HasFlag(flutter::SemanticsFlags::kScopesRoute)) { return false; } if (node.HasFlag(flutter::SemanticsFlags::kIsFocusable)) { return true; } // Always consider platform views focusable. if (node.IsPlatformViewNode()) { return true; } // Always consider actionable nodes focusable. if (node.actions != 0) { return true; } // Consider text nodes focusable. return !node.label.empty() || !node.value.empty() || !node.hint.empty(); } // |fuchsia::accessibility::semantics::SemanticListener| void AccessibilityBridge::OnSemanticsModeChanged( bool enabled, OnSemanticsModeChangedCallback callback) { set_semantics_enabled_callback_(enabled); } #if !FLUTTER_RELEASE void AccessibilityBridge::FillInspectTree(int32_t flutter_node_id, int32_t current_level, inspect::Node inspect_node, inspect::Inspector* inspector) const { const auto it = nodes_.find(flutter_node_id); if (it == nodes_.end()) { inspect_node.CreateString( "missing_child", "This node has a parent in the semantic tree but has no value", inspector); inspector->emplace(std::move(inspect_node)); return; } const auto& semantic_node = it->second; const auto& data = semantic_node.data; inspect_node.CreateInt("id", data.id, inspector); // Even with an empty label, we still want to create the property to // explicetly show that it is empty. inspect_node.CreateString("label", data.label, inspector); if (!data.hint.empty()) { inspect_node.CreateString("hint", data.hint, inspector); } if (!data.value.empty()) { inspect_node.CreateString("value", data.value, inspector); } if (!data.increasedValue.empty()) { inspect_node.CreateString("increased_value", data.increasedValue, inspector); } if (!data.decreasedValue.empty()) { inspect_node.CreateString("decreased_value", data.decreasedValue, inspector); } if (data.textDirection) { inspect_node.CreateString( "text_direction", data.textDirection == 1 ? "RTL" : "LTR", inspector); } if (data.flags) { inspect_node.CreateString("flags", NodeFlagsToString(data), inspector); } if (data.actions) { inspect_node.CreateString("actions", NodeActionsToString(data), inspector); } inspect_node.CreateString( "location", NodeLocationToString(semantic_node.screen_rect), inspector); if (!data.childrenInTraversalOrder.empty() || !data.childrenInHitTestOrder.empty()) { inspect_node.CreateString("children", NodeChildrenToString(data), inspector); } inspect_node.CreateInt("current_level", current_level, inspector); for (int32_t flutter_child_id : semantic_node.data.childrenInTraversalOrder) { const auto inspect_name = "node_" + std::to_string(flutter_child_id); FillInspectTree(flutter_child_id, current_level + 1, inspect_node.CreateChild(inspect_name), inspector); } inspector->emplace(std::move(inspect_node)); } #endif // !FLUTTER_RELEASE void AccessibilityBridge::Apply(FuchsiaAtomicUpdate* atomic_update) { size_t begin = 0; auto it = atomic_update->deletions.begin(); // Process up to kMaxDeletionsPerUpdate deletions at a time. while (it != atomic_update->deletions.end()) { std::vector<uint32_t> to_delete; size_t end = std::min(atomic_update->deletions.size() - begin, kMaxDeletionsPerUpdate); std::copy(std::make_move_iterator(it), std::make_move_iterator(it + end), std::back_inserter(to_delete)); tree_ptr_->DeleteSemanticNodes(std::move(to_delete)); begin = end; it += end; } std::vector<fuchsia::accessibility::semantics::Node> to_update; size_t current_size = 0; for (auto& node_and_size : atomic_update->updates) { if (current_size + node_and_size.second > kMaxMessageSize) { tree_ptr_->UpdateSemanticNodes(std::move(to_update)); current_size = 0; to_update.clear(); } current_size += node_and_size.second; to_update.push_back(std::move(node_and_size.first)); } if (!to_update.empty()) { tree_ptr_->UpdateSemanticNodes(std::move(to_update)); } // Commit this update and subsequent ones; for flow control wait for a // response between each commit. tree_ptr_->CommitUpdates( [this, atomic_updates = std::weak_ptr<std::queue<FuchsiaAtomicUpdate>>( atomic_updates_)]() { auto atomic_updates_ptr = atomic_updates.lock(); if (!atomic_updates_ptr) { // The queue no longer exists, which means that is no longer // necessary. return; } // Removes the update that just went through. atomic_updates_ptr->pop(); if (!atomic_updates_ptr->empty()) { Apply(&atomic_updates_ptr->front()); } }); atomic_update->deletions.clear(); atomic_update->updates.clear(); } void AccessibilityBridge::FuchsiaAtomicUpdate::AddNodeUpdate( fuchsia::accessibility::semantics::Node node, size_t size) { if (size > kMaxMessageSize) { // TODO(MI4-2531, FIDL-718): Remove this // This is defensive. If, despite our best efforts, we ended up with a node // that is larger than the max fidl size, we send no updates. PrintNodeSizeError(node.node_id()); return; } updates.emplace_back(std::move(node), size); } void AccessibilityBridge::FuchsiaAtomicUpdate::AddNodeDeletion(uint32_t id) { deletions.push_back(id); } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/accessibility_bridge.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/accessibility_bridge.cc", "repo_id": "engine", "token_count": 13430 }
404
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FILE_IN_NAMESPACE_BUFFER_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FILE_IN_NAMESPACE_BUFFER_H_ #include "flutter/fml/mapping.h" namespace flutter_runner { /// A mapping to a buffer for a file that has been loaded into a namespace. class FileInNamespaceBuffer final : public fml::Mapping { public: /// Loads the file at |path| into the namespace |namespace_fd|, creating /// a mapping to the loaded buffer. /// /// The file will be loaded with the readable permission. If |executable| is /// true, the file will also be loaded with the executable permission. FileInNamespaceBuffer(int namespace_fd, const char* path, bool executable); ~FileInNamespaceBuffer(); // |fml::Mapping| const uint8_t* GetMapping() const override; // |fml::Mapping| size_t GetSize() const override; // |fml::Mapping| bool IsDontNeedSafe() const override; private: /// The address that was mapped to the buffer. void* address_; /// The size of the buffer. size_t size_; FML_DISALLOW_COPY_AND_ASSIGN(FileInNamespaceBuffer); }; /// Loads a file from |file_path| into the namespace |namespace_fd|, returning /// the mapping for that file. /// /// The file will be loaded with the readable permission. If |executable| is /// true, the file will be also be loaded with the executable permission. std::unique_ptr<fml::Mapping> LoadFile(int namespace_fd, const char* path, bool executable); /// Opens the file at |path| and creates a file mapping for the file. /// /// The file will be opened with the readable permission. If |executable| is /// true, the file will also be opened with the executable permission. std::unique_ptr<fml::FileMapping> MakeFileMapping(const char* path, bool executable); } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FILE_IN_NAMESPACE_BUFFER_H_
engine/shell/platform/fuchsia/flutter/file_in_namespace_buffer.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/file_in_namespace_buffer.h", "repo_id": "engine", "token_count": 763 }
405
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "pointer_delegate.h" #include <lib/trace/event.h> #include <zircon/status.h> #include <zircon/types.h> #include <limits> #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" // TODO(fxbug.dev/87076): Add MouseSource tests. namespace fuchsia::ui::pointer { // For using TouchInteractionId as a map key. bool operator==(const fuchsia::ui::pointer::TouchInteractionId& a, const fuchsia::ui::pointer::TouchInteractionId& b) { return a.device_id == b.device_id && a.pointer_id == b.pointer_id && a.interaction_id == b.interaction_id; } } // namespace fuchsia::ui::pointer namespace flutter_runner { using fup_EventPhase = fuchsia::ui::pointer::EventPhase; using fup_MouseDeviceInfo = fuchsia::ui::pointer::MouseDeviceInfo; using fup_MouseEvent = fuchsia::ui::pointer::MouseEvent; using fup_TouchEvent = fuchsia::ui::pointer::TouchEvent; using fup_TouchIxnStatus = fuchsia::ui::pointer::TouchInteractionStatus; using fup_TouchResponse = fuchsia::ui::pointer::TouchResponse; using fup_TouchResponseType = fuchsia::ui::pointer::TouchResponseType; using fup_ViewParameters = fuchsia::ui::pointer::ViewParameters; namespace { void IssueTouchTraceEvent(const fup_TouchEvent& event) { FML_DCHECK(event.has_trace_flow_id()) << "API guarantee"; TRACE_FLOW_END("input", "dispatch_event_to_client", event.trace_flow_id()); } void IssueMouseTraceEvent(const fup_MouseEvent& event) { FML_DCHECK(event.has_trace_flow_id()) << "API guarantee"; TRACE_FLOW_END("input", "dispatch_event_to_client", event.trace_flow_id()); } bool HasValidatedTouchSample(const fup_TouchEvent& event) { if (!event.has_pointer_sample()) { return false; } FML_DCHECK(event.pointer_sample().has_interaction()) << "API guarantee"; FML_DCHECK(event.pointer_sample().has_phase()) << "API guarantee"; FML_DCHECK(event.pointer_sample().has_position_in_viewport()) << "API guarantee"; return true; } bool HasValidatedMouseSample(const fup_MouseEvent& event) { if (!event.has_pointer_sample()) { return false; } const auto& sample = event.pointer_sample(); FML_DCHECK(sample.has_device_id()) << "API guarantee"; FML_DCHECK(sample.has_position_in_viewport()) << "API guarantee"; FML_DCHECK(!sample.has_pressed_buttons() || !sample.pressed_buttons().empty()) << "API guarantee"; return true; } std::array<float, 2> ViewportToViewCoordinates( std::array<float, 2> viewport_coordinates, const std::array<float, 9>& viewport_to_view_transform) { // The transform matrix is a FIDL array with matrix data in column-major // order. For a matrix with data [a b c d e f g h i], and with the viewport // coordinates expressed as homogeneous coordinates, the logical view // coordinates are obtained with the following formula: // |a d g| |x| |x'| // |b e h| * |y| = |y'| // |c f i| |1| |w'| // which we then normalize based on the w component: // if z' not zero: (x'/w', y'/w') // else (x', y') const auto& M = viewport_to_view_transform; const float x = viewport_coordinates[0]; const float y = viewport_coordinates[1]; const float xp = M[0] * x + M[3] * y + M[6]; const float yp = M[1] * x + M[4] * y + M[7]; const float wp = M[2] * x + M[5] * y + M[8]; if (wp != 0) { return {xp / wp, yp / wp}; } else { return {xp, yp}; } } flutter::PointerData::Change GetChangeFromTouchEventPhase( fup_EventPhase phase) { switch (phase) { case fup_EventPhase::ADD: return flutter::PointerData::Change::kAdd; case fup_EventPhase::CHANGE: return flutter::PointerData::Change::kMove; case fup_EventPhase::REMOVE: return flutter::PointerData::Change::kRemove; case fup_EventPhase::CANCEL: return flutter::PointerData::Change::kCancel; default: return flutter::PointerData::Change::kCancel; } } std::array<float, 2> ClampToViewSpace(const float x, const float y, const fup_ViewParameters& p) { const float min_x = p.view.min[0]; const float min_y = p.view.min[1]; const float max_x = p.view.max[0]; const float max_y = p.view.max[1]; if (min_x <= x && x < max_x && min_y <= y && y < max_y) { return {x, y}; // No clamping to perform. } // View boundary is [min_x, max_x) x [min_y, max_y). Note that min is // inclusive, but max is exclusive - so we subtract epsilon. const float max_x_inclusive = max_x - std::numeric_limits<float>::epsilon(); const float max_y_inclusive = max_y - std::numeric_limits<float>::epsilon(); const float& clamped_x = std::clamp(x, min_x, max_x_inclusive); const float& clamped_y = std::clamp(y, min_y, max_y_inclusive); FML_LOG(INFO) << "Clamped (" << x << ", " << y << ") to (" << clamped_x << ", " << clamped_y << ")."; return {clamped_x, clamped_y}; } flutter::PointerData::Change ComputePhase( bool any_button_down, std::unordered_set<uint32_t>& mouse_down, uint32_t id) { if (!mouse_down.count(id) && !any_button_down) { return flutter::PointerData::Change::kHover; } else if (!mouse_down.count(id) && any_button_down) { mouse_down.insert(id); return flutter::PointerData::Change::kDown; } else if (mouse_down.count(id) && any_button_down) { return flutter::PointerData::Change::kMove; } else if (mouse_down.count(id) && !any_button_down) { mouse_down.erase(id); return flutter::PointerData::Change::kUp; } FML_UNREACHABLE(); return flutter::PointerData::Change::kCancel; } // Flutter's PointerData.device field is 64 bits and is expected to be unique // for each pointer. We pack Fuchsia's device ID (hi) and pointer ID (lo) into // 64 bits to retain uniqueness across multiple touch devices. uint64_t PackFuchsiaDeviceIdAndPointerId(uint32_t fuchsia_device_id, uint32_t fuchsia_pointer_id) { return (((uint64_t)fuchsia_device_id) << 32) | fuchsia_pointer_id; } // It returns a "draft" because the coordinates are logical. Later, view pixel // ratio is applied to obtain physical coordinates. // // The flutter pointerdata state machine has extra phases, which this function // synthesizes on the fly. Hence the return data is a flutter pointerdata, and // optionally a second one. // For example: <ADD, DOWN>, <MOVE, nullopt>, <UP, REMOVE>. // TODO(fxbug.dev/87074): Let PointerDataPacketConverter synthesize events. // // Flutter gestures expect a gesture to start within the logical view space, and // is not tolerant of floating point drift. This function coerces just the DOWN // event's coordinate to start within the logical view. std::pair<flutter::PointerData, std::optional<flutter::PointerData>> CreateTouchDraft(const fup_TouchEvent& event, const fup_ViewParameters& view_parameters) { FML_DCHECK(HasValidatedTouchSample(event)) << "precondition"; const auto& sample = event.pointer_sample(); const auto& ixn = sample.interaction(); flutter::PointerData ptr; ptr.Clear(); ptr.time_stamp = event.timestamp() / 1000; // in microseconds ptr.change = GetChangeFromTouchEventPhase(sample.phase()); ptr.kind = flutter::PointerData::DeviceKind::kTouch; // Load Fuchsia's pointer ID onto Flutter's |device| field, and not the // |pointer_identifier| field. The latter is written by // PointerDataPacketConverter, to track individual gesture interactions. ptr.device = PackFuchsiaDeviceIdAndPointerId(ixn.device_id, ixn.pointer_id); // View parameters can change mid-interaction; apply transform on the fly. auto logical = ViewportToViewCoordinates(sample.position_in_viewport(), view_parameters.viewport_to_view_transform); ptr.physical_x = logical[0]; // Not yet physical; adjusted in PlatformView. ptr.physical_y = logical[1]; // Not yet physical; adjusted in PlatformView. // Match Flutter pointer's state machine with synthesized events. if (ptr.change == flutter::PointerData::Change::kAdd) { flutter::PointerData down; memcpy(&down, &ptr, sizeof(flutter::PointerData)); down.change = flutter::PointerData::Change::kDown; { // Ensure gesture recognition: DOWN starts in the logical view space. auto [x, y] = ClampToViewSpace(down.physical_x, down.physical_y, view_parameters); down.physical_x = x; down.physical_y = y; } return {std::move(ptr), std::move(down)}; } else if (ptr.change == flutter::PointerData::Change::kRemove) { flutter::PointerData up; memcpy(&up, &ptr, sizeof(flutter::PointerData)); up.change = flutter::PointerData::Change::kUp; return {std::move(up), std::move(ptr)}; } else { return {std::move(ptr), std::nullopt}; } } // It returns a "draft" because the coordinates are logical. Later, view pixel // ratio is applied to obtain physical coordinates. // // Phase data is computed before this call; it involves state tracking based on // button-down state. // // Button data, if available, gets packed into the |buttons| field, in flutter // button order (kMousePrimaryButton, etc). The device-assigned button IDs are // provided in priority order in MouseEvent.device_info (at the start of channel // connection), and maps from device button ID (given in fup_MouseEvent) to // flutter button ID (flutter::PointerData). // // Scroll data, if available, gets packed into the |scroll_delta_x| or // |scroll_delta_y| fields, and the |signal_kind| field is set to kScroll. // The PointerDataPacketConverter reads this field to synthesize events to match // Flutter's expected pointer stream. // TODO(fxbug.dev/87073): PointerDataPacketConverter should synthesize a // discrete scroll event on kDown or kUp, to match engine expectations. // // Flutter gestures expect a gesture to start within the logical view space, and // is not tolerant of floating point drift. This function coerces just the DOWN // event's coordinate to start within the logical view. flutter::PointerData CreateMouseDraft(const fup_MouseEvent& event, const flutter::PointerData::Change phase, const fup_ViewParameters& view_parameters, const fup_MouseDeviceInfo& device_info) { FML_DCHECK(HasValidatedMouseSample(event)) << "precondition"; const auto& sample = event.pointer_sample(); flutter::PointerData ptr; ptr.Clear(); ptr.time_stamp = event.timestamp() / 1000; // in microseconds ptr.change = phase; ptr.kind = flutter::PointerData::DeviceKind::kMouse; ptr.device = sample.device_id(); // View parameters can change mid-interaction; apply transform on the fly. auto logical = ViewportToViewCoordinates(sample.position_in_viewport(), view_parameters.viewport_to_view_transform); ptr.physical_x = logical[0]; // Not yet physical; adjusted in PlatformView. ptr.physical_y = logical[1]; // Not yet physical; adjusted in PlatformView. // Ensure gesture recognition: DOWN starts in the logical view space. if (ptr.change == flutter::PointerData::Change::kDown) { auto [x, y] = ClampToViewSpace(ptr.physical_x, ptr.physical_y, view_parameters); ptr.physical_x = x; ptr.physical_y = y; } if (sample.has_pressed_buttons()) { int64_t flutter_buttons = 0; const auto& pressed = sample.pressed_buttons(); for (size_t idx = 0; idx < pressed.size(); ++idx) { const uint8_t button_id = pressed[idx]; FML_DCHECK(device_info.has_buttons()) << "API guarantee"; // Priority 0 maps to kPrimaryButton, and so on. for (uint8_t prio = 0; prio < device_info.buttons().size(); ++prio) { if (button_id == device_info.buttons()[prio]) { flutter_buttons |= (1 << prio); } } } FML_DCHECK(flutter_buttons != 0); ptr.buttons = flutter_buttons; } // Fuchsia previously only provided scroll data in "ticks", not physical // pixels. On legacy platforms, since Flutter expects scroll data in physical // pixels, to compensate for lack of guidance, we make up a "reasonable // amount". // TODO(fxbug.dev/103443): Remove the tick based scrolling after the // transition. const int kScrollOffsetMultiplier = 20; double dy = 0; double dx = 0; bool is_scroll = false; if (sample.has_scroll_v_physical_pixel()) { dy = -sample.scroll_v_physical_pixel(); is_scroll = true; } else if (sample.has_scroll_v()) { dy = -sample.scroll_v() * kScrollOffsetMultiplier; // logical amount, not yet physical; adjusted // in Platform View. is_scroll = true; } if (sample.has_scroll_h_physical_pixel()) { dx = sample.scroll_h_physical_pixel(); is_scroll = true; } else if (sample.has_scroll_h()) { dx = sample.scroll_h() * kScrollOffsetMultiplier; // logical amount is_scroll = true; } if (is_scroll) { ptr.signal_kind = flutter::PointerData::SignalKind::kScroll; ptr.scroll_delta_y = dy; ptr.scroll_delta_x = dx; } return ptr; } // Helper to insert one or two events into a vector buffer. void InsertIntoBuffer( std::pair<flutter::PointerData, std::optional<flutter::PointerData>> events, std::vector<flutter::PointerData>* buffer) { FML_DCHECK(buffer); buffer->emplace_back(std::move(events.first)); if (events.second.has_value()) { buffer->emplace_back(std::move(events.second.value())); } } } // namespace PointerDelegate::PointerDelegate( fuchsia::ui::pointer::TouchSourceHandle touch_source, fuchsia::ui::pointer::MouseSourceHandle mouse_source) : touch_source_(touch_source.Bind()), mouse_source_(mouse_source.Bind()) { if (touch_source_) { touch_source_.set_error_handler([](zx_status_t status) { FML_LOG(ERROR) << "TouchSource channel error: << " << zx_status_get_string(status); }); } if (mouse_source_) { mouse_source_.set_error_handler([](zx_status_t status) { FML_LOG(ERROR) << "MouseSource channel error: << " << zx_status_get_string(status); }); } } // Core logic of this class. // Aim to keep state management in this function. void PointerDelegate::WatchLoop( std::function<void(std::vector<flutter::PointerData>)> callback) { FML_LOG(INFO) << "Flutter - PointerDelegate started."; if (touch_responder_) { FML_LOG(ERROR) << "PointerDelegate::WatchLoop() must be called once."; return; } touch_responder_ = [this, callback](std::vector<fup_TouchEvent> events) { TRACE_EVENT0("flutter", "PointerDelegate::TouchHandler"); FML_DCHECK(touch_responses_.empty()) << "precondition"; std::vector<flutter::PointerData> to_client; for (const fup_TouchEvent& event : events) { IssueTouchTraceEvent(event); fup_TouchResponse response; // Response per event, matched on event's index. if (event.has_view_parameters()) { touch_view_parameters_ = std::move(event.view_parameters()); } if (HasValidatedTouchSample(event)) { const auto& sample = event.pointer_sample(); const auto& ixn = sample.interaction(); if (sample.phase() == fup_EventPhase::ADD && !event.has_interaction_result()) { touch_buffer_.emplace(ixn, std::vector<flutter::PointerData>()); } FML_DCHECK(touch_view_parameters_.has_value()) << "API guarantee"; auto events = CreateTouchDraft(event, touch_view_parameters_.value()); if (touch_buffer_.count(ixn) > 0) { InsertIntoBuffer(std::move(events), &touch_buffer_[ixn]); } else { InsertIntoBuffer(std::move(events), &to_client); } // For this simple client, always claim we want the gesture. response.set_response_type(fup_TouchResponseType::YES); } if (event.has_interaction_result()) { const auto& result = event.interaction_result(); const auto& ixn = result.interaction; if (result.status == fup_TouchIxnStatus::GRANTED && touch_buffer_.count(ixn) > 0) { FML_DCHECK(to_client.empty()) << "invariant"; to_client.insert(to_client.end(), touch_buffer_[ixn].begin(), touch_buffer_[ixn].end()); } touch_buffer_.erase(ixn); // Result seen, delete the buffer. } touch_responses_.push_back(std::move(response)); } callback(std::move(to_client)); // Notify client of touch events, if any. touch_source_->Watch(std::move(touch_responses_), /*copy*/ touch_responder_); touch_responses_.clear(); }; mouse_responder_ = [this, callback](std::vector<fup_MouseEvent> events) { TRACE_EVENT0("flutter", "PointerDelegate::MouseHandler"); std::vector<flutter::PointerData> to_client; for (fup_MouseEvent& event : events) { IssueMouseTraceEvent(event); if (event.has_device_info()) { const auto& id = event.device_info().id(); mouse_device_info_[id] = std::move(*event.mutable_device_info()); } if (event.has_view_parameters()) { mouse_view_parameters_ = std::move(event.view_parameters()); } if (HasValidatedMouseSample(event)) { const auto& sample = event.pointer_sample(); const auto& id = sample.device_id(); const bool any_button_down = sample.has_pressed_buttons(); FML_DCHECK(mouse_view_parameters_.has_value()) << "API guarantee"; FML_DCHECK(mouse_device_info_.count(id) > 0) << "API guarantee"; const auto phase = ComputePhase(any_button_down, mouse_down_, id); flutter::PointerData data = CreateMouseDraft(event, phase, mouse_view_parameters_.value(), mouse_device_info_[id]); to_client.emplace_back(std::move(data)); } } callback(std::move(to_client)); mouse_source_->Watch(/*copy*/ mouse_responder_); }; // Start watching both channels. touch_source_->Watch(std::move(touch_responses_), /*copy*/ touch_responder_); touch_responses_.clear(); if (mouse_source_) { mouse_source_->Watch(/*copy*/ mouse_responder_); } } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/pointer_delegate.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/pointer_delegate.cc", "repo_id": "engine", "token_count": 6953 }
406
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_H_ #include <fuchsia/sysmem/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <lib/async/cpp/wait.h> #include <lib/zx/event.h> #include <lib/zx/vmo.h> #include <array> #include <cstdint> #include <memory> #include "flutter/fml/macros.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkSurface.h" #include "surface_producer.h" namespace flutter_runner { class SoftwareSurface final : public SurfaceProducerSurface { public: SoftwareSurface(fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator, fuchsia::ui::composition::AllocatorPtr& flatland_allocator, const SkISize& size); ~SoftwareSurface() override; size_t GetAllocationSize() const { return surface_size_bytes_; } // |SurfaceProducerSurface| size_t AdvanceAndGetAge() override; // |SurfaceProducerSurface| bool FlushSessionAcquireAndReleaseEvents() override; // |SurfaceProducerSurface| bool IsValid() const override; // |SurfaceProducerSurface| SkISize GetSize() const override; // |SurfaceProducerSurface| void SignalWritesFinished( const std::function<void(void)>& on_surface_read_finished) override; // |SurfaceProducerSurface| void SetImageId(uint32_t image_id) override; // |SurfaceProducerSurface| uint32_t GetImageId() override; // |SurfaceProducerSurface| sk_sp<SkSurface> GetSkiaSurface() const override; // |SurfaceProducerSurface| fuchsia::ui::composition::BufferCollectionImportToken GetBufferCollectionImportToken() override; // |SurfaceProducerSurface| zx::event GetAcquireFence() override; // |SurfaceProducerSurface| zx::event GetReleaseFence() override; // |SurfaceProducerSurface| void SetReleaseImageCallback( ReleaseImageCallback release_image_callback) override; private: void OnSurfaceReadFinished(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal); bool SetupSkiaSurface( fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator, fuchsia::ui::composition::AllocatorPtr& flatland_allocator, const SkISize& size); bool CreateFences(); void Reset(); uint32_t image_id_ = 0; sk_sp<SkSurface> sk_surface_; // This is associated with `release_event_` and allows detection of when // scenic has finished reading from the surface (and thus it is safe to re-use // for writing). async::WaitMethod<SoftwareSurface, &SoftwareSurface::OnSurfaceReadFinished> wait_for_surface_read_finished_; // Called when scenic has finished reading from the surface, to allow // `SoftwareSurfaceProducer` to re-use the surface. std::function<void()> surface_read_finished_callback_; // Called when the surface is destroyed, to allow // `ExternalViewEmbedder` to release the associated Flatland image. ReleaseImageCallback release_image_callback_; // Allows Flatland to associate this surface with a Flatland Image. fuchsia::ui::composition::BufferCollectionImportToken import_token_; zx::event acquire_event_; // Signals to scenic that writing is finished. zx::event release_event_; // Signalled by scenic that reading is finished. zx::vmo surface_vmo_; // VMO that is backing the surface memory. uint32_t surface_size_bytes_; // Size of the surface memory, in bytes. size_t age_{0}; // Number of frames since surface was last written to. bool needs_cache_clean_{false}; bool valid_{false}; FML_DISALLOW_COPY_AND_ASSIGN(SoftwareSurface); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SOFTWARE_SURFACE_H_
engine/shell/platform/fuchsia/flutter/software_surface.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/software_surface.h", "repo_id": "engine", "token_count": 1432 }
407
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. assert(is_fuchsia) import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") source_set("scenic") { testonly = true sources = [ "fake_flatland.cc", "fake_flatland.h", "fake_flatland_types.cc", "fake_flatland_types.h", ] public_deps = [ "${fuchsia_sdk}/fidl/fuchsia.images", "${fuchsia_sdk}/fidl/fuchsia.scenic.scheduling", "${fuchsia_sdk}/fidl/fuchsia.ui.composition", "${fuchsia_sdk}/fidl/fuchsia.ui.views", "${fuchsia_sdk}/pkg/async-cpp", "${fuchsia_sdk}/pkg/async-testing", "${fuchsia_sdk}/pkg/fidl_cpp", "//flutter/fml", ] }
engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/BUILD.gn", "repo_id": "engine", "token_count": 350 }
408
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/inspect/cpp/fidl.h> #include <fuchsia/logger/cpp/fidl.h> #include <fuchsia/tracing/provider/cpp/fidl.h> #include <fuchsia/ui/app/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <fuchsia/ui/display/singleton/cpp/fidl.h> #include <fuchsia/ui/observation/geometry/cpp/fidl.h> #include <fuchsia/ui/test/input/cpp/fidl.h> #include <fuchsia/ui/test/scene/cpp/fidl.h> #include <lib/async-loop/testing/cpp/real_loop.h> #include <lib/async/cpp/task.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/sys/component/cpp/testing/realm_builder.h> #include <lib/sys/component/cpp/testing/realm_builder_types.h> #include <lib/zx/clock.h> #include <zircon/status.h> #include <zircon/time.h> #include <optional> #include <vector> #include "flutter/fml/logging.h" #include "gtest/gtest.h" #include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h" #include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.h" namespace flutter_embedder_test { namespace { // Types imported for the realm_builder library. using component_testing::ChildOptions; using component_testing::ChildRef; using component_testing::DirectoryContents; using component_testing::ParentRef; using component_testing::Protocol; using component_testing::RealmRoot; using component_testing::Route; using component_testing::StartupMode; using fuchsia_test_utils::CheckViewExistsInUpdates; // The FIDL bindings for this service are not exposed in the Fuchsia SDK, so we // must encode the name manually here. constexpr auto kVulkanLoaderServiceName = "fuchsia.vulkan.loader.Loader"; constexpr auto kFlutterJitRunnerUrl = "fuchsia-pkg://fuchsia.com/oot_flutter_jit_runner#meta/" "flutter_jit_runner.cm"; constexpr auto kFlutterJitProductRunnerUrl = "fuchsia-pkg://fuchsia.com/oot_flutter_jit_product_runner#meta/" "flutter_jit_product_runner.cm"; constexpr auto kFlutterAotRunnerUrl = "fuchsia-pkg://fuchsia.com/oot_flutter_aot_runner#meta/" "flutter_aot_runner.cm"; constexpr auto kFlutterAotProductRunnerUrl = "fuchsia-pkg://fuchsia.com/oot_flutter_aot_product_runner#meta/" "flutter_aot_product_runner.cm"; constexpr char kChildViewUrl[] = "fuchsia-pkg://fuchsia.com/child-view#meta/child-view.cm"; constexpr char kParentViewUrl[] = "fuchsia-pkg://fuchsia.com/parent-view#meta/parent-view.cm"; static constexpr auto kTestUiStackUrl = "fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/" "test-ui-stack.cm"; constexpr auto kFlutterRunnerEnvironment = "flutter_runner_env"; constexpr auto kFlutterJitRunner = "flutter_jit_runner"; constexpr auto kFlutterJitRunnerRef = ChildRef{kFlutterJitRunner}; constexpr auto kFlutterJitProductRunner = "flutter_jit_product_runner"; constexpr auto kFlutterJitProductRunnerRef = ChildRef{kFlutterJitProductRunner}; constexpr auto kFlutterAotRunner = "flutter_aot_runner"; constexpr auto kFlutterAotRunnerRef = ChildRef{kFlutterAotRunner}; constexpr auto kFlutterAotProductRunner = "flutter_aot_product_runner"; constexpr auto kFlutterAotProductRunnerRef = ChildRef{kFlutterAotProductRunner}; constexpr auto kChildView = "child_view"; constexpr auto kChildViewRef = ChildRef{kChildView}; constexpr auto kParentView = "parent_view"; constexpr auto kParentViewRef = ChildRef{kParentView}; constexpr auto kTestUiStack = "ui"; constexpr auto kTestUiStackRef = ChildRef{kTestUiStack}; // Background and foreground color values. const fuchsia_test_utils::Pixel kParentBackgroundColor(0xFF, 0x00, 0x00, 0xFF); // Blue const fuchsia_test_utils::Pixel kChildBackgroundColor(0xFF, 0x00, 0xFF, 0xFF); // Pink const fuchsia_test_utils::Pixel kFlatlandOverlayColor(0x00, 0xFF, 0x00, 0xFF); // Green static uint32_t OverlayPixelCount( std::map<fuchsia_test_utils::Pixel, uint32_t>& histogram) { return histogram[kFlatlandOverlayColor]; } // Timeout for |TakeScreenshot| FIDL call. constexpr zx::duration kScreenshotTimeout = zx::sec(10); // Timeout to fail the test if it goes beyond this duration. constexpr zx::duration kTestTimeout = zx::min(1); } // namespace class FlutterEmbedderTest : public ::loop_fixture::RealLoop, public ::testing::Test { public: FlutterEmbedderTest() : realm_builder_(component_testing::RealmBuilder::Create()) { FML_VLOG(1) << "Setting up base realm"; SetUpRealmBase(); // Post a "just in case" quit task, if the test hangs. async::PostDelayedTask( dispatcher(), [] { FML_LOG(FATAL) << "\n\n>> Test did not complete in time, terminating. <<\n\n"; }, kTestTimeout); } bool HasViewConnected( const fuchsia::ui::observation::geometry::ViewTreeWatcherPtr& view_tree_watcher, std::optional<fuchsia::ui::observation::geometry::WatchResponse>& watch_response, zx_koid_t view_ref_koid); void LaunchParentViewInRealm( const std::vector<std::string>& component_args = {}); fuchsia_test_utils::Screenshot TakeScreenshot(); bool TakeScreenshotUntil( fuchsia_test_utils::Pixel color, fit::function<void(std::map<fuchsia_test_utils::Pixel, uint32_t>)> callback = nullptr, zx::duration timeout = kTestTimeout); private: void SetUpRealmBase(); fuchsia::ui::test::scene::ControllerPtr scene_provider_; fuchsia::ui::observation::geometry::ViewTreeWatcherPtr view_tree_watcher_; fuchsia::ui::composition::ScreenshotPtr screenshot_; // Wrapped in optional since the view is not created until the middle of SetUp component_testing::RealmBuilder realm_builder_; std::unique_ptr<component_testing::RealmRoot> realm_; uint64_t display_width_ = 0; uint64_t display_height_ = 0; }; void FlutterEmbedderTest::SetUpRealmBase() { FML_LOG(INFO) << "Setting up realm base."; // First, add the flutter runner(s) as children. realm_builder_.AddChild(kFlutterJitRunner, kFlutterJitRunnerUrl); realm_builder_.AddChild(kFlutterJitProductRunner, kFlutterJitProductRunnerUrl); realm_builder_.AddChild(kFlutterAotRunner, kFlutterAotRunnerUrl); realm_builder_.AddChild(kFlutterAotProductRunner, kFlutterAotProductRunnerUrl); // Then, add an environment providing them. fuchsia::component::decl::Environment flutter_runner_environment; flutter_runner_environment.set_name(kFlutterRunnerEnvironment); flutter_runner_environment.set_extends( fuchsia::component::decl::EnvironmentExtends::REALM); flutter_runner_environment.set_runners({}); auto environment_runners = flutter_runner_environment.mutable_runners(); fuchsia::component::decl::RunnerRegistration flutter_jit_runner_reg; flutter_jit_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( fuchsia::component::decl::ChildRef{.name = kFlutterJitRunner})); flutter_jit_runner_reg.set_source_name(kFlutterJitRunner); flutter_jit_runner_reg.set_target_name(kFlutterJitRunner); environment_runners->push_back(std::move(flutter_jit_runner_reg)); fuchsia::component::decl::RunnerRegistration flutter_jit_product_runner_reg; flutter_jit_product_runner_reg.set_source( fuchsia::component::decl::Ref::WithChild( fuchsia::component::decl::ChildRef{.name = kFlutterJitProductRunner})); flutter_jit_product_runner_reg.set_source_name(kFlutterJitProductRunner); flutter_jit_product_runner_reg.set_target_name(kFlutterJitProductRunner); environment_runners->push_back(std::move(flutter_jit_product_runner_reg)); fuchsia::component::decl::RunnerRegistration flutter_aot_runner_reg; flutter_aot_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( fuchsia::component::decl::ChildRef{.name = kFlutterAotRunner})); flutter_aot_runner_reg.set_source_name(kFlutterAotRunner); flutter_aot_runner_reg.set_target_name(kFlutterAotRunner); environment_runners->push_back(std::move(flutter_aot_runner_reg)); fuchsia::component::decl::RunnerRegistration flutter_aot_product_runner_reg; flutter_aot_product_runner_reg.set_source( fuchsia::component::decl::Ref::WithChild( fuchsia::component::decl::ChildRef{.name = kFlutterAotProductRunner})); flutter_aot_product_runner_reg.set_source_name(kFlutterAotProductRunner); flutter_aot_product_runner_reg.set_target_name(kFlutterAotProductRunner); environment_runners->push_back(std::move(flutter_aot_product_runner_reg)); auto realm_decl = realm_builder_.GetRealmDecl(); if (!realm_decl.has_environments()) { realm_decl.set_environments({}); } auto realm_environments = realm_decl.mutable_environments(); realm_environments->push_back(std::move(flutter_runner_environment)); realm_builder_.ReplaceRealmDecl(std::move(realm_decl)); // Add test UI stack component. realm_builder_.AddChild(kTestUiStack, kTestUiStackUrl); // Add embedded parent and child components. realm_builder_.AddChild(kChildView, kChildViewUrl, ChildOptions{ .environment = kFlutterRunnerEnvironment, }); realm_builder_.AddChild(kParentView, kParentViewUrl, ChildOptions{ .environment = kFlutterRunnerEnvironment, }); // Route base system services to flutter runners. realm_builder_.AddRoute( Route{.capabilities = { Protocol{fuchsia::logger::LogSink::Name_}, Protocol{fuchsia::inspect::InspectSink::Name_}, Protocol{fuchsia::sysmem::Allocator::Name_}, Protocol{fuchsia::tracing::provider::Registry::Name_}, Protocol{kVulkanLoaderServiceName}, }, .source = ParentRef{}, .targets = {kFlutterJitRunnerRef, kFlutterJitProductRunnerRef, kFlutterAotRunnerRef, kFlutterAotProductRunnerRef}}); // Route base system services to the test UI stack. realm_builder_.AddRoute(Route{ .capabilities = {Protocol{fuchsia::logger::LogSink::Name_}, Protocol{fuchsia::inspect::InspectSink::Name_}, Protocol{fuchsia::sysmem::Allocator::Name_}, Protocol{fuchsia::tracing::provider::Registry::Name_}, Protocol{kVulkanLoaderServiceName}}, .source = ParentRef{}, .targets = {kTestUiStackRef}}); // Route UI capabilities from test UI stack to flutter runners. realm_builder_.AddRoute(Route{ .capabilities = {Protocol{fuchsia::ui::composition::Allocator::Name_}, Protocol{fuchsia::ui::composition::Flatland::Name_}}, .source = kTestUiStackRef, .targets = {kFlutterJitRunnerRef, kFlutterJitProductRunnerRef, kFlutterAotRunnerRef, kFlutterAotProductRunnerRef}}); // Route test capabilities from test UI stack to test driver. realm_builder_.AddRoute(Route{ .capabilities = {Protocol{fuchsia::ui::composition::Screenshot::Name_}, Protocol{fuchsia::ui::test::input::Registry::Name_}, Protocol{fuchsia::ui::test::scene::Controller::Name_}, Protocol{fuchsia::ui::display::singleton::Info::Name_}}, .source = kTestUiStackRef, .targets = {ParentRef()}}); // Route ViewProvider from child to parent, and parent to test. realm_builder_.AddRoute( Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, .source = kParentViewRef, .targets = {ParentRef()}}); realm_builder_.AddRoute( Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, .source = kChildViewRef, .targets = {kParentViewRef}}); } // Checks whether the view with |view_ref_koid| has connected to the view tree. // The response of a f.u.o.g.Provider.Watch call is stored in |watch_response| // if it contains |view_ref_koid|. bool FlutterEmbedderTest::HasViewConnected( const fuchsia::ui::observation::geometry::ViewTreeWatcherPtr& view_tree_watcher, std::optional<fuchsia::ui::observation::geometry::WatchResponse>& watch_response, zx_koid_t view_ref_koid) { std::optional<fuchsia::ui::observation::geometry::WatchResponse> watch_result; view_tree_watcher->Watch( [&watch_result](auto response) { watch_result = std::move(response); }); FML_LOG(INFO) << "Waiting for view tree watch result"; RunLoopUntil([&watch_result] { return watch_result.has_value(); }); FML_LOG(INFO) << "Received for view tree watch result"; if (CheckViewExistsInUpdates(watch_result->updates(), view_ref_koid)) { watch_response = std::move(watch_result); }; return watch_response.has_value(); } void FlutterEmbedderTest::LaunchParentViewInRealm( const std::vector<std::string>& component_args) { FML_LOG(INFO) << "Launching parent-view"; if (!component_args.empty()) { // Construct a args.csv file containing the specified comma-separated // component args. std::string csv; for (const auto& arg : component_args) { csv += arg + ','; } // Remove last comma. csv.pop_back(); auto config_directory_contents = DirectoryContents(); config_directory_contents.AddFile("args.csv", csv); realm_builder_.RouteReadOnlyDirectory("config-data", {kParentViewRef}, std::move(config_directory_contents)); } realm_ = std::make_unique<RealmRoot>(realm_builder_.Build()); // Get the display information using the |fuchsia.ui.display.singleton.Info|. std::optional<bool> display_metrics_obtained; fuchsia::ui::display::singleton::InfoPtr display_info = realm_->component().Connect<fuchsia::ui::display::singleton::Info>(); display_info->GetMetrics([this, &display_metrics_obtained](auto info) { display_width_ = info.extent_in_px().width; display_height_ = info.extent_in_px().height; display_metrics_obtained = true; }); RunLoopUntil([&display_metrics_obtained] { return display_metrics_obtained.has_value(); }); FML_LOG(INFO) << "Got display_width " << display_width_ << " display_height " << display_height_; // Instruct Test UI Stack to present parent-view's View. std::optional<zx_koid_t> view_ref_koid; scene_provider_ = realm_->component().Connect<fuchsia::ui::test::scene::Controller>(); scene_provider_.set_error_handler( [](auto) { FML_LOG(ERROR) << "Error from test scene provider"; }); fuchsia::ui::test::scene::ControllerAttachClientViewRequest request; request.set_view_provider( realm_->component().Connect<fuchsia::ui::app::ViewProvider>()); scene_provider_->RegisterViewTreeWatcher(view_tree_watcher_.NewRequest(), []() {}); scene_provider_->AttachClientView( std::move(request), [&view_ref_koid](auto client_view_ref_koid) { view_ref_koid = client_view_ref_koid; }); FML_LOG(INFO) << "Waiting for client view ref koid"; RunLoopUntil([&view_ref_koid] { return view_ref_koid.has_value(); }); // Wait for the client view to get attached to the view tree. std::optional<fuchsia::ui::observation::geometry::WatchResponse> watch_response; FML_LOG(INFO) << "Waiting for client view to render; koid is " << (view_ref_koid.has_value() ? view_ref_koid.value() : 0); RunLoopUntil([this, &watch_response, &view_ref_koid] { return HasViewConnected(view_tree_watcher_, watch_response, *view_ref_koid); }); FML_LOG(INFO) << "Client view has rendered"; screenshot_ = realm_->component().Connect<fuchsia::ui::composition::Screenshot>(); FML_LOG(INFO) << "Launched parent-view"; } fuchsia_test_utils::Screenshot FlutterEmbedderTest::TakeScreenshot() { FML_LOG(INFO) << "Taking screenshot... "; fuchsia::ui::composition::ScreenshotTakeRequest request; request.set_format(fuchsia::ui::composition::ScreenshotFormat::BGRA_RAW); std::optional<fuchsia::ui::composition::ScreenshotTakeResponse> response; screenshot_->Take(std::move(request), [this, &response](auto screenshot) { response = std::move(screenshot); QuitLoop(); }); EXPECT_FALSE(RunLoopWithTimeout(kScreenshotTimeout)) << "Timed out waiting for screenshot."; FML_LOG(INFO) << "Screenshot captured."; return fuchsia_test_utils::Screenshot( response->vmo(), display_width_, display_height_, /*display_rotation*/ 0); } bool FlutterEmbedderTest::TakeScreenshotUntil( fuchsia_test_utils::Pixel color, fit::function<void(std::map<fuchsia_test_utils::Pixel, uint32_t>)> callback, zx::duration timeout) { return RunLoopWithTimeoutOrUntil( [this, &callback, &color] { auto screenshot = TakeScreenshot(); auto histogram = screenshot.Histogram(); bool color_found = histogram[color] > 0; if (color_found && callback != nullptr) { callback(std::move(histogram)); } return color_found; }, timeout); } TEST_F(FlutterEmbedderTest, Embedding) { LaunchParentViewInRealm(); // Take screenshot until we see the child-view's embedded color. ASSERT_TRUE(TakeScreenshotUntil( kChildBackgroundColor, [](std::map<fuchsia_test_utils::Pixel, uint32_t> histogram) { // Expect parent and child background colors, with parent color > child // color. EXPECT_GT(histogram[kParentBackgroundColor], 0u); EXPECT_GT(histogram[kChildBackgroundColor], 0u); EXPECT_GT(histogram[kParentBackgroundColor], histogram[kChildBackgroundColor]); })); } TEST_F(FlutterEmbedderTest, EmbeddingWithOverlay) { LaunchParentViewInRealm({"--showOverlay"}); // Take screenshot until we see the child-view's embedded color. ASSERT_TRUE(TakeScreenshotUntil( kChildBackgroundColor, [](std::map<fuchsia_test_utils::Pixel, uint32_t> histogram) { // Expect parent, overlay and child background colors. // With parent color > child color and overlay color > child color. const uint32_t overlay_pixel_count = OverlayPixelCount(histogram); EXPECT_GT(histogram[kParentBackgroundColor], 0u); EXPECT_GT(overlay_pixel_count, 0u); EXPECT_GT(histogram[kChildBackgroundColor], 0u); EXPECT_GT(histogram[kParentBackgroundColor], histogram[kChildBackgroundColor]); EXPECT_GT(overlay_pixel_count, histogram[kChildBackgroundColor]); })); } } // namespace flutter_embedder_test
engine/shell/platform/fuchsia/flutter/tests/integration/embedder/flutter-embedder-test.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/embedder/flutter-embedder-test.cc", "repo_id": "engine", "token_count": 7791 }
409
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/feedback/cpp/fidl.h> #include <fuchsia/logger/cpp/fidl.h> #include <fuchsia/sysmem/cpp/fidl.h> #include <fuchsia/tracing/provider/cpp/fidl.h> #include <fuchsia/ui/app/cpp/fidl.h> #include <fuchsia/ui/display/singleton/cpp/fidl.h> #include <fuchsia/ui/input/cpp/fidl.h> #include <fuchsia/ui/test/input/cpp/fidl.h> #include <fuchsia/ui/test/scene/cpp/fidl.h> #include <lib/async-loop/testing/cpp/real_loop.h> #include <lib/async/cpp/task.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/sys/component/cpp/testing/realm_builder.h> #include <lib/sys/component/cpp/testing/realm_builder_types.h> #include <lib/zx/clock.h> #include <lib/zx/time.h> #include <zircon/status.h> #include <zircon/types.h> #include <zircon/utc.h> #include <cstddef> #include <cstdint> #include <iostream> #include <memory> #include <type_traits> #include <utility> #include <vector> #include <gtest/gtest.h> #include "flutter/fml/logging.h" #include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h" #include "flutter/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.h" namespace { // Types imported for the realm_builder library. using component_testing::ChildRef; using component_testing::LocalComponentImpl; using component_testing::ParentRef; using component_testing::Protocol; using component_testing::RealmBuilder; using component_testing::RealmRoot; using component_testing::Route; using fuchsia_test_utils::CheckViewExistsInUpdates; using fuchsia_test_utils::PortableUITest; /// Max timeout in failure cases. /// Set this as low as you can that still works across all test platforms. constexpr zx::duration kTimeout = zx::min(5); constexpr auto kKeyboardInputListener = "keyboard_input_listener"; constexpr auto kKeyboardInputListenerRef = ChildRef{kKeyboardInputListener}; constexpr auto kTextInputView = "text-input-view"; constexpr auto kTextInputViewRef = ChildRef{kTextInputView}; static constexpr auto kTextInputViewUrl = "fuchsia-pkg://fuchsia.com/text-input-view#meta/text-input-view.cm"; constexpr auto kTestUIStackUrl = "fuchsia-pkg://fuchsia.com/flatland-scene-manager-test-ui-stack#meta/" "test-ui-stack.cm"; /// |KeyboardInputListener| is a local test protocol that our test Flutter app /// uses to let us know what text is being entered into its only text field. /// /// The text field contents are reported on almost every change, so if you are /// entering a long text, you will see calls corresponding to successive /// additions of characters, not just the end result. class KeyboardInputListenerServer : public fuchsia::ui::test::input::KeyboardInputListener, public LocalComponentImpl { public: explicit KeyboardInputListenerServer(async_dispatcher_t* dispatcher) : dispatcher_(dispatcher) {} // |fuchsia::ui::test::input::KeyboardInputListener| void ReportTextInput( fuchsia::ui::test::input::KeyboardInputListenerReportTextInputRequest request) override { FML_LOG(INFO) << "Flutter app sent: '" << request.text() << "'"; response_list_.push_back(request.text()); } /// Starts this server. void OnStart() override { FML_LOG(INFO) << "Starting KeyboardInputListenerServer"; ASSERT_EQ(ZX_OK, outgoing()->AddPublicService( bindings_.GetHandler(this, dispatcher_))); } /// Returns true if the response vector values matches `expected` bool HasResponse(const std::vector<std::string>& expected) { if (response_list_.size() != expected.size()) { return false; } // Iterate through the expected vector // Corresponding indices for response_list and expected should contain the // same values for (size_t i = 0; i < expected.size(); ++i) { if (response_list_[i] != expected[i]) { return false; } } return true; } // KeyboardInputListener override void ReportReady(ReportReadyCallback callback) override { FML_LOG(INFO) << "ReportReady callback ready"; ready_ = true; callback(); } private: async_dispatcher_t* dispatcher_ = nullptr; fidl::BindingSet<fuchsia::ui::test::input::KeyboardInputListener> bindings_; std::vector<std::string> response_list_; bool ready_ = false; }; class TextInputTest : public PortableUITest, public ::testing::Test, public ::testing::WithParamInterface<std::string> { protected: void SetUp() override { PortableUITest::SetUp(); // Post a "just in case" quit task, if the test hangs. async::PostDelayedTask( dispatcher(), [] { FML_LOG(FATAL) << "\n\n>> Test did not complete in time, terminating. <<\n\n"; }, kTimeout); // Get the display dimensions. FML_LOG(INFO) << "Waiting for display info from fuchsia.ui.display.singleton.Info"; fuchsia::ui::display::singleton::InfoPtr display_info = realm_root() ->component() .Connect<fuchsia::ui::display::singleton::Info>(); display_info->GetMetrics( [this](fuchsia::ui::display::singleton::Metrics metrics) { display_width_ = metrics.extent_in_px().width; display_height_ = metrics.extent_in_px().height; FML_LOG(INFO) << "Got display_width = " << display_width_ << " and display_height = " << display_height_; }); RunLoopUntil( [this] { return display_width_ != 0 && display_height_ != 0; }); // Register input injection device. FML_LOG(INFO) << "Registering input injection device"; RegisterKeyboard(); } // Guaranteed to be initialized after SetUp(). uint32_t display_width() const { return display_width_; } uint32_t display_height() const { return display_height_; } std::string GetTestUIStackUrl() override { return GetParam(); }; KeyboardInputListenerServer* keyboard_input_listener_server_; private: void ExtendRealm() override { FML_LOG(INFO) << "Extending realm"; // Key part of service setup: have this test component vend the // |KeyboardInputListener| service in the constructed realm. auto keyboard_input_listener_server = std::make_unique<KeyboardInputListenerServer>(dispatcher()); keyboard_input_listener_server_ = keyboard_input_listener_server.get(); realm_builder()->AddLocalChild( kKeyboardInputListener, [keyboard_input_listener_server = std::move(keyboard_input_listener_server)]() mutable { return std::move(keyboard_input_listener_server); }); // Add text-input-view to the Realm realm_builder()->AddChild(kTextInputView, kTextInputViewUrl, component_testing::ChildOptions{ .environment = kFlutterRunnerEnvironment, }); // Route KeyboardInputListener to the runner and Flutter app realm_builder()->AddRoute( Route{.capabilities = {Protocol{ fuchsia::ui::test::input::KeyboardInputListener::Name_}}, .source = kKeyboardInputListenerRef, .targets = {kFlutterJitRunnerRef, kTextInputViewRef}}); // Expose fuchsia.ui.app.ViewProvider from the flutter app. realm_builder()->AddRoute( Route{.capabilities = {Protocol{fuchsia::ui::app::ViewProvider::Name_}}, .source = kTextInputViewRef, .targets = {ParentRef()}}); realm_builder()->AddRoute(Route{ .capabilities = {Protocol{fuchsia::ui::input3::Keyboard::Name_}, Protocol{"fuchsia.accessibility.semantics.SemanticsManager"}}, .source = kTestUIStackRef, .targets = {ParentRef(), kFlutterJitRunnerRef}}); } }; INSTANTIATE_TEST_SUITE_P(TextInputTestParameterized, TextInputTest, ::testing::Values(kTestUIStackUrl)); TEST_P(TextInputTest, TextInput) { // Launch view FML_LOG(INFO) << "Initializing scene"; LaunchClient(); FML_LOG(INFO) << "Client launched"; SimulateTextEntry("Hello\nworld!"); std::vector<std::string> expected = {"LEFT_SHIFT", "H", "E", "L", "L", "O", "ENTER", "W", "O", "R", "L", "D", "LEFT_SHIFT", "KEY_1"}; RunLoopUntil( [&] { return keyboard_input_listener_server_->HasResponse(expected); }); } } // namespace
engine/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-test.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/text-input/text-input-test.cc", "repo_id": "engine", "token_count": 3332 }
410
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "text_delegate.h" #include <fuchsia/ui/input/cpp/fidl.h> #include <fuchsia/ui/input3/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/fidl/cpp/binding.h> #include "flutter/fml/logging.h" #include "flutter/fml/mapping.h" #include "flutter/lib/ui/window/platform_message.h" #include "flutter/shell/platform/fuchsia/flutter/keyboard.h" #include "flutter/shell/platform/fuchsia/runtime/dart/utils/inlines.h" #include "third_party/rapidjson/include/rapidjson/document.h" #include "third_party/rapidjson/include/rapidjson/stringbuffer.h" #include "third_party/rapidjson/include/rapidjson/writer.h" #include "logging.h" namespace flutter_runner { static constexpr char kInputActionKey[] = "inputAction"; // See: https://api.flutter.dev/flutter/services/TextInputAction.html // Only the actions relevant for Fuchsia are listed here. static constexpr char kTextInputActionDone[] = "TextInputAction.done"; static constexpr char kTextInputActionNewline[] = "TextInputAction.newline"; static constexpr char kTextInputActionGo[] = "TextInputAction.go"; static constexpr char kTextInputActionNext[] = "TextInputAction.next"; static constexpr char kTextInputActionPrevious[] = "TextInputAction.previous"; static constexpr char kTextInputActionNone[] = "TextInputAction.none"; static constexpr char kTextInputActionSearch[] = "TextInputAction.search"; static constexpr char kTextInputActionSend[] = "TextInputAction.send"; static constexpr char kTextInputActionUnspecified[] = "TextInputAction.unspecified"; // Converts Flutter TextInputAction to Fuchsia action enum. static fuchsia::ui::input::InputMethodAction IntoInputMethodAction( const std::string action_string) { if (action_string == kTextInputActionNewline) { return fuchsia::ui::input::InputMethodAction::NEWLINE; } else if (action_string == kTextInputActionDone) { return fuchsia::ui::input::InputMethodAction::DONE; } else if (action_string == kTextInputActionGo) { return fuchsia::ui::input::InputMethodAction::GO; } else if (action_string == kTextInputActionNext) { return fuchsia::ui::input::InputMethodAction::NEXT; } else if (action_string == kTextInputActionPrevious) { return fuchsia::ui::input::InputMethodAction::PREVIOUS; } else if (action_string == kTextInputActionNone) { return fuchsia::ui::input::InputMethodAction::NONE; } else if (action_string == kTextInputActionSearch) { return fuchsia::ui::input::InputMethodAction::SEARCH; } else if (action_string == kTextInputActionSend) { return fuchsia::ui::input::InputMethodAction::SEND; } else if (action_string == kTextInputActionUnspecified) { return fuchsia::ui::input::InputMethodAction::UNSPECIFIED; } // If this message comes along it means we should really add the missing 'if' // above. FML_VLOG(1) << "unexpected action_string: " << action_string; // Substituting DONE for an unexpected action string will probably be OK. return fuchsia::ui::input::InputMethodAction::DONE; } // Converts the Fuchsia action enum into Flutter TextInputAction. static const std::string IntoTextInputAction( fuchsia::ui::input::InputMethodAction action) { if (action == fuchsia::ui::input::InputMethodAction::NEWLINE) { return kTextInputActionNewline; } else if (action == fuchsia::ui::input::InputMethodAction::DONE) { return kTextInputActionDone; } else if (action == fuchsia::ui::input::InputMethodAction::GO) { return kTextInputActionGo; } else if (action == fuchsia::ui::input::InputMethodAction::NEXT) { return kTextInputActionNext; } else if (action == fuchsia::ui::input::InputMethodAction::PREVIOUS) { return kTextInputActionPrevious; } else if (action == fuchsia::ui::input::InputMethodAction::NONE) { return kTextInputActionNone; } else if (action == fuchsia::ui::input::InputMethodAction::SEARCH) { return kTextInputActionSearch; } else if (action == fuchsia::ui::input::InputMethodAction::SEND) { return kTextInputActionSend; } else if (action == fuchsia::ui::input::InputMethodAction::UNSPECIFIED) { return kTextInputActionUnspecified; } // If this message comes along it means we should really add the missing 'if' // above. FML_VLOG(1) << "unexpected action: " << static_cast<uint32_t>(action); // Substituting "done" for an unexpected text input action will probably // be OK. return kTextInputActionDone; } // TODO(fxbug.dev/8868): Terminate engine if Fuchsia system FIDL connections // have error. template <class T> void SetInterfaceErrorHandler(fidl::InterfacePtr<T>& interface, std::string name) { interface.set_error_handler([name](zx_status_t status) { FML_LOG(ERROR) << "Interface error on: " << name << ", status: " << status; }); } template <class T> void SetInterfaceErrorHandler(fidl::Binding<T>& binding, std::string name) { binding.set_error_handler([name](zx_status_t status) { FML_LOG(ERROR) << "Binding error on: " << name << ", status: " << status; }); } TextDelegate::TextDelegate( fuchsia::ui::views::ViewRef view_ref, fuchsia::ui::input::ImeServiceHandle ime_service, fuchsia::ui::input3::KeyboardHandle keyboard, std::function<void(std::unique_ptr<flutter::PlatformMessage>)> dispatch_callback) : dispatch_callback_(dispatch_callback), ime_client_(this), text_sync_service_(ime_service.Bind()), keyboard_listener_binding_(this), keyboard_(keyboard.Bind()) { // Register all error handlers. SetInterfaceErrorHandler(ime_, "Input Method Editor"); SetInterfaceErrorHandler(ime_client_, "IME Client"); SetInterfaceErrorHandler(text_sync_service_, "Text Sync Service"); SetInterfaceErrorHandler(keyboard_listener_binding_, "Keyboard Listener"); SetInterfaceErrorHandler(keyboard_, "Keyboard"); // Configure keyboard listener. keyboard_->AddListener(std::move(view_ref), keyboard_listener_binding_.NewBinding(), [] {}); } void TextDelegate::ActivateIme() { ActivateIme(requested_text_action_.value_or( fuchsia::ui::input::InputMethodAction::DONE)); } void TextDelegate::ActivateIme(fuchsia::ui::input::InputMethodAction action) { FML_DCHECK(last_text_state_.has_value()); requested_text_action_ = action; text_sync_service_->GetInputMethodEditor( fuchsia::ui::input::KeyboardType::TEXT, // keyboard type action, // input method action last_text_state_.value(), // initial state ime_client_.NewBinding(), // client ime_.NewRequest() // editor ); } void TextDelegate::DeactivateIme() { if (ime_) { text_sync_service_->HideKeyboard(); ime_ = nullptr; } if (ime_client_.is_bound()) { ime_client_.Unbind(); } } // |fuchsia::ui::input::InputMethodEditorClient| void TextDelegate::DidUpdateState( fuchsia::ui::input::TextInputState state, std::unique_ptr<fuchsia::ui::input::InputEvent> input_event) { rapidjson::Document document; auto& allocator = document.GetAllocator(); rapidjson::Value encoded_state(rapidjson::kObjectType); encoded_state.AddMember("text", state.text, allocator); encoded_state.AddMember("selectionBase", state.selection.base, allocator); encoded_state.AddMember("selectionExtent", state.selection.extent, allocator); switch (state.selection.affinity) { case fuchsia::ui::input::TextAffinity::UPSTREAM: encoded_state.AddMember("selectionAffinity", rapidjson::Value("TextAffinity.upstream"), allocator); break; case fuchsia::ui::input::TextAffinity::DOWNSTREAM: encoded_state.AddMember("selectionAffinity", rapidjson::Value("TextAffinity.downstream"), allocator); break; } encoded_state.AddMember("selectionIsDirectional", true, allocator); encoded_state.AddMember("composingBase", state.composing.start, allocator); encoded_state.AddMember("composingExtent", state.composing.end, allocator); rapidjson::Value args(rapidjson::kArrayType); args.PushBack(current_text_input_client_, allocator); args.PushBack(encoded_state, allocator); document.SetObject(); document.AddMember("method", rapidjson::Value("TextInputClient.updateEditingState"), allocator); document.AddMember("args", args, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.GetString()); dispatch_callback_(std::make_unique<flutter::PlatformMessage>( kTextInputChannel, // channel fml::MallocMapping::Copy(data, buffer.GetSize()), // message nullptr) // response ); last_text_state_ = std::move(state); } // |fuchsia::ui::input::InputMethodEditorClient| void TextDelegate::OnAction(fuchsia::ui::input::InputMethodAction action) { rapidjson::Document document; auto& allocator = document.GetAllocator(); rapidjson::Value args(rapidjson::kArrayType); args.PushBack(current_text_input_client_, allocator); const std::string action_string = IntoTextInputAction(action); args.PushBack(rapidjson::Value{}.SetString(action_string.c_str(), action_string.length()), allocator); document.SetObject(); document.AddMember( "method", rapidjson::Value("TextInputClient.performAction"), allocator); document.AddMember("args", args, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.GetString()); dispatch_callback_(std::make_unique<flutter::PlatformMessage>( kTextInputChannel, // channel fml::MallocMapping::Copy(data, buffer.GetSize()), // message nullptr) // response ); } // Channel handler for kTextInputChannel bool TextDelegate::HandleFlutterTextInputChannelPlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { FML_DCHECK(message->channel() == kTextInputChannel); const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { return false; } auto root = document.GetObject(); auto method = root.FindMember("method"); if (method == root.MemberEnd() || !method->value.IsString()) { return false; } if (method->value == "TextInput.show") { if (ime_) { text_sync_service_->ShowKeyboard(); } } else if (method->value == "TextInput.hide") { if (ime_) { text_sync_service_->HideKeyboard(); } } else if (method->value == "TextInput.setClient") { // Sample "setClient" message: // // { // "method": "TextInput.setClient", // "args": [ // 7, // { // "inputType": { // "name": "TextInputType.multiline", // "signed":null, // "decimal":null // }, // "readOnly": false, // "obscureText": false, // "autocorrect":true, // "smartDashesType":"1", // "smartQuotesType":"1", // "enableSuggestions":true, // "enableInteractiveSelection":true, // "actionLabel":null, // "inputAction":"TextInputAction.newline", // "textCapitalization":"TextCapitalization.none", // "keyboardAppearance":"Brightness.dark", // "enableIMEPersonalizedLearning":true, // "enableDeltaModel":false // } // ] // } current_text_input_client_ = 0; DeactivateIme(); auto args = root.FindMember("args"); if (args == root.MemberEnd() || !args->value.IsArray() || args->value.Size() != 2) return false; const auto& configuration = args->value[1]; if (!configuration.IsObject()) { return false; } // TODO(abarth): Read the keyboard type from the configuration. current_text_input_client_ = args->value[0].GetInt(); auto initial_text_input_state = fuchsia::ui::input::TextInputState{}; initial_text_input_state.text = ""; last_text_state_ = std::move(initial_text_input_state); const auto configuration_object = configuration.GetObject(); if (!configuration_object.HasMember(kInputActionKey)) { return false; } const auto& action_object = configuration_object[kInputActionKey]; if (!action_object.IsString()) { return false; } const auto action_string = std::string(action_object.GetString(), action_object.GetStringLength()); ActivateIme(IntoInputMethodAction(std::move(action_string))); } else if (method->value == "TextInput.setEditingState") { if (ime_) { auto args_it = root.FindMember("args"); if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { return false; } const auto& args = args_it->value; fuchsia::ui::input::TextInputState state; state.text = ""; // TODO(abarth): Deserialize state. auto text = args.FindMember("text"); if (text != args.MemberEnd() && text->value.IsString()) { state.text = text->value.GetString(); } auto selection_base = args.FindMember("selectionBase"); if (selection_base != args.MemberEnd() && selection_base->value.IsInt()) { state.selection.base = selection_base->value.GetInt(); } auto selection_extent = args.FindMember("selectionExtent"); if (selection_extent != args.MemberEnd() && selection_extent->value.IsInt()) { state.selection.extent = selection_extent->value.GetInt(); } auto selection_affinity = args.FindMember("selectionAffinity"); if (selection_affinity != args.MemberEnd() && selection_affinity->value.IsString() && selection_affinity->value == "TextAffinity.upstream") { state.selection.affinity = fuchsia::ui::input::TextAffinity::UPSTREAM; } else { state.selection.affinity = fuchsia::ui::input::TextAffinity::DOWNSTREAM; } // We ignore selectionIsDirectional because that concept doesn't exist on // Fuchsia. auto composing_base = args.FindMember("composingBase"); if (composing_base != args.MemberEnd() && composing_base->value.IsInt()) { state.composing.start = composing_base->value.GetInt(); } auto composing_extent = args.FindMember("composingExtent"); if (composing_extent != args.MemberEnd() && composing_extent->value.IsInt()) { state.composing.end = composing_extent->value.GetInt(); } ime_->SetState(std::move(state)); } } else if (method->value == "TextInput.clearClient") { current_text_input_client_ = 0; last_text_state_ = std::nullopt; requested_text_action_ = std::nullopt; DeactivateIme(); } else if (method->value == "TextInput.setCaretRect" || method->value == "TextInput.setEditableSizeAndTransform" || method->value == "TextInput.setMarkedTextRect" || method->value == "TextInput.setStyle") { // We don't have these methods implemented and they get // sent a lot during text input, so we create an empty case for them // here to avoid "Unknown flutter/textinput method TextInput.*" // log spam. // // TODO(fxb/101619): We should implement these. } else { FML_LOG(ERROR) << "Unknown " << message->channel() << " method " << method->value.GetString(); } // Complete with an empty response. return false; } // |fuchsia::ui:input3::KeyboardListener| void TextDelegate::OnKeyEvent( fuchsia::ui::input3::KeyEvent key_event, fuchsia::ui::input3::KeyboardListener::OnKeyEventCallback callback) { const char* type = nullptr; switch (key_event.type()) { case fuchsia::ui::input3::KeyEventType::PRESSED: type = "keydown"; break; case fuchsia::ui::input3::KeyEventType::RELEASED: type = "keyup"; break; case fuchsia::ui::input3::KeyEventType::SYNC: // SYNC means the key was pressed while focus was not on this application. // This should possibly behave like PRESSED in the future, though it // doesn't hurt to ignore it today. case fuchsia::ui::input3::KeyEventType::CANCEL: // CANCEL means the key was released while focus was not on this // application. // This should possibly behave like RELEASED in the future to ensure that // a key is not repeated forever if it is pressed while focus is lost. default: break; } if (type == nullptr) { FML_VLOG(1) << "Unknown key event phase."; callback(fuchsia::ui::input3::KeyEventStatus::NOT_HANDLED); return; } keyboard_translator_.ConsumeEvent(std::move(key_event)); rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember("type", rapidjson::Value(type, strlen(type)), allocator); document.AddMember("keymap", rapidjson::Value("fuchsia"), allocator); document.AddMember("hidUsage", keyboard_translator_.LastHIDUsage(), allocator); document.AddMember("codePoint", keyboard_translator_.LastCodePoint(), allocator); document.AddMember("modifiers", keyboard_translator_.Modifiers(), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); const uint8_t* data = reinterpret_cast<const uint8_t*>(buffer.GetString()); dispatch_callback_(std::make_unique<flutter::PlatformMessage>( kKeyEventChannel, // channel fml::MallocMapping::Copy(data, buffer.GetSize()), // data nullptr) // response ); callback(fuchsia::ui::input3::KeyEventStatus::HANDLED); } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/text_delegate.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/text_delegate.cc", "repo_id": "engine", "token_count": 6911 }
411
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. name: profiler_symbols environment: sdk: '>=3.2.0-0 <4.0.0' version: 0 description: Extracts a minimal symbols table for the Dart VM profiler author: Dart Team <[email protected]>
engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/pubspec.yaml/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/pubspec.yaml", "repo_id": "engine", "token_count": 109 }
412
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tempfs.h" #include <string_view> #include <zircon/errors.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include "flutter/fml/logging.h" namespace { constexpr char kTmpPath[] = "/tmp"; } // namespace namespace dart_utils { void BindTemp(fdio_ns_t* ns) { // TODO(zra): Should isolates share a /tmp file system within a process, or // should isolates each get their own private file system for /tmp? For now, // sharing the process-wide /tmp simplifies hot reload since the hot reload // devfs requires sharing between the service isolate and the app isolates. fdio_flat_namespace_t* rootns; if (zx_status_t status = fdio_ns_export_root(&rootns); status != ZX_OK) { FML_LOG(ERROR) << "Failed to export root ns: " << zx_status_get_string(status); return; } zx_handle_t tmp_dir_handle; for (size_t i = 0; i < rootns->count; i++) { if (std::string_view{rootns->path[i]} == kTmpPath) { tmp_dir_handle = std::exchange(rootns->handle[i], ZX_HANDLE_INVALID); } } fdio_ns_free_flat_ns(rootns); if (zx_status_t status = fdio_ns_bind(ns, kTmpPath, tmp_dir_handle); status != ZX_OK) { zx_handle_close(tmp_dir_handle); FML_LOG(ERROR) << "Failed to bind /tmp directory into isolate namespace: " << zx_status_get_string(status); } } } // namespace dart_utils
engine/shell/platform/fuchsia/runtime/dart/utils/tempfs.cc/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/tempfs.cc", "repo_id": "engine", "token_count": 602 }
413
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_ #define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_ #include <flutter_glfw.h> #include <chrono> #include <memory> #include <string> #include <vector> #include "flutter_window.h" #include "plugin_registrar.h" #include "plugin_registry.h" namespace flutter { // Properties for Flutter window creation. struct WindowProperties { // The display title. std::string title; // Width in screen coordinates. int32_t width; // Height in screen coordinates. int32_t height; // Whether or not the user is prevented from resizing the window. // Reversed so that the default for a cleared struct is to allow resizing. bool prevent_resize; }; // A controller for a window displaying Flutter content. // // This is the primary wrapper class for the desktop C API. // If you use this class, you should not call any of the setup or teardown // methods in the C API directly, as this class will do that internally. // // Note: This is an early implementation (using GLFW internally) which // requires control of the application's event loop, and is thus useful // primarily for building a simple one-window shell hosting a Flutter // application. The final implementation and API will be very different. class FlutterWindowController : public PluginRegistry { public: // There must be only one instance of this class in an application at any // given time, as Flutter does not support multiple engines in one process, // or multiple views in one engine. // // |icu_data_path| is the path to the icudtl.dat file for the version of // Flutter you are using. explicit FlutterWindowController(const std::string& icu_data_path); virtual ~FlutterWindowController(); // Prevent copying. FlutterWindowController(FlutterWindowController const&) = delete; FlutterWindowController& operator=(FlutterWindowController const&) = delete; // Creates and displays a window for displaying Flutter content. // // The |assets_path| is the path to the flutter_assets folder for the Flutter // application to be run. // // The |arguments| are passed to the Flutter engine. See: // https://github.com/flutter/engine/blob/main/shell/common/switches.h for // details. Not all arguments will apply to desktop. // // The |aot_library_path| is the path to the libapp.so file for the Flutter // application to be run. While this parameter is only required in AOT mode, // it is perfectly safe to provide the path in non-AOT mode too. // // Only one Flutter window can exist at a time; see constructor comment. bool CreateWindow(const WindowProperties& window_properties, const std::string& assets_path, const std::vector<std::string>& arguments, const std::string& aot_library_path = ""); // Destroys the current window, if any. // // Because only one window can exist at a time, this method must be called // between calls to CreateWindow, or the second one will fail. void DestroyWindow(); // The FlutterWindow managed by this controller, if any. Returns nullptr // before CreateWindow is called, after DestroyWindow is called, and after // RunEventLoop returns; FlutterWindow* window() { return window_.get(); } // Processes the next event on this window, or returns early if |timeout| is // reached before the next event. // // Returns false if the window was closed as a result of event processing. bool RunEventLoopWithTimeout( std::chrono::milliseconds timeout = std::chrono::milliseconds::max()); // Deprecated. Use RunEventLoopWithTimeout. void RunEventLoop(); // flutter::PluginRegistry: FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( const std::string& plugin_name) override; private: // The path to the ICU data file. Set at creation time since it is the same // for any window created. std::string icu_data_path_; // Whether or not FlutterDesktopInit succeeded at creation time. bool init_succeeded_ = false; // The owned FlutterWindow, if any. std::unique_ptr<FlutterWindow> window_; // Handle for interacting with the C API's window controller, if any. FlutterDesktopWindowControllerRef controller_ = nullptr; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_
engine/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h", "repo_id": "engine", "token_count": 1391 }
414
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/glfw/platform_handler.h" #include <iostream> #include "flutter/shell/platform/common/json_method_codec.h" static constexpr char kChannelName[] = "flutter/platform"; static constexpr char kGetClipboardDataMethod[] = "Clipboard.getData"; static constexpr char kSetClipboardDataMethod[] = "Clipboard.setData"; static constexpr char kSystemNavigatorPopMethod[] = "SystemNavigator.pop"; static constexpr char kTextPlainFormat[] = "text/plain"; static constexpr char kTextKey[] = "text"; static constexpr char kNoWindowError[] = "Missing window error"; static constexpr char kUnknownClipboardFormatError[] = "Unknown clipboard format error"; namespace flutter { PlatformHandler::PlatformHandler(flutter::BinaryMessenger* messenger, GLFWwindow* window) : channel_(std::make_unique<flutter::MethodChannel<rapidjson::Document>>( messenger, kChannelName, &flutter::JsonMethodCodec::GetInstance())), window_(window) { channel_->SetMethodCallHandler( [this]( const flutter::MethodCall<rapidjson::Document>& call, std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) { HandleMethodCall(call, std::move(result)); }); } void PlatformHandler::HandleMethodCall( const flutter::MethodCall<rapidjson::Document>& method_call, std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) { const std::string& method = method_call.method_name(); if (method.compare(kGetClipboardDataMethod) == 0) { if (!window_) { result->Error(kNoWindowError, "Clipboard is not available in GLFW headless mode."); return; } // Only one string argument is expected. const rapidjson::Value& format = method_call.arguments()[0]; if (strcmp(format.GetString(), kTextPlainFormat) != 0) { result->Error(kUnknownClipboardFormatError, "GLFW clipboard API only supports text."); return; } const char* clipboardData = glfwGetClipboardString(window_); if (clipboardData == nullptr) { result->Error(kUnknownClipboardFormatError, "Failed to retrieve clipboard data from GLFW api."); return; } rapidjson::Document document; document.SetObject(); rapidjson::Document::AllocatorType& allocator = document.GetAllocator(); document.AddMember(rapidjson::Value(kTextKey, allocator), rapidjson::Value(clipboardData, allocator), allocator); result->Success(document); } else if (method.compare(kSetClipboardDataMethod) == 0) { if (!window_) { result->Error(kNoWindowError, "Clipboard is not available in GLFW headless mode."); return; } const rapidjson::Value& document = *method_call.arguments(); rapidjson::Value::ConstMemberIterator itr = document.FindMember(kTextKey); if (itr == document.MemberEnd()) { result->Error(kUnknownClipboardFormatError, "Missing text to store on clipboard."); return; } glfwSetClipboardString(window_, itr->value.GetString()); result->Success(); } else if (method.compare(kSystemNavigatorPopMethod) == 0) { exit(EXIT_SUCCESS); } else { result->NotImplemented(); } } } // namespace flutter
engine/shell/platform/glfw/platform_handler.cc/0
{ "file_path": "engine/shell/platform/glfw/platform_handler.cc", "repo_id": "engine", "token_count": 1313 }
415
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fl_backing_store_provider.h" #include <epoxy/gl.h> struct _FlBackingStoreProvider { GObject parent_instance; uint32_t framebuffer_id; uint32_t texture_id; GdkRectangle geometry; }; G_DEFINE_TYPE(FlBackingStoreProvider, fl_backing_store_provider, G_TYPE_OBJECT) static void fl_backing_store_provider_dispose(GObject* object) { FlBackingStoreProvider* self = FL_BACKING_STORE_PROVIDER(object); glDeleteFramebuffers(1, &self->framebuffer_id); glDeleteTextures(1, &self->texture_id); G_OBJECT_CLASS(fl_backing_store_provider_parent_class)->dispose(object); } static void fl_backing_store_provider_class_init( FlBackingStoreProviderClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_backing_store_provider_dispose; } static void fl_backing_store_provider_init(FlBackingStoreProvider* self) {} FlBackingStoreProvider* fl_backing_store_provider_new(int width, int height) { FlBackingStoreProvider* provider = FL_BACKING_STORE_PROVIDER( g_object_new(fl_backing_store_provider_get_type(), nullptr)); provider->geometry = { .x = 0, .y = 0, .width = width, .height = height, }; glGenTextures(1, &provider->texture_id); glGenFramebuffers(1, &provider->framebuffer_id); glBindFramebuffer(GL_FRAMEBUFFER, provider->framebuffer_id); glBindTexture(GL_TEXTURE_2D, provider->texture_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, provider->texture_id, 0); return provider; } uint32_t fl_backing_store_provider_get_gl_framebuffer_id( FlBackingStoreProvider* self) { return self->framebuffer_id; } uint32_t fl_backing_store_provider_get_gl_texture_id( FlBackingStoreProvider* self) { return self->texture_id; } uint32_t fl_backing_store_provider_get_gl_target(FlBackingStoreProvider* self) { return GL_TEXTURE_2D; } uint32_t fl_backing_store_provider_get_gl_format(FlBackingStoreProvider* self) { // Flutter defines SK_R32_SHIFT=16, so SK_PMCOLOR_BYTE_ORDER should be BGRA. // In Linux kN32_SkColorType is assumed to be kBGRA_8888_SkColorType. // So we must choose a valid gl format to be compatible with surface format // BGRA8. // Following logic is copied from Skia GrGLCaps.cpp: // https://github.com/google/skia/blob/4738ed711e03212aceec3cd502a4adb545f38e63/src/gpu/ganesh/gl/GrGLCaps.cpp#L1963-L2116 if (epoxy_is_desktop_gl()) { // For OpenGL. if (epoxy_gl_version() >= 12 || epoxy_has_gl_extension("GL_EXT_bgra")) { return GL_RGBA8; } } else { // For OpenGL ES. if (epoxy_has_gl_extension("GL_EXT_texture_format_BGRA8888") || (epoxy_has_gl_extension("GL_APPLE_texture_format_BGRA8888") && epoxy_gl_version() >= 30)) { return GL_BGRA8_EXT; } } g_critical("Failed to determine valid GL format for Flutter rendering"); return GL_RGBA8; } GdkRectangle fl_backing_store_provider_get_geometry( FlBackingStoreProvider* self) { return self->geometry; }
engine/shell/platform/linux/fl_backing_store_provider.cc/0
{ "file_path": "engine/shell/platform/linux/fl_backing_store_provider.cc", "repo_id": "engine", "token_count": 1434 }
416
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Included first as it collides with the X11 headers. #include "gtest/gtest.h" #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/fl_method_codec_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_event_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" #include "flutter/shell/platform/linux/testing/mock_renderer.h" // Data passed in tests. typedef struct { GMainLoop* loop; int count; } TestData; // Creates a mock engine that responds to platform messages. static FlEngine* make_mock_engine() { g_autoptr(FlDartProject) project = fl_dart_project_new(); g_autoptr(FlMockRenderer) renderer = fl_mock_renderer_new(); g_autoptr(FlEngine) engine = fl_engine_new(project, FL_RENDERER(renderer)); g_autoptr(GError) engine_error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &engine_error)); EXPECT_EQ(engine_error, nullptr); return static_cast<FlEngine*>(g_object_ref(engine)); } // Triggers the engine to start listening to the channel. static void listen_channel(FlBinaryMessenger* messenger, FlValue* args) { g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); // Trigger the engine to make a method call. g_autoptr(FlValue) invoke_args = fl_value_new_list(); fl_value_append_take(invoke_args, fl_value_new_string("test/standard-event")); fl_value_append_take(invoke_args, fl_value_new_string("listen")); g_autoptr(FlValue) value = args != nullptr ? fl_value_ref(args) : fl_value_new_null(); fl_value_append(invoke_args, value); fl_method_channel_invoke_method(channel, "InvokeMethod", invoke_args, nullptr, nullptr, nullptr); } // Triggers the engine to cancel the subscription to the channel. static void cancel_channel(FlBinaryMessenger* messenger, FlValue* args) { g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); // Trigger the engine to make a method call. g_autoptr(FlValue) invoke_args = fl_value_new_list(); fl_value_append_take(invoke_args, fl_value_new_string("test/standard-event")); fl_value_append_take(invoke_args, fl_value_new_string("cancel")); g_autoptr(FlValue) value = args != nullptr ? fl_value_ref(args) : fl_value_new_null(); fl_value_append(invoke_args, value); fl_method_channel_invoke_method(channel, "InvokeMethod", invoke_args, nullptr, nullptr, nullptr); } // Called when the remote end starts listening on the channel. static FlMethodErrorResponse* listen_listen_cb(FlEventChannel* channel, FlValue* args, gpointer user_data) { EXPECT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_NULL); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); return nullptr; } // Checks we detect a listen event. TEST(FlEventChannelTest, Listen) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel, listen_listen_cb, nullptr, loop, nullptr); listen_channel(messenger, nullptr); // Blocks here until listen_listen_cb called. g_main_loop_run(loop); // Manually unref because the compiler complains 'channel' is unused. g_object_unref(channel); } // Called when the remote end starts listening on the channel. static FlMethodErrorResponse* listen_exception_listen_cb( FlEventChannel* channel, FlValue* args, gpointer user_data) { return fl_method_error_response_new("LISTEN-ERROR", "LISTEN-ERROR-MESSAGE", nullptr); } // Called when a the test engine notifies us what response we sent in the // ListenException test. static void listen_exception_response_cb( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data) { fl_binary_messenger_send_response(messenger, response_handle, nullptr, nullptr); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); EXPECT_TRUE(FL_IS_METHOD_ERROR_RESPONSE(response)); EXPECT_STREQ( fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)), "LISTEN-ERROR"); EXPECT_STREQ( fl_method_error_response_get_message(FL_METHOD_ERROR_RESPONSE(response)), "LISTEN-ERROR-MESSAGE"); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks we can generate a listen exception. TEST(FlEventChannelTest, ListenException) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel, listen_exception_listen_cb, nullptr, loop, nullptr); // Listen for response to the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/responses", listen_exception_response_cb, loop, nullptr); listen_channel(messenger, nullptr); // Blocks here until listen_exception_response_cb called. g_main_loop_run(loop); // Manually unref because the compiler complains 'channel' is unused. g_object_unref(channel); } // Called when the remote end cancels their subscription. static FlMethodErrorResponse* cancel_cancel_cb(FlEventChannel* channel, FlValue* args, gpointer user_data) { EXPECT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_NULL); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); return nullptr; } // Checks we detect a cancel event. TEST(FlEventChannelTest, Cancel) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel, nullptr, cancel_cancel_cb, loop, nullptr); listen_channel(messenger, nullptr); cancel_channel(messenger, nullptr); // Blocks here until cancel_cancel_cb called. g_main_loop_run(loop); // Manually unref because the compiler complains 'channel' is unused. g_object_unref(channel); } // Called when the remote end cancels their subscription. static FlMethodErrorResponse* cancel_exception_cancel_cb( FlEventChannel* channel, FlValue* args, gpointer user_data) { return fl_method_error_response_new("CANCEL-ERROR", "CANCEL-ERROR-MESSAGE", nullptr); } // Called when a the test engine notifies us what response we sent in the // CancelException test. static void cancel_exception_response_cb( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data) { TestData* data = static_cast<TestData*>(user_data); fl_binary_messenger_send_response(messenger, response_handle, nullptr, nullptr); data->count++; if (data->count == 2) { g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response( FL_METHOD_CODEC(codec), message, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); EXPECT_TRUE(FL_IS_METHOD_ERROR_RESPONSE(response)); EXPECT_STREQ( fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)), "CANCEL-ERROR"); EXPECT_STREQ(fl_method_error_response_get_message( FL_METHOD_ERROR_RESPONSE(response)), "CANCEL-ERROR-MESSAGE"); g_main_loop_quit(data->loop); } } // Checks we can generate a cancel exception. TEST(FlEventChannelTest, CancelException) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); TestData data; data.loop = loop; data.count = 0; g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers( channel, nullptr, cancel_exception_cancel_cb, &data, nullptr); // Listen for response to the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/responses", cancel_exception_response_cb, &data, nullptr); listen_channel(messenger, nullptr); cancel_channel(messenger, nullptr); // Blocks here until cancel_exception_response_cb called. g_main_loop_run(loop); // Manually unref because the compiler complains 'channel' is unused. g_object_unref(channel); } // Called when the remote end starts listening on the channel. static FlMethodErrorResponse* args_listen_cb(FlEventChannel* channel, FlValue* args, gpointer user_data) { g_autoptr(FlValue) expected_args = fl_value_new_string("LISTEN-ARGS"); EXPECT_TRUE(fl_value_equal(args, expected_args)); return nullptr; } // Called when the remote end cancels their subscription. static FlMethodErrorResponse* args_cancel_cb(FlEventChannel* channel, FlValue* args, gpointer user_data) { g_autoptr(FlValue) expected_args = fl_value_new_string("CANCEL-ARGS"); EXPECT_TRUE(fl_value_equal(args, expected_args)); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); return nullptr; } // Checks args are passed to listen/cancel. TEST(FlEventChannelTest, Args) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel, args_listen_cb, args_cancel_cb, loop, nullptr); g_autoptr(FlValue) listen_args = fl_value_new_string("LISTEN-ARGS"); listen_channel(messenger, listen_args); g_autoptr(FlValue) cancel_args = fl_value_new_string("CANCEL-ARGS"); cancel_channel(messenger, cancel_args); // Blocks here until args_cancel_cb called. g_main_loop_run(loop); // Manually unref because the compiler complains 'channel' is unused. g_object_unref(channel); } // Called when the remote end starts listening on the channel. static FlMethodErrorResponse* send_events_listen_cb(FlEventChannel* channel, FlValue* args, gpointer user_data) { // Send some events. for (int i = 0; i < 5; i++) { g_autoptr(FlValue) event = fl_value_new_int(i); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_event_channel_send(channel, event, nullptr, &error)); EXPECT_EQ(error, nullptr); } return nullptr; } // Called when a the test engine notifies us what event we sent in the // Test test. static void send_events_events_cb( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data) { TestData* data = static_cast<TestData*>(user_data); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); FlValue* result = fl_method_response_get_result(response, &error); EXPECT_NE(result, nullptr); EXPECT_EQ(error, nullptr); EXPECT_EQ(fl_value_get_type(result), FL_VALUE_TYPE_INT); EXPECT_EQ(fl_value_get_int(result), data->count); data->count++; fl_binary_messenger_send_response(messenger, response_handle, nullptr, nullptr); // Got all the results! if (data->count == 5) { g_main_loop_quit(data->loop); } } // Checks can send events. TEST(FlEventChannelTest, Test) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); TestData data; data.loop = loop; data.count = 0; g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel, send_events_listen_cb, nullptr, &data, nullptr); // Listen for events from the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/events", send_events_events_cb, &data, nullptr); listen_channel(messenger, nullptr); cancel_channel(messenger, nullptr); // Blocks here until send_events_events_cb receives the last event. g_main_loop_run(loop); // Manually unref because the compiler complains 'channel' is unused. g_object_unref(channel); } // Check can register an event channel with the same name as one previously // used. TEST(FlEventChannelTest, ReuseChannel) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); TestData data; data.loop = loop; data.count = 0; // Register an event channel. g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel1 = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel1, send_events_listen_cb, nullptr, &data, nullptr); // Remove this channel g_object_unref(channel1); // Register a second channel with the same name. g_autoptr(FlEventChannel) channel2 = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel2, send_events_listen_cb, nullptr, &data, nullptr); // Listen for events from the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/events", send_events_events_cb, &data, nullptr); listen_channel(messenger, nullptr); cancel_channel(messenger, nullptr); // Blocks here until send_events_events_cb receives the last event. g_main_loop_run(loop); } // Check can register an event channel replacing an existing one. TEST(FlEventChannelTest, ReplaceChannel) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); TestData data; data.loop = loop; data.count = 0; // Register an event channel. g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); FlEventChannel* channel1 = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel1, send_events_listen_cb, nullptr, &data, nullptr); // Register a second channel with the same name. g_autoptr(FlEventChannel) channel2 = fl_event_channel_new( messenger, "test/standard-event", FL_METHOD_CODEC(codec)); fl_event_channel_set_stream_handlers(channel2, send_events_listen_cb, nullptr, &data, nullptr); // Listen for events from the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/events", send_events_events_cb, &data, nullptr); listen_channel(messenger, nullptr); cancel_channel(messenger, nullptr); // Blocks here until send_events_events_cb receives the last event. g_main_loop_run(loop); }
engine/shell/platform/linux/fl_event_channel_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_event_channel_test.cc", "repo_id": "engine", "token_count": 7034 }
417
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EVENT_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EVENT_H_ #include <gdk/gdk.h> /** * FlKeyEvent: * A struct that stores information from GdkEvent. * * This is a class only used within the GTK embedding, created by * FlView and consumed by FlKeyboardManager. It is not sent to * the embedder. * * This object contains information from GdkEvent as well as an origin event * object, so that Flutter can create an event object in unit tests even after * migrating to GDK 4.0 which stops supporting creating GdkEvent. */ typedef struct _FlKeyEvent { // Time in milliseconds. guint32 time; // True if is a press event, otherwise a release event. bool is_press; // Hardware keycode. guint16 keycode; // Keyval. guint keyval; // Modifier state. GdkModifierType state; // Keyboard group. guint8 group; // The original event. GdkEvent* origin; } FlKeyEvent; /** * fl_key_event_new_from_gdk_event: * @event: the #GdkEvent this #FlKeyEvent is based on. The #event must be a * #GdkEventKey, and will be destroyed by #fl_key_event_dispose. * * Create a new #FlKeyEvent based on a #GdkEvent. * * Returns: a new #FlKeyEvent. Must be freed with #fl_key_event_dispose. */ FlKeyEvent* fl_key_event_new_from_gdk_event(GdkEvent* event); /** * fl_key_event_dispose: * @event: the event to dispose. * * Properly disposes the content of #event and then the pointer. */ void fl_key_event_dispose(FlKeyEvent* event); FlKeyEvent* fl_key_event_clone(const FlKeyEvent* source); #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_KEY_EVENT_H_
engine/shell/platform/linux/fl_key_event.h/0
{ "file_path": "engine/shell/platform/linux/fl_key_event.h", "repo_id": "engine", "token_count": 604 }
418
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CODEC_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CODEC_PRIVATE_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h" G_BEGIN_DECLS /** * fl_method_codec_encode_method_call: * @codec: an #FlMethodCodec. * @name: method name. * @args: (allow-none): method arguments, or %NULL. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes a method call. * * Returns: (transfer full): a binary encoding of this method call or %NULL if * not able to encode. */ GBytes* fl_method_codec_encode_method_call(FlMethodCodec* codec, const gchar* name, FlValue* args, GError** error); /** * fl_method_codec_decode_method_call: * @codec: an #FlMethodCodec. * @message: message to decode. * @name: (transfer full): location to write method name or %NULL if not * required. * @args: (transfer full): location to write method arguments, or %NULL if not * required. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Decodes a method call. * * Returns: %TRUE if successfully decoded. */ gboolean fl_method_codec_decode_method_call(FlMethodCodec* codec, GBytes* message, gchar** name, FlValue** args, GError** error); /** * fl_method_codec_encode_success_envelope: * @codec: an #FlMethodCodec. * @result: (allow-none): method result, or %NULL. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes a successful response to a method call. * * Returns: (transfer full): a binary encoding of this response or %NULL if not * able to encode. */ GBytes* fl_method_codec_encode_success_envelope(FlMethodCodec* codec, FlValue* result, GError** error); /** * fl_method_codec_encode_error_envelope: * @codec: an #FlMethodCodec. * @code: an error code. * @message: (allow-none): an error message or %NULL. * @details: (allow-none): error details, or %NULL. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes an error response to a method call. * * Returns: (transfer full): a binary encoding of this response or %NULL if not * able to encode. */ GBytes* fl_method_codec_encode_error_envelope(FlMethodCodec* codec, const gchar* code, const gchar* message, FlValue* details, GError** error); /** * fl_method_codec_decode_response: * @codec: an #FlMethodCodec. * @message: message to decode. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Decodes a response to a method call. If the call resulted in an error then * @error_code is set, otherwise it is %NULL. * * Returns: a new #FlMethodResponse or %NULL on error. */ FlMethodResponse* fl_method_codec_decode_response(FlMethodCodec* codec, GBytes* message, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_METHOD_CODEC_PRIVATE_H_
engine/shell/platform/linux/fl_method_codec_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_method_codec_private.h", "repo_id": "engine", "token_count": 1761 }
419
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fl_renderer.h" #include <epoxy/egl.h> #include <epoxy/gl.h> #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/linux/fl_backing_store_provider.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/fl_view_private.h" // Vertex shader to draw Flutter window contents. static const char* vertex_shader_src = "attribute vec2 position;\n" "attribute vec2 in_texcoord;\n" "varying vec2 texcoord;\n" "\n" "void main() {\n" " gl_Position = vec4(position, 0, 1);\n" " texcoord = in_texcoord;\n" "}\n"; // Fragment shader to draw Flutter window contents. static const char* fragment_shader_src = "uniform sampler2D texture;\n" "varying vec2 texcoord;\n" "\n" "void main() {\n" " gl_FragColor = texture2D(texture, texcoord);\n" "}\n"; G_DEFINE_QUARK(fl_renderer_error_quark, fl_renderer_error) typedef struct { FlView* view; // target dimension for resizing int target_width; int target_height; // whether the renderer waits for frame render bool blocking_main_thread; // true if frame was completed; resizing is not synchronized until first frame // was rendered bool had_first_frame; // Shader program. GLuint program; // Textures to render. GPtrArray* textures; } FlRendererPrivate; G_DEFINE_TYPE_WITH_PRIVATE(FlRenderer, fl_renderer, G_TYPE_OBJECT) // Returns the log for the given OpenGL shader. Must be freed by the caller. static gchar* get_shader_log(GLuint shader) { int log_length; gchar* log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length); log = static_cast<gchar*>(g_malloc(log_length + 1)); glGetShaderInfoLog(shader, log_length, nullptr, log); return log; } // Returns the log for the given OpenGL program. Must be freed by the caller. static gchar* get_program_log(GLuint program) { int log_length; gchar* log; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length); log = static_cast<gchar*>(g_malloc(log_length + 1)); glGetProgramInfoLog(program, log_length, nullptr, log); return log; } /// Converts a pixel co-ordinate from 0..pixels to OpenGL -1..1. static GLfloat pixels_to_gl_coords(GLfloat position, GLfloat pixels) { return (2.0 * position / pixels) - 1.0; } static void fl_renderer_unblock_main_thread(FlRenderer* self) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); if (priv->blocking_main_thread) { priv->blocking_main_thread = false; FlTaskRunner* runner = fl_engine_get_task_runner(fl_view_get_engine(priv->view)); fl_task_runner_release_main_thread(runner); } } static void fl_renderer_dispose(GObject* object) { FlRenderer* self = FL_RENDERER(object); FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); fl_renderer_unblock_main_thread(self); g_clear_pointer(&priv->textures, g_ptr_array_unref); G_OBJECT_CLASS(fl_renderer_parent_class)->dispose(object); } static void fl_renderer_class_init(FlRendererClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_renderer_dispose; } static void fl_renderer_init(FlRenderer* self) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); priv->textures = g_ptr_array_new_with_free_func(g_object_unref); } gboolean fl_renderer_start(FlRenderer* self, FlView* view) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); g_return_val_if_fail(FL_IS_RENDERER(self), FALSE); priv->view = view; return TRUE; } void* fl_renderer_get_proc_address(FlRenderer* self, const char* name) { g_return_val_if_fail(FL_IS_RENDERER(self), NULL); return reinterpret_cast<void*>(eglGetProcAddress(name)); } void fl_renderer_make_current(FlRenderer* self) { g_return_if_fail(FL_IS_RENDERER(self)); FL_RENDERER_GET_CLASS(self)->make_current(self); } void fl_renderer_make_resource_current(FlRenderer* self) { g_return_if_fail(FL_IS_RENDERER(self)); FL_RENDERER_GET_CLASS(self)->make_resource_current(self); } void fl_renderer_clear_current(FlRenderer* self) { g_return_if_fail(FL_IS_RENDERER(self)); FL_RENDERER_GET_CLASS(self)->clear_current(self); } guint32 fl_renderer_get_fbo(FlRenderer* self) { g_return_val_if_fail(FL_IS_RENDERER(self), 0); // There is only one frame buffer object - always return that. return 0; } gboolean fl_renderer_create_backing_store( FlRenderer* renderer, const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { fl_renderer_make_current(renderer); FlBackingStoreProvider* provider = fl_backing_store_provider_new(config->size.width, config->size.height); if (!provider) { g_warning("Failed to create backing store"); return FALSE; } uint32_t name = fl_backing_store_provider_get_gl_framebuffer_id(provider); uint32_t format = fl_backing_store_provider_get_gl_format(provider); backing_store_out->type = kFlutterBackingStoreTypeOpenGL; backing_store_out->open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; backing_store_out->open_gl.framebuffer.user_data = provider; backing_store_out->open_gl.framebuffer.name = name; backing_store_out->open_gl.framebuffer.target = format; backing_store_out->open_gl.framebuffer.destruction_callback = [](void* p) { // Backing store destroyed in fl_renderer_collect_backing_store(), set // on FlutterCompositor.collect_backing_store_callback during engine start. }; return TRUE; } gboolean fl_renderer_collect_backing_store( FlRenderer* self, const FlutterBackingStore* backing_store) { fl_renderer_make_current(self); // OpenGL context is required when destroying #FlBackingStoreProvider. g_object_unref(backing_store->open_gl.framebuffer.user_data); return TRUE; } void fl_renderer_wait_for_frame(FlRenderer* self, int target_width, int target_height) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); g_return_if_fail(FL_IS_RENDERER(self)); priv->target_width = target_width; priv->target_height = target_height; if (priv->had_first_frame && !priv->blocking_main_thread) { priv->blocking_main_thread = true; FlTaskRunner* runner = fl_engine_get_task_runner(fl_view_get_engine(priv->view)); fl_task_runner_block_main_thread(runner); } } gboolean fl_renderer_present_layers(FlRenderer* self, const FlutterLayer** layers, size_t layers_count) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); g_return_val_if_fail(FL_IS_RENDERER(self), FALSE); // ignore incoming frame with wrong dimensions in trivial case with just one // layer if (priv->blocking_main_thread && layers_count == 1 && layers[0]->offset.x == 0 && layers[0]->offset.y == 0 && (layers[0]->size.width != priv->target_width || layers[0]->size.height != priv->target_height)) { return true; } priv->had_first_frame = true; fl_renderer_unblock_main_thread(self); if (!priv->view) { return FALSE; } g_ptr_array_set_size(priv->textures, 0); for (size_t i = 0; i < layers_count; ++i) { const FlutterLayer* layer = layers[i]; switch (layer->type) { case kFlutterLayerContentTypeBackingStore: { const FlutterBackingStore* backing_store = layer->backing_store; auto framebuffer = &backing_store->open_gl.framebuffer; FlBackingStoreProvider* provider = FL_BACKING_STORE_PROVIDER(framebuffer->user_data); g_ptr_array_add(priv->textures, g_object_ref(provider)); } break; case kFlutterLayerContentTypePlatformView: { // TODO(robert-ancell) Not implemented - // https://github.com/flutter/flutter/issues/41724 } break; } } fl_view_redraw(priv->view); return TRUE; } void fl_renderer_setup(FlRenderer* self) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); g_return_if_fail(FL_IS_RENDERER(self)); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_src, nullptr); glCompileShader(vertex_shader); int vertex_compile_status; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &vertex_compile_status); if (vertex_compile_status == GL_FALSE) { g_autofree gchar* shader_log = get_shader_log(vertex_shader); g_warning("Failed to compile vertex shader: %s", shader_log); } GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_src, nullptr); glCompileShader(fragment_shader); int fragment_compile_status; glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &fragment_compile_status); if (fragment_compile_status == GL_FALSE) { g_autofree gchar* shader_log = get_shader_log(fragment_shader); g_warning("Failed to compile fragment shader: %s", shader_log); } priv->program = glCreateProgram(); glAttachShader(priv->program, vertex_shader); glAttachShader(priv->program, fragment_shader); glLinkProgram(priv->program); int link_status; glGetProgramiv(priv->program, GL_LINK_STATUS, &link_status); if (link_status == GL_FALSE) { g_autofree gchar* program_log = get_program_log(priv->program); g_warning("Failed to link program: %s", program_log); } glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); } void fl_renderer_render(FlRenderer* self, int width, int height) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); g_return_if_fail(FL_IS_RENDERER(self)); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(priv->program); for (guint i = 0; i < priv->textures->len; i++) { FlBackingStoreProvider* texture = FL_BACKING_STORE_PROVIDER(g_ptr_array_index(priv->textures, i)); uint32_t texture_id = fl_backing_store_provider_get_gl_texture_id(texture); glBindTexture(GL_TEXTURE_2D, texture_id); // Translate into OpenGL co-ordinates GdkRectangle texture_geometry = fl_backing_store_provider_get_geometry(texture); GLfloat texture_x = texture_geometry.x; GLfloat texture_y = texture_geometry.y; GLfloat texture_width = texture_geometry.width; GLfloat texture_height = texture_geometry.height; GLfloat x0 = pixels_to_gl_coords(texture_x, width); GLfloat y0 = pixels_to_gl_coords(height - (texture_y + texture_height), height); GLfloat x1 = pixels_to_gl_coords(texture_x + texture_width, width); GLfloat y1 = pixels_to_gl_coords(height - texture_y, height); GLfloat vertex_data[] = {x0, y0, 0, 0, x1, y1, 1, 1, x0, y1, 0, 1, x0, y0, 0, 0, x1, y0, 1, 0, x1, y1, 1, 1}; GLuint vao, vertex_buffer; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); GLint position_index = glGetAttribLocation(priv->program, "position"); glEnableVertexAttribArray(position_index); glVertexAttribPointer(position_index, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, 0); GLint texcoord_index = glGetAttribLocation(priv->program, "in_texcoord"); glEnableVertexAttribArray(texcoord_index); glVertexAttribPointer(texcoord_index, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, (void*)(sizeof(GLfloat) * 2)); glDrawArrays(GL_TRIANGLES, 0, 6); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vertex_buffer); } glFlush(); } void fl_renderer_cleanup(FlRenderer* self) { FlRendererPrivate* priv = reinterpret_cast<FlRendererPrivate*>( fl_renderer_get_instance_private(self)); g_return_if_fail(FL_IS_RENDERER(self)); glDeleteProgram(priv->program); }
engine/shell/platform/linux/fl_renderer.cc/0
{ "file_path": "engine/shell/platform/linux/fl_renderer.cc", "repo_id": "engine", "token_count": 4947 }
420
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_settings_portal.h" #include <gio/gio.h> #include <glib.h> static constexpr char kPortalName[] = "org.freedesktop.portal.Desktop"; static constexpr char kPortalPath[] = "/org/freedesktop/portal/desktop"; static constexpr char kPortalSettings[] = "org.freedesktop.portal.Settings"; struct FlSetting { const gchar* ns; const gchar* key; const GVariantType* type; }; static constexpr char kXdgAppearance[] = "org.freedesktop.appearance"; static const FlSetting kColorScheme = { kXdgAppearance, "color-scheme", G_VARIANT_TYPE_UINT32, }; static constexpr char kGnomeA11yInterface[] = "org.gnome.desktop.a11y.interface"; static const FlSetting kHighContrast = { kGnomeA11yInterface, "high-contrast", G_VARIANT_TYPE_BOOLEAN, }; static constexpr char kGnomeDesktopInterface[] = "org.gnome.desktop.interface"; static const FlSetting kClockFormat = { kGnomeDesktopInterface, "clock-format", G_VARIANT_TYPE_STRING, }; static const FlSetting kEnableAnimations = { kGnomeDesktopInterface, "enable-animations", G_VARIANT_TYPE_BOOLEAN, }; static const FlSetting kGtkTheme = { kGnomeDesktopInterface, "gtk-theme", G_VARIANT_TYPE_STRING, }; static const FlSetting kTextScalingFactor = { kGnomeDesktopInterface, "text-scaling-factor", G_VARIANT_TYPE_DOUBLE, }; static const FlSetting kAllSettings[] = { kClockFormat, kColorScheme, kEnableAnimations, kGtkTheme, kHighContrast, kTextScalingFactor, }; static constexpr char kClockFormat12Hour[] = "12h"; static constexpr char kGtkThemeDarkSuffix[] = "-dark"; typedef enum { kDefault, kPreferDark, kPreferLight } ColorScheme; struct _FlSettingsPortal { GObject parent_instance; GDBusProxy* dbus_proxy; GVariantDict* values; }; static void fl_settings_portal_iface_init(FlSettingsInterface* iface); G_DEFINE_TYPE_WITH_CODE(FlSettingsPortal, fl_settings_portal, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(fl_settings_get_type(), fl_settings_portal_iface_init)) static gchar* format_key(const FlSetting* setting) { return g_strconcat(setting->ns, "::", setting->key, nullptr); } static gboolean get_value(FlSettingsPortal* portal, const FlSetting* setting, GVariant** value) { g_autofree const gchar* key = format_key(setting); *value = g_variant_dict_lookup_value(portal->values, key, setting->type); return *value != nullptr; } static void set_value(FlSettingsPortal* portal, const FlSetting* setting, GVariant* value) { g_autofree const gchar* key = format_key(setting); // ignore redundant changes from multiple XDG desktop portal backends g_autoptr(GVariant) old_value = g_variant_dict_lookup_value(portal->values, key, nullptr); if (old_value != nullptr && value != nullptr && g_variant_equal(old_value, value)) { return; } g_variant_dict_insert_value(portal->values, key, value); fl_settings_emit_changed(FL_SETTINGS(portal)); } // Based on // https://gitlab.gnome.org/GNOME/Initiatives/-/wikis/Dark-Style-Preference#other static gboolean settings_portal_read(GDBusProxy* proxy, const gchar* ns, const gchar* key, GVariant** out) { g_autoptr(GError) error = nullptr; g_autoptr(GVariant) value = g_dbus_proxy_call_sync(proxy, "Read", g_variant_new("(ss)", ns, key), G_DBUS_CALL_FLAGS_NONE, G_MAXINT, nullptr, &error); if (error) { if (error->domain == G_DBUS_ERROR && error->code == G_DBUS_ERROR_SERVICE_UNKNOWN) { g_debug("XDG desktop portal unavailable: %s", error->message); return false; } if (error->domain == G_DBUS_ERROR && error->code == G_DBUS_ERROR_UNKNOWN_METHOD) { g_debug("XDG desktop portal settings unavailable: %s", error->message); return false; } g_critical("Failed to read XDG desktop portal settings: %s", error->message); return false; } g_autoptr(GVariant) child = nullptr; g_variant_get(value, "(v)", &child); g_variant_get(child, "v", out); return true; } static void settings_portal_changed_cb(GDBusProxy* proxy, const char* sender_name, const char* signal_name, GVariant* parameters, gpointer user_data) { FlSettingsPortal* portal = FL_SETTINGS_PORTAL(user_data); if (g_strcmp0(signal_name, "SettingChanged")) { return; } FlSetting setting; g_autoptr(GVariant) value = nullptr; g_variant_get(parameters, "(&s&sv)", &setting.ns, &setting.key, &value); set_value(portal, &setting, value); } static FlClockFormat fl_settings_portal_get_clock_format(FlSettings* settings) { FlSettingsPortal* self = FL_SETTINGS_PORTAL(settings); FlClockFormat clock_format = FL_CLOCK_FORMAT_24H; g_autoptr(GVariant) value = nullptr; if (get_value(self, &kClockFormat, &value)) { const gchar* clock_format_str = g_variant_get_string(value, nullptr); if (g_strcmp0(clock_format_str, kClockFormat12Hour) == 0) { clock_format = FL_CLOCK_FORMAT_12H; } } return clock_format; } static FlColorScheme fl_settings_portal_get_color_scheme(FlSettings* settings) { FlSettingsPortal* self = FL_SETTINGS_PORTAL(settings); FlColorScheme color_scheme = FL_COLOR_SCHEME_LIGHT; g_autoptr(GVariant) value = nullptr; if (get_value(self, &kColorScheme, &value)) { if (g_variant_get_uint32(value) == kPreferDark) { color_scheme = FL_COLOR_SCHEME_DARK; } } else if (get_value(self, &kGtkTheme, &value)) { const gchar* gtk_theme_str = g_variant_get_string(value, nullptr); if (g_str_has_suffix(gtk_theme_str, kGtkThemeDarkSuffix)) { color_scheme = FL_COLOR_SCHEME_DARK; } } return color_scheme; } static gboolean fl_settings_portal_get_enable_animations(FlSettings* settings) { FlSettingsPortal* self = FL_SETTINGS_PORTAL(settings); gboolean enable_animations = true; g_autoptr(GVariant) value = nullptr; if (get_value(self, &kEnableAnimations, &value)) { enable_animations = g_variant_get_boolean(value); } return enable_animations; } static gboolean fl_settings_portal_get_high_contrast(FlSettings* settings) { FlSettingsPortal* self = FL_SETTINGS_PORTAL(settings); gboolean high_contrast = false; g_autoptr(GVariant) value = nullptr; if (get_value(self, &kHighContrast, &value)) { high_contrast = g_variant_get_boolean(value); } return high_contrast; } static gdouble fl_settings_portal_get_text_scaling_factor( FlSettings* settings) { FlSettingsPortal* self = FL_SETTINGS_PORTAL(settings); gdouble scaling_factor = 1.0; g_autoptr(GVariant) value = nullptr; if (get_value(self, &kTextScalingFactor, &value)) { scaling_factor = g_variant_get_double(value); } return scaling_factor; } static void fl_settings_portal_dispose(GObject* object) { FlSettingsPortal* self = FL_SETTINGS_PORTAL(object); g_clear_object(&self->dbus_proxy); g_clear_pointer(&self->values, g_variant_dict_unref); G_OBJECT_CLASS(fl_settings_portal_parent_class)->dispose(object); } static void fl_settings_portal_class_init(FlSettingsPortalClass* klass) { GObjectClass* object_class = G_OBJECT_CLASS(klass); object_class->dispose = fl_settings_portal_dispose; } static void fl_settings_portal_iface_init(FlSettingsInterface* iface) { iface->get_clock_format = fl_settings_portal_get_clock_format; iface->get_color_scheme = fl_settings_portal_get_color_scheme; iface->get_enable_animations = fl_settings_portal_get_enable_animations; iface->get_high_contrast = fl_settings_portal_get_high_contrast; iface->get_text_scaling_factor = fl_settings_portal_get_text_scaling_factor; } static void fl_settings_portal_init(FlSettingsPortal* self) {} FlSettingsPortal* fl_settings_portal_new() { g_autoptr(GVariantDict) values = g_variant_dict_new(nullptr); return fl_settings_portal_new_with_values(values); } FlSettingsPortal* fl_settings_portal_new_with_values(GVariantDict* values) { g_return_val_if_fail(values != nullptr, nullptr); FlSettingsPortal* portal = FL_SETTINGS_PORTAL(g_object_new(fl_settings_portal_get_type(), nullptr)); portal->values = g_variant_dict_ref(values); return portal; } gboolean fl_settings_portal_start(FlSettingsPortal* self, GError** error) { g_return_val_if_fail(FL_IS_SETTINGS_PORTAL(self), false); g_return_val_if_fail(self->dbus_proxy == nullptr, false); self->dbus_proxy = g_dbus_proxy_new_for_bus_sync( G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, nullptr, kPortalName, kPortalPath, kPortalSettings, nullptr, error); if (self->dbus_proxy == nullptr) { return false; } for (const FlSetting setting : kAllSettings) { g_autoptr(GVariant) value = nullptr; if (settings_portal_read(self->dbus_proxy, setting.ns, setting.key, &value)) { set_value(self, &setting, value); } } g_signal_connect_object(self->dbus_proxy, "g-signal", G_CALLBACK(settings_portal_changed_cb), self, static_cast<GConnectFlags>(0)); return true; }
engine/shell/platform/linux/fl_settings_portal.cc/0
{ "file_path": "engine/shell/platform/linux/fl_settings_portal.cc", "repo_id": "engine", "token_count": 4076 }
421
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/public/flutter_linux/fl_texture.h" #include "flutter/shell/platform/linux/fl_texture_private.h" #include <gmodule.h> #include <cstdio> G_DEFINE_INTERFACE(FlTexture, fl_texture, G_TYPE_OBJECT) static void fl_texture_default_init(FlTextureInterface* self) {} void fl_texture_set_id(FlTexture* self, int64_t id) { g_return_if_fail(FL_IS_TEXTURE(self)); FL_TEXTURE_GET_IFACE(self)->set_id(self, id); } G_MODULE_EXPORT int64_t fl_texture_get_id(FlTexture* self) { g_return_val_if_fail(FL_IS_TEXTURE(self), -1); return FL_TEXTURE_GET_IFACE(self)->get_id(self); }
engine/shell/platform/linux/fl_texture.cc/0
{ "file_path": "engine/shell/platform/linux/fl_texture.cc", "repo_id": "engine", "token_count": 288 }
422
// Copyright 2013 The Flutter 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 "key_mapping.h" #include <glib.h> #include <map> #include "flutter/shell/platform/linux/fl_key_embedder_responder_private.h" // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // This file is generated by // flutter/flutter@dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not // be edited directly. // // Edit the template dev/tools/gen_keycodes/data/gtk_key_mapping_cc.tmpl // instead. See dev/tools/gen_keycodes/README.md for more information. std::map<uint64_t, uint64_t> xkb_to_physical_key_map = { {0x00000009, 0x00070029}, // escape {0x0000000a, 0x0007001e}, // digit1 {0x0000000b, 0x0007001f}, // digit2 {0x0000000c, 0x00070020}, // digit3 {0x0000000d, 0x00070021}, // digit4 {0x0000000e, 0x00070022}, // digit5 {0x0000000f, 0x00070023}, // digit6 {0x00000010, 0x00070024}, // digit7 {0x00000011, 0x00070025}, // digit8 {0x00000012, 0x00070026}, // digit9 {0x00000013, 0x00070027}, // digit0 {0x00000014, 0x0007002d}, // minus {0x00000015, 0x0007002e}, // equal {0x00000016, 0x0007002a}, // backspace {0x00000017, 0x0007002b}, // tab {0x00000018, 0x00070014}, // keyQ {0x00000019, 0x0007001a}, // keyW {0x0000001a, 0x00070008}, // keyE {0x0000001b, 0x00070015}, // keyR {0x0000001c, 0x00070017}, // keyT {0x0000001d, 0x0007001c}, // keyY {0x0000001e, 0x00070018}, // keyU {0x0000001f, 0x0007000c}, // keyI {0x00000020, 0x00070012}, // keyO {0x00000021, 0x00070013}, // keyP {0x00000022, 0x0007002f}, // bracketLeft {0x00000023, 0x00070030}, // bracketRight {0x00000024, 0x00070028}, // enter {0x00000025, 0x000700e0}, // controlLeft {0x00000026, 0x00070004}, // keyA {0x00000027, 0x00070016}, // keyS {0x00000028, 0x00070007}, // keyD {0x00000029, 0x00070009}, // keyF {0x0000002a, 0x0007000a}, // keyG {0x0000002b, 0x0007000b}, // keyH {0x0000002c, 0x0007000d}, // keyJ {0x0000002d, 0x0007000e}, // keyK {0x0000002e, 0x0007000f}, // keyL {0x0000002f, 0x00070033}, // semicolon {0x00000030, 0x00070034}, // quote {0x00000031, 0x00070035}, // backquote {0x00000032, 0x000700e1}, // shiftLeft {0x00000033, 0x00070031}, // backslash {0x00000034, 0x0007001d}, // keyZ {0x00000035, 0x0007001b}, // keyX {0x00000036, 0x00070006}, // keyC {0x00000037, 0x00070019}, // keyV {0x00000038, 0x00070005}, // keyB {0x00000039, 0x00070011}, // keyN {0x0000003a, 0x00070010}, // keyM {0x0000003b, 0x00070036}, // comma {0x0000003c, 0x00070037}, // period {0x0000003d, 0x00070038}, // slash {0x0000003e, 0x000700e5}, // shiftRight {0x0000003f, 0x00070055}, // numpadMultiply {0x00000040, 0x000700e2}, // altLeft {0x00000041, 0x0007002c}, // space {0x00000042, 0x00070039}, // capsLock {0x00000043, 0x0007003a}, // f1 {0x00000044, 0x0007003b}, // f2 {0x00000045, 0x0007003c}, // f3 {0x00000046, 0x0007003d}, // f4 {0x00000047, 0x0007003e}, // f5 {0x00000048, 0x0007003f}, // f6 {0x00000049, 0x00070040}, // f7 {0x0000004a, 0x00070041}, // f8 {0x0000004b, 0x00070042}, // f9 {0x0000004c, 0x00070043}, // f10 {0x0000004d, 0x00070053}, // numLock {0x0000004e, 0x00070047}, // scrollLock {0x0000004f, 0x0007005f}, // numpad7 {0x00000050, 0x00070060}, // numpad8 {0x00000051, 0x00070061}, // numpad9 {0x00000052, 0x00070056}, // numpadSubtract {0x00000053, 0x0007005c}, // numpad4 {0x00000054, 0x0007005d}, // numpad5 {0x00000055, 0x0007005e}, // numpad6 {0x00000056, 0x00070057}, // numpadAdd {0x00000057, 0x00070059}, // numpad1 {0x00000058, 0x0007005a}, // numpad2 {0x00000059, 0x0007005b}, // numpad3 {0x0000005a, 0x00070062}, // numpad0 {0x0000005b, 0x00070063}, // numpadDecimal {0x0000005d, 0x00070094}, // lang5 {0x0000005e, 0x00070064}, // intlBackslash {0x0000005f, 0x00070044}, // f11 {0x00000060, 0x00070045}, // f12 {0x00000061, 0x00070087}, // intlRo {0x00000062, 0x00070092}, // lang3 {0x00000063, 0x00070093}, // lang4 {0x00000064, 0x0007008a}, // convert {0x00000065, 0x00070088}, // kanaMode {0x00000066, 0x0007008b}, // nonConvert {0x00000068, 0x00070058}, // numpadEnter {0x00000069, 0x000700e4}, // controlRight {0x0000006a, 0x00070054}, // numpadDivide {0x0000006b, 0x00070046}, // printScreen {0x0000006c, 0x000700e6}, // altRight {0x0000006e, 0x0007004a}, // home {0x0000006f, 0x00070052}, // arrowUp {0x00000070, 0x0007004b}, // pageUp {0x00000071, 0x00070050}, // arrowLeft {0x00000072, 0x0007004f}, // arrowRight {0x00000073, 0x0007004d}, // end {0x00000074, 0x00070051}, // arrowDown {0x00000075, 0x0007004e}, // pageDown {0x00000076, 0x00070049}, // insert {0x00000077, 0x0007004c}, // delete {0x00000079, 0x0007007f}, // audioVolumeMute {0x0000007a, 0x00070081}, // audioVolumeDown {0x0000007b, 0x00070080}, // audioVolumeUp {0x0000007c, 0x00070066}, // power {0x0000007d, 0x00070067}, // numpadEqual {0x0000007e, 0x000700d7}, // numpadSignChange {0x0000007f, 0x00070048}, // pause {0x00000080, 0x000c029f}, // showAllWindows {0x00000081, 0x00070085}, // numpadComma {0x00000082, 0x00070090}, // lang1 {0x00000083, 0x00070091}, // lang2 {0x00000084, 0x00070089}, // intlYen {0x00000085, 0x000700e3}, // metaLeft {0x00000086, 0x000700e7}, // metaRight {0x00000087, 0x00070065}, // contextMenu {0x00000088, 0x000c0226}, // browserStop {0x00000089, 0x00070079}, // again {0x0000008b, 0x0007007a}, // undo {0x0000008c, 0x00070077}, // select {0x0000008d, 0x0007007c}, // copy {0x0000008e, 0x00070074}, // open {0x0000008f, 0x0007007d}, // paste {0x00000090, 0x0007007e}, // find {0x00000091, 0x0007007b}, // cut {0x00000092, 0x00070075}, // help {0x00000094, 0x000c0192}, // launchApp2 {0x00000096, 0x00010082}, // sleep {0x00000097, 0x00010083}, // wakeUp {0x00000098, 0x000c0194}, // launchApp1 {0x0000009e, 0x000c0196}, // launchInternetBrowser {0x000000a0, 0x000c019e}, // lockScreen {0x000000a3, 0x000c018a}, // launchMail {0x000000a4, 0x000c022a}, // browserFavorites {0x000000a6, 0x000c0224}, // browserBack {0x000000a7, 0x000c0225}, // browserForward {0x000000a9, 0x000c00b8}, // eject {0x000000ab, 0x000c00b5}, // mediaTrackNext {0x000000ac, 0x000c00cd}, // mediaPlayPause {0x000000ad, 0x000c00b6}, // mediaTrackPrevious {0x000000ae, 0x000c00b7}, // mediaStop {0x000000af, 0x000c00b2}, // mediaRecord {0x000000b0, 0x000c00b4}, // mediaRewind {0x000000b1, 0x000c008c}, // launchPhone {0x000000b3, 0x000c0183}, // mediaSelect {0x000000b4, 0x000c0223}, // browserHome {0x000000b5, 0x000c0227}, // browserRefresh {0x000000b6, 0x000c0094}, // exit {0x000000bb, 0x000700b6}, // numpadParenLeft {0x000000bc, 0x000700b7}, // numpadParenRight {0x000000bd, 0x000c0201}, // newKey {0x000000be, 0x000c0279}, // redo {0x000000bf, 0x00070068}, // f13 {0x000000c0, 0x00070069}, // f14 {0x000000c1, 0x0007006a}, // f15 {0x000000c2, 0x0007006b}, // f16 {0x000000c3, 0x0007006c}, // f17 {0x000000c4, 0x0007006d}, // f18 {0x000000c5, 0x0007006e}, // f19 {0x000000c6, 0x0007006f}, // f20 {0x000000c7, 0x00070070}, // f21 {0x000000c8, 0x00070071}, // f22 {0x000000c9, 0x00070072}, // f23 {0x000000ca, 0x00070073}, // f24 {0x000000d1, 0x000c00b1}, // mediaPause {0x000000d6, 0x000c0203}, // close {0x000000d7, 0x000c00b0}, // mediaPlay {0x000000d8, 0x000c00b3}, // mediaFastForward {0x000000d9, 0x000c00e5}, // bassBoost {0x000000da, 0x000c0208}, // print {0x000000e1, 0x000c0221}, // browserSearch {0x000000e8, 0x000c0070}, // brightnessDown {0x000000e9, 0x000c006f}, // brightnessUp {0x000000eb, 0x000100b5}, // displayToggleIntExt {0x000000ed, 0x000c007a}, // kbdIllumDown {0x000000ee, 0x000c0079}, // kbdIllumUp {0x000000ef, 0x000c028c}, // mailSend {0x000000f0, 0x000c0289}, // mailReply {0x000000f1, 0x000c028b}, // mailForward {0x000000f2, 0x000c0207}, // save {0x000000f3, 0x000c01a7}, // launchDocuments {0x000000fc, 0x000c0075}, // brightnessAuto {0x00000100, 0x00000018}, // microphoneMuteToggle {0x0000016e, 0x000c0060}, // info {0x00000172, 0x000c008d}, // programGuide {0x0000017a, 0x000c0061}, // closedCaptionToggle {0x0000017c, 0x000c0232}, // zoomToggle {0x0000017e, 0x000c01ae}, // launchKeyboardLayout {0x00000190, 0x000c01b7}, // launchAudioBrowser {0x00000195, 0x000c018e}, // launchCalendar {0x0000019d, 0x000c0083}, // mediaLast {0x000001a2, 0x000c009c}, // channelUp {0x000001a3, 0x000c009d}, // channelDown {0x000001aa, 0x000c022d}, // zoomIn {0x000001ab, 0x000c022e}, // zoomOut {0x000001ad, 0x000c0184}, // launchWordProcessor {0x000001af, 0x000c0186}, // launchSpreadsheet {0x000001b5, 0x000c018d}, // launchContacts {0x000001b7, 0x000c0072}, // brightnessToggle {0x000001b8, 0x000c01ab}, // spellCheck {0x000001b9, 0x000c019c}, // logOff {0x0000024b, 0x000c019f}, // launchControlPanel {0x0000024c, 0x000c01a2}, // selectTask {0x0000024d, 0x000c01b1}, // launchScreenSaver {0x0000024e, 0x000c00cf}, // speechInputToggle {0x0000024f, 0x000c01cb}, // launchAssistant {0x00000250, 0x000c029d}, // keyboardLayoutSelect {0x00000258, 0x000c0073}, // brightnessMinimum {0x00000259, 0x000c0074}, // brightnessMaximum {0x00000281, 0x00000017}, // privacyScreenToggle }; std::map<uint64_t, uint64_t> gtk_keyval_to_logical_key_map = { {0x000000a5, 0x00200000022}, // yen {0x0000fd06, 0x00100000405}, // 3270_EraseEOF {0x0000fd0e, 0x00100000503}, // 3270_Attn {0x0000fd15, 0x00100000402}, // 3270_Copy {0x0000fd16, 0x00100000d2f}, // 3270_Play {0x0000fd1b, 0x00100000406}, // 3270_ExSelect {0x0000fd1d, 0x00100000608}, // 3270_PrintScreen {0x0000fd1e, 0x0010000000d}, // 3270_Enter {0x0000fe03, 0x00200000105}, // ISO_Level3_Shift {0x0000fe08, 0x00100000709}, // ISO_Next_Group {0x0000fe0a, 0x0010000070a}, // ISO_Prev_Group {0x0000fe0c, 0x00100000707}, // ISO_First_Group {0x0000fe0e, 0x00100000708}, // ISO_Last_Group {0x0000fe20, 0x00100000009}, // ISO_Left_Tab {0x0000fe34, 0x0010000000d}, // ISO_Enter {0x0000ff08, 0x00100000008}, // BackSpace {0x0000ff09, 0x00100000009}, // Tab {0x0000ff0b, 0x00100000401}, // Clear {0x0000ff0d, 0x0010000000d}, // Return {0x0000ff13, 0x00100000509}, // Pause {0x0000ff14, 0x0010000010c}, // Scroll_Lock {0x0000ff1b, 0x0010000001b}, // Escape {0x0000ff21, 0x00100000719}, // Kanji {0x0000ff24, 0x0010000071b}, // Romaji {0x0000ff25, 0x00100000716}, // Hiragana {0x0000ff26, 0x0010000071a}, // Katakana {0x0000ff27, 0x00100000717}, // Hiragana_Katakana {0x0000ff28, 0x0010000071c}, // Zenkaku {0x0000ff29, 0x00100000715}, // Hankaku {0x0000ff2a, 0x0010000071d}, // Zenkaku_Hankaku {0x0000ff2f, 0x00100000714}, // Eisu_Shift {0x0000ff31, 0x00100000711}, // Hangul {0x0000ff34, 0x00100000712}, // Hangul_Hanja {0x0000ff37, 0x00100000703}, // Codeinput {0x0000ff3c, 0x00100000710}, // SingleCandidate {0x0000ff3e, 0x0010000070e}, // PreviousCandidate {0x0000ff50, 0x00100000306}, // Home {0x0000ff51, 0x00100000302}, // Left {0x0000ff52, 0x00100000304}, // Up {0x0000ff53, 0x00100000303}, // Right {0x0000ff54, 0x00100000301}, // Down {0x0000ff55, 0x00100000308}, // Page_Up {0x0000ff56, 0x00100000307}, // Page_Down {0x0000ff57, 0x00100000305}, // End {0x0000ff60, 0x0010000050c}, // Select {0x0000ff61, 0x00100000a0c}, // Print {0x0000ff62, 0x00100000506}, // Execute {0x0000ff63, 0x00100000407}, // Insert {0x0000ff65, 0x0010000040a}, // Undo {0x0000ff66, 0x00100000409}, // Redo {0x0000ff67, 0x00100000505}, // Menu {0x0000ff68, 0x00100000507}, // Find {0x0000ff69, 0x00100000504}, // Cancel {0x0000ff6a, 0x00100000508}, // Help {0x0000ff7e, 0x0010000070b}, // Mode_switch {0x0000ff7f, 0x0010000010a}, // Num_Lock {0x0000ff80, 0x00000000020}, // KP_Space {0x0000ff89, 0x00100000009}, // KP_Tab {0x0000ff8d, 0x0020000020d}, // KP_Enter {0x0000ff91, 0x00100000801}, // KP_F1 {0x0000ff92, 0x00100000802}, // KP_F2 {0x0000ff93, 0x00100000803}, // KP_F3 {0x0000ff94, 0x00100000804}, // KP_F4 {0x0000ff95, 0x00200000237}, // KP_Home {0x0000ff96, 0x00200000234}, // KP_Left {0x0000ff97, 0x00200000238}, // KP_Up {0x0000ff98, 0x00200000236}, // KP_Right {0x0000ff99, 0x00200000232}, // KP_Down {0x0000ff9a, 0x00200000239}, // KP_Page_Up {0x0000ff9b, 0x00200000233}, // KP_Page_Down {0x0000ff9c, 0x00200000231}, // KP_End {0x0000ff9e, 0x00200000230}, // KP_Insert {0x0000ff9f, 0x0020000022e}, // KP_Delete {0x0000ffaa, 0x0020000022a}, // KP_Multiply {0x0000ffab, 0x0020000022b}, // KP_Add {0x0000ffad, 0x0020000022d}, // KP_Subtract {0x0000ffae, 0x0000000002e}, // KP_Decimal {0x0000ffaf, 0x0020000022f}, // KP_Divide {0x0000ffb0, 0x00200000230}, // KP_0 {0x0000ffb1, 0x00200000231}, // KP_1 {0x0000ffb2, 0x00200000232}, // KP_2 {0x0000ffb3, 0x00200000233}, // KP_3 {0x0000ffb4, 0x00200000234}, // KP_4 {0x0000ffb5, 0x00200000235}, // KP_5 {0x0000ffb6, 0x00200000236}, // KP_6 {0x0000ffb7, 0x00200000237}, // KP_7 {0x0000ffb8, 0x00200000238}, // KP_8 {0x0000ffb9, 0x00200000239}, // KP_9 {0x0000ffbd, 0x0020000023d}, // KP_Equal {0x0000ffbe, 0x00100000801}, // F1 {0x0000ffbf, 0x00100000802}, // F2 {0x0000ffc0, 0x00100000803}, // F3 {0x0000ffc1, 0x00100000804}, // F4 {0x0000ffc2, 0x00100000805}, // F5 {0x0000ffc3, 0x00100000806}, // F6 {0x0000ffc4, 0x00100000807}, // F7 {0x0000ffc5, 0x00100000808}, // F8 {0x0000ffc6, 0x00100000809}, // F9 {0x0000ffc7, 0x0010000080a}, // F10 {0x0000ffc8, 0x0010000080b}, // F11 {0x0000ffc9, 0x0010000080c}, // F12 {0x0000ffca, 0x0010000080d}, // F13 {0x0000ffcb, 0x0010000080e}, // F14 {0x0000ffcc, 0x0010000080f}, // F15 {0x0000ffcd, 0x00100000810}, // F16 {0x0000ffce, 0x00100000811}, // F17 {0x0000ffcf, 0x00100000812}, // F18 {0x0000ffd0, 0x00100000813}, // F19 {0x0000ffd1, 0x00100000814}, // F20 {0x0000ffd2, 0x00100000815}, // F21 {0x0000ffd3, 0x00100000816}, // F22 {0x0000ffd4, 0x00100000817}, // F23 {0x0000ffd5, 0x00100000818}, // F24 {0x0000ffe1, 0x00200000102}, // Shift_L {0x0000ffe2, 0x00200000103}, // Shift_R {0x0000ffe3, 0x00200000100}, // Control_L {0x0000ffe4, 0x00200000101}, // Control_R {0x0000ffe5, 0x00100000104}, // Caps_Lock {0x0000ffe7, 0x00200000106}, // Meta_L {0x0000ffe8, 0x00200000107}, // Meta_R {0x0000ffe9, 0x00200000104}, // Alt_L {0x0000ffea, 0x00200000105}, // Alt_R {0x0000ffeb, 0x0010000010e}, // Super_L {0x0000ffec, 0x0010000010e}, // Super_R {0x0000ffed, 0x00100000108}, // Hyper_L {0x0000ffee, 0x00100000108}, // Hyper_R {0x0000ffff, 0x0010000007f}, // Delete {0x1008ff02, 0x00100000602}, // MonBrightnessUp {0x1008ff03, 0x00100000601}, // MonBrightnessDown {0x1008ff10, 0x0010000060a}, // Standby {0x1008ff11, 0x00100000a0f}, // AudioLowerVolume {0x1008ff12, 0x00100000a11}, // AudioMute {0x1008ff13, 0x00100000a10}, // AudioRaiseVolume {0x1008ff14, 0x00100000d2f}, // AudioPlay {0x1008ff15, 0x00100000a07}, // AudioStop {0x1008ff16, 0x00100000a09}, // AudioPrev {0x1008ff17, 0x00100000a08}, // AudioNext {0x1008ff18, 0x00100000c04}, // HomePage {0x1008ff19, 0x00100000b03}, // Mail {0x1008ff1b, 0x00100000c06}, // Search {0x1008ff1c, 0x00100000d30}, // AudioRecord {0x1008ff20, 0x00100000b02}, // Calendar {0x1008ff26, 0x00100000c01}, // Back {0x1008ff27, 0x00100000c03}, // Forward {0x1008ff28, 0x00100000c07}, // Stop {0x1008ff29, 0x00100000c05}, // Refresh {0x1008ff2a, 0x00100000607}, // PowerOff {0x1008ff2b, 0x0010000060b}, // WakeUp {0x1008ff2c, 0x00100000604}, // Eject {0x1008ff2d, 0x00100000b07}, // ScreenSaver {0x1008ff2f, 0x00200000002}, // Sleep {0x1008ff30, 0x00100000c02}, // Favorites {0x1008ff31, 0x00100000d2e}, // AudioPause {0x1008ff3e, 0x00100000d31}, // AudioRewind {0x1008ff56, 0x00100000a01}, // Close {0x1008ff57, 0x00100000402}, // Copy {0x1008ff58, 0x00100000404}, // Cut {0x1008ff61, 0x00100000605}, // LogOff {0x1008ff68, 0x00100000a0a}, // New {0x1008ff6b, 0x00100000a0b}, // Open {0x1008ff6d, 0x00100000408}, // Paste {0x1008ff6e, 0x00100000b0d}, // Phone {0x1008ff72, 0x00100000a03}, // Reply {0x1008ff77, 0x00100000a0d}, // Save {0x1008ff7b, 0x00100000a04}, // Send {0x1008ff7c, 0x00100000a0e}, // Spell {0x1008ff8b, 0x0010000050d}, // ZoomIn {0x1008ff8c, 0x0010000050e}, // ZoomOut {0x1008ff90, 0x00100000a02}, // MailForward {0x1008ff97, 0x00100000d2c}, // AudioForward {0x1008ffa7, 0x00200000000}, // Suspend }; void initialize_modifier_bit_to_checked_keys(GHashTable* table) { FlKeyEmbedderCheckedKey* data; data = g_new(FlKeyEmbedderCheckedKey, 1); g_hash_table_insert(table, GUINT_TO_POINTER(GDK_SHIFT_MASK), data); data->is_caps_lock = false; data->primary_physical_key = 0x0000700e1; // shiftLeft data->primary_logical_key = 0x00200000102; // shiftLeft data->secondary_logical_key = 0x00200000103; // shiftRight data = g_new(FlKeyEmbedderCheckedKey, 1); g_hash_table_insert(table, GUINT_TO_POINTER(GDK_CONTROL_MASK), data); data->is_caps_lock = false; data->primary_physical_key = 0x0000700e0; // controlLeft data->primary_logical_key = 0x00200000100; // controlLeft data->secondary_logical_key = 0x00200000101; // controlRight data = g_new(FlKeyEmbedderCheckedKey, 1); g_hash_table_insert(table, GUINT_TO_POINTER(GDK_MOD1_MASK), data); data->is_caps_lock = false; data->primary_physical_key = 0x0000700e2; // altLeft data->primary_logical_key = 0x00200000104; // altLeft data->secondary_logical_key = 0x00200000105; // altRight data = g_new(FlKeyEmbedderCheckedKey, 1); g_hash_table_insert(table, GUINT_TO_POINTER(GDK_META_MASK), data); data->is_caps_lock = false; data->primary_physical_key = 0x0000700e3; // metaLeft data->primary_logical_key = 0x00200000106; // metaLeft data->secondary_logical_key = 0x00200000107; // metaRight } void initialize_lock_bit_to_checked_keys(GHashTable* table) { FlKeyEmbedderCheckedKey* data; data = g_new(FlKeyEmbedderCheckedKey, 1); g_hash_table_insert(table, GUINT_TO_POINTER(GDK_LOCK_MASK), data); data->is_caps_lock = true; data->primary_physical_key = 0x000070039; // capsLock data->primary_logical_key = 0x00100000104; // capsLock data = g_new(FlKeyEmbedderCheckedKey, 1); g_hash_table_insert(table, GUINT_TO_POINTER(GDK_MOD2_MASK), data); data->is_caps_lock = false; data->primary_physical_key = 0x000070053; // numLock data->primary_logical_key = 0x0010000010a; // numLock } const std::vector<LayoutGoal> layout_goals = { LayoutGoal{0x41, 0x20, false}, // Space LayoutGoal{0x30, 0x22, false}, // Quote LayoutGoal{0x3b, 0x2c, false}, // Comma LayoutGoal{0x14, 0x2d, false}, // Minus LayoutGoal{0x3c, 0x2e, false}, // Period LayoutGoal{0x3d, 0x2f, false}, // Slash LayoutGoal{0x13, 0x30, true}, // Digit0 LayoutGoal{0x0a, 0x31, true}, // Digit1 LayoutGoal{0x0b, 0x32, true}, // Digit2 LayoutGoal{0x0c, 0x33, true}, // Digit3 LayoutGoal{0x0d, 0x34, true}, // Digit4 LayoutGoal{0x0e, 0x35, true}, // Digit5 LayoutGoal{0x0f, 0x36, true}, // Digit6 LayoutGoal{0x10, 0x37, true}, // Digit7 LayoutGoal{0x11, 0x38, true}, // Digit8 LayoutGoal{0x12, 0x39, true}, // Digit9 LayoutGoal{0x2f, 0x3b, false}, // Semicolon LayoutGoal{0x15, 0x3d, false}, // Equal LayoutGoal{0x22, 0x5b, false}, // BracketLeft LayoutGoal{0x33, 0x5c, false}, // Backslash LayoutGoal{0x23, 0x5d, false}, // BracketRight LayoutGoal{0x31, 0x60, false}, // Backquote LayoutGoal{0x26, 0x61, true}, // KeyA LayoutGoal{0x38, 0x62, true}, // KeyB LayoutGoal{0x36, 0x63, true}, // KeyC LayoutGoal{0x28, 0x64, true}, // KeyD LayoutGoal{0x1a, 0x65, true}, // KeyE LayoutGoal{0x29, 0x66, true}, // KeyF LayoutGoal{0x2a, 0x67, true}, // KeyG LayoutGoal{0x2b, 0x68, true}, // KeyH LayoutGoal{0x1f, 0x69, true}, // KeyI LayoutGoal{0x2c, 0x6a, true}, // KeyJ LayoutGoal{0x2d, 0x6b, true}, // KeyK LayoutGoal{0x2e, 0x6c, true}, // KeyL LayoutGoal{0x3a, 0x6d, true}, // KeyM LayoutGoal{0x39, 0x6e, true}, // KeyN LayoutGoal{0x20, 0x6f, true}, // KeyO LayoutGoal{0x21, 0x70, true}, // KeyP LayoutGoal{0x18, 0x71, true}, // KeyQ LayoutGoal{0x1b, 0x72, true}, // KeyR LayoutGoal{0x27, 0x73, true}, // KeyS LayoutGoal{0x1c, 0x74, true}, // KeyT LayoutGoal{0x1e, 0x75, true}, // KeyU LayoutGoal{0x37, 0x76, true}, // KeyV LayoutGoal{0x19, 0x77, true}, // KeyW LayoutGoal{0x35, 0x78, true}, // KeyX LayoutGoal{0x1d, 0x79, true}, // KeyY LayoutGoal{0x34, 0x7a, true}, // KeyZ LayoutGoal{0x5e, 0x200000020, false}, // IntlBackslash }; const uint64_t kValueMask = 0x000ffffffff; const uint64_t kUnicodePlane = 0x00000000000; const uint64_t kGtkPlane = 0x01500000000;
engine/shell/platform/linux/key_mapping.g.cc/0
{ "file_path": "engine/shell/platform/linux/key_mapping.g.cc", "repo_id": "engine", "token_count": 11269 }
423
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PIXEL_BUFFER_TEXTURE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PIXEL_BUFFER_TEXTURE_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <gmodule.h> #include "fl_texture.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_DERIVABLE_TYPE(FlPixelBufferTexture, fl_pixel_buffer_texture, FL, PIXEL_BUFFER_TEXTURE, GObject) /** * FlPixelBufferTexture: * * #FlPixelBufferTexture represents an OpenGL texture generated from a pixel * buffer. * * The following example shows how to implement an #FlPixelBufferTexture. * ![<!-- language="C" --> * struct _MyTexture { * FlPixelBufferTexture parent_instance; * * uint8_t *buffer; // your pixel buffer. * } * * G_DEFINE_TYPE(MyTexture, * my_texture, * fl_pixel_buffer_texture_get_type ()) * * static gboolean * my_texture_copy_pixels (FlPixelBufferTexture* texture, * const uint8_t** out_buffer, * uint32_t* width, * uint32_t* height, * GError** error) { * // This method is called on Render Thread. Be careful with your * // cross-thread operation. * * // @width and @height are initially stored the canvas size in Flutter. * * // You must prepare your pixel buffer in RGBA format. * // So you may do some format conversion first if your original pixel * // buffer is not in RGBA format. * manage_your_pixel_buffer_here (); * * if (your_operations_are_successfully_finished) { * // Directly return pointer to your pixel buffer here. * // Flutter takes content of your pixel buffer after this function * // is finished. So you must make the buffer live long enough until * // next tick of Render Thread. * // If it is hard to manage lifetime of your pixel buffer, you should * // take look into #FlTextureGL. * * *out_buffer = buffer; * *width = real_width_of_buffer; * *height = real_height_of_buffer; * return TRUE; * } else { * // set @error to report failure. * return FALSE; * } * } * * static void my_texture_class_init(MyTextureClass* klass) { * FL_PIXEL_BUFFER_TEXTURE_CLASS(klass)->copy_pixels = * my_texture_copy_pixels; * } * * static void my_texture_init(MyTexture* self) {} * ]| */ struct _FlPixelBufferTextureClass { GObjectClass parent_class; /** * FlPixelBufferTexture::copy_pixels: * @texture: an #FlPixelBufferTexture. * @buffer: (out): pixel data. * @width: (inout): width of the texture in pixels. * @height: (inout): height of the texture in pixels. * @error: (allow-none): #GError location to store the error occurring, or * %NULL to ignore. * * Retrieve pixel buffer in RGBA format. * * As this method is usually invoked from the render thread, you must * take care of proper synchronization. It also needs to be ensured that * the returned buffer is not released prior to unregistering this texture. * * Returns: %TRUE on success. */ gboolean (*copy_pixels)(FlPixelBufferTexture* texture, const uint8_t** buffer, uint32_t* width, uint32_t* height, GError** error); }; G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_PIXEL_BUFFER_TEXTURE_H_
engine/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h", "repo_id": "engine", "token_count": 1611 }
424
# gsettings-desktop-schemas This directory contains a few variants of [gsettings-desktop-schemas](https://packages.ubuntu.com/search?keywords=gsettings-desktop-schemas) with different schemas for testing purposes. - [`ubuntu-20.04.compiled`](https://packages.ubuntu.com/focal/gsettings-desktop-schemas) ### Add or update schemas ```bash # download gsettings-desktop-schemas package wget http://archive.ubuntu.com/ubuntu/pool/main/g/gsettings-desktop-schemas/gsettings-desktop-schemas_<version>.deb # extract schema sources (/usr/share/glib-2.0/schemas/*.gschema.xml & .override) ar x gsettings-desktop-schemas_<version>.deb tar xf data.tar.zst # compile schemas (/usr/share/glib-2.0/schemas/gschemas.compiled) glib-compile-schemas --targetdir path/to/testing/gschemas usr/share/glib-2.0/schemas/ ```
engine/shell/platform/linux/testing/gschemas/README.md/0
{ "file_path": "engine/shell/platform/linux/testing/gschemas/README.md", "repo_id": "engine", "token_count": 293 }
425
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/testing/mock_signal_handler.h" namespace flutter { namespace testing { SignalHandler::SignalHandler(gpointer instance, const gchar* name, GCallback callback) : instance_(instance) { id_ = g_signal_connect_data(instance, name, callback, this, nullptr, G_CONNECT_SWAPPED); g_object_add_weak_pointer(G_OBJECT(instance), &instance_); } SignalHandler::~SignalHandler() { if (instance_) { g_signal_handler_disconnect(instance_, id_); g_object_remove_weak_pointer(G_OBJECT(instance_), &instance_); } } } // namespace testing } // namespace flutter
engine/shell/platform/linux/testing/mock_signal_handler.cc/0
{ "file_path": "engine/shell/platform/linux/testing/mock_signal_handler.cc", "repo_id": "engine", "token_count": 345 }
426
// Copyright 2013 The Flutter 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 <string> #include "flutter/shell/platform/windows/client_wrapper/include/flutter/dart_project.h" #include "gtest/gtest.h" namespace flutter { class DartProjectTest : public ::testing::Test { protected: // Wrapper for accessing private icu_data_path. std::wstring GetProjectIcuDataPath(const DartProject& project) { return project.icu_data_path(); } // Wrapper for accessing private assets_path. std::wstring GetProjectAssetsPath(const DartProject& project) { return project.assets_path(); } // Wrapper for accessing private aot_library_path_. std::wstring GetProjectAotLibraryPath(const DartProject& project) { return project.aot_library_path(); } }; TEST_F(DartProjectTest, StandardProjectFormat) { DartProject project(L"test"); EXPECT_EQ(GetProjectIcuDataPath(project), L"test\\icudtl.dat"); EXPECT_EQ(GetProjectAssetsPath(project), L"test\\flutter_assets"); EXPECT_EQ(GetProjectAotLibraryPath(project), L"test\\app.so"); } TEST_F(DartProjectTest, ProjectWithCustomPaths) { DartProject project(L"data\\assets", L"icu\\icudtl.dat", L"lib\\file.so"); EXPECT_EQ(GetProjectIcuDataPath(project), L"icu\\icudtl.dat"); EXPECT_EQ(GetProjectAssetsPath(project), L"data\\assets"); EXPECT_EQ(GetProjectAotLibraryPath(project), L"lib\\file.so"); } TEST_F(DartProjectTest, DartEntrypointArguments) { DartProject project(L"test"); std::vector<std::string> test_arguments = {"arg1", "arg2", "arg3"}; project.set_dart_entrypoint_arguments(test_arguments); auto returned_arguments = project.dart_entrypoint_arguments(); EXPECT_EQ(returned_arguments.size(), 3U); EXPECT_EQ(returned_arguments[0], "arg1"); EXPECT_EQ(returned_arguments[1], "arg2"); EXPECT_EQ(returned_arguments[2], "arg3"); } } // namespace flutter
engine/shell/platform/windows/client_wrapper/dart_project_unittests.cc/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/dart_project_unittests.cc", "repo_id": "engine", "token_count": 688 }
427
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_OPENGL_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_OPENGL_H_ #include <memory> #include "flutter/impeller/renderer/backend/gles/proc_table_gles.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/compositor.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" namespace flutter { // Enables the Flutter engine to render content on Windows using OpenGL. class CompositorOpenGL : public Compositor { public: CompositorOpenGL(FlutterWindowsEngine* engine, impeller::ProcTableGLES::Resolver resolver); /// |Compositor| bool CreateBackingStore(const FlutterBackingStoreConfig& config, FlutterBackingStore* result) override; /// |Compositor| bool CollectBackingStore(const FlutterBackingStore* store) override; /// |Compositor| bool Present(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) override; private: // The Flutter engine that manages the views to render. FlutterWindowsEngine* engine_; private: // The compositor initializes itself lazily once |CreateBackingStore| is // called. True if initialization completed successfully. bool is_initialized_ = false; // Function used to resolve GLES functions. impeller::ProcTableGLES::Resolver resolver_ = nullptr; // Table of resolved GLES functions. Null until the compositor is initialized. std::unique_ptr<impeller::ProcTableGLES> gl_ = nullptr; // The OpenGL texture target format for backing stores. Invalid value until // the compositor is initialized. uint32_t format_ = 0; // Initialize the compositor. This must run on the raster thread. bool Initialize(); // Clear the view's surface and removes any previously presented layers. bool Clear(FlutterWindowsView* view); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_OPENGL_H_
engine/shell/platform/windows/compositor_opengl.h/0
{ "file_path": "engine/shell/platform/windows/compositor_opengl.h", "repo_id": "engine", "token_count": 705 }
428
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/egl/egl.h" #include <EGL/egl.h> #include "flutter/fml/logging.h" namespace flutter { namespace egl { namespace { const char* EGLErrorToString(EGLint error) { switch (error) { case EGL_SUCCESS: return "Success"; case EGL_NOT_INITIALIZED: return "Not Initialized"; case EGL_BAD_ACCESS: return "Bad Access"; case EGL_BAD_ALLOC: return "Bad Alloc"; case EGL_BAD_ATTRIBUTE: return "Bad Attribute"; case EGL_BAD_CONTEXT: return "Bad Context"; case EGL_BAD_CONFIG: return "Bad Config"; case EGL_BAD_CURRENT_SURFACE: return "Bad Current Surface"; case EGL_BAD_DISPLAY: return "Bad Display"; case EGL_BAD_SURFACE: return "Bad Surface"; case EGL_BAD_MATCH: return "Bad Match"; case EGL_BAD_PARAMETER: return "Bad Parameter"; case EGL_BAD_NATIVE_PIXMAP: return "Bad Native Pixmap"; case EGL_BAD_NATIVE_WINDOW: return "Bad Native Window"; case EGL_CONTEXT_LOST: return "Context Lost"; } FML_UNREACHABLE(); return "Unknown"; } } // namespace void LogEGLError(std::string_view message) { const EGLint error = ::eglGetError(); return FML_LOG(ERROR) << "EGL Error: " << EGLErrorToString(error) << " (" << error << ") " << message; } void LogEGLError(std::string_view file, int line) { std::stringstream stream; stream << "in " << file << ":" << line; LogEGLError(stream.str()); } } // namespace egl } // namespace flutter
engine/shell/platform/windows/egl/egl.cc/0
{ "file_path": "engine/shell/platform/windows/egl/egl.cc", "repo_id": "engine", "token_count": 725 }
429
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_PIXELBUFFER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_PIXELBUFFER_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/public/flutter_texture_registrar.h" #include "flutter/shell/platform/windows/egl/proc_table.h" #include "flutter/shell/platform/windows/external_texture.h" namespace flutter { // An abstraction of an pixel-buffer based texture. class ExternalTexturePixelBuffer : public ExternalTexture { public: ExternalTexturePixelBuffer( const FlutterDesktopPixelBufferTextureCallback texture_callback, void* user_data, std::shared_ptr<egl::ProcTable> gl); virtual ~ExternalTexturePixelBuffer(); // |ExternalTexture| bool PopulateTexture(size_t width, size_t height, FlutterOpenGLTexture* opengl_texture) override; private: // Attempts to copy the pixel buffer returned by |texture_callback_| to // OpenGL. // The |width| and |height| will be set to the actual bounds of the copied // pixel buffer. // Returns true on success or false if the pixel buffer returned // by |texture_callback_| was invalid. bool CopyPixelBuffer(size_t& width, size_t& height); const FlutterDesktopPixelBufferTextureCallback texture_callback_ = nullptr; void* const user_data_ = nullptr; std::shared_ptr<egl::ProcTable> gl_; GLuint gl_texture_ = 0; FML_DISALLOW_COPY_AND_ASSIGN(ExternalTexturePixelBuffer); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_PIXELBUFFER_H_
engine/shell/platform/windows/external_texture_pixelbuffer.h/0
{ "file_path": "engine/shell/platform/windows/external_texture_pixelbuffer.h", "repo_id": "engine", "token_count": 595 }
430
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_INTERNAL_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_INTERNAL_H_ #include "flutter/shell/platform/windows/public/flutter_windows.h" #if defined(__cplusplus) extern "C" { #endif // Declare functions that are currently in-progress and shall be exposed to the // public facing API upon completion. typedef int64_t PlatformViewId; typedef struct { size_t struct_size; HWND parent_window; const char* platform_view_type; // user_data may hold any necessary additional information for creating a new // platform view. For example, an instance of FlutterWindow. void* user_data; PlatformViewId platform_view_id; } FlutterPlatformViewCreationParameters; typedef HWND (*FlutterPlatformViewFactory)( const FlutterPlatformViewCreationParameters*); typedef struct { size_t struct_size; FlutterPlatformViewFactory factory; void* user_data; // Arbitrary user data supplied to the creation struct. } FlutterPlatformViewTypeEntry; FLUTTER_EXPORT void FlutterDesktopEngineRegisterPlatformViewType( FlutterDesktopEngineRef engine, const char* view_type_name, FlutterPlatformViewTypeEntry view_type); #if defined(__cplusplus) } #endif #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_INTERNAL_H_
engine/shell/platform/windows/flutter_windows_internal.h/0
{ "file_path": "engine/shell/platform/windows/flutter_windows_internal.h", "repo_id": "engine", "token_count": 464 }
431
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/windows/keyboard_key_handler.h" #include <windows.h> #include "flutter/fml/logging.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" #include "flutter/shell/platform/windows/keyboard_utils.h" namespace flutter { namespace { // The maximum number of pending events to keep before // emitting a warning on the console about unhandled events. static constexpr int kMaxPendingEvents = 1000; // The name of the channel for keyboard state queries. static constexpr char kChannelName[] = "flutter/keyboard"; static constexpr char kGetKeyboardStateMethod[] = "getKeyboardState"; } // namespace KeyboardKeyHandler::KeyboardKeyHandlerDelegate::~KeyboardKeyHandlerDelegate() = default; KeyboardKeyHandler::KeyboardKeyHandler(flutter::BinaryMessenger* messenger) : last_sequence_id_(1), channel_(std::make_unique<MethodChannel<EncodableValue>>( messenger, kChannelName, &StandardMethodCodec::GetInstance())) {} KeyboardKeyHandler::~KeyboardKeyHandler() = default; void KeyboardKeyHandler::InitKeyboardChannel() { channel_->SetMethodCallHandler( [this](const MethodCall<EncodableValue>& call, std::unique_ptr<MethodResult<EncodableValue>> result) { HandleMethodCall(call, std::move(result)); }); } void KeyboardKeyHandler::HandleMethodCall( const MethodCall<EncodableValue>& method_call, std::unique_ptr<MethodResult<EncodableValue>> result) { const std::string& method = method_call.method_name(); if (method.compare(kGetKeyboardStateMethod) == 0) { EncodableMap value; const auto& pressed_state = GetPressedState(); for (const auto& pressed_key : pressed_state) { EncodableValue physical_value(static_cast<long long>(pressed_key.first)); EncodableValue logical_value(static_cast<long long>(pressed_key.second)); value[physical_value] = logical_value; } result->Success(EncodableValue(value)); } else { result->NotImplemented(); } } void KeyboardKeyHandler::AddDelegate( std::unique_ptr<KeyboardKeyHandlerDelegate> delegate) { delegates_.push_back(std::move(delegate)); } void KeyboardKeyHandler::SyncModifiersIfNeeded(int modifiers_state) { // Only call SyncModifierIfNeeded on the key embedder handler. auto& key_embedder_handler = delegates_.front(); key_embedder_handler->SyncModifiersIfNeeded(modifiers_state); } std::map<uint64_t, uint64_t> KeyboardKeyHandler::GetPressedState() { // The embedder responder is the first element in delegates_. auto& key_embedder_handler = delegates_.front(); return key_embedder_handler->GetPressedState(); } void KeyboardKeyHandler::KeyboardHook(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) { std::unique_ptr<PendingEvent> incoming = std::make_unique<PendingEvent>(); uint64_t sequence_id = ++last_sequence_id_; incoming->sequence_id = sequence_id; incoming->unreplied = delegates_.size(); incoming->any_handled = false; incoming->callback = std::move(callback); if (pending_responds_.size() > kMaxPendingEvents) { FML_LOG(ERROR) << "There are " << pending_responds_.size() << " keyboard events that have not yet received a response from the " << "framework. Are responses being sent?"; } pending_responds_.push_back(std::move(incoming)); for (const auto& delegate : delegates_) { delegate->KeyboardHook(key, scancode, action, character, extended, was_down, [sequence_id, this](bool handled) { ResolvePendingEvent(sequence_id, handled); }); } // |ResolvePendingEvent| might trigger redispatching synchronously, // which might occur before |KeyboardHook| is returned. This won't // make events out of order though, because |KeyboardHook| will always // return true at this time, preventing this event from affecting // others. } void KeyboardKeyHandler::ResolvePendingEvent(uint64_t sequence_id, bool handled) { // Find the pending event for (auto iter = pending_responds_.begin(); iter != pending_responds_.end(); ++iter) { if ((*iter)->sequence_id == sequence_id) { PendingEvent& event = **iter; event.any_handled = event.any_handled || handled; event.unreplied -= 1; FML_DCHECK(event.unreplied >= 0) << "Pending events must have unreplied count > 0"; // If all delegates have replied, report if any of them handled the event. if (event.unreplied == 0) { std::unique_ptr<PendingEvent> event_ptr = std::move(*iter); pending_responds_.erase(iter); event.callback(event.any_handled); } // Return here; |iter| can't do ++ after erase. return; } } // The pending event should always be found. FML_LOG(FATAL) << "Could not find pending key event for sequence ID " << sequence_id; } } // namespace flutter
engine/shell/platform/windows/keyboard_key_handler.cc/0
{ "file_path": "engine/shell/platform/windows/keyboard_key_handler.cc", "repo_id": "engine", "token_count": 2070 }
432
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_PUBLIC_FLUTTER_WINDOWS_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_PUBLIC_FLUTTER_WINDOWS_H_ #include <dxgi.h> #include <stddef.h> #include <stdint.h> #include <windows.h> #include "flutter_export.h" #include "flutter_messenger.h" #include "flutter_plugin_registrar.h" #if defined(__cplusplus) extern "C" { #endif typedef void (*VoidCallback)(void* /* user data */); // Opaque reference to a Flutter view controller. struct FlutterDesktopViewController; typedef struct FlutterDesktopViewController* FlutterDesktopViewControllerRef; // Opaque reference to a Flutter window. struct FlutterDesktopView; typedef struct FlutterDesktopView* FlutterDesktopViewRef; // Opaque reference to a Flutter engine instance. struct FlutterDesktopEngine; typedef struct FlutterDesktopEngine* FlutterDesktopEngineRef; // The unique identifier for a view. typedef int64_t FlutterDesktopViewId; // Properties for configuring a Flutter engine instance. typedef struct { // The path to the flutter_assets folder for the application to be run. // This can either be an absolute path or a path relative to the directory // containing the executable. const wchar_t* assets_path; // The path to the icudtl.dat file for the version of Flutter you are using. // This can either be an absolute path or a path relative to the directory // containing the executable. const wchar_t* icu_data_path; // The path to the AOT library file for your application, if any. // This can either be an absolute path or a path relative to the directory // containing the executable. This can be nullptr for a non-AOT build, as // it will be ignored in that case. const wchar_t* aot_library_path; // The name of the top-level Dart entrypoint function. If null or the empty // string, 'main' is assumed. If a custom entrypoint is used, this parameter // must specifiy the name of a top-level function in the same Dart library as // the app's main() function. Custom entrypoint functions must be decorated // with `@pragma('vm:entry-point')` to ensure the method is not tree-shaken // by the Dart compiler. const char* dart_entrypoint; // Number of elements in the array passed in as dart_entrypoint_argv. int dart_entrypoint_argc; // Array of Dart entrypoint arguments. This is deep copied during the call // to FlutterDesktopEngineCreate. const char** dart_entrypoint_argv; } FlutterDesktopEngineProperties; // ========== View Controller ========== // Creates a view that hosts and displays the given engine instance. // // This takes ownership of |engine|, so FlutterDesktopEngineDestroy should no // longer be called on it, as it will be called internally when the view // controller is destroyed. If creating the view controller fails, the engine // will be destroyed immediately. // // If |engine| is not already running, the view controller will start running // it automatically before displaying the window. // // The caller owns the returned reference, and is responsible for calling // FlutterDesktopViewControllerDestroy. Returns a null pointer in the event of // an error. // // The Win32 implementation accepts width, height with view hookup explicitly // performed using the caller using HWND parenting. FLUTTER_EXPORT FlutterDesktopViewControllerRef FlutterDesktopViewControllerCreate(int width, int height, FlutterDesktopEngineRef engine); // Shuts down the engine instance associated with |controller|, and cleans up // associated state. // // |controller| is no longer valid after this call. FLUTTER_EXPORT void FlutterDesktopViewControllerDestroy( FlutterDesktopViewControllerRef controller); // Returns the view controller's view ID. FLUTTER_EXPORT FlutterDesktopViewId FlutterDesktopViewControllerGetViewId( FlutterDesktopViewControllerRef view_controller); // Returns the handle for the engine running in FlutterDesktopViewControllerRef. // // Its lifetime is the same as the |controller|'s. FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopViewControllerGetEngine( FlutterDesktopViewControllerRef controller); // Returns the view managed by the given controller. FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopViewControllerGetView( FlutterDesktopViewControllerRef controller); // Requests new frame from the engine and repaints the view. FLUTTER_EXPORT void FlutterDesktopViewControllerForceRedraw( FlutterDesktopViewControllerRef controller); // Allows the Flutter engine and any interested plugins an opportunity to // handle the given message. // // If the WindowProc was handled and further handling should stop, this returns // true and |result| will be populated. |result| is not set if returning false. FLUTTER_EXPORT bool FlutterDesktopViewControllerHandleTopLevelWindowProc( FlutterDesktopViewControllerRef controller, HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result); // ========== Engine ========== // Creates a Flutter engine with the given properties. // // The caller owns the returned reference, and is responsible for calling // FlutterDesktopEngineDestroy. The lifetime of |engine_properties| is required // to extend only until the end of this call. FLUTTER_EXPORT FlutterDesktopEngineRef FlutterDesktopEngineCreate( const FlutterDesktopEngineProperties* engine_properties); // Shuts down and destroys the given engine instance. Returns true if the // shutdown was successful, or if the engine was not running. // // |engine| is no longer valid after this call. FLUTTER_EXPORT bool FlutterDesktopEngineDestroy(FlutterDesktopEngineRef engine); // Starts running the given engine instance. // // The entry_point parameter is deprecated but preserved for // backward-compatibility. If desired, a custom Dart entrypoint function can be // set in the dart_entrypoint field of the FlutterDesktopEngineProperties // struct passed to FlutterDesktopEngineCreate. // // If specified, entry_point must be the name of a top-level function from the // same Dart library that contains the app's main() function, and must be // decorated with `@pragma(vm:entry-point)` to ensure the method is not // tree-shaken by the Dart compiler. If conflicting non-null values are passed // to this function and via the FlutterDesktopEngineProperties struct, the run // will fail. // // Returns false if running the engine failed. FLUTTER_EXPORT bool FlutterDesktopEngineRun(FlutterDesktopEngineRef engine, const char* entry_point); // DEPRECATED: This is no longer necessary to call, Flutter will take care of // processing engine messages transparently through DispatchMessage. // // Processes any pending events in the Flutter engine, and returns the // number of nanoseconds until the next scheduled event (or max, if none). // // This should be called on every run of the application-level runloop, and // a wait for native events in the runloop should never be longer than the // last return value from this function. FLUTTER_EXPORT uint64_t FlutterDesktopEngineProcessMessages( FlutterDesktopEngineRef engine); FLUTTER_EXPORT void FlutterDesktopEngineReloadSystemFonts( FlutterDesktopEngineRef engine); // Returns the plugin registrar handle for the plugin with the given name. // // The name must be unique across the application. FLUTTER_EXPORT FlutterDesktopPluginRegistrarRef FlutterDesktopEngineGetPluginRegistrar(FlutterDesktopEngineRef engine, const char* plugin_name); // Returns the messenger associated with the engine. // // This does not provide an owning reference, so should *not* be balanced with a // call to |FlutterDesktopMessengerRelease|. // // Callers should use |FlutterDesktopMessengerAddRef| if the returned pointer // will potentially outlive 'engine', such as when passing it to another thread. FLUTTER_EXPORT FlutterDesktopMessengerRef FlutterDesktopEngineGetMessenger( FlutterDesktopEngineRef engine); // Returns the texture registrar associated with the engine. FLUTTER_EXPORT FlutterDesktopTextureRegistrarRef FlutterDesktopEngineGetTextureRegistrar(FlutterDesktopEngineRef engine); // Schedule a callback to be called after the next frame is drawn. // // This must be called from the platform thread. The callback is executed only // once on the platform thread. FLUTTER_EXPORT void FlutterDesktopEngineSetNextFrameCallback( FlutterDesktopEngineRef engine, VoidCallback callback, void* user_data); // ========== View ========== // Returns the backing HWND for manipulation in host application. FLUTTER_EXPORT HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef view); // Returns the DXGI adapter used for rendering or nullptr in case of error. FLUTTER_EXPORT IDXGIAdapter* FlutterDesktopViewGetGraphicsAdapter( FlutterDesktopViewRef view); // Called to pass an external window message to the engine for lifecycle // state updates. Non-Flutter windows must call this method in their WndProc // in order to be included in the logic for application lifecycle state // updates. Returns a result if the message should be consumed. FLUTTER_EXPORT bool FlutterDesktopEngineProcessExternalWindowMessage( FlutterDesktopEngineRef engine, HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result); // ========== Plugin Registrar (extensions) ========== // These are Windows-specific extensions to flutter_plugin_registrar.h // Function pointer type for top level WindowProc delegate registration. // // The user data will be whatever was passed to // FlutterDesktopRegisterTopLevelWindowProcHandler. // // Implementations should populate |result| and return true if the WindowProc // was handled and further handling should stop. |result| is ignored if the // function returns false. typedef bool (*FlutterDesktopWindowProcCallback)(HWND /* hwnd */, UINT /* uMsg */, WPARAM /*wParam*/, LPARAM /* lParam*/, void* /* user data */, LRESULT* result); // Returns the implicit view associated with this registrar's engine instance, // or null if there is no implicit view. // // See: // https://api.flutter.dev/flutter/dart-ui/PlatformDispatcher/implicitView.html // // DEPRECATED: Use |FlutterDesktopPluginRegistrarGetViewById| instead. FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetView( FlutterDesktopPluginRegistrarRef registrar); // Returns the view associated with the registrar's engine instance, or null if // the view does not exist. FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetViewById( FlutterDesktopPluginRegistrarRef registrar, FlutterDesktopViewId view_id); FLUTTER_EXPORT void FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate( FlutterDesktopPluginRegistrarRef registrar, FlutterDesktopWindowProcCallback delegate, void* user_data); FLUTTER_EXPORT void FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate( FlutterDesktopPluginRegistrarRef registrar, FlutterDesktopWindowProcCallback delegate); // ========== Freestanding Utilities ========== // Gets the DPI for a given |hwnd|, depending on the supported APIs per // windows version and DPI awareness mode. If nullptr is passed, returns the DPI // of the primary monitor. // // This uses the same logic and fallback for older Windows versions that is used // internally by Flutter to determine the DPI to use for displaying Flutter // content, so should be used by any code (e.g., in plugins) that translates // between Windows and Dart sizes/offsets. FLUTTER_EXPORT UINT FlutterDesktopGetDpiForHWND(HWND hwnd); // Gets the DPI for a given |monitor|. If the API is not available, a default // DPI of 96 is returned. // // See FlutterDesktopGetDpiForHWND for more information. FLUTTER_EXPORT UINT FlutterDesktopGetDpiForMonitor(HMONITOR monitor); // Reopens stdout and stderr and resysncs the standard library output streams. // Should be called if output is being directed somewhere in the runner process // (e.g., after an AllocConsole call). FLUTTER_EXPORT void FlutterDesktopResyncOutputStreams(); #if defined(__cplusplus) } // extern "C" #endif #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_PUBLIC_FLUTTER_WINDOWS_H_
engine/shell/platform/windows/public/flutter_windows.h/0
{ "file_path": "engine/shell/platform/windows/public/flutter_windows.h", "repo_id": "engine", "token_count": 3761 }
433
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_MANAGER_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/egl/manager.h" #include "gmock/gmock.h" namespace flutter { namespace testing { namespace egl { /// Mock for the |Manager| base class. class MockManager : public flutter::egl::Manager { public: MockManager() : Manager(false) {} MOCK_METHOD(std::unique_ptr<flutter::egl::WindowSurface>, CreateWindowSurface, (HWND, size_t, size_t), (override)); MOCK_METHOD(flutter::egl::Context*, render_context, (), (const, override)); MOCK_METHOD(flutter::egl::Context*, resource_context, (), (const, override)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockManager); }; } // namespace egl } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_MANAGER_H_
engine/shell/platform/windows/testing/egl/mock_manager.h/0
{ "file_path": "engine/shell/platform/windows/testing/egl/mock_manager.h", "repo_id": "engine", "token_count": 432 }
434
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_BINARY_MESSENGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_BINARY_MESSENGER_H_ #include <functional> #include <map> #include <string> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" namespace flutter { // A trivial BinaryMessenger implementation for use in tests. class TestBinaryMessenger : public BinaryMessenger { public: using SendHandler = std::function<void(const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply)>; // Creates a new messenge that forwards all calls to |send_handler|. explicit TestBinaryMessenger(SendHandler send_handler = nullptr) : send_handler_(std::move(send_handler)) {} virtual ~TestBinaryMessenger() = default; // Simulates a message from the engine on the given channel. // // Returns false if no handler is registered on that channel. bool SimulateEngineMessage(const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) { auto handler = registered_handlers_.find(channel); if (handler == registered_handlers_.end()) { return false; } (handler->second)(message, message_size, reply); return true; } // |flutter::BinaryMessenger| void Send(const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) const override { // If something under test sends a message, the test should be handling it. FML_DCHECK(send_handler_); send_handler_(channel, message, message_size, reply); } // |flutter::BinaryMessenger| void SetMessageHandler(const std::string& channel, BinaryMessageHandler handler) override { if (handler) { registered_handlers_[channel] = handler; } else { registered_handlers_.erase(channel); } } private: // Handler to call for SendMessage. SendHandler send_handler_; // Mapping of channel name to registered handlers. std::map<std::string, BinaryMessageHandler> registered_handlers_; FML_DISALLOW_COPY_AND_ASSIGN(TestBinaryMessenger); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_BINARY_MESSENGER_H_
engine/shell/platform/windows/testing/test_binary_messenger.h/0
{ "file_path": "engine/shell/platform/windows/testing/test_binary_messenger.h", "repo_id": "engine", "token_count": 1063 }
435
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TEXT_INPUT_PLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TEXT_INPUT_PLUGIN_H_ #include <array> #include <map> #include <memory> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h" #include "flutter/shell/platform/common/geometry.h" #include "flutter/shell/platform/common/json_method_codec.h" #include "flutter/shell/platform/common/text_editing_delta.h" #include "flutter/shell/platform/common/text_input_model.h" #include "flutter/shell/platform/windows/keyboard_handler_base.h" namespace flutter { class FlutterWindowsEngine; // Implements a text input plugin. // // Specifically handles window events within windows. class TextInputPlugin { public: TextInputPlugin(flutter::BinaryMessenger* messenger, FlutterWindowsEngine* engine); virtual ~TextInputPlugin(); // Called when the Flutter engine receives a raw keyboard message. virtual void KeyboardHook(int key, int scancode, int action, char32_t character, bool extended, bool was_down); // Called when the Flutter engine receives a keyboard character. virtual void TextHook(const std::u16string& text); // Called on an IME compose begin event. // // Triggered when the user begins editing composing text using a multi-step // input method such as in CJK text input. virtual void ComposeBeginHook(); // Called on an IME compose commit event. // // Triggered when the user triggers a commit of the current composing text // while using a multi-step input method such as in CJK text input. Composing // continues with the next keypress. virtual void ComposeCommitHook(); // Called on an IME compose end event. // // Triggered when the composing ends, for example when the user presses // ESC or when the user triggers a commit of the composing text while using a // multi-step input method such as in CJK text input. virtual void ComposeEndHook(); // Called on an IME composing region change event. // // Triggered when the user edits the composing text while using a multi-step // input method such as in CJK text input. virtual void ComposeChangeHook(const std::u16string& text, int cursor_pos); private: // Sends the current state of the given model to the Flutter engine. void SendStateUpdate(const TextInputModel& model); // Sends the current state of the given model to the Flutter engine. void SendStateUpdateWithDelta(const TextInputModel& model, const TextEditingDelta*); // Sends an action triggered by the Enter key to the Flutter engine. void EnterPressed(TextInputModel* model); // Called when a method is called on |channel_|; void HandleMethodCall( const flutter::MethodCall<rapidjson::Document>& method_call, std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result); // Returns the composing rect, or if IME composing mode is not active, the // cursor rect in the PipelineOwner root coordinate system. Rect GetCursorRect() const; // The MethodChannel used for communication with the Flutter engine. std::unique_ptr<flutter::MethodChannel<rapidjson::Document>> channel_; // The associated |FlutterWindowsEngine|. FlutterWindowsEngine* engine_; // The active client id. int client_id_; // The active model. nullptr if not set. std::unique_ptr<TextInputModel> active_model_; // Whether to enable that the engine sends text input updates to the framework // as TextEditingDeltas or as one TextEditingValue. // For more information on the delta model, see: // https://master-api.flutter.dev/flutter/services/TextInputConfiguration/enableDeltaModel.html bool enable_delta_model = false; // Keyboard type of the client. See available options: // https://api.flutter.dev/flutter/services/TextInputType-class.html std::string input_type_; // An action requested by the user on the input client. See available options: // https://api.flutter.dev/flutter/services/TextInputAction-class.html std::string input_action_; // The smallest rect, in local coordinates, of the text in the composing // range, or of the caret in the case where there is no current composing // range. This value is updated via `TextInput.setMarkedTextRect` messages // over the text input channel. Rect composing_rect_; // A 4x4 matrix that maps from `EditableText` local coordinates to the // coordinate system of `PipelineOwner.rootNode`. std::array<std::array<double, 4>, 4> editabletext_transform_ = { 0.0, 0.0, 0.0, 0.0, // 0.0, 0.0, 0.0, 0.0, // 0.0, 0.0, 0.0, 0.0, // 0.0, 0.0, 0.0, 0.0}; FML_DISALLOW_COPY_AND_ASSIGN(TextInputPlugin); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TEXT_INPUT_PLUGIN_H_
engine/shell/platform/windows/text_input_plugin.h/0
{ "file_path": "engine/shell/platform/windows/text_input_plugin.h", "repo_id": "engine", "token_count": 1720 }
436
// Copyright 2013 The Flutter 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/profiling/sampling_profiler.h" #include <utility> namespace flutter { SamplingProfiler::SamplingProfiler( const char* thread_label, fml::RefPtr<fml::TaskRunner> profiler_task_runner, Sampler sampler, int num_samples_per_sec) : thread_label_(thread_label), profiler_task_runner_(std::move(profiler_task_runner)), sampler_(std::move(sampler)), num_samples_per_sec_(num_samples_per_sec) {} SamplingProfiler::~SamplingProfiler() { if (is_running_) { Stop(); } } void SamplingProfiler::Start() { if (!profiler_task_runner_) { return; } FML_CHECK(num_samples_per_sec_ > 0) << "number of samples must be a positive integer, got: " << num_samples_per_sec_; double delay_between_samples = 1.0 / num_samples_per_sec_; auto task_delay = fml::TimeDelta::FromSecondsF(delay_between_samples); UpdateDartVMServiceThreadName(); is_running_ = true; SampleRepeatedly(task_delay); } void SamplingProfiler::Stop() { FML_DCHECK(is_running_); auto latch = std::make_unique<fml::AutoResetWaitableEvent>(); shutdown_latch_.store(latch.get()); latch->Wait(); shutdown_latch_.store(nullptr); is_running_ = false; } void SamplingProfiler::SampleRepeatedly(fml::TimeDelta task_delay) const { profiler_task_runner_->PostDelayedTask( [profiler = this, task_delay = task_delay, sampler = sampler_, &shutdown_latch = shutdown_latch_]() { // TODO(kaushikiska): consider buffering these every n seconds to // avoid spamming the trace buffer. const ProfileSample usage = sampler(); if (usage.cpu_usage) { const auto& cpu_usage = usage.cpu_usage; std::string total_cpu_usage = std::to_string(cpu_usage->total_cpu_usage); std::string num_threads = std::to_string(cpu_usage->num_threads); TRACE_EVENT_INSTANT2("flutter::profiling", "CpuUsage", "total_cpu_usage", total_cpu_usage.c_str(), "num_threads", num_threads.c_str()); } if (usage.memory_usage) { std::string dirty_memory_usage = std::to_string(usage.memory_usage->dirty_memory_usage); std::string owned_shared_memory_usage = std::to_string(usage.memory_usage->owned_shared_memory_usage); TRACE_EVENT_INSTANT2("flutter::profiling", "MemoryUsage", "dirty_memory_usage", dirty_memory_usage.c_str(), "owned_shared_memory_usage", owned_shared_memory_usage.c_str()); } if (usage.gpu_usage) { std::string gpu_usage = std::to_string(usage.gpu_usage->percent_usage); TRACE_EVENT_INSTANT1("flutter::profiling", "GpuUsage", "gpu_usage", gpu_usage.c_str()); } if (shutdown_latch.load()) { shutdown_latch.load()->Signal(); } else { profiler->SampleRepeatedly(task_delay); } }, task_delay); } void SamplingProfiler::UpdateDartVMServiceThreadName() const { FML_CHECK(profiler_task_runner_); profiler_task_runner_->PostTask( [label = thread_label_ + std::string{".profiler"}]() { Dart_SetThreadName(label.c_str()); }); } } // namespace flutter
engine/shell/profiling/sampling_profiler.cc/0
{ "file_path": "engine/shell/profiling/sampling_profiler.cc", "repo_id": "engine", "token_count": 1570 }
437
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. _skia_root = "//flutter/third_party/skia" import("$_skia_root/gn/shared_sources.gni") import("$_skia_root/gn/skia.gni") import("$_skia_root/gn/toolchain/wasm.gni") import("flutter_defines.gni") if (is_fuchsia) { import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") } # Skia public API, generally provided by :skia. config("skia_public") { include_dirs = [ "$_skia_root" ] defines = [ "SK_CODEC_DECODES_BMP", "SK_CODEC_DECODES_WBMP", ] defines += flutter_defines cflags_objcc = [] if (is_fuchsia || is_linux) { defines += [ "SK_R32_SHIFT=16" ] } # TODO(zra): Try using this. if (skia_enable_optimize_size) { defines += [ "SK_ENABLE_OPTIMIZE_SIZE", "SK_FORCE_AAA", ] } if (skia_enable_precompile) { defines += [ "SK_ENABLE_PRECOMPILE" ] } if (is_wasm) { defines += wasm_defines } if (skia_gl_standard == "gles") { defines += [ "SK_ASSUME_GL_ES=1" ] } else if (skia_gl_standard == "gl") { defines += [ "SK_ASSUME_GL=1" ] } else if (skia_gl_standard == "webgl") { defines += [ "SK_ASSUME_WEBGL=1", "SK_USE_WEBGL", ] } if (skia_enable_ganesh) { defines += [ "SK_GANESH" ] } # TODO(zra): Try turning this off. if (skia_use_perfetto) { defines += [ "SK_USE_PERFETTO" ] } # Some older versions of the Clang toolchain change the visibility of # symbols decorated with API_AVAILABLE macro to be visible. Users of such # toolchains suppress the use of this macro till toolchain updates are made. if (is_mac || is_ios) { cflags_objcc += [ "-Wno-unguarded-availability" ] } } # Skia internal APIs, used by Skia itself and a few test tools. config("skia_private") { visibility = [ "./*" ] defines = [ "SK_GAMMA_APPLY_TO_A8" ] if (skia_use_fixed_gamma_text) { defines += [ "SK_GAMMA_EXPONENT=1.4", "SK_GAMMA_CONTRAST=0.0", ] } libs = [] lib_dirs = [] if (skia_use_vma) { defines += [ "SK_USE_VMA" ] } } # Any code that's linked into Skia-the-library should use this config # via += skia_library_configs. config("skia_library") { visibility = [ "./*" ] defines = [ "SKIA_IMPLEMENTATION=1" ] } skia_library_configs = [ ":skia_public", ":skia_private", ":skia_library", ] # Use for CPU-specific Skia code that needs particular compiler flags. template("opts") { if (invoker.enabled) { skia_source_set(target_name) { visibility = [ ":*" ] check_includes = false configs = skia_library_configs forward_variables_from(invoker, "*") if (defined(invoker.configs)) { configs += invoker.configs } } } else { # If not enabled, a phony empty target that swallows all otherwise unused # variables. skia_source_set(target_name) { visibility = [ ":*" ] check_includes = false forward_variables_from(invoker, "*", [ "sources", "cflags", ]) } } } is_x86 = current_cpu == "x64" || current_cpu == "x86" opts("hsw") { enabled = is_x86 sources = skia_opts.hsw_sources if (is_win) { cflags = [ "/arch:AVX2" ] } else { cflags = [ "-march=haswell" ] } } # Any feature of Skia that requires third-party code should be optional and use # this template. template("optional") { if (invoker.enabled) { config(target_name + "_public") { if (defined(invoker.public_defines)) { defines = invoker.public_defines } if (defined(invoker.public_configs)) { configs = invoker.public_configs } if (defined(invoker.public_include_dirs)) { include_dirs = invoker.public_include_dirs } } skia_source_set(target_name) { visibility = [ ":*" ] # Opted out of check_includes, due to (logically) being part of skia. check_includes = false configs = skia_library_configs # "*" clobbers the current scope; append to existing configs forward_variables_from(invoker, "*", [ "configs", "public_defines", "sources_for_tests", "sources_when_disabled", ]) if (defined(invoker.configs)) { configs += invoker.configs } all_dependent_configs = [ ":" + target_name + "_public" ] } } else { skia_source_set(target_name) { visibility = [ ":*" ] configs = skia_library_configs # "*" clobbers the current scope; append to existing configs forward_variables_from(invoker, "*", [ "configs", "public", "public_defines", "public_deps", "deps", "libs", "frameworks", "sources", "sources_for_tests", "sources_when_disabled", ]) if (defined(invoker.configs)) { configs += invoker.configs } if (defined(invoker.sources_when_disabled)) { sources = invoker.sources_when_disabled } } if (defined(invoker.sources_for_tests)) { skia_source_set(target_name + "_tests") { visibility = [ ":*" ] } } } } optional("fontmgr_android") { enabled = skia_enable_fontmgr_android public_defines = [ "SK_FONTMGR_ANDROID_AVAILABLE" ] deps = [ ":typeface_freetype", "//flutter/third_party/expat", ] public = [ "$_skia_root/include/ports/SkFontMgr_android.h" ] sources = [ "$_skia_root/src/ports/SkFontMgr_android.cpp", "$_skia_root/src/ports/SkFontMgr_android_parser.cpp", "$_skia_root/src/ports/SkFontMgr_android_parser.h", ] } optional("fontmgr_custom") { enabled = skia_enable_fontmgr_custom_directory || skia_enable_fontmgr_custom_embedded || skia_enable_fontmgr_custom_empty deps = [ ":typeface_freetype" ] public = [ "$_skia_root/src/ports/SkFontMgr_custom.h" ] sources = [ "$_skia_root/src/ports/SkFontMgr_custom.cpp" ] } optional("fontmgr_custom_directory") { enabled = skia_enable_fontmgr_custom_directory public_defines = [ "SK_FONTMGR_FREETYPE_DIRECTORY_AVAILABLE" ] deps = [ ":fontmgr_custom", ":typeface_freetype", ] public = [ "$_skia_root/include/ports/SkFontMgr_directory.h" ] sources = [ "$_skia_root/src/ports/SkFontMgr_custom_directory.cpp" ] } optional("fontmgr_custom_embedded") { enabled = skia_enable_fontmgr_custom_embedded public_defines = [ "SK_FONTMGR_FREETYPE_EMBEDDED_AVAILABLE" ] deps = [ ":fontmgr_custom", ":typeface_freetype", ] sources = [ "$_skia_root/src/ports/SkFontMgr_custom_embedded.cpp" ] } optional("fontmgr_custom_empty") { enabled = skia_enable_fontmgr_custom_empty public_defines = [ "SK_FONTMGR_FREETYPE_EMPTY_AVAILABLE" ] deps = [ ":fontmgr_custom", ":typeface_freetype", ] public = [ "$_skia_root/include/ports/SkFontMgr_empty.h" ] sources = [ "$_skia_root/src/ports/SkFontMgr_custom_empty.cpp" ] } optional("fontmgr_fontconfig") { enabled = skia_enable_fontmgr_fontconfig public_defines = [ "SK_FONTMGR_FONTCONFIG_AVAILABLE" ] # The public header includes fontconfig.h and uses FcConfig* public_deps = [ "//third_party:fontconfig" ] public = [ "$_skia_root/include/ports/SkFontMgr_fontconfig.h" ] deps = [ ":typeface_freetype" ] sources = [ "$_skia_root/src/ports/SkFontMgr_fontconfig.cpp" ] } optional("fontmgr_fuchsia") { enabled = skia_enable_fontmgr_fuchsia public_defines = [ "SK_FONTMGR_FUCHSIA_AVAILABLE" ] deps = [] if (is_fuchsia) { deps += [ "${fuchsia_sdk}/fidl/fuchsia.fonts" ] } else { deps = [ "//sdk/fidl/fuchsia.fonts" ] } public = [ "$_skia_root/src/ports/SkFontMgr_fuchsia.h" ] sources = [ "$_skia_root/src/ports/SkFontMgr_fuchsia.cpp" ] } optional("fontmgr_mac_ct") { enabled = skia_use_fonthost_mac public_defines = [ "SK_TYPEFACE_FACTORY_CORETEXT", "SK_FONTMGR_CORETEXT_AVAILABLE", ] public = [ "$_skia_root/include/ports/SkFontMgr_mac_ct.h", "$_skia_root/include/ports/SkTypeface_mac.h", ] sources = [ "$_skia_root/src/ports/SkFontMgr_mac_ct.cpp", "$_skia_root/src/ports/SkScalerContext_mac_ct.cpp", "$_skia_root/src/ports/SkScalerContext_mac_ct.h", "$_skia_root/src/ports/SkTypeface_mac_ct.cpp", "$_skia_root/src/ports/SkTypeface_mac_ct.h", ] if (is_mac) { frameworks = [ # AppKit symbols NSFontWeightXXX may be dlsym'ed. "AppKit.framework", "ApplicationServices.framework", ] } if (is_ios) { frameworks = [ "CoreFoundation.framework", "CoreGraphics.framework", "CoreText.framework", # UIKit symbols UIFontWeightXXX may be dlsym'ed. "UIKit.framework", ] } } optional("fontmgr_win") { enabled = skia_enable_fontmgr_win public_defines = [ "SK_TYPEFACE_FACTORY_DIRECTWRITE", "SK_FONTMGR_DIRECTWRITE_AVAILABLE", ] public = [ "$_skia_root/include/ports/SkTypeface_win.h" ] sources = [ "$_skia_root/include/ports/SkFontMgr_indirect.h", "$_skia_root/include/ports/SkRemotableFontMgr.h", "$_skia_root/src/fonts/SkFontMgr_indirect.cpp", "$_skia_root/src/ports/SkFontMgr_win_dw.cpp", "$_skia_root/src/ports/SkScalerContext_win_dw.cpp", "$_skia_root/src/ports/SkScalerContext_win_dw.h", "$_skia_root/src/ports/SkTypeface_win_dw.cpp", "$_skia_root/src/ports/SkTypeface_win_dw.h", ] if (skia_dwritecore_sdk != "") { defines = [ "DWRITE_CORE" ] if (is_win && is_clang) { # Clang complains about these headers, so mark them as system. These # headers are hiding SDK headers of the same name, which are also # included as system headers, so these need to go first in the cflags # "includes" before the SDK. gn appends configs in the order listed, # so these flags will be first. cflags = [ "-imsvc", "${skia_dwritecore_sdk}/include", ] } else { include_dirs = [ "${skia_dwritecore_sdk}/include" ] } } } optional("gpu_shared") { enabled = skia_enable_ganesh deps = [] libs = [] public_defines = [] public_deps = [] frameworks = [] sources = skia_shared_gpu_sources + skia_sksl_gpu_sources if (skia_use_vulkan) { public_defines += [ "SK_VULKAN" ] sources += skia_shared_vk_sources if (skia_enable_vulkan_debug_layers) { public_defines += [ "SK_ENABLE_VK_LAYERS" ] } if (skia_use_vma) { public_deps += [ "$_skia_root/src/gpu/vk/vulkanmemoryallocator" ] } } if (skia_use_metal) { public_defines += [ "SK_METAL" ] sources += skia_shared_mtl_sources } } optional("gpu") { enabled = skia_enable_ganesh deps = [ ":gpu_shared" ] public_defines = [] public_configs = [] public_deps = [] public = skia_gpu_public sources = skia_ganesh_private libs = [] frameworks = [] if (is_android) { sources += skia_gpu_android_private } if (skia_use_gl) { public_defines += [ "SK_GL" ] if (is_android) { sources += [ "$_skia_root/src/gpu/ganesh/gl/egl/GrGLMakeEGLInterface.cpp", "$_skia_root/src/gpu/ganesh/gl/egl/GrGLMakeNativeInterface_egl.cpp", ] sources += skia_android_gl_sources # this lib is required to link against AHardwareBuffer if (defined(ndk_api) && ndk_api >= 26) { libs += [ "android" ] } } else if (skia_use_webgl) { sources += [ "$_skia_root/src/gpu/ganesh/gl/webgl/GrGLMakeNativeInterface_webgl.cpp", ] } else if (is_linux && skia_use_x11) { sources += [ "$_skia_root/src/gpu/ganesh/gl/glx/GrGLMakeGLXInterface.cpp", "$_skia_root/src/gpu/ganesh/gl/glx/GrGLMakeNativeInterface_glx.cpp", ] libs += [ "GL" ] } else if (is_win) { sources += [ "$_skia_root/src/gpu/ganesh/gl/win/GrGLMakeNativeInterface_win.cpp", ] if (target_cpu != "arm64") { libs += [ "OpenGL32.lib" ] } } else { sources += [ "$_skia_root/src/gpu/ganesh/gl/GrGLMakeNativeInterface_none.cpp" ] } public += skia_gpu_gl_public sources += skia_gpu_gl_private } if (skia_use_vulkan) { public += skia_gpu_vk_public sources += skia_gpu_vk_private if (is_fuchsia) { public_deps += [ "${fuchsia_sdk}/pkg/vulkan" ] } if (is_android) { sources += skia_gpu_vk_android_private } } if (is_android && (skia_use_gl || skia_use_vulkan)) { # this lib is required to link against AHardwareBuffer if (defined(ndk_api) && ndk_api >= 26) { libs += [ "android" ] } } cflags_objcc = [] if (skia_use_metal) { public_defines += [ "SK_METAL" ] public += skia_gpu_metal_public sources += skia_gpu_metal_private sources += skia_gpu_metal_cpp frameworks += [ "Metal.framework" ] frameworks += [ "Foundation.framework" ] if (is_ios) { frameworks += [ "UIKit.framework" ] } cflags_objcc += [ "-fobjc-arc" ] } if (is_debug) { public_defines += [ "SK_ENABLE_DUMP_GPU" ] } } optional("jpeg_decode") { enabled = skia_use_libjpeg_turbo_decode public_defines = [ "SK_CODEC_DECODES_JPEG" ] deps = [ "//flutter/third_party/libjpeg-turbo:libjpeg" ] sources = [ "$_skia_root/src/codec/SkJpegCodec.cpp", "$_skia_root/src/codec/SkJpegDecoderMgr.cpp", "$_skia_root/src/codec/SkJpegSourceMgr.cpp", "$_skia_root/src/codec/SkJpegUtility.cpp", ] } optional("jpeg_encode") { enabled = skia_use_libjpeg_turbo_encode && !skia_use_ndk_images deps = [ "//flutter/third_party/libjpeg-turbo:libjpeg" ] public = skia_encode_jpeg_public sources = skia_encode_jpeg_srcs } optional("ndk_images") { enabled = skia_use_ndk_images public_defines = [ "SK_ENABLE_NDK_IMAGES" ] sources = [ "$_skia_root/src/ports/SkImageEncoder_NDK.cpp", "$_skia_root/src/ports/SkImageGeneratorNDK.cpp", "$_skia_root/src/ports/SkNDKConversions.cpp", ] libs = [ "jnigraphics" ] } optional("xps") { enabled = skia_use_xps && is_win public_defines = [ "SK_SUPPORT_XPS" ] public = skia_xps_public sources = skia_xps_sources } optional("png_decode") { enabled = skia_use_libpng_decode public_defines = [ "SK_CODEC_DECODES_PNG", "SK_CODEC_DECODES_ICO", ] deps = [ "//flutter/third_party/libpng" ] sources = [ "$_skia_root/src/codec/SkIcoCodec.cpp", "$_skia_root/src/codec/SkPngCodec.cpp", ] } optional("png_encode") { enabled = skia_use_libpng_encode && !skia_use_ndk_images public = skia_encode_png_public deps = [ "//flutter/third_party/libpng" ] sources = skia_encode_png_srcs } optional("typeface_freetype") { enabled = skia_use_freetype public_defines = [ "SK_TYPEFACE_FACTORY_FREETYPE" ] deps = [ "//flutter/third_party/freetype2" ] sources = [ "$_skia_root/src/ports/SkFontHost_FreeType.cpp", "$_skia_root/src/ports/SkFontHost_FreeType_common.cpp", "$_skia_root/src/ports/SkFontHost_FreeType_common.h", ] } optional("webp_decode") { enabled = skia_use_libwebp_decode public_defines = [ "SK_CODEC_DECODES_WEBP" ] deps = [ "//flutter/third_party/libwebp" ] sources = [ "$_skia_root/src/codec/SkWebpCodec.cpp" ] } optional("webp_encode") { enabled = skia_use_libwebp_encode && !skia_use_ndk_images public = skia_encode_webp_public deps = [ "//flutter/third_party/libwebp" ] sources = skia_encode_webp_srcs } optional("wuffs") { enabled = skia_use_wuffs public_defines = [ "SK_HAS_WUFFS_LIBRARY", # TODO remove after rolling # http://review.skia.org/811816 "SK_CODEC_DECODES_GIF", ] deps = [ "//flutter/third_party/wuffs" ] sources = [ "$_skia_root/src/codec/SkWuffsCodec.cpp" ] } optional("xml") { enabled = skia_use_expat || skia_use_jpeg_gainmaps public_defines = [ "SK_XML" ] deps = [ "//flutter/third_party/expat" ] sources = skia_xml_sources + skia_codec_xmp + [ "$_skia_root/src/svg/SkSVGCanvas.cpp", "$_skia_root/src/svg/SkSVGDevice.cpp", ] } import("$_skia_root/gn/codec.gni") skia_component("skia") { public_configs = [ ":skia_public" ] configs = skia_library_configs # Opted out of check_includes, due to (logically) being part of skia. check_includes = false public_deps = [ ":fontmgr_android", ":fontmgr_custom_directory", ":fontmgr_custom_embedded", ":fontmgr_custom_empty", ":fontmgr_fontconfig", ":fontmgr_fuchsia", ":fontmgr_mac_ct", ":fontmgr_win", ":gpu", ":jpeg_encode", ":png_encode", ":webp_encode", ":xps", ] deps = [ ":hsw", ":jpeg_decode", ":ndk_images", ":png_decode", ":webp_decode", ":wuffs", ":xml", "modules/skcms", ] public = skia_core_public public += skia_codec_public public += skia_utils_public public += skia_effects_public public += skia_effects_imagefilter_public sources = [] sources += skia_core_sources sources += skia_utils_private sources += skia_utils_chromium sources += skia_effects_sources sources += skia_colorfilters_sources sources += skia_effects_imagefilter_sources sources += skia_codec_core sources += skia_codec_decode_bmp sources += skia_encode_srcs sources += skia_sksl_sources sources += [ "$_skia_root/src/android/SkAndroidFrameworkUtils.cpp", "$_skia_root/src/android/SkAnimatedImage.cpp", "$_skia_root/src/codec/SkAndroidCodec.cpp", "$_skia_root/src/codec/SkAndroidCodecAdapter.cpp", "$_skia_root/src/codec/SkEncodedInfo.cpp", "$_skia_root/src/codec/SkParseEncodedOrigin.cpp", "$_skia_root/src/codec/SkSampledCodec.cpp", "$_skia_root/src/ports/SkDiscardableMemory_none.cpp", "$_skia_root/src/ports/SkGlobalInitialization_default.cpp", "$_skia_root/src/ports/SkMemory_malloc.cpp", "$_skia_root/src/ports/SkOSFile_stdio.cpp", "$_skia_root/src/sfnt/SkOTTable_name.cpp", "$_skia_root/src/sfnt/SkOTUtils.cpp", ] defines = [] libs = [] if (skia_use_no_jpeg_encode) { sources += skia_no_encode_jpeg_srcs } if (skia_use_no_png_encode) { sources += skia_no_encode_png_srcs } if (skia_use_no_webp_encode) { sources += skia_no_encode_webp_srcs } if (is_win) { sources += [ "$_skia_root/src/ports/SkDebug_win.cpp", "$_skia_root/src/ports/SkImageGeneratorWIC.cpp", "$_skia_root/src/ports/SkOSFile_win.cpp", "$_skia_root/src/ports/SkOSLibrary_win.cpp", ] libs += [ "Ole32.lib", "OleAut32.lib", ] if (!skia_enable_winuwp) { libs += [ "FontSub.lib", "User32.lib", "Usp10.lib", ] } } else { sources += [ "$_skia_root/src/ports/SkOSFile_posix.cpp", "$_skia_root/src/ports/SkOSLibrary_posix.cpp", ] libs += [ "dl" ] } if (is_android) { deps += [ "//flutter/third_party/expat" ] sources += [ "$_skia_root/src/ports/SkDebug_android.cpp" ] libs += [ "EGL", "GLESv2", "log", ] } if (is_linux || is_wasm) { sources += [ "$_skia_root/src/ports/SkDebug_stdio.cpp" ] if (skia_use_egl) { libs += [ "GLESv2" ] } } if (is_mac) { public += [ "$_skia_root/include/ports/SkCFObject.h" ] sources += [ "$_skia_root/src/ports/SkDebug_stdio.cpp", "$_skia_root/src/ports/SkImageGeneratorCG.cpp", ] frameworks = [ "ApplicationServices.framework", "OpenGL.framework", ] } if (is_ios) { public += [ "$_skia_root/include/ports/SkCFObject.h" ] sources += [ "$_skia_root/src/ports/SkDebug_stdio.cpp", "$_skia_root/src/ports/SkImageGeneratorCG.cpp", ] frameworks = [ "CoreFoundation.framework", "ImageIO.framework", "MobileCoreServices.framework", ] } if (is_fuchsia) { sources += [ "$_skia_root/src/ports/SkDebug_stdio.cpp" ] } }
engine/skia/BUILD.gn/0
{ "file_path": "engine/skia/BUILD.gn", "repo_id": "engine", "token_count": 9647 }
438