embedder.cc 13.5 KB
Newer Older
1 2 3 4
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7 8 9 10 11
#define FML_USED_ON_EMBEDDER

#include "lib/fxl/build_config.h"

#if OS_WIN
#define FLUTTER_EXPORT __declspec(dllexport)
#else  // OS_WIN
12
#define FLUTTER_EXPORT __attribute__((visibility("default")))
13
#endif  // OS_WIN
14 15

#include "flutter/shell/platform/embedder/embedder.h"
16

17
#include <type_traits>
18 19 20 21

#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/common/task_runners.h"
#include "flutter/fml/file.h"
22
#include "flutter/fml/message_loop.h"
23
#include "flutter/fml/paths.h"
24 25 26 27
#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"
28
#include "flutter/shell/platform/embedder/platform_view_embedder.h"
29
#include "lib/fxl/command_line.h"
30
#include "lib/fxl/files/file.h"
31
#include "lib/fxl/functional/make_copyable.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

#define SAFE_ACCESS(pointer, member, default_value)                      \
  ({                                                                     \
    auto _return_value =                                                 \
        static_cast<__typeof__(pointer->member)>((default_value));       \
    if (offsetof(std::remove_pointer<decltype(pointer)>::type, member) + \
            sizeof(pointer->member) <=                                   \
        pointer->struct_size) {                                          \
      _return_value = pointer->member;                                   \
    }                                                                    \
    _return_value;                                                       \
  })

bool IsRendererValid(const FlutterRendererConfig* config) {
  if (config == nullptr || config->type != kOpenGL) {
    return false;
  }

  const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;

  if (SAFE_ACCESS(open_gl_config, make_current, nullptr) == nullptr ||
      SAFE_ACCESS(open_gl_config, clear_current, nullptr) == nullptr ||
      SAFE_ACCESS(open_gl_config, present, nullptr) == nullptr ||
      SAFE_ACCESS(open_gl_config, fbo_callback, nullptr) == nullptr) {
    return false;
  }

  return true;
}

62 63 64 65
struct _FlutterPlatformMessageResponseHandle {
  fxl::RefPtr<blink::PlatformMessage> message;
};

