window.cc 13.9 KB
Newer Older
M
Michael Goderbauer 已提交
1
// Copyright 2013 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "flutter/lib/ui/window/window.h"
6

7
#include "flutter/lib/ui/compositing/scene.h"
8
#include "flutter/lib/ui/ui_dart_state.h"
A
Adam Barth 已提交
9
#include "flutter/lib/ui/window/platform_message_response_dart.h"
10 11 12 13 14 15
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
16

17
namespace flutter {
18 19
namespace {

20
void DefaultRouteName(Dart_NativeArguments args) {
21 22
  std::string routeName =
      UIDartState::Current()->window()->client()->DefaultRouteName();
23
  Dart_SetReturnValue(args, tonic::StdStringToDart(routeName));
24 25
}

26
void ScheduleFrame(Dart_NativeArguments args) {
27
  UIDartState::Current()->window()->client()->ScheduleFrame();
28 29 30 31
}

void Render(Dart_NativeArguments args) {
  Dart_Handle exception = nullptr;
32 33
  Scene* scene =
      tonic::DartConverter<Scene*>::FromArguments(args, 1, exception);
34 35 36 37
  if (exception) {
    Dart_ThrowException(exception);
    return;
  }
38
  UIDartState::Current()->window()->client()->Render(scene);
39 40
}

41 42 43 44 45 46 47 48 49 50 51
void UpdateSemantics(Dart_NativeArguments args) {
  Dart_Handle exception = nullptr;
  SemanticsUpdate* update =
      tonic::DartConverter<SemanticsUpdate*>::FromArguments(args, 1, exception);
  if (exception) {
    Dart_ThrowException(exception);
    return;
  }
  UIDartState::Current()->window()->client()->UpdateSemantics(update);
}

52 53 54 55 56 57 58 59
void SetIsolateDebugName(Dart_NativeArguments args) {
  Dart_Handle exception = nullptr;
  const std::string name =
      tonic::DartConverter<std::string>::FromArguments(args, 1, exception);
  if (exception) {
    Dart_ThrowException(exception);
    return;
  }
60
  UIDartState::Current()->SetDebugName(name);
61 62
}

63 64 65 66 67 68
void SetNeedsReportTimings(Dart_NativeArguments args) {
  Dart_Handle exception = nullptr;
  bool value = tonic::DartConverter<bool>::FromArguments(args, 1, exception);
  UIDartState::Current()->window()->client()->SetNeedsReportTimings(value);
}

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
void ReportUnhandledException(Dart_NativeArguments args) {
  Dart_Handle exception = nullptr;

  auto error_name =
      tonic::DartConverter<std::string>::FromArguments(args, 0, exception);
  if (exception) {
    Dart_ThrowException(exception);
    return;
  }

  auto stack_trace =
      tonic::DartConverter<std::string>::FromArguments(args, 1, exception);
  if (exception) {
    Dart_ThrowException(exception);
    return;
  }

  UIDartState::Current()->ReportUnhandledException(std::move(error_name),
                                                   std::move(stack_trace));
}

90 91 92
Dart_Handle SendPlatformMessage(Dart_Handle window,
                                const std::string& name,
                                Dart_Handle callback,
93
                                Dart_Handle data_handle) {
94
  UIDartState* dart_state = UIDartState::Current();
A
Adam Barth 已提交
95

96
  if (!dart_state->window()) {
97 98
    return tonic::ToDart(
        "Platform messages can only be sent from the main isolate");
99 100
  }

101
  fml::RefPtr<PlatformMessageResponse> response;
A
Adam Barth 已提交
102
  if (!Dart_IsNull(callback)) {
103
    response = fml::MakeRefCounted<PlatformMessageResponseDart>(
104 105
        tonic::DartPersistentValue(dart_state, callback),
        dart_state->GetTaskRunners().GetUITaskRunner());
A
Adam Barth 已提交
106
  }
107
  if (Dart_IsNull(data_handle)) {
108
    dart_state->window()->client()->HandlePlatformMessage(
109
        fml::MakeRefCounted<PlatformMessage>(name, response));
110
  } else {
111
    tonic::DartByteData data(data_handle);
112
    const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
113
    dart_state->window()->client()->HandlePlatformMessage(
114
        fml::MakeRefCounted<PlatformMessage>(
115 116 117
            name, std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()),
            response));
  }
118 119

  return Dart_Null();
120 121 122 123 124 125
}

void _SendPlatformMessage(Dart_NativeArguments args) {
  tonic::DartCallStatic(&SendPlatformMessage, args);
}

A
Adam Barth 已提交
126 127 128
void RespondToPlatformMessage(Dart_Handle window,
                              int response_id,
                              const tonic::DartByteData& data) {
129 130 131 132
  if (Dart_IsNull(data.dart_handle())) {
    UIDartState::Current()->window()->CompletePlatformMessageEmptyResponse(
        response_id);
  } else {
133
    // TODO(engine): Avoid this copy.
134 135 136 137 138
    const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
    UIDartState::Current()->window()->CompletePlatformMessageResponse(
        response_id,
        std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()));
  }
A
Adam Barth 已提交
139 140 141 142 143 144
}

