Flutter Engine Uber Docs
Docs for the entire Flutter Engine repo.
 
Loading...
Searching...
No Matches
embedder.cc File Reference
#include <cstring>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "flutter/fml/build_config.h"
#include "flutter/fml/closure.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/native_library.h"
#include "flutter/fml/status_or.h"
#include "flutter/fml/thread.h"
#include "third_party/dart/runtime/bin/elf_loader.h"
#include "third_party/dart/runtime/include/dart_native_api.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GpuTypes.h"
#include "third_party/skia/include/gpu/ganesh/GrBackendSurface.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/common/graphics/persistent_cache.h"
#include "flutter/common/task_runners.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/file.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/trace_event.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/embedder_engine.h"
#include "flutter/shell/platform/embedder/embedder_external_texture_resolver.h"
#include "flutter/shell/platform/embedder/embedder_platform_message_response.h"
#include "flutter/shell/platform/embedder/embedder_render_target.h"
#include "flutter/shell/platform/embedder/embedder_render_target_skia.h"
#include "flutter/shell/platform/embedder/embedder_semantics_update.h"
#include "flutter/shell/platform/embedder/embedder_struct_macros.h"
#include "flutter/shell/platform/embedder/embedder_task_runner.h"
#include "flutter/shell/platform/embedder/embedder_thread_host.h"
#include "flutter/shell/platform/embedder/pixel_formats.h"
#include "flutter/shell/platform/embedder/platform_view_embedder.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/writer.h"

Go to the source code of this file.

Classes

struct  _FlutterPlatformMessageResponseHandle
 
struct  LoadedElfDeleter
 
struct  _FlutterEngineAOTData
 

Macros

#define FML_USED_ON_EMBEDDER
 
#define RAPIDJSON_HAS_STDSTRING   1
 
#define FLUTTER_EXPORT   __attribute__((visibility("default")))
 
#define LOG_EMBEDDER_ERROR(code, reason)    LogEmbedderError(code, reason, #code, __FUNCTION__, __FILE__, __LINE__)
 
#define SET_PROC(member, function)
 

Typedefs

using UniqueLoadedElf = std::unique_ptr< Dart_LoadedElf, LoadedElfDeleter >
 

Functions

static FlutterEngineResult LogEmbedderError (FlutterEngineResult code, const char *reason, const char *code_name, const char *function, const char *file, int line)
 
static bool IsOpenGLRendererConfigValid (const FlutterRendererConfig *config)
 
static bool IsSoftwareRendererConfigValid (const FlutterRendererConfig *config)
 
static bool IsMetalRendererConfigValid (const FlutterRendererConfig *config)
 
static bool IsVulkanRendererConfigValid (const FlutterRendererConfig *config)
 
static bool IsRendererValid (const FlutterRendererConfig *config)
 
static flutter::Shell::CreateCallback< flutter::PlatformViewInferOpenGLPlatformViewCreationCallback (const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
 
static flutter::Shell::CreateCallback< flutter::PlatformViewInferMetalPlatformViewCreationCallback (const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
 
static flutter::Shell::CreateCallback< flutter::PlatformViewInferVulkanPlatformViewCreationCallback (const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
 
static flutter::Shell::CreateCallback< flutter::PlatformViewInferSoftwarePlatformViewCreationCallback (const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder)
 
static flutter::Shell::CreateCallback< flutter::PlatformViewInferPlatformViewCreationCallback (const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
 
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore (GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterOpenGLTexture *texture)
 
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore (GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterOpenGLFramebuffer *framebuffer)
 
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore (GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterOpenGLSurface *surface)
 
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore (GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterSoftwareBackingStore *software)
 
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore (GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterSoftwareBackingStore2 *software)
 
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore (GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterMetalBackingStore *metal)
 
static std::unique_ptr< flutter::EmbedderRenderTargetMakeRenderTargetFromBackingStoreImpeller (FlutterBackingStore backing_store, const fml::closure &on_release, const std::shared_ptr< impeller::AiksContext > &aiks_context, const FlutterBackingStoreConfig &config, const FlutterOpenGLFramebuffer *framebuffer)
 
static std::unique_ptr< flutter::EmbedderRenderTargetMakeRenderTargetFromBackingStoreImpeller (FlutterBackingStore backing_store, const fml::closure &on_release, const std::shared_ptr< impeller::AiksContext > &aiks_context, const FlutterBackingStoreConfig &config, const FlutterMetalBackingStore *metal)
 
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore (GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterVulkanBackingStore *vulkan)
 
static std::unique_ptr< flutter::EmbedderRenderTargetMakeRenderTargetFromSkSurface (FlutterBackingStore backing_store, sk_sp< SkSurface > skia_surface, fml::closure on_release, flutter::EmbedderRenderTarget::MakeOrClearCurrentCallback on_make_current, flutter::EmbedderRenderTarget::MakeOrClearCurrentCallback on_clear_current)
 
static std::unique_ptr< flutter::EmbedderRenderTargetMakeRenderTargetFromSkSurface (FlutterBackingStore backing_store, sk_sp< SkSurface > skia_surface, fml::closure on_release)
 
static std::unique_ptr< flutter::EmbedderRenderTargetCreateEmbedderRenderTarget (const FlutterCompositor *compositor, const FlutterBackingStoreConfig &config, GrDirectContext *context, const std::shared_ptr< impeller::AiksContext > &aiks_context, bool enable_impeller)
 
static fml::StatusOr< std::unique_ptr< flutter::EmbedderExternalViewEmbedder > > InferExternalViewEmbedderFromArgs (const FlutterCompositor *compositor, bool enable_impeller)
 
static std::variant< flutter::ViewportMetrics, std::string > MakeViewportMetricsFromWindowMetrics (const FlutterWindowMetricsEvent *flutter_metrics)
 
FlutterEngineResult FlutterEngineCreateAOTData (const FlutterEngineAOTDataSource *source, FlutterEngineAOTData *data_out)
 Creates the necessary data structures to launch a Flutter Dart application in AOT mode. The data may only be collected after all FlutterEngine instances launched using this data have been terminated.
 
FlutterEngineResult FlutterEngineCollectAOTData (FlutterEngineAOTData data)
 Collects the AOT data.
 
void PopulateJITSnapshotMappingCallbacks (const FlutterProjectArgs *args, flutter::Settings &settings)
 
void PopulateAOTSnapshotMappingCallbacks (const FlutterProjectArgs *args, flutter::Settings &settings)
 
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV1 (FlutterUpdateSemanticsNodeCallback update_semantics_node_callback, FlutterUpdateSemanticsCustomActionCallback update_semantics_custom_action_callback, void *user_data)
 
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV2 (FlutterUpdateSemanticsCallback update_semantics_callback, void *user_data)
 
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV3 (FlutterUpdateSemanticsCallback2 update_semantics_callback, void *user_data)
 
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallback (const FlutterProjectArgs *args, void *user_data)
 
FlutterEngineResult FlutterEngineRun (size_t version, const FlutterRendererConfig *config, const FlutterProjectArgs *args, void *user_data, FLUTTER_API_SYMBOL(FlutterEngine) *engine_out)
 Initialize and run a Flutter engine instance and return a handle to it. This is a convenience method for the pair of calls to FlutterEngineInitialize and FlutterEngineRunInitialized.
 
FlutterEngineResult FlutterEngineInitialize (size_t version, const FlutterRendererConfig *config, const FlutterProjectArgs *args, void *user_data, FLUTTER_API_SYMBOL(FlutterEngine) *engine_out)
 Initialize a Flutter engine instance. This does not run the Flutter application code till the FlutterEngineRunInitialized call is made. Besides Flutter application code, no tasks are scheduled on embedder managed task runners either. This allows embedders providing custom task runners to the Flutter engine to obtain a handle to the Flutter engine before the engine can post tasks on these task runners.
 
FlutterEngineResult FlutterEngineRunInitialized (FLUTTER_API_SYMBOL(FlutterEngine) engine)
 Runs an initialized engine instance. An engine can be initialized via FlutterEngineInitialize. An initialized instance can only be run once. During and after this call, custom task runners supplied by the embedder are expected to start servicing tasks.
 
FLUTTER_EXPORT FlutterEngineResult FlutterEngineAddView (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterAddViewInfo *info)
 Adds a view.
 
FLUTTER_EXPORT FlutterEngineResult FlutterEngineRemoveView (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterRemoveViewInfo *info)
 Removes a view.
 
FlutterEngineResult FlutterEngineSendViewFocusEvent (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterViewFocusEvent *event)
 Notifies the engine that platform view focus state has changed.
 
FLUTTER_EXPORT FlutterEngineResult FlutterEngineDeinitialize (FLUTTER_API_SYMBOL(FlutterEngine) engine)
 Stops running the Flutter engine instance. After this call, the embedder is also guaranteed that no more calls to post tasks onto custom task runners specified by the embedder are made. The Flutter engine handle still needs to be collected via a call to FlutterEngineShutdown.
 
FlutterEngineResult FlutterEngineShutdown (FLUTTER_API_SYMBOL(FlutterEngine) engine)
 Shuts down a Flutter engine instance. The engine handle is no longer valid for any calls in the embedder API after this point. Making additional calls with this handle is undefined behavior.
 
FlutterEngineResult FlutterEngineSendWindowMetricsEvent (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterWindowMetricsEvent *flutter_metrics)
 
flutter::PointerData::Change ToPointerDataChange (FlutterPointerPhase phase)
 
flutter::PointerData::DeviceKind ToPointerDataKind (FlutterPointerDeviceKind device_kind)
 
flutter::PointerData::SignalKind ToPointerDataSignalKind (FlutterPointerSignalKind kind)
 
int64_t PointerDataButtonsForLegacyEvent (flutter::PointerData::Change change)
 
FlutterEngineResult FlutterEngineSendPointerEvent (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPointerEvent *pointers, size_t events_count)
 
static flutter::KeyEventType MapKeyEventType (FlutterKeyEventType event_kind)
 
static flutter::KeyEventDeviceType MapKeyEventDeviceType (FlutterKeyEventDeviceType event_kind)
 
static FlutterEngineResult InternalSendPlatformMessage (FLUTTER_API_SYMBOL(FlutterEngine) engine, const char *channel, const uint8_t *data, size_t size, FlutterDataCallback data_callback, void *user_data)
 
FlutterEngineResult FlutterEngineSendKeyEvent (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterKeyEvent *event, FlutterKeyEventCallback callback, void *user_data)
 Sends a key event to the engine. The framework will decide whether to handle this event in a synchronous fashion, although due to technical limitation, the result is always reported asynchronously. The callback is guaranteed to be called exactly once.
 
FlutterEngineResult FlutterEngineSendPlatformMessage (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessage *flutter_message)
 
FlutterEngineResult FlutterPlatformMessageCreateResponseHandle (FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterDataCallback data_callback, void *user_data, FlutterPlatformMessageResponseHandle **response_out)
 Creates a platform message response handle that allows the embedder to set a native callback for a response to a message. This handle may be set on the response_handle field of any FlutterPlatformMessage sent to the engine.
 
FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle (FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterPlatformMessageResponseHandle *response)
 Collects the handle created using FlutterPlatformMessageCreateResponseHandle.
 
FlutterEngineResult FlutterEngineSendPlatformMessageResponse (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessageResponseHandle *handle, const uint8_t *data, size_t data_length)
 Send a response from the native side to a platform message from the Dart Flutter application.
 
FlutterEngineResult __FlutterEngineFlushPendingTasksNow ()
 This API is only meant to be used by platforms that need to flush tasks on a message loop not controlled by the Flutter engine.
 
FlutterEngineResult FlutterEngineRegisterExternalTexture (FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
 Register an external texture with a unique (per engine) identifier. Only rendering backends that support external textures accept external texture registrations. After the external texture is registered, the application can mark that a frame is available by calling FlutterEngineMarkExternalTextureFrameAvailable.
 
FlutterEngineResult FlutterEngineUnregisterExternalTexture (FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
 Unregister a previous texture registration.
 
FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable (FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
 Mark that a new texture frame is available for a given texture identifier.
 
FlutterEngineResult FlutterEngineUpdateSemanticsEnabled (FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled)
 Enable or disable accessibility semantics.
 
FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures (FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterAccessibilityFeature flags)
 Sets additional accessibility features.
 
FlutterEngineResult FlutterEngineDispatchSemanticsAction (FLUTTER_API_SYMBOL(FlutterEngine) engine, uint64_t node_id, FlutterSemanticsAction action, const uint8_t *data, size_t data_length)
 Dispatch a semantics action to the specified semantics node in the implicit view.
 
FlutterEngineResult FlutterEngineSendSemanticsAction (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterSendSemanticsActionInfo *info)
 Dispatch a semantics action to the specified semantics node within a specific view.
 
FlutterEngineResult FlutterEngineOnVsync (FLUTTER_API_SYMBOL(FlutterEngine) engine, intptr_t baton, uint64_t frame_start_time_nanos, uint64_t frame_target_time_nanos)
 Notify the engine that a vsync event occurred. A baton passed to the platform via the vsync callback must be returned. This call must be made on the thread on which the call to FlutterEngineRun was made.
 
FlutterEngineResult FlutterEngineReloadSystemFonts (FLUTTER_API_SYMBOL(FlutterEngine) engine)
 Reloads the system fonts in engine.
 
void FlutterEngineTraceEventDurationBegin (const char *name)
 A profiling utility. Logs a trace duration begin event to the timeline. If the timeline is unavailable or disabled, this has no effect. Must be balanced with an duration end event (via FlutterEngineTraceEventDurationEnd) with the same name on the same thread. Can be called on any thread. Strings passed into the function will NOT be copied when added to the timeline. Only string literals may be passed in.
 
void FlutterEngineTraceEventDurationEnd (const char *name)
 A profiling utility. Logs a trace duration end event to the timeline. If the timeline is unavailable or disabled, this has no effect. This call must be preceded by a trace duration begin call (via FlutterEngineTraceEventDurationBegin) with the same name on the same thread. Can be called on any thread. Strings passed into the function will NOT be copied when added to the timeline. Only string literals may be passed in.
 
void FlutterEngineTraceEventInstant (const char *name)
 A profiling utility. Logs a trace duration instant event to the timeline. If the timeline is unavailable or disabled, this has no effect. Can be called on any thread. Strings passed into the function will NOT be copied when added to the timeline. Only string literals may be passed in.
 
FlutterEngineResult FlutterEnginePostRenderThreadTask (FLUTTER_API_SYMBOL(FlutterEngine) engine, VoidCallback callback, void *baton)
 Posts a task onto the Flutter render thread. Typically, this may be called from any thread as long as a FlutterEngineShutdown on the specific engine has not already been initiated.
 
uint64_t FlutterEngineGetCurrentTime ()
 Get the current time in nanoseconds from the clock used by the flutter engine. This is the system monotonic clock.
 
FlutterEngineResult FlutterEngineRunTask (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterTask *task)
 Inform the engine to run the specified task. This task has been given to the embedder via the FlutterTaskRunnerDescription.post_task_callback. This call must only be made at the target time specified in that callback. Running the task before that time is undefined behavior.
 
static bool DispatchJSONPlatformMessage (FLUTTER_API_SYMBOL(FlutterEngine) engine, const rapidjson::Document &document, const std::string &channel_name)
 
FlutterEngineResult FlutterEngineUpdateLocales (FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterLocale **locales, size_t locales_count)
 Notify a running engine instance that the locale has been updated. The preferred locale must be the first item in the list of locales supplied. The other entries will be used as a fallback.
 
bool FlutterEngineRunsAOTCompiledDartCode (void)
 Returns if the Flutter engine instance will run AOT compiled Dart code. This call has no threading restrictions.
 
FlutterEngineResult FlutterEnginePostDartObject (FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterEngineDartPort port, const FlutterEngineDartObject *object)
 Posts a Dart object to specified send port. The corresponding receive port for send port can be in any isolate running in the VM. This isolate can also be the root isolate for an unrelated engine. The engine parameter is necessary only to ensure the call is not made when no engine (and hence no VM) is running.
 
FlutterEngineResult FlutterEngineNotifyLowMemoryWarning (FLUTTER_API_SYMBOL(FlutterEngine) raw_engine)
 Posts a low memory notification to a running engine instance. The engine will do its best to release non-critical resources in response. It is not guaranteed that the resource would have been collected by the time this call returns however. The notification is posted to engine subsystems that may be operating on other threads.
 
FlutterEngineResult FlutterEnginePostCallbackOnAllNativeThreads (FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterNativeThreadCallback callback, void *user_data)
 Schedule a callback to be run on all engine managed threads. The engine will attempt to service this callback the next time the message loop for each managed thread is idle. Since the engine manages the entire lifecycle of multiple threads, there is no opportunity for the embedders to finely tune the priorities of threads directly, or, perform other thread specific configuration (for example, setting thread names for tracing). This callback gives embedders a chance to affect such tuning.
 
FlutterEngineResult FlutterEngineNotifyDisplayUpdate (FLUTTER_API_SYMBOL(FlutterEngine) raw_engine, const FlutterEngineDisplaysUpdateType update_type, const FlutterEngineDisplay *embedder_displays, size_t display_count)
 Posts updates corresponding to display changes to a running engine instance.
 
FlutterEngineResult FlutterEngineScheduleFrame (FLUTTER_API_SYMBOL(FlutterEngine) engine)
 Schedule a new frame to redraw the content.
 
FlutterEngineResult FlutterEngineSetNextFrameCallback (FLUTTER_API_SYMBOL(FlutterEngine) engine, VoidCallback callback, void *user_data)
 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 from the raster thread; embedders must re-thread if necessary. Performing blocking calls in this callback may introduce application jank.
 
FlutterEngineResult FlutterEngineGetProcAddresses (FlutterEngineProcTable *table)
 Gets the table of engine function pointers.
 

Variables

const uint8_t kPlatformStrongDill []
 
const intptr_t kPlatformStrongDillSize
 
const int32_t kFlutterSemanticsNodeIdBatchEnd = -1
 
const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1
 
static constexpr FlutterViewId kFlutterImplicitViewId = 0
 
const char * kFlutterKeyDataChannel = "flutter/keydata"
 

Macro Definition Documentation

◆ FLUTTER_EXPORT

#define FLUTTER_EXPORT   __attribute__((visibility("default")))

Definition at line 32 of file embedder.cc.

◆ FML_USED_ON_EMBEDDER

#define FML_USED_ON_EMBEDDER

Definition at line 5 of file embedder.cc.

◆ LOG_EMBEDDER_ERROR

#define LOG_EMBEDDER_ERROR (   code,
  reason 
)     LogEmbedderError(code, reason, #code, __FUNCTION__, __FILE__, __LINE__)

Definition at line 155 of file embedder.cc.

157 {
158 if (config->type != kOpenGL) {
159 return false;
160 }
161
162 const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
163
164 if (!SAFE_EXISTS(open_gl_config, make_current) ||
165 !SAFE_EXISTS(open_gl_config, clear_current) ||
166 !SAFE_EXISTS_ONE_OF(open_gl_config, fbo_callback,
167 fbo_with_frame_info_callback) ||
168 !SAFE_EXISTS_ONE_OF(open_gl_config, present, present_with_info)) {
169 return false;
170 }
171
172 return true;
173}
174
175static bool IsSoftwareRendererConfigValid(const FlutterRendererConfig* config) {
176 if (config->type != kSoftware) {
177 return false;
178 }
179
180 const FlutterSoftwareRendererConfig* software_config = &config->software;
181
182 if (SAFE_ACCESS(software_config, surface_present_callback, nullptr) ==
183 nullptr) {
184 return false;
185 }
186
187 return true;
188}
189
190static bool IsMetalRendererConfigValid(const FlutterRendererConfig* config) {
191 if (config->type != kMetal) {
192 return false;
193 }
194
195 const FlutterMetalRendererConfig* metal_config = &config->metal;
196
197 bool device = SAFE_ACCESS(metal_config, device, nullptr);
198 bool command_queue =
199 SAFE_ACCESS(metal_config, present_command_queue, nullptr);
200
201 bool present = SAFE_ACCESS(metal_config, present_drawable_callback, nullptr);
202 bool get_texture =
203 SAFE_ACCESS(metal_config, get_next_drawable_callback, nullptr);
204
205 return device && command_queue && present && get_texture;
206}
207
208static bool IsVulkanRendererConfigValid(const FlutterRendererConfig* config) {
209 if (config->type != kVulkan) {
210 return false;
211 }
212
213 const FlutterVulkanRendererConfig* vulkan_config = &config->vulkan;
214
215 if (!SAFE_EXISTS(vulkan_config, instance) ||
216 !SAFE_EXISTS(vulkan_config, physical_device) ||
217 !SAFE_EXISTS(vulkan_config, device) ||
218 !SAFE_EXISTS(vulkan_config, queue) ||
219 !SAFE_EXISTS(vulkan_config, get_instance_proc_address_callback) ||
220 !SAFE_EXISTS(vulkan_config, get_next_image_callback) ||
221 !SAFE_EXISTS(vulkan_config, present_image_callback)) {
222 return false;
223 }
224
225 return true;
226}
227
228static bool IsRendererValid(const FlutterRendererConfig* config) {
229 if (config == nullptr) {
230 return false;
231 }
232
233 switch (config->type) {
234 case kOpenGL:
235 return IsOpenGLRendererConfigValid(config);
236 case kSoftware:
237 return IsSoftwareRendererConfigValid(config);
238 case kMetal:
239 return IsMetalRendererConfigValid(config);
240 case kVulkan:
241 return IsVulkanRendererConfigValid(config);
242 default:
243 return false;
244 }
245
246 return false;
247}
248
249#if FML_OS_LINUX || FML_OS_WIN
250static void* DefaultGLProcResolver(const char* name) {
251 static fml::RefPtr<fml::NativeLibrary> proc_library =
252#if FML_OS_LINUX
254#elif FML_OS_WIN // FML_OS_LINUX
255 fml::NativeLibrary::Create("opengl32.dll");
256#endif // FML_OS_WIN
257 return static_cast<void*>(
258 const_cast<uint8_t*>(proc_library->ResolveSymbol(name)));
259}
260#endif // FML_OS_LINUX || FML_OS_WIN
261
262#ifdef SHELL_ENABLE_GL
263// Auxiliary function used to translate rectangles of type SkIRect to
264// FlutterRect.
265static FlutterRect DlIRectToFlutterRect(const flutter::DlIRect& dl_rect) {
266 FlutterRect flutter_rect = {static_cast<double>(dl_rect.GetLeft()),
267 static_cast<double>(dl_rect.GetTop()),
268 static_cast<double>(dl_rect.GetRight()),
269 static_cast<double>(dl_rect.GetBottom())};
270 return flutter_rect;
271}
272
273// Auxiliary function used to translate rectangles of type FlutterRect to
274// SkIRect.
275static const flutter::DlIRect FlutterRectToDlIRect(FlutterRect flutter_rect) {
276 return flutter::DlIRect::MakeLTRB(static_cast<int32_t>(flutter_rect.left),
277 static_cast<int32_t>(flutter_rect.top),
278 static_cast<int32_t>(flutter_rect.right),
279 static_cast<int32_t>(flutter_rect.bottom));
280}
281
282// We need GL_BGRA8_EXT for creating SkSurfaces from FlutterOpenGLSurfaces
283// below.
284#ifndef GL_BGRA8_EXT
285#define GL_BGRA8_EXT 0x93A1
286#endif
287
288static std::optional<SkColorType> FlutterFormatToSkColorType(uint32_t format) {
289 switch (format) {
290 case GL_BGRA8_EXT:
291 return kBGRA_8888_SkColorType;
292 case GL_RGBA8:
293 return kRGBA_8888_SkColorType;
294 default:
295 FML_LOG(ERROR) << "Cannot convert format " << format
296 << " to SkColorType.";
297 return std::nullopt;
298 }
299}
300
301#endif
302
305 const FlutterRendererConfig* config,
306 void* user_data,
308 platform_dispatch_table,
309 std::unique_ptr<flutter::EmbedderExternalViewEmbedder>
310 external_view_embedder,
311 bool enable_impeller) {
312#ifdef SHELL_ENABLE_GL
313 if (config->type != kOpenGL) {
314 return nullptr;
315 }
316
317 auto gl_make_current = [ptr = config->open_gl.make_current,
318 user_data]() -> bool { return ptr(user_data); };
319
320 auto gl_clear_current = [ptr = config->open_gl.clear_current,
321 user_data]() -> bool { return ptr(user_data); };
322
323 auto gl_present =
324 [present = config->open_gl.present,
325 present_with_info = config->open_gl.present_with_info,
326 user_data](flutter::GLPresentInfo gl_present_info) -> bool {
327 if (present) {
328 return present(user_data);
329 } else {
330 // Format the frame and buffer damages accordingly. Note that, since the
331 // current compute damage algorithm only returns one rectangle for damage
332 // we are assuming the number of rectangles provided in frame and buffer
333 // damage are always 1. Once the function that computes damage implements
334 // support for multiple damage rectangles, GLPresentInfo should also
335 // contain the number of damage rectangles.
336
337 std::optional<FlutterRect> frame_damage_rect;
338 if (gl_present_info.frame_damage) {
339 frame_damage_rect =
340 DlIRectToFlutterRect(*(gl_present_info.frame_damage));
341 }
342 std::optional<FlutterRect> buffer_damage_rect;
343 if (gl_present_info.buffer_damage) {
344 buffer_damage_rect =
345 DlIRectToFlutterRect(*(gl_present_info.buffer_damage));
346 }
347
348 FlutterDamage frame_damage{
349 .struct_size = sizeof(FlutterDamage),
350 .num_rects = frame_damage_rect ? size_t{1} : size_t{0},
351 .damage = frame_damage_rect ? &frame_damage_rect.value() : nullptr,
352 };
353 FlutterDamage buffer_damage{
354 .struct_size = sizeof(FlutterDamage),
355 .num_rects = buffer_damage_rect ? size_t{1} : size_t{0},
356 .damage = buffer_damage_rect ? &buffer_damage_rect.value() : nullptr,
357 };
358
359 // Construct the present information concerning the frame being rendered.
360 FlutterPresentInfo present_info = {
362 .fbo_id = gl_present_info.fbo_id,
363 .frame_damage = frame_damage,
364 .buffer_damage = buffer_damage,
365 };
366
367 return present_with_info(user_data, &present_info);
368 }
369 };
370
371 auto gl_fbo_callback =
372 [fbo_callback = config->open_gl.fbo_callback,
373 fbo_with_frame_info_callback =
375 user_data](flutter::GLFrameInfo gl_frame_info) -> intptr_t {
376 if (fbo_callback) {
377 return fbo_callback(user_data);
378 } else {
379 FlutterFrameInfo frame_info = {};
380 frame_info.struct_size = sizeof(FlutterFrameInfo);
381 frame_info.size = {gl_frame_info.width, gl_frame_info.height};
382 return fbo_with_frame_info_callback(user_data, &frame_info);
383 }
384 };
385
386 auto gl_populate_existing_damage =
387 [populate_existing_damage = config->open_gl.populate_existing_damage,
388 user_data](intptr_t id) -> flutter::GLFBOInfo {
389 // If no populate_existing_damage was provided, disable partial
390 // repaint.
391 if (!populate_existing_damage) {
392 return flutter::GLFBOInfo{
393 .fbo_id = static_cast<uint32_t>(id),
394 .existing_damage = std::nullopt,
395 };
396 }
397
398 // Given the FBO's ID, get its existing damage.
399 FlutterDamage existing_damage;
400 populate_existing_damage(user_data, id, &existing_damage);
401
402 std::optional<flutter::DlIRect> existing_damage_rect = std::nullopt;
403
404 // Verify that at least one damage rectangle was provided.
405 if (existing_damage.num_rects <= 0 || existing_damage.damage == nullptr) {
406 FML_LOG(INFO) << "No damage was provided. Forcing full repaint.";
407 } else {
408 existing_damage_rect = flutter::DlIRect();
409 for (size_t i = 0; i < existing_damage.num_rects; i++) {
410 existing_damage_rect = existing_damage_rect->Union(
411 FlutterRectToDlIRect(existing_damage.damage[i]));
412 }
413 }
414
415 // Pass the information about this FBO to the rendering backend.
416 return flutter::GLFBOInfo{
417 .fbo_id = static_cast<uint32_t>(id),
418 .existing_damage = existing_damage_rect,
419 };
420 };
421
422 const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
423 std::function<bool()> gl_make_resource_current_callback = nullptr;
424 if (SAFE_ACCESS(open_gl_config, make_resource_current, nullptr) != nullptr) {
425 gl_make_resource_current_callback =
426 [ptr = config->open_gl.make_resource_current, user_data]() {
427 return ptr(user_data);
428 };
429 }
430
431 std::function<flutter::DlMatrix(void)> gl_surface_transformation_callback =
432 nullptr;
433 if (SAFE_ACCESS(open_gl_config, surface_transformation, nullptr) != nullptr) {
434 gl_surface_transformation_callback =
435 [ptr = config->open_gl.surface_transformation, user_data]() {
436 FlutterTransformation transformation = ptr(user_data);
437 // clang-format off
438 return flutter::DlMatrix(
439 transformation.scaleX, transformation.skewY, 0.0f, transformation.pers0,
440 transformation.skewX, transformation.scaleY, 0.0f, transformation.pers1,
441 0.0f, 0.0f, 1.0f, 0.0f,
442 transformation.transX, transformation.transY, 0.0f, transformation.pers2
443 );
444 // clang-format on
445 };
446
447 // If there is an external view embedder, ask it to apply the surface
448 // transformation to its surfaces as well.
449 if (external_view_embedder) {
450 external_view_embedder->SetSurfaceTransformationCallback(
451 gl_surface_transformation_callback);
452 }
453 }
454
455 flutter::GPUSurfaceGLDelegate::GLProcResolver gl_proc_resolver = nullptr;
456 if (SAFE_ACCESS(open_gl_config, gl_proc_resolver, nullptr) != nullptr) {
457 gl_proc_resolver = [ptr = config->open_gl.gl_proc_resolver,
458 user_data](const char* gl_proc_name) {
459 return ptr(user_data, gl_proc_name);
460 };
461 } else {
462#if FML_OS_LINUX || FML_OS_WIN
463 gl_proc_resolver = DefaultGLProcResolver;
464#endif // FML_OS_LINUX || FML_OS_WIN
465 }
466
467 bool fbo_reset_after_present =
468 SAFE_ACCESS(open_gl_config, fbo_reset_after_present, false);
469
471 gl_make_current, // gl_make_current_callback
472 gl_clear_current, // gl_clear_current_callback
473 gl_present, // gl_present_callback
474 gl_fbo_callback, // gl_fbo_callback
475 gl_make_resource_current_callback, // gl_make_resource_current_callback
476 gl_surface_transformation_callback, // gl_surface_transformation_callback
477 gl_proc_resolver, // gl_proc_resolver
478 gl_populate_existing_damage, // gl_populate_existing_damage
479 };
480
481 return fml::MakeCopyable(
482 [gl_dispatch_table, fbo_reset_after_present, platform_dispatch_table,
483 enable_impeller,
484 external_view_embedder =
485 std::move(external_view_embedder)](flutter::Shell& shell) mutable {
486 std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder =
487 std::move(external_view_embedder);
488 if (enable_impeller) {
489 return std::make_unique<flutter::PlatformViewEmbedder>(
490 shell, // delegate
491 shell.GetTaskRunners(), // task runners
492 std::make_unique<flutter::EmbedderSurfaceGLImpeller>(
493 gl_dispatch_table, fbo_reset_after_present,
494 view_embedder), // embedder_surface
495 platform_dispatch_table, // embedder platform dispatch table
496 view_embedder // external view embedder
497 );
498 }
499 return std::make_unique<flutter::PlatformViewEmbedder>(
500 shell, // delegate
501 shell.GetTaskRunners(), // task runners
502 std::make_unique<flutter::EmbedderSurfaceGLSkia>(
503 gl_dispatch_table, fbo_reset_after_present,
504 view_embedder), // embedder_surface
505 platform_dispatch_table, // embedder platform dispatch table
506 view_embedder // external view embedder
507 );
508 });
509#else // SHELL_ENABLE_GL
510 FML_LOG(ERROR) << "This Flutter Engine does not support OpenGL rendering.";
511 return nullptr;
512#endif // SHELL_ENABLE_GL
513}
514
517 const FlutterRendererConfig* config,
518 void* user_data,
520 platform_dispatch_table,
521 std::unique_ptr<flutter::EmbedderExternalViewEmbedder>
522 external_view_embedder,
523 bool enable_impeller) {
524 if (config->type != kMetal) {
525 return nullptr;
526 }
527
528#ifdef SHELL_ENABLE_METAL
529 std::function<bool(flutter::GPUMTLTextureInfo texture)> metal_present =
530 [ptr = config->metal.present_drawable_callback,
532 FlutterMetalTexture embedder_texture;
533 embedder_texture.struct_size = sizeof(FlutterMetalTexture);
534 embedder_texture.texture = texture.texture;
535 embedder_texture.texture_id = texture.texture_id;
536 embedder_texture.user_data = texture.destruction_context;
537 embedder_texture.destruction_callback = texture.destruction_callback;
538 return ptr(user_data, &embedder_texture);
539 };
540 auto metal_get_texture =
542 const flutter::DlISize& frame_size) -> flutter::GPUMTLTextureInfo {
543 FlutterFrameInfo frame_info = {};
544 frame_info.struct_size = sizeof(FlutterFrameInfo);
545 frame_info.size = {static_cast<uint32_t>(frame_size.width),
546 static_cast<uint32_t>(frame_size.height)};
547 flutter::GPUMTLTextureInfo texture_info;
548
549 FlutterMetalTexture metal_texture = ptr(user_data, &frame_info);
550 texture_info.texture_id = metal_texture.texture_id;
551 texture_info.texture = metal_texture.texture;
552 texture_info.destruction_callback = metal_texture.destruction_callback;
553 texture_info.destruction_context = metal_texture.user_data;
554 return texture_info;
555 };
556
557 std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder =
558 std::move(external_view_embedder);
559
560 std::unique_ptr<flutter::EmbedderSurface> embedder_surface;
561
562 if (enable_impeller) {
564 metal_dispatch_table = {
565 .present = metal_present,
566 .get_texture = metal_get_texture,
567 };
568 embedder_surface = std::make_unique<flutter::EmbedderSurfaceMetalImpeller>(
569 const_cast<flutter::GPUMTLDeviceHandle>(config->metal.device),
572 metal_dispatch_table, view_embedder);
573 } else {
574#if !SLIMPELLER
576 {
577 .present = metal_present,
578 .get_texture = metal_get_texture,
579 };
580 embedder_surface = std::make_unique<flutter::EmbedderSurfaceMetalSkia>(
581 const_cast<flutter::GPUMTLDeviceHandle>(config->metal.device),
584 metal_dispatch_table, view_embedder);
585#else // !SLIMPELLER
586 FML_LOG(FATAL) << "Impeller opt-out unavailable.";
587#endif // !SLIMPELLER
588 }
589
590 // The static leak checker gets confused by the use of fml::MakeCopyable.
591 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
592 return fml::MakeCopyable(
593 [embedder_surface = std::move(embedder_surface), platform_dispatch_table,
594 external_view_embedder = view_embedder](flutter::Shell& shell) mutable {
595 return std::make_unique<flutter::PlatformViewEmbedder>(
596 shell, // delegate
597 shell.GetTaskRunners(), // task runners
598 std::move(embedder_surface), // embedder surface
599 platform_dispatch_table, // platform dispatch table
600 std::move(external_view_embedder) // external view embedder
601 );
602 });
603#else // SHELL_ENABLE_METAL
604 FML_LOG(ERROR) << "This Flutter Engine does not support Metal rendering.";
605 return nullptr;
606#endif // SHELL_ENABLE_METAL
607}
608
611 const FlutterRendererConfig* config,
612 void* user_data,
614 platform_dispatch_table,
615 std::unique_ptr<flutter::EmbedderExternalViewEmbedder>
616 external_view_embedder,
617 bool enable_impeller) {
618 if (config->type != kVulkan) {
619 return nullptr;
620 }
621
622#ifdef SHELL_ENABLE_VULKAN
623 std::function<void*(VkInstance, const char*)>
624 vulkan_get_instance_proc_address =
626 VkInstance instance, const char* proc_name) -> void* {
627 return ptr(user_data, instance, proc_name);
628 };
629
630 auto vulkan_get_next_image =
631 [ptr = config->vulkan.get_next_image_callback,
632 user_data](const flutter::DlISize& frame_size) -> FlutterVulkanImage {
633 FlutterFrameInfo frame_info = {
634 .struct_size = sizeof(FlutterFrameInfo),
635 .size = {static_cast<uint32_t>(frame_size.width),
636 static_cast<uint32_t>(frame_size.height)},
637 };
638
639 return ptr(user_data, &frame_info);
640 };
641
642 auto vulkan_present_image_callback =
643 [ptr = config->vulkan.present_image_callback, user_data](
644 VkImage image, VkFormat format) -> bool {
645 FlutterVulkanImage image_desc = {
647 .image = reinterpret_cast<uint64_t>(image),
648 .format = static_cast<uint32_t>(format),
649 };
650 return ptr(user_data, &image_desc);
651 };
652
653 auto vk_instance = static_cast<VkInstance>(config->vulkan.instance);
654 auto proc_addr =
655 vulkan_get_instance_proc_address(vk_instance, "vkGetInstanceProcAddr");
656
657 std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder =
658 std::move(external_view_embedder);
659
660#if IMPELLER_SUPPORTS_RENDERING
661 if (enable_impeller) {
663 vulkan_dispatch_table = {
665 reinterpret_cast<PFN_vkGetInstanceProcAddr>(proc_addr),
666 .get_next_image = vulkan_get_next_image,
667 .present_image = vulkan_present_image_callback,
668 };
669
670 std::unique_ptr<flutter::EmbedderSurfaceVulkanImpeller> embedder_surface =
671 std::make_unique<flutter::EmbedderSurfaceVulkanImpeller>(
672 config->vulkan.version, vk_instance,
677 static_cast<VkPhysicalDevice>(config->vulkan.physical_device),
678 static_cast<VkDevice>(config->vulkan.device),
680 static_cast<VkQueue>(config->vulkan.queue), vulkan_dispatch_table,
681 view_embedder);
682
683 return fml::MakeCopyable(
684 [embedder_surface = std::move(embedder_surface),
685 platform_dispatch_table,
686 external_view_embedder =
687 std::move(view_embedder)](flutter::Shell& shell) mutable {
688 return std::make_unique<flutter::PlatformViewEmbedder>(
689 shell, // delegate
690 shell.GetTaskRunners(), // task runners
691 std::move(embedder_surface), // embedder surface
692 platform_dispatch_table, // platform dispatch table
693 std::move(external_view_embedder) // external view embedder
694 );
695 });
696 } else {
698 {
700 reinterpret_cast<PFN_vkGetInstanceProcAddr>(proc_addr),
701 .get_next_image = vulkan_get_next_image,
702 .present_image = vulkan_present_image_callback,
703 };
704
705 std::unique_ptr<flutter::EmbedderSurfaceVulkan> embedder_surface =
706 std::make_unique<flutter::EmbedderSurfaceVulkan>(
707 config->vulkan.version, vk_instance,
712 static_cast<VkPhysicalDevice>(config->vulkan.physical_device),
713 static_cast<VkDevice>(config->vulkan.device),
715 static_cast<VkQueue>(config->vulkan.queue), vulkan_dispatch_table,
716 view_embedder);
717
718 return fml::MakeCopyable(
719 [embedder_surface = std::move(embedder_surface),
720 platform_dispatch_table,
721 external_view_embedder =
722 std::move(view_embedder)](flutter::Shell& shell) mutable {
723 return std::make_unique<flutter::PlatformViewEmbedder>(
724 shell, // delegate
725 shell.GetTaskRunners(), // task runners
726 std::move(embedder_surface), // embedder surface
727 platform_dispatch_table, // platform dispatch table
728 std::move(external_view_embedder) // external view embedder
729 );
730 });
731 }
732#else
735 reinterpret_cast<PFN_vkGetInstanceProcAddr>(proc_addr),
736 .get_next_image = vulkan_get_next_image,
737 .present_image = vulkan_present_image_callback,
738 };
739
740 std::unique_ptr<flutter::EmbedderSurfaceVulkan> embedder_surface =
741 std::make_unique<flutter::EmbedderSurfaceVulkan>(
742 config->vulkan.version, vk_instance,
747 static_cast<VkPhysicalDevice>(config->vulkan.physical_device),
748 static_cast<VkDevice>(config->vulkan.device),
750 static_cast<VkQueue>(config->vulkan.queue), vulkan_dispatch_table,
751 view_embedder);
752
753 return fml::MakeCopyable(
754 [embedder_surface = std::move(embedder_surface), platform_dispatch_table,
755 external_view_embedder =
756 std::move(view_embedder)](flutter::Shell& shell) mutable {
757 return std::make_unique<flutter::PlatformViewEmbedder>(
758 shell, // delegate
759 shell.GetTaskRunners(), // task runners
760 std::move(embedder_surface), // embedder surface
761 platform_dispatch_table, // platform dispatch table
762 std::move(external_view_embedder) // external view embedder
763 );
764 });
765#endif // // IMPELLER_SUPPORTS_RENDERING
766#else // SHELL_ENABLE_VULKAN
767 FML_LOG(ERROR) << "This Flutter Engine does not support Vulkan rendering.";
768 return nullptr;
769#endif // SHELL_ENABLE_VULKAN
770}
771
774 const FlutterRendererConfig* config,
775 void* user_data,
777 platform_dispatch_table,
778 std::unique_ptr<flutter::EmbedderExternalViewEmbedder>
779 external_view_embedder) {
780 if (config->type != kSoftware) {
781 return nullptr;
782 }
783
784 auto software_present_backing_store =
786 const void* allocation, size_t row_bytes, size_t height) -> bool {
787 return ptr(user_data, allocation, row_bytes, height);
788 };
789
791 software_dispatch_table = {
792 software_present_backing_store, // required
793 };
794
795 return fml::MakeCopyable(
796 [software_dispatch_table, platform_dispatch_table,
797 external_view_embedder =
798 std::move(external_view_embedder)](flutter::Shell& shell) mutable {
799 return std::make_unique<flutter::PlatformViewEmbedder>(
800 shell, // delegate
801 shell.GetTaskRunners(), // task runners
802 software_dispatch_table, // software dispatch table
803 platform_dispatch_table, // platform dispatch table
804 std::move(external_view_embedder) // external view embedder
805 );
806 });
807}
808
811 const FlutterRendererConfig* config,
812 void* user_data,
814 platform_dispatch_table,
815 std::unique_ptr<flutter::EmbedderExternalViewEmbedder>
816 external_view_embedder,
817 bool enable_impeller) {
818 if (config == nullptr) {
819 return nullptr;
820 }
821
822 switch (config->type) {
823 case kOpenGL:
825 config, user_data, platform_dispatch_table,
826 std::move(external_view_embedder), enable_impeller);
827 case kSoftware:
829 config, user_data, platform_dispatch_table,
830 std::move(external_view_embedder));
831 case kMetal:
833 config, user_data, platform_dispatch_table,
834 std::move(external_view_embedder), enable_impeller);
835 case kVulkan:
837 config, user_data, platform_dispatch_table,
838 std::move(external_view_embedder), enable_impeller);
839 default:
840 return nullptr;
841 }
842 return nullptr;
843}
844
845static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore(
846 GrDirectContext* context,
847 const FlutterBackingStoreConfig& config,
849#ifdef SHELL_ENABLE_GL
850 GrGLTextureInfo texture_info;
851 texture_info.fTarget = texture->target;
852 texture_info.fID = texture->name;
853 texture_info.fFormat = texture->format;
854
855 GrBackendTexture backend_texture =
856 GrBackendTextures::MakeGL(config.size.width, config.size.height,
857 skgpu::Mipmapped::kNo, texture_info);
858
859 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
860
861 std::optional<SkColorType> color_type =
862 FlutterFormatToSkColorType(texture->format);
863 if (!color_type) {
864 return nullptr;
865 }
866
867 auto surface = SkSurfaces::WrapBackendTexture(
868 context, // context
869 backend_texture, // back-end texture
870 kBottomLeft_GrSurfaceOrigin, // surface origin
871 1, // sample count
872 color_type.value(), // color type
873 SkColorSpace::MakeSRGB(), // color space
874 &surface_properties, // surface properties
875 static_cast<SkSurfaces::TextureReleaseProc>(
876 texture->destruction_callback), // release proc
877 texture->user_data // release context
878 );
879
880 if (!surface) {
881 FML_LOG(ERROR) << "Could not wrap embedder supplied render texture.";
882 return nullptr;
883 }
884
885 return surface;
886#else
887 return nullptr;
888#endif
889}
890
891static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore(
892 GrDirectContext* context,
893 const FlutterBackingStoreConfig& config,
894 const FlutterOpenGLFramebuffer* framebuffer) {
895#ifdef SHELL_ENABLE_GL
896 GrGLFramebufferInfo framebuffer_info = {};
897 framebuffer_info.fFormat = framebuffer->target;
898 framebuffer_info.fFBOID = framebuffer->name;
899
900 auto backend_render_target =
901 GrBackendRenderTargets::MakeGL(config.size.width, // width
902 config.size.height, // height
903 1, // sample count
904 0, // stencil bits
905 framebuffer_info // framebuffer info
906 );
907
908 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
909
910 std::optional<SkColorType> color_type =
911 FlutterFormatToSkColorType(framebuffer->target);
912 if (!color_type) {
913 return nullptr;
914 }
915
916 auto surface = SkSurfaces::WrapBackendRenderTarget(
917 context, // context
918 backend_render_target, // backend render target
919 kBottomLeft_GrSurfaceOrigin, // surface origin
920 color_type.value(), // color type
921 SkColorSpace::MakeSRGB(), // color space
922 &surface_properties, // surface properties
923 static_cast<SkSurfaces::RenderTargetReleaseProc>(
924 framebuffer->destruction_callback), // release proc
925 framebuffer->user_data // release context
926 );
927
928 if (!surface) {
929 FML_LOG(ERROR) << "Could not wrap embedder supplied frame-buffer.";
930 return nullptr;
931 }
932 return surface;
933#else
934 return nullptr;
935#endif
936}
937
938static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore(
939 GrDirectContext* context,
940 const FlutterBackingStoreConfig& config,
941 const FlutterOpenGLSurface* surface) {
942#ifdef SHELL_ENABLE_GL
943 GrGLFramebufferInfo framebuffer_info = {};
944 framebuffer_info.fFormat = SAFE_ACCESS(surface, format, GL_BGRA8_EXT);
945 framebuffer_info.fFBOID = 0;
946
947 auto backend_render_target =
948 GrBackendRenderTargets::MakeGL(config.size.width, // width
949 config.size.height, // height
950 1, // sample count
951 0, // stencil bits
952 framebuffer_info // framebuffer info
953 );
954
955 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
956
957 std::optional<SkColorType> color_type =
958 FlutterFormatToSkColorType(surface->format);
959 if (!color_type) {
960 return nullptr;
961 }
962
963 auto sk_surface = SkSurfaces::WrapBackendRenderTarget(
964 context, // context
965 backend_render_target, // backend render target
966 kBottomLeft_GrSurfaceOrigin, // surface origin
967 color_type.value(), // color type
968 SkColorSpace::MakeSRGB(), // color space
969 &surface_properties, // surface properties
970 static_cast<SkSurfaces::RenderTargetReleaseProc>(
971 surface->destruction_callback), // release proc
972 surface->user_data // release context
973 );
974
975 if (!sk_surface) {
976 FML_LOG(ERROR) << "Could not wrap embedder supplied frame-buffer.";
977 return nullptr;
978 }
979 return sk_surface;
980#else
981 return nullptr;
982#endif
983}
984
985static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore(
986 GrDirectContext* context,
987 const FlutterBackingStoreConfig& config,
988 const FlutterSoftwareBackingStore* software) {
989 const auto image_info =
990 SkImageInfo::MakeN32Premul(config.size.width, config.size.height);
991
992 struct Captures {
993 VoidCallback destruction_callback;
994 void* user_data;
995 };
996 auto captures = std::make_unique<Captures>();
997 captures->destruction_callback = software->destruction_callback;
998 captures->user_data = software->user_data;
999 auto release_proc = [](void* pixels, void* context) {
1000 auto captures = reinterpret_cast<Captures*>(context);
1001 if (captures->destruction_callback) {
1002 captures->destruction_callback(captures->user_data);
1003 }
1004 delete captures;
1005 };
1006
1007 auto surface =
1008 SkSurfaces::WrapPixels(image_info, // image info
1009 const_cast<void*>(software->allocation), // pixels
1010 software->row_bytes, // row bytes
1011 release_proc, // release proc
1012 captures.get() // get context
1013 );
1014
1015 if (!surface) {
1016 FML_LOG(ERROR)
1017 << "Could not wrap embedder supplied software render buffer.";
1018 if (software->destruction_callback) {
1019 software->destruction_callback(software->user_data);
1020 }
1021 return nullptr;
1022 }
1023 if (surface) {
1024 captures.release(); // Skia has assumed ownership of the struct.
1025 }
1026 return surface;
1027}
1028
1029static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore(
1030 GrDirectContext* context,
1031 const FlutterBackingStoreConfig& config,
1032 const FlutterSoftwareBackingStore2* software) {
1033 const auto color_info = getSkColorInfo(software->pixel_format);
1034 if (!color_info) {
1035 return nullptr;
1036 }
1037
1038 const auto image_info = SkImageInfo::Make(
1039 SkISize::Make(config.size.width, config.size.height), *color_info);
1040
1041 struct Captures {
1042 VoidCallback destruction_callback;
1043 void* user_data;
1044 };
1045 auto captures = std::make_unique<Captures>();
1046 captures->destruction_callback = software->destruction_callback;
1047 captures->user_data = software->user_data;
1048 auto release_proc = [](void* pixels, void* context) {
1049 auto captures = reinterpret_cast<Captures*>(context);
1050 if (captures->destruction_callback) {
1051 captures->destruction_callback(captures->user_data);
1052 }
1053 };
1054
1055 auto surface =
1056 SkSurfaces::WrapPixels(image_info, // image info
1057 const_cast<void*>(software->allocation), // pixels
1058 software->row_bytes, // row bytes
1059 release_proc, // release proc
1060 captures.release() // release context
1061 );
1062
1063 if (!surface) {
1064 FML_LOG(ERROR)
1065 << "Could not wrap embedder supplied software render buffer.";
1066 if (software->destruction_callback) {
1067 software->destruction_callback(software->user_data);
1068 }
1069 return nullptr;
1070 }
1071 return surface;
1072}
1073
1074static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore(
1075 GrDirectContext* context,
1076 const FlutterBackingStoreConfig& config,
1077 const FlutterMetalBackingStore* metal) {
1078#if defined(SHELL_ENABLE_METAL) && !SLIMPELLER
1079 GrMtlTextureInfo texture_info;
1080 if (!metal->texture.texture) {
1081 FML_LOG(ERROR) << "Embedder supplied null Metal texture.";
1082 return nullptr;
1083 }
1084 sk_cfp<FlutterMetalTextureHandle> mtl_texture;
1085 mtl_texture.retain(metal->texture.texture);
1086 texture_info.fTexture = mtl_texture;
1087 GrBackendTexture backend_texture =
1088 GrBackendTextures::MakeMtl(config.size.width, //
1089 config.size.height, //
1090 skgpu::Mipmapped::kNo, //
1091 texture_info //
1092 );
1093
1094 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
1095
1096 auto surface = SkSurfaces::WrapBackendTexture(
1097 context, // context
1098 backend_texture, // back-end texture
1099 kTopLeft_GrSurfaceOrigin, // surface origin
1100 1, // sample count
1101 kBGRA_8888_SkColorType, // color type
1102 nullptr, // color space
1103 &surface_properties, // surface properties
1104 static_cast<SkSurfaces::TextureReleaseProc>(
1105 metal->texture.destruction_callback), // release proc
1106 metal->texture.user_data // release context
1107 );
1108
1109 if (!surface) {
1110 FML_LOG(ERROR) << "Could not wrap embedder supplied Metal render texture.";
1111 return nullptr;
1112 }
1113
1114 return surface;
1115#else
1116 return nullptr;
1117#endif
1118}
1119
1120#if defined(SHELL_ENABLE_GL) && defined(IMPELLER_SUPPORTS_RENDERING)
1121static std::optional<impeller::PixelFormat> FlutterFormatToImpellerPixelFormat(
1122 uint32_t format) {
1123 switch (format) {
1124 case GL_BGRA8_EXT:
1126 case GL_RGBA8:
1128 default:
1129 FML_LOG(ERROR) << "Cannot convert format " << format
1130 << " to impeller::PixelFormat.";
1131 return std::nullopt;
1132 }
1133}
1134
1135#endif // defined(SHELL_ENABLE_GL) && defined(IMPELLER_SUPPORTS_RENDERING)
1136
1137static std::unique_ptr<flutter::EmbedderRenderTarget>
1139 FlutterBackingStore backing_store,
1140 const fml::closure& on_release,
1141 const std::shared_ptr<impeller::AiksContext>& aiks_context,
1142 const FlutterBackingStoreConfig& config,
1143 const FlutterOpenGLFramebuffer* framebuffer) {
1144#if defined(SHELL_ENABLE_GL) && defined(IMPELLER_SUPPORTS_RENDERING)
1145 auto format = FlutterFormatToImpellerPixelFormat(framebuffer->target);
1146 if (!format.has_value()) {
1147 return nullptr;
1148 }
1149
1150 const auto& gl_context =
1151 impeller::ContextGLES::Cast(*aiks_context->GetContext());
1152 const bool implicit_msaa = aiks_context->GetContext()
1153 ->GetCapabilities()
1154 ->SupportsImplicitResolvingMSAA();
1155 const auto size = impeller::ISize(config.size.width, config.size.height);
1156
1157 impeller::TextureDescriptor color0_tex;
1158 if (implicit_msaa) {
1161 } else {
1164 }
1165 color0_tex.format = format.value();
1166 color0_tex.size = size;
1167 color0_tex.usage = static_cast<impeller::TextureUsageMask>(
1170
1173 gl_context.GetReactor(), color0_tex, framebuffer->name);
1176 if (implicit_msaa) {
1178 color0.resolve_texture = color0.texture;
1179 } else {
1181 }
1182
1183 impeller::TextureDescriptor depth_stencil_texture_desc;
1184 depth_stencil_texture_desc.format = impeller::PixelFormat::kD24UnormS8Uint;
1185 depth_stencil_texture_desc.size = size;
1186 depth_stencil_texture_desc.usage = static_cast<impeller::TextureUsageMask>(
1188 if (implicit_msaa) {
1189 depth_stencil_texture_desc.type =
1191 depth_stencil_texture_desc.sample_count = impeller::SampleCount::kCount4;
1192 } else {
1193 depth_stencil_texture_desc.type = impeller::TextureType::kTexture2D;
1194 depth_stencil_texture_desc.sample_count = impeller::SampleCount::kCount1;
1195 }
1196
1197 auto depth_stencil_tex = impeller::TextureGLES::CreatePlaceholder(
1198 gl_context.GetReactor(), depth_stencil_texture_desc);
1199
1201 depth0.clear_depth = 0;
1202 depth0.texture = depth_stencil_tex;
1205
1207 stencil0.clear_stencil = 0;
1208 stencil0.texture = depth_stencil_tex;
1211
1212 impeller::RenderTarget render_target_desc;
1213
1214 render_target_desc.SetColorAttachment(color0, 0u);
1215 render_target_desc.SetDepthAttachment(depth0);
1216 render_target_desc.SetStencilAttachment(stencil0);
1217
1218 fml::closure framebuffer_destruct =
1219 [callback = framebuffer->destruction_callback,
1220 user_data = framebuffer->user_data]() { callback(user_data); };
1221
1222 return std::make_unique<flutter::EmbedderRenderTargetImpeller>(
1223 backing_store, aiks_context,
1224 std::make_unique<impeller::RenderTarget>(std::move(render_target_desc)),
1225 on_release, framebuffer_destruct);
1226#else
1227 return nullptr;
1228#endif
1229}
1230
1231static std::unique_ptr<flutter::EmbedderRenderTarget>
1233 FlutterBackingStore backing_store,
1234 const fml::closure& on_release,
1235 const std::shared_ptr<impeller::AiksContext>& aiks_context,
1236 const FlutterBackingStoreConfig& config,
1237 const FlutterMetalBackingStore* metal) {
1238#if defined(SHELL_ENABLE_METAL) && defined(IMPELLER_SUPPORTS_RENDERING)
1239 if (!metal->texture.texture) {
1240 FML_LOG(ERROR) << "Embedder supplied null Metal texture.";
1241 return nullptr;
1242 }
1243
1244 const auto size = impeller::ISize(config.size.width, config.size.height);
1245
1246 impeller::TextureDescriptor resolve_tex_desc;
1247 resolve_tex_desc.size = size;
1250 resolve_tex_desc.usage = impeller::TextureUsage::kRenderTarget |
1252
1253 auto resolve_tex = impeller::WrapTextureMTL(
1254 resolve_tex_desc, metal->texture.texture,
1256 user_data = metal->texture.user_data]() { callback(user_data); });
1257 if (!resolve_tex) {
1258 FML_LOG(ERROR) << "Could not wrap embedder supplied Metal render texture.";
1259 return nullptr;
1260 }
1261 resolve_tex->SetLabel("ImpellerBackingStoreResolve");
1262
1263 impeller::TextureDescriptor msaa_tex_desc;
1267 msaa_tex_desc.format = resolve_tex->GetTextureDescriptor().format;
1268 msaa_tex_desc.size = size;
1270
1271 auto msaa_tex =
1272 aiks_context->GetContext()->GetResourceAllocator()->CreateTexture(
1273 msaa_tex_desc);
1274 if (!msaa_tex) {
1275 FML_LOG(ERROR) << "Could not allocate MSAA color texture.";
1276 return nullptr;
1277 }
1278 msaa_tex->SetLabel("ImpellerBackingStoreColorMSAA");
1279
1281 color0.texture = msaa_tex;
1285 color0.resolve_texture = resolve_tex;
1286
1287 impeller::RenderTarget render_target_desc;
1288 render_target_desc.SetColorAttachment(color0, 0u);
1289
1290 return std::make_unique<flutter::EmbedderRenderTargetImpeller>(
1291 backing_store, aiks_context,
1292 std::make_unique<impeller::RenderTarget>(std::move(render_target_desc)),
1293 on_release, fml::closure());
1294#else
1295 return nullptr;
1296#endif
1297}
1298
1299static sk_sp<SkSurface> MakeSkSurfaceFromBackingStore(
1300 GrDirectContext* context,
1301 const FlutterBackingStoreConfig& config,
1303#ifdef SHELL_ENABLE_VULKAN
1304 if (!vulkan->image) {
1305 FML_LOG(ERROR) << "Embedder supplied null Vulkan image.";
1306 return nullptr;
1307 }
1308 GrVkImageInfo image_info = {
1309 .fImage = reinterpret_cast<VkImage>(vulkan->image->image),
1310 .fImageTiling = VK_IMAGE_TILING_OPTIMAL,
1311 .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1312 .fFormat = static_cast<VkFormat>(vulkan->image->format),
1313 .fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1314 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
1315 VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1316 VK_IMAGE_USAGE_SAMPLED_BIT,
1317 .fSampleCount = 1,
1318 .fLevelCount = 1,
1319 };
1320 auto backend_texture = GrBackendTextures::MakeVk(
1321 config.size.width, config.size.height, image_info);
1322
1323 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
1324
1325 auto surface = SkSurfaces::WrapBackendTexture(
1326 context, // context
1327 backend_texture, // back-end texture
1328 kTopLeft_GrSurfaceOrigin, // surface origin
1329 1, // sample count
1331 static_cast<VkFormat>(vulkan->image->format)), // color type
1332 SkColorSpace::MakeSRGB(), // color space
1333 &surface_properties, // surface properties
1334 static_cast<SkSurfaces::TextureReleaseProc>(
1335 vulkan->destruction_callback), // release proc
1336 vulkan->user_data // release context
1337 );
1338
1339 if (!surface) {
1340 FML_LOG(ERROR) << "Could not wrap embedder supplied Vulkan render texture.";
1341 return nullptr;
1342 }
1343
1344 return surface;
1345#else
1346 return nullptr;
1347#endif
1348}
1349
1350static std::unique_ptr<flutter::EmbedderRenderTarget>
1352 FlutterBackingStore backing_store,
1353 sk_sp<SkSurface> skia_surface,
1354 fml::closure on_release,
1357 on_clear_current) {
1358 if (!skia_surface) {
1359 return nullptr;
1360 }
1361 return std::make_unique<flutter::EmbedderRenderTargetSkia>(
1362 backing_store, std::move(skia_surface), std::move(on_release),
1363 std::move(on_make_current), std::move(on_clear_current));
1364}
1365
1366static std::unique_ptr<flutter::EmbedderRenderTarget>
1368 sk_sp<SkSurface> skia_surface,
1369 fml::closure on_release) {
1370 return MakeRenderTargetFromSkSurface(backing_store, std::move(skia_surface),
1371 std::move(on_release), nullptr, nullptr);
1372}
1373
1374static std::unique_ptr<flutter::EmbedderRenderTarget>
1376 const FlutterCompositor* compositor,
1377 const FlutterBackingStoreConfig& config,
1378 GrDirectContext* context,
1379 const std::shared_ptr<impeller::AiksContext>& aiks_context,
1380 bool enable_impeller) {
1381 FlutterBackingStore backing_store = {};
1382 backing_store.struct_size = sizeof(backing_store);
1383
1384 // Safe access checks on the compositor struct have been performed in
1385 // InferExternalViewEmbedderFromArgs and are not necessary here.
1386 auto c_create_callback = compositor->create_backing_store_callback;
1387 auto c_collect_callback = compositor->collect_backing_store_callback;
1388
1389 {
1390 TRACE_EVENT0("flutter", "FlutterCompositorCreateBackingStore");
1391 if (!c_create_callback(&config, &backing_store, compositor->user_data)) {
1392 FML_LOG(ERROR) << "Could not create the embedder backing store.";
1393 return nullptr;
1394 }
1395 }
1396
1397 if (backing_store.struct_size != sizeof(backing_store)) {
1398 FML_LOG(ERROR) << "Embedder modified the backing store struct size.";
1399 return nullptr;
1400 }
1401
1402 // In case we return early without creating an embedder render target, the
1403 // embedder has still given us ownership of its baton which we must return
1404 // back to it. If this method is successful, the closure is released when the
1405 // render target is eventually released.
1406 fml::ScopedCleanupClosure collect_callback(
1407 [c_collect_callback, backing_store, user_data = compositor->user_data]() {
1408 TRACE_EVENT0("flutter", "FlutterCompositorCollectBackingStore");
1409 c_collect_callback(&backing_store, user_data);
1410 });
1411
1412 // No safe access checks on the renderer are necessary since we allocated
1413 // the struct.
1414
1415 std::unique_ptr<flutter::EmbedderRenderTarget> render_target;
1416
1417 switch (backing_store.type) {
1419 switch (backing_store.open_gl.type) {
1421 auto skia_surface = MakeSkSurfaceFromBackingStore(
1422 context, config, &backing_store.open_gl.texture);
1423 render_target = MakeRenderTargetFromSkSurface(
1424 backing_store, std::move(skia_surface),
1425 collect_callback.Release());
1426 break;
1427 }
1429 if (enable_impeller) {
1431 backing_store, collect_callback.Release(), aiks_context, config,
1432 &backing_store.open_gl.framebuffer);
1433 break;
1434 } else {
1435 auto skia_surface = MakeSkSurfaceFromBackingStore(
1436 context, config, &backing_store.open_gl.framebuffer);
1437 render_target = MakeRenderTargetFromSkSurface(
1438 backing_store, std::move(skia_surface),
1439 collect_callback.Release());
1440 break;
1441 }
1442 }
1443
1445 auto on_make_current =
1447 context = backing_store.open_gl.surface.user_data]()
1449 bool invalidate_api_state = false;
1450 bool ok = callback(context, &invalidate_api_state);
1451 return {ok, invalidate_api_state};
1452 };
1453
1454 auto on_clear_current =
1456 context = backing_store.open_gl.surface.user_data]()
1458 bool invalidate_api_state = false;
1459 bool ok = callback(context, &invalidate_api_state);
1460 return {ok, invalidate_api_state};
1461 };
1462
1463 if (enable_impeller) {
1464 // TODO(https://github.com/flutter/flutter/issues/151670): Implement
1465 // GL Surface backing stores for Impeller.
1466 FML_LOG(ERROR) << "Unimplemented";
1467 break;
1468 } else {
1469 auto skia_surface = MakeSkSurfaceFromBackingStore(
1470 context, config, &backing_store.open_gl.surface);
1471
1472 render_target = MakeRenderTargetFromSkSurface(
1473 backing_store, std::move(skia_surface),
1474 collect_callback.Release(), on_make_current, on_clear_current);
1475 break;
1476 }
1477 }
1478 }
1479 break;
1480 }
1481
1483 auto skia_surface = MakeSkSurfaceFromBackingStore(
1484 context, config, &backing_store.software);
1485 render_target = MakeRenderTargetFromSkSurface(
1486 backing_store, std::move(skia_surface), collect_callback.Release());
1487 break;
1488 }
1490 auto skia_surface = MakeSkSurfaceFromBackingStore(
1491 context, config, &backing_store.software2);
1492 render_target = MakeRenderTargetFromSkSurface(
1493 backing_store, std::move(skia_surface), collect_callback.Release());
1494 break;
1495 }
1497 if (enable_impeller) {
1499 backing_store, collect_callback.Release(), aiks_context, config,
1500 &backing_store.metal);
1501 } else {
1502 auto skia_surface = MakeSkSurfaceFromBackingStore(context, config,
1503 &backing_store.metal);
1504 render_target = MakeRenderTargetFromSkSurface(
1505 backing_store, std::move(skia_surface), collect_callback.Release());
1506 }
1507 break;
1508 }
1510 if (enable_impeller) {
1511 FML_LOG(ERROR) << "Unimplemented";
1512 break;
1513 } else {
1514 auto skia_surface = MakeSkSurfaceFromBackingStore(
1515 context, config, &backing_store.vulkan);
1516 render_target = MakeRenderTargetFromSkSurface(
1517 backing_store, std::move(skia_surface), collect_callback.Release());
1518 break;
1519 }
1520 }
1521 };
1522
1523 if (!render_target) {
1524 FML_LOG(ERROR) << "Could not create a surface from an embedder provided "
1525 "render target.";
1526 }
1527 return render_target;
1528}
1529
1530/// Creates an EmbedderExternalViewEmbedder.
1531///
1532/// When a non-OK status is returned, engine startup should be halted.
1535 bool enable_impeller) {
1536 if (compositor == nullptr) {
1537 return std::unique_ptr<flutter::EmbedderExternalViewEmbedder>{nullptr};
1538 }
1539
1540 auto c_create_callback =
1541 SAFE_ACCESS(compositor, create_backing_store_callback, nullptr);
1542 auto c_collect_callback =
1543 SAFE_ACCESS(compositor, collect_backing_store_callback, nullptr);
1544 auto c_present_callback =
1545 SAFE_ACCESS(compositor, present_layers_callback, nullptr);
1546 auto c_present_view_callback =
1547 SAFE_ACCESS(compositor, present_view_callback, nullptr);
1548 bool avoid_backing_store_cache =
1549 SAFE_ACCESS(compositor, avoid_backing_store_cache, false);
1550
1551 // Make sure the required callbacks are present
1552 if (!c_create_callback || !c_collect_callback) {
1554 "Required compositor callbacks absent.");
1555 }
1556 // Either the present view or the present layers callback must be provided.
1557 if ((!c_present_view_callback && !c_present_callback) ||
1558 (c_present_view_callback && c_present_callback)) {
1560 "Either present_layers_callback or "
1561 "present_view_callback must be provided but not both.");
1562 }
1563
1564 FlutterCompositor captured_compositor = *compositor;
1565
1567 create_render_target_callback =
1568 [captured_compositor, enable_impeller](
1569 GrDirectContext* context,
1570 const std::shared_ptr<impeller::AiksContext>& aiks_context,
1571 const auto& config) {
1572 return CreateEmbedderRenderTarget(&captured_compositor, config,
1573 context, aiks_context,
1574 enable_impeller);
1575 };
1576
1578 if (c_present_callback) {
1579 present_callback = [c_present_callback, user_data = compositor->user_data](
1580 FlutterViewId view_id, const auto& layers) {
1581 TRACE_EVENT0("flutter", "FlutterCompositorPresentLayers");
1582 return c_present_callback(const_cast<const FlutterLayer**>(layers.data()),
1583 layers.size(), user_data);
1584 };
1585 } else {
1586 FML_DCHECK(c_present_view_callback != nullptr);
1587 present_callback = [c_present_view_callback,
1588 user_data = compositor->user_data](
1589 FlutterViewId view_id, const auto& layers) {
1590 TRACE_EVENT0("flutter", "FlutterCompositorPresentLayers");
1591
1592 FlutterPresentViewInfo info = {
1594 .view_id = view_id,
1595 .layers = const_cast<const FlutterLayer**>(layers.data()),
1597 .user_data = user_data,
1598 };
1599
1600 return c_present_view_callback(&info);
1601 };
1602 }
1603
1604 return std::make_unique<flutter::EmbedderExternalViewEmbedder>(
1605 avoid_backing_store_cache, create_render_target_callback,
1606 present_callback);
1607}
1608
1609// Translates embedder metrics to engine metrics, or returns a string on error.
1610static std::variant<flutter::ViewportMetrics, std::string>
1612 const FlutterWindowMetricsEvent* flutter_metrics) {
1613 if (flutter_metrics == nullptr) {
1614 return "Invalid metrics handle.";
1615 }
1616
1618
1619 metrics.physical_width = SAFE_ACCESS(flutter_metrics, width, 0.0);
1620 metrics.physical_height = SAFE_ACCESS(flutter_metrics, height, 0.0);
1621 metrics.device_pixel_ratio = SAFE_ACCESS(flutter_metrics, pixel_ratio, 1.0);
1622 metrics.physical_view_inset_top =
1623 SAFE_ACCESS(flutter_metrics, physical_view_inset_top, 0.0);
1625 SAFE_ACCESS(flutter_metrics, physical_view_inset_right, 0.0);
1627 SAFE_ACCESS(flutter_metrics, physical_view_inset_bottom, 0.0);
1628 metrics.physical_view_inset_left =
1629 SAFE_ACCESS(flutter_metrics, physical_view_inset_left, 0.0);
1630 metrics.display_id = SAFE_ACCESS(flutter_metrics, display_id, 0);
1631
1632 if (metrics.device_pixel_ratio <= 0.0) {
1633 return "Device pixel ratio was invalid. It must be greater than zero.";
1634 }
1635
1636 if (metrics.physical_view_inset_top < 0 ||
1637 metrics.physical_view_inset_right < 0 ||
1638 metrics.physical_view_inset_bottom < 0 ||
1639 metrics.physical_view_inset_left < 0) {
1640 return "Physical view insets are invalid. They must be non-negative.";
1641 }
1642
1643 if (metrics.physical_view_inset_top > metrics.physical_height ||
1644 metrics.physical_view_inset_right > metrics.physical_width ||
1645 metrics.physical_view_inset_bottom > metrics.physical_height ||
1646 metrics.physical_view_inset_left > metrics.physical_width) {
1647 return "Physical view insets are invalid. They cannot be greater than "
1648 "physical height or width.";
1649 }
1650
1655
1656 return metrics;
1657}
1658
1660 std::unique_ptr<flutter::PlatformMessage> message;
1661};
1662
1663struct LoadedElfDeleter {
1664 void operator()(Dart_LoadedElf* elf) {
1665 if (elf) {
1666 ::Dart_UnloadELF(elf);
1667 }
1668 }
1669};
1670
1671using UniqueLoadedElf = std::unique_ptr<Dart_LoadedElf, LoadedElfDeleter>;
1672
1673struct _FlutterEngineAOTData {
1674 UniqueLoadedElf loaded_elf = nullptr;
1675 const uint8_t* vm_snapshot_data = nullptr;
1676 const uint8_t* vm_snapshot_instrs = nullptr;
1677 const uint8_t* vm_isolate_data = nullptr;
1678 const uint8_t* vm_isolate_instrs = nullptr;
1679};
1680
1682 const FlutterEngineAOTDataSource* source,
1683 FlutterEngineAOTData* data_out) {
1686 "AOT data can only be created in AOT mode.");
1687 } else if (!source) {
1688 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null source specified.");
1689 } else if (!data_out) {
1690 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null data_out specified.");
1691 }
1692
1693 switch (source->type) {
1695 if (!source->elf_path || !fml::IsFile(source->elf_path)) {
1697 "Invalid ELF path specified.");
1698 }
1699
1700 auto aot_data = std::make_unique<_FlutterEngineAOTData>();
1701 const char* error = nullptr;
1702
1703#if OS_FUCHSIA
1704 // TODO(gw280): https://github.com/flutter/flutter/issues/50285
1705 // Dart doesn't implement Dart_LoadELF on Fuchsia
1706 Dart_LoadedElf* loaded_elf = nullptr;
1707#else
1708 Dart_LoadedElf* loaded_elf = Dart_LoadELF(
1709 source->elf_path, // file path
1710 0, // file offset
1711 &error, // error (out)
1712 &aot_data->vm_snapshot_data, // vm snapshot data (out)
1713 &aot_data->vm_snapshot_instrs, // vm snapshot instr (out)
1714 &aot_data->vm_isolate_data, // vm isolate data (out)
1715 &aot_data->vm_isolate_instrs // vm isolate instr (out)
1716 );
1717#endif
1718
1719 if (loaded_elf == nullptr) {
1721 }
1722
1723 aot_data->loaded_elf.reset(loaded_elf);
1724
1725 *data_out = aot_data.release();
1726 return kSuccess;
1727 }
1728 }
1729
1730 return LOG_EMBEDDER_ERROR(
1732 "Invalid FlutterEngineAOTDataSourceType type specified.");
1733}
1734
1736 if (!data) {
1737 // Deleting a null object should be a no-op.
1738 return kSuccess;
1739 }
1740
1741 // Created in a unique pointer in `FlutterEngineCreateAOTData`.
1742 delete data;
1743 return kSuccess;
1744}
1745
1746// Constructs appropriate mapping callbacks if JIT snapshot locations have been
1747// explictly specified.
1749 flutter::Settings& settings) {
1750 auto make_mapping_callback = [](const char* path, bool executable) {
1751 return [path, executable]() {
1752 if (executable) {
1754 } else {
1756 }
1757 };
1758 };
1759
1760 // Users are allowed to specify only certain snapshots if they so desire.
1761 if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) {
1762 settings.vm_snapshot_data = make_mapping_callback(
1763 reinterpret_cast<const char*>(args->vm_snapshot_data), false);
1764 }
1765
1766 if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) {
1767 settings.vm_snapshot_instr = make_mapping_callback(
1768 reinterpret_cast<const char*>(args->vm_snapshot_instructions), true);
1769 }
1770
1771 if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) {
1772 settings.isolate_snapshot_data = make_mapping_callback(
1773 reinterpret_cast<const char*>(args->isolate_snapshot_data), false);
1774 }
1775
1776 if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) {
1777 settings.isolate_snapshot_instr = make_mapping_callback(
1778 reinterpret_cast<const char*>(args->isolate_snapshot_instructions),
1779 true);
1780 }
1781
1782#if !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
1783 settings.dart_library_sources_kernel = []() {
1784 return std::make_unique<fml::NonOwnedMapping>(kPlatformStrongDill,
1786 };
1787#endif // !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE ==
1788 // FLUTTER_RUNTIME_MODE_DEBUG)
1789}
1790
1792 const FlutterProjectArgs* args,
1793 flutter::Settings& settings) { // NOLINT(google-runtime-references)
1794 // There are no ownership concerns here as all mappings are owned by the
1795 // embedder and not the engine.
1796 auto make_mapping_callback = [](const uint8_t* mapping, size_t size) {
1797 return [mapping, size]() {
1798 return std::make_unique<fml::NonOwnedMapping>(mapping, size);
1799 };
1800 };
1801
1802 if (SAFE_ACCESS(args, aot_data, nullptr) != nullptr) {
1803 settings.vm_snapshot_data =
1804 make_mapping_callback(args->aot_data->vm_snapshot_data, 0);
1805
1806 settings.vm_snapshot_instr =
1807 make_mapping_callback(args->aot_data->vm_snapshot_instrs, 0);
1808
1809 settings.isolate_snapshot_data =
1810 make_mapping_callback(args->aot_data->vm_isolate_data, 0);
1811
1812 settings.isolate_snapshot_instr =
1813 make_mapping_callback(args->aot_data->vm_isolate_instrs, 0);
1814 }
1815
1816 if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) {
1817 settings.vm_snapshot_data = make_mapping_callback(
1818 args->vm_snapshot_data, SAFE_ACCESS(args, vm_snapshot_data_size, 0));
1819 }
1820
1821 if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) {
1822 settings.vm_snapshot_instr = make_mapping_callback(
1823 args->vm_snapshot_instructions,
1824 SAFE_ACCESS(args, vm_snapshot_instructions_size, 0));
1825 }
1826
1827 if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) {
1828 settings.isolate_snapshot_data =
1829 make_mapping_callback(args->isolate_snapshot_data,
1830 SAFE_ACCESS(args, isolate_snapshot_data_size, 0));
1831 }
1832
1833 if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) {
1834 settings.isolate_snapshot_instr = make_mapping_callback(
1835 args->isolate_snapshot_instructions,
1836 SAFE_ACCESS(args, isolate_snapshot_instructions_size, 0));
1837 }
1838}
1839
1840// Create a callback to notify the embedder of semantic updates
1841// using the legacy embedder callbacks 'update_semantics_node_callback' and
1842// 'update_semantics_custom_action_callback'.
1845 FlutterUpdateSemanticsNodeCallback update_semantics_node_callback,
1847 update_semantics_custom_action_callback,
1848 void* user_data) {
1849 return [update_semantics_node_callback,
1850 update_semantics_custom_action_callback, user_data](
1851 int64_t view_id, const flutter::SemanticsNodeUpdates& nodes,
1853 flutter::EmbedderSemanticsUpdate update{nodes, actions};
1854 FlutterSemanticsUpdate* update_ptr = update.get();
1855
1856 // First, queue all node and custom action updates.
1857 if (update_semantics_node_callback != nullptr) {
1858 for (size_t i = 0; i < update_ptr->nodes_count; i++) {
1859 update_semantics_node_callback(&update_ptr->nodes[i], user_data);
1860 }
1861 }
1862
1863 if (update_semantics_custom_action_callback != nullptr) {
1864 for (size_t i = 0; i < update_ptr->custom_actions_count; i++) {
1865 update_semantics_custom_action_callback(&update_ptr->custom_actions[i],
1866 user_data);
1867 }
1868 }
1869
1870 // Second, mark node and action batches completed now that all
1871 // updates are queued.
1872 if (update_semantics_node_callback != nullptr) {
1873 const FlutterSemanticsNode batch_end_sentinel = {
1874 sizeof(FlutterSemanticsNode),
1876 };
1877 update_semantics_node_callback(&batch_end_sentinel, user_data);
1878 }
1879
1880 if (update_semantics_custom_action_callback != nullptr) {
1881 const FlutterSemanticsCustomAction batch_end_sentinel = {
1884 };
1885 update_semantics_custom_action_callback(&batch_end_sentinel, user_data);
1886 }
1887 };
1888}
1889
1890// Create a callback to notify the embedder of semantic updates
1891// using the deprecated embedder callback 'update_semantics_callback'.
1894 FlutterUpdateSemanticsCallback update_semantics_callback,
1895 void* user_data) {
1896 return [update_semantics_callback, user_data](
1897 int64_t view_id, const flutter::SemanticsNodeUpdates& nodes,
1899 flutter::EmbedderSemanticsUpdate update{nodes, actions};
1900
1901 update_semantics_callback(update.get(), user_data);
1902 };
1903}
1904
1905// Create a callback to notify the embedder of semantic updates
1906// using the new embedder callback 'update_semantics_callback2'.
1909 FlutterUpdateSemanticsCallback2 update_semantics_callback,
1910 void* user_data) {
1911 return [update_semantics_callback, user_data](
1912 int64_t view_id, const flutter::SemanticsNodeUpdates& nodes,
1914 flutter::EmbedderSemanticsUpdate2 update{view_id, nodes, actions};
1915
1916 update_semantics_callback(update.get(), user_data);
1917 };
1918}
1919
1920// Creates a callback that receives semantic updates from the engine
1921// and notifies the embedder's callback(s). Returns null if the embedder
1922// did not register any callbacks.
1925 void* user_data) {
1926 // There are three variants for the embedder API's semantic update callbacks.
1927 // Create a callback that maps to the embedder's desired semantic update API.
1928 //
1929 // Handle the case where the embedder registered the callback
1930 // 'updated_semantics_callback2'
1931 if (SAFE_ACCESS(args, update_semantics_callback2, nullptr) != nullptr) {
1933 args->update_semantics_callback2, user_data);
1934 }
1935
1936 // Handle the case where the embedder registered the deprecated callback
1937 // 'update_semantics_callback'.
1938 if (SAFE_ACCESS(args, update_semantics_callback, nullptr) != nullptr) {
1940 args->update_semantics_callback, user_data);
1941 }
1942
1943 // Handle the case where the embedder registered the deprecated callbacks
1944 // 'update_semantics_node_callback' and
1945 // 'update_semantics_custom_action_callback'.
1946 FlutterUpdateSemanticsNodeCallback update_semantics_node_callback = nullptr;
1947 if (SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr) {
1948 update_semantics_node_callback = args->update_semantics_node_callback;
1949 }
1950
1952 update_semantics_custom_action_callback = nullptr;
1953 if (SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) !=
1954 nullptr) {
1955 update_semantics_custom_action_callback =
1956 args->update_semantics_custom_action_callback;
1957 }
1958
1959 if (update_semantics_node_callback != nullptr ||
1960 update_semantics_custom_action_callback != nullptr) {
1962 update_semantics_node_callback, update_semantics_custom_action_callback,
1963 user_data);
1964 }
1965
1966 // Handle the case where the embedder registered no callbacks.
1967 return nullptr;
1968}
1969
1971 const FlutterRendererConfig* config,
1972 const FlutterProjectArgs* args,
1973 void* user_data,
1975 engine_out) {
1976 auto result =
1977 FlutterEngineInitialize(version, config, args, user_data, engine_out);
1978
1979 if (result != kSuccess) {
1980 return result;
1981 }
1982
1983 return FlutterEngineRunInitialized(*engine_out);
1984}
1985
1987 const FlutterRendererConfig* config,
1988 const FlutterProjectArgs* args,
1989 void* user_data,
1991 engine_out) {
1992 // Step 0: Figure out arguments for shell creation.
1993 if (version != FLUTTER_ENGINE_VERSION) {
1994 return LOG_EMBEDDER_ERROR(
1996 "Flutter embedder version mismatch. There has been a breaking change. "
1997 "Please consult the changelog and update the embedder.");
1998 }
1999
2000 if (engine_out == nullptr) {
2002 "The engine out parameter was missing.");
2003 }
2004
2005 if (args == nullptr) {
2007 "The Flutter project arguments were missing.");
2008 }
2009
2010 if (SAFE_ACCESS(args, assets_path, nullptr) == nullptr) {
2011 return LOG_EMBEDDER_ERROR(
2013 "The assets path in the Flutter project arguments was missing.");
2014 }
2015
2016 if (SAFE_ACCESS(args, main_path__unused__, nullptr) != nullptr) {
2017 FML_LOG(WARNING)
2018 << "FlutterProjectArgs.main_path is deprecated and should be set null.";
2019 }
2020
2021 if (SAFE_ACCESS(args, packages_path__unused__, nullptr) != nullptr) {
2022 FML_LOG(WARNING) << "FlutterProjectArgs.packages_path is deprecated and "
2023 "should be set null.";
2024 }
2025
2026 if (!IsRendererValid(config)) {
2028 "The renderer configuration was invalid.");
2029 }
2030
2031 std::string icu_data_path;
2032 if (SAFE_ACCESS(args, icu_data_path, nullptr) != nullptr) {
2033 icu_data_path = SAFE_ACCESS(args, icu_data_path, nullptr);
2034 }
2035
2036#if !SLIMPELLER
2037 if (SAFE_ACCESS(args, persistent_cache_path, nullptr) != nullptr) {
2038 std::string persistent_cache_path =
2039 SAFE_ACCESS(args, persistent_cache_path, nullptr);
2041 }
2042
2043 if (SAFE_ACCESS(args, is_persistent_cache_read_only, false)) {
2045 }
2046#endif // !SLIMPELLER
2047
2048 fml::CommandLine command_line;
2049 if (SAFE_ACCESS(args, command_line_argc, 0) != 0 &&
2050 SAFE_ACCESS(args, command_line_argv, nullptr) != nullptr) {
2051 command_line = fml::CommandLineFromArgcArgv(
2052 SAFE_ACCESS(args, command_line_argc, 0),
2053 SAFE_ACCESS(args, command_line_argv, nullptr));
2054 }
2055
2056 flutter::Settings settings = flutter::SettingsFromCommandLine(command_line);
2057
2058 if (SAFE_ACCESS(args, aot_data, nullptr)) {
2059 if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) ||
2060 SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) ||
2061 SAFE_ACCESS(args, isolate_snapshot_data, nullptr) ||
2062 SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr)) {
2063 return LOG_EMBEDDER_ERROR(
2065 "Multiple AOT sources specified. Embedders should provide either "
2066 "*_snapshot_* buffers or aot_data, not both.");
2067 }
2068 }
2069
2072 } else {
2074 }
2075
2076 settings.icu_data_path = icu_data_path;
2077 settings.assets_path = args->assets_path;
2078 settings.leak_vm = !SAFE_ACCESS(args, shutdown_dart_vm_when_done, false);
2079 settings.old_gen_heap_size = SAFE_ACCESS(args, dart_old_gen_heap_size, -1);
2080
2082 // Verify the assets path contains Dart 2 kernel assets.
2083 const std::string kApplicationKernelSnapshotFileName = "kernel_blob.bin";
2084 std::string application_kernel_path = fml::paths::JoinPaths(
2086 if (!fml::IsFile(application_kernel_path)) {
2087 return LOG_EMBEDDER_ERROR(
2089 "Not running in AOT mode but could not resolve the kernel binary.");
2090 }
2092 }
2093
2094 if (SAFE_ACCESS(args, root_isolate_create_callback, nullptr) != nullptr) {
2096 SAFE_ACCESS(args, root_isolate_create_callback, nullptr);
2098 [callback, user_data](const auto& isolate) { callback(user_data); };
2099 }
2100
2101 // Wire up callback for engine and print logging.
2102 if (SAFE_ACCESS(args, log_message_callback, nullptr) != nullptr) {
2104 SAFE_ACCESS(args, log_message_callback, nullptr);
2106 const std::string& tag,
2107 const std::string& message) {
2108 callback(tag.c_str(), message.c_str(), user_data);
2109 };
2110 } else {
2111 settings.log_message_callback = [](const std::string& tag,
2112 const std::string& message) {
2113 // Fall back to logging to stdout if unspecified.
2114 if (tag.empty()) {
2115 std::cout << tag << ": ";
2116 }
2117 std::cout << message << std::endl;
2118 };
2119 }
2120
2121 if (SAFE_ACCESS(args, log_tag, nullptr) != nullptr) {
2122 settings.log_tag = SAFE_ACCESS(args, log_tag, nullptr);
2123 }
2124
2125 bool has_update_semantics_2_callback =
2126 SAFE_ACCESS(args, update_semantics_callback2, nullptr) != nullptr;
2127 bool has_update_semantics_callback =
2128 SAFE_ACCESS(args, update_semantics_callback, nullptr) != nullptr;
2129 bool has_legacy_update_semantics_callback =
2130 SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr ||
2131 SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) !=
2132 nullptr;
2133
2134 int semantic_callback_count = (has_update_semantics_2_callback ? 1 : 0) +
2135 (has_update_semantics_callback ? 1 : 0) +
2136 (has_legacy_update_semantics_callback ? 1 : 0);
2137
2138 if (semantic_callback_count > 1) {
2139 return LOG_EMBEDDER_ERROR(
2141 "Multiple semantics update callbacks provided. "
2142 "Embedders should provide either `update_semantics_callback2`, "
2143 "`update_semantics_callback`, or both "
2144 "`update_semantics_node_callback` and "
2145 "`update_semantics_custom_action_callback`.");
2146 }
2147
2149 update_semantics_callback =
2151
2153 platform_message_response_callback = nullptr;
2154 if (SAFE_ACCESS(args, platform_message_callback, nullptr) != nullptr) {
2155 platform_message_response_callback =
2156 [ptr = args->platform_message_callback,
2157 user_data](std::unique_ptr<flutter::PlatformMessage> message) {
2158 auto handle = new FlutterPlatformMessageResponseHandle();
2159 const FlutterPlatformMessage incoming_message = {
2160 sizeof(FlutterPlatformMessage), // struct_size
2161 message->channel().c_str(), // channel
2162 message->data().GetMapping(), // message
2163 message->data().GetSize(), // message_size
2164 handle, // response_handle
2165 };
2166 handle->message = std::move(message);
2167 return ptr(&incoming_message, user_data);
2168 };
2169 }
2170
2171 flutter::VsyncWaiterEmbedder::VsyncCallback vsync_callback = nullptr;
2172 if (SAFE_ACCESS(args, vsync_callback, nullptr) != nullptr) {
2173 vsync_callback = [ptr = args->vsync_callback, user_data](intptr_t baton) {
2174 return ptr(user_data, baton);
2175 };
2176 }
2177
2179 compute_platform_resolved_locale_callback = nullptr;
2180 if (SAFE_ACCESS(args, compute_platform_resolved_locale_callback, nullptr) !=
2181 nullptr) {
2182 compute_platform_resolved_locale_callback =
2183 [ptr = args->compute_platform_resolved_locale_callback](
2184 const std::vector<std::string>& supported_locales_data) {
2185 const size_t number_of_strings_per_locale = 3;
2186 size_t locale_count =
2187 supported_locales_data.size() / number_of_strings_per_locale;
2188 std::vector<FlutterLocale> supported_locales;
2189 std::vector<const FlutterLocale*> supported_locales_ptr;
2190 for (size_t i = 0; i < locale_count; ++i) {
2191 supported_locales.push_back(
2192 {.struct_size = sizeof(FlutterLocale),
2193 .language_code =
2194 supported_locales_data[i * number_of_strings_per_locale +
2195 0]
2196 .c_str(),
2197 .country_code =
2198 supported_locales_data[i * number_of_strings_per_locale +
2199 1]
2200 .c_str(),
2201 .script_code =
2202 supported_locales_data[i * number_of_strings_per_locale +
2203 2]
2204 .c_str(),
2205 .variant_code = nullptr});
2206 supported_locales_ptr.push_back(&supported_locales[i]);
2207 }
2208
2209 const FlutterLocale* result =
2210 ptr(supported_locales_ptr.data(), locale_count);
2211
2212 std::unique_ptr<std::vector<std::string>> out =
2213 std::make_unique<std::vector<std::string>>();
2214 if (result) {
2215 std::string language_code(SAFE_ACCESS(result, language_code, ""));
2216 if (language_code != "") {
2217 out->push_back(language_code);
2218 out->emplace_back(SAFE_ACCESS(result, country_code, ""));
2219 out->emplace_back(SAFE_ACCESS(result, script_code, ""));
2220 }
2221 }
2222 return out;
2223 };
2224 }
2225
2227 on_pre_engine_restart_callback = nullptr;
2228 if (SAFE_ACCESS(args, on_pre_engine_restart_callback, nullptr) != nullptr) {
2229 on_pre_engine_restart_callback = [ptr =
2230 args->on_pre_engine_restart_callback,
2231 user_data]() { return ptr(user_data); };
2232 }
2233
2235 nullptr;
2236 if (SAFE_ACCESS(args, channel_update_callback, nullptr) != nullptr) {
2237 channel_update_callback = [ptr = args->channel_update_callback, user_data](
2238 const std::string& name, bool listening) {
2239 FlutterChannelUpdate update{sizeof(FlutterChannelUpdate), name.c_str(),
2240 listening};
2241 ptr(&update, user_data);
2242 };
2243 }
2244
2246 view_focus_change_request_callback = nullptr;
2247 if (SAFE_ACCESS(args, view_focus_change_request_callback, nullptr) !=
2248 nullptr) {
2249 view_focus_change_request_callback =
2250 [ptr = args->view_focus_change_request_callback,
2252 FlutterViewFocusChangeRequest embedder_request{
2254 .view_id = request.view_id(),
2255 .state = static_cast<FlutterViewFocusState>(request.state()),
2256 .direction =
2257 static_cast<FlutterViewFocusDirection>(request.direction()),
2258 };
2259 ptr(&embedder_request, user_data);
2260 };
2261 }
2262
2263 auto external_view_embedder_result = InferExternalViewEmbedderFromArgs(
2264 SAFE_ACCESS(args, compositor, nullptr), settings.enable_impeller);
2265 if (!external_view_embedder_result.ok()) {
2266 FML_LOG(ERROR) << external_view_embedder_result.status().message();
2268 "Compositor arguments were invalid.");
2269 }
2270
2272 {
2273 update_semantics_callback, //
2274 platform_message_response_callback, //
2275 vsync_callback, //
2276 compute_platform_resolved_locale_callback, //
2277 on_pre_engine_restart_callback, //
2278 channel_update_callback, //
2279 view_focus_change_request_callback, //
2280 };
2281
2282 auto on_create_platform_view = InferPlatformViewCreationCallback(
2283 config, user_data, platform_dispatch_table,
2284 std::move(external_view_embedder_result.value()),
2285 settings.enable_impeller);
2286
2287 if (!on_create_platform_view) {
2288 return LOG_EMBEDDER_ERROR(
2290 "Could not infer platform view creation callback.");
2291 }
2292
2294 [](flutter::Shell& shell) {
2295 return std::make_unique<flutter::Rasterizer>(shell);
2296 };
2297
2298 using ExternalTextureResolver = flutter::EmbedderExternalTextureResolver;
2299 std::unique_ptr<ExternalTextureResolver> external_texture_resolver;
2300 external_texture_resolver = std::make_unique<ExternalTextureResolver>();
2301
2302#ifdef SHELL_ENABLE_GL
2304 external_texture_callback;
2305 if (config->type == kOpenGL) {
2306 const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
2307 if (SAFE_ACCESS(open_gl_config, gl_external_texture_frame_callback,
2308 nullptr) != nullptr) {
2309 external_texture_callback =
2310 [ptr = open_gl_config->gl_external_texture_frame_callback, user_data](
2311 int64_t texture_identifier, size_t width,
2312 size_t height) -> std::unique_ptr<FlutterOpenGLTexture> {
2313 std::unique_ptr<FlutterOpenGLTexture> texture =
2314 std::make_unique<FlutterOpenGLTexture>();
2315 if (!ptr(user_data, texture_identifier, width, height, texture.get())) {
2316 return nullptr;
2317 }
2318 return texture;
2319 };
2320 external_texture_resolver =
2321 std::make_unique<ExternalTextureResolver>(external_texture_callback);
2322 }
2323 }
2324#endif
2325#ifdef SHELL_ENABLE_METAL
2327 external_texture_metal_callback;
2328 if (config->type == kMetal) {
2329 const FlutterMetalRendererConfig* metal_config = &config->metal;
2330 if (SAFE_ACCESS(metal_config, external_texture_frame_callback, nullptr)) {
2331 external_texture_metal_callback =
2332 [ptr = metal_config->external_texture_frame_callback, user_data](
2333 int64_t texture_identifier, size_t width,
2334 size_t height) -> std::unique_ptr<FlutterMetalExternalTexture> {
2335 std::unique_ptr<FlutterMetalExternalTexture> texture =
2336 std::make_unique<FlutterMetalExternalTexture>();
2337 texture->struct_size = sizeof(FlutterMetalExternalTexture);
2338 if (!ptr(user_data, texture_identifier, width, height, texture.get())) {
2339 return nullptr;
2340 }
2341 return texture;
2342 };
2343 external_texture_resolver = std::make_unique<ExternalTextureResolver>(
2344 external_texture_metal_callback);
2345 }
2346 }
2347#endif
2348 auto custom_task_runners = SAFE_ACCESS(args, custom_task_runners, nullptr);
2349 auto thread_config_callback = [&custom_task_runners](
2350 const fml::Thread::ThreadConfig& config) {
2352 if (!custom_task_runners || !custom_task_runners->thread_priority_setter) {
2353 return;
2354 }
2356 switch (config.priority) {
2359 break;
2362 break;
2365 break;
2368 break;
2369 }
2370 custom_task_runners->thread_priority_setter(priority);
2371 };
2372 auto thread_host =
2374 custom_task_runners, thread_config_callback);
2375
2376 if (!thread_host || !thread_host->IsValid()) {
2378 "Could not set up or infer thread configuration "
2379 "to run the Flutter engine on.");
2380 }
2381
2382 auto task_runners = thread_host->GetTaskRunners();
2383
2384 if (!task_runners.IsValid()) {
2386 "Task runner configuration was invalid.");
2387 }
2388
2389 // Embedder supplied UI task runner runner does not have a message loop.
2390 bool has_ui_thread_message_loop =
2391 task_runners.GetUITaskRunner()->GetTaskQueueId().is_valid();
2392 // Message loop observers are used to flush the microtask queue.
2393 // If there is no message loop the queue is flushed from
2394 // EmbedderEngine::RunTask.
2395 settings.task_observer_add = [has_ui_thread_message_loop](
2396 intptr_t key, const fml::closure& callback) {
2397 if (has_ui_thread_message_loop) {
2399 }
2401 };
2402 settings.task_observer_remove = [has_ui_thread_message_loop](
2403 fml::TaskQueueId queue_id, intptr_t key) {
2404 if (has_ui_thread_message_loop) {
2406 }
2407 };
2408
2409 auto run_configuration =
2411
2412 if (SAFE_ACCESS(args, custom_dart_entrypoint, nullptr) != nullptr) {
2413 auto dart_entrypoint = std::string{args->custom_dart_entrypoint};
2414 if (!dart_entrypoint.empty()) {
2415 run_configuration.SetEntrypoint(std::move(dart_entrypoint));
2416 }
2417 }
2418
2419 if (SAFE_ACCESS(args, dart_entrypoint_argc, 0) > 0) {
2420 if (SAFE_ACCESS(args, dart_entrypoint_argv, nullptr) == nullptr) {
2422 "Could not determine Dart entrypoint arguments "
2423 "as dart_entrypoint_argc "
2424 "was set, but dart_entrypoint_argv was null.");
2425 }
2426 std::vector<std::string> arguments(args->dart_entrypoint_argc);
2427 for (int i = 0; i < args->dart_entrypoint_argc; ++i) {
2428 arguments[i] = std::string{args->dart_entrypoint_argv[i]};
2429 }
2430 run_configuration.SetEntrypointArgs(std::move(arguments));
2431 }
2432
2433 if (SAFE_ACCESS(args, engine_id, 0) != 0) {
2434 run_configuration.SetEngineId(args->engine_id);
2435 }
2436
2437 if (!run_configuration.IsValid()) {
2438 return LOG_EMBEDDER_ERROR(
2440 "Could not infer the Flutter project to run from given arguments.");
2441 }
2442
2443 // Create the engine but don't launch the shell or run the root isolate.
2444 auto embedder_engine = std::make_unique<flutter::EmbedderEngine>(
2445 std::move(thread_host), //
2446 std::move(task_runners), //
2447 std::move(settings), //
2448 std::move(run_configuration), //
2449 on_create_platform_view, //
2450 on_create_rasterizer, //
2451 std::move(external_texture_resolver) //
2452 );
2453
2454 // Release the ownership of the embedder engine to the caller.
2455 *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(
2456 embedder_engine.release());
2457 return kSuccess;
2458}
2459
2462 if (!engine) {
2463 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2464 }
2465
2466 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2467
2468 // The engine must not already be running. Initialize may only be called
2469 // once on an engine instance.
2470 if (embedder_engine->IsValid()) {
2471 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2472 }
2473
2474 // Step 1: Launch the shell.
2475 if (!embedder_engine->LaunchShell()) {
2477 "Could not launch the engine using supplied "
2478 "initialization arguments.");
2479 }
2480
2481 // Step 2: Tell the platform view to initialize itself.
2482 if (!embedder_engine->NotifyCreated()) {
2484 "Could not create platform view components.");
2485 }
2486
2487 // Step 3: Launch the root isolate.
2488 if (!embedder_engine->RunRootIsolate()) {
2489 return LOG_EMBEDDER_ERROR(
2491 "Could not run the root isolate of the Flutter application using the "
2492 "project arguments specified.");
2493 }
2494
2495 return kSuccess;
2496}
2497
2500 engine,
2501 const FlutterAddViewInfo* info) {
2502 if (!engine) {
2503 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2504 }
2505 if (!info || !info->view_metrics || !info->add_view_callback) {
2507 "Add view info handle was invalid.");
2508 }
2509
2512 return LOG_EMBEDDER_ERROR(
2514 "Add view info was invalid. The implicit view cannot be added.");
2515 }
2517 view_id) {
2520 "Add view info was invalid. The info and "
2521 "window metric view IDs must match.");
2522 }
2523 }
2524
2525 // TODO(loicsharma): Return an error if the engine was initialized with
2526 // callbacks that are incompatible with multiple views.
2527 // https://github.com/flutter/flutter/issues/144806
2528
2529 std::variant<flutter::ViewportMetrics, std::string> metrics_or_error =
2531
2532 if (const std::string* error = std::get_if<std::string>(&metrics_or_error)) {
2533 return LOG_EMBEDDER_ERROR(kInvalidArguments, error->c_str());
2534 }
2535
2536 auto metrics = std::get<flutter::ViewportMetrics>(metrics_or_error);
2537
2538 // The engine must be running to add a view.
2539 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2540 if (!embedder_engine->IsValid()) {
2541 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2542 }
2543
2545 [c_callback = info->add_view_callback,
2546 user_data = info->user_data](bool added) {
2547 FlutterAddViewResult result = {};
2548 result.struct_size = sizeof(FlutterAddViewResult);
2549 result.added = added;
2550 result.user_data = user_data;
2551 c_callback(&result);
2552 };
2553
2554 embedder_engine->GetShell().GetPlatformView()->AddView(view_id, metrics,
2555 callback);
2556 return kSuccess;
2557}
2558
2561 engine,
2562 const FlutterRemoveViewInfo* info) {
2563 if (!engine) {
2564 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2565 }
2566 if (!info || !info->remove_view_callback) {
2568 "Remove view info handle was invalid.");
2569 }
2570
2571 if (info->view_id == kFlutterImplicitViewId) {
2572 return LOG_EMBEDDER_ERROR(
2574 "Remove view info was invalid. The implicit view cannot be removed.");
2575 }
2576
2577 // TODO(loicsharma): Return an error if the engine was initialized with
2578 // callbacks that are incompatible with multiple views.
2579 // https://github.com/flutter/flutter/issues/144806
2580
2581 // The engine must be running to remove a view.
2582 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2583 if (!embedder_engine->IsValid()) {
2584 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2585 }
2586
2588 [c_callback = info->remove_view_callback,
2589 user_data = info->user_data](bool removed) {
2590 FlutterRemoveViewResult result = {};
2591 result.struct_size = sizeof(FlutterRemoveViewResult);
2592 result.removed = removed;
2593 result.user_data = user_data;
2594 c_callback(&result);
2595 };
2596
2597 embedder_engine->GetShell().GetPlatformView()->RemoveView(info->view_id,
2598 callback);
2599 return kSuccess;
2600}
2601
2604 const FlutterViewFocusEvent* event) {
2605 if (!engine) {
2606 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2607 }
2608 if (!event) {
2610 "View focus event must not be null.");
2611 }
2612 // The engine must be running to focus a view.
2613 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2614 if (!embedder_engine->IsValid()) {
2615 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2616 }
2617
2618 if (!STRUCT_HAS_MEMBER(event, direction)) {
2620 "The event struct has invalid size.");
2621 }
2622
2623 flutter::ViewFocusEvent flutter_event(
2624 event->view_id, //
2625 static_cast<flutter::ViewFocusState>(event->state),
2626 static_cast<flutter::ViewFocusDirection>(event->direction));
2627
2628 embedder_engine->GetShell().GetPlatformView()->SendViewFocusEvent(
2629 flutter_event);
2630
2631 return kSuccess;
2632}
2633
2636 engine) {
2637 if (engine == nullptr) {
2638 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2639 }
2640
2641 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2642 embedder_engine->NotifyDestroyed();
2643 embedder_engine->CollectShell();
2644 embedder_engine->CollectThreadHost();
2645 return kSuccess;
2646}
2647
2649 engine) {
2650 auto result = FlutterEngineDeinitialize(engine);
2651 if (result != kSuccess) {
2652 return result;
2653 }
2654 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2655 delete embedder_engine;
2656 return kSuccess;
2657}
2658
2661 const FlutterWindowMetricsEvent* flutter_metrics) {
2662 if (engine == nullptr || flutter_metrics == nullptr) {
2663 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2664 }
2666 SAFE_ACCESS(flutter_metrics, view_id, kFlutterImplicitViewId);
2667
2668 std::variant<flutter::ViewportMetrics, std::string> metrics_or_error =
2669 MakeViewportMetricsFromWindowMetrics(flutter_metrics);
2670 if (const std::string* error = std::get_if<std::string>(&metrics_or_error)) {
2671 return LOG_EMBEDDER_ERROR(kInvalidArguments, error->c_str());
2672 }
2673
2674 auto metrics = std::get<flutter::ViewportMetrics>(metrics_or_error);
2675
2676 return reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetViewportMetrics(
2677 view_id, metrics)
2678 ? kSuccess
2680 "Viewport metrics were invalid.");
2681}
2682
2683// Returns the flutter::PointerData::Change for the given FlutterPointerPhase.
2685 FlutterPointerPhase phase) {
2686 switch (phase) {
2687 case kCancel:
2689 case kUp:
2691 case kDown:
2693 case kMove:
2695 case kAdd:
2697 case kRemove:
2699 case kHover:
2701 case kPanZoomStart:
2703 case kPanZoomUpdate:
2705 case kPanZoomEnd:
2707 }
2709}
2710
2711// Returns the flutter::PointerData::DeviceKind for the given
2712// FlutterPointerDeviceKind.
2714 FlutterPointerDeviceKind device_kind) {
2715 switch (device_kind) {
2724 }
2726}
2727
2728// Returns the flutter::PointerData::SignalKind for the given
2729// FlutterPointerSignaKind.
2732 switch (kind) {
2741 }
2743}
2744
2745// Returns the buttons to synthesize for a PointerData from a
2746// FlutterPointerEvent with no type or buttons set.
2749 switch (change) {
2752 // These kinds of change must have a non-zero `buttons`, otherwise
2753 // gesture recognizers will ignore these events.
2763 return 0;
2764 }
2765 return 0;
2766}
2767
2770 const FlutterPointerEvent* pointers,
2771 size_t events_count) {
2772 if (engine == nullptr) {
2773 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2774 }
2775
2776 if (pointers == nullptr || events_count == 0) {
2777 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid pointer events.");
2778 }
2779
2780 auto packet = std::make_unique<flutter::PointerDataPacket>(events_count);
2781
2782 const FlutterPointerEvent* current = pointers;
2783
2784 for (size_t i = 0; i < events_count; ++i) {
2785 flutter::PointerData pointer_data;
2786 pointer_data.Clear();
2787 // this is currely in use only on android embedding.
2788 pointer_data.embedder_id = 0;
2789 pointer_data.time_stamp = SAFE_ACCESS(current, timestamp, 0);
2790 pointer_data.change = ToPointerDataChange(
2791 SAFE_ACCESS(current, phase, FlutterPointerPhase::kCancel));
2792 pointer_data.physical_x = SAFE_ACCESS(current, x, 0.0);
2793 pointer_data.physical_y = SAFE_ACCESS(current, y, 0.0);
2794 // Delta will be generated in pointer_data_packet_converter.cc.
2795 pointer_data.physical_delta_x = 0.0;
2796 pointer_data.physical_delta_y = 0.0;
2797 pointer_data.device = SAFE_ACCESS(current, device, 0);
2798 // Pointer identifier will be generated in
2799 // pointer_data_packet_converter.cc.
2800 pointer_data.pointer_identifier = 0;
2801 pointer_data.signal_kind = ToPointerDataSignalKind(
2802 SAFE_ACCESS(current, signal_kind, kFlutterPointerSignalKindNone));
2803 pointer_data.scroll_delta_x = SAFE_ACCESS(current, scroll_delta_x, 0.0);
2804 pointer_data.scroll_delta_y = SAFE_ACCESS(current, scroll_delta_y, 0.0);
2805 FlutterPointerDeviceKind device_kind =
2806 SAFE_ACCESS(current, device_kind, kFlutterPointerDeviceKindMouse);
2807 // For backwards compatibility with embedders written before the device
2808 // kind and buttons were exposed, if the device kind is not set treat it
2809 // as a mouse, with a synthesized primary button state based on the phase.
2810 if (device_kind == 0) {
2812 pointer_data.buttons =
2814
2815 } else {
2816 pointer_data.kind = ToPointerDataKind(device_kind);
2817 if (pointer_data.kind == flutter::PointerData::DeviceKind::kTouch) {
2818 // For touch events, set the button internally rather than requiring
2819 // it at the API level, since it's a confusing construction to expose.
2820 if (pointer_data.change == flutter::PointerData::Change::kDown ||
2823 }
2824 } else {
2825 // Buttons use the same mask values, so pass them through directly.
2826 pointer_data.buttons = SAFE_ACCESS(current, buttons, 0);
2827 }
2828 }
2829 pointer_data.pan_x = SAFE_ACCESS(current, pan_x, 0.0);
2830 pointer_data.pan_y = SAFE_ACCESS(current, pan_y, 0.0);
2831 // Delta will be generated in pointer_data_packet_converter.cc.
2832 pointer_data.pan_delta_x = 0.0;
2833 pointer_data.pan_delta_y = 0.0;
2834 pointer_data.scale = SAFE_ACCESS(current, scale, 0.0);
2835 pointer_data.rotation = SAFE_ACCESS(current, rotation, 0.0);
2836 pointer_data.view_id =
2838 packet->SetPointerData(i, pointer_data);
2839 current = reinterpret_cast<const FlutterPointerEvent*>(
2840 reinterpret_cast<const uint8_t*>(current) + current->struct_size);
2841 }
2842
2843 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
2844 ->DispatchPointerDataPacket(std::move(packet))
2845 ? kSuccess
2847 "Could not dispatch pointer events to the "
2848 "running Flutter application.");
2849}
2850
2852 FlutterKeyEventType event_kind) {
2853 switch (event_kind) {
2860 }
2862}
2863
2865 FlutterKeyEventDeviceType event_kind) {
2866 switch (event_kind) {
2877 }
2879}
2880
2881// Send a platform message to the framework.
2882//
2883// The `data_callback` will be invoked with `user_data`, and must not be empty.
2886 const char* channel,
2887 const uint8_t* data,
2888 size_t size,
2889 FlutterDataCallback data_callback,
2890 void* user_data) {
2891 FlutterEngineResult result;
2892
2893 FlutterPlatformMessageResponseHandle* response_handle;
2895 engine, data_callback, user_data, &response_handle);
2896 if (result != kSuccess) {
2897 return result;
2898 }
2899
2901 sizeof(FlutterPlatformMessage), // struct_size
2902 channel, // channel
2903 data, // message
2904 size, // message_size
2905 response_handle, // response_handle
2906 };
2907
2909 // Whether `SendPlatformMessage` succeeds or not, the response handle must be
2910 // released.
2911 FlutterEngineResult release_result =
2913 if (result != kSuccess) {
2914 return result;
2915 }
2916
2917 return release_result;
2918}
2919
2921 engine,
2922 const FlutterKeyEvent* event,
2924 void* user_data) {
2925 if (engine == nullptr) {
2926 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2927 }
2928
2929 if (event == nullptr) {
2930 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid key event.");
2931 }
2932
2933 const char* character = SAFE_ACCESS(event, character, nullptr);
2934
2935 flutter::KeyData key_data;
2936 key_data.Clear();
2937 key_data.timestamp = static_cast<uint64_t>(SAFE_ACCESS(event, timestamp, 0));
2938 key_data.type = MapKeyEventType(
2940 key_data.physical = SAFE_ACCESS(event, physical, 0);
2941 key_data.logical = SAFE_ACCESS(event, logical, 0);
2942 key_data.synthesized = SAFE_ACCESS(event, synthesized, false);
2944 event, device_type,
2946
2947 auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character);
2948
2949 struct MessageData {
2951 void* user_data;
2952 };
2953
2954 MessageData* message_data =
2955 new MessageData{.callback = callback, .user_data = user_data};
2956
2957 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
2959 engine, kFlutterKeyDataChannel, packet->data().data(),
2960 packet->data().size(),
2961 [](const uint8_t* data, size_t size, void* user_data) {
2962 auto message_data = std::unique_ptr<MessageData>(
2963 reinterpret_cast<MessageData*>(user_data));
2964 if (message_data->callback == nullptr) {
2965 return;
2966 }
2967 bool handled = false;
2968 if (size == 1) {
2969 handled = *data != 0;
2970 }
2971 message_data->callback(handled, message_data->user_data);
2972 },
2973 message_data);
2974}
2975
2978 const FlutterPlatformMessage* flutter_message) {
2979 if (engine == nullptr) {
2980 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
2981 }
2982
2983 if (flutter_message == nullptr) {
2984 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid message argument.");
2985 }
2986
2987 if (SAFE_ACCESS(flutter_message, channel, nullptr) == nullptr) {
2988 return LOG_EMBEDDER_ERROR(
2989 kInvalidArguments, "Message argument did not specify a valid channel.");
2990 }
2991
2992 size_t message_size = SAFE_ACCESS(flutter_message, message_size, 0);
2993 const uint8_t* message_data = SAFE_ACCESS(flutter_message, message, nullptr);
2994
2995 if (message_size != 0 && message_data == nullptr) {
2996 return LOG_EMBEDDER_ERROR(
2998 "Message size was non-zero but the message data was nullptr.");
2999 }
3000
3001 const FlutterPlatformMessageResponseHandle* response_handle =
3002 SAFE_ACCESS(flutter_message, response_handle, nullptr);
3003
3005 if (response_handle && response_handle->message) {
3006 response = response_handle->message->response();
3007 }
3008
3009 std::unique_ptr<flutter::PlatformMessage> message;
3010 if (message_size == 0) {
3011 message = std::make_unique<flutter::PlatformMessage>(
3012 flutter_message->channel, response);
3013 } else {
3014 message = std::make_unique<flutter::PlatformMessage>(
3015 flutter_message->channel,
3016 fml::MallocMapping::Copy(message_data, message_size), response);
3017 }
3018
3019 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3020 ->SendPlatformMessage(std::move(message))
3021 ? kSuccess
3023 "Could not send a message to the running "
3024 "Flutter application.");
3025}
3026
3029 FlutterDataCallback data_callback,
3030 void* user_data,
3031 FlutterPlatformMessageResponseHandle** response_out) {
3032 if (engine == nullptr) {
3033 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
3034 }
3035
3036 if (data_callback == nullptr || response_out == nullptr) {
3037 return LOG_EMBEDDER_ERROR(
3038 kInvalidArguments, "Data callback or the response handle was invalid.");
3039 }
3040
3042 [user_data, data_callback](const uint8_t* data, size_t size) {
3043 data_callback(data, size, user_data);
3044 };
3045
3046 auto platform_task_runner = reinterpret_cast<flutter::EmbedderEngine*>(engine)
3047 ->GetTaskRunners()
3048 .GetPlatformTaskRunner();
3049
3050 auto handle = new FlutterPlatformMessageResponseHandle();
3051
3052 handle->message = std::make_unique<flutter::PlatformMessage>(
3053 "", // The channel is empty and unused as the response handle is going
3054 // to referenced directly in the |FlutterEngineSendPlatformMessage|
3055 // with the container message discarded.
3056 fml::MakeRefCounted<flutter::EmbedderPlatformMessageResponse>(
3057 std::move(platform_task_runner), response_callback));
3058 *response_out = handle;
3059 return kSuccess;
3060}
3061
3065 if (engine == nullptr) {
3066 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3067 }
3068
3069 if (response == nullptr) {
3070 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid response handle.");
3071 }
3072 delete response;
3073 return kSuccess;
3074}
3075
3076// Note: This can execute on any thread.
3080 const uint8_t* data,
3081 size_t data_length) {
3082 if (data_length != 0 && data == nullptr) {
3083 return LOG_EMBEDDER_ERROR(
3085 "Data size was non zero but the pointer to the data was null.");
3086 }
3087
3088 auto response = handle->message->response();
3089
3090 if (response) {
3091 if (data_length == 0) {
3092 response->CompleteEmpty();
3093 } else {
3094 response->Complete(std::make_unique<fml::DataMapping>(
3095 std::vector<uint8_t>({data, data + data_length})));
3096 }
3097 }
3098
3099 delete handle;
3100
3101 return kSuccess;
3102}
3103
3106 return kSuccess;
3107}
3108
3111 int64_t texture_identifier) {
3112 if (engine == nullptr) {
3113 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
3114 }
3115
3116 if (texture_identifier == 0) {
3118 "Texture identifier was invalid.");
3119 }
3120 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->RegisterTexture(
3121 texture_identifier)) {
3123 "Could not register the specified texture.");
3124 }
3125 return kSuccess;
3126}
3127
3130 int64_t texture_identifier) {
3131 if (engine == nullptr) {
3132 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
3133 }
3134
3135 if (texture_identifier == 0) {
3137 "Texture identifier was invalid.");
3138 }
3139
3140 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->UnregisterTexture(
3141 texture_identifier)) {
3143 "Could not un-register the specified texture.");
3144 }
3145
3146 return kSuccess;
3147}
3148
3151 int64_t texture_identifier) {
3152 if (engine == nullptr) {
3153 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3154 }
3155 if (texture_identifier == 0) {
3156 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid texture identifier.");
3157 }
3158 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3159 ->MarkTextureFrameAvailable(texture_identifier)) {
3160 return LOG_EMBEDDER_ERROR(
3162 "Could not mark the texture frame as being available.");
3163 }
3164 return kSuccess;
3165}
3166
3169 bool enabled) {
3170 if (engine == nullptr) {
3171 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3172 }
3173 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetSemanticsEnabled(
3174 enabled)) {
3176 "Could not update semantics state.");
3177 }
3178 return kSuccess;
3179}
3180
3184 if (engine == nullptr) {
3185 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3186 }
3187 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3188 ->SetAccessibilityFeatures(flags)) {
3190 "Could not update accessibility features.");
3191 }
3192 return kSuccess;
3193}
3194
3197 uint64_t node_id,
3199 const uint8_t* data,
3200 size_t data_length) {
3204 .node_id = node_id,
3205 .action = action,
3206 .data = data,
3207 .data_length = data_length};
3209}
3210
3213 const FlutterSendSemanticsActionInfo* info) {
3214 if (engine == nullptr) {
3215 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3216 }
3217 auto engine_action = static_cast<flutter::SemanticsAction>(info->action);
3218 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3220 info->view_id, info->node_id, engine_action,
3221 fml::MallocMapping::Copy(info->data, info->data_length))) {
3223 "Could not dispatch semantics action.");
3224 }
3225 return kSuccess;
3226}
3227
3229 engine,
3230 intptr_t baton,
3231 uint64_t frame_start_time_nanos,
3232 uint64_t frame_target_time_nanos) {
3233 if (engine == nullptr) {
3234 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3235 }
3236
3237 TRACE_EVENT0("flutter", "FlutterEngineOnVsync");
3238
3239 auto start_time = fml::TimePoint::FromEpochDelta(
3240 fml::TimeDelta::FromNanoseconds(frame_start_time_nanos));
3241
3242 auto target_time = fml::TimePoint::FromEpochDelta(
3243 fml::TimeDelta::FromNanoseconds(frame_target_time_nanos));
3244
3245 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->OnVsyncEvent(
3246 baton, start_time, target_time)) {
3247 return LOG_EMBEDDER_ERROR(
3249 "Could not notify the running engine instance of a Vsync event.");
3250 }
3251
3252 return kSuccess;
3253}
3254
3257 if (engine == nullptr) {
3258 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3259 }
3260
3261 TRACE_EVENT0("flutter", "FlutterEngineReloadSystemFonts");
3262
3263 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3264 ->ReloadSystemFonts()) {
3266 "Could not reload system fonts.");
3267 }
3268
3269 return kSuccess;
3270}
3271
3273 fml::tracing::TraceEvent0("flutter", name, /*flow_id_count=*/0,
3274 /*flow_ids=*/nullptr);
3275}
3276
3277void FlutterEngineTraceEventDurationEnd(const char* name) {
3279}
3280
3281void FlutterEngineTraceEventInstant(const char* name) {
3282 fml::tracing::TraceEventInstant0("flutter", name, /*flow_id_count=*/0,
3283 /*flow_ids=*/nullptr);
3284}
3285
3289 void* baton) {
3290 if (engine == nullptr) {
3291 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3292 }
3293
3294 if (callback == nullptr) {
3296 "Render thread callback was null.");
3297 }
3298
3299 auto task = [callback, baton]() { callback(baton); };
3300
3301 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3302 ->PostRenderThreadTask(task)
3303 ? kSuccess
3305 "Could not post the render thread task.");
3306}
3307
3308uint64_t FlutterEngineGetCurrentTime() {
3310}
3311
3313 engine,
3314 const FlutterTask* task) {
3315 if (engine == nullptr) {
3316 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3317 }
3318
3320 reinterpret_cast<intptr_t>(task->runner))) {
3321 // This task came too late, the embedder has already been destroyed.
3322 // This is not an error, just ignore the task.
3323 return kSuccess;
3324 }
3325
3326 return reinterpret_cast<flutter::EmbedderEngine*>(engine)->RunTask(task)
3327 ? kSuccess
3329 "Could not run the specified task.");
3330}
3331
3333 engine,
3334 const rapidjson::Document& document,
3335 const std::string& channel_name) {
3336 if (channel_name.empty()) {
3337 return false;
3338 }
3339
3340 rapidjson::StringBuffer buffer;
3341 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
3342
3343 if (!document.Accept(writer)) {
3344 return false;
3345 }
3346
3347 const char* message = buffer.GetString();
3348
3349 if (message == nullptr || buffer.GetSize() == 0) {
3350 return false;
3351 }
3352
3353 auto platform_message = std::make_unique<flutter::PlatformMessage>(
3354 channel_name.c_str(), // channel
3356 buffer.GetSize()), // message
3357 nullptr // response
3358 );
3359
3360 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3361 ->SendPlatformMessage(std::move(platform_message));
3362}
3363
3365 engine,
3366 const FlutterLocale** locales,
3367 size_t locales_count) {
3368 if (engine == nullptr) {
3369 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3370 }
3371
3372 if (locales_count == 0) {
3373 return kSuccess;
3374 }
3375
3376 if (locales == nullptr) {
3377 return LOG_EMBEDDER_ERROR(kInvalidArguments, "No locales were specified.");
3378 }
3379
3380 rapidjson::Document document;
3381 auto& allocator = document.GetAllocator();
3382
3383 document.SetObject();
3384 document.AddMember("method", "setLocale", allocator);
3385
3386 rapidjson::Value args(rapidjson::kArrayType);
3387 args.Reserve(locales_count * 4, allocator);
3388 for (size_t i = 0; i < locales_count; ++i) {
3389 const FlutterLocale* locale = locales[i];
3390 const char* language_code_str = SAFE_ACCESS(locale, language_code, nullptr);
3391 if (language_code_str == nullptr || ::strlen(language_code_str) == 0) {
3392 return LOG_EMBEDDER_ERROR(
3394 "Language code is required but not present in FlutterLocale.");
3395 }
3396
3397 const char* country_code_str = SAFE_ACCESS(locale, country_code, "");
3398 const char* script_code_str = SAFE_ACCESS(locale, script_code, "");
3399 const char* variant_code_str = SAFE_ACCESS(locale, variant_code, "");
3400
3401 rapidjson::Value language_code, country_code, script_code, variant_code;
3402
3403 language_code.SetString(language_code_str, allocator);
3404 country_code.SetString(country_code_str ? country_code_str : "", allocator);
3405 script_code.SetString(script_code_str ? script_code_str : "", allocator);
3406 variant_code.SetString(variant_code_str ? variant_code_str : "", allocator);
3407
3408 // Required.
3409 args.PushBack(language_code, allocator);
3410 args.PushBack(country_code, allocator);
3411 args.PushBack(script_code, allocator);
3412 args.PushBack(variant_code, allocator);
3413 }
3414 document.AddMember("args", args, allocator);
3415
3416 return DispatchJSONPlatformMessage(engine, document, "flutter/localization")
3417 ? kSuccess
3419 "Could not send message to update locale of "
3420 "a running Flutter application.");
3421}
3422
3425}
3426
3430 const FlutterEngineDartObject* object) {
3431 if (engine == nullptr) {
3432 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3433 }
3434
3435 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->IsValid()) {
3436 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine not running.");
3437 }
3438
3439 if (port == ILLEGAL_PORT) {
3441 "Attempted to post to an illegal port.");
3442 }
3443
3444 if (object == nullptr) {
3446 "Invalid Dart object to post.");
3447 }
3448
3449 Dart_CObject dart_object = {};
3450 fml::ScopedCleanupClosure typed_data_finalizer;
3451
3452 switch (object->type) {
3454 dart_object.type = Dart_CObject_kNull;
3455 break;
3457 dart_object.type = Dart_CObject_kBool;
3458 dart_object.value.as_bool = object->bool_value;
3459 break;
3461 dart_object.type = Dart_CObject_kInt32;
3462 dart_object.value.as_int32 = object->int32_value;
3463 break;
3465 dart_object.type = Dart_CObject_kInt64;
3466 dart_object.value.as_int64 = object->int64_value;
3467 break;
3469 dart_object.type = Dart_CObject_kDouble;
3470 dart_object.value.as_double = object->double_value;
3471 break;
3473 if (object->string_value == nullptr) {
3475 "kFlutterEngineDartObjectTypeString must be "
3476 "a null terminated string but was null.");
3477 }
3478 dart_object.type = Dart_CObject_kString;
3479 dart_object.value.as_string = const_cast<char*>(object->string_value);
3480 break;
3482 auto* buffer = SAFE_ACCESS(object->buffer_value, buffer, nullptr);
3483 if (buffer == nullptr) {
3485 "kFlutterEngineDartObjectTypeBuffer must "
3486 "specify a buffer but found nullptr.");
3487 }
3488 auto buffer_size = SAFE_ACCESS(object->buffer_value, buffer_size, 0);
3489 auto callback =
3490 SAFE_ACCESS(object->buffer_value, buffer_collect_callback, nullptr);
3491 auto user_data = SAFE_ACCESS(object->buffer_value, user_data, nullptr);
3492
3493 // The user has provided a callback, let them manage the lifecycle of
3494 // the underlying data. If not, copy it out from the provided buffer.
3495
3496 if (callback == nullptr) {
3497 dart_object.type = Dart_CObject_kTypedData;
3498 dart_object.value.as_typed_data.type = Dart_TypedData_kUint8;
3499 dart_object.value.as_typed_data.length = buffer_size;
3500 dart_object.value.as_typed_data.values = buffer;
3501 } else {
3502 struct ExternalTypedDataPeer {
3503 void* user_data = nullptr;
3504 VoidCallback trampoline = nullptr;
3505 };
3506 auto peer = new ExternalTypedDataPeer();
3507 peer->user_data = user_data;
3508 peer->trampoline = callback;
3509 // This finalizer is set so that in case of failure of the
3510 // Dart_PostCObject below, we collect the peer. The embedder is still
3511 // responsible for collecting the buffer in case of non-kSuccess
3512 // returns from this method. This finalizer must be released in case
3513 // of kSuccess returns from this method.
3514 typed_data_finalizer.SetClosure([peer]() {
3515 // This is the tiny object we use as the peer to the Dart call so
3516 // that we can attach the a trampoline to the embedder supplied
3517 // callback. In case of error, we need to collect this object lest
3518 // we introduce a tiny leak.
3519 delete peer;
3520 });
3521 dart_object.type = Dart_CObject_kExternalTypedData;
3522 dart_object.value.as_external_typed_data.type = Dart_TypedData_kUint8;
3523 dart_object.value.as_external_typed_data.length = buffer_size;
3524 dart_object.value.as_external_typed_data.data = buffer;
3525 dart_object.value.as_external_typed_data.peer = peer;
3526 dart_object.value.as_external_typed_data.callback =
3527 +[](void* unused_isolate_callback_data, void* peer) {
3528 auto typed_peer = reinterpret_cast<ExternalTypedDataPeer*>(peer);
3529 typed_peer->trampoline(typed_peer->user_data);
3530 delete typed_peer;
3531 };
3532 }
3533 } break;
3534 default:
3535 return LOG_EMBEDDER_ERROR(
3537 "Invalid FlutterEngineDartObjectType type specified.");
3538 }
3539
3540 if (!Dart_PostCObject(port, &dart_object)) {
3542 "Could not post the object to the Dart VM.");
3543 }
3544
3545 // On a successful call, the VM takes ownership of and is responsible for
3546 // invoking the finalizer.
3547 typed_data_finalizer.Release();
3548 return kSuccess;
3549}
3550
3552 FLUTTER_API_SYMBOL(FlutterEngine) raw_engine) {
3553 auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine);
3554 if (engine == nullptr || !engine->IsValid()) {
3555 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine was invalid.");
3556 }
3557
3558 engine->GetShell().NotifyLowMemoryWarning();
3559
3560 rapidjson::Document document;
3561 auto& allocator = document.GetAllocator();
3562
3563 document.SetObject();
3564 document.AddMember("type", "memoryPressure", allocator);
3565
3566 return DispatchJSONPlatformMessage(raw_engine, document, "flutter/system")
3567 ? kSuccess
3570 "Could not dispatch the low memory notification message.");
3571}
3572
3576 void* user_data) {
3577 if (engine == nullptr) {
3578 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3579 }
3580
3581 if (callback == nullptr) {
3583 "Invalid native thread callback.");
3584 }
3585
3586 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3587 ->PostTaskOnEngineManagedNativeThreads(
3590 })
3591 ? kSuccess
3593 "Internal error while attempting to post "
3594 "tasks to all threads.");
3595}
3596
3597namespace {
3598static bool ValidDisplayConfiguration(const FlutterEngineDisplay* displays,
3599 size_t display_count) {
3600 std::set<FlutterEngineDisplayId> display_ids;
3601 for (size_t i = 0; i < display_count; i++) {
3602 if (displays[i].single_display && display_count != 1) {
3603 return false;
3604 }
3605 display_ids.insert(displays[i].display_id);
3606 }
3607
3608 return display_ids.size() == display_count;
3609}
3610} // namespace
3611
3614 const FlutterEngineDisplaysUpdateType update_type,
3615 const FlutterEngineDisplay* embedder_displays,
3616 size_t display_count) {
3617 if (raw_engine == nullptr) {
3618 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3619 }
3620
3621 if (!ValidDisplayConfiguration(embedder_displays, display_count)) {
3622 return LOG_EMBEDDER_ERROR(
3624 "Invalid FlutterEngineDisplay configuration specified.");
3625 }
3626
3627 auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine);
3628
3629 switch (update_type) {
3631 std::vector<std::unique_ptr<flutter::Display>> displays;
3632 const auto* display = embedder_displays;
3633 for (size_t i = 0; i < display_count; i++) {
3634 displays.push_back(std::make_unique<flutter::Display>(
3635 SAFE_ACCESS(display, display_id, i), //
3636 SAFE_ACCESS(display, refresh_rate, 0), //
3637 SAFE_ACCESS(display, width, 0), //
3638 SAFE_ACCESS(display, height, 0), //
3639 SAFE_ACCESS(display, device_pixel_ratio, 1)));
3640 display = reinterpret_cast<const FlutterEngineDisplay*>(
3641 reinterpret_cast<const uint8_t*>(display) + display->struct_size);
3642 }
3643 engine->GetShell().OnDisplayUpdates(std::move(displays));
3644 return kSuccess;
3645 }
3646 default:
3647 return LOG_EMBEDDER_ERROR(
3649 "Invalid FlutterEngineDisplaysUpdateType type specified.");
3650 }
3651}
3652
3654 engine) {
3655 if (engine == nullptr) {
3656 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3657 }
3658
3659 return reinterpret_cast<flutter::EmbedderEngine*>(engine)->ScheduleFrame()
3660 ? kSuccess
3662 "Could not schedule frame.");
3663}
3664
3668 void* user_data) {
3669 if (engine == nullptr) {
3670 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3671 }
3672
3673 if (callback == nullptr) {
3675 "Next frame callback was null.");
3676 }
3677
3678 flutter::EmbedderEngine* embedder_engine =
3679 reinterpret_cast<flutter::EmbedderEngine*>(engine);
3680
3681 fml::WeakPtr<flutter::PlatformView> weak_platform_view =
3682 embedder_engine->GetShell().GetPlatformView();
3683
3684 if (!weak_platform_view) {
3686 "Platform view unavailable.");
3687 }
3688
3689 weak_platform_view->SetNextFrameCallback(
3691
3692 return kSuccess;
3693}
3694
3696 FlutterEngineProcTable* table) {
3697 if (!table) {
3698 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null table specified.");
3699 }
3700#define SET_PROC(member, function) \
3701 if (STRUCT_HAS_MEMBER(table, member)) { \
3702 table->member = &function; \
3703 }
3704
3705 SET_PROC(CreateAOTData, FlutterEngineCreateAOTData);
3706 SET_PROC(CollectAOTData, FlutterEngineCollectAOTData);
3709 SET_PROC(Initialize, FlutterEngineInitialize);
3710 SET_PROC(Deinitialize, FlutterEngineDeinitialize);
3711 SET_PROC(RunInitialized, FlutterEngineRunInitialized);
3712 SET_PROC(SendWindowMetricsEvent, FlutterEngineSendWindowMetricsEvent);
3713 SET_PROC(SendPointerEvent, FlutterEngineSendPointerEvent);
3714 SET_PROC(SendKeyEvent, FlutterEngineSendKeyEvent);
3715 SET_PROC(SendPlatformMessage, FlutterEngineSendPlatformMessage);
3716 SET_PROC(PlatformMessageCreateResponseHandle,
3718 SET_PROC(PlatformMessageReleaseResponseHandle,
3720 SET_PROC(SendPlatformMessageResponse,
3722 SET_PROC(RegisterExternalTexture, FlutterEngineRegisterExternalTexture);
3723 SET_PROC(UnregisterExternalTexture, FlutterEngineUnregisterExternalTexture);
3724 SET_PROC(MarkExternalTextureFrameAvailable,
3726 SET_PROC(UpdateSemanticsEnabled, FlutterEngineUpdateSemanticsEnabled);
3727 SET_PROC(UpdateAccessibilityFeatures,
3729 SET_PROC(DispatchSemanticsAction, FlutterEngineDispatchSemanticsAction);
3730 SET_PROC(SendSemanticsAction, FlutterEngineSendSemanticsAction);
3732 SET_PROC(ReloadSystemFonts, FlutterEngineReloadSystemFonts);
3733 SET_PROC(TraceEventDurationBegin, FlutterEngineTraceEventDurationBegin);
3734 SET_PROC(TraceEventDurationEnd, FlutterEngineTraceEventDurationEnd);
3735 SET_PROC(TraceEventInstant, FlutterEngineTraceEventInstant);
3736 SET_PROC(PostRenderThreadTask, FlutterEnginePostRenderThreadTask);
3739 SET_PROC(UpdateLocales, FlutterEngineUpdateLocales);
3740 SET_PROC(RunsAOTCompiledDartCode, FlutterEngineRunsAOTCompiledDartCode);
3741 SET_PROC(PostDartObject, FlutterEnginePostDartObject);
3742 SET_PROC(NotifyLowMemoryWarning, FlutterEngineNotifyLowMemoryWarning);
3743 SET_PROC(PostCallbackOnAllNativeThreads,
3745 SET_PROC(NotifyDisplayUpdate, FlutterEngineNotifyDisplayUpdate);
3746 SET_PROC(ScheduleFrame, FlutterEngineScheduleFrame);
3747 SET_PROC(SetNextFrameCallback, FlutterEngineSetNextFrameCallback);
3749 SET_PROC(RemoveView, FlutterEngineRemoveView);
3750 SET_PROC(SendViewFocusEvent, FlutterEngineSendViewFocusEvent);
3751#undef SET_PROC
3752
3753 return kSuccess;
3754}
GLenum type
static bool IsRunningPrecompiledCode()
Checks if VM instances in the process can run precompiled code. This call can be made at any time and...
Definition dart_vm.cc:176
bool DispatchSemanticsAction(int64_t view_id, int node_id, flutter::SemanticsAction action, fml::MallocMapping args)
std::function< std::unique_ptr< FlutterOpenGLTexture >(int64_t, size_t, size_t)> ExternalTextureCallback
std::function< std::unique_ptr< FlutterMetalExternalTexture >(int64_t, size_t, size_t)> ExternalTextureCallback
std::function< bool(FlutterViewId view_id, const std::vector< const FlutterLayer * > &layers)> PresentCallback
std::function< std::unique_ptr< EmbedderRenderTarget >(GrDirectContext *context, const std::shared_ptr< impeller::AiksContext > &aiks_context, const FlutterBackingStoreConfig &config)> CreateRenderTargetCallback
std::function< void(const uint8_t *data, size_t size)> Callback
std::function< SetCurrentResult()> MakeOrClearCurrentCallback
static bool RunnerIsValid(intptr_t runner)
static std::unique_ptr< EmbedderThreadHost > CreateEmbedderOrEngineManagedThreadHost(const FlutterCustomTaskRunners *custom_task_runners, const flutter::ThreadConfigSetter &config_setter=fml::Thread::SetCurrentThreadName)
std::function< void *(const char *)> GLProcResolver
static SkColorType ColorTypeFromFormat(const VkFormat format)
static void SetCacheDirectoryPath(std::string path)
std::function< void()> OnPreEngineRestartCallback
std::function< void(int64_t view_id, flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions)> UpdateSemanticsCallback
std::function< void(std::unique_ptr< PlatformMessage >)> PlatformMessageResponseCallback
std::function< std::unique_ptr< std::vector< std::string > >(const std::vector< std::string > &supported_locale_data)> ComputePlatformResolvedLocaleCallback
std::function< void(const std::string &, bool)> ChanneUpdateCallback
std::function< void(const ViewFocusChangeRequest &)> ViewFocusChangeRequestCallback
std::function< void(bool removed)> RemoveViewCallback
std::function< void(bool added)> AddViewCallback
static RunConfiguration InferFromSettings(const Settings &settings, const fml::RefPtr< fml::TaskRunner > &io_worker=nullptr, IsolateLaunchType launch_type=IsolateLaunchType::kNewGroup)
Attempts to infer a run configuration from the settings object. This tries to create a run configurat...
const TaskRunners & GetTaskRunners() const override
If callers wish to interact directly with any shell subcomponents, they must (on the platform thread)...
Definition shell.cc:911
std::function< std::unique_ptr< T >(Shell &)> CreateCallback
Definition shell.h:121
fml::WeakPtr< PlatformView > GetPlatformView()
Platform views may only be accessed on the platform task runner.
Definition shell.cc:930
std::function< void(intptr_t)> VsyncCallback
static std::unique_ptr< FileMapping > CreateReadExecute(const std::string &path)
Definition mapping.cc:44
static std::unique_ptr< FileMapping > CreateReadOnly(const std::string &path)
Definition mapping.cc:20
static MallocMapping Copy(const T *begin, const T *end)
Definition mapping.h:162
void RemoveTaskObserver(intptr_t key)
void AddTaskObserver(intptr_t key, const fml::closure &callback)
static FML_EMBEDDER_ONLY MessageLoop & GetCurrent()
void RunExpiredTasksNow()
static fml::RefPtr< NativeLibrary > CreateForCurrentProcess()
static fml::RefPtr< NativeLibrary > Create(const char *path)
Wraps a closure that is invoked in the destructor unless released by the caller.
Definition closure.h:32
fml::closure SetClosure(const fml::closure &closure)
Definition closure.h:50
fml::closure Release()
Definition closure.h:56
static TaskQueueId Invalid()
@ kNormal
Default priority level.
@ kRaster
Suitable for thread which raster data.
@ kBackground
Suitable for threads that shouldn't disrupt high priority work.
@ kDisplay
Suitable for threads which generate data for the display.
static void SetCurrentThreadName(const ThreadConfig &config)
Definition thread.cc:135
static constexpr TimeDelta FromNanoseconds(int64_t nanos)
Definition time_delta.h:40
constexpr int64_t ToNanoseconds() const
Definition time_delta.h:61
constexpr TimeDelta ToEpochDelta() const
Definition time_point.h:52
static TimePoint Now()
Definition time_point.cc:49
static constexpr TimePoint FromEpochDelta(TimeDelta ticks)
Definition time_point.h:43
static ContextGLES & Cast(Context &base)
RenderTarget & SetColorAttachment(const ColorAttachment &attachment, size_t index)
RenderTarget & SetDepthAttachment(std::optional< DepthAttachment > attachment)
RenderTarget & SetStencilAttachment(std::optional< StencilAttachment > attachment)
static std::shared_ptr< TextureGLES > WrapFBO(std::shared_ptr< ReactorGLES > reactor, TextureDescriptor desc, GLuint fbo)
Create a texture by wrapping an external framebuffer object whose lifecycle is owned by the caller.
static std::shared_ptr< TextureGLES > CreatePlaceholder(std::shared_ptr< ReactorGLES > reactor, TextureDescriptor desc)
Create a "texture" that is never expected to be bound/unbound explicitly or initialized in any way....
int32_t x
#define SET_PROC(member, function)
void FlutterEngineTraceEventInstant(const char *name)
A profiling utility. Logs a trace duration instant event to the timeline. If the timeline is unavaila...
Definition embedder.cc:3282
static FlutterEngineResult InternalSendPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, const char *channel, const uint8_t *data, size_t size, FlutterDataCallback data_callback, void *user_data)
Definition embedder.cc:2885
FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable(FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
Mark that a new texture frame is available for a given texture identifier.
Definition embedder.cc:3150
FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterTask *task)
Inform the engine to run the specified task. This task has been given to the embedder via the Flutter...
Definition embedder.cc:3313
FlutterEngineResult FlutterEngineOnVsync(FLUTTER_API_SYMBOL(FlutterEngine) engine, intptr_t baton, uint64_t frame_start_time_nanos, uint64_t frame_target_time_nanos)
Notify the engine that a vsync event occurred. A baton passed to the platform via the vsync callback ...
Definition embedder.cc:3229
const int32_t kFlutterSemanticsNodeIdBatchEnd
Definition embedder.cc:107
const int32_t kFlutterSemanticsCustomActionIdBatchEnd
Definition embedder.cc:108
static bool IsMetalRendererConfigValid(const FlutterRendererConfig *config)
Definition embedder.cc:191
FlutterEngineResult FlutterEngineRun(size_t version, const FlutterRendererConfig *config, const FlutterProjectArgs *args, void *user_data, FLUTTER_API_SYMBOL(FlutterEngine) *engine_out)
Initialize and run a Flutter engine instance and return a handle to it. This is a convenience method ...
Definition embedder.cc:1971
FlutterEngineResult FlutterEngineRegisterExternalTexture(FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
Register an external texture with a unique (per engine) identifier. Only rendering backends that supp...
Definition embedder.cc:3110
FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterLocale **locales, size_t locales_count)
Notify a running engine instance that the locale has been updated. The preferred locale must be the f...
Definition embedder.cc:3365
const uint8_t kPlatformStrongDill[]
static flutter::Shell::CreateCallback< flutter::PlatformView > InferPlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
Definition embedder.cc:811
FlutterEngineResult FlutterEngineSendViewFocusEvent(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterViewFocusEvent *event)
Notifies the engine that platform view focus state has changed.
Definition embedder.cc:2603
FlutterEngineResult FlutterEngineGetProcAddresses(FlutterEngineProcTable *table)
Gets the table of engine function pointers.
Definition embedder.cc:3696
static bool DispatchJSONPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, const rapidjson::Document &document, const std::string &channel_name)
Definition embedder.cc:3333
FlutterEngineResult FlutterEngineScheduleFrame(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Schedule a new frame to redraw the content.
Definition embedder.cc:3654
void FlutterEngineTraceEventDurationBegin(const char *name)
A profiling utility. Logs a trace duration begin event to the timeline. If the timeline is unavailabl...
Definition embedder.cc:3273
FlutterEngineResult FlutterEngineSendWindowMetricsEvent(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterWindowMetricsEvent *flutter_metrics)
Definition embedder.cc:2660
flutter::PointerData::SignalKind ToPointerDataSignalKind(FlutterPointerSignalKind kind)
Definition embedder.cc:2731
uint64_t FlutterEngineGetCurrentTime()
Get the current time in nanoseconds from the clock used by the flutter engine. This is the system mon...
Definition embedder.cc:3309
static bool IsOpenGLRendererConfigValid(const FlutterRendererConfig *config)
Definition embedder.cc:158
FlutterEngineResult FlutterEngineSetNextFrameCallback(FLUTTER_API_SYMBOL(FlutterEngine) engine, VoidCallback callback, void *user_data)
Schedule a callback to be called after the next frame is drawn. This must be called from the platform...
Definition embedder.cc:3666
FlutterEngineResult __FlutterEngineFlushPendingTasksNow()
This API is only meant to be used by platforms that need to flush tasks on a message loop not control...
Definition embedder.cc:3105
#define LOG_EMBEDDER_ERROR(code, reason)
Definition embedder.cc:155
FlutterEngineResult FlutterEnginePostRenderThreadTask(FLUTTER_API_SYMBOL(FlutterEngine) engine, VoidCallback callback, void *baton)
Posts a task onto the Flutter render thread. Typically, this may be called from any thread as long as...
Definition embedder.cc:3287
static flutter::Shell::CreateCallback< flutter::PlatformView > InferVulkanPlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
Definition embedder.cc:611
static flutter::KeyEventDeviceType MapKeyEventDeviceType(FlutterKeyEventDeviceType event_kind)
Definition embedder.cc:2865
static bool IsRendererValid(const FlutterRendererConfig *config)
Definition embedder.cc:229
static std::unique_ptr< flutter::EmbedderRenderTarget > MakeRenderTargetFromBackingStoreImpeller(FlutterBackingStore backing_store, const fml::closure &on_release, const std::shared_ptr< impeller::AiksContext > &aiks_context, const FlutterBackingStoreConfig &config, const FlutterOpenGLFramebuffer *framebuffer)
Definition embedder.cc:1139
std::unique_ptr< Dart_LoadedElf, LoadedElfDeleter > UniqueLoadedElf
Definition embedder.cc:1672
FlutterEngineResult FlutterEngineDispatchSemanticsAction(FLUTTER_API_SYMBOL(FlutterEngine) engine, uint64_t node_id, FlutterSemanticsAction action, const uint8_t *data, size_t data_length)
Dispatch a semantics action to the specified semantics node in the implicit view.
Definition embedder.cc:3196
FlutterEngineResult FlutterEnginePostDartObject(FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterEngineDartPort port, const FlutterEngineDartObject *object)
Posts a Dart object to specified send port. The corresponding receive port for send port can be in an...
Definition embedder.cc:3428
flutter::PointerData::DeviceKind ToPointerDataKind(FlutterPointerDeviceKind device_kind)
Definition embedder.cc:2714
FLUTTER_EXPORT FlutterEngineResult FlutterEngineDeinitialize(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Stops running the Flutter engine instance. After this call, the embedder is also guaranteed that no m...
Definition embedder.cc:2636
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore(GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterOpenGLTexture *texture)
Definition embedder.cc:846
flutter::PointerData::Change ToPointerDataChange(FlutterPointerPhase phase)
Definition embedder.cc:2685
static constexpr FlutterViewId kFlutterImplicitViewId
Definition embedder.cc:110
FlutterEngineResult FlutterEnginePostCallbackOnAllNativeThreads(FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterNativeThreadCallback callback, void *user_data)
Schedule a callback to be run on all engine managed threads. The engine will attempt to service this ...
Definition embedder.cc:3574
FLUTTER_EXPORT FlutterEngineResult FlutterEngineAddView(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterAddViewInfo *info)
Adds a view.
Definition embedder.cc:2500
static std::unique_ptr< flutter::EmbedderRenderTarget > MakeRenderTargetFromSkSurface(FlutterBackingStore backing_store, sk_sp< SkSurface > skia_surface, fml::closure on_release, flutter::EmbedderRenderTarget::MakeOrClearCurrentCallback on_make_current, flutter::EmbedderRenderTarget::MakeOrClearCurrentCallback on_clear_current)
Definition embedder.cc:1352
FlutterEngineResult FlutterEngineInitialize(size_t version, const FlutterRendererConfig *config, const FlutterProjectArgs *args, void *user_data, FLUTTER_API_SYMBOL(FlutterEngine) *engine_out)
Initialize a Flutter engine instance. This does not run the Flutter application code till the Flutter...
Definition embedder.cc:1987
static std::unique_ptr< flutter::EmbedderRenderTarget > CreateEmbedderRenderTarget(const FlutterCompositor *compositor, const FlutterBackingStoreConfig &config, GrDirectContext *context, const std::shared_ptr< impeller::AiksContext > &aiks_context, bool enable_impeller)
Definition embedder.cc:1376
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV3(FlutterUpdateSemanticsCallback2 update_semantics_callback, void *user_data)
Definition embedder.cc:1909
FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures(FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterAccessibilityFeature flags)
Sets additional accessibility features.
Definition embedder.cc:3182
FlutterEngineResult FlutterEngineShutdown(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Shuts down a Flutter engine instance. The engine handle is no longer valid for any calls in the embed...
Definition embedder.cc:2649
FlutterEngineResult FlutterPlatformMessageCreateResponseHandle(FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterDataCallback data_callback, void *user_data, FlutterPlatformMessageResponseHandle **response_out)
Creates a platform message response handle that allows the embedder to set a native callback for a re...
Definition embedder.cc:3028
FlutterEngineResult FlutterEngineCollectAOTData(FlutterEngineAOTData data)
Collects the AOT data.
Definition embedder.cc:1736
FlutterEngineResult FlutterEngineNotifyDisplayUpdate(FLUTTER_API_SYMBOL(FlutterEngine) raw_engine, const FlutterEngineDisplaysUpdateType update_type, const FlutterEngineDisplay *embedder_displays, size_t display_count)
Posts updates corresponding to display changes to a running engine instance.
Definition embedder.cc:3613
FlutterEngineResult FlutterEngineSendPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessage *flutter_message)
Definition embedder.cc:2977
bool FlutterEngineRunsAOTCompiledDartCode(void)
Returns if the Flutter engine instance will run AOT compiled Dart code. This call has no threading re...
Definition embedder.cc:3424
FlutterEngineResult FlutterEngineReloadSystemFonts(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Reloads the system fonts in engine.
Definition embedder.cc:3256
static flutter::KeyEventType MapKeyEventType(FlutterKeyEventType event_kind)
Definition embedder.cc:2852
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallback(const FlutterProjectArgs *args, void *user_data)
Definition embedder.cc:1925
static flutter::Shell::CreateCallback< flutter::PlatformView > InferSoftwarePlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder)
Definition embedder.cc:774
static fml::StatusOr< std::unique_ptr< flutter::EmbedderExternalViewEmbedder > > InferExternalViewEmbedderFromArgs(const FlutterCompositor *compositor, bool enable_impeller)
Definition embedder.cc:1535
const intptr_t kPlatformStrongDillSize
#define FLUTTER_EXPORT
Definition embedder.cc:32
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV1(FlutterUpdateSemanticsNodeCallback update_semantics_node_callback, FlutterUpdateSemanticsCustomActionCallback update_semantics_custom_action_callback, void *user_data)
Definition embedder.cc:1845
FlutterEngineResult FlutterEngineSendPointerEvent(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPointerEvent *pointers, size_t events_count)
Definition embedder.cc:2769
FlutterEngineResult FlutterEngineRunInitialized(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Runs an initialized engine instance. An engine can be initialized via FlutterEngineInitialize....
Definition embedder.cc:2461
static bool IsSoftwareRendererConfigValid(const FlutterRendererConfig *config)
Definition embedder.cc:176
static flutter::Shell::CreateCallback< flutter::PlatformView > InferOpenGLPlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
Definition embedder.cc:305
void PopulateJITSnapshotMappingCallbacks(const FlutterProjectArgs *args, flutter::Settings &settings)
Definition embedder.cc:1749
static bool IsVulkanRendererConfigValid(const FlutterRendererConfig *config)
Definition embedder.cc:209
FlutterEngineResult FlutterEngineSendSemanticsAction(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterSendSemanticsActionInfo *info)
Dispatch a semantics action to the specified semantics node within a specific view.
Definition embedder.cc:3212
FlutterEngineResult FlutterEngineNotifyLowMemoryWarning(FLUTTER_API_SYMBOL(FlutterEngine) raw_engine)
Posts a low memory notification to a running engine instance. The engine will do its best to release ...
Definition embedder.cc:3552
FlutterEngineResult FlutterEngineUnregisterExternalTexture(FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
Unregister a previous texture registration.
Definition embedder.cc:3129
FlutterEngineResult FlutterEngineUpdateSemanticsEnabled(FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled)
Enable or disable accessibility semantics.
Definition embedder.cc:3168
FlutterEngineResult FlutterEngineSendKeyEvent(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterKeyEvent *event, FlutterKeyEventCallback callback, void *user_data)
Sends a key event to the engine. The framework will decide whether to handle this event in a synchron...
Definition embedder.cc:2921
static flutter::Shell::CreateCallback< flutter::PlatformView > InferMetalPlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, const flutter::PlatformViewEmbedder::PlatformDispatchTable &platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder, bool enable_impeller)
Definition embedder.cc:517
void FlutterEngineTraceEventDurationEnd(const char *name)
A profiling utility. Logs a trace duration end event to the timeline. If the timeline is unavailable ...
Definition embedder.cc:3278
FlutterEngineResult FlutterEngineSendPlatformMessageResponse(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessageResponseHandle *handle, const uint8_t *data, size_t data_length)
Send a response from the native side to a platform message from the Dart Flutter application.
Definition embedder.cc:3078
const char * kFlutterKeyDataChannel
Definition embedder.cc:132
FLUTTER_EXPORT FlutterEngineResult FlutterEngineRemoveView(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterRemoveViewInfo *info)
Removes a view.
Definition embedder.cc:2561
int64_t PointerDataButtonsForLegacyEvent(flutter::PointerData::Change change)
Definition embedder.cc:2748
void PopulateAOTSnapshotMappingCallbacks(const FlutterProjectArgs *args, flutter::Settings &settings)
Definition embedder.cc:1792
FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle(FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterPlatformMessageResponseHandle *response)
Collects the handle created using FlutterPlatformMessageCreateResponseHandle.
Definition embedder.cc:3063
flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV2(FlutterUpdateSemanticsCallback update_semantics_callback, void *user_data)
Definition embedder.cc:1894
static std::variant< flutter::ViewportMetrics, std::string > MakeViewportMetricsFromWindowMetrics(const FlutterWindowMetricsEvent *flutter_metrics)
Definition embedder.cc:1612
FlutterEngineResult FlutterEngineCreateAOTData(const FlutterEngineAOTDataSource *source, FlutterEngineAOTData *data_out)
Creates the necessary data structures to launch a Flutter Dart application in AOT mode....
Definition embedder.cc:1682
#define FLUTTER_API_SYMBOL(symbol)
Definition embedder.h:67
FlutterKeyEventDeviceType
Definition embedder.h:1352
@ kFlutterKeyEventDeviceTypeKeyboard
Definition embedder.h:1353
@ kFlutterKeyEventDeviceTypeDirectionalPad
Definition embedder.h:1354
@ kFlutterKeyEventDeviceTypeHdmi
Definition embedder.h:1357
@ kFlutterKeyEventDeviceTypeJoystick
Definition embedder.h:1356
@ kFlutterKeyEventDeviceTypeGamepad
Definition embedder.h:1355
void(* FlutterUpdateSemanticsCustomActionCallback)(const FlutterSemanticsCustomAction *, void *)
Definition embedder.h:1816
void(* FlutterUpdateSemanticsCallback)(const FlutterSemanticsUpdate *, void *)
Definition embedder.h:1820
FlutterViewFocusState
Represents the focus state of a given [FlutterView].
Definition embedder.h:1189
@ kFlutterEngineAOTDataSourceTypeElfPath
Definition embedder.h:2428
FlutterViewFocusDirection
Definition embedder.h:1170
struct _FlutterPlatformMessageResponseHandle FlutterPlatformMessageResponseHandle
Definition embedder.h:1431
@ kVulkan
Definition embedder.h:86
@ kOpenGL
Definition embedder.h:80
@ kMetal
Definition embedder.h:85
@ kSoftware
Definition embedder.h:81
void(* FlutterDataCallback)(const uint8_t *, size_t, void *)
Definition embedder.h:1453
FlutterPointerPhase
The phase of the pointer event.
Definition embedder.h:1237
@ kPanZoomUpdate
The pan/zoom updated.
Definition embedder.h:1273
@ kHover
The pointer moved while up.
Definition embedder.h:1269
@ kUp
Definition embedder.h:1245
@ kPanZoomStart
A pan/zoom started on this pointer.
Definition embedder.h:1271
@ kRemove
Definition embedder.h:1267
@ kCancel
Definition embedder.h:1238
@ kDown
Definition embedder.h:1252
@ kAdd
Definition embedder.h:1262
@ kMove
Definition embedder.h:1257
@ kPanZoomEnd
The pan/zoom ended.
Definition embedder.h:1275
FlutterAccessibilityFeature
Definition embedder.h:91
void(* FlutterNativeThreadCallback)(FlutterNativeThreadType type, void *user_data)
Definition embedder.h:2423
@ kFlutterEngineDartObjectTypeString
Definition embedder.h:2336
@ kFlutterEngineDartObjectTypeBool
Definition embedder.h:2332
@ kFlutterEngineDartObjectTypeDouble
Definition embedder.h:2335
@ kFlutterEngineDartObjectTypeInt32
Definition embedder.h:2333
@ kFlutterEngineDartObjectTypeBuffer
Definition embedder.h:2339
@ kFlutterEngineDartObjectTypeInt64
Definition embedder.h:2334
@ kFlutterEngineDartObjectTypeNull
Definition embedder.h:2331
void(* FlutterLogMessageCallback)(const char *, const char *, void *)
Definition embedder.h:2448
FlutterEngineResult
Definition embedder.h:72
@ kInternalInconsistency
Definition embedder.h:76
@ kInvalidLibraryVersion
Definition embedder.h:74
@ kInvalidArguments
Definition embedder.h:75
@ kSuccess
Definition embedder.h:73
FlutterNativeThreadType
Definition embedder.h:2404
FlutterPointerSignalKind
The type of a pointer signal.
Definition embedder.h:1299
@ kFlutterPointerSignalKindScale
Definition embedder.h:1303
@ kFlutterPointerSignalKindScrollInertiaCancel
Definition embedder.h:1302
@ kFlutterPointerSignalKindScroll
Definition embedder.h:1301
@ kFlutterPointerSignalKindNone
Definition embedder.h:1300
void(* FlutterUpdateSemanticsNodeCallback)(const FlutterSemanticsNode *, void *)
Definition embedder.h:1812
void(* VoidCallback)(void *)
Definition embedder.h:409
FlutterEngineDisplaysUpdateType
Definition embedder.h:2318
@ kFlutterEngineDisplaysUpdateTypeStartup
Definition embedder.h:2324
FlutterThreadPriority
Valid values for priority of Thread.
Definition embedder.h:369
@ kBackground
Suitable for threads that shouldn't disrupt high priority work.
Definition embedder.h:371
@ kDisplay
Suitable for threads which generate data for the display.
Definition embedder.h:375
@ kNormal
Default priority level.
Definition embedder.h:373
@ kRaster
Suitable for thread which raster data.
Definition embedder.h:377
FlutterSemanticsAction
Definition embedder.h:115
void(* FlutterKeyEventCallback)(bool, void *)
Definition embedder.h:1427
int64_t FlutterViewId
Definition embedder.h:386
FlutterKeyEventType
Definition embedder.h:1346
@ kFlutterKeyEventTypeDown
Definition embedder.h:1348
@ kFlutterKeyEventTypeUp
Definition embedder.h:1347
@ kFlutterKeyEventTypeRepeat
Definition embedder.h:1349
void(* FlutterUpdateSemanticsCallback2)(const FlutterSemanticsUpdate2 *, void *)
Definition embedder.h:1824
int64_t FlutterEngineDartPort
Definition embedder.h:2328
@ kFlutterOpenGLTargetTypeFramebuffer
Definition embedder.h:417
@ kFlutterOpenGLTargetTypeSurface
Definition embedder.h:420
@ kFlutterOpenGLTargetTypeTexture
Definition embedder.h:414
@ kFlutterBackingStoreTypeSoftware2
Definition embedder.h:2060
@ kFlutterBackingStoreTypeMetal
Specifies a Metal backing store. This is backed by a Metal texture.
Definition embedder.h:2055
@ kFlutterBackingStoreTypeVulkan
Specifies a Vulkan backing store. This is backed by a Vulkan VkImage.
Definition embedder.h:2057
@ kFlutterBackingStoreTypeSoftware
Specified an software allocation for Flutter to render into using the CPU.
Definition embedder.h:2053
@ kFlutterBackingStoreTypeOpenGL
Definition embedder.h:2051
#define FLUTTER_ENGINE_VERSION
Definition embedder.h:70
FlutterPointerDeviceKind
The device type that created a pointer event.
Definition embedder.h:1279
@ kFlutterPointerDeviceKindTouch
Definition embedder.h:1281
@ kFlutterPointerDeviceKindTrackpad
Definition embedder.h:1283
@ kFlutterPointerDeviceKindStylus
Definition embedder.h:1282
@ kFlutterPointerDeviceKindMouse
Definition embedder.h:1280
#define SAFE_EXISTS(pointer, member)
Checks if the member exists and is non-null.
#define SAFE_ACCESS(pointer, member, default_value)
#define STRUCT_HAS_MEMBER(pointer, member)
#define SAFE_EXISTS_ONE_OF(pointer, member1, member2)
Checks if exactly one of member1 or member2 exists and is non-null.
FlutterVulkanImage * image
VkPhysicalDevice physical_device
Definition main.cc:67
VkDevice device
Definition main.cc:69
FlutterEngine engine
Definition main.cc:84
VkInstance instance
Definition main.cc:64
VkQueue queue
Definition main.cc:71
VkSurfaceKHR surface
Definition main.cc:65
const FlutterLayer size_t layers_count
const FlutterLayer ** layers
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args
const gchar * channel
G_BEGIN_DECLS GBytes * message
const uint8_t uint32_t uint32_t GError ** error
uint32_t uint32_t * format
G_BEGIN_DECLS FlutterViewId view_id
FlutterDesktopBinaryReply callback
#define FML_LOG(severity)
Definition logging.h:101
#define FML_DCHECK(condition)
Definition logging.h:122
const char * name
Definition fuchsia.cc:49
std::shared_ptr< ImpellerAllocator > allocator
static const char * kApplicationKernelSnapshotFileName
FlTexture * texture
double y
std::unordered_map< int32_t, SemanticsNode > SemanticsNodeUpdates
impeller::Matrix DlMatrix
std::unordered_map< int32_t, CustomAccessibilityAction > CustomAccessibilityActionUpdates
it will be possible to load the file into Perfetto s trace viewer use test Running tests that layout and measure text will not yield consistent results across various platforms Enabling this option will make font resolution default to the Ahem test font on all disable asset Prevents usage of any non test fonts unless they were explicitly Loaded via prefetched default font Indicates whether the embedding started a prefetch of the default font manager before creating the engine run In non interactive keep the shell running after the Dart script has completed enable serial On low power devices with low core running concurrent GC tasks on threads can cause them to contend with the UI thread which could potentially lead to jank This option turns off all concurrent GC activities domain network JSON encoded network policy per domain This overrides the DisallowInsecureConnections switch Embedder can specify whether to allow or disallow insecure connections at a domain level old gen heap size
@ kPointerButtonMousePrimary
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir path
Definition switch_defs.h:52
@ kPointerButtonTouchContact
KeyEventType
Definition key_data.h:22
impeller::IRect32 DlIRect
ViewFocusDirection
Definition view_focus.h:22
Settings SettingsFromCommandLine(const fml::CommandLine &command_line, bool require_merged_platform_ui_thread)
Definition switches.cc:230
KeyEventDeviceType
Definition key_data.h:34
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set profile Make the profiler discard new samples once the profiler sample buffer is full When this flag is not the profiler sample buffer is used as a ring buffer
Definition switch_defs.h:98
std::string JoinPaths(std::initializer_list< std::string > components)
Definition paths.cc:14
void TraceEventInstant0(TraceArg category_group, TraceArg name, size_t flow_id_count, const uint64_t *flow_ids)
void TraceEvent0(TraceArg category_group, TraceArg name, size_t flow_id_count, const uint64_t *flow_ids)
void TraceEventEnd(TraceArg name)
CommandLine CommandLineFromArgcArgv(int argc, const char *const *argv)
internal::CopyableLambda< T > MakeCopyable(T lambda)
bool IsFile(const std::string &path)
std::function< void()> closure
Definition closure.h:14
std::shared_ptr< Texture > WrapTextureMTL(TextureDescriptor desc, const void *mtl_texture, std::function< void()> deletion_proc=nullptr)
ISize64 ISize
Definition size.h:162
std::optional< SkColorInfo > getSkColorInfo(FlutterSoftwarePixelFormat pixfmt)
std::vector< FlutterEngineDisplay > * displays
uint32_t color_type
int32_t height
int32_t width
UniqueLoadedElf loaded_elf
Definition embedder.cc:1675
const uint8_t * vm_isolate_instrs
Definition embedder.cc:1679
const uint8_t * vm_snapshot_instrs
Definition embedder.cc:1677
const uint8_t * vm_snapshot_data
Definition embedder.cc:1676
const uint8_t * vm_isolate_data
Definition embedder.cc:1678
std::unique_ptr< flutter::PlatformMessage > message
Definition embedder.cc:1661
FlutterAddViewCallback add_view_callback
Definition embedder.h:1117
FlutterViewId view_id
The identifier for the view to add. This must be unique.
Definition embedder.h:1097
const FlutterWindowMetricsEvent * view_metrics
Definition embedder.h:1102
void * user_data
The |FlutterAddViewInfo.user_data|.
Definition embedder.h:1081
bool added
True if the add view operation succeeded.
Definition embedder.h:1078
FlutterSize size
The size of the render target the engine expects to render into.
Definition embedder.h:2093
FlutterVulkanBackingStore vulkan
Definition embedder.h:2085
FlutterMetalBackingStore metal
Definition embedder.h:2083
FlutterBackingStoreType type
Specifies the type of backing store.
Definition embedder.h:2071
FlutterOpenGLBackingStore open_gl
The description of the OpenGL backing store.
Definition embedder.h:2077
FlutterSoftwareBackingStore software
The description of the software backing store.
Definition embedder.h:2079
FlutterSoftwareBackingStore2 software2
The description of the software backing store.
Definition embedder.h:2081
size_t struct_size
The size of this struct. Must be sizeof(FlutterBackingStore).
Definition embedder.h:2065
An update to whether a message channel has a listener set or not.
Definition embedder.h:1829
FlutterBackingStoreCreateCallback create_backing_store_callback
Definition embedder.h:2213
FlutterBackingStoreCollectCallback collect_backing_store_callback
Definition embedder.h:2218
A structure to represent a damage region.
Definition embedder.h:664
size_t num_rects
The number of rectangles within the damage region.
Definition embedder.h:668
size_t struct_size
The size of this struct. Must be sizeof(FlutterDamage).
Definition embedder.h:666
FlutterRect * damage
The actual damage region(s) in question.
Definition embedder.h:670
FlutterEngineAOTDataSourceType type
Definition embedder.h:2434
const char * elf_path
Absolute path to an ELF library file.
Definition embedder.h:2437
FlutterEngineDartObjectType type
Definition embedder.h:2387
const char * string_value
Definition embedder.h:2396
const FlutterEngineDartBuffer * buffer_value
Definition embedder.h:2397
Function-pointer-based versions of the APIs above.
Definition embedder.h:3704
size_t struct_size
The size of this struct. Must be sizeof(FlutterFrameInfo).
Definition embedder.h:681
FlutterUIntSize size
The size of the surface that will be backed by the fbo.
Definition embedder.h:683
FlutterSize size
The size of the layer (in physical pixels).
Definition embedder.h:2147
FlutterMetalTexture texture
Definition embedder.h:1974
FlutterMetalTextureFrameCallback external_texture_frame_callback
Definition embedder.h:908
FlutterMetalCommandQueueHandle present_command_queue
Alias for id<MTLCommandQueue>.
Definition embedder.h:893
FlutterMetalDeviceHandle device
Alias for id<MTLDevice>.
Definition embedder.h:891
FlutterMetalPresentCallback present_drawable_callback
Definition embedder.h:903
FlutterMetalTextureCallback get_next_drawable_callback
Definition embedder.h:898
FlutterMetalTextureHandle texture
Definition embedder.h:865
size_t struct_size
The size of this struct. Must be sizeof(FlutterMetalTexture).
Definition embedder.h:855
VoidCallback destruction_callback
Definition embedder.h:872
FlutterOpenGLSurface surface
Definition embedder.h:1923
FlutterOpenGLTexture texture
A texture for Flutter to render into.
Definition embedder.h:1917
FlutterOpenGLTargetType type
Definition embedder.h:1914
FlutterOpenGLFramebuffer framebuffer
Definition embedder.h:1920
uint32_t name
The name of the framebuffer.
Definition embedder.h:544
VoidCallback destruction_callback
Definition embedder.h:551
void * user_data
User data to be returned on the invocation of the destruction callback.
Definition embedder.h:547
ProcResolver gl_proc_resolver
Definition embedder.h:758
BoolPresentInfoCallback present_with_info
Definition embedder.h:782
TextureFrameCallback gl_external_texture_frame_callback
Definition embedder.h:763
FlutterFrameBufferWithDamageCallback populate_existing_damage
Definition embedder.h:796
TransformationCallback surface_transformation
Definition embedder.h:757
BoolCallback make_resource_current
Definition embedder.h:741
UIntFrameInfoCallback fbo_with_frame_info_callback
Definition embedder.h:771
FlutterOpenGLSurfaceCallback clear_current_callback
Definition embedder.h:594
FlutterOpenGLSurfaceCallback make_current_callback
Definition embedder.h:577
const char * channel
Definition embedder.h:1437
size_t struct_size
The size of this struct. Must be sizeof(FlutterPointerEvent).
Definition embedder.h:1308
size_t struct_size
The size of this struct. Must be sizeof(FlutterPresentInfo).
Definition embedder.h:703
A structure to represent a rectangle.
Definition embedder.h:641
double bottom
Definition embedder.h:645
double top
Definition embedder.h:643
double left
Definition embedder.h:642
double right
Definition embedder.h:644
FlutterRemoveViewCallback remove_view_callback
Definition embedder.h:1165
FlutterViewId view_id
Definition embedder.h:1148
void * user_data
The |FlutterRemoveViewInfo.user_data|.
Definition embedder.h:1129
bool removed
True if the remove view operation succeeded.
Definition embedder.h:1126
FlutterVulkanRendererConfig vulkan
Definition embedder.h:1036
FlutterMetalRendererConfig metal
Definition embedder.h:1035
FlutterSoftwareRendererConfig software
Definition embedder.h:1034
FlutterOpenGLRendererConfig open_gl
Definition embedder.h:1033
FlutterRendererType type
Definition embedder.h:1031
FlutterSemanticsNode * nodes
Definition embedder.h:1788
size_t nodes_count
The number of semantics node updates.
Definition embedder.h:1786
size_t custom_actions_count
The number of semantics custom action updates.
Definition embedder.h:1790
FlutterSemanticsCustomAction * custom_actions
Array of semantics custom actions. Has length custom_actions_count.
Definition embedder.h:1792
FlutterViewId view_id
The ID of the view that includes the node.
Definition embedder.h:2774
FlutterSemanticsAction action
The semantics action.
Definition embedder.h:2780
size_t data_length
The data length.
Definition embedder.h:2786
uint64_t node_id
The semantics node identifier.
Definition embedder.h:2777
const uint8_t * data
Data associated with the action.
Definition embedder.h:2783
double height
Definition embedder.h:629
double width
Definition embedder.h:628
VoidCallback destruction_callback
Definition embedder.h:1960
size_t row_bytes
The number of bytes in a single row of the allocation.
Definition embedder.h:1951
FlutterSoftwarePixelFormat pixel_format
Definition embedder.h:1964
VoidCallback destruction_callback
Definition embedder.h:1941
size_t row_bytes
The number of bytes in a single row of the allocation.
Definition embedder.h:1932
SoftwareSurfacePresentCallback surface_present_callback
Definition embedder.h:1027
FlutterTaskRunner runner
Definition embedder.h:1849
double transY
vertical translation
Definition embedder.h:400
double pers2
perspective scale factor
Definition embedder.h:406
double skewX
horizontal skew factor
Definition embedder.h:392
double pers0
input x-axis perspective factor
Definition embedder.h:402
double scaleX
horizontal scale factor
Definition embedder.h:390
double skewY
vertical skew factor
Definition embedder.h:396
double scaleY
vertical scale factor
Definition embedder.h:398
double pers1
input y-axis perspective factor
Definition embedder.h:404
double transX
horizontal translation
Definition embedder.h:394
uint32_t width
Definition embedder.h:636
FlutterViewFocusState state
The focus state of the view.
Definition embedder.h:1210
FlutterViewFocusDirection direction
The direction in which the focus transitioned across [FlutterView]s.
Definition embedder.h:1213
FlutterViewId view_id
The identifier of the view that received the focus event.
Definition embedder.h:1207
size_t struct_size
The size of this struct. Must be sizeof(FlutterVulkanImage).
Definition embedder.h:928
uint32_t format
The VkFormat of the image (for example: VK_FORMAT_R8G8B8A8_UNORM).
Definition embedder.h:933
FlutterVulkanQueueHandle queue
Definition embedder.h:977
FlutterVulkanDeviceHandle device
Definition embedder.h:968
FlutterVulkanInstanceProcAddressCallback get_instance_proc_address_callback
Definition embedder.h:1006
size_t enabled_instance_extension_count
Definition embedder.h:980
uint32_t queue_family_index
The queue family index of the VkQueue supplied in the next field.
Definition embedder.h:970
FlutterVulkanImageCallback get_next_image_callback
Definition embedder.h:1010
const char ** enabled_instance_extensions
Definition embedder.h:987
const char ** enabled_device_extensions
Definition embedder.h:998
FlutterVulkanInstanceHandle instance
Definition embedder.h:963
FlutterVulkanPresentCallback present_image_callback
Definition embedder.h:1016
FlutterVulkanPhysicalDeviceHandle physical_device
VkPhysicalDevice handle.
Definition embedder.h:965
void operator()(Dart_LoadedElf *elf)
Definition embedder.cc:1665
GPUMTLDestructionCallback destruction_callback
uint64_t synthesized
Definition key_data.h:70
KeyEventDeviceType device_type
Definition key_data.h:71
uint64_t logical
Definition key_data.h:66
uint64_t physical
Definition key_data.h:65
KeyEventType type
Definition key_data.h:64
uint64_t timestamp
Definition key_data.h:63
std::string application_kernel_asset
Definition settings.h:140
LogMessageCallback log_message_callback
Definition settings.h:316
MappingCallback isolate_snapshot_instr
Definition settings.h:123
std::function< void(const DartIsolate &)> root_isolate_create_callback
Definition settings.h:285
std::string assets_path
Definition settings.h:333
TaskObserverRemove task_observer_remove
Definition settings.h:282
MappingCallback isolate_snapshot_data
Definition settings.h:121
MappingCallback vm_snapshot_data
Definition settings.h:116
TaskObserverAdd task_observer_add
Definition settings.h:281
std::string log_tag
Definition settings.h:320
std::string icu_data_path
Definition settings.h:327
MappingCallback vm_snapshot_instr
Definition settings.h:118
MappingCallback dart_library_sources_kernel
Definition settings.h:129
int64_t old_gen_heap_size
Definition settings.h:352
The ThreadConfig is the thread info include thread name, thread priority.
Definition thread.h:35
std::shared_ptr< Texture > resolve_texture
Definition formats.h:662
LoadAction load_action
Definition formats.h:663
std::shared_ptr< Texture > texture
Definition formats.h:661
StoreAction store_action
Definition formats.h:664
static constexpr Color DarkSlateGray()
Definition color.h:418
constexpr auto GetBottom() const
Definition rect.h:357
constexpr auto GetTop() const
Definition rect.h:353
constexpr auto GetLeft() const
Definition rect.h:351
constexpr auto GetRight() const
Definition rect.h:355
static constexpr TRect MakeLTRB(Type left, Type top, Type right, Type bottom)
Definition rect.h:129
A lightweight object that describes the attributes of a texture that can then used an allocator to cr...
std::shared_ptr< const fml::Mapping > data
const uintptr_t id
#define TRACE_EVENT0(category_group, name)
#define GetCurrentTime()

◆ RAPIDJSON_HAS_STDSTRING

#define RAPIDJSON_HAS_STDSTRING   1

Definition at line 6 of file embedder.cc.

◆ SET_PROC

#define SET_PROC (   member,
  function 
)
Value:
if (STRUCT_HAS_MEMBER(table, member)) { \
table->member = &function; \
}
Dart_NativeFunction function
Definition fuchsia.cc:50

Typedef Documentation

◆ UniqueLoadedElf

using UniqueLoadedElf = std::unique_ptr<Dart_LoadedElf, LoadedElfDeleter>

Definition at line 1672 of file embedder.cc.

Function Documentation

◆ __FlutterEngineFlushPendingTasksNow()

FlutterEngineResult __FlutterEngineFlushPendingTasksNow ( )

This API is only meant to be used by platforms that need to flush tasks on a message loop not controlled by the Flutter engine.

Returns
The result of the call.

Definition at line 3105 of file embedder.cc.

3105 {
3107 return kSuccess;
3108}

References fml::MessageLoop::GetCurrent(), kSuccess, and fml::MessageLoop::RunExpiredTasksNow().

◆ CreateEmbedderRenderTarget()

static std::unique_ptr< flutter::EmbedderRenderTarget > CreateEmbedderRenderTarget ( const FlutterCompositor compositor,
const FlutterBackingStoreConfig config,
GrDirectContext *  context,
const std::shared_ptr< impeller::AiksContext > &  aiks_context,
bool  enable_impeller 
)
static

Definition at line 1376 of file embedder.cc.

1381 {
1382 FlutterBackingStore backing_store = {};
1383 backing_store.struct_size = sizeof(backing_store);
1384
1385 // Safe access checks on the compositor struct have been performed in
1386 // InferExternalViewEmbedderFromArgs and are not necessary here.
1387 auto c_create_callback = compositor->create_backing_store_callback;
1388 auto c_collect_callback = compositor->collect_backing_store_callback;
1389
1390 {
1391 TRACE_EVENT0("flutter", "FlutterCompositorCreateBackingStore");
1392 if (!c_create_callback(&config, &backing_store, compositor->user_data)) {
1393 FML_LOG(ERROR) << "Could not create the embedder backing store.";
1394 return nullptr;
1395 }
1396 }
1397
1398 if (backing_store.struct_size != sizeof(backing_store)) {
1399 FML_LOG(ERROR) << "Embedder modified the backing store struct size.";
1400 return nullptr;
1401 }
1402
1403 // In case we return early without creating an embedder render target, the
1404 // embedder has still given us ownership of its baton which we must return
1405 // back to it. If this method is successful, the closure is released when the
1406 // render target is eventually released.
1407 fml::ScopedCleanupClosure collect_callback(
1408 [c_collect_callback, backing_store, user_data = compositor->user_data]() {
1409 TRACE_EVENT0("flutter", "FlutterCompositorCollectBackingStore");
1410 c_collect_callback(&backing_store, user_data);
1411 });
1412
1413 // No safe access checks on the renderer are necessary since we allocated
1414 // the struct.
1415
1416 std::unique_ptr<flutter::EmbedderRenderTarget> render_target;
1417
1418 switch (backing_store.type) {
1420 switch (backing_store.open_gl.type) {
1422 auto skia_surface = MakeSkSurfaceFromBackingStore(
1423 context, config, &backing_store.open_gl.texture);
1424 render_target = MakeRenderTargetFromSkSurface(
1425 backing_store, std::move(skia_surface),
1426 collect_callback.Release());
1427 break;
1428 }
1430 if (enable_impeller) {
1432 backing_store, collect_callback.Release(), aiks_context, config,
1433 &backing_store.open_gl.framebuffer);
1434 break;
1435 } else {
1436 auto skia_surface = MakeSkSurfaceFromBackingStore(
1437 context, config, &backing_store.open_gl.framebuffer);
1438 render_target = MakeRenderTargetFromSkSurface(
1439 backing_store, std::move(skia_surface),
1440 collect_callback.Release());
1441 break;
1442 }
1443 }
1444
1446 auto on_make_current =
1448 context = backing_store.open_gl.surface.user_data]()
1450 bool invalidate_api_state = false;
1451 bool ok = callback(context, &invalidate_api_state);
1452 return {ok, invalidate_api_state};
1453 };
1454
1455 auto on_clear_current =
1457 context = backing_store.open_gl.surface.user_data]()
1459 bool invalidate_api_state = false;
1460 bool ok = callback(context, &invalidate_api_state);
1461 return {ok, invalidate_api_state};
1462 };
1463
1464 if (enable_impeller) {
1465 // TODO(https://github.com/flutter/flutter/issues/151670): Implement
1466 // GL Surface backing stores for Impeller.
1467 FML_LOG(ERROR) << "Unimplemented";
1468 break;
1469 } else {
1470 auto skia_surface = MakeSkSurfaceFromBackingStore(
1471 context, config, &backing_store.open_gl.surface);
1472
1473 render_target = MakeRenderTargetFromSkSurface(
1474 backing_store, std::move(skia_surface),
1475 collect_callback.Release(), on_make_current, on_clear_current);
1476 break;
1477 }
1478 }
1479 }
1480 break;
1481 }
1482
1484 auto skia_surface = MakeSkSurfaceFromBackingStore(
1485 context, config, &backing_store.software);
1486 render_target = MakeRenderTargetFromSkSurface(
1487 backing_store, std::move(skia_surface), collect_callback.Release());
1488 break;
1489 }
1491 auto skia_surface = MakeSkSurfaceFromBackingStore(
1492 context, config, &backing_store.software2);
1493 render_target = MakeRenderTargetFromSkSurface(
1494 backing_store, std::move(skia_surface), collect_callback.Release());
1495 break;
1496 }
1498 if (enable_impeller) {
1500 backing_store, collect_callback.Release(), aiks_context, config,
1501 &backing_store.metal);
1502 } else {
1503 auto skia_surface = MakeSkSurfaceFromBackingStore(context, config,
1504 &backing_store.metal);
1505 render_target = MakeRenderTargetFromSkSurface(
1506 backing_store, std::move(skia_surface), collect_callback.Release());
1507 }
1508 break;
1509 }
1511 if (enable_impeller) {
1512 FML_LOG(ERROR) << "Unimplemented";
1513 break;
1514 } else {
1515 auto skia_surface = MakeSkSurfaceFromBackingStore(
1516 context, config, &backing_store.vulkan);
1517 render_target = MakeRenderTargetFromSkSurface(
1518 backing_store, std::move(skia_surface), collect_callback.Release());
1519 break;
1520 }
1521 }
1522 };
1523
1524 if (!render_target) {
1525 FML_LOG(ERROR) << "Could not create a surface from an embedder provided "
1526 "render target.";
1527 }
1528 return render_target;
1529}

References callback, FlutterOpenGLSurface::clear_current_callback, FlutterCompositor::collect_backing_store_callback, FlutterCompositor::create_backing_store_callback, FML_LOG, FlutterOpenGLBackingStore::framebuffer, kFlutterBackingStoreTypeMetal, kFlutterBackingStoreTypeOpenGL, kFlutterBackingStoreTypeSoftware, kFlutterBackingStoreTypeSoftware2, kFlutterBackingStoreTypeVulkan, kFlutterOpenGLTargetTypeFramebuffer, kFlutterOpenGLTargetTypeSurface, kFlutterOpenGLTargetTypeTexture, FlutterOpenGLSurface::make_current_callback, MakeRenderTargetFromBackingStoreImpeller(), MakeRenderTargetFromSkSurface(), MakeSkSurfaceFromBackingStore(), FlutterBackingStore::metal, FlutterBackingStore::open_gl, fml::ScopedCleanupClosure::Release(), FlutterBackingStore::software, FlutterBackingStore::software2, FlutterBackingStore::struct_size, FlutterOpenGLBackingStore::surface, FlutterOpenGLBackingStore::texture, TRACE_EVENT0, FlutterOpenGLBackingStore::type, FlutterBackingStore::type, user_data, FlutterOpenGLSurface::user_data, FlutterCompositor::user_data, and FlutterBackingStore::vulkan.

Referenced by InferExternalViewEmbedderFromArgs().

◆ CreateEmbedderSemanticsUpdateCallback()

flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallback ( const FlutterProjectArgs args,
void *  user_data 
)

Definition at line 1925 of file embedder.cc.

1926 {
1927 // There are three variants for the embedder API's semantic update callbacks.
1928 // Create a callback that maps to the embedder's desired semantic update API.
1929 //
1930 // Handle the case where the embedder registered the callback
1931 // 'updated_semantics_callback2'
1932 if (SAFE_ACCESS(args, update_semantics_callback2, nullptr) != nullptr) {
1934 args->update_semantics_callback2, user_data);
1935 }
1936
1937 // Handle the case where the embedder registered the deprecated callback
1938 // 'update_semantics_callback'.
1939 if (SAFE_ACCESS(args, update_semantics_callback, nullptr) != nullptr) {
1941 args->update_semantics_callback, user_data);
1942 }
1943
1944 // Handle the case where the embedder registered the deprecated callbacks
1945 // 'update_semantics_node_callback' and
1946 // 'update_semantics_custom_action_callback'.
1947 FlutterUpdateSemanticsNodeCallback update_semantics_node_callback = nullptr;
1948 if (SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr) {
1949 update_semantics_node_callback = args->update_semantics_node_callback;
1950 }
1951
1953 update_semantics_custom_action_callback = nullptr;
1954 if (SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) !=
1955 nullptr) {
1956 update_semantics_custom_action_callback =
1957 args->update_semantics_custom_action_callback;
1958 }
1959
1960 if (update_semantics_node_callback != nullptr ||
1961 update_semantics_custom_action_callback != nullptr) {
1963 update_semantics_node_callback, update_semantics_custom_action_callback,
1964 user_data);
1965 }
1966
1967 // Handle the case where the embedder registered no callbacks.
1968 return nullptr;
1969}

References args, CreateEmbedderSemanticsUpdateCallbackV1(), CreateEmbedderSemanticsUpdateCallbackV2(), CreateEmbedderSemanticsUpdateCallbackV3(), SAFE_ACCESS, and user_data.

Referenced by FlutterEngineInitialize().

◆ CreateEmbedderSemanticsUpdateCallbackV1()

flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV1 ( FlutterUpdateSemanticsNodeCallback  update_semantics_node_callback,
FlutterUpdateSemanticsCustomActionCallback  update_semantics_custom_action_callback,
void *  user_data 
)

Definition at line 1845 of file embedder.cc.

1849 {
1850 return [update_semantics_node_callback,
1851 update_semantics_custom_action_callback, user_data](
1852 int64_t view_id, const flutter::SemanticsNodeUpdates& nodes,
1854 flutter::EmbedderSemanticsUpdate update{nodes, actions};
1855 FlutterSemanticsUpdate* update_ptr = update.get();
1856
1857 // First, queue all node and custom action updates.
1858 if (update_semantics_node_callback != nullptr) {
1859 for (size_t i = 0; i < update_ptr->nodes_count; i++) {
1860 update_semantics_node_callback(&update_ptr->nodes[i], user_data);
1861 }
1862 }
1863
1864 if (update_semantics_custom_action_callback != nullptr) {
1865 for (size_t i = 0; i < update_ptr->custom_actions_count; i++) {
1866 update_semantics_custom_action_callback(&update_ptr->custom_actions[i],
1867 user_data);
1868 }
1869 }
1870
1871 // Second, mark node and action batches completed now that all
1872 // updates are queued.
1873 if (update_semantics_node_callback != nullptr) {
1874 const FlutterSemanticsNode batch_end_sentinel = {
1875 sizeof(FlutterSemanticsNode),
1877 };
1878 update_semantics_node_callback(&batch_end_sentinel, user_data);
1879 }
1880
1881 if (update_semantics_custom_action_callback != nullptr) {
1882 const FlutterSemanticsCustomAction batch_end_sentinel = {
1885 };
1886 update_semantics_custom_action_callback(&batch_end_sentinel, user_data);
1887 }
1888 };
1889}

References FlutterSemanticsUpdate::custom_actions, FlutterSemanticsUpdate::custom_actions_count, i, kFlutterSemanticsCustomActionIdBatchEnd, kFlutterSemanticsNodeIdBatchEnd, FlutterSemanticsUpdate::nodes, FlutterSemanticsUpdate::nodes_count, user_data, and view_id.

Referenced by CreateEmbedderSemanticsUpdateCallback().

◆ CreateEmbedderSemanticsUpdateCallbackV2()

flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV2 ( FlutterUpdateSemanticsCallback  update_semantics_callback,
void *  user_data 
)

Definition at line 1894 of file embedder.cc.

1896 {
1897 return [update_semantics_callback, user_data](
1898 int64_t view_id, const flutter::SemanticsNodeUpdates& nodes,
1900 flutter::EmbedderSemanticsUpdate update{nodes, actions};
1901
1902 update_semantics_callback(update.get(), user_data);
1903 };
1904}

References user_data, and view_id.

Referenced by CreateEmbedderSemanticsUpdateCallback().

◆ CreateEmbedderSemanticsUpdateCallbackV3()

flutter::PlatformViewEmbedder::UpdateSemanticsCallback CreateEmbedderSemanticsUpdateCallbackV3 ( FlutterUpdateSemanticsCallback2  update_semantics_callback,
void *  user_data 
)

Definition at line 1909 of file embedder.cc.

1911 {
1912 return [update_semantics_callback, user_data](
1913 int64_t view_id, const flutter::SemanticsNodeUpdates& nodes,
1915 flutter::EmbedderSemanticsUpdate2 update{view_id, nodes, actions};
1916
1917 update_semantics_callback(update.get(), user_data);
1918 };
1919}

References user_data, and view_id.

Referenced by CreateEmbedderSemanticsUpdateCallback().

◆ DispatchJSONPlatformMessage()

static bool DispatchJSONPlatformMessage ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const rapidjson::Document &  document,
const std::string &  channel_name 
)
static

Definition at line 3333 of file embedder.cc.

3336 {
3337 if (channel_name.empty()) {
3338 return false;
3339 }
3340
3341 rapidjson::StringBuffer buffer;
3342 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
3343
3344 if (!document.Accept(writer)) {
3345 return false;
3346 }
3347
3348 const char* message = buffer.GetString();
3349
3350 if (message == nullptr || buffer.GetSize() == 0) {
3351 return false;
3352 }
3353
3354 auto platform_message = std::make_unique<flutter::PlatformMessage>(
3355 channel_name.c_str(), // channel
3357 buffer.GetSize()), // message
3358 nullptr // response
3359 );
3360
3361 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3362 ->SendPlatformMessage(std::move(platform_message));
3363}

References fml::MallocMapping::Copy(), engine, and message.

Referenced by FlutterEngineNotifyLowMemoryWarning(), and FlutterEngineUpdateLocales().

◆ FlutterEngineAddView()

FLUTTER_EXPORT FlutterEngineResult FlutterEngineAddView ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterAddViewInfo info 
)

Adds a view.

        This is an asynchronous operation. The view should not be used
        until the |info.add_view_callback| is invoked with an |added|
        value of true. The embedder should prepare resources in advance
        but be ready to clean up on failure.

        A frame is scheduled if the operation succeeds.

        The callback is invoked on a thread managed by the engine. The
        embedder should re-thread if needed.

        Attempting to add the implicit view will fail and will return
        kInvalidArguments. Attempting to add a view with an already
        existing view ID will fail, and |info.add_view_callback| will be
        invoked with an |added| value of false.
Parameters
[in]engineA running engine instance.
[in]infoThe add view arguments. This can be deallocated once |FlutterEngineAddView| returns, before |add_view_callback| is invoked.
Returns
The result of starting the asynchronous operation. If kSuccess, the |add_view_callback| will be invoked.

Definition at line 2500 of file embedder.cc.

2502 {
2503 if (!engine) {
2504 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2505 }
2506 if (!info || !info->view_metrics || !info->add_view_callback) {
2508 "Add view info handle was invalid.");
2509 }
2510
2513 return LOG_EMBEDDER_ERROR(
2515 "Add view info was invalid. The implicit view cannot be added.");
2516 }
2518 view_id) {
2521 "Add view info was invalid. The info and "
2522 "window metric view IDs must match.");
2523 }
2524 }
2525
2526 // TODO(loicsharma): Return an error if the engine was initialized with
2527 // callbacks that are incompatible with multiple views.
2528 // https://github.com/flutter/flutter/issues/144806
2529
2530 std::variant<flutter::ViewportMetrics, std::string> metrics_or_error =
2532
2533 if (const std::string* error = std::get_if<std::string>(&metrics_or_error)) {
2534 return LOG_EMBEDDER_ERROR(kInvalidArguments, error->c_str());
2535 }
2536
2537 auto metrics = std::get<flutter::ViewportMetrics>(metrics_or_error);
2538
2539 // The engine must be running to add a view.
2540 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2541 if (!embedder_engine->IsValid()) {
2542 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2543 }
2544
2546 [c_callback = info->add_view_callback,
2547 user_data = info->user_data](bool added) {
2548 FlutterAddViewResult result = {};
2549 result.struct_size = sizeof(FlutterAddViewResult);
2550 result.added = added;
2551 result.user_data = user_data;
2552 c_callback(&result);
2553 };
2554
2555 embedder_engine->GetShell().GetPlatformView()->AddView(view_id, metrics,
2556 callback);
2557 return kSuccess;
2558}

References FlutterAddViewInfo::add_view_callback, FlutterAddViewResult::added, callback, engine, error, kFlutterImplicitViewId, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, MakeViewportMetricsFromWindowMetrics(), SAFE_ACCESS, FlutterAddViewResult::struct_size, user_data, FlutterAddViewResult::user_data, FlutterAddViewInfo::user_data, FlutterAddViewInfo::view_id, view_id, and FlutterAddViewInfo::view_metrics.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineCollectAOTData()

FlutterEngineResult FlutterEngineCollectAOTData ( FlutterEngineAOTData  data)

Collects the AOT data.

Warning
The embedder must ensure that this call is made only after all FlutterEngine instances launched using this data have been terminated, and that all of those instances were launched with the FlutterProjectArgs::shutdown_dart_vm_when_done flag set to true.
Parameters
[in]dataThe data to collect.
Returns
Returns if the AOT data was successfully collected.

Definition at line 1736 of file embedder.cc.

1736 {
1737 if (!data) {
1738 // Deleting a null object should be a no-op.
1739 return kSuccess;
1740 }
1741
1742 // Created in a unique pointer in `FlutterEngineCreateAOTData`.
1743 delete data;
1744 return kSuccess;
1745}

References data, and kSuccess.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::AOTDataDeleter::operator()(), AOTDataDeleter::operator()(), and flutter::testing::TEST_F().

◆ FlutterEngineCreateAOTData()

FlutterEngineResult FlutterEngineCreateAOTData ( const FlutterEngineAOTDataSource source,
FlutterEngineAOTData data_out 
)

Creates the necessary data structures to launch a Flutter Dart application in AOT mode. The data may only be collected after all FlutterEngine instances launched using this data have been terminated.

Parameters
[in]sourceThe source of the AOT data.
[out]data_outThe AOT data on success. Unchanged on failure.
Returns
Returns if the AOT data could be successfully resolved.

Definition at line 1682 of file embedder.cc.

1684 {
1687 "AOT data can only be created in AOT mode.");
1688 } else if (!source) {
1689 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null source specified.");
1690 } else if (!data_out) {
1691 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null data_out specified.");
1692 }
1693
1694 switch (source->type) {
1696 if (!source->elf_path || !fml::IsFile(source->elf_path)) {
1698 "Invalid ELF path specified.");
1699 }
1700
1701 auto aot_data = std::make_unique<_FlutterEngineAOTData>();
1702 const char* error = nullptr;
1703
1704#if OS_FUCHSIA
1705 // TODO(gw280): https://github.com/flutter/flutter/issues/50285
1706 // Dart doesn't implement Dart_LoadELF on Fuchsia
1707 Dart_LoadedElf* loaded_elf = nullptr;
1708#else
1709 Dart_LoadedElf* loaded_elf = Dart_LoadELF(
1710 source->elf_path, // file path
1711 0, // file offset
1712 &error, // error (out)
1713 &aot_data->vm_snapshot_data, // vm snapshot data (out)
1714 &aot_data->vm_snapshot_instrs, // vm snapshot instr (out)
1715 &aot_data->vm_isolate_data, // vm isolate data (out)
1716 &aot_data->vm_isolate_instrs // vm isolate instr (out)
1717 );
1718#endif
1719
1720 if (loaded_elf == nullptr) {
1722 }
1723
1724 aot_data->loaded_elf.reset(loaded_elf);
1725
1726 *data_out = aot_data.release();
1727 return kSuccess;
1728 }
1729 }
1730
1731 return LOG_EMBEDDER_ERROR(
1733 "Invalid FlutterEngineAOTDataSourceType type specified.");
1734}

References FlutterEngineAOTDataSource::elf_path, error, fml::IsFile(), flutter::DartVM::IsRunningPrecompiledCode(), kFlutterEngineAOTDataSourceTypeElfPath, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and FlutterEngineAOTDataSource::type.

Referenced by FlutterEngineGetProcAddresses(), LoadAotData(), flutter::testing::EmbedderTestContext::SetupAOTDataIfNecessary(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineDeinitialize()

FLUTTER_EXPORT FlutterEngineResult FlutterEngineDeinitialize ( FLUTTER_API_SYMBOL(FlutterEngine engine)

Stops running the Flutter engine instance. After this call, the embedder is also guaranteed that no more calls to post tasks onto custom task runners specified by the embedder are made. The Flutter engine handle still needs to be collected via a call to FlutterEngineShutdown.

Parameters
[in]engineThe running engine instance to de-initialize.
Returns
The result of the call to de-initialize the Flutter engine.

Definition at line 2636 of file embedder.cc.

2637 {
2638 if (engine == nullptr) {
2639 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2640 }
2641
2642 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2643 embedder_engine->NotifyDestroyed();
2644 embedder_engine->CollectShell();
2645 embedder_engine->CollectThreadHost();
2646 return kSuccess;
2647}

References engine, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and flutter::EmbedderEngine::NotifyDestroyed().

Referenced by FlutterEngineGetProcAddresses(), FlutterEngineShutdown(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_P().

◆ FlutterEngineDispatchSemanticsAction()

FlutterEngineResult FlutterEngineDispatchSemanticsAction ( FLUTTER_API_SYMBOL(FlutterEngine engine,
uint64_t  node_id,
FlutterSemanticsAction  action,
const uint8_t *  data,
size_t  data_length 
)

Dispatch a semantics action to the specified semantics node in the implicit view.

Parameters
[in]engineA running engine instance.
[in]node_idThe semantics node identifier.
[in]actionThe semantics action.
[in]dataData associated with the action.
[in]data_lengthThe data length.
Returns
The result of the call.

Definition at line 3196 of file embedder.cc.

3201 {
3205 .node_id = node_id,
3206 .action = action,
3207 .data = data,
3208 .data_length = data_length};
3210}

References action, data, engine, FlutterEngineSendSemanticsAction(), kFlutterImplicitViewId, FlutterSendSemanticsActionInfo::struct_size, and view_id.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineGetCurrentTime()

uint64_t FlutterEngineGetCurrentTime ( )

Get the current time in nanoseconds from the clock used by the flutter engine. This is the system monotonic clock.

Returns
The current time in nanoseconds.

Definition at line 3309 of file embedder.cc.

3309 {
3311}

References fml::TimePoint::Now(), fml::TimePoint::ToEpochDelta(), and fml::TimeDelta::ToNanoseconds().

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST(), and flutter::EventLoop::TimePointFromFlutterTime().

◆ FlutterEngineGetProcAddresses()

FlutterEngineResult FlutterEngineGetProcAddresses ( FlutterEngineProcTable table)

Gets the table of engine function pointers.

Parameters
[out]tableThe table to fill with pointers. This should be zero-initialized, except for struct_size.
Returns
Returns whether the table was successfully populated.

Definition at line 3696 of file embedder.cc.

3697 {
3698 if (!table) {
3699 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null table specified.");
3700 }
3701#define SET_PROC(member, function) \
3702 if (STRUCT_HAS_MEMBER(table, member)) { \
3703 table->member = &function; \
3704 }
3705
3706 SET_PROC(CreateAOTData, FlutterEngineCreateAOTData);
3707 SET_PROC(CollectAOTData, FlutterEngineCollectAOTData);
3710 SET_PROC(Initialize, FlutterEngineInitialize);
3711 SET_PROC(Deinitialize, FlutterEngineDeinitialize);
3712 SET_PROC(RunInitialized, FlutterEngineRunInitialized);
3713 SET_PROC(SendWindowMetricsEvent, FlutterEngineSendWindowMetricsEvent);
3714 SET_PROC(SendPointerEvent, FlutterEngineSendPointerEvent);
3715 SET_PROC(SendKeyEvent, FlutterEngineSendKeyEvent);
3716 SET_PROC(SendPlatformMessage, FlutterEngineSendPlatformMessage);
3717 SET_PROC(PlatformMessageCreateResponseHandle,
3719 SET_PROC(PlatformMessageReleaseResponseHandle,
3721 SET_PROC(SendPlatformMessageResponse,
3723 SET_PROC(RegisterExternalTexture, FlutterEngineRegisterExternalTexture);
3724 SET_PROC(UnregisterExternalTexture, FlutterEngineUnregisterExternalTexture);
3725 SET_PROC(MarkExternalTextureFrameAvailable,
3727 SET_PROC(UpdateSemanticsEnabled, FlutterEngineUpdateSemanticsEnabled);
3728 SET_PROC(UpdateAccessibilityFeatures,
3730 SET_PROC(DispatchSemanticsAction, FlutterEngineDispatchSemanticsAction);
3731 SET_PROC(SendSemanticsAction, FlutterEngineSendSemanticsAction);
3733 SET_PROC(ReloadSystemFonts, FlutterEngineReloadSystemFonts);
3734 SET_PROC(TraceEventDurationBegin, FlutterEngineTraceEventDurationBegin);
3735 SET_PROC(TraceEventDurationEnd, FlutterEngineTraceEventDurationEnd);
3736 SET_PROC(TraceEventInstant, FlutterEngineTraceEventInstant);
3737 SET_PROC(PostRenderThreadTask, FlutterEnginePostRenderThreadTask);
3740 SET_PROC(UpdateLocales, FlutterEngineUpdateLocales);
3741 SET_PROC(RunsAOTCompiledDartCode, FlutterEngineRunsAOTCompiledDartCode);
3742 SET_PROC(PostDartObject, FlutterEnginePostDartObject);
3743 SET_PROC(NotifyLowMemoryWarning, FlutterEngineNotifyLowMemoryWarning);
3744 SET_PROC(PostCallbackOnAllNativeThreads,
3746 SET_PROC(NotifyDisplayUpdate, FlutterEngineNotifyDisplayUpdate);
3747 SET_PROC(ScheduleFrame, FlutterEngineScheduleFrame);
3748 SET_PROC(SetNextFrameCallback, FlutterEngineSetNextFrameCallback);
3750 SET_PROC(RemoveView, FlutterEngineRemoveView);
3751 SET_PROC(SendViewFocusEvent, FlutterEngineSendViewFocusEvent);
3752#undef SET_PROC
3753
3754 return kSuccess;
3755}

References FlutterEngineAddView(), FlutterEngineCollectAOTData(), FlutterEngineCreateAOTData(), FlutterEngineDeinitialize(), FlutterEngineDispatchSemanticsAction(), FlutterEngineGetCurrentTime(), FlutterEngineInitialize(), FlutterEngineMarkExternalTextureFrameAvailable(), FlutterEngineNotifyDisplayUpdate(), FlutterEngineNotifyLowMemoryWarning(), FlutterEngineOnVsync(), FlutterEnginePostCallbackOnAllNativeThreads(), FlutterEnginePostDartObject(), FlutterEnginePostRenderThreadTask(), FlutterEngineRegisterExternalTexture(), FlutterEngineReloadSystemFonts(), FlutterEngineRemoveView(), FlutterEngineRun(), FlutterEngineRunInitialized(), FlutterEngineRunsAOTCompiledDartCode(), FlutterEngineRunTask(), FlutterEngineScheduleFrame(), FlutterEngineSendKeyEvent(), FlutterEngineSendPlatformMessage(), FlutterEngineSendPlatformMessageResponse(), FlutterEngineSendPointerEvent(), FlutterEngineSendSemanticsAction(), FlutterEngineSendViewFocusEvent(), FlutterEngineSendWindowMetricsEvent(), FlutterEngineSetNextFrameCallback(), FlutterEngineShutdown(), FlutterEngineTraceEventDurationBegin(), FlutterEngineTraceEventDurationEnd(), FlutterEngineTraceEventInstant(), FlutterEngineUnregisterExternalTexture(), FlutterEngineUpdateAccessibilityFeatures(), FlutterEngineUpdateLocales(), FlutterEngineUpdateSemanticsEnabled(), FlutterPlatformMessageCreateResponseHandle(), FlutterPlatformMessageReleaseResponseHandle(), GetCurrentTime, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and SET_PROC.

Referenced by fl_engine_init(), flutter::FlutterWindowsEngine::FlutterWindowsEngine(), flutter::testing::TEST(), flutter::testing::TEST(), and flutter::testing::TEST().

◆ FlutterEngineInitialize()

FlutterEngineResult FlutterEngineInitialize ( size_t  version,
const FlutterRendererConfig config,
const FlutterProjectArgs args,
void *  user_data,
FLUTTER_API_SYMBOL(FlutterEngine) *  engine_out 
)

Initialize a Flutter engine instance. This does not run the Flutter application code till the FlutterEngineRunInitialized call is made. Besides Flutter application code, no tasks are scheduled on embedder managed task runners either. This allows embedders providing custom task runners to the Flutter engine to obtain a handle to the Flutter engine before the engine can post tasks on these task runners.

Parameters
[in]versionThe Flutter embedder API version. Must be FLUTTER_ENGINE_VERSION.
[in]configThe renderer configuration.
[in]argsThe Flutter project arguments.
user_dataA user data baton passed back to embedders in callbacks.
[out]engine_outThe engine handle on successful engine creation.
Returns
The result of the call to initialize the Flutter engine.

Definition at line 1987 of file embedder.cc.

1992 {
1993 // Step 0: Figure out arguments for shell creation.
1994 if (version != FLUTTER_ENGINE_VERSION) {
1995 return LOG_EMBEDDER_ERROR(
1997 "Flutter embedder version mismatch. There has been a breaking change. "
1998 "Please consult the changelog and update the embedder.");
1999 }
2000
2001 if (engine_out == nullptr) {
2003 "The engine out parameter was missing.");
2004 }
2005
2006 if (args == nullptr) {
2008 "The Flutter project arguments were missing.");
2009 }
2010
2011 if (SAFE_ACCESS(args, assets_path, nullptr) == nullptr) {
2012 return LOG_EMBEDDER_ERROR(
2014 "The assets path in the Flutter project arguments was missing.");
2015 }
2016
2017 if (SAFE_ACCESS(args, main_path__unused__, nullptr) != nullptr) {
2018 FML_LOG(WARNING)
2019 << "FlutterProjectArgs.main_path is deprecated and should be set null.";
2020 }
2021
2022 if (SAFE_ACCESS(args, packages_path__unused__, nullptr) != nullptr) {
2023 FML_LOG(WARNING) << "FlutterProjectArgs.packages_path is deprecated and "
2024 "should be set null.";
2025 }
2026
2027 if (!IsRendererValid(config)) {
2029 "The renderer configuration was invalid.");
2030 }
2031
2032 std::string icu_data_path;
2033 if (SAFE_ACCESS(args, icu_data_path, nullptr) != nullptr) {
2034 icu_data_path = SAFE_ACCESS(args, icu_data_path, nullptr);
2035 }
2036
2037#if !SLIMPELLER
2038 if (SAFE_ACCESS(args, persistent_cache_path, nullptr) != nullptr) {
2039 std::string persistent_cache_path =
2040 SAFE_ACCESS(args, persistent_cache_path, nullptr);
2042 }
2043
2044 if (SAFE_ACCESS(args, is_persistent_cache_read_only, false)) {
2046 }
2047#endif // !SLIMPELLER
2048
2049 fml::CommandLine command_line;
2050 if (SAFE_ACCESS(args, command_line_argc, 0) != 0 &&
2051 SAFE_ACCESS(args, command_line_argv, nullptr) != nullptr) {
2052 command_line = fml::CommandLineFromArgcArgv(
2053 SAFE_ACCESS(args, command_line_argc, 0),
2054 SAFE_ACCESS(args, command_line_argv, nullptr));
2055 }
2056
2057 flutter::Settings settings = flutter::SettingsFromCommandLine(command_line);
2058
2059 if (SAFE_ACCESS(args, aot_data, nullptr)) {
2060 if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) ||
2061 SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) ||
2062 SAFE_ACCESS(args, isolate_snapshot_data, nullptr) ||
2063 SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr)) {
2064 return LOG_EMBEDDER_ERROR(
2066 "Multiple AOT sources specified. Embedders should provide either "
2067 "*_snapshot_* buffers or aot_data, not both.");
2068 }
2069 }
2070
2073 } else {
2075 }
2076
2077 settings.icu_data_path = icu_data_path;
2078 settings.assets_path = args->assets_path;
2079 settings.leak_vm = !SAFE_ACCESS(args, shutdown_dart_vm_when_done, false);
2080 settings.old_gen_heap_size = SAFE_ACCESS(args, dart_old_gen_heap_size, -1);
2081
2083 // Verify the assets path contains Dart 2 kernel assets.
2084 const std::string kApplicationKernelSnapshotFileName = "kernel_blob.bin";
2085 std::string application_kernel_path = fml::paths::JoinPaths(
2087 if (!fml::IsFile(application_kernel_path)) {
2088 return LOG_EMBEDDER_ERROR(
2090 "Not running in AOT mode but could not resolve the kernel binary.");
2091 }
2093 }
2094
2095 if (SAFE_ACCESS(args, root_isolate_create_callback, nullptr) != nullptr) {
2097 SAFE_ACCESS(args, root_isolate_create_callback, nullptr);
2099 [callback, user_data](const auto& isolate) { callback(user_data); };
2100 }
2101
2102 // Wire up callback for engine and print logging.
2103 if (SAFE_ACCESS(args, log_message_callback, nullptr) != nullptr) {
2105 SAFE_ACCESS(args, log_message_callback, nullptr);
2107 const std::string& tag,
2108 const std::string& message) {
2109 callback(tag.c_str(), message.c_str(), user_data);
2110 };
2111 } else {
2112 settings.log_message_callback = [](const std::string& tag,
2113 const std::string& message) {
2114 // Fall back to logging to stdout if unspecified.
2115 if (tag.empty()) {
2116 std::cout << tag << ": ";
2117 }
2118 std::cout << message << std::endl;
2119 };
2120 }
2121
2122 if (SAFE_ACCESS(args, log_tag, nullptr) != nullptr) {
2123 settings.log_tag = SAFE_ACCESS(args, log_tag, nullptr);
2124 }
2125
2126 bool has_update_semantics_2_callback =
2127 SAFE_ACCESS(args, update_semantics_callback2, nullptr) != nullptr;
2128 bool has_update_semantics_callback =
2129 SAFE_ACCESS(args, update_semantics_callback, nullptr) != nullptr;
2130 bool has_legacy_update_semantics_callback =
2131 SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr ||
2132 SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) !=
2133 nullptr;
2134
2135 int semantic_callback_count = (has_update_semantics_2_callback ? 1 : 0) +
2136 (has_update_semantics_callback ? 1 : 0) +
2137 (has_legacy_update_semantics_callback ? 1 : 0);
2138
2139 if (semantic_callback_count > 1) {
2140 return LOG_EMBEDDER_ERROR(
2142 "Multiple semantics update callbacks provided. "
2143 "Embedders should provide either `update_semantics_callback2`, "
2144 "`update_semantics_callback`, or both "
2145 "`update_semantics_node_callback` and "
2146 "`update_semantics_custom_action_callback`.");
2147 }
2148
2150 update_semantics_callback =
2152
2154 platform_message_response_callback = nullptr;
2155 if (SAFE_ACCESS(args, platform_message_callback, nullptr) != nullptr) {
2156 platform_message_response_callback =
2157 [ptr = args->platform_message_callback,
2158 user_data](std::unique_ptr<flutter::PlatformMessage> message) {
2159 auto handle = new FlutterPlatformMessageResponseHandle();
2160 const FlutterPlatformMessage incoming_message = {
2161 sizeof(FlutterPlatformMessage), // struct_size
2162 message->channel().c_str(), // channel
2163 message->data().GetMapping(), // message
2164 message->data().GetSize(), // message_size
2165 handle, // response_handle
2166 };
2167 handle->message = std::move(message);
2168 return ptr(&incoming_message, user_data);
2169 };
2170 }
2171
2172 flutter::VsyncWaiterEmbedder::VsyncCallback vsync_callback = nullptr;
2173 if (SAFE_ACCESS(args, vsync_callback, nullptr) != nullptr) {
2174 vsync_callback = [ptr = args->vsync_callback, user_data](intptr_t baton) {
2175 return ptr(user_data, baton);
2176 };
2177 }
2178
2180 compute_platform_resolved_locale_callback = nullptr;
2181 if (SAFE_ACCESS(args, compute_platform_resolved_locale_callback, nullptr) !=
2182 nullptr) {
2183 compute_platform_resolved_locale_callback =
2184 [ptr = args->compute_platform_resolved_locale_callback](
2185 const std::vector<std::string>& supported_locales_data) {
2186 const size_t number_of_strings_per_locale = 3;
2187 size_t locale_count =
2188 supported_locales_data.size() / number_of_strings_per_locale;
2189 std::vector<FlutterLocale> supported_locales;
2190 std::vector<const FlutterLocale*> supported_locales_ptr;
2191 for (size_t i = 0; i < locale_count; ++i) {
2192 supported_locales.push_back(
2193 {.struct_size = sizeof(FlutterLocale),
2194 .language_code =
2195 supported_locales_data[i * number_of_strings_per_locale +
2196 0]
2197 .c_str(),
2198 .country_code =
2199 supported_locales_data[i * number_of_strings_per_locale +
2200 1]
2201 .c_str(),
2202 .script_code =
2203 supported_locales_data[i * number_of_strings_per_locale +
2204 2]
2205 .c_str(),
2206 .variant_code = nullptr});
2207 supported_locales_ptr.push_back(&supported_locales[i]);
2208 }
2209
2210 const FlutterLocale* result =
2211 ptr(supported_locales_ptr.data(), locale_count);
2212
2213 std::unique_ptr<std::vector<std::string>> out =
2214 std::make_unique<std::vector<std::string>>();
2215 if (result) {
2216 std::string language_code(SAFE_ACCESS(result, language_code, ""));
2217 if (language_code != "") {
2218 out->push_back(language_code);
2219 out->emplace_back(SAFE_ACCESS(result, country_code, ""));
2220 out->emplace_back(SAFE_ACCESS(result, script_code, ""));
2221 }
2222 }
2223 return out;
2224 };
2225 }
2226
2228 on_pre_engine_restart_callback = nullptr;
2229 if (SAFE_ACCESS(args, on_pre_engine_restart_callback, nullptr) != nullptr) {
2230 on_pre_engine_restart_callback = [ptr =
2231 args->on_pre_engine_restart_callback,
2232 user_data]() { return ptr(user_data); };
2233 }
2234
2236 nullptr;
2237 if (SAFE_ACCESS(args, channel_update_callback, nullptr) != nullptr) {
2238 channel_update_callback = [ptr = args->channel_update_callback, user_data](
2239 const std::string& name, bool listening) {
2240 FlutterChannelUpdate update{sizeof(FlutterChannelUpdate), name.c_str(),
2241 listening};
2242 ptr(&update, user_data);
2243 };
2244 }
2245
2247 view_focus_change_request_callback = nullptr;
2248 if (SAFE_ACCESS(args, view_focus_change_request_callback, nullptr) !=
2249 nullptr) {
2250 view_focus_change_request_callback =
2251 [ptr = args->view_focus_change_request_callback,
2253 FlutterViewFocusChangeRequest embedder_request{
2255 .view_id = request.view_id(),
2256 .state = static_cast<FlutterViewFocusState>(request.state()),
2257 .direction =
2258 static_cast<FlutterViewFocusDirection>(request.direction()),
2259 };
2260 ptr(&embedder_request, user_data);
2261 };
2262 }
2263
2264 auto external_view_embedder_result = InferExternalViewEmbedderFromArgs(
2265 SAFE_ACCESS(args, compositor, nullptr), settings.enable_impeller);
2266 if (!external_view_embedder_result.ok()) {
2267 FML_LOG(ERROR) << external_view_embedder_result.status().message();
2269 "Compositor arguments were invalid.");
2270 }
2271
2273 {
2274 update_semantics_callback, //
2275 platform_message_response_callback, //
2276 vsync_callback, //
2277 compute_platform_resolved_locale_callback, //
2278 on_pre_engine_restart_callback, //
2279 channel_update_callback, //
2280 view_focus_change_request_callback, //
2281 };
2282
2283 auto on_create_platform_view = InferPlatformViewCreationCallback(
2284 config, user_data, platform_dispatch_table,
2285 std::move(external_view_embedder_result.value()),
2286 settings.enable_impeller);
2287
2288 if (!on_create_platform_view) {
2289 return LOG_EMBEDDER_ERROR(
2291 "Could not infer platform view creation callback.");
2292 }
2293
2295 [](flutter::Shell& shell) {
2296 return std::make_unique<flutter::Rasterizer>(shell);
2297 };
2298
2299 using ExternalTextureResolver = flutter::EmbedderExternalTextureResolver;
2300 std::unique_ptr<ExternalTextureResolver> external_texture_resolver;
2301 external_texture_resolver = std::make_unique<ExternalTextureResolver>();
2302
2303#ifdef SHELL_ENABLE_GL
2305 external_texture_callback;
2306 if (config->type == kOpenGL) {
2307 const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
2308 if (SAFE_ACCESS(open_gl_config, gl_external_texture_frame_callback,
2309 nullptr) != nullptr) {
2310 external_texture_callback =
2311 [ptr = open_gl_config->gl_external_texture_frame_callback, user_data](
2312 int64_t texture_identifier, size_t width,
2313 size_t height) -> std::unique_ptr<FlutterOpenGLTexture> {
2314 std::unique_ptr<FlutterOpenGLTexture> texture =
2315 std::make_unique<FlutterOpenGLTexture>();
2316 if (!ptr(user_data, texture_identifier, width, height, texture.get())) {
2317 return nullptr;
2318 }
2319 return texture;
2320 };
2321 external_texture_resolver =
2322 std::make_unique<ExternalTextureResolver>(external_texture_callback);
2323 }
2324 }
2325#endif
2326#ifdef SHELL_ENABLE_METAL
2328 external_texture_metal_callback;
2329 if (config->type == kMetal) {
2330 const FlutterMetalRendererConfig* metal_config = &config->metal;
2331 if (SAFE_ACCESS(metal_config, external_texture_frame_callback, nullptr)) {
2332 external_texture_metal_callback =
2333 [ptr = metal_config->external_texture_frame_callback, user_data](
2334 int64_t texture_identifier, size_t width,
2335 size_t height) -> std::unique_ptr<FlutterMetalExternalTexture> {
2336 std::unique_ptr<FlutterMetalExternalTexture> texture =
2337 std::make_unique<FlutterMetalExternalTexture>();
2338 texture->struct_size = sizeof(FlutterMetalExternalTexture);
2339 if (!ptr(user_data, texture_identifier, width, height, texture.get())) {
2340 return nullptr;
2341 }
2342 return texture;
2343 };
2344 external_texture_resolver = std::make_unique<ExternalTextureResolver>(
2345 external_texture_metal_callback);
2346 }
2347 }
2348#endif
2349 auto custom_task_runners = SAFE_ACCESS(args, custom_task_runners, nullptr);
2350 auto thread_config_callback = [&custom_task_runners](
2351 const fml::Thread::ThreadConfig& config) {
2353 if (!custom_task_runners || !custom_task_runners->thread_priority_setter) {
2354 return;
2355 }
2357 switch (config.priority) {
2360 break;
2363 break;
2366 break;
2369 break;
2370 }
2371 custom_task_runners->thread_priority_setter(priority);
2372 };
2373 auto thread_host =
2375 custom_task_runners, thread_config_callback);
2376
2377 if (!thread_host || !thread_host->IsValid()) {
2379 "Could not set up or infer thread configuration "
2380 "to run the Flutter engine on.");
2381 }
2382
2383 auto task_runners = thread_host->GetTaskRunners();
2384
2385 if (!task_runners.IsValid()) {
2387 "Task runner configuration was invalid.");
2388 }
2389
2390 // Embedder supplied UI task runner runner does not have a message loop.
2391 bool has_ui_thread_message_loop =
2392 task_runners.GetUITaskRunner()->GetTaskQueueId().is_valid();
2393 // Message loop observers are used to flush the microtask queue.
2394 // If there is no message loop the queue is flushed from
2395 // EmbedderEngine::RunTask.
2396 settings.task_observer_add = [has_ui_thread_message_loop](
2397 intptr_t key, const fml::closure& callback) {
2398 if (has_ui_thread_message_loop) {
2400 }
2402 };
2403 settings.task_observer_remove = [has_ui_thread_message_loop](
2404 fml::TaskQueueId queue_id, intptr_t key) {
2405 if (has_ui_thread_message_loop) {
2407 }
2408 };
2409
2410 auto run_configuration =
2412
2413 if (SAFE_ACCESS(args, custom_dart_entrypoint, nullptr) != nullptr) {
2414 auto dart_entrypoint = std::string{args->custom_dart_entrypoint};
2415 if (!dart_entrypoint.empty()) {
2416 run_configuration.SetEntrypoint(std::move(dart_entrypoint));
2417 }
2418 }
2419
2420 if (SAFE_ACCESS(args, dart_entrypoint_argc, 0) > 0) {
2421 if (SAFE_ACCESS(args, dart_entrypoint_argv, nullptr) == nullptr) {
2423 "Could not determine Dart entrypoint arguments "
2424 "as dart_entrypoint_argc "
2425 "was set, but dart_entrypoint_argv was null.");
2426 }
2427 std::vector<std::string> arguments(args->dart_entrypoint_argc);
2428 for (int i = 0; i < args->dart_entrypoint_argc; ++i) {
2429 arguments[i] = std::string{args->dart_entrypoint_argv[i]};
2430 }
2431 run_configuration.SetEntrypointArgs(std::move(arguments));
2432 }
2433
2434 if (SAFE_ACCESS(args, engine_id, 0) != 0) {
2435 run_configuration.SetEngineId(args->engine_id);
2436 }
2437
2438 if (!run_configuration.IsValid()) {
2439 return LOG_EMBEDDER_ERROR(
2441 "Could not infer the Flutter project to run from given arguments.");
2442 }
2443
2444 // Create the engine but don't launch the shell or run the root isolate.
2445 auto embedder_engine = std::make_unique<flutter::EmbedderEngine>(
2446 std::move(thread_host), //
2447 std::move(task_runners), //
2448 std::move(settings), //
2449 std::move(run_configuration), //
2450 on_create_platform_view, //
2451 on_create_rasterizer, //
2452 std::move(external_texture_resolver) //
2453 );
2454
2455 // Release the ownership of the embedder engine to the caller.
2456 *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(
2457 embedder_engine.release());
2458 return kSuccess;
2459}

References fml::MessageLoop::AddTaskObserver(), flutter::Settings::application_kernel_asset, args, flutter::Settings::assets_path, callback, FlutterPlatformMessage::channel, fml::CommandLineFromArgcArgv(), flutter::EmbedderThreadHost::CreateEmbedderOrEngineManagedThreadHost(), CreateEmbedderSemanticsUpdateCallback(), flutter::Settings::enable_impeller, FlutterMetalRendererConfig::external_texture_frame_callback, FLUTTER_API_SYMBOL, FLUTTER_ENGINE_VERSION, FML_LOG, fml::MessageLoop::GetCurrent(), flutter::PersistentCache::gIsReadOnly, FlutterOpenGLRendererConfig::gl_external_texture_frame_callback, height, i, flutter::Settings::icu_data_path, InferExternalViewEmbedderFromArgs(), flutter::RunConfiguration::InferFromSettings(), InferPlatformViewCreationCallback(), fml::TaskQueueId::Invalid(), fml::IsFile(), IsRendererValid(), flutter::DartVM::IsRunningPrecompiledCode(), fml::paths::JoinPaths(), kApplicationKernelSnapshotFileName, fml::Thread::kBackground, kBackground, fml::Thread::kDisplay, kDisplay, key, kInternalInconsistency, kInvalidArguments, kInvalidLibraryVersion, kMetal, fml::Thread::kNormal, kNormal, kOpenGL, fml::Thread::kRaster, kRaster, kSuccess, flutter::Settings::leak_vm, LOG_EMBEDDER_ERROR, flutter::Settings::log_message_callback, flutter::Settings::log_tag, message, FlutterRendererConfig::metal, name, flutter::Settings::old_gen_heap_size, FlutterRendererConfig::open_gl, PopulateAOTSnapshotMappingCallbacks(), PopulateJITSnapshotMappingCallbacks(), fml::MessageLoop::RemoveTaskObserver(), flutter::Settings::root_isolate_create_callback, SAFE_ACCESS, flutter::PersistentCache::SetCacheDirectoryPath(), fml::Thread::SetCurrentThreadName(), flutter::SettingsFromCommandLine(), FlutterViewFocusChangeRequest::struct_size, flutter::Settings::task_observer_add, flutter::Settings::task_observer_remove, texture, FlutterRendererConfig::type, user_data, view_id, and width.

Referenced by FlutterEngineGetProcAddresses(), and FlutterEngineRun().

◆ FlutterEngineMarkExternalTextureFrameAvailable()

FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable ( FLUTTER_API_SYMBOL(FlutterEngine engine,
int64_t  texture_identifier 
)

Mark that a new texture frame is available for a given texture identifier.

See also
FlutterEngineRegisterExternalTexture()
FlutterEngineUnregisterExternalTexture()
Parameters
[in]engineA running engine instance.
[in]texture_identifierThe identifier of the texture whose frame has been updated.
Returns
The result of the call.

Definition at line 3150 of file embedder.cc.

3152 {
3153 if (engine == nullptr) {
3154 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3155 }
3156 if (texture_identifier == 0) {
3157 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid texture identifier.");
3158 }
3159 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3160 ->MarkTextureFrameAvailable(texture_identifier)) {
3161 return LOG_EMBEDDER_ERROR(
3163 "Could not mark the texture frame as being available.");
3164 }
3165 return kSuccess;
3166}

References engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses().

◆ FlutterEngineNotifyDisplayUpdate()

FlutterEngineResult FlutterEngineNotifyDisplayUpdate ( FLUTTER_API_SYMBOL(FlutterEngine engine,
FlutterEngineDisplaysUpdateType  update_type,
const FlutterEngineDisplay displays,
size_t  display_count 
)

Posts updates corresponding to display changes to a running engine instance.

Parameters
[in]update_typeThe type of update pushed to the engine.
[in]displaysThe displays affected by this update.
[in]display_countSize of the displays array, must be at least 1.
Returns
the result of the call made to the engine.

Definition at line 3613 of file embedder.cc.

3617 {
3618 if (raw_engine == nullptr) {
3619 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3620 }
3621
3622 if (!ValidDisplayConfiguration(embedder_displays, display_count)) {
3623 return LOG_EMBEDDER_ERROR(
3625 "Invalid FlutterEngineDisplay configuration specified.");
3626 }
3627
3628 auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine);
3629
3630 switch (update_type) {
3632 std::vector<std::unique_ptr<flutter::Display>> displays;
3633 const auto* display = embedder_displays;
3634 for (size_t i = 0; i < display_count; i++) {
3635 displays.push_back(std::make_unique<flutter::Display>(
3636 SAFE_ACCESS(display, display_id, i), //
3637 SAFE_ACCESS(display, refresh_rate, 0), //
3638 SAFE_ACCESS(display, width, 0), //
3639 SAFE_ACCESS(display, height, 0), //
3640 SAFE_ACCESS(display, device_pixel_ratio, 1)));
3641 display = reinterpret_cast<const FlutterEngineDisplay*>(
3642 reinterpret_cast<const uint8_t*>(display) + display->struct_size);
3643 }
3644 engine->GetShell().OnDisplayUpdates(std::move(displays));
3645 return kSuccess;
3646 }
3647 default:
3648 return LOG_EMBEDDER_ERROR(
3650 "Invalid FlutterEngineDisplaysUpdateType type specified.");
3651 }
3652}

References displays, engine, height, i, kFlutterEngineDisplaysUpdateTypeStartup, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, SAFE_ACCESS, and width.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineNotifyLowMemoryWarning()

FlutterEngineResult FlutterEngineNotifyLowMemoryWarning ( FLUTTER_API_SYMBOL(FlutterEngine engine)

Posts a low memory notification to a running engine instance. The engine will do its best to release non-critical resources in response. It is not guaranteed that the resource would have been collected by the time this call returns however. The notification is posted to engine subsystems that may be operating on other threads.

Flutter applications can respond to these notifications by setting WidgetsBindingObserver.didHaveMemoryPressure observers.

Parameters
[in]engineA running engine instance.
Returns
If the low memory notification was sent to the running engine instance.

Definition at line 3552 of file embedder.cc.

3553 {
3554 auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine);
3555 if (engine == nullptr || !engine->IsValid()) {
3556 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine was invalid.");
3557 }
3558
3559 engine->GetShell().NotifyLowMemoryWarning();
3560
3561 rapidjson::Document document;
3562 auto& allocator = document.GetAllocator();
3563
3564 document.SetObject();
3565 document.AddMember("type", "memoryPressure", allocator);
3566
3567 return DispatchJSONPlatformMessage(raw_engine, document, "flutter/system")
3568 ? kSuccess
3571 "Could not dispatch the low memory notification message.");
3572}

References allocator, DispatchJSONPlatformMessage(), engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEngineOnVsync()

FlutterEngineResult FlutterEngineOnVsync ( FLUTTER_API_SYMBOL(FlutterEngine engine,
intptr_t  baton,
uint64_t  frame_start_time_nanos,
uint64_t  frame_target_time_nanos 
)

Notify the engine that a vsync event occurred. A baton passed to the platform via the vsync callback must be returned. This call must be made on the thread on which the call to FlutterEngineRun was made.

See also
FlutterEngineGetCurrentTime()
Attention
That frame timepoints are in nanoseconds.
The system monotonic clock is used as the timebase.
Parameters
[in]engine.A running engine instance.
[in]batonThe baton supplied by the engine.
[in]frame_start_time_nanosThe point at which the vsync event occurred or will occur. If the time point is in the future, the engine will wait till that point to begin its frame workload.
[in]frame_target_time_nanosThe point at which the embedder anticipates the next vsync to occur. This is a hint the engine uses to schedule Dart VM garbage collection in periods in which the various threads are most likely to be idle. For example, for a 60Hz display, embedders should add 16.6 * 1e6 to the frame time field.
Returns
The result of the call.

Definition at line 3229 of file embedder.cc.

3233 {
3234 if (engine == nullptr) {
3235 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3236 }
3237
3238 TRACE_EVENT0("flutter", "FlutterEngineOnVsync");
3239
3240 auto start_time = fml::TimePoint::FromEpochDelta(
3241 fml::TimeDelta::FromNanoseconds(frame_start_time_nanos));
3242
3243 auto target_time = fml::TimePoint::FromEpochDelta(
3244 fml::TimeDelta::FromNanoseconds(frame_target_time_nanos));
3245
3246 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->OnVsyncEvent(
3247 baton, start_time, target_time)) {
3248 return LOG_EMBEDDER_ERROR(
3250 "Could not notify the running engine instance of a Vsync event.");
3251 }
3252
3253 return kSuccess;
3254}

References engine, fml::TimePoint::FromEpochDelta(), fml::TimeDelta::FromNanoseconds(), kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and TRACE_EVENT0.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEnginePostCallbackOnAllNativeThreads()

FlutterEngineResult FlutterEnginePostCallbackOnAllNativeThreads ( FLUTTER_API_SYMBOL(FlutterEngine engine,
FlutterNativeThreadCallback  callback,
void *  user_data 
)

Schedule a callback to be run on all engine managed threads. The engine will attempt to service this callback the next time the message loop for each managed thread is idle. Since the engine manages the entire lifecycle of multiple threads, there is no opportunity for the embedders to finely tune the priorities of threads directly, or, perform other thread specific configuration (for example, setting thread names for tracing). This callback gives embedders a chance to affect such tuning.

Attention
This call is expensive and must be made as few times as possible. The callback must also return immediately as not doing so may risk performance issues (especially for callbacks of type kFlutterNativeThreadTypeUI and kFlutterNativeThreadTypeRender).
Some callbacks (especially the ones of type kFlutterNativeThreadTypeWorker) may be called after the FlutterEngine instance has shut down. Embedders must be careful in handling the lifecycle of objects associated with the user data baton.
In case there are multiple running Flutter engine instances, their workers are shared.
Parameters
[in]engineA running engine instance.
[in]callbackThe callback that will get called multiple times on each engine managed thread.
[in]user_dataA baton passed by the engine to the callback. This baton is not interpreted by the engine in any way.
Returns
Returns if the callback was successfully posted to all threads.

Definition at line 3574 of file embedder.cc.

3577 {
3578 if (engine == nullptr) {
3579 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3580 }
3581
3582 if (callback == nullptr) {
3584 "Invalid native thread callback.");
3585 }
3586
3587 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3588 ->PostTaskOnEngineManagedNativeThreads(
3591 })
3592 ? kSuccess
3594 "Internal error while attempting to post "
3595 "tasks to all threads.");
3596}

References callback, engine, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, type, and user_data.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEnginePostDartObject()

FlutterEngineResult FlutterEnginePostDartObject ( FLUTTER_API_SYMBOL(FlutterEngine engine,
FlutterEngineDartPort  port,
const FlutterEngineDartObject object 
)

Posts a Dart object to specified send port. The corresponding receive port for send port can be in any isolate running in the VM. This isolate can also be the root isolate for an unrelated engine. The engine parameter is necessary only to ensure the call is not made when no engine (and hence no VM) is running.

Unlike the platform messages mechanism, there are no threading restrictions when using this API. Message can be posted on any thread and they will be made available to isolate on which the corresponding send port is listening.

However, it is the embedders responsibility to ensure that the call is not made during an ongoing call the FlutterEngineDeinitialize or FlutterEngineShutdown on another thread.

Parameters
[in]engineA running engine instance.
[in]portThe send port to send the object to.
[in]objectThe object to send to the isolate with the corresponding receive port.
Returns
If the message was posted to the send port.

Definition at line 3428 of file embedder.cc.

3431 {
3432 if (engine == nullptr) {
3433 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3434 }
3435
3436 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->IsValid()) {
3437 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine not running.");
3438 }
3439
3440 if (port == ILLEGAL_PORT) {
3442 "Attempted to post to an illegal port.");
3443 }
3444
3445 if (object == nullptr) {
3447 "Invalid Dart object to post.");
3448 }
3449
3450 Dart_CObject dart_object = {};
3451 fml::ScopedCleanupClosure typed_data_finalizer;
3452
3453 switch (object->type) {
3455 dart_object.type = Dart_CObject_kNull;
3456 break;
3458 dart_object.type = Dart_CObject_kBool;
3459 dart_object.value.as_bool = object->bool_value;
3460 break;
3462 dart_object.type = Dart_CObject_kInt32;
3463 dart_object.value.as_int32 = object->int32_value;
3464 break;
3466 dart_object.type = Dart_CObject_kInt64;
3467 dart_object.value.as_int64 = object->int64_value;
3468 break;
3470 dart_object.type = Dart_CObject_kDouble;
3471 dart_object.value.as_double = object->double_value;
3472 break;
3474 if (object->string_value == nullptr) {
3476 "kFlutterEngineDartObjectTypeString must be "
3477 "a null terminated string but was null.");
3478 }
3479 dart_object.type = Dart_CObject_kString;
3480 dart_object.value.as_string = const_cast<char*>(object->string_value);
3481 break;
3483 auto* buffer = SAFE_ACCESS(object->buffer_value, buffer, nullptr);
3484 if (buffer == nullptr) {
3486 "kFlutterEngineDartObjectTypeBuffer must "
3487 "specify a buffer but found nullptr.");
3488 }
3489 auto buffer_size = SAFE_ACCESS(object->buffer_value, buffer_size, 0);
3490 auto callback =
3491 SAFE_ACCESS(object->buffer_value, buffer_collect_callback, nullptr);
3492 auto user_data = SAFE_ACCESS(object->buffer_value, user_data, nullptr);
3493
3494 // The user has provided a callback, let them manage the lifecycle of
3495 // the underlying data. If not, copy it out from the provided buffer.
3496
3497 if (callback == nullptr) {
3498 dart_object.type = Dart_CObject_kTypedData;
3499 dart_object.value.as_typed_data.type = Dart_TypedData_kUint8;
3500 dart_object.value.as_typed_data.length = buffer_size;
3501 dart_object.value.as_typed_data.values = buffer;
3502 } else {
3503 struct ExternalTypedDataPeer {
3504 void* user_data = nullptr;
3505 VoidCallback trampoline = nullptr;
3506 };
3507 auto peer = new ExternalTypedDataPeer();
3508 peer->user_data = user_data;
3509 peer->trampoline = callback;
3510 // This finalizer is set so that in case of failure of the
3511 // Dart_PostCObject below, we collect the peer. The embedder is still
3512 // responsible for collecting the buffer in case of non-kSuccess
3513 // returns from this method. This finalizer must be released in case
3514 // of kSuccess returns from this method.
3515 typed_data_finalizer.SetClosure([peer]() {
3516 // This is the tiny object we use as the peer to the Dart call so
3517 // that we can attach the a trampoline to the embedder supplied
3518 // callback. In case of error, we need to collect this object lest
3519 // we introduce a tiny leak.
3520 delete peer;
3521 });
3522 dart_object.type = Dart_CObject_kExternalTypedData;
3523 dart_object.value.as_external_typed_data.type = Dart_TypedData_kUint8;
3524 dart_object.value.as_external_typed_data.length = buffer_size;
3525 dart_object.value.as_external_typed_data.data = buffer;
3526 dart_object.value.as_external_typed_data.peer = peer;
3527 dart_object.value.as_external_typed_data.callback =
3528 +[](void* unused_isolate_callback_data, void* peer) {
3529 auto typed_peer = reinterpret_cast<ExternalTypedDataPeer*>(peer);
3530 typed_peer->trampoline(typed_peer->user_data);
3531 delete typed_peer;
3532 };
3533 }
3534 } break;
3535 default:
3536 return LOG_EMBEDDER_ERROR(
3538 "Invalid FlutterEngineDartObjectType type specified.");
3539 }
3540
3541 if (!Dart_PostCObject(port, &dart_object)) {
3543 "Could not post the object to the Dart VM.");
3544 }
3545
3546 // On a successful call, the VM takes ownership of and is responsible for
3547 // invoking the finalizer.
3548 typed_data_finalizer.Release();
3549 return kSuccess;
3550}

References FlutterEngineDartObject::buffer_value, callback, engine, kFlutterEngineDartObjectTypeBool, kFlutterEngineDartObjectTypeBuffer, kFlutterEngineDartObjectTypeDouble, kFlutterEngineDartObjectTypeInt32, kFlutterEngineDartObjectTypeInt64, kFlutterEngineDartObjectTypeNull, kFlutterEngineDartObjectTypeString, kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, fml::ScopedCleanupClosure::Release(), SAFE_ACCESS, fml::ScopedCleanupClosure::SetClosure(), FlutterEngineDartObject::string_value, FlutterEngineDartObject::type, and user_data.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEnginePostRenderThreadTask()

FlutterEngineResult FlutterEnginePostRenderThreadTask ( FLUTTER_API_SYMBOL(FlutterEngine engine,
VoidCallback  callback,
void *  callback_data 
)

Posts a task onto the Flutter render thread. Typically, this may be called from any thread as long as a FlutterEngineShutdown on the specific engine has not already been initiated.

Parameters
[in]engineA running engine instance.
[in]callbackThe callback to execute on the render thread.
callback_dataThe callback context.
Returns
The result of the call.

Definition at line 3287 of file embedder.cc.

3290 {
3291 if (engine == nullptr) {
3292 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3293 }
3294
3295 if (callback == nullptr) {
3297 "Render thread callback was null.");
3298 }
3299
3300 auto task = [callback, baton]() { callback(baton); };
3301
3302 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3303 ->PostRenderThreadTask(task)
3304 ? kSuccess
3306 "Could not post the render thread task.");
3307}

References callback, engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses().

◆ FlutterEngineRegisterExternalTexture()

FlutterEngineResult FlutterEngineRegisterExternalTexture ( FLUTTER_API_SYMBOL(FlutterEngine engine,
int64_t  texture_identifier 
)

Register an external texture with a unique (per engine) identifier. Only rendering backends that support external textures accept external texture registrations. After the external texture is registered, the application can mark that a frame is available by calling FlutterEngineMarkExternalTextureFrameAvailable.

See also
FlutterEngineUnregisterExternalTexture()
FlutterEngineMarkExternalTextureFrameAvailable()
Parameters
[in]engineA running engine instance.
[in]texture_identifierThe identifier of the texture to register with the engine. The embedder may supply new frames to this texture using the same identifier.
Returns
The result of the call.

Definition at line 3110 of file embedder.cc.

3112 {
3113 if (engine == nullptr) {
3114 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
3115 }
3116
3117 if (texture_identifier == 0) {
3119 "Texture identifier was invalid.");
3120 }
3121 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->RegisterTexture(
3122 texture_identifier)) {
3124 "Could not register the specified texture.");
3125 }
3126 return kSuccess;
3127}

References engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEngineReloadSystemFonts()

FlutterEngineResult FlutterEngineReloadSystemFonts ( FLUTTER_API_SYMBOL(FlutterEngine engine)

Reloads the system fonts in engine.

Parameters
[in]engine.A running engine instance.
Returns
The result of the call.

Definition at line 3256 of file embedder.cc.

3257 {
3258 if (engine == nullptr) {
3259 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3260 }
3261
3262 TRACE_EVENT0("flutter", "FlutterEngineReloadSystemFonts");
3263
3264 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3265 ->ReloadSystemFonts()) {
3267 "Could not reload system fonts.");
3268 }
3269
3270 return kSuccess;
3271}

References engine, kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and TRACE_EVENT0.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEngineRemoveView()

FLUTTER_EXPORT FlutterEngineResult FlutterEngineRemoveView ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterRemoveViewInfo info 
)

Removes a view.

        This is an asynchronous operation. The view's resources must not
        be cleaned up until |info.remove_view_callback| is invoked with
        a |removed| value of true.

        The callback is invoked on a thread managed by the engine. The
        embedder should re-thread if needed.

        Attempting to remove the implicit view will fail and will return
        kInvalidArguments. Attempting to remove a view with a
        non-existent view ID will fail, and |info.remove_view_callback|
        will be invoked with a |removed| value of false.
Parameters
[in]engineA running engine instance.
[in]infoThe remove view arguments. This can be deallocated once |FlutterEngineRemoveView| returns, before |remove_view_callback| is invoked.
Returns
The result of starting the asynchronous operation. If kSuccess, the |remove_view_callback| will be invoked.

Definition at line 2561 of file embedder.cc.

2563 {
2564 if (!engine) {
2565 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2566 }
2567 if (!info || !info->remove_view_callback) {
2569 "Remove view info handle was invalid.");
2570 }
2571
2572 if (info->view_id == kFlutterImplicitViewId) {
2573 return LOG_EMBEDDER_ERROR(
2575 "Remove view info was invalid. The implicit view cannot be removed.");
2576 }
2577
2578 // TODO(loicsharma): Return an error if the engine was initialized with
2579 // callbacks that are incompatible with multiple views.
2580 // https://github.com/flutter/flutter/issues/144806
2581
2582 // The engine must be running to remove a view.
2583 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2584 if (!embedder_engine->IsValid()) {
2585 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2586 }
2587
2589 [c_callback = info->remove_view_callback,
2590 user_data = info->user_data](bool removed) {
2591 FlutterRemoveViewResult result = {};
2592 result.struct_size = sizeof(FlutterRemoveViewResult);
2593 result.removed = removed;
2594 result.user_data = user_data;
2595 c_callback(&result);
2596 };
2597
2598 embedder_engine->GetShell().GetPlatformView()->RemoveView(info->view_id,
2599 callback);
2600 return kSuccess;
2601}

References callback, engine, kFlutterImplicitViewId, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, FlutterRemoveViewInfo::remove_view_callback, FlutterRemoveViewResult::removed, FlutterRemoveViewResult::struct_size, user_data, FlutterRemoveViewResult::user_data, FlutterRemoveViewInfo::user_data, and FlutterRemoveViewInfo::view_id.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineRun()

FlutterEngineResult FlutterEngineRun ( size_t  version,
const FlutterRendererConfig config,
const FlutterProjectArgs args,
void *  user_data,
FLUTTER_API_SYMBOL(FlutterEngine) *  engine_out 
)

Initialize and run a Flutter engine instance and return a handle to it. This is a convenience method for the pair of calls to FlutterEngineInitialize and FlutterEngineRunInitialized.

Note
This method of running a Flutter engine works well except in cases where the embedder specifies custom task runners via FlutterProjectArgs::custom_task_runners. In such cases, the engine may need the embedder to post tasks back to it before FlutterEngineRun has returned. Embedders can only post tasks to the engine if they have a handle to the engine. In such cases, embedders are advised to get the engine handle by calling FlutterEngineInitialize. Then they can call FlutterEngineRunInitialized knowing that they will be able to service custom tasks on other threads with the engine handle.
Parameters
[in]versionThe Flutter embedder API version. Must be FLUTTER_ENGINE_VERSION.
[in]configThe renderer configuration.
[in]argsThe Flutter project arguments.
user_dataA user data baton passed back to embedders in callbacks.
[out]engine_outThe engine handle on successful engine creation.
Returns
The result of the call to run the Flutter engine.

Definition at line 1971 of file embedder.cc.

1976 {
1977 auto result =
1978 FlutterEngineInitialize(version, config, args, user_data, engine_out);
1979
1980 if (result != kSuccess) {
1981 return result;
1982 }
1983
1984 return FlutterEngineRunInitialized(*engine_out);
1985}

References args, FlutterEngineInitialize(), FlutterEngineRunInitialized(), kSuccess, and user_data.

Referenced by FlutterEngineGetProcAddresses(), main(), RunFlutter(), and RunFlutterEngine().

◆ FlutterEngineRunInitialized()

FlutterEngineResult FlutterEngineRunInitialized ( FLUTTER_API_SYMBOL(FlutterEngine engine)

Runs an initialized engine instance. An engine can be initialized via FlutterEngineInitialize. An initialized instance can only be run once. During and after this call, custom task runners supplied by the embedder are expected to start servicing tasks.

Parameters
[in]engineAn initialized engine instance that has not previously been run.
Returns
The result of the call to run the initialized Flutter engine instance.

Definition at line 2461 of file embedder.cc.

2462 {
2463 if (!engine) {
2464 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2465 }
2466
2467 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2468
2469 // The engine must not already be running. Initialize may only be called
2470 // once on an engine instance.
2471 if (embedder_engine->IsValid()) {
2472 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2473 }
2474
2475 // Step 1: Launch the shell.
2476 if (!embedder_engine->LaunchShell()) {
2478 "Could not launch the engine using supplied "
2479 "initialization arguments.");
2480 }
2481
2482 // Step 2: Tell the platform view to initialize itself.
2483 if (!embedder_engine->NotifyCreated()) {
2485 "Could not create platform view components.");
2486 }
2487
2488 // Step 3: Launch the root isolate.
2489 if (!embedder_engine->RunRootIsolate()) {
2490 return LOG_EMBEDDER_ERROR(
2492 "Could not run the root isolate of the Flutter application using the "
2493 "project arguments specified.");
2494 }
2495
2496 return kSuccess;
2497}

References engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses(), FlutterEngineRun(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_P().

◆ FlutterEngineRunsAOTCompiledDartCode()

bool FlutterEngineRunsAOTCompiledDartCode ( void  )

Returns if the Flutter engine instance will run AOT compiled Dart code. This call has no threading restrictions.

For embedder code that is configured for both AOT and JIT mode Dart execution based on the Flutter engine being linked to, this runtime check may be used to appropriately configure the FlutterProjectArgs. In JIT mode execution, the kernel snapshots must be present in the Flutter assets directory specified in the FlutterProjectArgs. For AOT execution, the fields vm_snapshot_data, vm_snapshot_instructions, isolate_snapshot_data and isolate_snapshot_instructions (along with their size fields) must be specified in FlutterProjectArgs.

Returns
True, if AOT Dart code is run. JIT otherwise.

Definition at line 3424 of file embedder.cc.

3424 {
3426}

References flutter::DartVM::IsRunningPrecompiledCode().

Referenced by FlutterEngineGetProcAddresses(), RunFlutterEngine(), and flutter::testing::TEST_F().

◆ FlutterEngineRunTask()

FlutterEngineResult FlutterEngineRunTask ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterTask task 
)

Inform the engine to run the specified task. This task has been given to the embedder via the FlutterTaskRunnerDescription.post_task_callback. This call must only be made at the target time specified in that callback. Running the task before that time is undefined behavior.

Parameters
[in]engineA running engine instance.
[in]taskthe task handle.
Returns
The result of the call.

Definition at line 3313 of file embedder.cc.

3315 {
3316 if (engine == nullptr) {
3317 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3318 }
3319
3321 reinterpret_cast<intptr_t>(task->runner))) {
3322 // This task came too late, the embedder has already been destroyed.
3323 // This is not an error, just ignore the task.
3324 return kSuccess;
3325 }
3326
3327 return reinterpret_cast<flutter::EmbedderEngine*>(engine)->RunTask(task)
3328 ? kSuccess
3330 "Could not run the specified task.");
3331}

References engine, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, FlutterTask::runner, and flutter::EmbedderThreadHost::RunnerIsValid().

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_P().

◆ FlutterEngineScheduleFrame()

FlutterEngineResult FlutterEngineScheduleFrame ( FLUTTER_API_SYMBOL(FlutterEngine engine)

Schedule a new frame to redraw the content.

Parameters
[in]engineA running engine instance.
Returns
the result of the call made to the engine.

Definition at line 3654 of file embedder.cc.

3655 {
3656 if (engine == nullptr) {
3657 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3658 }
3659
3660 return reinterpret_cast<flutter::EmbedderEngine*>(engine)->ScheduleFrame()
3661 ? kSuccess
3663 "Could not schedule frame.");
3664}

References engine, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEngineSendKeyEvent()

FlutterEngineResult FlutterEngineSendKeyEvent ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterKeyEvent event,
FlutterKeyEventCallback  callback,
void *  user_data 
)

Sends a key event to the engine. The framework will decide whether to handle this event in a synchronous fashion, although due to technical limitation, the result is always reported asynchronously. The callback is guaranteed to be called exactly once.

Parameters
[in]engineA running engine instance.
[in]eventThe event data to be sent. This function will no longer access event after returning.
[in]callbackThe callback invoked by the engine when the Flutter application has decided whether it handles this event. Accepts nullptr.
[in]user_dataThe context associated with the callback. The exact same value will used to invoke callback. Accepts nullptr.
Returns
The result of the call.

Definition at line 2921 of file embedder.cc.

2925 {
2926 if (engine == nullptr) {
2927 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2928 }
2929
2930 if (event == nullptr) {
2931 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid key event.");
2932 }
2933
2934 const char* character = SAFE_ACCESS(event, character, nullptr);
2935
2936 flutter::KeyData key_data;
2937 key_data.Clear();
2938 key_data.timestamp = static_cast<uint64_t>(SAFE_ACCESS(event, timestamp, 0));
2939 key_data.type = MapKeyEventType(
2941 key_data.physical = SAFE_ACCESS(event, physical, 0);
2942 key_data.logical = SAFE_ACCESS(event, logical, 0);
2943 key_data.synthesized = SAFE_ACCESS(event, synthesized, false);
2945 event, device_type,
2947
2948 auto packet = std::make_unique<flutter::KeyDataPacket>(key_data, character);
2949
2950 struct MessageData {
2952 void* user_data;
2953 };
2954
2955 MessageData* message_data =
2956 new MessageData{.callback = callback, .user_data = user_data};
2957
2958 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
2960 engine, kFlutterKeyDataChannel, packet->data().data(),
2961 packet->data().size(),
2962 [](const uint8_t* data, size_t size, void* user_data) {
2963 auto message_data = std::unique_ptr<MessageData>(
2964 reinterpret_cast<MessageData*>(user_data));
2965 if (message_data->callback == nullptr) {
2966 return;
2967 }
2968 bool handled = false;
2969 if (size == 1) {
2970 handled = *data != 0;
2971 }
2972 message_data->callback(handled, message_data->user_data);
2973 },
2974 message_data);
2975}

References callback, character, flutter::KeyData::Clear(), data, flutter::KeyData::device_type, engine, InternalSendPlatformMessage(), kFlutterKeyDataChannel, kFlutterKeyEventDeviceTypeKeyboard, kFlutterKeyEventTypeUp, kInvalidArguments, LOG_EMBEDDER_ERROR, flutter::KeyData::logical, MapKeyEventDeviceType(), MapKeyEventType(), flutter::KeyData::physical, SAFE_ACCESS, flutter::KeyData::synthesized, flutter::KeyData::timestamp, type, flutter::KeyData::type, and user_data.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineSendPlatformMessage()

FlutterEngineResult FlutterEngineSendPlatformMessage ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterPlatformMessage flutter_message 
)

Definition at line 2977 of file embedder.cc.

2979 {
2980 if (engine == nullptr) {
2981 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
2982 }
2983
2984 if (flutter_message == nullptr) {
2985 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid message argument.");
2986 }
2987
2988 if (SAFE_ACCESS(flutter_message, channel, nullptr) == nullptr) {
2989 return LOG_EMBEDDER_ERROR(
2990 kInvalidArguments, "Message argument did not specify a valid channel.");
2991 }
2992
2993 size_t message_size = SAFE_ACCESS(flutter_message, message_size, 0);
2994 const uint8_t* message_data = SAFE_ACCESS(flutter_message, message, nullptr);
2995
2996 if (message_size != 0 && message_data == nullptr) {
2997 return LOG_EMBEDDER_ERROR(
2999 "Message size was non-zero but the message data was nullptr.");
3000 }
3001
3002 const FlutterPlatformMessageResponseHandle* response_handle =
3003 SAFE_ACCESS(flutter_message, response_handle, nullptr);
3004
3006 if (response_handle && response_handle->message) {
3007 response = response_handle->message->response();
3008 }
3009
3010 std::unique_ptr<flutter::PlatformMessage> message;
3011 if (message_size == 0) {
3012 message = std::make_unique<flutter::PlatformMessage>(
3013 flutter_message->channel, response);
3014 } else {
3015 message = std::make_unique<flutter::PlatformMessage>(
3016 flutter_message->channel,
3017 fml::MallocMapping::Copy(message_data, message_size), response);
3018 }
3019
3020 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
3021 ->SendPlatformMessage(std::move(message))
3022 ? kSuccess
3024 "Could not send a message to the running "
3025 "Flutter application.");
3026}

References FlutterPlatformMessage::channel, channel, fml::MallocMapping::Copy(), engine, kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, _FlutterPlatformMessageResponseHandle::message, message, and SAFE_ACCESS.

Referenced by FlutterDesktopMessengerSendWithReply(), FlutterEngineGetProcAddresses(), InternalSendPlatformMessage(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineSendPlatformMessageResponse()

FlutterEngineResult FlutterEngineSendPlatformMessageResponse ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterPlatformMessageResponseHandle handle,
const uint8_t *  data,
size_t  data_length 
)

Send a response from the native side to a platform message from the Dart Flutter application.

Parameters
[in]engineThe running engine instance.
[in]handleThe platform message response handle.
[in]dataThe data to associate with the platform message response.
[in]data_lengthThe length of the platform message response data.
Returns
The result of the call.

Definition at line 3078 of file embedder.cc.

3082 {
3083 if (data_length != 0 && data == nullptr) {
3084 return LOG_EMBEDDER_ERROR(
3086 "Data size was non zero but the pointer to the data was null.");
3087 }
3088
3089 auto response = handle->message->response();
3090
3091 if (response) {
3092 if (data_length == 0) {
3093 response->CompleteEmpty();
3094 } else {
3095 response->Complete(std::make_unique<fml::DataMapping>(
3096 std::vector<uint8_t>({data, data + data_length})));
3097 }
3098 }
3099
3100 delete handle;
3101
3102 return kSuccess;
3103}

References data, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and _FlutterPlatformMessageResponseHandle::message.

Referenced by FlutterDesktopMessengerSendResponse(), FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineSendPointerEvent()

FlutterEngineResult FlutterEngineSendPointerEvent ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterPointerEvent pointers,
size_t  events_count 
)

Definition at line 2769 of file embedder.cc.

2772 {
2773 if (engine == nullptr) {
2774 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2775 }
2776
2777 if (pointers == nullptr || events_count == 0) {
2778 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid pointer events.");
2779 }
2780
2781 auto packet = std::make_unique<flutter::PointerDataPacket>(events_count);
2782
2783 const FlutterPointerEvent* current = pointers;
2784
2785 for (size_t i = 0; i < events_count; ++i) {
2786 flutter::PointerData pointer_data;
2787 pointer_data.Clear();
2788 // this is currely in use only on android embedding.
2789 pointer_data.embedder_id = 0;
2790 pointer_data.time_stamp = SAFE_ACCESS(current, timestamp, 0);
2791 pointer_data.change = ToPointerDataChange(
2792 SAFE_ACCESS(current, phase, FlutterPointerPhase::kCancel));
2793 pointer_data.physical_x = SAFE_ACCESS(current, x, 0.0);
2794 pointer_data.physical_y = SAFE_ACCESS(current, y, 0.0);
2795 // Delta will be generated in pointer_data_packet_converter.cc.
2796 pointer_data.physical_delta_x = 0.0;
2797 pointer_data.physical_delta_y = 0.0;
2798 pointer_data.device = SAFE_ACCESS(current, device, 0);
2799 // Pointer identifier will be generated in
2800 // pointer_data_packet_converter.cc.
2801 pointer_data.pointer_identifier = 0;
2802 pointer_data.signal_kind = ToPointerDataSignalKind(
2803 SAFE_ACCESS(current, signal_kind, kFlutterPointerSignalKindNone));
2804 pointer_data.scroll_delta_x = SAFE_ACCESS(current, scroll_delta_x, 0.0);
2805 pointer_data.scroll_delta_y = SAFE_ACCESS(current, scroll_delta_y, 0.0);
2806 FlutterPointerDeviceKind device_kind =
2807 SAFE_ACCESS(current, device_kind, kFlutterPointerDeviceKindMouse);
2808 // For backwards compatibility with embedders written before the device
2809 // kind and buttons were exposed, if the device kind is not set treat it
2810 // as a mouse, with a synthesized primary button state based on the phase.
2811 if (device_kind == 0) {
2813 pointer_data.buttons =
2815
2816 } else {
2817 pointer_data.kind = ToPointerDataKind(device_kind);
2818 if (pointer_data.kind == flutter::PointerData::DeviceKind::kTouch) {
2819 // For touch events, set the button internally rather than requiring
2820 // it at the API level, since it's a confusing construction to expose.
2821 if (pointer_data.change == flutter::PointerData::Change::kDown ||
2824 }
2825 } else {
2826 // Buttons use the same mask values, so pass them through directly.
2827 pointer_data.buttons = SAFE_ACCESS(current, buttons, 0);
2828 }
2829 }
2830 pointer_data.pan_x = SAFE_ACCESS(current, pan_x, 0.0);
2831 pointer_data.pan_y = SAFE_ACCESS(current, pan_y, 0.0);
2832 // Delta will be generated in pointer_data_packet_converter.cc.
2833 pointer_data.pan_delta_x = 0.0;
2834 pointer_data.pan_delta_y = 0.0;
2835 pointer_data.scale = SAFE_ACCESS(current, scale, 0.0);
2836 pointer_data.rotation = SAFE_ACCESS(current, rotation, 0.0);
2837 pointer_data.view_id =
2839 packet->SetPointerData(i, pointer_data);
2840 current = reinterpret_cast<const FlutterPointerEvent*>(
2841 reinterpret_cast<const uint8_t*>(current) + current->struct_size);
2842 }
2843
2844 return reinterpret_cast<flutter::EmbedderEngine*>(engine)
2845 ->DispatchPointerDataPacket(std::move(packet))
2846 ? kSuccess
2848 "Could not dispatch pointer events to the "
2849 "running Flutter application.");
2850}

References flutter::PointerData::buttons, flutter::PointerData::change, flutter::PointerData::Clear(), device, flutter::PointerData::device, flutter::PointerData::embedder_id, engine, i, kCancel, flutter::PointerData::kDown, kFlutterImplicitViewId, kFlutterPointerDeviceKindMouse, kFlutterPointerSignalKindNone, flutter::PointerData::kind, kInternalInconsistency, kInvalidArguments, flutter::PointerData::kMouse, flutter::PointerData::kMove, flutter::kPointerButtonTouchContact, kSuccess, flutter::PointerData::kTouch, LOG_EMBEDDER_ERROR, flutter::PointerData::pan_delta_x, flutter::PointerData::pan_delta_y, flutter::PointerData::pan_x, flutter::PointerData::pan_y, flutter::PointerData::physical_delta_x, flutter::PointerData::physical_delta_y, flutter::PointerData::physical_x, flutter::PointerData::physical_y, flutter::PointerData::pointer_identifier, PointerDataButtonsForLegacyEvent(), flutter::PointerData::rotation, SAFE_ACCESS, flutter::PointerData::scale, flutter::PointerData::scroll_delta_x, flutter::PointerData::scroll_delta_y, flutter::PointerData::signal_kind, FlutterPointerEvent::struct_size, flutter::PointerData::time_stamp, ToPointerDataChange(), ToPointerDataKind(), ToPointerDataSignalKind(), flutter::PointerData::view_id, view_id, x, and y.

Referenced by FlutterEngineGetProcAddresses(), GLFWcursorPositionCallbackAtPhase(), SendPointerEventWithData(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineSendSemanticsAction()

FlutterEngineResult FlutterEngineSendSemanticsAction ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterSendSemanticsActionInfo info 
)

Dispatch a semantics action to the specified semantics node within a specific view.

Parameters
[in]engineA running engine instance.
[in]infoThe dispatch semantics on view arguments. This can be deallocated once |FlutterEngineSendSemanticsAction| returns.
Returns
The result of the call.

Definition at line 3212 of file embedder.cc.

3214 {
3215 if (engine == nullptr) {
3216 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3217 }
3218 auto engine_action = static_cast<flutter::SemanticsAction>(info->action);
3219 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3221 info->view_id, info->node_id, engine_action,
3222 fml::MallocMapping::Copy(info->data, info->data_length))) {
3224 "Could not dispatch semantics action.");
3225 }
3226 return kSuccess;
3227}

References FlutterSendSemanticsActionInfo::action, fml::MallocMapping::Copy(), FlutterSendSemanticsActionInfo::data, FlutterSendSemanticsActionInfo::data_length, flutter::EmbedderEngine::DispatchSemanticsAction(), engine, kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, FlutterSendSemanticsActionInfo::node_id, and FlutterSendSemanticsActionInfo::view_id.

Referenced by FlutterEngineDispatchSemanticsAction(), and FlutterEngineGetProcAddresses().

◆ FlutterEngineSendViewFocusEvent()

FlutterEngineResult FlutterEngineSendViewFocusEvent ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterViewFocusEvent event 
)

Notifies the engine that platform view focus state has changed.

Parameters
[in]engineA running engine instance
[in]eventThe focus event data describing the change.

Definition at line 2603 of file embedder.cc.

2605 {
2606 if (!engine) {
2607 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2608 }
2609 if (!event) {
2611 "View focus event must not be null.");
2612 }
2613 // The engine must be running to focus a view.
2614 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2615 if (!embedder_engine->IsValid()) {
2616 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2617 }
2618
2619 if (!STRUCT_HAS_MEMBER(event, direction)) {
2621 "The event struct has invalid size.");
2622 }
2623
2624 flutter::ViewFocusEvent flutter_event(
2625 event->view_id, //
2626 static_cast<flutter::ViewFocusState>(event->state),
2627 static_cast<flutter::ViewFocusDirection>(event->direction));
2628
2629 embedder_engine->GetShell().GetPlatformView()->SendViewFocusEvent(
2630 flutter_event);
2631
2632 return kSuccess;
2633}

References FlutterViewFocusEvent::direction, engine, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, FlutterViewFocusEvent::state, STRUCT_HAS_MEMBER, and FlutterViewFocusEvent::view_id.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEngineSendWindowMetricsEvent()

FlutterEngineResult FlutterEngineSendWindowMetricsEvent ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterWindowMetricsEvent flutter_metrics 
)

Definition at line 2660 of file embedder.cc.

2662 {
2663 if (engine == nullptr || flutter_metrics == nullptr) {
2664 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
2665 }
2667 SAFE_ACCESS(flutter_metrics, view_id, kFlutterImplicitViewId);
2668
2669 std::variant<flutter::ViewportMetrics, std::string> metrics_or_error =
2670 MakeViewportMetricsFromWindowMetrics(flutter_metrics);
2671 if (const std::string* error = std::get_if<std::string>(&metrics_or_error)) {
2672 return LOG_EMBEDDER_ERROR(kInvalidArguments, error->c_str());
2673 }
2674
2675 auto metrics = std::get<flutter::ViewportMetrics>(metrics_or_error);
2676
2677 return reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetViewportMetrics(
2678 view_id, metrics)
2679 ? kSuccess
2681 "Viewport metrics were invalid.");
2682}

References engine, error, kFlutterImplicitViewId, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, MakeViewportMetricsFromWindowMetrics(), SAFE_ACCESS, and view_id.

Referenced by flutter::testing::expectSoftwareRenderingOutputMatches(), FlutterEngineGetProcAddresses(), GLFWframebufferSizeCallback(), GLFWwindowSizeCallback(), SendWindowMetrics(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_P(), flutter::testing::TEST_P(), flutter::testing::TEST_P(), flutter::testing::TEST_P(), flutter::testing::TEST_P(), and flutter::testing::TEST_P().

◆ FlutterEngineSetNextFrameCallback()

FlutterEngineResult FlutterEngineSetNextFrameCallback ( FLUTTER_API_SYMBOL(FlutterEngine engine,
VoidCallback  callback,
void *  user_data 
)

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 from the raster thread; embedders must re-thread if necessary. Performing blocking calls in this callback may introduce application jank.

Parameters
[in]engineA running engine instance.
[in]callbackThe callback to execute.
[in]user_dataA baton passed by the engine to the callback. This baton is not interpreted by the engine in any way.
Returns
The result of the call.

Definition at line 3666 of file embedder.cc.

3669 {
3670 if (engine == nullptr) {
3671 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3672 }
3673
3674 if (callback == nullptr) {
3676 "Next frame callback was null.");
3677 }
3678
3679 flutter::EmbedderEngine* embedder_engine =
3680 reinterpret_cast<flutter::EmbedderEngine*>(engine);
3681
3682 fml::WeakPtr<flutter::PlatformView> weak_platform_view =
3683 embedder_engine->GetShell().GetPlatformView();
3684
3685 if (!weak_platform_view) {
3687 "Platform view unavailable.");
3688 }
3689
3690 weak_platform_view->SetNextFrameCallback(
3692
3693 return kSuccess;
3694}

References callback, engine, flutter::Shell::GetPlatformView(), flutter::EmbedderEngine::GetShell(), kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and user_data.

Referenced by FlutterEngineGetProcAddresses(), and flutter::testing::TEST_F().

◆ FlutterEngineShutdown()

FlutterEngineResult FlutterEngineShutdown ( FLUTTER_API_SYMBOL(FlutterEngine engine)

Shuts down a Flutter engine instance. The engine handle is no longer valid for any calls in the embedder API after this point. Making additional calls with this handle is undefined behavior.

Note
This de-initializes the Flutter engine instance (via an implicit call to FlutterEngineDeinitialize) if necessary.
Parameters
[in]engineThe Flutter engine instance to collect.
Returns
The result of the call to shutdown the Flutter engine instance.

Definition at line 2649 of file embedder.cc.

2650 {
2651 auto result = FlutterEngineDeinitialize(engine);
2652 if (result != kSuccess) {
2653 return result;
2654 }
2655 auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
2656 delete embedder_engine;
2657 return kSuccess;
2658}

References engine, FlutterEngineDeinitialize(), and kSuccess.

Referenced by FlutterDesktopDestroyWindow(), FlutterDesktopShutDownEngine(), FlutterEngineGetProcAddresses(), flutter::testing::UniqueEngineTraits::Free(), main(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineTraceEventDurationBegin()

void FlutterEngineTraceEventDurationBegin ( const char *  name)

A profiling utility. Logs a trace duration begin event to the timeline. If the timeline is unavailable or disabled, this has no effect. Must be balanced with an duration end event (via FlutterEngineTraceEventDurationEnd) with the same name on the same thread. Can be called on any thread. Strings passed into the function will NOT be copied when added to the timeline. Only string literals may be passed in.

Parameters
[in]nameThe name of the trace event.

Definition at line 3273 of file embedder.cc.

3273 {
3274 fml::tracing::TraceEvent0("flutter", name, /*flow_id_count=*/0,
3275 /*flow_ids=*/nullptr);
3276}

References name, and fml::tracing::TraceEvent0().

Referenced by FlutterEngineGetProcAddresses().

◆ FlutterEngineTraceEventDurationEnd()

void FlutterEngineTraceEventDurationEnd ( const char *  name)

A profiling utility. Logs a trace duration end event to the timeline. If the timeline is unavailable or disabled, this has no effect. This call must be preceded by a trace duration begin call (via FlutterEngineTraceEventDurationBegin) with the same name on the same thread. Can be called on any thread. Strings passed into the function will NOT be copied when added to the timeline. Only string literals may be passed in.

Parameters
[in]nameThe name of the trace event.

Definition at line 3278 of file embedder.cc.

3278 {
3280}

References name, and fml::tracing::TraceEventEnd().

Referenced by FlutterEngineGetProcAddresses().

◆ FlutterEngineTraceEventInstant()

void FlutterEngineTraceEventInstant ( const char *  name)

A profiling utility. Logs a trace duration instant event to the timeline. If the timeline is unavailable or disabled, this has no effect. Can be called on any thread. Strings passed into the function will NOT be copied when added to the timeline. Only string literals may be passed in.

Parameters
[in]nameThe name of the trace event.

Definition at line 3282 of file embedder.cc.

3282 {
3283 fml::tracing::TraceEventInstant0("flutter", name, /*flow_id_count=*/0,
3284 /*flow_ids=*/nullptr);
3285}

References name, and fml::tracing::TraceEventInstant0().

Referenced by FlutterEngineGetProcAddresses().

◆ FlutterEngineUnregisterExternalTexture()

FlutterEngineResult FlutterEngineUnregisterExternalTexture ( FLUTTER_API_SYMBOL(FlutterEngine engine,
int64_t  texture_identifier 
)

Unregister a previous texture registration.

See also
FlutterEngineRegisterExternalTexture()
FlutterEngineMarkExternalTextureFrameAvailable()
Parameters
[in]engineA running engine instance.
[in]texture_identifierThe identifier of the texture for which new frame will not be available.
Returns
The result of the call.

Definition at line 3129 of file embedder.cc.

3131 {
3132 if (engine == nullptr) {
3133 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
3134 }
3135
3136 if (texture_identifier == 0) {
3138 "Texture identifier was invalid.");
3139 }
3140
3141 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->UnregisterTexture(
3142 texture_identifier)) {
3144 "Could not un-register the specified texture.");
3145 }
3146
3147 return kSuccess;
3148}

References engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses().

◆ FlutterEngineUpdateAccessibilityFeatures()

FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures ( FLUTTER_API_SYMBOL(FlutterEngine engine,
FlutterAccessibilityFeature  features 
)

Sets additional accessibility features.

Parameters
[in]engineA running engine instance
[in]featuresThe accessibility features to set.
Returns
The result of the call.

Definition at line 3182 of file embedder.cc.

3184 {
3185 if (engine == nullptr) {
3186 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3187 }
3188 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
3189 ->SetAccessibilityFeatures(flags)) {
3191 "Could not update accessibility features.");
3192 }
3193 return kSuccess;
3194}

References engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterEngineUpdateLocales()

FlutterEngineResult FlutterEngineUpdateLocales ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const FlutterLocale **  locales,
size_t  locales_count 
)

Notify a running engine instance that the locale has been updated. The preferred locale must be the first item in the list of locales supplied. The other entries will be used as a fallback.

Parameters
[in]engineA running engine instance.
[in]localesThe updated locales in the order of preference.
[in]locales_countThe count of locales supplied.
Returns
Whether the locale updates were applied.

Definition at line 3365 of file embedder.cc.

3368 {
3369 if (engine == nullptr) {
3370 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3371 }
3372
3373 if (locales_count == 0) {
3374 return kSuccess;
3375 }
3376
3377 if (locales == nullptr) {
3378 return LOG_EMBEDDER_ERROR(kInvalidArguments, "No locales were specified.");
3379 }
3380
3381 rapidjson::Document document;
3382 auto& allocator = document.GetAllocator();
3383
3384 document.SetObject();
3385 document.AddMember("method", "setLocale", allocator);
3386
3387 rapidjson::Value args(rapidjson::kArrayType);
3388 args.Reserve(locales_count * 4, allocator);
3389 for (size_t i = 0; i < locales_count; ++i) {
3390 const FlutterLocale* locale = locales[i];
3391 const char* language_code_str = SAFE_ACCESS(locale, language_code, nullptr);
3392 if (language_code_str == nullptr || ::strlen(language_code_str) == 0) {
3393 return LOG_EMBEDDER_ERROR(
3395 "Language code is required but not present in FlutterLocale.");
3396 }
3397
3398 const char* country_code_str = SAFE_ACCESS(locale, country_code, "");
3399 const char* script_code_str = SAFE_ACCESS(locale, script_code, "");
3400 const char* variant_code_str = SAFE_ACCESS(locale, variant_code, "");
3401
3402 rapidjson::Value language_code, country_code, script_code, variant_code;
3403
3404 language_code.SetString(language_code_str, allocator);
3405 country_code.SetString(country_code_str ? country_code_str : "", allocator);
3406 script_code.SetString(script_code_str ? script_code_str : "", allocator);
3407 variant_code.SetString(variant_code_str ? variant_code_str : "", allocator);
3408
3409 // Required.
3410 args.PushBack(language_code, allocator);
3411 args.PushBack(country_code, allocator);
3412 args.PushBack(script_code, allocator);
3413 args.PushBack(variant_code, allocator);
3414 }
3415 document.AddMember("args", args, allocator);
3416
3417 return DispatchJSONPlatformMessage(engine, document, "flutter/localization")
3418 ? kSuccess
3420 "Could not send message to update locale of "
3421 "a running Flutter application.");
3422}

References allocator, args, DispatchJSONPlatformMessage(), engine, i, kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and SAFE_ACCESS.

Referenced by FlutterEngineGetProcAddresses(), SetUpLocales(), and flutter::testing::TEST_F().

◆ FlutterEngineUpdateSemanticsEnabled()

FlutterEngineResult FlutterEngineUpdateSemanticsEnabled ( FLUTTER_API_SYMBOL(FlutterEngine engine,
bool  enabled 
)

Enable or disable accessibility semantics.

Parameters
[in]engineA running engine instance.
[in]enabledWhen enabled, changes to the semantic contents of the window are sent via the FlutterUpdateSemanticsCallback2 registered to update_semantics_callback2 in FlutterProjectArgs.
Returns
The result of the call.

Definition at line 3168 of file embedder.cc.

3170 {
3171 if (engine == nullptr) {
3172 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3173 }
3174 if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetSemanticsEnabled(
3175 enabled)) {
3177 "Could not update semantics state.");
3178 }
3179 return kSuccess;
3180}

References engine, kInternalInconsistency, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterPlatformMessageCreateResponseHandle()

FlutterEngineResult FlutterPlatformMessageCreateResponseHandle ( FLUTTER_API_SYMBOL(FlutterEngine engine,
FlutterDataCallback  data_callback,
void *  user_data,
FlutterPlatformMessageResponseHandle **  response_out 
)

Creates a platform message response handle that allows the embedder to set a native callback for a response to a message. This handle may be set on the response_handle field of any FlutterPlatformMessage sent to the engine.

The handle must be collected via a call to FlutterPlatformMessageReleaseResponseHandle. This may be done immediately after a call to FlutterEngineSendPlatformMessage with a platform message whose response handle contains the handle created using this call. In case a handle is created but never sent in a message, the release call must still be made. Not calling release on the handle results in a small memory leak.

The user data baton passed to the data callback is the one specified in this call as the third argument.

See also
FlutterPlatformMessageReleaseResponseHandle()
Parameters
[in]engineA running engine instance.
[in]data_callbackThe callback invoked by the engine when the Flutter application send a response on the handle.
[in]user_dataThe user data associated with the data callback.
[out]response_outThe response handle created when this call is successful.
Returns
The result of the call.

Definition at line 3028 of file embedder.cc.

3032 {
3033 if (engine == nullptr) {
3034 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
3035 }
3036
3037 if (data_callback == nullptr || response_out == nullptr) {
3038 return LOG_EMBEDDER_ERROR(
3039 kInvalidArguments, "Data callback or the response handle was invalid.");
3040 }
3041
3043 [user_data, data_callback](const uint8_t* data, size_t size) {
3044 data_callback(data, size, user_data);
3045 };
3046
3047 auto platform_task_runner = reinterpret_cast<flutter::EmbedderEngine*>(engine)
3048 ->GetTaskRunners()
3049 .GetPlatformTaskRunner();
3050
3051 auto handle = new FlutterPlatformMessageResponseHandle();
3052
3053 handle->message = std::make_unique<flutter::PlatformMessage>(
3054 "", // The channel is empty and unused as the response handle is going
3055 // to referenced directly in the |FlutterEngineSendPlatformMessage|
3056 // with the container message discarded.
3057 fml::MakeRefCounted<flutter::EmbedderPlatformMessageResponse>(
3058 std::move(platform_task_runner), response_callback));
3059 *response_out = handle;
3060 return kSuccess;
3061}

References data, engine, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and user_data.

Referenced by FlutterDesktopMessengerSendWithReply(), FlutterEngineGetProcAddresses(), InternalSendPlatformMessage(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ FlutterPlatformMessageReleaseResponseHandle()

FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle ( FLUTTER_API_SYMBOL(FlutterEngine engine,
FlutterPlatformMessageResponseHandle response 
)

Collects the handle created using FlutterPlatformMessageCreateResponseHandle.

See also
FlutterPlatformMessageCreateResponseHandle()
Parameters
[in]engineA running engine instance.
[in]responseThe platform message response handle to collect. These handles are created using FlutterPlatformMessageCreateResponseHandle().
Returns
The result of the call.

Definition at line 3063 of file embedder.cc.

3065 {
3066 if (engine == nullptr) {
3067 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
3068 }
3069
3070 if (response == nullptr) {
3071 return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid response handle.");
3072 }
3073 delete response;
3074 return kSuccess;
3075}

References engine, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

Referenced by FlutterDesktopMessengerSendWithReply(), FlutterEngineGetProcAddresses(), InternalSendPlatformMessage(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ InferExternalViewEmbedderFromArgs()

static fml::StatusOr< std::unique_ptr< flutter::EmbedderExternalViewEmbedder > > InferExternalViewEmbedderFromArgs ( const FlutterCompositor compositor,
bool  enable_impeller 
)
static

Creates an EmbedderExternalViewEmbedder.

When a non-OK status is returned, engine startup should be halted.

Definition at line 1535 of file embedder.cc.

1536 {
1537 if (compositor == nullptr) {
1538 return std::unique_ptr<flutter::EmbedderExternalViewEmbedder>{nullptr};
1539 }
1540
1541 auto c_create_callback =
1542 SAFE_ACCESS(compositor, create_backing_store_callback, nullptr);
1543 auto c_collect_callback =
1544 SAFE_ACCESS(compositor, collect_backing_store_callback, nullptr);
1545 auto c_present_callback =
1546 SAFE_ACCESS(compositor, present_layers_callback, nullptr);
1547 auto c_present_view_callback =
1548 SAFE_ACCESS(compositor, present_view_callback, nullptr);
1549 bool avoid_backing_store_cache =
1550 SAFE_ACCESS(compositor, avoid_backing_store_cache, false);
1551
1552 // Make sure the required callbacks are present
1553 if (!c_create_callback || !c_collect_callback) {
1555 "Required compositor callbacks absent.");
1556 }
1557 // Either the present view or the present layers callback must be provided.
1558 if ((!c_present_view_callback && !c_present_callback) ||
1559 (c_present_view_callback && c_present_callback)) {
1561 "Either present_layers_callback or "
1562 "present_view_callback must be provided but not both.");
1563 }
1564
1565 FlutterCompositor captured_compositor = *compositor;
1566
1568 create_render_target_callback =
1569 [captured_compositor, enable_impeller](
1570 GrDirectContext* context,
1571 const std::shared_ptr<impeller::AiksContext>& aiks_context,
1572 const auto& config) {
1573 return CreateEmbedderRenderTarget(&captured_compositor, config,
1574 context, aiks_context,
1575 enable_impeller);
1576 };
1577
1579 if (c_present_callback) {
1580 present_callback = [c_present_callback, user_data = compositor->user_data](
1581 FlutterViewId view_id, const auto& layers) {
1582 TRACE_EVENT0("flutter", "FlutterCompositorPresentLayers");
1583 return c_present_callback(const_cast<const FlutterLayer**>(layers.data()),
1584 layers.size(), user_data);
1585 };
1586 } else {
1587 FML_DCHECK(c_present_view_callback != nullptr);
1588 present_callback = [c_present_view_callback,
1589 user_data = compositor->user_data](
1590 FlutterViewId view_id, const auto& layers) {
1591 TRACE_EVENT0("flutter", "FlutterCompositorPresentLayers");
1592
1593 FlutterPresentViewInfo info = {
1595 .view_id = view_id,
1596 .layers = const_cast<const FlutterLayer**>(layers.data()),
1598 .user_data = user_data,
1599 };
1600
1601 return c_present_view_callback(&info);
1602 };
1603 }
1604
1605 return std::make_unique<flutter::EmbedderExternalViewEmbedder>(
1606 avoid_backing_store_cache, create_render_target_callback,
1607 present_callback);
1608}

References CreateEmbedderRenderTarget(), FML_DCHECK, fml::kInvalidArgument, layers, layers_count, SAFE_ACCESS, FlutterLayer::size, FlutterPresentViewInfo::struct_size, TRACE_EVENT0, user_data, FlutterCompositor::user_data, and view_id.

Referenced by FlutterEngineInitialize().

◆ InferMetalPlatformViewCreationCallback()

static flutter::Shell::CreateCallback< flutter::PlatformView > InferMetalPlatformViewCreationCallback ( const FlutterRendererConfig config,
void *  user_data,
const flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table,
std::unique_ptr< flutter::EmbedderExternalViewEmbedder external_view_embedder,
bool  enable_impeller 
)
static

Definition at line 517 of file embedder.cc.

524 {
525 if (config->type != kMetal) {
526 return nullptr;
527 }
528
529#ifdef SHELL_ENABLE_METAL
530 std::function<bool(flutter::GPUMTLTextureInfo texture)> metal_present =
531 [ptr = config->metal.present_drawable_callback,
533 FlutterMetalTexture embedder_texture;
534 embedder_texture.struct_size = sizeof(FlutterMetalTexture);
535 embedder_texture.texture = texture.texture;
536 embedder_texture.texture_id = texture.texture_id;
537 embedder_texture.user_data = texture.destruction_context;
538 embedder_texture.destruction_callback = texture.destruction_callback;
539 return ptr(user_data, &embedder_texture);
540 };
541 auto metal_get_texture =
543 const flutter::DlISize& frame_size) -> flutter::GPUMTLTextureInfo {
544 FlutterFrameInfo frame_info = {};
545 frame_info.struct_size = sizeof(FlutterFrameInfo);
546 frame_info.size = {static_cast<uint32_t>(frame_size.width),
547 static_cast<uint32_t>(frame_size.height)};
548 flutter::GPUMTLTextureInfo texture_info;
549
550 FlutterMetalTexture metal_texture = ptr(user_data, &frame_info);
551 texture_info.texture_id = metal_texture.texture_id;
552 texture_info.texture = metal_texture.texture;
553 texture_info.destruction_callback = metal_texture.destruction_callback;
554 texture_info.destruction_context = metal_texture.user_data;
555 return texture_info;
556 };
557
558 std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder =
559 std::move(external_view_embedder);
560
561 std::unique_ptr<flutter::EmbedderSurface> embedder_surface;
562
563 if (enable_impeller) {
565 metal_dispatch_table = {
566 .present = metal_present,
567 .get_texture = metal_get_texture,
568 };
569 embedder_surface = std::make_unique<flutter::EmbedderSurfaceMetalImpeller>(
570 const_cast<flutter::GPUMTLDeviceHandle>(config->metal.device),
573 metal_dispatch_table, view_embedder);
574 } else {
575#if !SLIMPELLER
577 {
578 .present = metal_present,
579 .get_texture = metal_get_texture,
580 };
581 embedder_surface = std::make_unique<flutter::EmbedderSurfaceMetalSkia>(
582 const_cast<flutter::GPUMTLDeviceHandle>(config->metal.device),
585 metal_dispatch_table, view_embedder);
586#else // !SLIMPELLER
587 FML_LOG(FATAL) << "Impeller opt-out unavailable.";
588#endif // !SLIMPELLER
589 }
590
591 // The static leak checker gets confused by the use of fml::MakeCopyable.
592 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
593 return fml::MakeCopyable(
594 [embedder_surface = std::move(embedder_surface), platform_dispatch_table,
595 external_view_embedder = view_embedder](flutter::Shell& shell) mutable {
596 return std::make_unique<flutter::PlatformViewEmbedder>(
597 shell, // delegate
598 shell.GetTaskRunners(), // task runners
599 std::move(embedder_surface), // embedder surface
600 platform_dispatch_table, // platform dispatch table
601 std::move(external_view_embedder) // external view embedder
602 );
603 });
604#else // SHELL_ENABLE_METAL
605 FML_LOG(ERROR) << "This Flutter Engine does not support Metal rendering.";
606 return nullptr;
607#endif // SHELL_ENABLE_METAL
608}

References flutter::GPUMTLTextureInfo::destruction_callback, FlutterMetalTexture::destruction_callback, flutter::GPUMTLTextureInfo::destruction_context, FlutterMetalRendererConfig::device, FML_LOG, FlutterMetalRendererConfig::get_next_drawable_callback, flutter::Shell::GetTaskRunners(), kMetal, fml::MakeCopyable(), FlutterRendererConfig::metal, flutter::EmbedderSurfaceMetalImpeller::MetalDispatchTable::present, flutter::EmbedderSurfaceMetalSkia::MetalDispatchTable::present, FlutterMetalRendererConfig::present_command_queue, FlutterMetalRendererConfig::present_drawable_callback, FlutterFrameInfo::size, FlutterFrameInfo::struct_size, FlutterMetalTexture::struct_size, flutter::GPUMTLTextureInfo::texture, FlutterMetalTexture::texture, texture, flutter::GPUMTLTextureInfo::texture_id, FlutterMetalTexture::texture_id, FlutterRendererConfig::type, user_data, and FlutterMetalTexture::user_data.

Referenced by InferPlatformViewCreationCallback().

◆ InferOpenGLPlatformViewCreationCallback()

static flutter::Shell::CreateCallback< flutter::PlatformView > InferOpenGLPlatformViewCreationCallback ( const FlutterRendererConfig config,
void *  user_data,
const flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table,
std::unique_ptr< flutter::EmbedderExternalViewEmbedder external_view_embedder,
bool  enable_impeller 
)
inlinestatic

Definition at line 305 of file embedder.cc.

312 {
313#ifdef SHELL_ENABLE_GL
314 if (config->type != kOpenGL) {
315 return nullptr;
316 }
317
318 auto gl_make_current = [ptr = config->open_gl.make_current,
319 user_data]() -> bool { return ptr(user_data); };
320
321 auto gl_clear_current = [ptr = config->open_gl.clear_current,
322 user_data]() -> bool { return ptr(user_data); };
323
324 auto gl_present =
325 [present = config->open_gl.present,
326 present_with_info = config->open_gl.present_with_info,
327 user_data](flutter::GLPresentInfo gl_present_info) -> bool {
328 if (present) {
329 return present(user_data);
330 } else {
331 // Format the frame and buffer damages accordingly. Note that, since the
332 // current compute damage algorithm only returns one rectangle for damage
333 // we are assuming the number of rectangles provided in frame and buffer
334 // damage are always 1. Once the function that computes damage implements
335 // support for multiple damage rectangles, GLPresentInfo should also
336 // contain the number of damage rectangles.
337
338 std::optional<FlutterRect> frame_damage_rect;
339 if (gl_present_info.frame_damage) {
340 frame_damage_rect =
341 DlIRectToFlutterRect(*(gl_present_info.frame_damage));
342 }
343 std::optional<FlutterRect> buffer_damage_rect;
344 if (gl_present_info.buffer_damage) {
345 buffer_damage_rect =
346 DlIRectToFlutterRect(*(gl_present_info.buffer_damage));
347 }
348
349 FlutterDamage frame_damage{
350 .struct_size = sizeof(FlutterDamage),
351 .num_rects = frame_damage_rect ? size_t{1} : size_t{0},
352 .damage = frame_damage_rect ? &frame_damage_rect.value() : nullptr,
353 };
354 FlutterDamage buffer_damage{
355 .struct_size = sizeof(FlutterDamage),
356 .num_rects = buffer_damage_rect ? size_t{1} : size_t{0},
357 .damage = buffer_damage_rect ? &buffer_damage_rect.value() : nullptr,
358 };
359
360 // Construct the present information concerning the frame being rendered.
361 FlutterPresentInfo present_info = {
363 .fbo_id = gl_present_info.fbo_id,
364 .frame_damage = frame_damage,
365 .buffer_damage = buffer_damage,
366 };
367
368 return present_with_info(user_data, &present_info);
369 }
370 };
371
372 auto gl_fbo_callback =
373 [fbo_callback = config->open_gl.fbo_callback,
374 fbo_with_frame_info_callback =
376 user_data](flutter::GLFrameInfo gl_frame_info) -> intptr_t {
377 if (fbo_callback) {
378 return fbo_callback(user_data);
379 } else {
380 FlutterFrameInfo frame_info = {};
381 frame_info.struct_size = sizeof(FlutterFrameInfo);
382 frame_info.size = {gl_frame_info.width, gl_frame_info.height};
383 return fbo_with_frame_info_callback(user_data, &frame_info);
384 }
385 };
386
387 auto gl_populate_existing_damage =
388 [populate_existing_damage = config->open_gl.populate_existing_damage,
389 user_data](intptr_t id) -> flutter::GLFBOInfo {
390 // If no populate_existing_damage was provided, disable partial
391 // repaint.
392 if (!populate_existing_damage) {
393 return flutter::GLFBOInfo{
394 .fbo_id = static_cast<uint32_t>(id),
395 .existing_damage = std::nullopt,
396 };
397 }
398
399 // Given the FBO's ID, get its existing damage.
400 FlutterDamage existing_damage;
401 populate_existing_damage(user_data, id, &existing_damage);
402
403 std::optional<flutter::DlIRect> existing_damage_rect = std::nullopt;
404
405 // Verify that at least one damage rectangle was provided.
406 if (existing_damage.num_rects <= 0 || existing_damage.damage == nullptr) {
407 FML_LOG(INFO) << "No damage was provided. Forcing full repaint.";
408 } else {
409 existing_damage_rect = flutter::DlIRect();
410 for (size_t i = 0; i < existing_damage.num_rects; i++) {
411 existing_damage_rect = existing_damage_rect->Union(
412 FlutterRectToDlIRect(existing_damage.damage[i]));
413 }
414 }
415
416 // Pass the information about this FBO to the rendering backend.
417 return flutter::GLFBOInfo{
418 .fbo_id = static_cast<uint32_t>(id),
419 .existing_damage = existing_damage_rect,
420 };
421 };
422
423 const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
424 std::function<bool()> gl_make_resource_current_callback = nullptr;
425 if (SAFE_ACCESS(open_gl_config, make_resource_current, nullptr) != nullptr) {
426 gl_make_resource_current_callback =
427 [ptr = config->open_gl.make_resource_current, user_data]() {
428 return ptr(user_data);
429 };
430 }
431
432 std::function<flutter::DlMatrix(void)> gl_surface_transformation_callback =
433 nullptr;
434 if (SAFE_ACCESS(open_gl_config, surface_transformation, nullptr) != nullptr) {
435 gl_surface_transformation_callback =
436 [ptr = config->open_gl.surface_transformation, user_data]() {
437 FlutterTransformation transformation = ptr(user_data);
438 // clang-format off
439 return flutter::DlMatrix(
440 transformation.scaleX, transformation.skewY, 0.0f, transformation.pers0,
441 transformation.skewX, transformation.scaleY, 0.0f, transformation.pers1,
442 0.0f, 0.0f, 1.0f, 0.0f,
443 transformation.transX, transformation.transY, 0.0f, transformation.pers2
444 );
445 // clang-format on
446 };
447
448 // If there is an external view embedder, ask it to apply the surface
449 // transformation to its surfaces as well.
450 if (external_view_embedder) {
451 external_view_embedder->SetSurfaceTransformationCallback(
452 gl_surface_transformation_callback);
453 }
454 }
455
456 flutter::GPUSurfaceGLDelegate::GLProcResolver gl_proc_resolver = nullptr;
457 if (SAFE_ACCESS(open_gl_config, gl_proc_resolver, nullptr) != nullptr) {
458 gl_proc_resolver = [ptr = config->open_gl.gl_proc_resolver,
459 user_data](const char* gl_proc_name) {
460 return ptr(user_data, gl_proc_name);
461 };
462 } else {
463#if FML_OS_LINUX || FML_OS_WIN
464 gl_proc_resolver = DefaultGLProcResolver;
465#endif // FML_OS_LINUX || FML_OS_WIN
466 }
467
468 bool fbo_reset_after_present =
469 SAFE_ACCESS(open_gl_config, fbo_reset_after_present, false);
470
472 gl_make_current, // gl_make_current_callback
473 gl_clear_current, // gl_clear_current_callback
474 gl_present, // gl_present_callback
475 gl_fbo_callback, // gl_fbo_callback
476 gl_make_resource_current_callback, // gl_make_resource_current_callback
477 gl_surface_transformation_callback, // gl_surface_transformation_callback
478 gl_proc_resolver, // gl_proc_resolver
479 gl_populate_existing_damage, // gl_populate_existing_damage
480 };
481
482 return fml::MakeCopyable(
483 [gl_dispatch_table, fbo_reset_after_present, platform_dispatch_table,
484 enable_impeller,
485 external_view_embedder =
486 std::move(external_view_embedder)](flutter::Shell& shell) mutable {
487 std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder =
488 std::move(external_view_embedder);
489 if (enable_impeller) {
490 return std::make_unique<flutter::PlatformViewEmbedder>(
491 shell, // delegate
492 shell.GetTaskRunners(), // task runners
493 std::make_unique<flutter::EmbedderSurfaceGLImpeller>(
494 gl_dispatch_table, fbo_reset_after_present,
495 view_embedder), // embedder_surface
496 platform_dispatch_table, // embedder platform dispatch table
497 view_embedder // external view embedder
498 );
499 }
500 return std::make_unique<flutter::PlatformViewEmbedder>(
501 shell, // delegate
502 shell.GetTaskRunners(), // task runners
503 std::make_unique<flutter::EmbedderSurfaceGLSkia>(
504 gl_dispatch_table, fbo_reset_after_present,
505 view_embedder), // embedder_surface
506 platform_dispatch_table, // embedder platform dispatch table
507 view_embedder // external view embedder
508 );
509 });
510#else // SHELL_ENABLE_GL
511 FML_LOG(ERROR) << "This Flutter Engine does not support OpenGL rendering.";
512 return nullptr;
513#endif // SHELL_ENABLE_GL
514}

References FlutterOpenGLRendererConfig::clear_current, FlutterDamage::damage, FlutterOpenGLRendererConfig::fbo_callback, flutter::GLFBOInfo::fbo_id, FlutterOpenGLRendererConfig::fbo_with_frame_info_callback, FML_LOG, flutter::Shell::GetTaskRunners(), FlutterOpenGLRendererConfig::gl_proc_resolver, i, id, kOpenGL, FlutterOpenGLRendererConfig::make_current, FlutterOpenGLRendererConfig::make_resource_current, fml::MakeCopyable(), FlutterDamage::num_rects, FlutterRendererConfig::open_gl, FlutterTransformation::pers0, FlutterTransformation::pers1, FlutterTransformation::pers2, FlutterOpenGLRendererConfig::populate_existing_damage, FlutterOpenGLRendererConfig::present, FlutterOpenGLRendererConfig::present_with_info, SAFE_ACCESS, FlutterTransformation::scaleX, FlutterTransformation::scaleY, FlutterFrameInfo::size, FlutterTransformation::skewX, FlutterTransformation::skewY, FlutterDamage::struct_size, FlutterFrameInfo::struct_size, FlutterPresentInfo::struct_size, FlutterOpenGLRendererConfig::surface_transformation, FlutterTransformation::transX, FlutterTransformation::transY, FlutterRendererConfig::type, user_data, and FlutterUIntSize::width.

Referenced by InferPlatformViewCreationCallback().

◆ InferPlatformViewCreationCallback()

static flutter::Shell::CreateCallback< flutter::PlatformView > InferPlatformViewCreationCallback ( const FlutterRendererConfig config,
void *  user_data,
const flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table,
std::unique_ptr< flutter::EmbedderExternalViewEmbedder external_view_embedder,
bool  enable_impeller 
)
static

Definition at line 811 of file embedder.cc.

818 {
819 if (config == nullptr) {
820 return nullptr;
821 }
822
823 switch (config->type) {
824 case kOpenGL:
826 config, user_data, platform_dispatch_table,
827 std::move(external_view_embedder), enable_impeller);
828 case kSoftware:
830 config, user_data, platform_dispatch_table,
831 std::move(external_view_embedder));
832 case kMetal:
834 config, user_data, platform_dispatch_table,
835 std::move(external_view_embedder), enable_impeller);
836 case kVulkan:
838 config, user_data, platform_dispatch_table,
839 std::move(external_view_embedder), enable_impeller);
840 default:
841 return nullptr;
842 }
843 return nullptr;
844}

References InferMetalPlatformViewCreationCallback(), InferOpenGLPlatformViewCreationCallback(), InferSoftwarePlatformViewCreationCallback(), InferVulkanPlatformViewCreationCallback(), kMetal, kOpenGL, kSoftware, kVulkan, FlutterRendererConfig::type, and user_data.

Referenced by FlutterEngineInitialize().

◆ InferSoftwarePlatformViewCreationCallback()

static flutter::Shell::CreateCallback< flutter::PlatformView > InferSoftwarePlatformViewCreationCallback ( const FlutterRendererConfig config,
void *  user_data,
const flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table,
std::unique_ptr< flutter::EmbedderExternalViewEmbedder external_view_embedder 
)
static

Definition at line 774 of file embedder.cc.

780 {
781 if (config->type != kSoftware) {
782 return nullptr;
783 }
784
785 auto software_present_backing_store =
787 const void* allocation, size_t row_bytes, size_t height) -> bool {
788 return ptr(user_data, allocation, row_bytes, height);
789 };
790
792 software_dispatch_table = {
793 software_present_backing_store, // required
794 };
795
796 return fml::MakeCopyable(
797 [software_dispatch_table, platform_dispatch_table,
798 external_view_embedder =
799 std::move(external_view_embedder)](flutter::Shell& shell) mutable {
800 return std::make_unique<flutter::PlatformViewEmbedder>(
801 shell, // delegate
802 shell.GetTaskRunners(), // task runners
803 software_dispatch_table, // software dispatch table
804 platform_dispatch_table, // platform dispatch table
805 std::move(external_view_embedder) // external view embedder
806 );
807 });
808}

References flutter::Shell::GetTaskRunners(), height, kSoftware, fml::MakeCopyable(), FlutterRendererConfig::software, FlutterSoftwareRendererConfig::surface_present_callback, FlutterRendererConfig::type, and user_data.

Referenced by InferPlatformViewCreationCallback().

◆ InferVulkanPlatformViewCreationCallback()

static flutter::Shell::CreateCallback< flutter::PlatformView > InferVulkanPlatformViewCreationCallback ( const FlutterRendererConfig config,
void *  user_data,
const flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table,
std::unique_ptr< flutter::EmbedderExternalViewEmbedder external_view_embedder,
bool  enable_impeller 
)
static

Definition at line 611 of file embedder.cc.

618 {
619 if (config->type != kVulkan) {
620 return nullptr;
621 }
622
623#ifdef SHELL_ENABLE_VULKAN
624 std::function<void*(VkInstance, const char*)>
625 vulkan_get_instance_proc_address =
627 VkInstance instance, const char* proc_name) -> void* {
628 return ptr(user_data, instance, proc_name);
629 };
630
631 auto vulkan_get_next_image =
632 [ptr = config->vulkan.get_next_image_callback,
633 user_data](const flutter::DlISize& frame_size) -> FlutterVulkanImage {
634 FlutterFrameInfo frame_info = {
635 .struct_size = sizeof(FlutterFrameInfo),
636 .size = {static_cast<uint32_t>(frame_size.width),
637 static_cast<uint32_t>(frame_size.height)},
638 };
639
640 return ptr(user_data, &frame_info);
641 };
642
643 auto vulkan_present_image_callback =
644 [ptr = config->vulkan.present_image_callback, user_data](
645 VkImage image, VkFormat format) -> bool {
646 FlutterVulkanImage image_desc = {
648 .image = reinterpret_cast<uint64_t>(image),
649 .format = static_cast<uint32_t>(format),
650 };
651 return ptr(user_data, &image_desc);
652 };
653
654 auto vk_instance = static_cast<VkInstance>(config->vulkan.instance);
655 auto proc_addr =
656 vulkan_get_instance_proc_address(vk_instance, "vkGetInstanceProcAddr");
657
658 std::shared_ptr<flutter::EmbedderExternalViewEmbedder> view_embedder =
659 std::move(external_view_embedder);
660
661#if IMPELLER_SUPPORTS_RENDERING
662 if (enable_impeller) {
664 vulkan_dispatch_table = {
666 reinterpret_cast<PFN_vkGetInstanceProcAddr>(proc_addr),
667 .get_next_image = vulkan_get_next_image,
668 .present_image = vulkan_present_image_callback,
669 };
670
671 std::unique_ptr<flutter::EmbedderSurfaceVulkanImpeller> embedder_surface =
672 std::make_unique<flutter::EmbedderSurfaceVulkanImpeller>(
673 config->vulkan.version, vk_instance,
678 static_cast<VkPhysicalDevice>(config->vulkan.physical_device),
679 static_cast<VkDevice>(config->vulkan.device),
681 static_cast<VkQueue>(config->vulkan.queue), vulkan_dispatch_table,
682 view_embedder);
683
684 return fml::MakeCopyable(
685 [embedder_surface = std::move(embedder_surface),
686 platform_dispatch_table,
687 external_view_embedder =
688 std::move(view_embedder)](flutter::Shell& shell) mutable {
689 return std::make_unique<flutter::PlatformViewEmbedder>(
690 shell, // delegate
691 shell.GetTaskRunners(), // task runners
692 std::move(embedder_surface), // embedder surface
693 platform_dispatch_table, // platform dispatch table
694 std::move(external_view_embedder) // external view embedder
695 );
696 });
697 } else {
699 {
701 reinterpret_cast<PFN_vkGetInstanceProcAddr>(proc_addr),
702 .get_next_image = vulkan_get_next_image,
703 .present_image = vulkan_present_image_callback,
704 };
705
706 std::unique_ptr<flutter::EmbedderSurfaceVulkan> embedder_surface =
707 std::make_unique<flutter::EmbedderSurfaceVulkan>(
708 config->vulkan.version, vk_instance,
713 static_cast<VkPhysicalDevice>(config->vulkan.physical_device),
714 static_cast<VkDevice>(config->vulkan.device),
716 static_cast<VkQueue>(config->vulkan.queue), vulkan_dispatch_table,
717 view_embedder);
718
719 return fml::MakeCopyable(
720 [embedder_surface = std::move(embedder_surface),
721 platform_dispatch_table,
722 external_view_embedder =
723 std::move(view_embedder)](flutter::Shell& shell) mutable {
724 return std::make_unique<flutter::PlatformViewEmbedder>(
725 shell, // delegate
726 shell.GetTaskRunners(), // task runners
727 std::move(embedder_surface), // embedder surface
728 platform_dispatch_table, // platform dispatch table
729 std::move(external_view_embedder) // external view embedder
730 );
731 });
732 }
733#else
736 reinterpret_cast<PFN_vkGetInstanceProcAddr>(proc_addr),
737 .get_next_image = vulkan_get_next_image,
738 .present_image = vulkan_present_image_callback,
739 };
740
741 std::unique_ptr<flutter::EmbedderSurfaceVulkan> embedder_surface =
742 std::make_unique<flutter::EmbedderSurfaceVulkan>(
743 config->vulkan.version, vk_instance,
748 static_cast<VkPhysicalDevice>(config->vulkan.physical_device),
749 static_cast<VkDevice>(config->vulkan.device),
751 static_cast<VkQueue>(config->vulkan.queue), vulkan_dispatch_table,
752 view_embedder);
753
754 return fml::MakeCopyable(
755 [embedder_surface = std::move(embedder_surface), platform_dispatch_table,
756 external_view_embedder =
757 std::move(view_embedder)](flutter::Shell& shell) mutable {
758 return std::make_unique<flutter::PlatformViewEmbedder>(
759 shell, // delegate
760 shell.GetTaskRunners(), // task runners
761 std::move(embedder_surface), // embedder surface
762 platform_dispatch_table, // platform dispatch table
763 std::move(external_view_embedder) // external view embedder
764 );
765 });
766#endif // // IMPELLER_SUPPORTS_RENDERING
767#else // SHELL_ENABLE_VULKAN
768 FML_LOG(ERROR) << "This Flutter Engine does not support Vulkan rendering.";
769 return nullptr;
770#endif // SHELL_ENABLE_VULKAN
771}

References FlutterVulkanRendererConfig::device, FlutterVulkanRendererConfig::enabled_device_extension_count, FlutterVulkanRendererConfig::enabled_device_extensions, FlutterVulkanRendererConfig::enabled_instance_extension_count, FlutterVulkanRendererConfig::enabled_instance_extensions, FML_LOG, FlutterVulkanImage::format, format, flutter::EmbedderSurfaceVulkan::VulkanDispatchTable::get_instance_proc_address, flutter::EmbedderSurfaceVulkanImpeller::VulkanDispatchTable::get_instance_proc_address, FlutterVulkanRendererConfig::get_instance_proc_address_callback, FlutterVulkanRendererConfig::get_next_image_callback, flutter::Shell::GetTaskRunners(), image, instance, FlutterVulkanRendererConfig::instance, kVulkan, fml::MakeCopyable(), FlutterVulkanRendererConfig::physical_device, FlutterVulkanRendererConfig::present_image_callback, FlutterVulkanRendererConfig::queue, FlutterVulkanRendererConfig::queue_family_index, FlutterFrameInfo::struct_size, FlutterVulkanImage::struct_size, FlutterRendererConfig::type, user_data, FlutterVulkanRendererConfig::version, and FlutterRendererConfig::vulkan.

Referenced by InferPlatformViewCreationCallback().

◆ InternalSendPlatformMessage()

static FlutterEngineResult InternalSendPlatformMessage ( FLUTTER_API_SYMBOL(FlutterEngine engine,
const char *  channel,
const uint8_t *  data,
size_t  size,
FlutterDataCallback  data_callback,
void *  user_data 
)
static

Definition at line 2885 of file embedder.cc.

2891 {
2892 FlutterEngineResult result;
2893
2894 FlutterPlatformMessageResponseHandle* response_handle;
2896 engine, data_callback, user_data, &response_handle);
2897 if (result != kSuccess) {
2898 return result;
2899 }
2900
2902 sizeof(FlutterPlatformMessage), // struct_size
2903 channel, // channel
2904 data, // message
2905 size, // message_size
2906 response_handle, // response_handle
2907 };
2908
2910 // Whether `SendPlatformMessage` succeeds or not, the response handle must be
2911 // released.
2912 FlutterEngineResult release_result =
2914 if (result != kSuccess) {
2915 return result;
2916 }
2917
2918 return release_result;
2919}

References channel, data, engine, FlutterEngineSendPlatformMessage(), FlutterPlatformMessageCreateResponseHandle(), FlutterPlatformMessageReleaseResponseHandle(), kSuccess, message, and user_data.

Referenced by FlutterEngineSendKeyEvent().

◆ IsMetalRendererConfigValid()

static bool IsMetalRendererConfigValid ( const FlutterRendererConfig config)
static

Definition at line 191 of file embedder.cc.

191 {
192 if (config->type != kMetal) {
193 return false;
194 }
195
196 const FlutterMetalRendererConfig* metal_config = &config->metal;
197
198 bool device = SAFE_ACCESS(metal_config, device, nullptr);
199 bool command_queue =
200 SAFE_ACCESS(metal_config, present_command_queue, nullptr);
201
202 bool present = SAFE_ACCESS(metal_config, present_drawable_callback, nullptr);
203 bool get_texture =
204 SAFE_ACCESS(metal_config, get_next_drawable_callback, nullptr);
205
206 return device && command_queue && present && get_texture;
207}

References device, kMetal, FlutterRendererConfig::metal, SAFE_ACCESS, and FlutterRendererConfig::type.

Referenced by IsRendererValid().

◆ IsOpenGLRendererConfigValid()

static bool IsOpenGLRendererConfigValid ( const FlutterRendererConfig config)
static

Definition at line 158 of file embedder.cc.

158 {
159 if (config->type != kOpenGL) {
160 return false;
161 }
162
163 const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
164
165 if (!SAFE_EXISTS(open_gl_config, make_current) ||
166 !SAFE_EXISTS(open_gl_config, clear_current) ||
167 !SAFE_EXISTS_ONE_OF(open_gl_config, fbo_callback,
168 fbo_with_frame_info_callback) ||
169 !SAFE_EXISTS_ONE_OF(open_gl_config, present, present_with_info)) {
170 return false;
171 }
172
173 return true;
174}

References kOpenGL, FlutterRendererConfig::open_gl, SAFE_EXISTS, SAFE_EXISTS_ONE_OF, and FlutterRendererConfig::type.

Referenced by IsRendererValid().

◆ IsRendererValid()

static bool IsRendererValid ( const FlutterRendererConfig config)
static

Definition at line 229 of file embedder.cc.

229 {
230 if (config == nullptr) {
231 return false;
232 }
233
234 switch (config->type) {
235 case kOpenGL:
236 return IsOpenGLRendererConfigValid(config);
237 case kSoftware:
238 return IsSoftwareRendererConfigValid(config);
239 case kMetal:
240 return IsMetalRendererConfigValid(config);
241 case kVulkan:
242 return IsVulkanRendererConfigValid(config);
243 default:
244 return false;
245 }
246
247 return false;
248}

References IsMetalRendererConfigValid(), IsOpenGLRendererConfigValid(), IsSoftwareRendererConfigValid(), IsVulkanRendererConfigValid(), kMetal, kOpenGL, kSoftware, kVulkan, and FlutterRendererConfig::type.

Referenced by FlutterEngineInitialize().

◆ IsSoftwareRendererConfigValid()

static bool IsSoftwareRendererConfigValid ( const FlutterRendererConfig config)
static

Definition at line 176 of file embedder.cc.

176 {
177 if (config->type != kSoftware) {
178 return false;
179 }
180
181 const FlutterSoftwareRendererConfig* software_config = &config->software;
182
183 if (SAFE_ACCESS(software_config, surface_present_callback, nullptr) ==
184 nullptr) {
185 return false;
186 }
187
188 return true;
189}

References kSoftware, SAFE_ACCESS, FlutterRendererConfig::software, and FlutterRendererConfig::type.

Referenced by IsRendererValid().

◆ IsVulkanRendererConfigValid()

static bool IsVulkanRendererConfigValid ( const FlutterRendererConfig config)
static

Definition at line 209 of file embedder.cc.

209 {
210 if (config->type != kVulkan) {
211 return false;
212 }
213
214 const FlutterVulkanRendererConfig* vulkan_config = &config->vulkan;
215
216 if (!SAFE_EXISTS(vulkan_config, instance) ||
217 !SAFE_EXISTS(vulkan_config, physical_device) ||
218 !SAFE_EXISTS(vulkan_config, device) ||
219 !SAFE_EXISTS(vulkan_config, queue) ||
220 !SAFE_EXISTS(vulkan_config, get_instance_proc_address_callback) ||
221 !SAFE_EXISTS(vulkan_config, get_next_image_callback) ||
222 !SAFE_EXISTS(vulkan_config, present_image_callback)) {
223 return false;
224 }
225
226 return true;
227}

References device, instance, kVulkan, physical_device, queue, SAFE_EXISTS, FlutterRendererConfig::type, and FlutterRendererConfig::vulkan.

Referenced by IsRendererValid().

◆ LogEmbedderError()

static FlutterEngineResult LogEmbedderError ( FlutterEngineResult  code,
const char *  reason,
const char *  code_name,
const char *  function,
const char *  file,
int  line 
)
static

Definition at line 134 of file embedder.cc.

139 {
140#if FML_OS_WIN
141 constexpr char kSeparator = '\\';
142#else
143 constexpr char kSeparator = '/';
144#endif
145 const auto file_base =
146 (::strrchr(file, kSeparator) ? strrchr(file, kSeparator) + 1 : file);
147 char error[256] = {};
148 snprintf(error, (sizeof(error) / sizeof(char)),
149 "%s (%d): '%s' returned '%s'. %s", file_base, line, function,
150 code_name, reason);
151 std::cerr << error << std::endl;
152 return code;
153}

References error, and function.

◆ MakeRenderTargetFromBackingStoreImpeller() [1/2]

static std::unique_ptr< flutter::EmbedderRenderTarget > MakeRenderTargetFromBackingStoreImpeller ( FlutterBackingStore  backing_store,
const fml::closure on_release,
const std::shared_ptr< impeller::AiksContext > &  aiks_context,
const FlutterBackingStoreConfig config,
const FlutterMetalBackingStore metal 
)
static

Definition at line 1233 of file embedder.cc.

1238 {
1239#if defined(SHELL_ENABLE_METAL) && defined(IMPELLER_SUPPORTS_RENDERING)
1240 if (!metal->texture.texture) {
1241 FML_LOG(ERROR) << "Embedder supplied null Metal texture.";
1242 return nullptr;
1243 }
1244
1245 const auto size = impeller::ISize(config.size.width, config.size.height);
1246
1247 impeller::TextureDescriptor resolve_tex_desc;
1248 resolve_tex_desc.size = size;
1251 resolve_tex_desc.usage = impeller::TextureUsage::kRenderTarget |
1253
1254 auto resolve_tex = impeller::WrapTextureMTL(
1255 resolve_tex_desc, metal->texture.texture,
1257 user_data = metal->texture.user_data]() { callback(user_data); });
1258 if (!resolve_tex) {
1259 FML_LOG(ERROR) << "Could not wrap embedder supplied Metal render texture.";
1260 return nullptr;
1261 }
1262 resolve_tex->SetLabel("ImpellerBackingStoreResolve");
1263
1264 impeller::TextureDescriptor msaa_tex_desc;
1268 msaa_tex_desc.format = resolve_tex->GetTextureDescriptor().format;
1269 msaa_tex_desc.size = size;
1271
1272 auto msaa_tex =
1273 aiks_context->GetContext()->GetResourceAllocator()->CreateTexture(
1274 msaa_tex_desc);
1275 if (!msaa_tex) {
1276 FML_LOG(ERROR) << "Could not allocate MSAA color texture.";
1277 return nullptr;
1278 }
1279 msaa_tex->SetLabel("ImpellerBackingStoreColorMSAA");
1280
1282 color0.texture = msaa_tex;
1286 color0.resolve_texture = resolve_tex;
1287
1288 impeller::RenderTarget render_target_desc;
1289 render_target_desc.SetColorAttachment(color0, 0u);
1290
1291 return std::make_unique<flutter::EmbedderRenderTargetImpeller>(
1292 backing_store, aiks_context,
1293 std::make_unique<impeller::RenderTarget>(std::move(render_target_desc)),
1294 on_release, fml::closure());
1295#else
1296 return nullptr;
1297#endif
1298}

References callback, impeller::ColorAttachment::clear_color, impeller::Color::DarkSlateGray(), FlutterMetalTexture::destruction_callback, FML_LOG, impeller::TextureDescriptor::format, FlutterSize::height, impeller::kClear, impeller::kCount1, impeller::kCount4, impeller::kDevicePrivate, impeller::kDeviceTransient, impeller::kMultisampleResolve, impeller::kRenderTarget, impeller::kShaderRead, impeller::kTexture2DMultisample, impeller::Attachment::load_action, impeller::Attachment::resolve_texture, impeller::TextureDescriptor::sample_count, impeller::RenderTarget::SetColorAttachment(), impeller::TextureDescriptor::size, FlutterBackingStoreConfig::size, impeller::TextureDescriptor::storage_mode, impeller::Attachment::store_action, impeller::Attachment::texture, FlutterMetalTexture::texture, FlutterMetalBackingStore::texture, impeller::TextureDescriptor::type, impeller::TextureDescriptor::usage, user_data, FlutterMetalTexture::user_data, FlutterSize::width, and impeller::WrapTextureMTL().

◆ MakeRenderTargetFromBackingStoreImpeller() [2/2]

static std::unique_ptr< flutter::EmbedderRenderTarget > MakeRenderTargetFromBackingStoreImpeller ( FlutterBackingStore  backing_store,
const fml::closure on_release,
const std::shared_ptr< impeller::AiksContext > &  aiks_context,
const FlutterBackingStoreConfig config,
const FlutterOpenGLFramebuffer framebuffer 
)
static

Definition at line 1139 of file embedder.cc.

1144 {
1145#if defined(SHELL_ENABLE_GL) && defined(IMPELLER_SUPPORTS_RENDERING)
1146 auto format = FlutterFormatToImpellerPixelFormat(framebuffer->target);
1147 if (!format.has_value()) {
1148 return nullptr;
1149 }
1150
1151 const auto& gl_context =
1152 impeller::ContextGLES::Cast(*aiks_context->GetContext());
1153 const bool implicit_msaa = aiks_context->GetContext()
1154 ->GetCapabilities()
1155 ->SupportsImplicitResolvingMSAA();
1156 const auto size = impeller::ISize(config.size.width, config.size.height);
1157
1158 impeller::TextureDescriptor color0_tex;
1159 if (implicit_msaa) {
1162 } else {
1165 }
1166 color0_tex.format = format.value();
1167 color0_tex.size = size;
1168 color0_tex.usage = static_cast<impeller::TextureUsageMask>(
1171
1174 gl_context.GetReactor(), color0_tex, framebuffer->name);
1177 if (implicit_msaa) {
1179 color0.resolve_texture = color0.texture;
1180 } else {
1182 }
1183
1184 impeller::TextureDescriptor depth_stencil_texture_desc;
1185 depth_stencil_texture_desc.format = impeller::PixelFormat::kD24UnormS8Uint;
1186 depth_stencil_texture_desc.size = size;
1187 depth_stencil_texture_desc.usage = static_cast<impeller::TextureUsageMask>(
1189 if (implicit_msaa) {
1190 depth_stencil_texture_desc.type =
1192 depth_stencil_texture_desc.sample_count = impeller::SampleCount::kCount4;
1193 } else {
1194 depth_stencil_texture_desc.type = impeller::TextureType::kTexture2D;
1195 depth_stencil_texture_desc.sample_count = impeller::SampleCount::kCount1;
1196 }
1197
1198 auto depth_stencil_tex = impeller::TextureGLES::CreatePlaceholder(
1199 gl_context.GetReactor(), depth_stencil_texture_desc);
1200
1202 depth0.clear_depth = 0;
1203 depth0.texture = depth_stencil_tex;
1206
1208 stencil0.clear_stencil = 0;
1209 stencil0.texture = depth_stencil_tex;
1212
1213 impeller::RenderTarget render_target_desc;
1214
1215 render_target_desc.SetColorAttachment(color0, 0u);
1216 render_target_desc.SetDepthAttachment(depth0);
1217 render_target_desc.SetStencilAttachment(stencil0);
1218
1219 fml::closure framebuffer_destruct =
1220 [callback = framebuffer->destruction_callback,
1221 user_data = framebuffer->user_data]() { callback(user_data); };
1222
1223 return std::make_unique<flutter::EmbedderRenderTargetImpeller>(
1224 backing_store, aiks_context,
1225 std::make_unique<impeller::RenderTarget>(std::move(render_target_desc)),
1226 on_release, framebuffer_destruct);
1227#else
1228 return nullptr;
1229#endif
1230}

References callback, impeller::BackendCast< ContextGLES, Context >::Cast(), impeller::ColorAttachment::clear_color, impeller::DepthAttachment::clear_depth, impeller::StencilAttachment::clear_stencil, impeller::TextureGLES::CreatePlaceholder(), impeller::Color::DarkSlateGray(), FlutterOpenGLFramebuffer::destruction_callback, impeller::TextureDescriptor::format, format, FlutterSize::height, impeller::kClear, impeller::kCount1, impeller::kCount4, impeller::kD24UnormS8Uint, impeller::kDevicePrivate, impeller::kDontCare, impeller::kMultisampleResolve, impeller::kRenderTarget, impeller::kStore, impeller::kTexture2D, impeller::kTexture2DMultisample, impeller::Attachment::load_action, FlutterOpenGLFramebuffer::name, impeller::Attachment::resolve_texture, impeller::TextureDescriptor::sample_count, impeller::RenderTarget::SetColorAttachment(), impeller::RenderTarget::SetDepthAttachment(), impeller::RenderTarget::SetStencilAttachment(), impeller::TextureDescriptor::size, FlutterBackingStoreConfig::size, impeller::TextureDescriptor::storage_mode, impeller::Attachment::store_action, FlutterOpenGLFramebuffer::target, impeller::Attachment::texture, impeller::TextureDescriptor::type, impeller::TextureDescriptor::usage, user_data, FlutterOpenGLFramebuffer::user_data, FlutterSize::width, and impeller::TextureGLES::WrapFBO().

Referenced by CreateEmbedderRenderTarget().

◆ MakeRenderTargetFromSkSurface() [1/2]

static std::unique_ptr< flutter::EmbedderRenderTarget > MakeRenderTargetFromSkSurface ( FlutterBackingStore  backing_store,
sk_sp< SkSurface >  skia_surface,
fml::closure  on_release 
)
static

Definition at line 1368 of file embedder.cc.

1370 {
1371 return MakeRenderTargetFromSkSurface(backing_store, std::move(skia_surface),
1372 std::move(on_release), nullptr, nullptr);
1373}

References MakeRenderTargetFromSkSurface().

◆ MakeRenderTargetFromSkSurface() [2/2]

static std::unique_ptr< flutter::EmbedderRenderTarget > MakeRenderTargetFromSkSurface ( FlutterBackingStore  backing_store,
sk_sp< SkSurface >  skia_surface,
fml::closure  on_release,
flutter::EmbedderRenderTarget::MakeOrClearCurrentCallback  on_make_current,
flutter::EmbedderRenderTarget::MakeOrClearCurrentCallback  on_clear_current 
)
static

Definition at line 1352 of file embedder.cc.

1358 {
1359 if (!skia_surface) {
1360 return nullptr;
1361 }
1362 return std::make_unique<flutter::EmbedderRenderTargetSkia>(
1363 backing_store, std::move(skia_surface), std::move(on_release),
1364 std::move(on_make_current), std::move(on_clear_current));
1365}

Referenced by CreateEmbedderRenderTarget(), and MakeRenderTargetFromSkSurface().

◆ MakeSkSurfaceFromBackingStore() [1/7]

static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore ( GrDirectContext *  context,
const FlutterBackingStoreConfig config,
const FlutterMetalBackingStore metal 
)
static

Definition at line 1075 of file embedder.cc.

1078 {
1079#if defined(SHELL_ENABLE_METAL) && !SLIMPELLER
1080 GrMtlTextureInfo texture_info;
1081 if (!metal->texture.texture) {
1082 FML_LOG(ERROR) << "Embedder supplied null Metal texture.";
1083 return nullptr;
1084 }
1085 sk_cfp<FlutterMetalTextureHandle> mtl_texture;
1086 mtl_texture.retain(metal->texture.texture);
1087 texture_info.fTexture = mtl_texture;
1088 GrBackendTexture backend_texture =
1089 GrBackendTextures::MakeMtl(config.size.width, //
1090 config.size.height, //
1091 skgpu::Mipmapped::kNo, //
1092 texture_info //
1093 );
1094
1095 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
1096
1097 auto surface = SkSurfaces::WrapBackendTexture(
1098 context, // context
1099 backend_texture, // back-end texture
1100 kTopLeft_GrSurfaceOrigin, // surface origin
1101 1, // sample count
1102 kBGRA_8888_SkColorType, // color type
1103 nullptr, // color space
1104 &surface_properties, // surface properties
1105 static_cast<SkSurfaces::TextureReleaseProc>(
1106 metal->texture.destruction_callback), // release proc
1107 metal->texture.user_data // release context
1108 );
1109
1110 if (!surface) {
1111 FML_LOG(ERROR) << "Could not wrap embedder supplied Metal render texture.";
1112 return nullptr;
1113 }
1114
1115 return surface;
1116#else
1117 return nullptr;
1118#endif
1119}

References FlutterMetalTexture::destruction_callback, FML_LOG, FlutterSize::height, FlutterBackingStoreConfig::size, surface, FlutterMetalTexture::texture, FlutterMetalBackingStore::texture, FlutterMetalTexture::user_data, and FlutterSize::width.

◆ MakeSkSurfaceFromBackingStore() [2/7]

static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore ( GrDirectContext *  context,
const FlutterBackingStoreConfig config,
const FlutterOpenGLFramebuffer framebuffer 
)
static

Definition at line 892 of file embedder.cc.

895 {
896#ifdef SHELL_ENABLE_GL
897 GrGLFramebufferInfo framebuffer_info = {};
898 framebuffer_info.fFormat = framebuffer->target;
899 framebuffer_info.fFBOID = framebuffer->name;
900
901 auto backend_render_target =
902 GrBackendRenderTargets::MakeGL(config.size.width, // width
903 config.size.height, // height
904 1, // sample count
905 0, // stencil bits
906 framebuffer_info // framebuffer info
907 );
908
909 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
910
911 std::optional<SkColorType> color_type =
912 FlutterFormatToSkColorType(framebuffer->target);
913 if (!color_type) {
914 return nullptr;
915 }
916
917 auto surface = SkSurfaces::WrapBackendRenderTarget(
918 context, // context
919 backend_render_target, // backend render target
920 kBottomLeft_GrSurfaceOrigin, // surface origin
921 color_type.value(), // color type
922 SkColorSpace::MakeSRGB(), // color space
923 &surface_properties, // surface properties
924 static_cast<SkSurfaces::RenderTargetReleaseProc>(
925 framebuffer->destruction_callback), // release proc
926 framebuffer->user_data // release context
927 );
928
929 if (!surface) {
930 FML_LOG(ERROR) << "Could not wrap embedder supplied frame-buffer.";
931 return nullptr;
932 }
933 return surface;
934#else
935 return nullptr;
936#endif
937}

References color_type, FlutterOpenGLFramebuffer::destruction_callback, FML_LOG, FlutterSize::height, FlutterOpenGLFramebuffer::name, FlutterBackingStoreConfig::size, surface, FlutterOpenGLFramebuffer::target, FlutterOpenGLFramebuffer::user_data, and FlutterSize::width.

◆ MakeSkSurfaceFromBackingStore() [3/7]

static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore ( GrDirectContext *  context,
const FlutterBackingStoreConfig config,
const FlutterOpenGLSurface surface 
)
static

Definition at line 939 of file embedder.cc.

942 {
943#ifdef SHELL_ENABLE_GL
944 GrGLFramebufferInfo framebuffer_info = {};
945 framebuffer_info.fFormat = SAFE_ACCESS(surface, format, GL_BGRA8_EXT);
946 framebuffer_info.fFBOID = 0;
947
948 auto backend_render_target =
949 GrBackendRenderTargets::MakeGL(config.size.width, // width
950 config.size.height, // height
951 1, // sample count
952 0, // stencil bits
953 framebuffer_info // framebuffer info
954 );
955
956 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
957
958 std::optional<SkColorType> color_type =
959 FlutterFormatToSkColorType(surface->format);
960 if (!color_type) {
961 return nullptr;
962 }
963
964 auto sk_surface = SkSurfaces::WrapBackendRenderTarget(
965 context, // context
966 backend_render_target, // backend render target
967 kBottomLeft_GrSurfaceOrigin, // surface origin
968 color_type.value(), // color type
969 SkColorSpace::MakeSRGB(), // color space
970 &surface_properties, // surface properties
971 static_cast<SkSurfaces::RenderTargetReleaseProc>(
972 surface->destruction_callback), // release proc
973 surface->user_data // release context
974 );
975
976 if (!sk_surface) {
977 FML_LOG(ERROR) << "Could not wrap embedder supplied frame-buffer.";
978 return nullptr;
979 }
980 return sk_surface;
981#else
982 return nullptr;
983#endif
984}

References color_type, FML_LOG, format, FlutterSize::height, SAFE_ACCESS, FlutterBackingStoreConfig::size, surface, and FlutterSize::width.

◆ MakeSkSurfaceFromBackingStore() [4/7]

static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore ( GrDirectContext *  context,
const FlutterBackingStoreConfig config,
const FlutterOpenGLTexture texture 
)
static

Definition at line 846 of file embedder.cc.

849 {
850#ifdef SHELL_ENABLE_GL
851 GrGLTextureInfo texture_info;
852 texture_info.fTarget = texture->target;
853 texture_info.fID = texture->name;
854 texture_info.fFormat = texture->format;
855
856 GrBackendTexture backend_texture =
857 GrBackendTextures::MakeGL(config.size.width, config.size.height,
858 skgpu::Mipmapped::kNo, texture_info);
859
860 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
861
862 std::optional<SkColorType> color_type =
863 FlutterFormatToSkColorType(texture->format);
864 if (!color_type) {
865 return nullptr;
866 }
867
868 auto surface = SkSurfaces::WrapBackendTexture(
869 context, // context
870 backend_texture, // back-end texture
871 kBottomLeft_GrSurfaceOrigin, // surface origin
872 1, // sample count
873 color_type.value(), // color type
874 SkColorSpace::MakeSRGB(), // color space
875 &surface_properties, // surface properties
876 static_cast<SkSurfaces::TextureReleaseProc>(
877 texture->destruction_callback), // release proc
878 texture->user_data // release context
879 );
880
881 if (!surface) {
882 FML_LOG(ERROR) << "Could not wrap embedder supplied render texture.";
883 return nullptr;
884 }
885
886 return surface;
887#else
888 return nullptr;
889#endif
890}

References color_type, FML_LOG, FlutterSize::height, FlutterBackingStoreConfig::size, surface, texture, and FlutterSize::width.

Referenced by CreateEmbedderRenderTarget().

◆ MakeSkSurfaceFromBackingStore() [5/7]

static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore ( GrDirectContext *  context,
const FlutterBackingStoreConfig config,
const FlutterSoftwareBackingStore software 
)
static

Definition at line 986 of file embedder.cc.

989 {
990 const auto image_info =
991 SkImageInfo::MakeN32Premul(config.size.width, config.size.height);
992
993 struct Captures {
994 VoidCallback destruction_callback;
995 void* user_data;
996 };
997 auto captures = std::make_unique<Captures>();
998 captures->destruction_callback = software->destruction_callback;
999 captures->user_data = software->user_data;
1000 auto release_proc = [](void* pixels, void* context) {
1001 auto captures = reinterpret_cast<Captures*>(context);
1002 if (captures->destruction_callback) {
1003 captures->destruction_callback(captures->user_data);
1004 }
1005 delete captures;
1006 };
1007
1008 auto surface =
1009 SkSurfaces::WrapPixels(image_info, // image info
1010 const_cast<void*>(software->allocation), // pixels
1011 software->row_bytes, // row bytes
1012 release_proc, // release proc
1013 captures.get() // get context
1014 );
1015
1016 if (!surface) {
1017 FML_LOG(ERROR)
1018 << "Could not wrap embedder supplied software render buffer.";
1019 if (software->destruction_callback) {
1020 software->destruction_callback(software->user_data);
1021 }
1022 return nullptr;
1023 }
1024 if (surface) {
1025 captures.release(); // Skia has assumed ownership of the struct.
1026 }
1027 return surface;
1028}

References FlutterSoftwareBackingStore::allocation, FlutterSoftwareBackingStore::destruction_callback, FML_LOG, FlutterSize::height, FlutterSoftwareBackingStore::row_bytes, FlutterBackingStoreConfig::size, surface, user_data, FlutterSoftwareBackingStore::user_data, and FlutterSize::width.

◆ MakeSkSurfaceFromBackingStore() [6/7]

static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore ( GrDirectContext *  context,
const FlutterBackingStoreConfig config,
const FlutterSoftwareBackingStore2 software 
)
static

Definition at line 1030 of file embedder.cc.

1033 {
1034 const auto color_info = getSkColorInfo(software->pixel_format);
1035 if (!color_info) {
1036 return nullptr;
1037 }
1038
1039 const auto image_info = SkImageInfo::Make(
1040 SkISize::Make(config.size.width, config.size.height), *color_info);
1041
1042 struct Captures {
1043 VoidCallback destruction_callback;
1044 void* user_data;
1045 };
1046 auto captures = std::make_unique<Captures>();
1047 captures->destruction_callback = software->destruction_callback;
1048 captures->user_data = software->user_data;
1049 auto release_proc = [](void* pixels, void* context) {
1050 auto captures = reinterpret_cast<Captures*>(context);
1051 if (captures->destruction_callback) {
1052 captures->destruction_callback(captures->user_data);
1053 }
1054 };
1055
1056 auto surface =
1057 SkSurfaces::WrapPixels(image_info, // image info
1058 const_cast<void*>(software->allocation), // pixels
1059 software->row_bytes, // row bytes
1060 release_proc, // release proc
1061 captures.release() // release context
1062 );
1063
1064 if (!surface) {
1065 FML_LOG(ERROR)
1066 << "Could not wrap embedder supplied software render buffer.";
1067 if (software->destruction_callback) {
1068 software->destruction_callback(software->user_data);
1069 }
1070 return nullptr;
1071 }
1072 return surface;
1073}

References FlutterSoftwareBackingStore2::allocation, FlutterSoftwareBackingStore2::destruction_callback, FML_LOG, getSkColorInfo(), FlutterSize::height, FlutterSoftwareBackingStore2::pixel_format, FlutterSoftwareBackingStore2::row_bytes, FlutterBackingStoreConfig::size, surface, user_data, FlutterSoftwareBackingStore2::user_data, and FlutterSize::width.

◆ MakeSkSurfaceFromBackingStore() [7/7]

static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore ( GrDirectContext *  context,
const FlutterBackingStoreConfig config,
const FlutterVulkanBackingStore vulkan 
)
static

Definition at line 1300 of file embedder.cc.

1303 {
1304#ifdef SHELL_ENABLE_VULKAN
1305 if (!vulkan->image) {
1306 FML_LOG(ERROR) << "Embedder supplied null Vulkan image.";
1307 return nullptr;
1308 }
1309 GrVkImageInfo image_info = {
1310 .fImage = reinterpret_cast<VkImage>(vulkan->image->image),
1311 .fImageTiling = VK_IMAGE_TILING_OPTIMAL,
1312 .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1313 .fFormat = static_cast<VkFormat>(vulkan->image->format),
1314 .fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
1315 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
1316 VK_IMAGE_USAGE_TRANSFER_DST_BIT |
1317 VK_IMAGE_USAGE_SAMPLED_BIT,
1318 .fSampleCount = 1,
1319 .fLevelCount = 1,
1320 };
1321 auto backend_texture = GrBackendTextures::MakeVk(
1322 config.size.width, config.size.height, image_info);
1323
1324 SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
1325
1326 auto surface = SkSurfaces::WrapBackendTexture(
1327 context, // context
1328 backend_texture, // back-end texture
1329 kTopLeft_GrSurfaceOrigin, // surface origin
1330 1, // sample count
1332 static_cast<VkFormat>(vulkan->image->format)), // color type
1333 SkColorSpace::MakeSRGB(), // color space
1334 &surface_properties, // surface properties
1335 static_cast<SkSurfaces::TextureReleaseProc>(
1336 vulkan->destruction_callback), // release proc
1337 vulkan->user_data // release context
1338 );
1339
1340 if (!surface) {
1341 FML_LOG(ERROR) << "Could not wrap embedder supplied Vulkan render texture.";
1342 return nullptr;
1343 }
1344
1345 return surface;
1346#else
1347 return nullptr;
1348#endif
1349}

References flutter::GPUSurfaceVulkan::ColorTypeFromFormat(), FML_LOG, FlutterSize::height, FlutterBackingStoreConfig::size, surface, and FlutterSize::width.

◆ MakeViewportMetricsFromWindowMetrics()

static std::variant< flutter::ViewportMetrics, std::string > MakeViewportMetricsFromWindowMetrics ( const FlutterWindowMetricsEvent flutter_metrics)
static

Definition at line 1612 of file embedder.cc.

1613 {
1614 if (flutter_metrics == nullptr) {
1615 return "Invalid metrics handle.";
1616 }
1617
1619
1620 metrics.physical_width = SAFE_ACCESS(flutter_metrics, width, 0.0);
1621 metrics.physical_height = SAFE_ACCESS(flutter_metrics, height, 0.0);
1622 metrics.device_pixel_ratio = SAFE_ACCESS(flutter_metrics, pixel_ratio, 1.0);
1623 metrics.physical_view_inset_top =
1624 SAFE_ACCESS(flutter_metrics, physical_view_inset_top, 0.0);
1626 SAFE_ACCESS(flutter_metrics, physical_view_inset_right, 0.0);
1628 SAFE_ACCESS(flutter_metrics, physical_view_inset_bottom, 0.0);
1629 metrics.physical_view_inset_left =
1630 SAFE_ACCESS(flutter_metrics, physical_view_inset_left, 0.0);
1631 metrics.display_id = SAFE_ACCESS(flutter_metrics, display_id, 0);
1632
1633 if (metrics.device_pixel_ratio <= 0.0) {
1634 return "Device pixel ratio was invalid. It must be greater than zero.";
1635 }
1636
1637 if (metrics.physical_view_inset_top < 0 ||
1638 metrics.physical_view_inset_right < 0 ||
1639 metrics.physical_view_inset_bottom < 0 ||
1640 metrics.physical_view_inset_left < 0) {
1641 return "Physical view insets are invalid. They must be non-negative.";
1642 }
1643
1644 if (metrics.physical_view_inset_top > metrics.physical_height ||
1645 metrics.physical_view_inset_right > metrics.physical_width ||
1646 metrics.physical_view_inset_bottom > metrics.physical_height ||
1647 metrics.physical_view_inset_left > metrics.physical_width) {
1648 return "Physical view insets are invalid. They cannot be greater than "
1649 "physical height or width.";
1650 }
1651
1656
1657 return metrics;
1658}

References flutter::ViewportMetrics::device_pixel_ratio, flutter::ViewportMetrics::display_id, height, flutter::ViewportMetrics::physical_height, flutter::ViewportMetrics::physical_max_height_constraint, flutter::ViewportMetrics::physical_max_width_constraint, flutter::ViewportMetrics::physical_min_height_constraint, flutter::ViewportMetrics::physical_min_width_constraint, flutter::ViewportMetrics::physical_view_inset_bottom, flutter::ViewportMetrics::physical_view_inset_left, flutter::ViewportMetrics::physical_view_inset_right, flutter::ViewportMetrics::physical_view_inset_top, flutter::ViewportMetrics::physical_width, SAFE_ACCESS, and width.

Referenced by FlutterEngineAddView(), and FlutterEngineSendWindowMetricsEvent().

◆ MapKeyEventDeviceType()

◆ MapKeyEventType()

static flutter::KeyEventType MapKeyEventType ( FlutterKeyEventType  event_kind)
inlinestatic

◆ PointerDataButtonsForLegacyEvent()

◆ PopulateAOTSnapshotMappingCallbacks()

void PopulateAOTSnapshotMappingCallbacks ( const FlutterProjectArgs args,
flutter::Settings settings 
)

Definition at line 1792 of file embedder.cc.

1794 { // NOLINT(google-runtime-references)
1795 // There are no ownership concerns here as all mappings are owned by the
1796 // embedder and not the engine.
1797 auto make_mapping_callback = [](const uint8_t* mapping, size_t size) {
1798 return [mapping, size]() {
1799 return std::make_unique<fml::NonOwnedMapping>(mapping, size);
1800 };
1801 };
1802
1803 if (SAFE_ACCESS(args, aot_data, nullptr) != nullptr) {
1804 settings.vm_snapshot_data =
1805 make_mapping_callback(args->aot_data->vm_snapshot_data, 0);
1806
1807 settings.vm_snapshot_instr =
1808 make_mapping_callback(args->aot_data->vm_snapshot_instrs, 0);
1809
1810 settings.isolate_snapshot_data =
1811 make_mapping_callback(args->aot_data->vm_isolate_data, 0);
1812
1813 settings.isolate_snapshot_instr =
1814 make_mapping_callback(args->aot_data->vm_isolate_instrs, 0);
1815 }
1816
1817 if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) {
1818 settings.vm_snapshot_data = make_mapping_callback(
1819 args->vm_snapshot_data, SAFE_ACCESS(args, vm_snapshot_data_size, 0));
1820 }
1821
1822 if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) {
1823 settings.vm_snapshot_instr = make_mapping_callback(
1824 args->vm_snapshot_instructions,
1825 SAFE_ACCESS(args, vm_snapshot_instructions_size, 0));
1826 }
1827
1828 if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) {
1829 settings.isolate_snapshot_data =
1830 make_mapping_callback(args->isolate_snapshot_data,
1831 SAFE_ACCESS(args, isolate_snapshot_data_size, 0));
1832 }
1833
1834 if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) {
1835 settings.isolate_snapshot_instr = make_mapping_callback(
1836 args->isolate_snapshot_instructions,
1837 SAFE_ACCESS(args, isolate_snapshot_instructions_size, 0));
1838 }
1839}

References args, flutter::Settings::isolate_snapshot_data, flutter::Settings::isolate_snapshot_instr, SAFE_ACCESS, flutter::Settings::vm_snapshot_data, and flutter::Settings::vm_snapshot_instr.

Referenced by FlutterEngineInitialize().

◆ PopulateJITSnapshotMappingCallbacks()

void PopulateJITSnapshotMappingCallbacks ( const FlutterProjectArgs args,
flutter::Settings settings 
)

Definition at line 1749 of file embedder.cc.

1750 {
1751 auto make_mapping_callback = [](const char* path, bool executable) {
1752 return [path, executable]() {
1753 if (executable) {
1755 } else {
1757 }
1758 };
1759 };
1760
1761 // Users are allowed to specify only certain snapshots if they so desire.
1762 if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) {
1763 settings.vm_snapshot_data = make_mapping_callback(
1764 reinterpret_cast<const char*>(args->vm_snapshot_data), false);
1765 }
1766
1767 if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) {
1768 settings.vm_snapshot_instr = make_mapping_callback(
1769 reinterpret_cast<const char*>(args->vm_snapshot_instructions), true);
1770 }
1771
1772 if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) {
1773 settings.isolate_snapshot_data = make_mapping_callback(
1774 reinterpret_cast<const char*>(args->isolate_snapshot_data), false);
1775 }
1776
1777 if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) {
1778 settings.isolate_snapshot_instr = make_mapping_callback(
1779 reinterpret_cast<const char*>(args->isolate_snapshot_instructions),
1780 true);
1781 }
1782
1783#if !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
1784 settings.dart_library_sources_kernel = []() {
1785 return std::make_unique<fml::NonOwnedMapping>(kPlatformStrongDill,
1787 };
1788#endif // !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE ==
1789 // FLUTTER_RUNTIME_MODE_DEBUG)
1790}

References args, fml::FileMapping::CreateReadExecute(), fml::FileMapping::CreateReadOnly(), flutter::Settings::dart_library_sources_kernel, flutter::Settings::isolate_snapshot_data, flutter::Settings::isolate_snapshot_instr, kPlatformStrongDill, kPlatformStrongDillSize, SAFE_ACCESS, flutter::Settings::vm_snapshot_data, and flutter::Settings::vm_snapshot_instr.

Referenced by FlutterEngineInitialize().

◆ ToPointerDataChange()

◆ ToPointerDataKind()

◆ ToPointerDataSignalKind()

Variable Documentation

◆ kFlutterImplicitViewId

◆ kFlutterKeyDataChannel

const char* kFlutterKeyDataChannel = "flutter/keydata"

Definition at line 132 of file embedder.cc.

Referenced by FlutterEngineSendKeyEvent().

◆ kFlutterSemanticsCustomActionIdBatchEnd

const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1

FlutterSemanticsCustomAction ID used as a sentinel to signal the end of a batch of semantics custom action updates. This is unused if using FlutterUpdateSemanticsCallback2.

Definition at line 108 of file embedder.cc.

Referenced by CreateEmbedderSemanticsUpdateCallbackV1(), and flutter::testing::TEST_F().

◆ kFlutterSemanticsNodeIdBatchEnd

const int32_t kFlutterSemanticsNodeIdBatchEnd = -1

FlutterSemanticsNode ID used as a sentinel to signal the end of a batch of semantics node updates. This is unused if using FlutterUpdateSemanticsCallback2.

Definition at line 107 of file embedder.cc.

Referenced by CreateEmbedderSemanticsUpdateCallbackV1(), flutter::testing::TEST_F(), flutter::testing::TEST_F(), and flutter::testing::TEST_F().

◆ kPlatformStrongDill

const uint8_t kPlatformStrongDill[]
extern

◆ kPlatformStrongDillSize

const intptr_t kPlatformStrongDillSize
extern