66 67 68 69 70
FlutterResult FlutterEngineRun(size_t version,
                               const FlutterRendererConfig* config,
                               const FlutterProjectArgs* args,
                               void* user_data,
                               FlutterEngine* engine_out) {
71
  // Step 0: Figure out arguments for shell creation.
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  if (version != FLUTTER_ENGINE_VERSION) {
    return kInvalidLibraryVersion;
  }

  if (engine_out == nullptr) {
    return kInvalidArguments;
  }

  if (args == nullptr) {
    return kInvalidArguments;
  }

  if (SAFE_ACCESS(args, assets_path, nullptr) == nullptr ||
      SAFE_ACCESS(args, main_path, nullptr) == nullptr ||
      SAFE_ACCESS(args, packages_path, nullptr) == nullptr) {
    return kInvalidArguments;
  }

  if (!IsRendererValid(config)) {
    return kInvalidArguments;
  }

94 95
  auto make_current = [ptr = config->open_gl.make_current,
                       user_data]() -> bool { return ptr(user_data); };
96

97 98
  auto clear_current = [ptr = config->open_gl.clear_current,
                        user_data]() -> bool { return ptr(user_data); };
99

100
  auto present = [ptr = config->open_gl.present, user_data]() -> bool {
101 102 103
    return ptr(user_data);
  };

104 105
  auto fbo_callback = [ptr = config->open_gl.fbo_callback,
                       user_data]() -> intptr_t { return ptr(user_data); };
106

107 108 109 110
  shell::PlatformViewEmbedder::PlatformMessageResponseCallback
      platform_message_response_callback = nullptr;
  if (SAFE_ACCESS(args, platform_message_callback, nullptr) != nullptr) {
    platform_message_response_callback =
111 112 113 114 115 116 117 118 119 120 121 122 123
        [ptr = args->platform_message_callback,
         user_data](fxl::RefPtr<blink::PlatformMessage> message) {
          auto handle = new FlutterPlatformMessageResponseHandle();
          const FlutterPlatformMessage incoming_message = {
              .struct_size = sizeof(FlutterPlatformMessage),
              .channel = message->channel().c_str(),
              .message = message->data().data(),
              .message_size = message->data().size(),
              .response_handle = handle,
          };
          handle->message = std::move(message);
          return ptr(&incoming_message, user_data);
        };
124 125
  }

126 127 128
  const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl;
  std::function<bool()> make_resource_current_callback = nullptr;
  if (SAFE_ACCESS(open_gl_config, make_resource_current, nullptr) != nullptr) {
129 130 131
    make_resource_current_callback = [ptr =
                                          config->open_gl.make_resource_current,
                                      user_data]() { return ptr(user_data); };
132 133
  }

134 135 136 137 138 139 140 141 142 143 144 145 146
  std::string icu_data_path;
  if (SAFE_ACCESS(args, icu_data_path, nullptr) != nullptr) {
    icu_data_path = SAFE_ACCESS(args, icu_data_path, nullptr);
  }

  fxl::CommandLine command_line;
  if (SAFE_ACCESS(args, command_line_argc, 0) != 0 &&
      SAFE_ACCESS(args, command_line_argv, nullptr) != nullptr) {
    command_line = fxl::CommandLineFromArgcArgv(
        SAFE_ACCESS(args, command_line_argc, 0),
        SAFE_ACCESS(args, command_line_argv, nullptr));
  }

147 148 149
  blink::Settings settings = shell::SettingsFromCommandLine(command_line);
  settings.icu_data_path = icu_data_path;
  settings.assets_path = args->assets_path;
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

  // Check whether the assets path contains Dart 2 kernel assets.
  const std::string kApplicationKernelSnapshotFileName = "kernel_blob.bin";
  std::string platform_kernel_path =
      fml::paths::JoinPaths({settings.assets_path, "platform.dill"});
  std::string application_kernel_path = fml::paths::JoinPaths(
      {settings.assets_path, kApplicationKernelSnapshotFileName});
  if (files::IsFile(platform_kernel_path) &&
      files::IsFile(application_kernel_path)) {
    // Run from a kernel snapshot.
    settings.application_kernel_asset = kApplicationKernelSnapshotFileName;
    settings.kernel_snapshot_path = platform_kernel_path;
  } else {
    // Run from a main Dart file.
    settings.main_dart_file_path = args->main_path;
    settings.packages_file_path = args->packages_path;
  }

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
  settings.task_observer_add = [](intptr_t key, fxl::Closure callback) {
    fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));
  };
  settings.task_observer_remove = [](intptr_t key) {
    fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
  };

  // Create a thread host with the current thread as the platform thread and all
  // other threads managed.
  shell::ThreadHost thread_host("io.flutter", shell::ThreadHost::Type::GPU |
                                                  shell::ThreadHost::Type::IO |
                                                  shell::ThreadHost::Type::UI);
  fml::MessageLoop::EnsureInitializedForCurrentThread();
  blink::TaskRunners task_runners(
      "io.flutter",
      fml::MessageLoop::GetCurrent().GetTaskRunner(),  // platform
      thread_host.gpu_thread->GetTaskRunner(),         // gpu
      thread_host.ui_thread->GetTaskRunner(),          // ui
      thread_host.io_thread->GetTaskRunner()           // io
  );

  shell::PlatformViewEmbedder::DispatchTable dispatch_table = {
190 191 192
      .gl_make_current_callback = make_current,
      .gl_clear_current_callback = clear_current,
      .gl_present_callback = present,
193 194
      .gl_fbo_callback = fbo_callback,
      .platform_message_response_callback = platform_message_response_callback,
195
      .gl_make_resource_current_callback = make_resource_current_callback,
196
  };
197

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  shell::Shell::CreateCallback<shell::PlatformView> on_create_platform_view =
      [dispatch_table](shell::Shell& shell) {
        return std::make_unique<shell::PlatformViewEmbedder>(
            shell,                   // delegate
            shell.GetTaskRunners(),  // task runners
            dispatch_table           // embedder dispatch table
        );
      };

  shell::Shell::CreateCallback<shell::Rasterizer> on_create_rasterizer =
      [](shell::Shell& shell) {
        return std::make_unique<shell::Rasterizer>(shell.GetTaskRunners());
      };

  // Step 1: Create the engine.
  auto embedder_engine =
      std::make_unique<shell::EmbedderEngine>(std::move(thread_host),   //
                                              std::move(task_runners),  //
                                              settings,                 //
                                              on_create_platform_view,  //
                                              on_create_rasterizer      //
      );

  if (!embedder_engine->IsValid()) {
    return kInvalidArguments;
  }

  // Step 2: Setup the rendering surface.
  if (!embedder_engine->NotifyCreated()) {
    return kInvalidArguments;
  }

  // Step 3: Run the engine.
  auto run_configuration = shell::RunConfiguration::InferFromSettings(settings);

  run_configuration.AddAssetResolver(
      std::make_unique<blink::DirectoryAssetBundle>(
          fml::Duplicate(settings.assets_dir)));
236

237 238 239 240 241 242 243 244 245 246
  run_configuration.AddAssetResolver(
      std::make_unique<blink::DirectoryAssetBundle>(fml::OpenFile(
          settings.assets_path.c_str(), fml::OpenPermission::kRead, true)));

  if (!embedder_engine->Run(std::move(run_configuration))) {
    return kInvalidArguments;
  }

  // Finally! Release the ownership of the embedder engine to the caller.
  *engine_out = reinterpret_cast<FlutterEngine>(embedder_engine.release());
