engine.cc 11.1 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/sky/shell/ui/engine.h"
6

7 8
#include <unistd.h>

9 10
#include <utility>

11 12
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/assets/zip_asset_bundle.h"
13 14
#include "flutter/glue/movable_wrapper.h"
#include "flutter/glue/trace_event.h"
15
#include "lib/ftl/files/path.h"
16
#include "mojo/public/cpp/application/connect.h"
17
#include "flutter/sky/engine/bindings/mojo_services.h"
18
#include "flutter/sky/engine/core/script/dart_controller.h"
19 20 21 22 23 24 25
#include "flutter/sky/engine/core/script/dart_init.h"
#include "flutter/sky/engine/core/script/ui_dart_state.h"
#include "flutter/sky/engine/public/platform/Platform.h"
#include "flutter/sky/engine/public/web/Sky.h"
#include "flutter/sky/shell/ui/animator.h"
#include "flutter/sky/shell/ui/flutter_font_selector.h"
#include "flutter/sky/shell/ui/platform_impl.h"
A
Adam Barth 已提交
26 27
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
28 29 30

namespace sky {
namespace shell {
31
namespace {
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
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;
}

49 50
PlatformImpl* g_platform_impl = nullptr;

51 52
}  // namespace

53
Engine::Config::Config() {}
A
Adam Barth 已提交
54

55
Engine::Config::~Config() {}
A
Adam Barth 已提交
56

F
Florian Loitsch 已提交
57
Engine::Engine(const Config& config, rasterizer::RasterizerPtr rasterizer)
58
    : config_(config),
F
Florian Loitsch 已提交
59
      animator_(new Animator(config, rasterizer.Pass(), this)),
60
      binding_(this),
61 62
      activity_running_(false),
      have_surface_(false),
63
      weak_factory_(this) {}
64

65
Engine::~Engine() {}
66

67
ftl::WeakPtr<Engine> Engine::GetWeakPtr() {
68 69 70
  return weak_factory_.GetWeakPtr();
}

71
void Engine::Init() {
72
  TRACE_EVENT0("flutter", "Engine::Init");
A
Adam Barth 已提交
73

74 75 76
  DCHECK(!g_platform_impl);
  g_platform_impl = new PlatformImpl();
  blink::initialize(g_platform_impl);
77 78
}

A
Adam Barth 已提交
79
void Engine::BeginFrame(ftl::TimePoint frame_time) {
80
  TRACE_EVENT0("flutter", "Engine::BeginFrame");
81 82
  if (sky_view_)
    sky_view_->BeginFrame(frame_time);
A
Adam Barth 已提交
83 84
}

85 86
void Engine::RunFromSource(const std::string& main,
                           const std::string& packages,
87
                           const std::string& bundle) {
88
  TRACE_EVENT0("flutter", "Engine::RunFromSource");
89 90 91
  std::string packages_path = packages;
  if (packages_path.empty())
    packages_path = FindPackagesPath(main);
92 93 94 95
  if (!bundle.empty())
    ConfigureDirectoryAssetBundle(bundle);
  ConfigureView(main);
  sky_view_->dart_controller()->RunFromSource(main, packages_path);
96 97
}

98
Dart_Port Engine::GetUIIsolateMainPort() {
99
  if (!sky_view_)
100 101 102 103
    return ILLEGAL_PORT;
  return sky_view_->GetMainPort();
}

104 105
void Engine::ConnectToEngine(mojo::InterfaceRequest<SkyEngine> request) {
  binding_.Bind(request.Pass());
106 107
}

108 109
void Engine::OnOutputSurfaceCreated(const ftl::Closure& gpu_continuation) {
  config_.gpu_task_runner->PostTask(gpu_continuation);
110 111
  have_surface_ = true;
  StartAnimatorIfPossible();
112
  if (sky_view_)
113
    ScheduleFrame();
114 115
}

116
void Engine::OnOutputSurfaceDestroyed(const ftl::Closure& gpu_continuation) {
117 118
  have_surface_ = false;
  StopAnimator();
119
  config_.gpu_task_runner->PostTask(gpu_continuation);
120 121
}

122 123 124
void Engine::SetServices(ServicesDataPtr services) {
  services_ = services.Pass();

A
Adam Barth 已提交
125
  if (services_->incoming_services) {
A
Adam Barth 已提交
126 127
    incoming_services_ =
        mojo::ServiceProviderPtr::Create(services_->incoming_services.Pass());
128
    service_provider_impl_.set_fallback_service_provider(
A
Adam Barth 已提交
129
        incoming_services_.get());
130 131
  }

A
Adam Barth 已提交
132
  if (services_->frame_scheduler) {
133
    animator_->Reset();
A
Adam Barth 已提交
134
    animator_->set_frame_scheduler(services_->frame_scheduler.Pass());
A
Adam Barth 已提交
135
  } else {
136
#if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_MACOSX)
A
Adam Barth 已提交
137 138
    vsync::VSyncProviderPtr vsync_provider;
    if (services_->shell) {
139 140 141
      // We bind and unbind our Shell here, since this is the only place we use
      // it in this class.
      auto shell = mojo::ShellPtr::Create(services_->shell.Pass());
A
Adam Barth 已提交
142 143
      mojo::ConnectToService(shell.get(), "mojo:vsync",
                             mojo::GetProxy(&vsync_provider));
144
      services_->shell = shell.Pass();
A
Adam Barth 已提交
145
    } else {
A
Adam Barth 已提交
146 147
      mojo::ConnectToService(incoming_services_.get(),
                             mojo::GetProxy(&vsync_provider));
A
Adam Barth 已提交
148
    }
149
    animator_->Reset();
A
Adam Barth 已提交
150
    animator_->set_vsync_provider(vsync_provider.Pass());
151
#endif
A
Adam Barth 已提交
152
  }
153 154
}

A
Adam Barth 已提交
155
void Engine::OnViewportMetricsChanged(ViewportMetricsPtr metrics) {
156
  viewport_metrics_ = metrics.Pass();
A
Adam Barth 已提交
157
  if (sky_view_)
158
    sky_view_->SetViewportMetrics(viewport_metrics_);
159 160
}

161
void Engine::OnLocaleChanged(const mojo::String& language_code,
162
                             const mojo::String& country_code) {
163 164 165 166 167 168
  language_code_ = language_code;
  country_code_ = country_code;
  if (sky_view_)
    sky_view_->SetLocale(language_code_, country_code_);
}

169
void Engine::OnPointerPacket(pointer::PointerPacketPtr packet) {
170
  TRACE_EVENT0("flutter", "Engine::OnPointerPacket");
171 172 173

  // Convert the pointers' x and y coordinates to logical pixels.
  for (auto it = packet->pointers.begin(); it != packet->pointers.end(); ++it) {
174 175
    (*it)->x /= viewport_metrics_->device_pixel_ratio;
    (*it)->y /= viewport_metrics_->device_pixel_ratio;
176 177 178 179
  }

  if (sky_view_)
    sky_view_->HandlePointerPacket(packet);
180 181
}

182
void Engine::RunFromSnapshotStream(
183
    const std::string& script_uri,
184
    mojo::ScopedDataPipeConsumerHandle snapshot) {
185
  TRACE_EVENT0("flutter", "Engine::RunFromSnapshotStream");
186 187 188 189 190 191 192 193
  ConfigureView(script_uri);
  snapshot_drainer_.reset(new glue::DrainDataPipeJob(
      std::move(snapshot), [this](std::vector<char> snapshot) {
        FTL_DCHECK(sky_view_);
        FTL_DCHECK(sky_view_->dart_controller());
        sky_view_->dart_controller()->RunFromSnapshot(
            reinterpret_cast<uint8_t*>(snapshot.data()), snapshot.size());
      }));
194 195
}

196
void Engine::ConfigureZipAssetBundle(const std::string& path) {
197
  asset_store_ = ftl::MakeRefCounted<blink::ZipAssetStore>(
198 199
      path, ftl::RefPtr<ftl::TaskRunner>(
                blink::Platform::current()->GetIOTaskRunner()));
200
  new blink::ZipAssetBundle(mojo::GetProxy(&root_bundle_), asset_store_);
201 202
}

203 204 205 206 207
void Engine::ConfigureDirectoryAssetBundle(const std::string& path) {
  new blink::DirectoryAssetBundle(
      mojo::GetProxy(&root_bundle_), path,
      ftl::RefPtr<ftl::TaskRunner>(
          blink::Platform::current()->GetIOTaskRunner()));
208 209
}

210 211
void Engine::ConfigureView(const std::string& script_uri) {
  snapshot_drainer_.reset();
212
  sky_view_ = blink::SkyView::Create(this);
213
  sky_view_->CreateView(std::move(script_uri));
214
  sky_view_->SetViewportMetrics(viewport_metrics_);
215
  sky_view_->SetLocale(language_code_, country_code_);
A
Adam Barth 已提交
216 217
  if (!initial_route_.empty())
    sky_view_->PushRoute(initial_route_);
218 219
}

220 221 222 223 224 225 226
void Engine::RunFromPrecompiledSnapshot(const mojo::String& bundle_path) {
  TRACE_EVENT0("flutter", "Engine::RunFromPrecompiledSnapshot");
  ConfigureZipAssetBundle(bundle_path.get());
  ConfigureView("http://localhost");
  sky_view_->dart_controller()->RunFromPrecompiledSnapshot();
}

227
void Engine::RunFromFile(const mojo::String& main,
228
                         const mojo::String& packages,
229
                         const mojo::String& bundle) {
230
  RunFromSource(main, packages, bundle);
231 232
}

233 234
void Engine::RunFromBundle(const mojo::String& script_uri,
                           const mojo::String& path) {
235
  TRACE_EVENT0("flutter", "Engine::RunFromBundle");
236
  ConfigureZipAssetBundle(path);
237 238 239 240
  mojo::DataPipe pipe;
  asset_store_->GetAsStream(blink::kSnapshotAssetKey,
                            std::move(pipe.producer_handle));
  RunFromSnapshotStream(script_uri, std::move(pipe.consumer_handle));
241 242
}

243 244
void Engine::RunFromBundleAndSnapshot(const mojo::String& script_uri,
                                      const mojo::String& bundle_path,
245 246
                                      const mojo::String& snapshot_path) {
  TRACE_EVENT0("flutter", "Engine::RunFromBundleAndSnapshot");
247 248

  ConfigureZipAssetBundle(bundle_path);
249

250
  asset_store_->AddOverlayFile(blink::kSnapshotAssetKey, snapshot_path);
251 252 253 254
  mojo::DataPipe pipe;
  asset_store_->GetAsStream(blink::kSnapshotAssetKey,
                            std::move(pipe.producer_handle));
  RunFromSnapshotStream(script_uri, std::move(pipe.consumer_handle));
255 256
}

A
Adam Barth 已提交
257 258 259 260 261 262 263 264 265 266 267 268
void Engine::PushRoute(const mojo::String& route) {
  if (sky_view_)
    sky_view_->PushRoute(route);
  else
    initial_route_ = route;
}

void Engine::PopRoute() {
  if (sky_view_)
    sky_view_->PopRoute();
}

269 270 271 272 273 274 275 276 277 278 279 280
void Engine::OnAppLifecycleStateChanged(sky::AppLifecycleState state) {
  switch (state) {
    case sky::AppLifecycleState::PAUSED:
      activity_running_ = false;
      StopAnimator();
      break;

    case sky::AppLifecycleState::RESUMED:
      activity_running_ = true;
      StartAnimatorIfPossible();
      break;
  }
281

282 283
  if (sky_view_)
    sky_view_->OnAppLifecycleStateChanged(state);
284 285
}

286 287 288 289 290
void Engine::DidCreateMainIsolate(Dart_Isolate isolate) {
  mojo::ServiceProviderPtr services_from_embedder;
  service_provider_bindings_.AddBinding(
      &service_provider_impl_, mojo::GetProxy(&services_from_embedder));

A
Adam Barth 已提交
291 292 293
  blink::MojoServices::Create(isolate, services_.Pass(),
                              services_from_embedder.Pass(),
                              root_bundle_.Pass());
J
Jason Simmons 已提交
294

295 296
  if (asset_store_)
    FlutterFontSelector::Install(asset_store_);
297 298
}

299 300
void Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {
  mojo::ServiceProviderPtr services_from_embedder;
301 302
  auto request = glue::WrapMovable(mojo::GetProxy(&services_from_embedder));
  ftl::WeakPtr<Engine> engine = weak_factory_.GetWeakPtr();
303
  blink::Platform::current()->GetUITaskRunner()->PostTask(
304 305 306 307 308 309
      [engine, request]() mutable {
        if (engine)
          engine->BindToServiceProvider(request.Unwrap());
      });
  blink::MojoServices::Create(isolate, nullptr,
                              std::move(services_from_embedder), nullptr);
310 311 312 313 314 315 316 317
}

void Engine::BindToServiceProvider(
    mojo::InterfaceRequest<mojo::ServiceProvider> request) {
  service_provider_bindings_.AddBinding(&service_provider_impl_,
                                        request.Pass());
}

318 319 320 321 322 323 324 325 326
void Engine::StopAnimator() {
  animator_->Stop();
}

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

327
void Engine::ScheduleFrame() {
A
Adam Barth 已提交
328 329 330
  animator_->RequestFrame();
}

331 332 333 334
void Engine::FlushRealTimeEvents() {
  animator_->FlushRealTimeEvents();
}

335 336 337 338 339
void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) {
  if (!layer_tree)
    return;
  if (viewport_metrics_) {
    layer_tree->set_scene_version(viewport_metrics_->scene_version);
A
Adam Barth 已提交
340 341
    layer_tree->set_frame_size(SkISize::Make(
        viewport_metrics_->physical_width, viewport_metrics_->physical_height));
342 343 344 345 346 347
  } else {
    layer_tree->set_scene_version(0);
    layer_tree->set_frame_size(SkISize::Make(0, 0));
  }
  animator_->Render(std::move(layer_tree));
}
348

349 350
}  // namespace shell
}  // namespace sky