engine.cc 11.8 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 10
#include <utility>

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

namespace shell {
31
namespace {
32

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

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
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;
}

54 55 56 57
std::string GetScriptUriFromPath(const std::string& path) {
  return "file://" + path;
}

58 59
}  // namespace

60 61
Engine::Engine(PlatformView* platform_view)
    : platform_view_(platform_view->GetWeakPtr()),
62 63 64 65
      animator_(std::make_unique<Animator>(
          platform_view->rasterizer().GetWeakRasterizerPtr(),
          platform_view->GetVsyncWaiter(),
          this)),
66 67
      activity_running_(false),
      have_surface_(false),
68
      weak_factory_(this) {}
69

70
Engine::~Engine() {}
71

72
ftl::WeakPtr<Engine> Engine::GetWeakPtr() {
73 74 75
  return weak_factory_.GetWeakPtr();
}

76
void Engine::Init() {
77
  blink::InitRuntime();
78 79
}

80 81 82 83 84 85 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 125 126 127 128 129
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 {
    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));
  runtime_->dart_controller()->RunFromSource(main, packages_path);
}

A
Adam Barth 已提交
130
void Engine::BeginFrame(ftl::TimePoint frame_time) {
131
  TRACE_EVENT0("flutter", "Engine::BeginFrame");
132 133
  if (runtime_)
    runtime_->BeginFrame(frame_time);
A
Adam Barth 已提交
134 135
}

136 137
void Engine::RunFromSource(const std::string& main,
                           const std::string& packages,
138 139
                           const std::string& bundle_path) {
  RunBundleAndSource(bundle_path, main, packages);
140 141
}

142
Dart_Port Engine::GetUIIsolateMainPort() {
143
  if (!runtime_)
144
    return ILLEGAL_PORT;
145
  return runtime_->GetMainPort();
146 147
}

148 149 150 151 152 153 154
std::string Engine::GetUIIsolateName() {
  if (!runtime_) {
    return "";
  }
  return runtime_->GetIsolateName();
}

155
void Engine::OnOutputSurfaceCreated(const ftl::Closure& gpu_continuation) {
156
  blink::Threads::Gpu()->PostTask(gpu_continuation);
157 158
  have_surface_ = true;
  StartAnimatorIfPossible();
159
  if (runtime_)
160
    ScheduleFrame();
161 162
}

163
void Engine::OnOutputSurfaceDestroyed(const ftl::Closure& gpu_continuation) {
164 165
  have_surface_ = false;
  StopAnimator();
166
  blink::Threads::Gpu()->PostTask(gpu_continuation);
167 168
}

169 170
void Engine::SetViewportMetrics(const blink::ViewportMetrics& metrics) {
  viewport_metrics_ = metrics;
171 172
  if (runtime_)
    runtime_->SetViewportMetrics(viewport_metrics_);
173 174
}

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
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));
193 194
}

195 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
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 已提交
227
    ftl::RefPtr<blink::PlatformMessage> message) {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
  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 已提交
251
  if (runtime_)
252 253
    runtime_->SetLocale(language_code_, country_code_);
  return true;
A
Adam Barth 已提交
254 255
}

256
void Engine::DispatchPointerDataPacket(const PointerDataPacket& packet) {
257
  if (runtime_)
258
    runtime_->DispatchPointerDataPacket(packet);
259 260
}

261 262 263 264 265 266
void Engine::DispatchSemanticsAction(int id, blink::SemanticsAction action) {
  if (runtime_)
    runtime_->DispatchSemanticsAction(id, action);
}

void Engine::SetSemanticsEnabled(bool enabled) {
A
Adam Barth 已提交
267
  semantics_enabled_ = enabled;
268
  if (runtime_)
A
Adam Barth 已提交
269
    runtime_->SetSemanticsEnabled(semantics_enabled_);
270 271
}

272 273 274
void Engine::ConfigureAssetBundle(const std::string& path) {
  struct stat stat_result = {0};

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

279 280 281 282
  if (::stat(path.c_str(), &stat_result) != 0) {
    LOG(INFO) << "Could not configure asset bundle at path: " << path;
    return;
  }
283

284
  if (S_ISDIR(stat_result.st_mode)) {
A
Adam Barth 已提交
285 286
    directory_asset_bundle_ =
        std::make_unique<blink::DirectoryAssetBundle>(path);
287 288 289 290
    return;
  }

  if (S_ISREG(stat_result.st_mode)) {
A
Adam Barth 已提交
291
    asset_store_ = ftl::MakeRefCounted<blink::ZipAssetStore>(
A
Adam Barth 已提交
292
        blink::GetUnzipperProviderForPath(path));
293 294
    return;
  }
295 296
}

297 298 299 300 301
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 已提交
302
  runtime_->SetSemanticsEnabled(semantics_enabled_);
303 304
  if (pending_push_route_message_)
    runtime_->DispatchPlatformMessage(std::move(pending_push_route_message_));
305 306
}

307
void Engine::DidCreateMainIsolate(Dart_Isolate isolate) {
308
  if (asset_store_)
309
    blink::AssetFontSelector::Install(asset_store_);
310 311
}

312
void Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {}
313

314 315 316 317 318 319 320 321 322
void Engine::StopAnimator() {
  animator_->Stop();
}

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

323
void Engine::ScheduleFrame() {
A
Adam Barth 已提交
324 325 326
  animator_->RequestFrame();
}

327 328 329
void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
  if (!layer_tree)
    return;
330

331 332
  SkISize frame_size = SkISize::Make(viewport_metrics_.physical_width,
                                     viewport_metrics_.physical_height);
333 334 335 336
  if (frame_size.isEmpty())
    return;

  layer_tree->set_frame_size(frame_size);
337 338
  animator_->Render(std::move(layer_tree));
}
339

340 341 342 343 344 345 346
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));
      }));
}
347

348 349
void Engine::HandlePlatformMessage(
    ftl::RefPtr<blink::PlatformMessage> message) {
350
  if (message->channel() == kAssetChannel) {
A
Adam Barth 已提交
351 352 353
    HandleAssetPlatformMessage(std::move(message));
    return;
  }
354 355 356 357 358 359 360 361
  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 已提交
362 363 364 365 366 367 368 369 370
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;
371
  if (GetAssetAsBuffer(asset_name, &asset_data)) {
A
Adam Barth 已提交
372 373 374 375 376 377
    response->Complete(std::move(asset_data));
  } else {
    response->CompleteWithError();
  }
}

378 379 380 381 382 383 384
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));
}

385
}  // namespace shell