engine.cc 16.6 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

R
Ryan Macnak 已提交
7 8 9
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/mman.h>
10
#include <sys/stat.h>
11
#include <unistd.h>
12
#include <memory>
13 14
#include <utility>

15
#include "flutter/assets/directory_asset_bundle.h"
A
Adam Barth 已提交
16
#include "flutter/assets/unzipper_provider.h"
A
Adam Barth 已提交
17
#include "flutter/assets/zip_asset_store.h"
18
#include "flutter/common/settings.h"
19
#include "flutter/common/threads.h"
20
#include "flutter/glue/trace_event.h"
R
Ryan Macnak 已提交
21
#include "flutter/lib/snapshot/snapshot.h"
22
#include "flutter/runtime/asset_font_selector.h"
23 24
#include "flutter/runtime/dart_controller.h"
#include "flutter/runtime/dart_init.h"
25
#include "flutter/runtime/runtime_init.h"
26
#include "flutter/runtime/test_font_selector.h"
27
#include "flutter/shell/common/animator.h"
28
#include "flutter/shell/common/platform_view.h"
29
#include "flutter/sky/engine/public/web/Sky.h"
R
Ryan Macnak 已提交
30
#include "lib/ftl/files/eintr_wrapper.h"
31
#include "lib/ftl/files/file.h"
32
#include "lib/ftl/files/path.h"
R
Ryan Macnak 已提交
33
#include "lib/ftl/files/unique_fd.h"
34
#include "lib/ftl/functional/make_copyable.h"
35
#include "third_party/rapidjson/rapidjson/document.h"
A
Adam Barth 已提交
36 37
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
38 39

namespace shell {
40
namespace {
41

42 43 44 45
constexpr char kAssetChannel[] = "flutter/assets";
constexpr char kLifecycleChannel[] = "flutter/lifecycle";
constexpr char kNavigationChannel[] = "flutter/navigation";
constexpr char kLocalizationChannel[] = "flutter/localization";
A
Adam Barth 已提交
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
bool PathExists(const std::string& path) {
  return access(path.c_str(), R_OK) == 0;
}

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();
  }
  return packages_path;
}

63 64 65 66
std::string GetScriptUriFromPath(const std::string& path) {
  return "file://" + path;
}

67 68
}  // namespace

69 70
Engine::Engine(PlatformView* platform_view)
    : platform_view_(platform_view->GetWeakPtr()),
71 72 73 74
      animator_(std::make_unique<Animator>(
          platform_view->rasterizer().GetWeakRasterizerPtr(),
          platform_view->GetVsyncWaiter(),
          this)),
75
      load_script_error_(tonic::kNoError),
76 77
      activity_running_(false),
      have_surface_(false),
78
      weak_factory_(this) {}
79

80
Engine::~Engine() {}
81

82
ftl::WeakPtr<Engine> Engine::GetWeakPtr() {
83 84 85
  return weak_factory_.GetWeakPtr();
}

R
Ryan Macnak 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
#if !FLUTTER_AOT
#elif OS(IOS)
#elif OS(ANDROID)
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;
  }

  struct stat info;
  if (stat(asset_path.c_str(), &info) < 0) {
    return nullptr;
  }
  int64_t asset_size = info.st_size;

  ftl::UniqueFD fd(HANDLE_EINTR(open(asset_path.c_str(), O_RDONLY)));
  if (fd.get() == -1) {
    return nullptr;
  }

  int mmap_flags = PROT_READ;
  if (executable) mmap_flags |= PROT_EXEC;

  void* symbol = mmap(NULL, asset_size, mmap_flags, MAP_PRIVATE, fd.get(), 0);
  if (symbol == MAP_FAILED) {
    return nullptr;
  }
  return reinterpret_cast<const uint8_t*>(symbol);
}
#endif

static const uint8_t* default_isolate_snapshot_data = nullptr;
static const uint8_t* default_isolate_snapshot_instr = nullptr;

125
void Engine::Init() {
R
Ryan Macnak 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  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) {
    FTL_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)
  const blink::Settings& settings = blink::Settings::Get();
  const std::string& aot_snapshot_path = settings.aot_snapshot_path;
  FTL_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);
