Flutter Engine
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 "third_party/dart/runtime/bin/elf_loader.h"
#include "third_party/dart/runtime/include/dart_native_api.h"
#include "flutter/assets/directory_asset_bundle.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/persistent_cache.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_platform_message_response.h"
#include "flutter/shell/platform/embedder/embedder_render_target.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/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 IsRendererValid (const FlutterRendererConfig *config)
 
static flutter::Shell::CreateCallback< flutter::PlatformViewInferOpenGLPlatformViewCreationCallback (const FlutterRendererConfig *config, void *user_data, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder)
 
static flutter::Shell::CreateCallback< flutter::PlatformViewInferSoftwarePlatformViewCreationCallback (const FlutterRendererConfig *config, void *user_data, 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, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder)
 
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 FlutterSoftwareBackingStore *software)
 
static std::unique_ptr< flutter::EmbedderRenderTargetCreateEmbedderRenderTarget (const FlutterCompositor *compositor, const FlutterBackingStoreConfig &config, GrDirectContext *context)
 
static std::pair< std::unique_ptr< flutter::EmbedderExternalViewEmbedder >, bool > InferExternalViewEmbedderFromArgs (const FlutterCompositor *compositor)
 
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. More...
 
FlutterEngineResult FlutterEngineCollectAOTData (FlutterEngineAOTData data)
 Collects the AOT data. More...
 
void PopulateSnapshotMappingCallbacks (const FlutterProjectArgs *args, flutter::Settings &settings)
 
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. More...
 
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. More...
 
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. More...
 
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. More...
 
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. More...
 
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)
 
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. More...
 
FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle (FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterPlatformMessageResponseHandle *response)
 Collects the handle created using FlutterPlatformMessageCreateResponseHandle. More...
 
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. More...
 
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. More...
 
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. More...
 
FlutterEngineResult FlutterEngineUnregisterExternalTexture (FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
 Unregister a previous texture registration. More...
 
FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable (FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
 Mark that a new texture frame is available for a given texture identifier. More...
 
FlutterEngineResult FlutterEngineUpdateSemanticsEnabled (FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled)
 Enable or disable accessibility semantics. More...
 
FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures (FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterAccessibilityFeature flags)
 Sets additional accessibility features. More...
 
FlutterEngineResult FlutterEngineDispatchSemanticsAction (FLUTTER_API_SYMBOL(FlutterEngine) engine, uint64_t id, FlutterSemanticsAction action, const uint8_t *data, size_t data_length)
 Dispatch a semantics action to the specified semantics node. More...
 
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. More...
 
FlutterEngineResult FlutterEngineReloadSystemFonts (FLUTTER_API_SYMBOL(FlutterEngine) engine)
 Reloads the system fonts in engine. More...
 
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. More...
 
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. More...
 
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. More...
 
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. More...
 
uint64_t FlutterEngineGetCurrentTime ()
 Get the current time in nanoseconds from the clock used by the flutter engine. This is the system monotonic clock. More...
 
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 engine 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. More...
 
static bool DispatchJSONPlatformMessage (FLUTTER_API_SYMBOL(FlutterEngine) engine, 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. More...
 
bool FlutterEngineRunsAOTCompiledDartCode (void)
 Returns if the Flutter engine instance will run AOT compiled Dart code. This call has no threading restrictions. More...
 
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. More...
 
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. More...
 
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. More...
 
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. More...
 
FlutterEngineResult FlutterEngineGetProcAddresses (FlutterEngineProcTable *table)
 Gets the table of engine function pointers. More...
 

Variables

const uint8_t kPlatformStrongDill []
 
const intptr_t kPlatformStrongDillSize
 
const int32_t kFlutterSemanticsNodeIdBatchEnd = -1
 
const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1
 

Macro Definition Documentation

◆ FLUTTER_EXPORT

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

Definition at line 26 of file embedder.cc.

Referenced by FlutterEngineRunInitialized().

◆ FML_USED_ON_EMBEDDER

#define FML_USED_ON_EMBEDDER

Definition at line 5 of file embedder.cc.

◆ LOG_EMBEDDER_ERROR

◆ 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; \
}
#define STRUCT_HAS_MEMBER(pointer, member)

Referenced by FlutterEngineGetProcAddresses().

Typedef Documentation

◆ UniqueLoadedElf

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

Definition at line 587 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 1524 of file embedder.cc.

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

1524  {
1526  return kSuccess;
1527 }
static FML_EMBEDDER_ONLY MessageLoop & GetCurrent()
Definition: message_loop.cc:19
void RunExpiredTasksNow()
Definition: message_loop.cc:72

◆ CreateEmbedderRenderTarget()

static std::unique_ptr<flutter::EmbedderRenderTarget> CreateEmbedderRenderTarget ( const FlutterCompositor compositor,
const FlutterBackingStoreConfig config,
GrDirectContext *  context 
)
static

Definition at line 464 of file embedder.cc.

References FlutterCompositor::collect_backing_store_callback, FlutterCompositor::create_backing_store_callback, FML_LOG, FlutterOpenGLBackingStore::framebuffer, kFlutterBackingStoreTypeOpenGL, kFlutterBackingStoreTypeSoftware, kFlutterOpenGLTargetTypeFramebuffer, kFlutterOpenGLTargetTypeTexture, MakeSkSurfaceFromBackingStore(), FlutterBackingStore::open_gl, fml::ScopedCleanupClosure::Release(), FlutterBackingStore::software, FlutterBackingStore::struct_size, FlutterOpenGLBackingStore::texture, TRACE_EVENT0, FlutterOpenGLBackingStore::type, FlutterBackingStore::type, user_data, and FlutterCompositor::user_data.

Referenced by InferExternalViewEmbedderFromArgs().

466  {
467  FlutterBackingStore backing_store = {};
468  backing_store.struct_size = sizeof(backing_store);
469 
470  // Safe access checks on the compositor struct have been performed in
471  // InferExternalViewEmbedderFromArgs and are not necessary here.
472  auto c_create_callback = compositor->create_backing_store_callback;
473  auto c_collect_callback = compositor->collect_backing_store_callback;
474 
475  {
476  TRACE_EVENT0("flutter", "FlutterCompositorCreateBackingStore");
477  if (!c_create_callback(&config, &backing_store, compositor->user_data)) {
478  FML_LOG(ERROR) << "Could not create the embedder backing store.";
479  return nullptr;
480  }
481  }
482 
483  if (backing_store.struct_size != sizeof(backing_store)) {
484  FML_LOG(ERROR) << "Embedder modified the backing store struct size.";
485  return nullptr;
486  }
487 
488  // In case we return early without creating an embedder render target, the
489  // embedder has still given us ownership of its baton which we must return
490  // back to it. If this method is successful, the closure is released when the
491  // render target is eventually released.
492  fml::ScopedCleanupClosure collect_callback(
493  [c_collect_callback, backing_store, user_data = compositor->user_data]() {
494  TRACE_EVENT0("flutter", "FlutterCompositorCollectBackingStore");
495  c_collect_callback(&backing_store, user_data);
496  });
497 
498  // No safe access checks on the renderer are necessary since we allocated
499  // the struct.
500 
501  sk_sp<SkSurface> render_surface;
502 
503  switch (backing_store.type) {
505  switch (backing_store.open_gl.type) {
507  render_surface = MakeSkSurfaceFromBackingStore(
508  context, config, &backing_store.open_gl.texture);
509  break;
511  render_surface = MakeSkSurfaceFromBackingStore(
512  context, config, &backing_store.open_gl.framebuffer);
513  break;
514  }
515  break;
517  render_surface = MakeSkSurfaceFromBackingStore(context, config,
518  &backing_store.software);
519  break;
520  };
521 
522  if (!render_surface) {
523  FML_LOG(ERROR) << "Could not create a surface from an embedder provided "
524  "render target.";
525  return nullptr;
526  }
527 
528  return std::make_unique<flutter::EmbedderRenderTarget>(
529  backing_store, std::move(render_surface), collect_callback.Release());
530 }
Specified an software allocation for Flutter to render into using the CPU.
Definition: embedder.h:846
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:75
FlutterOpenGLFramebuffer framebuffer
Definition: embedder.h:769
void * user_data
Definition: embedder.h:925
#define FML_LOG(severity)
Definition: logging.h:65
Wraps a closure that is invoked in the destructor unless released by the caller.
Definition: closure.h:32
FlutterOpenGLTargetType type
Definition: embedder.h:763
G_BEGIN_DECLS FlValue gpointer user_data
FlutterSoftwareBackingStore software
The description of the software backing store.
Definition: embedder.h:865
FlutterOpenGLBackingStore open_gl
The description of the OpenGL backing store.
Definition: embedder.h:863
size_t struct_size
The size of this struct. Must be sizeof(FlutterBackingStore).
Definition: embedder.h:851
FlutterBackingStoreCollectCallback collect_backing_store_callback
Definition: embedder.h:936
FlutterBackingStoreType type
Specifies the type of backing store.
Definition: embedder.h:857
static sk_sp< SkSurface > MakeSkSurfaceFromBackingStore(GrDirectContext *context, const FlutterBackingStoreConfig &config, const FlutterOpenGLTexture *texture)
Definition: embedder.cc:342
FlutterOpenGLTexture texture
A texture for Flutter to render into.
Definition: embedder.h:766
FlutterBackingStoreCreateCallback create_backing_store_callback
Definition: embedder.h:933

◆ DispatchJSONPlatformMessage()

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

Definition at line 1730 of file embedder.cc.

References engine.

Referenced by FlutterEngineNotifyLowMemoryWarning(), and FlutterEngineUpdateLocales().

1733  {
1734  if (channel_name.size() == 0) {
1735  return false;
1736  }
1737 
1738  rapidjson::StringBuffer buffer;
1739  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
1740 
1741  if (!document.Accept(writer)) {
1742  return false;
1743  }
1744 
1745  const char* message = buffer.GetString();
1746 
1747  if (message == nullptr || buffer.GetSize() == 0) {
1748  return false;
1749  }
1750 
1751  auto platform_message = fml::MakeRefCounted<flutter::PlatformMessage>(
1752  channel_name.c_str(), // channel
1753  std::vector<uint8_t>{message, message + buffer.GetSize()}, // message
1754  nullptr // response
1755  );
1756 
1757  return reinterpret_cast<flutter::EmbedderEngine*>(engine)
1758  ->SendPlatformMessage(std::move(platform_message));
1759 }

◆ 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 651 of file embedder.cc.

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

651  {
652  if (!data) {
653  // Deleting a null object should be a no-op.
654  return kSuccess;
655  }
656 
657  // Created in a unique pointer in `FlutterEngineCreateAOTData`.
658  delete data;
659  return kSuccess;
660 }

◆ 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 597 of file embedder.cc.

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

599  {
602  "AOT data can only be created in AOT mode.");
603  } else if (!source) {
604  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null source specified.");
605  } else if (!data_out) {
606  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null data_out specified.");
607  }
608 
609  switch (source->type) {
611  if (!source->elf_path || !fml::IsFile(source->elf_path)) {
613  "Invalid ELF path specified.");
614  }
615 
616  auto aot_data = std::make_unique<_FlutterEngineAOTData>();
617  const char* error = nullptr;
618 
619 #if OS_FUCHSIA
620  // TODO(gw280): https://github.com/flutter/flutter/issues/50285
621  // Dart doesn't implement Dart_LoadELF on Fuchsia
622  Dart_LoadedElf* loaded_elf = nullptr;
623 #else
624  Dart_LoadedElf* loaded_elf = Dart_LoadELF(
625  source->elf_path, // file path
626  0, // file offset
627  &error, // error (out)
628  &aot_data->vm_snapshot_data, // vm snapshot data (out)
629  &aot_data->vm_snapshot_instrs, // vm snapshot instr (out)
630  &aot_data->vm_isolate_data, // vm isolate data (out)
631  &aot_data->vm_isolate_instrs // vm isolate instr (out)
632  );
633 #endif
634 
635  if (loaded_elf == nullptr) {
636  return LOG_EMBEDDER_ERROR(kInvalidArguments, error);
637  }
638 
639  aot_data->loaded_elf.reset(loaded_elf);
640 
641  *data_out = aot_data.release();
642  return kSuccess;
643  }
644  }
645 
646  return LOG_EMBEDDER_ERROR(
648  "Invalid FlutterEngineAOTDataSourceType type specified.");
649 }
FlMethodResponse GError ** error
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
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:199
bool IsFile(const std::string &path)
Definition: file_posix.cc:143
FlutterEngineAOTDataSourceType type
Definition: embedder.h:1110
const char * elf_path
Absolute path to an ELF library file.
Definition: embedder.h:1113

◆ 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 1206 of file embedder.cc.

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