void _RespondToPlatformMessage(Dart_NativeArguments args) {
  tonic::DartCallStatic(&RespondToPlatformMessage, args);
}

145 146
}  // namespace

147
Dart_Handle ToByteData(const std::vector<uint8_t>& buffer) {
148 149
  Dart_Handle data_handle =
      Dart_NewTypedData(Dart_TypedData_kByteData, buffer.size());
150 151 152 153 154 155
  if (Dart_IsError(data_handle))
    return data_handle;

  Dart_TypedData_Type type;
  void* data = nullptr;
  intptr_t num_bytes = 0;
156
  FML_CHECK(!Dart_IsError(
157 158 159 160 161 162 163
      Dart_TypedDataAcquireData(data_handle, &type, &data, &num_bytes)));

  memcpy(data, buffer.data(), num_bytes);
  Dart_TypedDataReleaseData(data_handle);
  return data_handle;
}

A
Adam Barth 已提交
164
WindowClient::~WindowClient() {}
165

A
Adam Barth 已提交
166
Window::Window(WindowClient* client) : client_(client) {}
167

A
Adam Barth 已提交
168
Window::~Window() {}
169 170

void Window::DidCreateIsolate() {
171 172
  library_.Set(tonic::DartState::Current(),
               Dart_LookupLibrary(tonic::ToDart("dart:ui")));
173 174
}

175
void Window::UpdateWindowMetrics(const ViewportMetrics& metrics) {
176 177
  viewport_metrics_ = metrics;

178
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
179 180
  if (!dart_state)
    return;
181
  tonic::DartState::Scope scope(dart_state);
182 183 184 185 186 187
  tonic::LogIfError(tonic::DartInvokeField(
      library_.value(), "_updateWindowMetrics",
      {
          tonic::ToDart(metrics.device_pixel_ratio),
          tonic::ToDart(metrics.physical_width),
          tonic::ToDart(metrics.physical_height),
D
Dan Field 已提交
188
          tonic::ToDart(metrics.physical_depth),
189 190 191 192 193 194 195 196
          tonic::ToDart(metrics.physical_padding_top),
          tonic::ToDart(metrics.physical_padding_right),
          tonic::ToDart(metrics.physical_padding_bottom),
          tonic::ToDart(metrics.physical_padding_left),
          tonic::ToDart(metrics.physical_view_inset_top),
          tonic::ToDart(metrics.physical_view_inset_right),
          tonic::ToDart(metrics.physical_view_inset_bottom),
          tonic::ToDart(metrics.physical_view_inset_left),
197 198 199 200
          tonic::ToDart(metrics.physical_system_gesture_inset_top),
          tonic::ToDart(metrics.physical_system_gesture_inset_right),
          tonic::ToDart(metrics.physical_system_gesture_inset_bottom),
          tonic::ToDart(metrics.physical_system_gesture_inset_left),
201
      }));
202 203
}

204
void Window::UpdateLocales(const std::vector<std::string>& locales) {
205
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
206 207
  if (!dart_state)
    return;
208
  tonic::DartState::Scope scope(dart_state);
209 210 211 212 213
  tonic::LogIfError(tonic::DartInvokeField(
      library_.value(), "_updateLocales",
      {
          tonic::ToDart<std::vector<std::string>>(locales),
      }));
214 215
}

216
void Window::UpdateUserSettingsData(const std::string& data) {
217
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
218 219 220 221
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

222 223 224 225 226
  tonic::LogIfError(tonic::DartInvokeField(library_.value(),
                                           "_updateUserSettingsData",
                                           {
                                               tonic::StdStringToDart(data),
                                           }));
227 228
}

229 230 231 232 233 234 235 236 237 238 239 240
void Window::UpdateLifecycleState(const std::string& data) {
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);
  tonic::LogIfError(tonic::DartInvokeField(library_.value(),
                                           "_updateLifecycleState",
                                           {
                                               tonic::StdStringToDart(data),
                                           }));
}

241
void Window::UpdateSemanticsEnabled(bool enabled) {
242
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
243 244 245 246
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

247 248
  tonic::LogIfError(tonic::DartInvokeField(
      library_.value(), "_updateSemanticsEnabled", {tonic::ToDart(enabled)}));
249 250
}

251
void Window::UpdateAccessibilityFeatures(int32_t values) {
252
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
253 254 255 256
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

257 258 259
  tonic::LogIfError(tonic::DartInvokeField(library_.value(),
                                           "_updateAccessibilityFeatures",
                                           {tonic::ToDart(values)}));
260 261
}