247 248 249 250 251 252 253
  return kSuccess;
}

FlutterResult FlutterEngineShutdown(FlutterEngine engine) {
  if (engine == nullptr) {
    return kInvalidArguments;
  }
254 255 256
  auto embedder_engine = reinterpret_cast<shell::EmbedderEngine*>(engine);
  embedder_engine->NotifyDestroyed();
  delete embedder_engine;
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  return kSuccess;
}

FlutterResult FlutterEngineSendWindowMetricsEvent(
    FlutterEngine engine,
    const FlutterWindowMetricsEvent* flutter_metrics) {
  if (engine == nullptr || flutter_metrics == nullptr) {
    return kInvalidArguments;
  }

  blink::ViewportMetrics metrics;

  metrics.physical_width = SAFE_ACCESS(flutter_metrics, width, 0.0);
  metrics.physical_height = SAFE_ACCESS(flutter_metrics, height, 0.0);
  metrics.device_pixel_ratio = SAFE_ACCESS(flutter_metrics, pixel_ratio, 1.0);

273 274 275 276
  return reinterpret_cast<shell::EmbedderEngine*>(engine)->SetViewportMetrics(
             std::move(metrics))
             ? kSuccess
             : kInvalidArguments;
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
}

inline blink::PointerData::Change ToPointerDataChange(
    FlutterPointerPhase phase) {
  switch (phase) {
    case kCancel:
      return blink::PointerData::Change::kCancel;
    case kUp:
      return blink::PointerData::Change::kUp;
    case kDown:
      return blink::PointerData::Change::kDown;
    case kMove:
      return blink::PointerData::Change::kMove;
  }
  return blink::PointerData::Change::kCancel;
}

FlutterResult FlutterEngineSendPointerEvent(FlutterEngine engine,
                                            const FlutterPointerEvent* pointers,
                                            size_t events_count) {
  if (engine == nullptr || pointers == nullptr || events_count == 0) {
    return kInvalidArguments;
  }

  auto packet = std::make_unique<blink::PointerDataPacket>(events_count);

  const FlutterPointerEvent* current = pointers;

  for (size_t i = 0; i < events_count; ++i) {
    blink::PointerData pointer_data;
    pointer_data.Clear();
    pointer_data.time_stamp = SAFE_ACCESS(current, timestamp, 0);
    pointer_data.change = ToPointerDataChange(
        SAFE_ACCESS(current, phase, FlutterPointerPhase::kCancel));
    pointer_data.kind = blink::PointerData::DeviceKind::kMouse;
    pointer_data.physical_x = SAFE_ACCESS(current, x, 0.0);
    pointer_data.physical_y = SAFE_ACCESS(current, y, 0.0);
    packet->SetPointerData(i, pointer_data);
    current = reinterpret_cast<const FlutterPointerEvent*>(
        reinterpret_cast<const uint8_t*>(current) + current->struct_size);
  }

319 320 321 322
  return reinterpret_cast<shell::EmbedderEngine*>(engine)
                 ->DispatchPointerDataPacket(std::move(packet))
             ? kSuccess
             : kInvalidArguments;
323
}
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

FlutterResult FlutterEngineSendPlatformMessage(
    FlutterEngine engine,
    const FlutterPlatformMessage* flutter_message) {
  if (engine == nullptr || flutter_message == nullptr) {
    return kInvalidArguments;
  }

  if (SAFE_ACCESS(flutter_message, channel, nullptr) == nullptr ||
      SAFE_ACCESS(flutter_message, message, nullptr) == nullptr) {
    return kInvalidArguments;
  }

  auto message = fxl::MakeRefCounted<blink::PlatformMessage>(
      flutter_message->channel,
      std::vector<uint8_t>(
          flutter_message->message,
          flutter_message->message + flutter_message->message_size),
      nullptr);

344 345 346 347
  return reinterpret_cast<shell::EmbedderEngine*>(engine)->SendPlatformMessage(
             std::move(message))
             ? kSuccess
             : kInvalidArguments;
348
}
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

FlutterResult FlutterEngineSendPlatformMessageResponse(
    FlutterEngine engine,
    const FlutterPlatformMessageResponseHandle* handle,
    const uint8_t* data,
    size_t data_length) {
  if (data_length != 0 && data == nullptr) {
    return kInvalidArguments;
  }

  auto response = handle->message->response();

  if (data_length == 0) {
    response->CompleteEmpty();
  } else {
    response->Complete({data, data + data_length});
  }

  delete handle;

  return kSuccess;
}
371 372 373 374 375

FlutterResult __FlutterEngineFlushPendingTasksNow() {
  fml::MessageLoop::GetCurrent().RunExpiredTasksNow();
  return kSuccess;
}