1207  {
1208  if (engine == nullptr) {
1209  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1210  }
1211 
1212  auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
1213  embedder_engine->NotifyDestroyed();
1214  embedder_engine->CollectShell();
1215  return kSuccess;
1216 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ FlutterEngineDispatchSemanticsAction()

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

Dispatch a semantics action to the specified semantics node.

Parameters
[in]engineA running engine instance.
[in]identifierThe semantics action 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 1615 of file embedder.cc.

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

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

1620  {
1621  if (engine == nullptr) {
1622  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1623  }
1624  auto engine_action = static_cast<flutter::SemanticsAction>(action);
1625  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
1626  ->DispatchSemanticsAction(
1627  id, engine_action,
1628  std::vector<uint8_t>({data, data + data_length}))) {
1630  "Could not dispatch semantics action.");
1631  }
1632  return kSuccess;
1633 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
SemanticsAction action

◆ 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 1713 of file embedder.cc.

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

Referenced by FlutterEngineGetProcAddresses(), flutter::Win32TaskRunner::ProcessTasks(), FlutterEngine::shutDownEngine, flutter::testing::TEST(), and flutter::EventLoop::TimePointFromFlutterTime().

1713  {
1715 }
TimeDelta ToEpochDelta() const
Definition: time_point.h:40
constexpr int64_t ToNanoseconds() const
Definition: time_delta.h:61
static TimePoint Now()
Definition: time_point.cc:26

◆ 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 2052 of file embedder.cc.

References flutter::DispatchSemanticsAction(), FlutterEngineCollectAOTData(), FlutterEngineCreateAOTData(), FlutterEngineDeinitialize(), FlutterEngineDispatchSemanticsAction(), FlutterEngineGetCurrentTime(), FlutterEngineInitialize(), FlutterEngineMarkExternalTextureFrameAvailable(), FlutterEngineNotifyDisplayUpdate(), FlutterEngineNotifyLowMemoryWarning(), FlutterEngineOnVsync(), FlutterEnginePostCallbackOnAllNativeThreads(), FlutterEnginePostDartObject(), FlutterEnginePostRenderThreadTask(), FlutterEngineRegisterExternalTexture(), FlutterEngineReloadSystemFonts(), FlutterEngineRun(), FlutterEngineRunInitialized(), FlutterEngineRunsAOTCompiledDartCode(), FlutterEngineRunTask(), FlutterEngineSendPlatformMessage(), FlutterEngineSendPlatformMessageResponse(), FlutterEngineSendPointerEvent(), FlutterEngineSendWindowMetricsEvent(), FlutterEngineShutdown(), FlutterEngineTraceEventDurationBegin(), FlutterEngineTraceEventDurationEnd(), FlutterEngineTraceEventInstant(), FlutterEngineUnregisterExternalTexture(), FlutterEngineUpdateAccessibilityFeatures(), FlutterEngineUpdateLocales(), FlutterEngineUpdateSemanticsEnabled(), FlutterPlatformMessageCreateResponseHandle(), FlutterPlatformMessageReleaseResponseHandle(), fuchsia::dart::Initialize(), kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, flutter::NotifyLowMemoryWarning(), and SET_PROC.

Referenced by flutter::testing::TEST().

