engine.cc 22.5 KB
Newer Older
1 2 3 4
// Copyright 2015 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
#include "flutter/shell/common/engine.h"
6

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#if OS(WIN)
#include <io.h>
#include <windows.h>
#define access _access
#define R_OK 0x4

#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)
#endif

#ifndef S_ISREG
#define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG)
#endif

#else
#include <dlfcn.h>
#include <sys/mman.h>
#include <unistd.h>
#endif  // OS(WIN)

#include <fcntl.h>
#include <sys/stat.h>
29
#include <memory>
30 31
#include <utility>

32 33 34 35
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/assets/unzipper_provider.h"
#include "flutter/assets/zip_asset_store.h"
#include "flutter/assets/asset_provider.h"
36
#include "flutter/common/settings.h"
37
#include "flutter/common/threads.h"
38
#include "flutter/glue/trace_event.h"
R
Ryan Macnak 已提交
39
#include "flutter/lib/snapshot/snapshot.h"
40
#include "flutter/lib/ui/text/font_collection.h"
41
#include "flutter/runtime/asset_font_selector.h"
42 43 44
#include "flutter/runtime/dart_controller.h"
#include "flutter/runtime/dart_init.h"
#include "flutter/runtime/runtime_init.h"
45
#include "flutter/runtime/test_font_selector.h"
46
#include "flutter/shell/common/animator.h"
47
#include "flutter/shell/common/platform_view.h"
48
#include "flutter/sky/engine/public/web/Sky.h"
49 50 51 52 53
#include "lib/fxl/files/eintr_wrapper.h"
#include "lib/fxl/files/file.h"
#include "lib/fxl/files/path.h"
#include "lib/fxl/files/unique_fd.h"
#include "lib/fxl/functional/make_copyable.h"
54
#include "third_party/rapidjson/rapidjson/document.h"
A
Adam Barth 已提交
55 56
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
namespace shell {
namespace {

constexpr char kAssetChannel[] = "flutter/assets";
constexpr char kLifecycleChannel[] = "flutter/lifecycle";
constexpr char kNavigationChannel[] = "flutter/navigation";
constexpr char kLocalizationChannel[] = "flutter/localization";
constexpr char kSettingsChannel[] = "flutter/settings";

#if OS(WIN)
void FindAndReplaceInPlace(std::string& str,
                           const std::string& findStr,
                           const std::string& replaceStr) {
  size_t pos = 0;
  while ((pos = str.find(findStr, pos)) != std::string::npos) {
    str.replace(pos, findStr.length(), replaceStr);
    pos += replaceStr.length();
  }
}
77
#endif
78

79 80 81 82 83 84 85 86 87 88 89 90 91
std::string SanitizePath(const std::string& path) {
#if OS(WIN)
  std::string sanitized = path;
  FindAndReplaceInPlace(sanitized, "\\\\", "/");
  if ((sanitized.length() > 2) && (sanitized[1] == ':')) {
    // Path begins with a drive letter.
    sanitized = '/' + sanitized;
  }
  return sanitized;
#else
  return path;
#endif
}
92

93 94 95
bool PathExists(const std::string& path) {
  return access(path.c_str(), R_OK) == 0;
}
96

97 98 99 100 101 102 103 104
std::string FindPackagesPath(const std::string& main_dart) {
  std::string directory = files::GetDirectoryName(main_dart);
  std::string packages_path = directory + "/.packages";
  if (!PathExists(packages_path)) {
    directory = files::GetDirectoryName(directory);
    packages_path = directory + "/.packages";
    if (!PathExists(packages_path))
      packages_path = std::string();
105
  }
106 107
  return packages_path;
}
108

109 110
std::string GetScriptUriFromPath(const std::string& path) {
  return "file://" + SanitizePath(path);
111 112
}

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
}  // namespace

Engine::Engine(PlatformView* platform_view)
    : platform_view_(platform_view->GetWeakPtr()),
      animator_(std::make_unique<Animator>(
          platform_view->rasterizer().GetWeakRasterizerPtr(),
          platform_view->GetVsyncWaiter(),
          this)),
      load_script_error_(tonic::kNoError),
      user_settings_data_("{}"),
      activity_running_(false),
      have_surface_(false),
      weak_factory_(this) {}

Engine::~Engine() {}

void Engine::set_rasterizer(fml::WeakPtr<Rasterizer> rasterizer) {
  animator_->set_rasterizer(rasterizer);
131 132
}

133 134
fml::WeakPtr<Engine> Engine::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
135 136
}

