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

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 313 314 315
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;
  }

  // If there's no runtime_, we need to buffer some navigation messages.
  if (message->channel() == kNavigationChannel)
    HandleNavigationPlatformMessage(std::move(message));
316 317
}

318 319 320 321 322 323 324 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
bool Engine::HandleLifecyclePlatformMessage(blink::PlatformMessage* message) {
  const auto& data = message->data();
  std::string state(reinterpret_cast<const char*>(data.data()), data.size());
  if (state == "AppLifecycleState.paused") {
    activity_running_ = false;
    StopAnimator();
  } else if (state == "AppLifecycleState.resumed") {
    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");
  if (method == root.MemberEnd() || method->value != "pushRoute")
    return false;

  pending_push_route_message_ = std::move(message);
  return true;
}

bool Engine::HandleLocalizationPlatformMessage(
A
Adam Barth 已提交
350
    ftl::RefPtr<blink::PlatformMessage> message) {
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  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 已提交
374
  if (runtime_)
375 376
    runtime_->SetLocale(language_code_, country_code_);
  return true;
A
Adam Barth 已提交
377 378
}

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

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

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

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

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

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

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

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

420 421
void Engine::ConfigureRuntime(const std::string& script_uri) {
  runtime_ = blink::RuntimeController::Create(this);
R
Ryan Macnak 已提交
422 423 424
  runtime_->CreateDartController(std::move(script_uri),
                                 default_isolate_snapshot_data,
                                 default_isolate_snapshot_instr);
425 426
  runtime_->SetViewportMetrics(viewport_metrics_);
  runtime_->SetLocale(language_code_, country_code_);
A
Adam Barth 已提交
427
  runtime_->SetSemanticsEnabled(semantics_enabled_);
428 429
  if (pending_push_route_message_)
    runtime_->DispatchPlatformMessage(std::move(pending_push_route_message_));
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
void Engine::ScheduleFrame() {
A
Adam Barth 已提交
452 453 454
  animator_->RequestFrame();
}

455 456 457
void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
  if (!layer_tree)
    return;
458

459 460
  SkISize frame_size = SkISize::Make(viewport_metrics_.physical_width,
                                     viewport_metrics_.physical_height);
461 462 463 464
  if (frame_size.isEmpty())
    return;

  layer_tree->set_frame_size(frame_size);
465 466
  animator_->Render(std::move(layer_tree));
}
467

468 469 470 471 472 473 474
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));
      }));
}
475

476 477
void Engine::HandlePlatformMessage(
    ftl::RefPtr<blink::PlatformMessage> message) {
478
  if (message->channel() == kAssetChannel) {
A
Adam Barth 已提交
479 480 481
    HandleAssetPlatformMessage(std::move(message));
    return;
  }
482 483 484 485 486 487 488 489
  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 已提交
490 491 492 493 494 495 496 497 498
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;
499
  if (GetAssetAsBuffer(asset_name, &asset_data)) {
A
Adam Barth 已提交
500 501
    response->Complete(std::move(asset_data));
  } else {
502
    response->CompleteEmpty();
A
Adam Barth 已提交
503 504 505
  }
}

506 507 508 509 510 511 512
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));
}

513
}  // namespace shell