2053  {
2054  if (!table) {
2055  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Null table specified.");
2056  }
2057 #define SET_PROC(member, function) \
2058  if (STRUCT_HAS_MEMBER(table, member)) { \
2059  table->member = &function; \
2060  }
2061 
2062  SET_PROC(CreateAOTData, FlutterEngineCreateAOTData);
2063  SET_PROC(CollectAOTData, FlutterEngineCollectAOTData);
2064  SET_PROC(Run, FlutterEngineRun);
2065  SET_PROC(Shutdown, FlutterEngineShutdown);
2067  SET_PROC(Deinitialize, FlutterEngineDeinitialize);
2068  SET_PROC(RunInitialized, FlutterEngineRunInitialized);
2069  SET_PROC(SendWindowMetricsEvent, FlutterEngineSendWindowMetricsEvent);
2070  SET_PROC(SendPointerEvent, FlutterEngineSendPointerEvent);
2071  SET_PROC(SendPlatformMessage, FlutterEngineSendPlatformMessage);
2072  SET_PROC(PlatformMessageCreateResponseHandle,
2074  SET_PROC(PlatformMessageReleaseResponseHandle,
2076  SET_PROC(SendPlatformMessageResponse,
2078  SET_PROC(RegisterExternalTexture, FlutterEngineRegisterExternalTexture);
2079  SET_PROC(UnregisterExternalTexture, FlutterEngineUnregisterExternalTexture);
2080  SET_PROC(MarkExternalTextureFrameAvailable,
2082  SET_PROC(UpdateSemanticsEnabled, FlutterEngineUpdateSemanticsEnabled);
2083  SET_PROC(UpdateAccessibilityFeatures,
2086  SET_PROC(OnVsync, FlutterEngineOnVsync);
2087  SET_PROC(ReloadSystemFonts, FlutterEngineReloadSystemFonts);
2088  SET_PROC(TraceEventDurationBegin, FlutterEngineTraceEventDurationBegin);
2089  SET_PROC(TraceEventDurationEnd, FlutterEngineTraceEventDurationEnd);
2090  SET_PROC(TraceEventInstant, FlutterEngineTraceEventInstant);
2091  SET_PROC(PostRenderThreadTask, FlutterEnginePostRenderThreadTask);
2092  SET_PROC(GetCurrentTime, FlutterEngineGetCurrentTime);
2093  SET_PROC(RunTask, FlutterEngineRunTask);
2094  SET_PROC(UpdateLocales, FlutterEngineUpdateLocales);
2095  SET_PROC(RunsAOTCompiledDartCode, FlutterEngineRunsAOTCompiledDartCode);
2096  SET_PROC(PostDartObject, FlutterEnginePostDartObject);
2098  SET_PROC(PostCallbackOnAllNativeThreads,
2100  SET_PROC(NotifyDisplayUpdate, FlutterEngineNotifyDisplayUpdate);
2101 #undef SET_PROC
2102 
2103  return kSuccess;
2104 }
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:2012
static void DispatchSemanticsAction(JNIEnv *env, jobject jcaller, jlong shell_holder, jint id, jint action, jobject args, jint args_position)
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:1206
FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle(FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterPlatformMessageResponseHandle *response)
Collects the handle created using FlutterPlatformMessageCreateResponseHandle.
Definition: embedder.cc:1483
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 engine via the FlutterTa...
Definition: embedder.cc:1717
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:1683
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:1691
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:1497
FlutterEngineResult FlutterEngineDispatchSemanticsAction(FLUTTER_API_SYMBOL(FlutterEngine) engine, uint64_t id, FlutterSemanticsAction action, const uint8_t *data, size_t data_length)
Dispatch a semantics action to the specified semantics node.
Definition: embedder.cc:1615
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures(FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterAccessibilityFeature flags)
Sets additional accessibility features.
Definition: embedder.cc:1601
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:1218
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:1825
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:1569
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:1950
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:1679
FlutterEngineResult FlutterEngineReloadSystemFonts(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Reloads the system fonts in engine.
Definition: embedder.cc:1662
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:1687
static void NotifyLowMemoryWarning(JNIEnv *env, jobject obj, jlong shell_holder)
FlutterEngineResult FlutterEngineUpdateSemanticsEnabled(FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled)
Enable or disable accessibility semantics.
Definition: embedder.cc:1587
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:718
FlutterEngineResult FlutterEngineCollectAOTData(FlutterEngineAOTData data)
Collects the AOT data.
Definition: embedder.cc:651
void Initialize(fidl::InterfaceHandle< fuchsia::sys::Environment > environment, zx::channel directory_request, std::optional< zx::eventpair > view_ref)
Definition: fuchsia.cc:103
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:1761
#define SET_PROC(member, function)
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:1529
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:1973
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:734
FlutterEngineResult FlutterEngineUnregisterExternalTexture(FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier)
Unregister a previous texture registration.
Definition: embedder.cc:1548
FlutterEngineResult FlutterEngineSendPointerEvent(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPointerEvent *pointers, size_t events_count)
Definition: embedder.cc:1323
FlutterEngineResult FlutterEngineSendWindowMetricsEvent(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterWindowMetricsEvent *flutter_metrics)
Definition: embedder.cc:1229
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:1635
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.
Definition: embedder.cc:1167
bool FlutterEngineRunsAOTCompiledDartCode(void)
Returns if the Flutter engine instance will run AOT compiled Dart code. This call has no threading re...
Definition: embedder.cc:1821
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:1713
FlutterEngineResult FlutterEngineSendPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessage *flutter_message)
Definition: embedder.cc:1396
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:1448
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:597

◆ 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 734 of file embedder.cc.

Referenced by fl_engine_start(), FlutterEngineGetProcAddresses(), FlutterEngineRun(), and flutter::testing::EmbedderConfigBuilder::InitializeEngine().

739  {
740  // Step 0: Figure out arguments for shell creation.
741  if (version != FLUTTER_ENGINE_VERSION) {
742  return LOG_EMBEDDER_ERROR(
744  "Flutter embedder version mismatch. There has been a breaking change. "
745  "Please consult the changelog and update the embedder.");
746  }
747 
748  if (engine_out == nullptr) {
750  "The engine out parameter was missing.");
751  }
752 
753  if (args == nullptr) {
755  "The Flutter project arguments were missing.");
756  }
757 
758  if (SAFE_ACCESS(args, assets_path, nullptr) == nullptr) {
759  return LOG_EMBEDDER_ERROR(
761  "The assets path in the Flutter project arguments was missing.");
762  }
763 
764  if (SAFE_ACCESS(args, main_path__unused__, nullptr) != nullptr) {
765  FML_LOG(WARNING)
766  << "FlutterProjectArgs.main_path is deprecated and should be set null.";
767  }
768 
769  if (SAFE_ACCESS(args, packages_path__unused__, nullptr) != nullptr) {
770  FML_LOG(WARNING) << "FlutterProjectArgs.packages_path is deprecated and "
771  "should be set null.";
772  }
773 
774  if (!IsRendererValid(config)) {
776  "The renderer configuration was invalid.");
777  }
778 
779  std::string icu_data_path;
780  if (SAFE_ACCESS(args, icu_data_path, nullptr) != nullptr) {
781  icu_data_path = SAFE_ACCESS(args, icu_data_path, nullptr);
782  }
783 
784  if (SAFE_ACCESS(args, persistent_cache_path, nullptr) != nullptr) {
785  std::string persistent_cache_path =
786  SAFE_ACCESS(args, persistent_cache_path, nullptr);
788  }
789 
790  if (SAFE_ACCESS(args, is_persistent_cache_read_only, false)) {
792  }
793 
794  fml::CommandLine command_line;
795  if (SAFE_ACCESS(args, command_line_argc, 0) != 0 &&
796  SAFE_ACCESS(args, command_line_argv, nullptr) != nullptr) {
797  command_line = fml::CommandLineFromArgcArgv(
798  SAFE_ACCESS(args, command_line_argc, 0),
799  SAFE_ACCESS(args, command_line_argv, nullptr));
800  }
801 
802  flutter::Settings settings = flutter::SettingsFromCommandLine(command_line);
803 
804  if (SAFE_ACCESS(args, aot_data, nullptr)) {
805  if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) ||
806  SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) ||
807  SAFE_ACCESS(args, isolate_snapshot_data, nullptr) ||
808  SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr)) {
809  return LOG_EMBEDDER_ERROR(
811  "Multiple AOT sources specified. Embedders should provide either "
812  "*_snapshot_* buffers or aot_data, not both.");
813  }
814  }
815 
816  PopulateSnapshotMappingCallbacks(args, settings);
817 
818  settings.icu_data_path = icu_data_path;
819  settings.assets_path = args->assets_path;
820  settings.leak_vm = !SAFE_ACCESS(args, shutdown_dart_vm_when_done, false);
821  settings.old_gen_heap_size = SAFE_ACCESS(args, dart_old_gen_heap_size, -1);
822 
824  // Verify the assets path contains Dart 2 kernel assets.
825  const std::string kApplicationKernelSnapshotFileName = "kernel_blob.bin";
826  std::string application_kernel_path = fml::paths::JoinPaths(
827  {settings.assets_path, kApplicationKernelSnapshotFileName});
828  if (!fml::IsFile(application_kernel_path)) {
829  return LOG_EMBEDDER_ERROR(
831  "Not running in AOT mode but could not resolve the kernel binary.");
832  }
834  }
835 
836  settings.task_observer_add = [](intptr_t key, fml::closure callback) {
837  fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));
838  };
839  settings.task_observer_remove = [](intptr_t key) {
841  };
842  if (SAFE_ACCESS(args, root_isolate_create_callback, nullptr) != nullptr) {
843  VoidCallback callback =
844  SAFE_ACCESS(args, root_isolate_create_callback, nullptr);
846  [callback, user_data](const auto& isolate) { callback(user_data); };
847  }
848 
850  update_semantics_nodes_callback = nullptr;
851  if (SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr) {
852  update_semantics_nodes_callback =
853  [ptr = args->update_semantics_node_callback,
855  for (const auto& value : update) {
856  const auto& node = value.second;
857  SkMatrix transform = node.transform.asM33();
858  FlutterTransformation flutter_transform{
859  transform.get(SkMatrix::kMScaleX),
860  transform.get(SkMatrix::kMSkewX),
861  transform.get(SkMatrix::kMTransX),
862  transform.get(SkMatrix::kMSkewY),
863  transform.get(SkMatrix::kMScaleY),
864  transform.get(SkMatrix::kMTransY),
865  transform.get(SkMatrix::kMPersp0),
866  transform.get(SkMatrix::kMPersp1),
867  transform.get(SkMatrix::kMPersp2)};
868  const FlutterSemanticsNode embedder_node{
869  sizeof(FlutterSemanticsNode),
870  node.id,
871  static_cast<FlutterSemanticsFlag>(node.flags),
872  static_cast<FlutterSemanticsAction>(node.actions),
873  node.textSelectionBase,
874  node.textSelectionExtent,
875  node.scrollChildren,
876  node.scrollIndex,
877  node.scrollPosition,
878  node.scrollExtentMax,
879  node.scrollExtentMin,
880  node.elevation,
881  node.thickness,
882  node.label.c_str(),
883  node.hint.c_str(),
884  node.value.c_str(),
885  node.increasedValue.c_str(),
886  node.decreasedValue.c_str(),
887  static_cast<FlutterTextDirection>(node.textDirection),
888  FlutterRect{node.rect.fLeft, node.rect.fTop, node.rect.fRight,
889  node.rect.fBottom},
890  flutter_transform,
891  node.childrenInTraversalOrder.size(),
892  &node.childrenInTraversalOrder[0],
893  &node.childrenInHitTestOrder[0],
894  node.customAccessibilityActions.size(),
895  &node.customAccessibilityActions[0],
896  node.platformViewId,
897  };
898  ptr(&embedder_node, user_data);
899  }
900  const FlutterSemanticsNode batch_end_sentinel = {
901  sizeof(FlutterSemanticsNode),
903  };
904  ptr(&batch_end_sentinel, user_data);
905  };
906  }
907 
909  update_semantics_custom_actions_callback = nullptr;
910  if (SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) !=
911  nullptr) {
912  update_semantics_custom_actions_callback =
915  for (const auto& value : actions) {
916  const auto& action = value.second;
917  const FlutterSemanticsCustomAction embedder_action = {
919  action.id,
920  static_cast<FlutterSemanticsAction>(action.overrideId),
921  action.label.c_str(),
922  action.hint.c_str(),
923  };
924  ptr(&embedder_action, user_data);
925  }
926  const FlutterSemanticsCustomAction batch_end_sentinel = {
929  };
930  ptr(&batch_end_sentinel, user_data);
931  };
932  }
933 
935  platform_message_response_callback = nullptr;
936  if (SAFE_ACCESS(args, platform_message_callback, nullptr) != nullptr) {
937  platform_message_response_callback =
938  [ptr = args->platform_message_callback,
940  auto handle = new FlutterPlatformMessageResponseHandle();
941  const FlutterPlatformMessage incoming_message = {
942  sizeof(FlutterPlatformMessage), // struct_size
943  message->channel().c_str(), // channel
944  message->data().data(), // message
945  message->data().size(), // message_size
946  handle, // response_handle
947  };
948  handle->message = std::move(message);
949  return ptr(&incoming_message, user_data);
950  };
951  }
952 
953  flutter::VsyncWaiterEmbedder::VsyncCallback vsync_callback = nullptr;
954  if (SAFE_ACCESS(args, vsync_callback, nullptr) != nullptr) {
955  vsync_callback = [ptr = args->vsync_callback, user_data](intptr_t baton) {
956  return ptr(user_data, baton);
957  };
958  }
959 
961  compute_platform_resolved_locale_callback = nullptr;
962  if (SAFE_ACCESS(args, compute_platform_resolved_locale_callback, nullptr) !=
963  nullptr) {
964  compute_platform_resolved_locale_callback =
966  const std::vector<std::string>& supported_locales_data) {
967  const size_t number_of_strings_per_locale = 3;
968  size_t locale_count =
969  supported_locales_data.size() / number_of_strings_per_locale;
970  std::vector<FlutterLocale> supported_locales;
971  std::vector<const FlutterLocale*> supported_locales_ptr;
972  for (size_t i = 0; i < locale_count; ++i) {
973  supported_locales.push_back(
974  {.struct_size = sizeof(FlutterLocale),
975  .language_code =
976  supported_locales_data[i * number_of_strings_per_locale +
977  0]
978  .c_str(),
979  .country_code =
980  supported_locales_data[i * number_of_strings_per_locale +
981  1]
982  .c_str(),
983  .script_code =
984  supported_locales_data[i * number_of_strings_per_locale +
985  2]
986  .c_str(),
987  .variant_code = nullptr});
988  supported_locales_ptr.push_back(&supported_locales[i]);
989  }
990 
991  const FlutterLocale* result =
992  ptr(supported_locales_ptr.data(), locale_count);
993 
994  std::unique_ptr<std::vector<std::string>> out =
995  std::make_unique<std::vector<std::string>>();
996  if (result) {
997  std::string language_code(SAFE_ACCESS(result, language_code, ""));
998  if (language_code != "") {
999  out->push_back(language_code);
1000  out->emplace_back(SAFE_ACCESS(result, country_code, ""));
1001  out->emplace_back(SAFE_ACCESS(result, script_code, ""));
1002  }
1003  }
1004  return out;
1005  };
1006  }
1007 
1008  auto external_view_embedder_result =
1009  InferExternalViewEmbedderFromArgs(SAFE_ACCESS(args, compositor, nullptr));
1010  if (external_view_embedder_result.second) {
1012  "Compositor arguments were invalid.");
1013  }
1014 
1016  {
1017  update_semantics_nodes_callback, //
1018  update_semantics_custom_actions_callback, //
1019  platform_message_response_callback, //
1020  vsync_callback, //
1021  compute_platform_resolved_locale_callback, //
1022  };
1023 
1024  auto on_create_platform_view = InferPlatformViewCreationCallback(
1025  config, user_data, platform_dispatch_table,
1026  std::move(external_view_embedder_result.first));
1027 
1028  if (!on_create_platform_view) {
1029  return LOG_EMBEDDER_ERROR(
1031  "Could not infer platform view creation callback.");
1032  }
1033 
1035  [](flutter::Shell& shell) {
1036  return std::make_unique<flutter::Rasterizer>(shell);
1037  };
1038 
1039 #ifdef SHELL_ENABLE_GL
1040  // TODO(chinmaygarde): This is the wrong spot for this. It belongs in the
1041  // platform view jump table.
1043  external_texture_callback;
1044  if (config->type == kOpenGL) {
1045  const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
1046  if (SAFE_ACCESS(open_gl_config, gl_external_texture_frame_callback,
1047  nullptr) != nullptr) {
1048  external_texture_callback =
1049  [ptr = open_gl_config->gl_external_texture_frame_callback, user_data](
1050  int64_t texture_identifier, GrDirectContext* context,
1051  const SkISize& size) -> sk_sp<SkImage> {
1052  FlutterOpenGLTexture texture = {};
1053 
1054  if (!ptr(user_data, texture_identifier, size.width(), size.height(),
1055  &texture)) {
1056  return nullptr;
1057  }
1058 
1059  GrGLTextureInfo gr_texture_info = {texture.target, texture.name,
1060  texture.format};
1061 
1062  size_t width = size.width();
1063  size_t height = size.height();
1064 
1065  if (texture.width != 0 && texture.height != 0) {
1066  width = texture.width;
1067  height = texture.height;
1068  }
1069 
1070  GrBackendTexture gr_backend_texture(width, height, GrMipMapped::kNo,
1071  gr_texture_info);
1072  SkImage::TextureReleaseProc release_proc = texture.destruction_callback;
1073  auto image = SkImage::MakeFromTexture(
1074  context, // context
1075  gr_backend_texture, // texture handle
1076  kTopLeft_GrSurfaceOrigin, // origin
1077  kRGBA_8888_SkColorType, // color type
1078  kPremul_SkAlphaType, // alpha type
1079  nullptr, // colorspace
1080  release_proc, // texture release proc
1081  texture.user_data // texture release context
1082  );
1083 
1084  if (!image) {
1085  // In case Skia rejects the image, call the release proc so that
1086  // embedders can perform collection of intermediates.
1087  if (release_proc) {
1088  release_proc(texture.user_data);
1089  }
1090  FML_LOG(ERROR) << "Could not create external texture.";
1091  return nullptr;
1092  }
1093 
1094  return image;
1095  };
1096  }
1097  }
1098 #endif
1099 
1100  auto thread_host =
1102  SAFE_ACCESS(args, custom_task_runners, nullptr));
1103 
1104  if (!thread_host || !thread_host->IsValid()) {
1106  "Could not setup or infer thread configuration "
1107  "to run the Flutter engine on.");
1108  }
1109 
1110  auto task_runners = thread_host->GetTaskRunners();
1111 
1112  if (!task_runners.IsValid()) {
1114  "Task runner configuration was invalid.");
1115  }
1116 
1117  auto run_configuration =
1119 
1120  if (SAFE_ACCESS(args, custom_dart_entrypoint, nullptr) != nullptr) {
1121  auto dart_entrypoint = std::string{args->custom_dart_entrypoint};
1122  if (dart_entrypoint.size() != 0) {
1123  run_configuration.SetEntrypoint(std::move(dart_entrypoint));
1124  }
1125  }
1126 
1127  if (SAFE_ACCESS(args, dart_entrypoint_argc, 0) > 0) {
1128  if (SAFE_ACCESS(args, dart_entrypoint_argv, nullptr) == nullptr) {
1130  "Could not determine Dart entrypoint arguments "
1131  "as dart_entrypoint_argc "
1132  "was set, but dart_entrypoint_argv was null.");
1133  }
1134  std::vector<std::string> arguments(args->dart_entrypoint_argc);
1135  for (int i = 0; i < args->dart_entrypoint_argc; ++i) {
1136  arguments[i] = std::string{args->dart_entrypoint_argv[i]};
1137  }
1138  settings.dart_entrypoint_args = std::move(arguments);
1139  }
1140 
1141  if (!run_configuration.IsValid()) {
1142  return LOG_EMBEDDER_ERROR(
1144  "Could not infer the Flutter project to run from given arguments.");
1145  }
1146 
1147  // Create the engine but don't launch the shell or run the root isolate.
1148  auto embedder_engine = std::make_unique<flutter::EmbedderEngine>(
1149  std::move(thread_host), //
1150  std::move(task_runners), //
1151  std::move(settings), //
1152  std::move(run_configuration), //
1153  on_create_platform_view, //
1154  on_create_rasterizer //
1155 #ifdef SHELL_ENABLE_GL
1156  ,
1157  external_texture_callback //
1158 #endif
1159  );
1160 
1161  // Release the ownership of the embedder engine to the caller.
1162  *engine_out = reinterpret_cast<FLUTTER_API_SYMBOL(FlutterEngine)>(
1163  embedder_engine.release());
1164  return kSuccess;
1165 }
const char * channel
Definition: embedder.h:567
struct _FlutterEngine * FLUTTER_API_SYMBOL(FlutterEngine)
Definition: embedder.h:220
std::function< std::unique_ptr< T >(Shell &)> CreateCallback
Definition: shell.h:99
FlutterComputePlatformResolvedLocaleCallback compute_platform_resolved_locale_callback
Definition: embedder.h:1326
std::vector< std::string > dart_entrypoint_args
Definition: settings.h:98
std::function< void(const DartIsolate &)> root_isolate_create_callback
Definition: settings.h:174
std::string application_kernel_asset
Definition: settings.h:91
void AddTaskObserver(intptr_t key, const fml::closure &callback)
Definition: message_loop.cc:64
CommandLine CommandLineFromArgcArgv(int argc, const char *const *argv)
Definition: command_line.h:222
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
int64_t old_gen_heap_size
Definition: settings.h:236
static bool IsRendererValid(const FlutterRendererConfig *config)
Definition: embedder.cc:124
static FML_EMBEDDER_ONLY MessageLoop & GetCurrent()
Definition: message_loop.cc:19
std::unordered_map< int32_t, SemanticsNode > SemanticsNodeUpdates
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
Settings SettingsFromCommandLine(const fml::CommandLine &command_line)
Definition: switches.cc:216
#define FML_LOG(severity)
Definition: logging.h:65
FlutterPlatformMessageCallback platform_message_callback
Definition: embedder.h:1174
A structure to represent a rectangle.
Definition: embedder.h:324
static const char * kApplicationKernelSnapshotFileName
#define SAFE_ACCESS(pointer, member, default_value)
FlutterSemanticsAction
Definition: embedder.h:97
const char *const * dart_entrypoint_argv
Definition: embedder.h:1338
VsyncCallback vsync_callback
Definition: embedder.h:1251
std::function< void()> closure
Definition: closure.h:14
std::string JoinPaths(std::initializer_list< std::string > components)
Definition: paths.cc:14
G_BEGIN_DECLS FlValue gpointer user_data
static RunConfiguration InferFromSettings(const Settings &settings, fml::RefPtr< fml::TaskRunner > io_worker=nullptr)
Attempts to infer a run configuration from the settings object. This tries to create a run configurat...
#define FLUTTER_ENGINE_VERSION
Definition: embedder.h:63
FlutterRendererType type
Definition: embedder.h:448
uint8_t value
VoidCallback destruction_callback
Definition: embedder.h:266
static void SetCacheDirectoryPath(std::string path)
FlutterUpdateSemanticsNodeCallback update_semantics_node_callback
Definition: embedder.h:1218
std::function< void(flutter::CustomAccessibilityActionUpdates actions)> UpdateSemanticsCustomActionsCallback
SemanticsAction action
int32_t id
The unique identifier for this node.
Definition: embedder.h:607
int32_t height
FlutterUpdateSemanticsCustomActionCallback update_semantics_custom_action_callback
Definition: embedder.h:1229
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:199
TextureFrameCallback gl_external_texture_frame_callback
Definition: embedder.h:420
int32_t width
static std::pair< std::unique_ptr< flutter::EmbedderExternalViewEmbedder >, bool > InferExternalViewEmbedderFromArgs(const FlutterCompositor *compositor)
Definition: embedder.cc:534
std::function< void(fml::RefPtr< flutter::PlatformMessage >)> PlatformMessageResponseCallback
TaskObserverAdd task_observer_add
Definition: settings.h:170
void PopulateSnapshotMappingCallbacks(const FlutterProjectArgs *args, flutter::Settings &settings)
Definition: embedder.cc:662
static std::unique_ptr< EmbedderThreadHost > CreateEmbedderOrEngineManagedThreadHost(const FlutterCustomTaskRunners *custom_task_runners)
std::string icu_data_path
Definition: settings.h:211
const char * custom_dart_entrypoint
Definition: embedder.h:1260
const char * assets_path
Definition: embedder.h:1127
FlutterOpenGLRendererConfig open_gl
Definition: embedder.h:450
const int32_t kFlutterSemanticsNodeIdBatchEnd
Definition: embedder.cc:64
size_t height
Height of the texture.
Definition: embedder.h:274
bool IsFile(const std::string &path)
Definition: file_posix.cc:143
std::function< void(flutter::SemanticsNodeUpdates update)> UpdateSemanticsNodesCallback
void RemoveTaskObserver(intptr_t key)
Definition: message_loop.cc:68
std::function< void(intptr_t)> VsyncCallback
void(* VoidCallback)(void *)
Definition: embedder.h:243
struct _FlutterPlatformMessageResponseHandle FlutterPlatformMessageResponseHandle
Definition: embedder.h:561
uint32_t name
The name of the texture.
Definition: embedder.h:259
FlutterTextDirection
Definition: embedder.h:211
std::unordered_map< int32_t, CustomAccessibilityAction > CustomAccessibilityActionUpdates
TaskObserverRemove task_observer_remove
Definition: settings.h:171
void * user_data
User data to be returned on the invocation of the destruction callback.
Definition: embedder.h:263
std::function< sk_sp< SkImage >(int64_t texture_identifier, GrDirectContext *, const SkISize &)> ExternalTextureCallback
std::string assets_path
Definition: settings.h:217
uint32_t format
The texture format (example GL_RGBA8).
Definition: embedder.h:261
const int32_t kFlutterSemanticsCustomActionIdBatchEnd
Definition: embedder.cc:65
static flutter::Shell::CreateCallback< flutter::PlatformView > InferPlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder)
Definition: embedder.cc:316
std::function< std::unique_ptr< std::vector< std::string > >(const std::vector< std::string > &supported_locale_data)> ComputePlatformResolvedLocaleCallback