137 138 139 140 141 142 143 144 145 146 147 148 149
#if !FLUTTER_AOT
#elif OS(IOS)
#elif OS(ANDROID)
// TODO(bkonyi): do we even get here for Windows?
static const uint8_t* MemMapSnapshot(const std::string& aot_snapshot_path,
                                     const std::string& default_file_name,
                                     const std::string& settings_file_name,
                                     bool executable) {
  std::string asset_path;
  if (settings_file_name.empty()) {
    asset_path = aot_snapshot_path + "/" + default_file_name;
  } else {
    asset_path = aot_snapshot_path + "/" + settings_file_name;
R
Ryan Macnak 已提交
150 151
  }

152 153 154 155 156
#if OS(WIN)
  HANDLE file_handle_ =
      CreateFileA(reinterpret_cast<LPCSTR>(path.c_str()), GENERIC_READ,
                  FILE_SHARE_READ, nullptr, OPEN_EXISTING,
                  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, nullptr);
157

158 159
  if (file_handle_ == INVALID_HANDLE_VALUE) {
    return;
160 161
  }

162 163 164 165
  size_ = GetFileSize(file_handle_, nullptr);
  if (size_ == INVALID_FILE_SIZE) {
    size_ = 0;
    return;
166 167
  }

168 169 170
  int mapping_flags = executable ? PAGE_EXECUTE_READ : PAGE_READONLY;
  mapping_handle_ = CreateFileMapping(file_handle_, nullptr, mapping_flags, 0,
                                      size_, nullptr);
171

172
  CloseHandle(file_handle_);
173

174 175
  if (mapping_handle_ == INVALID_HANDLE_VALUE) {
    return;
176 177
  }

178 179 180
  int access_flags = FILE_MAP_READ;
  if (executable) {
    access_flags |= FILE_MAP_EXECUTE;
181
  }
182
  auto mapping = MapViewOfFile(mapping_handle_, access_flags, 0, 0, size_);
R
Ryan Macnak 已提交
183

184 185 186 187 188
  if (mapping == INVALID_HANDLE_VALUE) {
    CloseHandle(mapping_handle_);
    mapping_handle_ = INVALID_HANDLE_VALUE;
    return;
  }
R
Ryan Macnak 已提交
189

190 191 192 193 194 195 196 197 198 199
  void* symbol = static_cast<void*>(mapping);
  if (symbol == NULL) {
    return nullptr;
  }
#else
  struct stat info;
  if (stat(asset_path.c_str(), &info) < 0) {
    return nullptr;
  }
  int64_t asset_size = info.st_size;
R
Ryan Macnak 已提交
200

201 202 203 204
  fxl::UniqueFD fd(HANDLE_EINTR(open(asset_path.c_str(), O_RDONLY)));
  if (fd.get() == -1) {
    return nullptr;
  }
R
Ryan Macnak 已提交
205

206 207 208
  int mmap_flags = PROT_READ;
  if (executable)
    mmap_flags |= PROT_EXEC;
209

210 211 212 213 214 215 216 217
  void* symbol = mmap(NULL, asset_size, mmap_flags, MAP_PRIVATE, fd.get(), 0);
  if (symbol == MAP_FAILED) {
    return nullptr;
  }
#endif
  return reinterpret_cast<const uint8_t*>(symbol);
}
#endif
218

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
static const uint8_t* default_isolate_snapshot_data = nullptr;
static const uint8_t* default_isolate_snapshot_instr = nullptr;