262
void Window::DispatchPlatformMessage(fml::RefPtr<PlatformMessage> message) {
263
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
264 265 266 267
  if (!dart_state) {
    FML_DLOG(WARNING)
        << "Dropping platform message for lack of DartState on channel: "
        << message->channel();
268
    return;
269
  }
270
  tonic::DartState::Scope scope(dart_state);
271 272
  Dart_Handle data_handle =
      (message->hasData()) ? ToByteData(message->data()) : Dart_Null();
273 274 275 276
  if (Dart_IsError(data_handle)) {
    FML_DLOG(WARNING)
        << "Dropping platform message because of a Dart error on channel: "
        << message->channel();
277
    return;
278
  }
279

A
Adam Barth 已提交
280 281 282 283 284
  int response_id = 0;
  if (auto response = message->response()) {
    response_id = next_response_id_++;
    pending_responses_[response_id] = response;
  }
285

286 287 288 289
  tonic::LogIfError(
      tonic::DartInvokeField(library_.value(), "_dispatchPlatformMessage",
                             {tonic::ToDart(message->channel()), data_handle,
                              tonic::ToDart(response_id)}));
A
Adam Barth 已提交
290
}
291

A
Adam Barth 已提交
292
void Window::DispatchPointerDataPacket(const PointerDataPacket& packet) {
293
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
A
Adam Barth 已提交
294 295 296 297 298 299 300
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

  Dart_Handle data_handle = ToByteData(packet.data());
  if (Dart_IsError(data_handle))
    return;
301 302
  tonic::LogIfError(tonic::DartInvokeField(
      library_.value(), "_dispatchPointerDataPacket", {data_handle}));
303 304
}

305 306 307
void Window::DispatchSemanticsAction(int32_t id,
                                     SemanticsAction action,
                                     std::vector<uint8_t> args) {
308
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
309 310 311 312
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

313 314 315 316 317
  Dart_Handle args_handle = (args.empty()) ? Dart_Null() : ToByteData(args);

  if (Dart_IsError(args_handle))
    return;

318
  tonic::LogIfError(tonic::DartInvokeField(
319
      library_.value(), "_dispatchSemanticsAction",
320 321
      {tonic::ToDart(id), tonic::ToDart(static_cast<int32_t>(action)),
       args_handle}));
322 323
}

324
void Window::BeginFrame(fml::TimePoint frameTime) {
325
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
326 327
  if (!dart_state)
    return;
328
  tonic::DartState::Scope scope(dart_state);
329

330
  int64_t microseconds = (frameTime - fml::TimePoint()).ToMicroseconds();
331

332 333 334 335
  tonic::LogIfError(tonic::DartInvokeField(library_.value(), "_beginFrame",
                                           {
                                               Dart_NewInteger(microseconds),
                                           }));
336

337
  UIDartState::Current()->FlushMicrotasksNow();
338

339
  tonic::LogIfError(tonic::DartInvokeField(library_.value(), "_drawFrame", {}));
340 341
}

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
void Window::ReportTimings(std::vector<int64_t> timings) {
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

  Dart_Handle data_handle =
      Dart_NewTypedData(Dart_TypedData_kInt64, timings.size());

  Dart_TypedData_Type type;
  void* data = nullptr;
  intptr_t num_acquired = 0;
  FML_CHECK(!Dart_IsError(
      Dart_TypedDataAcquireData(data_handle, &type, &data, &num_acquired)));
  FML_DCHECK(num_acquired == static_cast<int>(timings.size()));

  memcpy(data, timings.data(), sizeof(int64_t) * timings.size());
  FML_CHECK(Dart_TypedDataReleaseData(data_handle));

  tonic::LogIfError(tonic::DartInvokeField(library_.value(), "_reportTimings",
                                           {
                                               data_handle,
                                           }));
}

367 368 369 370 371 372 373 374 375 376 377
void Window::CompletePlatformMessageEmptyResponse(int response_id) {
  if (!response_id)
    return;
  auto it = pending_responses_.find(response_id);
  if (it == pending_responses_.end())
    return;
  auto response = std::move(it->second);
  pending_responses_.erase(it);
  response->CompleteEmpty();
}

A
Adam Barth 已提交
378
void Window::CompletePlatformMessageResponse(int response_id,
379
                                             std::vector<uint8_t> data) {
A
Adam Barth 已提交
380 381 382 383 384 385 386
  if (!response_id)
    return;
  auto it = pending_responses_.find(response_id);
  if (it == pending_responses_.end())
    return;
  auto response = std::move(it->second);
  pending_responses_.erase(it);
387
  response->Complete(std::make_unique<fml::DataMapping>(std::move(data)));
A
Adam Barth 已提交
388 389
}

390
void Window::RegisterNatives(tonic::DartLibraryNatives* natives) {
391
  natives->Register({
392
      {"Window_defaultRouteName", DefaultRouteName, 1, true},
393 394
      {"Window_scheduleFrame", ScheduleFrame, 1, true},
      {"Window_sendPlatformMessage", _SendPlatformMessage, 4, true},
A
Adam Barth 已提交
395
      {"Window_respondToPlatformMessage", _RespondToPlatformMessage, 3, true},
396 397
      {"Window_render", Render, 2, true},
      {"Window_updateSemantics", UpdateSemantics, 2, true},
398
      {"Window_setIsolateDebugName", SetIsolateDebugName, 2, true},
399
      {"Window_reportUnhandledException", ReportUnhandledException, 2, true},
400
      {"Window_setNeedsReportTimings", SetNeedsReportTimings, 2, true},
401
  });
402 403
}

404
}  // namespace flutter