◆ 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 1569 of file embedder.cc.

References kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and flutter::MarkTextureFrameAvailable().

Referenced by FlutterEngineGetProcAddresses(), and FlutterEngine::shutDownEngine.

1571  {
1572  if (engine == nullptr) {
1573  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1574  }
1575  if (texture_identifier == 0) {
1576  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid texture identifier.");
1577  }
1578  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
1579  ->MarkTextureFrameAvailable(texture_identifier)) {
1580  return LOG_EMBEDDER_ERROR(
1582  "Could not mark the texture frame as being available.");
1583  }
1584  return kSuccess;
1585 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
static void MarkTextureFrameAvailable(JNIEnv *env, jobject jcaller, jlong shell_holder, jlong texture_id)

◆ 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 2012 of file embedder.cc.

References engine, kFlutterEngineDisplaysUpdateTypeStartup, kInvalidArguments, flutter::kStartup, kSuccess, and LOG_EMBEDDER_ERROR.

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

2016  {
2017  if (raw_engine == nullptr) {
2018  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
2019  }
2020 
2021  if (!ValidDisplayConfiguration(embedder_displays, display_count)) {
2022  return LOG_EMBEDDER_ERROR(
2024  "Invalid FlutterEngineDisplay configuration specified.");
2025  }
2026 
2027  auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine);
2028 
2029  switch (update_type) {
2031  std::vector<flutter::Display> displays;
2032  for (size_t i = 0; i < display_count; i++) {
2033  flutter::Display display =
2034  flutter::Display(embedder_displays[i].refresh_rate);
2035  if (!embedder_displays[i].single_display) {
2036  display = flutter::Display(embedder_displays[i].display_id,
2037  embedder_displays[i].refresh_rate);
2038  }
2039  displays.push_back(display);
2040  }
2041  engine->GetShell().OnDisplayUpdates(flutter::DisplayUpdateType::kStartup,
2042  displays);
2043  return kSuccess;
2044  }
2045  default:
2046  return LOG_EMBEDDER_ERROR(
2048  "Invalid FlutterEngineDisplaysUpdateType type specified.");
2049  }
2050 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ 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 1950 of file embedder.cc.

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

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

1951  {
1952  auto engine = reinterpret_cast<flutter::EmbedderEngine*>(raw_engine);
1953  if (engine == nullptr || !engine->IsValid()) {
1954  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine was invalid.");
1955  }
1956 
1957  engine->GetShell().NotifyLowMemoryWarning();
1958 
1959  rapidjson::Document document;
1960  auto& allocator = document.GetAllocator();
1961 
1962  document.SetObject();
1963  document.AddMember("type", "memoryPressure", allocator);
1964 
1965  return DispatchJSONPlatformMessage(raw_engine, std::move(document),
1966  "flutter/system")
1967  ? kSuccess
1970  "Could not dispatch the low memory notification message.");
1971 }
static bool DispatchJSONPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, rapidjson::Document document, const std::string &channel_name)
Definition: embedder.cc:1730
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ 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 1635 of file embedder.cc.

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

Referenced by FlutterEngineGetProcAddresses().

1639  {
1640  if (engine == nullptr) {
1641  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1642  }
1643 
1644  TRACE_EVENT0("flutter", "FlutterEngineOnVsync");
1645 
1646  auto start_time = fml::TimePoint::FromEpochDelta(
1647  fml::TimeDelta::FromNanoseconds(frame_start_time_nanos));
1648 
1649  auto target_time = fml::TimePoint::FromEpochDelta(
1650  fml::TimeDelta::FromNanoseconds(frame_target_time_nanos));
1651 
1652  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->OnVsyncEvent(
1653  baton, start_time, target_time)) {
1654  return LOG_EMBEDDER_ERROR(
1656  "Could not notify the running engine instance of a Vsync event.");
1657  }
1658 
1659  return kSuccess;
1660 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:75
static constexpr TimeDelta FromNanoseconds(int64_t nanos)
Definition: time_delta.h:40
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
static constexpr TimePoint FromEpochDelta(TimeDelta ticks)
Definition: time_point.h:36

◆ 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 1973 of file embedder.cc.

References engine, kInvalidArguments, kSuccess, and LOG_EMBEDDER_ERROR.

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

1976  {
1977  if (engine == nullptr) {
1978  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1979  }
1980 
1981  if (callback == nullptr) {
1983  "Invalid native thread callback.");
1984  }
1985 
1986  return reinterpret_cast<flutter::EmbedderEngine*>(engine)
1987  ->PostTaskOnEngineManagedNativeThreads(
1988  [callback, user_data](FlutterNativeThreadType type) {
1989  callback(type, user_data);
1990  })
1991  ? kSuccess
1993  "Internal error while attempting to post "
1994  "tasks to all threads.");
1995 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
G_BEGIN_DECLS FlValue gpointer user_data
FlutterNativeThreadType
Definition: embedder.h:1080

◆ 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 1825 of file embedder.cc.

References FlutterEngineDartObject::buffer_value, 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(), and flutter::testing::TEST_F().

1828  {
1829  if (engine == nullptr) {
1830  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1831  }
1832 
1833  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->IsValid()) {
1834  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine not running.");
1835  }
1836 
1837  if (port == ILLEGAL_PORT) {
1839  "Attempted to post to an illegal port.");
1840  }
1841 
1842  if (object == nullptr) {
1844  "Invalid Dart object to post.");
1845  }
1846 
1847  Dart_CObject dart_object = {};
1848  fml::ScopedCleanupClosure typed_data_finalizer;
1849 
1850  switch (object->type) {
1852  dart_object.type = Dart_CObject_kNull;
1853  break;
1855  dart_object.type = Dart_CObject_kBool;
1856  dart_object.value.as_bool = object->bool_value;
1857  break;
1859  dart_object.type = Dart_CObject_kInt32;
1860  dart_object.value.as_int32 = object->int32_value;
1861  break;
1863  dart_object.type = Dart_CObject_kInt64;
1864  dart_object.value.as_int64 = object->int64_value;
1865  break;
1867  dart_object.type = Dart_CObject_kDouble;
1868  dart_object.value.as_double = object->double_value;
1869  break;
1871  if (object->string_value == nullptr) {
1873  "kFlutterEngineDartObjectTypeString must be "
1874  "a null terminated string but was null.");
1875  }
1876  dart_object.type = Dart_CObject_kString;
1877  dart_object.value.as_string = const_cast<char*>(object->string_value);
1878  break;
1880  auto* buffer = SAFE_ACCESS(object->buffer_value, buffer, nullptr);
1881  if (buffer == nullptr) {
1883  "kFlutterEngineDartObjectTypeBuffer must "
1884  "specify a buffer but found nullptr.");
1885  }
1886  auto buffer_size = SAFE_ACCESS(object->buffer_value, buffer_size, 0);
1887  auto callback =
1888  SAFE_ACCESS(object->buffer_value, buffer_collect_callback, nullptr);
1889  auto user_data = SAFE_ACCESS(object->buffer_value, user_data, nullptr);
1890 
1891  // The user has provided a callback, let them manage the lifecycle of
1892  // the underlying data. If not, copy it out from the provided buffer.
1893 
1894  if (callback == nullptr) {
1895  dart_object.type = Dart_CObject_kTypedData;
1896  dart_object.value.as_typed_data.type = Dart_TypedData_kUint8;
1897  dart_object.value.as_typed_data.length = buffer_size;
1898  dart_object.value.as_typed_data.values = buffer;
1899  } else {
1900  struct ExternalTypedDataPeer {
1901  void* user_data = nullptr;
1902  VoidCallback trampoline = nullptr;
1903  };
1904  auto peer = new ExternalTypedDataPeer();
1905  peer->user_data = user_data;
1906  peer->trampoline = callback;
1907  // This finalizer is set so that in case of failure of the
1908  // Dart_PostCObject below, we collect the peer. The embedder is still
1909  // responsible for collecting the buffer in case of non-kSuccess
1910  // returns from this method. This finalizer must be released in case
1911  // of kSuccess returns from this method.
1912  typed_data_finalizer.SetClosure([peer]() {
1913  // This is the tiny object we use as the peer to the Dart call so
1914  // that we can attach the a trampoline to the embedder supplied
1915  // callback. In case of error, we need to collect this object lest
1916  // we introduce a tiny leak.
1917  delete peer;
1918  });
1919  dart_object.type = Dart_CObject_kExternalTypedData;
1920  dart_object.value.as_external_typed_data.type = Dart_TypedData_kUint8;
1921  dart_object.value.as_external_typed_data.length = buffer_size;
1922  dart_object.value.as_external_typed_data.data = buffer;
1923  dart_object.value.as_external_typed_data.peer = peer;
1924  dart_object.value.as_external_typed_data.callback =
1925  +[](void* unused_isolate_callback_data,
1926  Dart_WeakPersistentHandle unused_handle, void* peer) {
1927  auto typed_peer = reinterpret_cast<ExternalTypedDataPeer*>(peer);
1928  typed_peer->trampoline(typed_peer->user_data);
1929  delete typed_peer;
1930  };
1931  }
1932  } break;
1933  default:
1934  return LOG_EMBEDDER_ERROR(
1936  "Invalid FlutterEngineDartObjectType type specified.");
1937  }
1938 
1939  if (!Dart_PostCObject(port, &dart_object)) {
1941  "Could not post the object to the Dart VM.");
1942  }
1943 
1944  // On a successful call, the VM takes ownership of and is responsible for
1945  // invoking the finalizer.
1946  typed_data_finalizer.Release();
1947  return kSuccess;
1948 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
DEF_SWITCHES_START snapshot asset Path to the directory containing the four files specified by VmSnapshotInstructions and IsolateSnapshotInstructions vm snapshot The VM instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present isolate snapshot The isolate instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present icu symbol Prefix for the symbols representing ICU data linked into the Flutter library dart Flags passed directly to the Dart VM without being interpreted by the Flutter shell observatory port
Definition: switches.h:75
#define SAFE_ACCESS(pointer, member, default_value)
const char * string_value
Definition: embedder.h:1072
Wraps a closure that is invoked in the destructor unless released by the caller.
Definition: closure.h:32
G_BEGIN_DECLS FlValue gpointer user_data
fml::closure SetClosure(const fml::closure &closure)
Definition: closure.h:44
fml::closure Release()
Definition: closure.h:50
void(* VoidCallback)(void *)
Definition: embedder.h:243
const FlutterEngineDartBuffer * buffer_value
Definition: embedder.h:1073
FlutterEngineDartObjectType type
Definition: embedder.h:1063