void Engine::Init(const std::string& bundle_path) {
  const uint8_t* vm_snapshot_data;
  const uint8_t* vm_snapshot_instr;
#if !FLUTTER_AOT
  vm_snapshot_data = ::kDartVmSnapshotData;
  vm_snapshot_instr = ::kDartVmSnapshotInstructions;
  default_isolate_snapshot_data = ::kDartIsolateCoreSnapshotData;
  default_isolate_snapshot_instr = ::kDartIsolateCoreSnapshotInstructions;
#elif OS(IOS)
  const char* kDartApplicationLibraryPath = "App.framework/App";
  const char* application_library_path = kDartApplicationLibraryPath;
  const blink::Settings& settings = blink::Settings::Get();
  const std::string& application_library_path_setting =
      settings.application_library_path;
  if (!application_library_path_setting.empty()) {
    application_library_path = application_library_path_setting.c_str();
  }
  dlerror();  // clear previous errors on thread
  void* library_handle = dlopen(application_library_path, RTLD_NOW);
  const char* err = dlerror();
  if (err != nullptr) {
    FXL_LOG(FATAL) << "dlopen failed: " << err;
  }
  vm_snapshot_data = reinterpret_cast<const uint8_t*>(
      dlsym(library_handle, "kDartVmSnapshotData"));
  vm_snapshot_instr = reinterpret_cast<const uint8_t*>(
      dlsym(library_handle, "kDartVmSnapshotInstructions"));
  default_isolate_snapshot_data = reinterpret_cast<const uint8_t*>(
      dlsym(library_handle, "kDartIsolateSnapshotData"));
  default_isolate_snapshot_instr = reinterpret_cast<const uint8_t*>(
      dlsym(library_handle, "kDartIsolateSnapshotInstructions"));
#elif OS(ANDROID) || OS(WIN)
  const blink::Settings& settings = blink::Settings::Get();
  const std::string& aot_shared_library_path = settings.aot_shared_library_path;
  const std::string& aot_snapshot_path = settings.aot_snapshot_path;

  if (!aot_shared_library_path.empty()) {
    FXL_CHECK(aot_snapshot_path.empty());
    dlerror();  // clear previous errors on thread
    void* library_handle = dlopen(aot_shared_library_path.c_str(), RTLD_NOW);
    const char* err = dlerror();
    if (err != nullptr) {
      FXL_LOG(FATAL) << "dlopen failed: " << err;
265
    }
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    vm_snapshot_data = reinterpret_cast<const uint8_t*>(
        dlsym(library_handle, "_kDartVmSnapshotData"));
    vm_snapshot_instr = reinterpret_cast<const uint8_t*>(
        dlsym(library_handle, "_kDartVmSnapshotInstructions"));
    default_isolate_snapshot_data = reinterpret_cast<const uint8_t*>(
        dlsym(library_handle, "_kDartIsolateSnapshotData"));
    default_isolate_snapshot_instr = reinterpret_cast<const uint8_t*>(
        dlsym(library_handle, "_kDartIsolateSnapshotInstructions"));
  } else {
    FXL_CHECK(!aot_snapshot_path.empty());
    vm_snapshot_data =
        MemMapSnapshot(aot_snapshot_path, "vm_snapshot_data",
                       settings.aot_vm_snapshot_data_filename, false);
    vm_snapshot_instr =
        MemMapSnapshot(aot_snapshot_path, "vm_snapshot_instr",
                       settings.aot_vm_snapshot_instr_filename, true);
    default_isolate_snapshot_data =
        MemMapSnapshot(aot_snapshot_path, "isolate_snapshot_data",
                       settings.aot_isolate_snapshot_data_filename, false);
    default_isolate_snapshot_instr =
        MemMapSnapshot(aot_snapshot_path, "isolate_snapshot_instr",
                       settings.aot_isolate_snapshot_instr_filename, true);
288
  }
289 290 291 292 293 294
#else
#error Unknown OS
#endif
  blink::InitRuntime(vm_snapshot_data, vm_snapshot_instr,
                     default_isolate_snapshot_data,
                     default_isolate_snapshot_instr, bundle_path);
295 296
}