#else
#error Unknown OS
#endif

  blink::InitRuntime(vm_snapshot_data, vm_snapshot_instr,
                     default_isolate_snapshot_data,
                     default_isolate_snapshot_instr);
179 180
}

181 182 183 184 185 186 187
void Engine::RunBundle(const std::string& bundle_path) {
  TRACE_EVENT0("flutter", "Engine::RunBundle");
  ConfigureAssetBundle(bundle_path);
  ConfigureRuntime(GetScriptUriFromPath(bundle_path));
  if (blink::IsRunningPrecompiledCode()) {
    runtime_->dart_controller()->RunFromPrecompiledSnapshot();
  } else {
D
Dan Rubel 已提交
188 189
    std::vector<uint8_t> kernel;
    if (GetAssetAsBuffer(blink::kKernelAssetKey, &kernel)) {
190
      runtime_->dart_controller()->RunFromKernel(kernel.data(), kernel.size());
D
Dan Rubel 已提交
191 192
      return;
    }
193 194 195
    std::vector<uint8_t> snapshot;
    if (!GetAssetAsBuffer(blink::kSnapshotAssetKey, &snapshot))
      return;
R
Ryan Macnak 已提交
196 197
    runtime_->dart_controller()->RunFromScriptSnapshot(snapshot.data(),
                                                       snapshot.size());
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  }
}

void Engine::RunBundleAndSnapshot(const std::string& bundle_path,
                                  const std::string& snapshot_override) {
  TRACE_EVENT0("flutter", "Engine::RunBundleAndSnapshot");
  if (snapshot_override.empty()) {
    RunBundle(bundle_path);
    return;
  }
  ConfigureAssetBundle(bundle_path);
  ConfigureRuntime(GetScriptUriFromPath(bundle_path));
  if (blink::IsRunningPrecompiledCode()) {
    runtime_->dart_controller()->RunFromPrecompiledSnapshot();
  } else {
    std::vector<uint8_t> snapshot;
    if (!files::ReadFileToVector(snapshot_override, &snapshot))
      return;
R
Ryan Macnak 已提交
216 217
    runtime_->dart_controller()->RunFromScriptSnapshot(snapshot.data(),
                                                       snapshot.size());
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  }
}

void Engine::RunBundleAndSource(const std::string& bundle_path,
                                const std::string& main,
                                const std::string& packages) {
  TRACE_EVENT0("flutter", "Engine::RunBundleAndSource");
  FTL_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(GetScriptUriFromPath(main));
233 234
  load_script_error_ =
      runtime_->dart_controller()->RunFromSource(main, packages_path);
235 236
}

A
Adam Barth 已提交
237
void Engine::BeginFrame(ftl::TimePoint frame_time) {
238
  TRACE_EVENT0("flutter", "Engine::BeginFrame");
239 240
  if (runtime_)
    runtime_->BeginFrame(frame_time);
A
Adam Barth 已提交
241 242
}

243 244
void Engine::RunFromSource(const std::string& main,
                           const std::string& packages,
245 246
                           const std::string& bundle_path) {
  RunBundleAndSource(bundle_path, main, packages);
247 248
}

249
Dart_Port Engine::GetUIIsolateMainPort() {
250
  if (!runtime_)
251
    return ILLEGAL_PORT;
252
  return runtime_->GetMainPort();
253 254
}

255 256 257 258 259 260 261
std::string Engine::GetUIIsolateName() {
  if (!runtime_) {
    return "";
  }
  return runtime_->GetIsolateName();
}

262 263 264 265 266 267
bool Engine::UIIsolateHasLivePorts() {
  if (!runtime_)
    return false;
  return runtime_->HasLivePorts();
}

268 269 270 271 272 273 274 275 276 277
tonic::DartErrorHandleType Engine::GetUIIsolateLastError() {
  if (!runtime_)
    return tonic::kNoError;
  return runtime_->GetLastError();
}

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

278
void Engine::OnOutputSurfaceCreated(const ftl::Closure& gpu_continuation) {
279
  blink::Threads::Gpu()->PostTask(gpu_continuation);
280 281
  have_surface_ = true;
  StartAnimatorIfPossible();
282
  if (runtime_)
283
    ScheduleFrame();
284 285
}