◆ 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 1691 of file embedder.cc.

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

Referenced by FlutterEngineGetProcAddresses().

1694  {
1695  if (engine == nullptr) {
1696  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1697  }
1698 
1699  if (callback == nullptr) {
1701  "Render thread callback was null.");
1702  }
1703 
1704  auto task = [callback, baton]() { callback(baton); };
1705 
1706  return reinterpret_cast<flutter::EmbedderEngine*>(engine)
1707  ->PostRenderThreadTask(task)
1708  ? kSuccess
1710  "Could not post the render thread task.");
1711 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ 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 1529 of file embedder.cc.

References kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and flutter::RegisterTexture().

Referenced by FlutterEngineGetProcAddresses(), and FlutterEngine::shutDownEngine.

1531  {
1532  if (engine == nullptr) {
1533  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1534  }
1535 
1536  if (texture_identifier == 0) {
1538  "Texture identifier was invalid.");
1539  }
1540  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->RegisterTexture(
1541  texture_identifier)) {
1543  "Could not register the specified texture.");
1544  }
1545  return kSuccess;
1546 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
static void RegisterTexture(JNIEnv *env, jobject jcaller, jlong shell_holder, jlong texture_id, jobject surface_texture)

◆ 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 1662 of file embedder.cc.

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

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

1663  {
1664  if (engine == nullptr) {
1665  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1666  }
1667 
1668  TRACE_EVENT0("flutter", "FlutterEngineReloadSystemFonts");
1669 
1670  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
1671  ->ReloadSystemFonts()) {
1673  "Could not reload system fonts.");
1674  }
1675 
1676  return kSuccess;
1677 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:75
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ 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 via the FlutterInitializeCall. 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 718 of file embedder.cc.

Referenced by FlutterEngineGetProcAddresses(), flutter::testing::EmbedderConfigBuilder::InitializeEngine(), RunFlutter(), RunFlutterEngine(), and flutter::FlutterWindowsEngine::RunWithEntrypoint().

723  {
724  auto result =
725  FlutterEngineInitialize(version, config, args, user_data, engine_out);
726 
727  if (result != kSuccess) {
728  return result;
729  }
730 
731  return FlutterEngineRunInitialized(*engine_out);
732 }
G_BEGIN_DECLS FlValue gpointer user_data
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:734
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.
Definition: embedder.cc:1167

◆ 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 1167 of file embedder.cc.

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

1168  {
1169  if (!engine) {
1170  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1171  }
1172 
1173  auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
1174 
1175  // The engine must not already be running. Initialize may only be called
1176  // once on an engine instance.
1177  if (embedder_engine->IsValid()) {
1178  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1179  }
1180 
1181  // Step 1: Launch the shell.
1182  if (!embedder_engine->LaunchShell()) {
1184  "Could not launch the engine using supplied "
1185  "initialization arguments.");
1186  }
1187 
1188  // Step 2: Tell the platform view to initialize itself.
1189  if (!embedder_engine->NotifyCreated()) {
1191  "Could not create platform view components.");
1192  }
1193 
1194  // Step 3: Launch the root isolate.
1195  if (!embedder_engine->RunRootIsolate()) {
1196  return LOG_EMBEDDER_ERROR(
1198  "Could not run the root isolate of the Flutter application using the "
1199  "project arguments specified.");
1200  }
1201 
1202  return kSuccess;
1203 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ 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 1821 of file embedder.cc.

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

1821  {
1823 }
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:199

◆ 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 engine 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 1717 of file embedder.cc.

Referenced by flutter_source_dispatch(), FlutterDesktopCreateWindow(), FlutterDesktopRunEngine(), FlutterEngineGetProcAddresses(), flutter::FlutterWindowsEngine::FlutterWindowsEngine(), FlutterEngine::shutDownEngine, and flutter::testing::TEST_F().

1719  {
1720  if (engine == nullptr) {
1721  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1722  }
1723 
1724  return reinterpret_cast<flutter::EmbedderEngine*>(engine)->RunTask(task)
1725  ? kSuccess
1727  "Could not run the specified task.");
1728 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ FlutterEngineSendPlatformMessage()

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

Definition at line 1396 of file embedder.cc.

Referenced by fl_engine_send_platform_message(), FlutterDesktopMessengerSendWithReply(), FlutterEngineGetProcAddresses(), FlutterEngine::shutDownEngine, and flutter::testing::TEST_F().

1398  {
1399  if (engine == nullptr) {
1400  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1401  }
1402 
1403  if (flutter_message == nullptr) {
1404  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid message argument.");
1405  }
1406 
1407  if (SAFE_ACCESS(flutter_message, channel, nullptr) == nullptr) {
1408  return LOG_EMBEDDER_ERROR(
1409  kInvalidArguments, "Message argument did not specify a valid channel.");
1410  }
1411 
1412  size_t message_size = SAFE_ACCESS(flutter_message, message_size, 0);
1413  const uint8_t* message_data = SAFE_ACCESS(flutter_message, message, nullptr);
1414 
1415  if (message_size != 0 && message_data == nullptr) {
1416  return LOG_EMBEDDER_ERROR(
1418  "Message size was non-zero but the message data was nullptr.");
1419  }
1420 
1421  const FlutterPlatformMessageResponseHandle* response_handle =
1422  SAFE_ACCESS(flutter_message, response_handle, nullptr);
1423 
1425  if (response_handle && response_handle->message) {
1426  response = response_handle->message->response();
1427  }
1428 
1430  if (message_size == 0) {
1431  message = fml::MakeRefCounted<flutter::PlatformMessage>(
1432  flutter_message->channel, response);
1433  } else {
1434  message = fml::MakeRefCounted<flutter::PlatformMessage>(
1435  flutter_message->channel,
1436  std::vector<uint8_t>(message_data, message_data + message_size),
1437  response);
1438  }
1439 
1440  return reinterpret_cast<flutter::EmbedderEngine*>(engine)
1441  ->SendPlatformMessage(std::move(message))
1442  ? kSuccess
1444  "Could not send a message to the running "
1445  "Flutter application.");
1446 }
const char * channel
Definition: embedder.h:567
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
#define SAFE_ACCESS(pointer, member, default_value)
fml::RefPtr< flutter::PlatformMessage > message
Definition: embedder.cc:576
const fml::RefPtr< PlatformMessageResponse > & response() const

◆ 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 1497 of file embedder.cc.

Referenced by fl_engine_send_platform_message_response(), FlutterDesktopMessengerSendResponse(), and FlutterEngineGetProcAddresses().