297
const std::string Engine::main_entrypoint_ = "main";
298

299 300 301 302 303 304 305 306
void Engine::RunBundle(const std::string& bundle_path,
                       const std::string& entrypoint,
                       bool reuse_runtime_controller) {
  TRACE_EVENT0("flutter", "Engine::RunBundle");
  ConfigureAssetBundle(bundle_path);
  DoRunBundle(GetScriptUriFromPath(bundle_path), entrypoint,
              reuse_runtime_controller);
}
307

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
void Engine::DoRunBundle(const std::string& script_uri,
                         const std::string& entrypoint,
                         bool reuse_runtime_controller) {
  ConfigureRuntime(script_uri, reuse_runtime_controller);
  if (blink::IsRunningPrecompiledCode()) {
    runtime_->dart_controller()->RunFromPrecompiledSnapshot(entrypoint);
  } else {
    std::vector<uint8_t> kernel;
    if (GetAssetAsBuffer(blink::kKernelAssetKey, &kernel)) {
      runtime_->dart_controller()->RunFromKernel(kernel, entrypoint);
      return;
    }
    std::vector<uint8_t> snapshot;
    if (!GetAssetAsBuffer(blink::kSnapshotAssetKey, &snapshot))
      return;
    runtime_->dart_controller()->RunFromScriptSnapshot(
        snapshot.data(), snapshot.size(), entrypoint);
325
  }
326
}
327

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
// TODO(jsimmons): merge this with RunBundle
void Engine::RunBundleWithAssets(
    fxl::RefPtr<blink::AssetProvider> asset_provider,
    const std::string& bundle_path,
    const std::string& entrypoint,
    bool reuse_runtime_controller) {
  TRACE_EVENT0("flutter", "Engine::RunBundleWithAssets");
  asset_provider_ = asset_provider;
  DoRunBundle(GetScriptUriFromPath(bundle_path), entrypoint,
              reuse_runtime_controller);
}

void Engine::RunBundleAndSource(const std::string& bundle_path,
                                const std::string& main,
                                const std::string& packages,
                                bool reuse_runtime_controller) {
  TRACE_EVENT0("flutter", "Engine::RunBundleAndSource");
  FXL_CHECK(!blink::IsRunningPrecompiledCode())
      << "Cannot run from source in a precompiled build.";
  std::string packages_path = packages;
  if (packages_path.empty())
    packages_path = FindPackagesPath(main);

  if (!bundle_path.empty())
    ConfigureAssetBundle(bundle_path);

  ConfigureRuntime(main, reuse_runtime_controller);

  if (blink::GetKernelPlatformBinary() != nullptr) {
    std::vector<uint8_t> kernel;
    if (!files::ReadFileToVector(main, &kernel)) {
      load_script_error_ = tonic::kUnknownErrorType;
    }
    load_script_error_ = runtime_->dart_controller()->RunFromKernel(kernel);
  } else {
    load_script_error_ =
        runtime_->dart_controller()->RunFromSource(main, packages_path);
365
  }
366 367
}

368
void Engine::BeginFrame(fxl::TimePoint frame_time) {
369
  TRACE_EVENT0("flutter", "Engine::BeginFrame");
370 371
  if (runtime_)
    runtime_->BeginFrame(frame_time);
A
Adam Barth 已提交
372 373
}

374 375
void Engine::NotifyIdle(int64_t deadline) {
  TRACE_EVENT0("flutter", "Engine::NotifyIdle");
376 377 378 379 380 381 382 383
  if (runtime_)
    runtime_->NotifyIdle(deadline);
}

void Engine::RunFromSource(const std::string& main,
                           const std::string& packages,
                           const std::string& bundle_path) {
  RunBundleAndSource(bundle_path, main, packages);
384 385
}

386 387 388
void Engine::SetAssetBundlePath(const std::string& bundle_path) {
  TRACE_EVENT0("flutter", "Engine::SetAssetBundlePath");
  ConfigureAssetBundle(bundle_path);
389 390
}

