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

7
#include <sys/stat.h>
8
#include <unistd.h>
9
#include <memory>
10 11
#include <utility>

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

namespace shell {
34
namespace {
35

36 37 38 39
constexpr char kAssetChannel[] = "flutter/assets";
constexpr char kLifecycleChannel[] = "flutter/lifecycle";
constexpr char kNavigationChannel[] = "flutter/navigation";
constexpr char kLocalizationChannel[] = "flutter/localization";
A
Adam Barth 已提交
40

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
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;
}

57 58 59 60
std::string GetScriptUriFromPath(const std::string& path) {
  return "file://" + path;
}

61 62
}  // namespace

63 64
Engine::Engine(PlatformView* platform_view)
    : platform_view_(platform_view->GetWeakPtr()),
65 66 67 68
      animator_(std::make_unique<Animator>(
          platform_view->rasterizer().GetWeakRasterizerPtr(),
          platform_view->GetVsyncWaiter(),
          this)),
69
      load_script_error_(tonic::kNoError),
70 71
      activity_running_(false),
      have_surface_(false),
72
      weak_factory_(this) {}
73

74
Engine::~Engine() {}
75

76
ftl::WeakPtr<Engine> Engine::GetWeakPtr() {
77 78 79
  return weak_factory_.GetWeakPtr();
}

80
void Engine::Init() {
81
  blink::InitRuntime();
82 83
}

84 85 86 87 88 89 90
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 已提交
91 92
    std::vector<uint8_t> kernel;
    if (GetAssetAsBuffer(blink::kKernelAssetKey, &kernel)) {
93
      runtime_->dart_controller()->RunFromKernel(kernel.data(), kernel.size());
D
Dan Rubel 已提交
94 95
      return;
    }
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 125 126 127 128 129 130 131 132 133 134 135
    std::vector<uint8_t> snapshot;
    if (!GetAssetAsBuffer(blink::kSnapshotAssetKey, &snapshot))
      return;
    runtime_->dart_controller()->RunFromSnapshot(snapshot.data(),
                                                 snapshot.size());
  }
}

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;
    runtime_->dart_controller()->RunFromSnapshot(snapshot.data(),
                                                 snapshot.size());
  }
}

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));
136 137
  load_script_error_ =
      runtime_->dart_controller()->RunFromSource(main, packages_path);
138 139
}

A
Adam Barth 已提交
140
void Engine::BeginFrame(ftl::TimePoint frame_time) {
141
  TRACE_EVENT0("flutter", "Engine::BeginFrame");
142 143
  if (runtime_)
    runtime_->BeginFrame(frame_time);
A
Adam Barth 已提交
144 145
}

146 147
void Engine::RunFromSource(const std::string& main,
                           const std::string& packages,
148 149
                           const std::string& bundle_path) {
  RunBundleAndSource(bundle_path, main, packages);
150 151
}

152
Dart_Port Engine::GetUIIsolateMainPort() {
153
  if (!runtime_)
154
    return ILLEGAL_PORT;
155
  return runtime_->GetMainPort();
156 157
}

158 159 160 161 162 163 164
std::string Engine::GetUIIsolateName() {
  if (!runtime_) {
    return "";
  }
  return runtime_->GetIsolateName();
}

165 166 167 168 169 170
bool Engine::UIIsolateHasLivePorts() {
  if (!runtime_)
    return false;
  return runtime_->HasLivePorts();
}

171 172 173 174 175 176 177 178 179 180
tonic::DartErrorHandleType Engine::GetUIIsolateLastError() {
  if (!runtime_)
    return tonic::kNoError;
  return runtime_->GetLastError();
}

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

181
void Engine::OnOutputSurfaceCreated(const ftl::Closure& gpu_continuation) {
182
  blink::Threads::Gpu()->PostTask(gpu_continuation);
183 184
  have_surface_ = true;
  StartAnimatorIfPossible();
185
  if (runtime_)
186
    ScheduleFrame();
187 188
}

189
void Engine::OnOutputSurfaceDestroyed(const ftl::Closure& gpu_continuation) {
190 191
  have_surface_ = false;
  StopAnimator();
192
  blink::Threads::Gpu()->PostTask(gpu_continuation);
193 194
}