1501  {
1502  if (data_length != 0 && data == nullptr) {
1503  return LOG_EMBEDDER_ERROR(
1505  "Data size was non zero but the pointer to the data was null.");
1506  }
1507 
1508  auto response = handle->message->response();
1509 
1510  if (response) {
1511  if (data_length == 0) {
1512  response->CompleteEmpty();
1513  } else {
1514  response->Complete(std::make_unique<fml::DataMapping>(
1515  std::vector<uint8_t>({data, data + data_length})));
1516  }
1517  }
1518 
1519  delete handle;
1520 
1521  return kSuccess;
1522 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
fml::RefPtr< flutter::PlatformMessage > message
Definition: embedder.cc:576
const fml::RefPtr< PlatformMessageResponse > & response() const

◆ FlutterEngineSendPointerEvent()

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

Definition at line 1323 of file embedder.cc.

Referenced by fl_engine_send_mouse_pointer_event(), FlutterEngineGetProcAddresses(), GLFWcursorPositionCallbackAtPhase(), flutter::FlutterWindowsView::SendInitialBounds(), and SendPointerEventWithData().

1326  {
1327  if (engine == nullptr) {
1328  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1329  }
1330 
1331  if (pointers == nullptr || events_count == 0) {
1332  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid pointer events.");
1333  }
1334 
1335  auto packet = std::make_unique<flutter::PointerDataPacket>(events_count);
1336 
1337  const FlutterPointerEvent* current = pointers;
1338 
1339  for (size_t i = 0; i < events_count; ++i) {
1340  flutter::PointerData pointer_data;
1341  pointer_data.Clear();
1342  // this is currely in use only on android embedding.
1343  pointer_data.embedder_id = 0;
1344  pointer_data.time_stamp = SAFE_ACCESS(current, timestamp, 0);
1345  pointer_data.change = ToPointerDataChange(
1347  pointer_data.physical_x = SAFE_ACCESS(current, x, 0.0);
1348  pointer_data.physical_y = SAFE_ACCESS(current, y, 0.0);
1349  // Delta will be generated in pointer_data_packet_converter.cc.
1350  pointer_data.physical_delta_x = 0.0;
1351  pointer_data.physical_delta_y = 0.0;
1352  pointer_data.device = SAFE_ACCESS(current, device, 0);
1353  // Pointer identifier will be generated in
1354  // pointer_data_packet_converter.cc.
1355  pointer_data.pointer_identifier = 0;
1356  pointer_data.signal_kind = ToPointerDataSignalKind(
1357  SAFE_ACCESS(current, signal_kind, kFlutterPointerSignalKindNone));
1358  pointer_data.scroll_delta_x = SAFE_ACCESS(current, scroll_delta_x, 0.0);
1359  pointer_data.scroll_delta_y = SAFE_ACCESS(current, scroll_delta_y, 0.0);
1360  FlutterPointerDeviceKind device_kind = SAFE_ACCESS(current, device_kind, 0);
1361  // For backwards compatibility with embedders written before the device
1362  // kind and buttons were exposed, if the device kind is not set treat it
1363  // as a mouse, with a synthesized primary button state based on the phase.
1364  if (device_kind == 0) {
1366  pointer_data.buttons =
1368 
1369  } else {
1370  pointer_data.kind = ToPointerDataKind(device_kind);
1371  if (pointer_data.kind == flutter::PointerData::DeviceKind::kTouch) {
1372  // For touch events, set the button internally rather than requiring
1373  // it at the API level, since it's a confusing construction to expose.
1374  if (pointer_data.change == flutter::PointerData::Change::kDown ||
1375  pointer_data.change == flutter::PointerData::Change::kMove) {
1377  }
1378  } else {
1379  // Buttons use the same mask values, so pass them through directly.
1380  pointer_data.buttons = SAFE_ACCESS(current, buttons, 0);
1381  }
1382  }
1383  packet->SetPointerData(i, pointer_data);
1384  current = reinterpret_cast<const FlutterPointerEvent*>(
1385  reinterpret_cast<const uint8_t*>(current) + current->struct_size);
1386  }
1387 
1388  return reinterpret_cast<flutter::EmbedderEngine*>(engine)
1389  ->DispatchPointerDataPacket(std::move(packet))
1390  ? kSuccess
1392  "Could not dispatch pointer events to the "
1393  "running Flutter application.");
1394 }
flutter::PointerData::SignalKind ToPointerDataSignalKind(FlutterPointerSignalKind kind)
Definition: embedder.cc:1292
flutter::PointerData::DeviceKind ToPointerDataKind(FlutterPointerDeviceKind device_kind)
Definition: embedder.cc:1279
SignalKind signal_kind
Definition: pointer_data.h:65
int64_t pointer_identifier
Definition: pointer_data.h:67
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
FlutterPointerDeviceKind
The device type that created a pointer event.
Definition: embedder.h:507
#define SAFE_ACCESS(pointer, member, default_value)
flutter::PointerData::Change ToPointerDataChange(FlutterPointerPhase phase)
Definition: embedder.cc:1256
FlutterPointerPhase phase
Definition: fl_view.cc:78
int64_t PointerDataButtonsForLegacyEvent(flutter::PointerData::Change change)
Definition: embedder.cc:1305
static void DispatchPointerDataPacket(JNIEnv *env, jobject jcaller, jlong shell_holder, jobject buffer, jint position)

◆ FlutterEngineSendWindowMetricsEvent()

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

Definition at line 1229 of file embedder.cc.

Referenced by fl_engine_send_window_metrics_event(), FlutterEngineGetProcAddresses(), GLFWwindowSizeCallback(), flutter::FlutterWindowsView::OnScroll(), SendWindowMetrics(), and flutter::testing::TEST_F().

1231  {
1232  if (engine == nullptr || flutter_metrics == nullptr) {
1233  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1234  }
1235 
1236  flutter::ViewportMetrics metrics;
1237 
1238  metrics.physical_width = SAFE_ACCESS(flutter_metrics, width, 0.0);
1239  metrics.physical_height = SAFE_ACCESS(flutter_metrics, height, 0.0);
1240  metrics.device_pixel_ratio = SAFE_ACCESS(flutter_metrics, pixel_ratio, 1.0);
1241 
1242  if (metrics.device_pixel_ratio <= 0.0) {
1243  return LOG_EMBEDDER_ERROR(
1245  "Device pixel ratio was invalid. It must be greater than zero.");
1246  }
1247 
1248  return reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetViewportMetrics(
1249  std::move(metrics))
1250  ? kSuccess
1252  "Viewport metrics were invalid.");
1253 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
#define SAFE_ACCESS(pointer, member, default_value)
static void SetViewportMetrics(JNIEnv *env, jobject jcaller, jlong shell_holder, jfloat devicePixelRatio, jint physicalWidth, jint physicalHeight, jint physicalPaddingTop, jint physicalPaddingRight, jint physicalPaddingBottom, jint physicalPaddingLeft, jint physicalViewInsetTop, jint physicalViewInsetRight, jint physicalViewInsetBottom, jint physicalViewInsetLeft, jint systemGestureInsetTop, jint systemGestureInsetRight, jint systemGestureInsetBottom, jint systemGestureInsetLeft)
int32_t height
int32_t width

◆ 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 1218 of file embedder.cc.

Referenced by fl_engine_dispose(), FlutterDesktopDestroyWindow(), FlutterDesktopShutDownEngine(), FlutterEngineGetProcAddresses(), flutter::testing::UniqueEngineTraits::Free(), FlutterEngine::shutDownEngine, and flutter::FlutterWindowsEngine::Stop().

1219  {
1220  auto result = FlutterEngineDeinitialize(engine);
1221  if (result != kSuccess) {
1222  return result;
1223  }
1224  auto embedder_engine = reinterpret_cast<flutter::EmbedderEngine*>(engine);
1225  delete embedder_engine;
1226  return kSuccess;
1227 }
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:1206

◆ 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 1679 of file embedder.cc.

References fml::tracing::TraceEvent0().

Referenced by FlutterEngineGetProcAddresses().

1679  {
1680  fml::tracing::TraceEvent0("flutter", name);
1681 }
const char * name
Definition: fuchsia.cc:50
void TraceEvent0(TraceArg category_group, TraceArg name)
Definition: trace_event.cc:310

◆ 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 1683 of file embedder.cc.

References fml::tracing::TraceEventEnd().

Referenced by FlutterEngineGetProcAddresses().

1683  {
1685 }
void TraceEventEnd(TraceArg name)
Definition: trace_event.cc:324
const char * name
Definition: fuchsia.cc:50

◆ 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 1687 of file embedder.cc.

References fml::tracing::TraceEventInstant0().

Referenced by FlutterEngineGetProcAddresses().

1687  {
1689 }
void TraceEventInstant0(TraceArg category_group, TraceArg name)
Definition: trace_event.cc:351
const char * name
Definition: fuchsia.cc:50

◆ 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 1548 of file embedder.cc.

References kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and flutter::UnregisterTexture().

Referenced by FlutterEngineGetProcAddresses(), and FlutterEngine::shutDownEngine.

1550  {
1551  if (engine == nullptr) {
1552  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1553  }
1554 
1555  if (texture_identifier == 0) {
1557  "Texture identifier was invalid.");
1558  }
1559 
1560  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->UnregisterTexture(
1561  texture_identifier)) {
1563  "Could not un-register the specified texture.");
1564  }
1565 
1566  return kSuccess;
1567 }
static void UnregisterTexture(JNIEnv *env, jobject jcaller, jlong shell_holder, jlong texture_id)
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ 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 1601 of file embedder.cc.

References kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and flutter::SetAccessibilityFeatures().

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

1603  {
1604  if (engine == nullptr) {
1605  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1606  }
1607  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)
1610  "Could not update accessibility features.");
1611  }
1612  return kSuccess;
1613 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
static void SetAccessibilityFeatures(JNIEnv *env, jobject jcaller, jlong shell_holder, jint flags)
DEF_SWITCHES_START snapshot asset Path to the directory containing the four files specified by VmSnapshotInstructions and IsolateSnapshotInstructions vm snapshot The VM instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present isolate snapshot The isolate instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present icu symbol Prefix for the symbols representing ICU data linked into the Flutter library dart flags
Definition: switches.h:66

◆ 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 1761 of file embedder.cc.

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

1764  {
1765  if (engine == nullptr) {
1766  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1767  }
1768 
1769  if (locales_count == 0) {
1770  return kSuccess;
1771  }
1772 
1773  if (locales == nullptr) {
1774  return LOG_EMBEDDER_ERROR(kInvalidArguments, "No locales were specified.");
1775  }
1776 
1777  rapidjson::Document document;
1778  auto& allocator = document.GetAllocator();
1779 
1780  document.SetObject();
1781  document.AddMember("method", "setLocale", allocator);
1782 
1783  rapidjson::Value args(rapidjson::kArrayType);
1784  args.Reserve(locales_count * 4, allocator);
1785  for (size_t i = 0; i < locales_count; ++i) {
1786  const FlutterLocale* locale = locales[i];
1787  const char* language_code_str = SAFE_ACCESS(locale, language_code, nullptr);
1788  if (language_code_str == nullptr || ::strlen(language_code_str) == 0) {
1789  return LOG_EMBEDDER_ERROR(
1791  "Language code is required but not present in FlutterLocale.");
1792  }
1793 
1794  const char* country_code_str = SAFE_ACCESS(locale, country_code, "");
1795  const char* script_code_str = SAFE_ACCESS(locale, script_code, "");
1796  const char* variant_code_str = SAFE_ACCESS(locale, variant_code, "");
1797 
1798  rapidjson::Value language_code, country_code, script_code, variant_code;
1799 
1800  language_code.SetString(language_code_str, allocator);
1801  country_code.SetString(country_code_str ? country_code_str : "", allocator);
1802  script_code.SetString(script_code_str ? script_code_str : "", allocator);
1803  variant_code.SetString(variant_code_str ? variant_code_str : "", allocator);
1804 
1805  // Required.
1806  args.PushBack(language_code, allocator);
1807  args.PushBack(country_code, allocator);
1808  args.PushBack(script_code, allocator);
1809  args.PushBack(variant_code, allocator);
1810  }
1811  document.AddMember("args", args, allocator);
1812 
1813  return DispatchJSONPlatformMessage(engine, std::move(document),
1814  "flutter/localization")
1815  ? kSuccess
1817  "Could not send message to update locale of "
1818  "a running Flutter application.");
1819 }
G_BEGIN_DECLS FlValue * args
static bool DispatchJSONPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, rapidjson::Document document, const std::string &channel_name)
Definition: embedder.cc:1730
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
#define SAFE_ACCESS(pointer, member, default_value)

◆ 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 FlutterUpdateSemanticsNodeCallback registered to update_semantics_node_callback in FlutterProjectArgs.
Returns
The result of the call.

Definition at line 1587 of file embedder.cc.

References kInternalInconsistency, kInvalidArguments, kSuccess, LOG_EMBEDDER_ERROR, and flutter::SetSemanticsEnabled().

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

1589  {
1590  if (engine == nullptr) {
1591  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1592  }
1593  if (!reinterpret_cast<flutter::EmbedderEngine*>(engine)->SetSemanticsEnabled(
1594  enabled)) {
1596  "Could not update semantics state.");
1597  }
1598  return kSuccess;
1599 }
static void SetSemanticsEnabled(JNIEnv *env, jobject jcaller, jlong shell_holder, jboolean enabled)
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ 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 1448 of file embedder.cc.

Referenced by fl_engine_send_platform_message(), FlutterDesktopMessengerSendWithReply(), FlutterEngineGetProcAddresses(), FlutterEngine::shutDownEngine, and flutter::testing::TEST_F().