391
Dart_Port Engine::GetUIIsolateMainPort() {
392 393 394
  if (!runtime_)
    return ILLEGAL_PORT;
  return runtime_->GetMainPort();
395 396
}

397
std::string Engine::GetUIIsolateName() {
398 399 400 401
  if (!runtime_) {
    return "";
  }
  return runtime_->GetIsolateName();
402 403
}

404
bool Engine::UIIsolateHasLivePorts() {
405 406 407
  if (!runtime_)
    return false;
  return runtime_->HasLivePorts();
408 409
}

410
tonic::DartErrorHandleType Engine::GetUIIsolateLastError() {
411 412 413
  if (!runtime_)
    return tonic::kNoError;
  return runtime_->GetLastError();
414 415 416 417 418 419
}

tonic::DartErrorHandleType Engine::GetLoadScriptError() {
  return load_script_error_;
}

420 421
void Engine::OnOutputSurfaceCreated(const fxl::Closure& gpu_continuation) {
  blink::Threads::Gpu()->PostTask(gpu_continuation);
422 423
  have_surface_ = true;
  StartAnimatorIfPossible();
424 425
  if (runtime_)
    ScheduleFrame();
426 427
}

428
void Engine::OnOutputSurfaceDestroyed(const fxl::Closure& gpu_continuation) {
429 430
  have_surface_ = false;
  StopAnimator();
431
  blink::Threads::Gpu()->PostTask(gpu_continuation);
432 433
}

434
void Engine::SetViewportMetrics(const blink::ViewportMetrics& metrics) {
435 436 437
  bool dimensions_changed =
      viewport_metrics_.physical_height != metrics.physical_height ||
      viewport_metrics_.physical_width != metrics.physical_width;
438
  viewport_metrics_ = metrics;
439 440
  if (runtime_)
    runtime_->SetViewportMetrics(viewport_metrics_);
441
  if (animator_) {
442 443
    if (dimensions_changed)
      animator_->SetDimensionChangePending();
444 445 446
    if (have_surface_)
      ScheduleFrame();
  }
447 448
}

449
void Engine::DispatchPlatformMessage(
450
    fxl::RefPtr<blink::PlatformMessage> message) {
451 452 453 454
  if (message->channel() == kLifecycleChannel) {
    if (HandleLifecyclePlatformMessage(message.get()))
      return;
  } else if (message->channel() == kLocalizationChannel) {
455 456
    if (HandleLocalizationPlatformMessage(message.get()))
      return;
457 458 459
  } else if (message->channel() == kSettingsChannel) {
    HandleSettingsPlatformMessage(message.get());
    return;
460 461
  }

462 463
  if (runtime_) {
    runtime_->DispatchPlatformMessage(std::move(message));
464 465 466
    return;
  }

467
  // If there's no runtime_, we may still need to set the initial route.
468 469
  if (message->channel() == kNavigationChannel)
    HandleNavigationPlatformMessage(std::move(message));
470 471
}

472 473 474
bool Engine::HandleLifecyclePlatformMessage(blink::PlatformMessage* message) {
  const auto& data = message->data();
  std::string state(reinterpret_cast<const char*>(data.data()), data.size());
475 476
  if (state == "AppLifecycleState.paused" ||
      state == "AppLifecycleState.suspending") {
477 478
    activity_running_ = false;
    StopAnimator();
479
  } else if (state == "AppLifecycleState.resumed" ||
480
             state == "AppLifecycleState.inactive") {
481 482 483
    activity_running_ = true;
    StartAnimatorIfPossible();
  }
484 485

  // Always schedule a frame when the app does become active as per API
486 487
  // recommendation
  // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc
488 489 490
  if (state == "AppLifecycleState.resumed" && have_surface_) {
    ScheduleFrame();
  }
491 492 493 494
  return false;
}