286
void Engine::OnOutputSurfaceDestroyed(const ftl::Closure& gpu_continuation) {
287 288
  have_surface_ = false;
  StopAnimator();
289
  blink::Threads::Gpu()->PostTask(gpu_continuation);
290 291
}

292 293
void Engine::SetViewportMetrics(const blink::ViewportMetrics& metrics) {
  viewport_metrics_ = metrics;
294 295
  if (runtime_)
    runtime_->SetViewportMetrics(viewport_metrics_);
296 297
}

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
void Engine::DispatchPlatformMessage(
    ftl::RefPtr<blink::PlatformMessage> message) {
  if (message->channel() == kLifecycleChannel) {
    if (HandleLifecyclePlatformMessage(message.get()))
      return;
  } else if (message->channel() == kLocalizationChannel) {
    if (HandleLocalizationPlatformMessage(std::move(message)))
      return;
  }

  if (runtime_) {
    runtime_->DispatchPlatformMessage(std::move(message));
    return;
  }

313
  // If there's no runtime_, we may still need to set the initial route.
314 315
  if (message->channel() == kNavigationChannel)
    HandleNavigationPlatformMessage(std::move(message));
316 317
}

318 319 320
bool Engine::HandleLifecyclePlatformMessage(blink::PlatformMessage* message) {
  const auto& data = message->data();
  std::string state(reinterpret_cast<const char*>(data.data()), data.size());
321 322
  if (state == "AppLifecycleState.paused" ||
      state == "AppLifecycleState.suspending") {
323 324
    activity_running_ = false;
    StopAnimator();
325 326
  } else if (state == "AppLifecycleState.resumed" ||
             state == "AppLifecycle.inactive") {
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    activity_running_ = true;
    StartAnimatorIfPossible();
  }
  return false;
}

bool Engine::HandleNavigationPlatformMessage(
    ftl::RefPtr<blink::PlatformMessage> message) {
  FTL_DCHECK(!runtime_);
  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");
344
  if (method->value != "setInitialRoute")
345
    return false;
346 347
  auto route = root.FindMember("args");
  initial_route_ = std::move(route->value.GetString());
348 349 350 351
  return true;
}

bool Engine::HandleLocalizationPlatformMessage(
A
Adam Barth 已提交
352
    ftl::RefPtr<blink::PlatformMessage> message) {
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
  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;

  language_code_ = language.GetString();
  country_code_ = country.GetString();
A
Adam Barth 已提交
376
  if (runtime_)
377 378
    runtime_->SetLocale(language_code_, country_code_);
  return true;
A
Adam Barth 已提交
379 380
}

381
void Engine::DispatchPointerDataPacket(const PointerDataPacket& packet) {
382
  if (runtime_)
383
    runtime_->DispatchPointerDataPacket(packet);
384 385
}

386 387 388 389 390 391
void Engine::DispatchSemanticsAction(int id, blink::SemanticsAction action) {
  if (runtime_)
    runtime_->DispatchSemanticsAction(id, action);
}

void Engine::SetSemanticsEnabled(bool enabled) {
A
Adam Barth 已提交
392
  semantics_enabled_ = enabled;
393
  if (runtime_)
A
Adam Barth 已提交
394
    runtime_->SetSemanticsEnabled(semantics_enabled_);
395 396
}

397
void Engine::ConfigureAssetBundle(const std::string& path) {
398
  struct stat stat_result = {};
399

A
Adam Barth 已提交
400
  directory_asset_bundle_.reset();
A
Adam Barth 已提交
401 402
  // TODO(abarth): We should reset asset_store_ as well, but that might break
  // custom font loading in hot reload.
A
Adam Barth 已提交
403

404
  if (::stat(path.c_str(), &stat_result) != 0) {
405
    FTL_LOG(INFO) << "Could not configure asset bundle at path: " << path;
406 407
    return;
  }
408

409
  if (S_ISDIR(stat_result.st_mode)) {
A
Adam Barth 已提交
410 411
    directory_asset_bundle_ =
        std::make_unique<blink::DirectoryAssetBundle>(path);
412 413 414 415
    return;
  }

  if (S_ISREG(stat_result.st_mode)) {
A
Adam Barth 已提交
416
    asset_store_ = ftl::MakeRefCounted<blink::ZipAssetStore>(
A
Adam Barth 已提交
417
        blink::GetUnzipperProviderForPath(path));
418 419
    return;
  }
420 421
}