1452  {
1453  if (engine == nullptr) {
1454  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Engine handle was invalid.");
1455  }
1456 
1457  if (data_callback == nullptr || response_out == nullptr) {
1458  return LOG_EMBEDDER_ERROR(
1459  kInvalidArguments, "Data callback or the response handle was invalid.");
1460  }
1461 
1463  [user_data, data_callback](const uint8_t* data, size_t size) {
1464  data_callback(data, size, user_data);
1465  };
1466 
1467  auto platform_task_runner = reinterpret_cast<flutter::EmbedderEngine*>(engine)
1468  ->GetTaskRunners()
1469  .GetPlatformTaskRunner();
1470 
1471  auto handle = new FlutterPlatformMessageResponseHandle();
1472 
1473  handle->message = fml::MakeRefCounted<flutter::PlatformMessage>(
1474  "", // The channel is empty and unused as the response handle is going
1475  // to referenced directly in the |FlutterEngineSendPlatformMessage|
1476  // with the container message discarded.
1477  fml::MakeRefCounted<flutter::EmbedderPlatformMessageResponse>(
1478  std::move(platform_task_runner), response_callback));
1479  *response_out = handle;
1480  return kSuccess;
1481 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88
std::function< void(const uint8_t *data, size_t size)> Callback
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
G_BEGIN_DECLS FlValue gpointer user_data
struct _FlutterPlatformMessageResponseHandle FlutterPlatformMessageResponseHandle
Definition: embedder.h:561

◆ 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 1483 of file embedder.cc.

Referenced by fl_engine_send_platform_message(), FlutterDesktopMessengerSendWithReply(), FlutterEngineGetProcAddresses(), FlutterEngine::shutDownEngine, and flutter::testing::TEST_F().

1485  {
1486  if (engine == nullptr) {
1487  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid engine handle.");
1488  }
1489 
1490  if (response == nullptr) {
1491  return LOG_EMBEDDER_ERROR(kInvalidArguments, "Invalid response handle.");
1492  }
1493  delete response;
1494  return kSuccess;
1495 }
#define LOG_EMBEDDER_ERROR(code, reason)
Definition: embedder.cc:88

◆ InferExternalViewEmbedderFromArgs()

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

Definition at line 534 of file embedder.cc.

References CreateEmbedderRenderTarget(), FML_LOG, SAFE_ACCESS, TRACE_EVENT0, user_data, and FlutterCompositor::user_data.

Referenced by FlutterEngineInitialize().

534  {
535  if (compositor == nullptr) {
536  return {nullptr, false};
537  }
538 
539  auto c_create_callback =
540  SAFE_ACCESS(compositor, create_backing_store_callback, nullptr);
541  auto c_collect_callback =
542  SAFE_ACCESS(compositor, collect_backing_store_callback, nullptr);
543  auto c_present_callback =
544  SAFE_ACCESS(compositor, present_layers_callback, nullptr);
545 
546  // Make sure the required callbacks are present
547  if (!c_create_callback || !c_collect_callback || !c_present_callback) {
548  FML_LOG(ERROR) << "Required compositor callbacks absent.";
549  return {nullptr, true};
550  }
551 
552  FlutterCompositor captured_compositor = *compositor;
553 
555  create_render_target_callback =
556  [captured_compositor](GrDirectContext* context, const auto& config) {
557  return CreateEmbedderRenderTarget(&captured_compositor, config,
558  context);
559  };
560 
562  [c_present_callback,
563  user_data = compositor->user_data](const auto& layers) {
564  TRACE_EVENT0("flutter", "FlutterCompositorPresentLayers");
565  return c_present_callback(
566  const_cast<const FlutterLayer**>(layers.data()), layers.size(),
567  user_data);
568  };
569 
570  return {std::make_unique<flutter::EmbedderExternalViewEmbedder>(
571  create_render_target_callback, present_callback),
572  false};
573 }
#define TRACE_EVENT0(category_group, name)
Definition: trace_event.h:75
void * user_data
Definition: embedder.h:925
#define FML_LOG(severity)
Definition: logging.h:65
#define SAFE_ACCESS(pointer, member, default_value)
std::function< bool(const std::vector< const FlutterLayer * > &layers)> PresentCallback
G_BEGIN_DECLS FlValue gpointer user_data
static std::unique_ptr< flutter::EmbedderRenderTarget > CreateEmbedderRenderTarget(const FlutterCompositor *compositor, const FlutterBackingStoreConfig &config, GrDirectContext *context)
Definition: embedder.cc:464
std::function< std::unique_ptr< EmbedderRenderTarget >(GrDirectContext *context, const FlutterBackingStoreConfig &config)> CreateRenderTargetCallback

◆ InferOpenGLPlatformViewCreationCallback()

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

Definition at line 155 of file embedder.cc.

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

Referenced by InferPlatformViewCreationCallback().

161  {
162 #ifdef SHELL_ENABLE_GL
163  if (config->type != kOpenGL) {
164  return nullptr;
165  }
166 
167  auto gl_make_current = [ptr = config->open_gl.make_current,
168  user_data]() -> bool { return ptr(user_data); };
169 
170  auto gl_clear_current = [ptr = config->open_gl.clear_current,
171  user_data]() -> bool { return ptr(user_data); };
172 
173  auto gl_present = [present = config->open_gl.present,
174  present_with_info = config->open_gl.present_with_info,
175  user_data](uint32_t fbo_id) -> bool {
176  if (present) {
177  return present(user_data);
178  } else {
179  FlutterPresentInfo present_info = {};
180  present_info.struct_size = sizeof(FlutterPresentInfo);
181  present_info.fbo_id = fbo_id;
182  return present_with_info(user_data, &present_info);
183  }
184  };
185 
186  auto gl_fbo_callback =
187  [fbo_callback = config->open_gl.fbo_callback,
188  fbo_with_frame_info_callback =
190  user_data](flutter::GLFrameInfo gl_frame_info) -> intptr_t {
191  if (fbo_callback) {
192  return fbo_callback(user_data);
193  } else {
194  FlutterFrameInfo frame_info = {};
195  frame_info.struct_size = sizeof(FlutterFrameInfo);
196  frame_info.size = {gl_frame_info.width, gl_frame_info.height};
197  return fbo_with_frame_info_callback(user_data, &frame_info);
198  }
199  };
200 
201  const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
202  std::function<bool()> gl_make_resource_current_callback = nullptr;
203  if (SAFE_ACCESS(open_gl_config, make_resource_current, nullptr) != nullptr) {
204  gl_make_resource_current_callback =
205  [ptr = config->open_gl.make_resource_current, user_data]() {
206  return ptr(user_data);
207  };
208  }
209 
210  std::function<SkMatrix(void)> gl_surface_transformation_callback = nullptr;
211  if (SAFE_ACCESS(open_gl_config, surface_transformation, nullptr) != nullptr) {
212  gl_surface_transformation_callback =
213  [ptr = config->open_gl.surface_transformation, user_data]() {
214  FlutterTransformation transformation = ptr(user_data);
215  return SkMatrix::MakeAll(transformation.scaleX, //
216  transformation.skewX, //
217  transformation.transX, //
218  transformation.skewY, //
219  transformation.scaleY, //
220  transformation.transY, //
221  transformation.pers0, //
222  transformation.pers1, //
223  transformation.pers2 //
224  );
225  };
226 
227  // If there is an external view embedder, ask it to apply the surface
228  // transformation to its surfaces as well.
229  if (external_view_embedder) {
230  external_view_embedder->SetSurfaceTransformationCallback(
231  gl_surface_transformation_callback);
232  }
233  }
234 
235  flutter::GPUSurfaceGLDelegate::GLProcResolver gl_proc_resolver = nullptr;
236  if (SAFE_ACCESS(open_gl_config, gl_proc_resolver, nullptr) != nullptr) {
237  gl_proc_resolver = [ptr = config->open_gl.gl_proc_resolver,
238  user_data](const char* gl_proc_name) {
239  return ptr(user_data, gl_proc_name);
240  };
241  } else {
242 #if OS_LINUX || OS_WIN
243  gl_proc_resolver = DefaultGLProcResolver;
244 #endif
245  }
246 
247  bool fbo_reset_after_present =
248  SAFE_ACCESS(open_gl_config, fbo_reset_after_present, false);
249 
250  flutter::EmbedderSurfaceGL::GLDispatchTable gl_dispatch_table = {
251  gl_make_current, // gl_make_current_callback
252  gl_clear_current, // gl_clear_current_callback
253  gl_present, // gl_present_callback
254  gl_fbo_callback, // gl_fbo_callback
255  gl_make_resource_current_callback, // gl_make_resource_current_callback
256  gl_surface_transformation_callback, // gl_surface_transformation_callback
257  gl_proc_resolver, // gl_proc_resolver
258  };
259 
260  return fml::MakeCopyable(
261  [gl_dispatch_table, fbo_reset_after_present, platform_dispatch_table,
262  external_view_embedder =
263  std::move(external_view_embedder)](flutter::Shell& shell) mutable {
264  return std::make_unique<flutter::PlatformViewEmbedder>(
265  shell, // delegate
266  shell.GetTaskRunners(), // task runners
267  gl_dispatch_table, // embedder GL dispatch table
268  fbo_reset_after_present, // fbo reset after present
269  platform_dispatch_table, // embedder platform dispatch table
270  std::move(external_view_embedder) // external view embedder
271  );
272  });
273 #else
274  return nullptr;
275 #endif
276 }
double skewY
vertical skew factor
Definition: embedder.h:230
uint32_t fbo_id
Id of the fbo backing the surface that was presented.
Definition: embedder.h:369
TransformationCallback surface_transformation
Definition: embedder.h:414
double skewX
horizontal skew factor
Definition: embedder.h:226
double pers1
input y-axis perspective factor
Definition: embedder.h:238
double pers2
perspective scale factor
Definition: embedder.h:240
uint32_t width
Definition: embedder.h:319
const TaskRunners & GetTaskRunners() const override
If callers wish to interact directly with any shell subcomponents, they must (on the platform thread)...
Definition: shell.cc:583
double pers0
input x-axis perspective factor
Definition: embedder.h:236
BoolPresentInfoCallback present_with_info
Definition: embedder.h:434
UIntFrameInfoCallback fbo_with_frame_info_callback
Definition: embedder.h:428
std::function< void *(const char *)> GLProcResolver
#define SAFE_ACCESS(pointer, member, default_value)
double scaleY
vertical scale factor
Definition: embedder.h:232
FlutterUIntSize size
The size of the surface that will be backed by the fbo.
Definition: embedder.h:354
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57
G_BEGIN_DECLS FlValue gpointer user_data
size_t struct_size
The size of this struct. Must be sizeof(FlutterFrameInfo).
Definition: embedder.h:352
FlutterRendererType type
Definition: embedder.h:448
double transX
horizontal translation
Definition: embedder.h:228
BoolCallback make_resource_current
Definition: embedder.h:398
BoolCallback clear_current
Definition: embedder.h:381
BoolCallback make_current
Definition: embedder.h:380
FlutterOpenGLRendererConfig open_gl
Definition: embedder.h:450
size_t struct_size
The size of this struct. Must be sizeof(FlutterFrameInfo).
Definition: embedder.h:367
UIntCallback fbo_callback
Definition: embedder.h:391
double transY
vertical translation
Definition: embedder.h:234
ProcResolver gl_proc_resolver
Definition: embedder.h:415
double scaleX
horizontal scale factor
Definition: embedder.h:224

◆ InferPlatformViewCreationCallback()

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

Definition at line 316 of file embedder.cc.

References InferOpenGLPlatformViewCreationCallback(), InferSoftwarePlatformViewCreationCallback(), kOpenGL, kSoftware, and FlutterRendererConfig::type.

Referenced by FlutterEngineInitialize().

322  {
323  if (config == nullptr) {
324  return nullptr;
325  }
326 
327  switch (config->type) {
328  case kOpenGL:
330  config, user_data, platform_dispatch_table,
331  std::move(external_view_embedder));
332  case kSoftware:
334  config, user_data, platform_dispatch_table,
335  std::move(external_view_embedder));
336  default:
337  return nullptr;
338  }
339  return nullptr;
340 }
static flutter::Shell::CreateCallback< flutter::PlatformView > InferSoftwarePlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder)
Definition: embedder.cc:279
G_BEGIN_DECLS FlValue gpointer user_data
FlutterRendererType type
Definition: embedder.h:448
static flutter::Shell::CreateCallback< flutter::PlatformView > InferOpenGLPlatformViewCreationCallback(const FlutterRendererConfig *config, void *user_data, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr< flutter::EmbedderExternalViewEmbedder > external_view_embedder)
Definition: embedder.cc:155

◆ InferSoftwarePlatformViewCreationCallback()

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

Definition at line 279 of file embedder.cc.

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

Referenced by InferPlatformViewCreationCallback().

285  {
286  if (config->type != kSoftware) {
287  return nullptr;
288  }
289 
290  auto software_present_backing_store =
292  const void* allocation, size_t row_bytes, size_t height) -> bool {
293  return ptr(user_data, allocation, row_bytes, height);
294  };
295 
297  software_dispatch_table = {
298  software_present_backing_store, // required
299  };
300 
301  return fml::MakeCopyable(
302  [software_dispatch_table, platform_dispatch_table,
303  external_view_embedder =
304  std::move(external_view_embedder)](flutter::Shell& shell) mutable {
305  return std::make_unique<flutter::PlatformViewEmbedder>(
306  shell, // delegate
307  shell.GetTaskRunners(), // task runners
308  software_dispatch_table, // software dispatch table
309  platform_dispatch_table, // platform dispatch table
310  std::move(external_view_embedder) // external view embedder
311  );
312  });
313 }
FlutterSoftwareRendererConfig software
Definition: embedder.h:451
const TaskRunners & GetTaskRunners() const override
If callers wish to interact directly with any shell subcomponents, they must (on the platform thread)...
Definition: shell.cc:583
internal::CopyableLambda< T > MakeCopyable(T lambda)
Definition: make_copyable.h:57
G_BEGIN_DECLS FlValue gpointer user_data
FlutterRendererType type
Definition: embedder.h:448
int32_t height
SoftwareSurfacePresentCallback surface_present_callback
Definition: embedder.h:444

◆ IsOpenGLRendererConfigValid()

static bool IsOpenGLRendererConfigValid ( const FlutterRendererConfig config)
static

Definition at line 91 of file embedder.cc.

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

Referenced by IsRendererValid().

91  {
92  if (config->type != kOpenGL) {
93  return false;
94  }
95 
96  const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
97 
98  if (!SAFE_EXISTS(open_gl_config, make_current) ||
99  !SAFE_EXISTS(open_gl_config, clear_current) ||
100  !SAFE_EXISTS_ONE_OF(open_gl_config, fbo_callback,
101  fbo_with_frame_info_callback) ||
102  !SAFE_EXISTS_ONE_OF(open_gl_config, present, present_with_info)) {
103  return false;
104  }
105 
106  return true;
107 }
FlutterRendererType type
Definition: embedder.h:448
FlutterOpenGLRendererConfig open_gl
Definition: embedder.h:450
#define SAFE_EXISTS(pointer, member)
Checks if the member exists and is non-null.
#define SAFE_EXISTS_ONE_OF(pointer, member1, member2)
Checks if exactly one of member1 or member2 exists and is non-null.

◆ IsRendererValid()

static bool IsRendererValid ( const FlutterRendererConfig config)
static

Definition at line 124 of file embedder.cc.

References fml::NativeLibrary::Create(), fml::NativeLibrary::CreateForCurrentProcess(), IsOpenGLRendererConfigValid(), IsSoftwareRendererConfigValid(), kOpenGL, kSoftware, name, fml::NativeLibrary::ResolveSymbol(), and FlutterRendererConfig::type.

Referenced by FlutterEngineInitialize().