bool Engine::HandleNavigationPlatformMessage(
495
    fxl::RefPtr<blink::PlatformMessage> message) {
496
  FXL_DCHECK(!runtime_);
497 498 499 500 501 502 503 504
  const auto& data = message->data();

  rapidjson::Document document;
  document.Parse(reinterpret_cast<const char*>(data.data()), data.size());
  if (document.HasParseError() || !document.IsObject())
    return false;
  auto root = document.GetObject();
  auto method = root.FindMember("method");
505
  if (method->value != "setInitialRoute")
506
    return false;
507 508
  auto route = root.FindMember("args");
  initial_route_ = std::move(route->value.GetString());
509 510 511 512
  return true;
}

bool Engine::HandleLocalizationPlatformMessage(
513
    blink::PlatformMessage* message) {
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
  const auto& data = message->data();

  rapidjson::Document document;
  document.Parse(reinterpret_cast<const char*>(data.data()), data.size());
  if (document.HasParseError() || !document.IsObject())
    return false;
  auto root = document.GetObject();
  auto method = root.FindMember("method");
  if (method == root.MemberEnd() || method->value != "setLocale")
    return false;

  auto args = root.FindMember("args");
  if (args == root.MemberEnd() || !args->value.IsArray())
    return false;

  const auto& language = args->value[0];
  const auto& country = args->value[1];

  if (!language.IsString() || !country.IsString())
    return false;

535 536 537 538 539
  language_code_ = language.GetString();
  country_code_ = country.GetString();
  if (runtime_)
    runtime_->SetLocale(language_code_, country_code_);
  return true;
A
Adam Barth 已提交
540 541
}

542
void Engine::HandleSettingsPlatformMessage(blink::PlatformMessage* message) {
543
  const auto& data = message->data();
544
  std::string jsonData(reinterpret_cast<const char*>(data.data()), data.size());
545 546 547 548 549
  user_settings_data_ = jsonData;
  if (runtime_) {
    runtime_->SetUserSettingsData(user_settings_data_);
    if (have_surface_)
      ScheduleFrame();
550 551 552
  }
}

553 554 555
void Engine::DispatchPointerDataPacket(const PointerDataPacket& packet) {
  if (runtime_)
    runtime_->DispatchPointerDataPacket(packet);
556 557
}

558 559 560
void Engine::DispatchSemanticsAction(int id,
                                     blink::SemanticsAction action,
                                     std::vector<uint8_t> args) {
561 562
  if (runtime_)
    runtime_->DispatchSemanticsAction(id, action, std::move(args));
563 564 565
}

void Engine::SetSemanticsEnabled(bool enabled) {
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
  semantics_enabled_ = enabled;
  if (runtime_)
    runtime_->SetSemanticsEnabled(semantics_enabled_);
}

void Engine::ConfigureAssetBundle(const std::string& path) {
  asset_provider_ = fxl::MakeRefCounted<blink::DirectoryAssetBundle>(path);

  struct stat stat_result = {};

  // TODO(abarth): We should reset directory_asset_bundle_, but that might break
  // custom font loading in hot reload.

  if (::stat(path.c_str(), &stat_result) != 0) {
    FXL_LOG(INFO) << "Could not configure asset bundle at path: " << path;
    return;
  }

  std::string flx_path;
  if (S_ISDIR(stat_result.st_mode)) {
    flx_path = files::GetDirectoryName(path) + "/app.flx";
  } else if (S_ISREG(stat_result.st_mode)) {
    flx_path = path;
  }

  if (PathExists(flx_path)) {
    asset_store_ = fxl::MakeRefCounted<blink::ZipAssetStore>(
        blink::GetUnzipperProviderForPath(flx_path));
  }
}

void Engine::ConfigureRuntime(const std::string& script_uri,
                              bool reuse_runtime_controller) {
  if (runtime_ && reuse_runtime_controller) {
    return;
  }
  runtime_ = blink::RuntimeController::Create(this);
  runtime_->CreateDartController(std::move(script_uri),
                                 default_isolate_snapshot_data,
                                 default_isolate_snapshot_instr);
  runtime_->SetViewportMetrics(viewport_metrics_);
  runtime_->SetLocale(language_code_, country_code_);
  runtime_->SetUserSettingsData(user_settings_data_);
  runtime_->SetSemanticsEnabled(semantics_enabled_);
}