422 423
void Engine::ConfigureRuntime(const std::string& script_uri) {
  runtime_ = blink::RuntimeController::Create(this);
R
Ryan Macnak 已提交
424 425 426
  runtime_->CreateDartController(std::move(script_uri),
                                 default_isolate_snapshot_data,
                                 default_isolate_snapshot_instr);
427 428
  runtime_->SetViewportMetrics(viewport_metrics_);
  runtime_->SetLocale(language_code_, country_code_);
A
Adam Barth 已提交
429
  runtime_->SetSemanticsEnabled(semantics_enabled_);
430 431
}

432
void Engine::DidCreateMainIsolate(Dart_Isolate isolate) {
433 434 435
  if (blink::Settings::Get().use_test_fonts) {
    blink::TestFontSelector::Install();
  } else if (asset_store_) {
436
    blink::AssetFontSelector::Install(asset_store_);
437
  }
438 439
}

440
void Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {}
441

442 443 444 445 446 447 448 449 450
void Engine::StopAnimator() {
  animator_->Stop();
}

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

451 452 453 454 455 456 457
std::string Engine::DefaultRouteName() {
  if (!initial_route_.empty()) {
    return initial_route_;
  }
  return "/";
}

458
void Engine::ScheduleFrame() {
A
Adam Barth 已提交
459 460 461
  animator_->RequestFrame();
}

462 463 464
void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
  if (!layer_tree)
    return;
465

466 467
  SkISize frame_size = SkISize::Make(viewport_metrics_.physical_width,
                                     viewport_metrics_.physical_height);
468 469 470 471
  if (frame_size.isEmpty())
    return;

  layer_tree->set_frame_size(frame_size);
472 473
  animator_->Render(std::move(layer_tree));
}
474

475 476 477 478 479 480 481
void Engine::UpdateSemantics(std::vector<blink::SemanticsNode> update) {
  blink::Threads::Platform()->PostTask(ftl::MakeCopyable(
      [ platform_view = platform_view_, update = std::move(update) ]() mutable {
        if (platform_view)
          platform_view->UpdateSemantics(std::move(update));
      }));
}
482

483 484
void Engine::HandlePlatformMessage(
    ftl::RefPtr<blink::PlatformMessage> message) {
485
  if (message->channel() == kAssetChannel) {
A
Adam Barth 已提交
486 487 488
    HandleAssetPlatformMessage(std::move(message));
    return;
  }
489 490 491 492 493 494 495 496
  blink::Threads::Platform()->PostTask([
    platform_view = platform_view_, message = std::move(message)
  ]() mutable {
    if (platform_view)
      platform_view->HandlePlatformMessage(std::move(message));
  });
}

A
Adam Barth 已提交
497 498 499 500 501 502 503 504 505
void Engine::HandleAssetPlatformMessage(
    ftl::RefPtr<blink::PlatformMessage> message) {
  ftl::RefPtr<blink::PlatformMessageResponse> response = message->response();
  if (!response)
    return;
  const auto& data = message->data();
  std::string asset_name(reinterpret_cast<const char*>(data.data()),
                         data.size());
  std::vector<uint8_t> asset_data;
506
  if (GetAssetAsBuffer(asset_name, &asset_data)) {
A
Adam Barth 已提交
507 508
    response->Complete(std::move(asset_data));
  } else {
509
    response->CompleteEmpty();
A
Adam Barth 已提交
510 511 512
  }
}

513 514 515 516 517 518 519
bool Engine::GetAssetAsBuffer(const std::string& name,
                              std::vector<uint8_t>* data) {
  return (directory_asset_bundle_ &&
          directory_asset_bundle_->GetAsBuffer(name, data)) ||
         (asset_store_ && asset_store_->GetAsBuffer(name, data));
}

520
}  // namespace shell