124  {
125  if (config == nullptr) {
126  return false;
127  }
128 
129  switch (config->type) {
130  case kOpenGL:
131  return IsOpenGLRendererConfigValid(config);
132  case kSoftware:
133  return IsSoftwareRendererConfigValid(config);
134  default:
135  return false;
136  }
137 
138  return false;
139 }
static bool IsSoftwareRendererConfigValid(const FlutterRendererConfig *config)
Definition: embedder.cc:109
FlutterRendererType type
Definition: embedder.h:448
static bool IsOpenGLRendererConfigValid(const FlutterRendererConfig *config)
Definition: embedder.cc:91

◆ IsSoftwareRendererConfigValid()

static bool IsSoftwareRendererConfigValid ( const FlutterRendererConfig config)
static

Definition at line 109 of file embedder.cc.

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

Referenced by IsRendererValid().

109  {
110  if (config->type != kSoftware) {
111  return false;
112  }
113 
114  const FlutterSoftwareRendererConfig* software_config = &config->software;
115 
116  if (SAFE_ACCESS(software_config, surface_present_callback, nullptr) ==
117  nullptr) {
118  return false;
119  }
120 
121  return true;
122 }
FlutterSoftwareRendererConfig software
Definition: embedder.h:451
#define SAFE_ACCESS(pointer, member, default_value)
FlutterRendererType type
Definition: embedder.h:448

◆ 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 67 of file embedder.cc.

References error.

72  {
73 #if OS_WIN
74  constexpr char kSeparator = '\\';
75 #else
76  constexpr char kSeparator = '/';
77 #endif
78  const auto file_base =
79  (::strrchr(file, kSeparator) ? strrchr(file, kSeparator) + 1 : file);
80  char error[256] = {};
81  snprintf(error, (sizeof(error) / sizeof(char)),
82  "%s (%d): '%s' returned '%s'. %s", file_base, line, function,
83  code_name, reason);
84  std::cerr << error << std::endl;
85  return code;
86 }
FlMethodResponse GError ** error

◆ MakeSkSurfaceFromBackingStore() [1/3]

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

Definition at line 342 of file embedder.cc.

References FlutterOpenGLTexture::destruction_callback, FML_LOG, FlutterOpenGLTexture::format, FlutterSize::height, FlutterOpenGLTexture::name, FlutterBackingStoreConfig::size, FlutterOpenGLTexture::target, FlutterOpenGLTexture::user_data, and FlutterSize::width.

Referenced by CreateEmbedderRenderTarget().

345  {
346 #ifdef SHELL_ENABLE_GL
347  GrGLTextureInfo texture_info;
348  texture_info.fTarget = texture->target;
349  texture_info.fID = texture->name;
350  texture_info.fFormat = texture->format;
351 
352  GrBackendTexture backend_texture(config.size.width, //
353  config.size.height, //
354  GrMipMapped::kNo, //
355  texture_info //
356  );
357 
358  SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
359 
360  auto surface = SkSurface::MakeFromBackendTexture(
361  context, // context
362  backend_texture, // back-end texture
363  kBottomLeft_GrSurfaceOrigin, // surface origin
364  1, // sample count
365  kN32_SkColorType, // color type
366  SkColorSpace::MakeSRGB(), // color space
367  &surface_properties, // surface properties
368  static_cast<SkSurface::TextureReleaseProc>(
369  texture->destruction_callback), // release proc
370  texture->user_data // release context
371  );
372 
373  if (!surface) {
374  FML_LOG(ERROR) << "Could not wrap embedder supplied render texture.";
375  texture->destruction_callback(texture->user_data);
376  return nullptr;
377  }
378 
379  return surface;
380 #else
381  return nullptr;
382 #endif
383 }
#define FML_LOG(severity)
Definition: logging.h:65
VoidCallback destruction_callback
Definition: embedder.h:266
double width
Definition: embedder.h:311
double height
Definition: embedder.h:312
uint32_t name
The name of the texture.
Definition: embedder.h:259
FlutterSize size
The size of the render target the engine expects to render into.
Definition: embedder.h:873
void * user_data
User data to be returned on the invocation of the destruction callback.
Definition: embedder.h:263
uint32_t format
The texture format (example GL_RGBA8).
Definition: embedder.h:261

◆ MakeSkSurfaceFromBackingStore() [2/3]

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

Definition at line 385 of file embedder.cc.

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

388  {
389 #ifdef SHELL_ENABLE_GL
390  GrGLFramebufferInfo framebuffer_info = {};
391  framebuffer_info.fFormat = framebuffer->target;
392  framebuffer_info.fFBOID = framebuffer->name;
393 
394  GrBackendRenderTarget backend_render_target(
395  config.size.width, // width
396  config.size.height, // height
397  1, // sample count
398  0, // stencil bits
399  framebuffer_info // framebuffer info
400  );
401 
402  SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry);
403 
404  auto surface = SkSurface::MakeFromBackendRenderTarget(
405  context, // context
406  backend_render_target, // backend render target
407  kBottomLeft_GrSurfaceOrigin, // surface origin
408  kN32_SkColorType, // color type
409  SkColorSpace::MakeSRGB(), // color space
410  &surface_properties, // surface properties
411  static_cast<SkSurface::RenderTargetReleaseProc>(
412  framebuffer->destruction_callback), // release proc
413  framebuffer->user_data // release context
414  );
415 
416  if (!surface) {
417  FML_LOG(ERROR) << "Could not wrap embedder supplied frame-buffer.";
418  framebuffer->destruction_callback(framebuffer->user_data);
419  return nullptr;
420  }
421  return surface;
422 #else
423  return nullptr;
424 #endif
425 }
#define FML_LOG(severity)
Definition: logging.h:65
VoidCallback destruction_callback
Definition: embedder.h:291
double width
Definition: embedder.h:311
double height
Definition: embedder.h:312
FlutterSize size
The size of the render target the engine expects to render into.
Definition: embedder.h:873
void * user_data
User data to be returned on the invocation of the destruction callback.
Definition: embedder.h:287
uint32_t name
The name of the framebuffer.
Definition: embedder.h:284

◆ MakeSkSurfaceFromBackingStore() [3/3]

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

Definition at line 427 of file embedder.cc.

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

430  {
431  const auto image_info =
432  SkImageInfo::MakeN32Premul(config.size.width, config.size.height);
433 
434  struct Captures {
435  VoidCallback destruction_callback;
436  void* user_data;
437  };
438  auto captures = std::make_unique<Captures>();
439  captures->destruction_callback = software->destruction_callback;
440  captures->user_data = software->user_data;
441  auto release_proc = [](void* pixels, void* context) {
442  auto captures = reinterpret_cast<Captures*>(context);
443  captures->destruction_callback(captures->user_data);
444  };
445 
446  auto surface = SkSurface::MakeRasterDirectReleaseProc(
447  image_info, // image info
448  const_cast<void*>(software->allocation), // pixels
449  software->row_bytes, // row bytes
450  release_proc, // release proc
451  captures.release() // release context
452  );
453 
454  if (!surface) {
455  FML_LOG(ERROR)
456  << "Could not wrap embedder supplied software render buffer.";
457  software->destruction_callback(software->user_data);
458  return nullptr;
459  }
460  return surface;
461 }
#define FML_LOG(severity)
Definition: logging.h:65
VoidCallback destruction_callback
Definition: embedder.h:787
G_BEGIN_DECLS FlValue gpointer user_data
size_t row_bytes
The number of bytes in a single row of the allocation.
Definition: embedder.h:778
double width
Definition: embedder.h:311
double height
Definition: embedder.h:312
void(* VoidCallback)(void *)
Definition: embedder.h:243
FlutterSize size
The size of the render target the engine expects to render into.
Definition: embedder.h:873

◆ PointerDataButtonsForLegacyEvent()

◆ PopulateSnapshotMappingCallbacks()

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

Definition at line 662 of file embedder.cc.

References FlutterProjectArgs::aot_data, flutter::Settings::dart_library_sources_kernel, flutter::Settings::isolate_snapshot_data, FlutterProjectArgs::isolate_snapshot_data, flutter::Settings::isolate_snapshot_instr, FlutterProjectArgs::isolate_snapshot_instructions, flutter::DartVM::IsRunningPrecompiledCode(), kPlatformStrongDill, kPlatformStrongDillSize, SAFE_ACCESS, fml::size(), _FlutterEngineAOTData::vm_isolate_data, _FlutterEngineAOTData::vm_isolate_instrs, flutter::Settings::vm_snapshot_data, _FlutterEngineAOTData::vm_snapshot_data, FlutterProjectArgs::vm_snapshot_data, flutter::Settings::vm_snapshot_instr, _FlutterEngineAOTData::vm_snapshot_instrs, and FlutterProjectArgs::vm_snapshot_instructions.

Referenced by FlutterEngineInitialize().

664  { // NOLINT(google-runtime-references)
665  // There are no ownership concerns here as all mappings are owned by the
666  // embedder and not the engine.
667  auto make_mapping_callback = [](const uint8_t* mapping, size_t size) {
668  return [mapping, size]() {
669  return std::make_unique<fml::NonOwnedMapping>(mapping, size);
670  };
671  };
672 
674  if (SAFE_ACCESS(args, aot_data, nullptr) != nullptr) {
675  settings.vm_snapshot_data =
676  make_mapping_callback(args->aot_data->vm_snapshot_data, 0);
677 
678  settings.vm_snapshot_instr =
679  make_mapping_callback(args->aot_data->vm_snapshot_instrs, 0);
680 
681  settings.isolate_snapshot_data =
682  make_mapping_callback(args->aot_data->vm_isolate_data, 0);
683 
684  settings.isolate_snapshot_instr =
685  make_mapping_callback(args->aot_data->vm_isolate_instrs, 0);
686  }
687 
688  if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) {
689  settings.vm_snapshot_data = make_mapping_callback(
690  args->vm_snapshot_data, SAFE_ACCESS(args, vm_snapshot_data_size, 0));
691  }
692 
693  if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) {
694  settings.vm_snapshot_instr = make_mapping_callback(
696  SAFE_ACCESS(args, vm_snapshot_instructions_size, 0));
697  }
698 
699  if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) {
700  settings.isolate_snapshot_data = make_mapping_callback(
701  args->isolate_snapshot_data,
702  SAFE_ACCESS(args, isolate_snapshot_data_size, 0));
703  }
704 
705  if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) {
706  settings.isolate_snapshot_instr = make_mapping_callback(
708  SAFE_ACCESS(args, isolate_snapshot_instructions_size, 0));
709  }
710  }
711 
712 #if !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
713  settings.dart_library_sources_kernel =
714  make_mapping_callback(kPlatformStrongDill, kPlatformStrongDillSize);
715 #endif // !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG)
716 }
MappingCallback isolate_snapshot_instr
Definition: settings.h:80
const uint8_t * isolate_snapshot_data
Definition: embedder.h:1195
const uint8_t kPlatformStrongDill[]
const uint8_t * vm_isolate_data
Definition: embedder.cc:593
const intptr_t kPlatformStrongDillSize
MappingCallback vm_snapshot_data
Definition: settings.h:73
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
#define SAFE_ACCESS(pointer, member, default_value)
const uint8_t * vm_snapshot_instrs
Definition: embedder.cc:592
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:199
const uint8_t * vm_snapshot_data
Definition: embedder.h:1179
const uint8_t * vm_snapshot_instructions
Definition: embedder.h:1187
MappingCallback isolate_snapshot_data
Definition: settings.h:78
const uint8_t * vm_isolate_instrs
Definition: embedder.cc:594
MappingCallback dart_library_sources_kernel
Definition: settings.h:84
MappingCallback vm_snapshot_instr
Definition: settings.h:75
FlutterEngineAOTData aot_data
Definition: embedder.h:1315
const uint8_t * isolate_snapshot_instructions
Definition: embedder.h:1203
const uint8_t * vm_snapshot_data
Definition: embedder.cc:591

◆ ToPointerDataChange()

flutter::PointerData::Change ToPointerDataChange ( FlutterPointerPhase  phase)
inline

Definition at line 1256 of file embedder.cc.

References flutter::PointerData::kAdd, kAdd, flutter::PointerData::kCancel, kCancel, flutter::PointerData::kDown, kDown, flutter::PointerData::kHover, kHover, flutter::PointerData::kMove, kMove, flutter::PointerData::kRemove, kRemove, flutter::PointerData::kUp, and kUp.

Referenced by FlutterEngineSendPointerEvent().

◆ ToPointerDataKind()

◆ ToPointerDataSignalKind()

Variable Documentation

◆ kFlutterSemanticsCustomActionIdBatchEnd

const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1

FlutterSemanticsCustomAction ID used as a sentinel to signal the end of a batch of semantics custom action updates.

Definition at line 65 of file embedder.cc.

Referenced by FlutterEngineInitialize(), 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.

Definition at line 64 of file embedder.cc.

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

◆ kPlatformStrongDill

const uint8_t kPlatformStrongDill[]

◆ kPlatformStrongDillSize

const intptr_t kPlatformStrongDillSize