195 196
void Engine::SetViewportMetrics(const blink::ViewportMetrics& metrics) {
  viewport_metrics_ = metrics;
197 198
  if (runtime_)
    runtime_->SetViewportMetrics(viewport_metrics_);
199 200
}

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
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));
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
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 已提交
253
    ftl::RefPtr<blink::PlatformMessage> message) {
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  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 已提交
277
  if (runtime_)
278 279
    runtime_->SetLocale(language_code_, country_code_);
  return true;
A
Adam Barth 已提交
280 281
}

282
void Engine::DispatchPointerDataPacket(const PointerDataPacket& packet) {
283
  if (runtime_)
284
    runtime_->DispatchPointerDataPacket(packet);
285 286
}

287 288 289 290 291 292
void Engine::DispatchSemanticsAction(int id, blink::SemanticsAction action) {
  if (runtime_)
    runtime_->DispatchSemanticsAction(id, action);
}

void Engine::SetSemanticsEnabled(bool enabled) {
A
Adam Barth 已提交
293
  semantics_enabled_ = enabled;
294
  if (runtime_)
A
Adam Barth 已提交
295
    runtime_->SetSemanticsEnabled(semantics_enabled_);
296 297
}

298 299 300
void Engine::ConfigureAssetBundle(const std::string& path) {
  struct stat stat_result = {0};

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

305
  if (::stat(path.c_str(), &stat_result) != 0) {
306
    FTL_LOG(INFO) << "Could not configure asset bundle at path: " << path;
307 308
    return;
  }
309

310
  if (S_ISDIR(stat_result.st_mode)) {
A
Adam Barth 已提交
311 312
    directory_asset_bundle_ =
        std::make_unique<blink::DirectoryAssetBundle>(path);
313 314 315 316
    return;
  }

  if (S_ISREG(stat_result.st_mode)) {
A
Adam Barth 已提交
317
    asset_store_ = ftl::MakeRefCounted<blink::ZipAssetStore>(
A
Adam Barth 已提交
318
        blink::GetUnzipperProviderForPath(path));
319 320
    return;
  }
321 322
}

323 324 325 326 327
void Engine::ConfigureRuntime(const std::string& script_uri) {
  runtime_ = blink::RuntimeController::Create(this);
  runtime_->CreateDartController(std::move(script_uri));
  runtime_->SetViewportMetrics(viewport_metrics_);
  runtime_->SetLocale(language_code_, country_code_);
A
Adam Barth 已提交
328
  runtime_->SetSemanticsEnabled(semantics_enabled_);
329 330
  if (pending_push_route_message_)
    runtime_->DispatchPlatformMessage(std::move(pending_push_route_message_));
331 332
}

333
void Engine::DidCreateMainIsolate(Dart_Isolate isolate) {
334 335 336
  if (blink::Settings::Get().use_test_fonts) {
    blink::TestFontSelector::Install();
  } else if (asset_store_) {
337
    blink::AssetFontSelector::Install(asset_store_);
338
  }
339 340
}

341
void Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {}
342

343 344 345 346 347 348 349 350 351
void Engine::StopAnimator() {
  animator_->Stop();
}

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

352
void Engine::ScheduleFrame() {
A
Adam Barth 已提交
353 354 355
  animator_->RequestFrame();
}

356 357 358
void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
  if (!layer_tree)
    return;
359

360 361
  SkISize frame_size = SkISize::Make(viewport_metrics_.physical_width,
                                     viewport_metrics_.physical_height);
362 363 364 365
  if (frame_size.isEmpty())
    return;

  layer_tree->set_frame_size(frame_size);
366 367
  animator_->Render(std::move(layer_tree));
}
368

369 370 371 372 373 374 375
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));
      }));
}
376

377 378
void Engine::HandlePlatformMessage(
    ftl::RefPtr<blink::PlatformMessage> message) {
379
  if (message->channel() == kAssetChannel) {
A
Adam Barth 已提交
380 381 382
    HandleAssetPlatformMessage(std::move(message));
    return;
  }
383 384 385 386 387 388 389 390
  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 已提交
391 392 393 394 395 396 397 398 399
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;
400
  if (GetAssetAsBuffer(asset_name, &asset_data)) {
A
Adam Barth 已提交
401 402 403 404 405 406
    response->Complete(std::move(asset_data));
  } else {
    response->CompleteWithError();
  }
}

407 408 409 410 411 412 413
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));
}

414
}  // namespace shell