void Engine::DidCreateMainIsolate(Dart_Isolate isolate) {
  if (blink::Settings::Get().use_test_fonts) {
    blink::TestFontSelector::Install();
    if (!blink::Settings::Get().using_blink)
      blink::FontCollection::ForProcess().RegisterTestFonts();
  } else if (asset_provider_) {
    blink::AssetFontSelector::Install(asset_provider_);
    if (!blink::Settings::Get().using_blink) {
      blink::FontCollection::ForProcess().RegisterFontsFromAssetProvider(
          asset_provider_);
    }
  }
624 625
}

626 627
void Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {}

628 629 630 631 632 633 634 635 636
void Engine::StopAnimator() {
  animator_->Stop();
}

void Engine::StartAnimatorIfPossible() {
  if (activity_running_ && have_surface_)
    animator_->Start();
}

637 638 639 640 641 642 643
std::string Engine::DefaultRouteName() {
  if (!initial_route_.empty()) {
    return initial_route_;
  }
  return "/";
}

644 645
void Engine::ScheduleFrame(bool regenerate_layer_tree) {
  animator_->RequestFrame(regenerate_layer_tree);
A
Adam Barth 已提交
646 647
}

648 649 650
void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
  if (!layer_tree)
    return;
651

652 653
  SkISize frame_size = SkISize::Make(viewport_metrics_.physical_width,
                                     viewport_metrics_.physical_height);
654 655 656 657
  if (frame_size.isEmpty())
    return;

  layer_tree->set_frame_size(frame_size);
658 659
  animator_->Render(std::move(layer_tree));
}
660

Y
Yegor 已提交
661
void Engine::UpdateSemantics(blink::SemanticsNodeUpdates update) {
662 663 664 665 666 667
  blink::Threads::Platform()->PostTask(fxl::MakeCopyable([
    platform_view = platform_view_.lock(), update = std::move(update)
  ]() mutable {
    if (platform_view)
      platform_view->UpdateSemantics(std::move(update));
  }));
668
}
669

670
void Engine::HandlePlatformMessage(
671
    fxl::RefPtr<blink::PlatformMessage> message) {
672
  if (message->channel() == kAssetChannel) {
A
Adam Barth 已提交
673
    HandleAssetPlatformMessage(std::move(message));
674
    return;
A
Adam Barth 已提交
675
  }
676 677 678 679 680 681
  blink::Threads::Platform()->PostTask([
    platform_view = platform_view_.lock(), message = std::move(message)
  ]() mutable {
    if (platform_view)
      platform_view->HandlePlatformMessage(std::move(message));
  });
682 683
}

A
Adam Barth 已提交
684
void Engine::HandleAssetPlatformMessage(
685 686
    fxl::RefPtr<blink::PlatformMessage> message) {
  fxl::RefPtr<blink::PlatformMessageResponse> response = message->response();
687
  if (!response)
A
Adam Barth 已提交
688 689 690 691 692
    return;
  const auto& data = message->data();
  std::string asset_name(reinterpret_cast<const char*>(data.data()),
                         data.size());
  std::vector<uint8_t> asset_data;
693
  if (GetAssetAsBuffer(asset_name, &asset_data)) {
A
Adam Barth 已提交
694 695
    response->Complete(std::move(asset_data));
  } else {
696
    response->CompleteEmpty();
A
Adam Barth 已提交
697 698 699
  }
}

700 701 702 703 704 705 706
bool Engine::GetAssetAsBuffer(const std::string& name,
                              std::vector<uint8_t>* data) {
  return ((asset_provider_ &&
           asset_provider_->GetAsBuffer(name, data)) ||
          (asset_store_ && asset_store_->GetAsBuffer(name, data)));
}

707
}  // namespace shell