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

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

8
#include "flutter/lib/ui/compositing/scene.h"
9
#include "flutter/lib/ui/ui_dart_state.h"
A
Adam Barth 已提交
10
#include "flutter/lib/ui/window/platform_message_response_dart.h"
11 12 13 14 15 16
#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"
17

18
namespace flutter {
19 20
namespace {

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

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

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

45
void UpdateSemantics(Dart_NativeArguments args) {
46
  UIDartState::ThrowIfUIOperationsProhibited();
47 48 49 50 51 52 53 54 55 56
  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);
}

57
void SetIsolateDebugName(Dart_NativeArguments args) {
58
  UIDartState::ThrowIfUIOperationsProhibited();
59 60 61 62 63 64 65
  Dart_Handle exception = nullptr;
  const std::string name =
      tonic::DartConverter<std::string>::FromArguments(args, 1, exception);
  if (exception) {
    Dart_ThrowException(exception);
    return;
  }
66
  UIDartState::Current()->SetDebugName(name);
67 68
}

69
void SetNeedsReportTimings(Dart_NativeArguments args) {
70
  UIDartState::ThrowIfUIOperationsProhibited();
71 72 73 74 75
  Dart_Handle exception = nullptr;
  bool value = tonic::DartConverter<bool>::FromArguments(args, 1, exception);
  UIDartState::Current()->window()->client()->SetNeedsReportTimings(value);
}

76
void ReportUnhandledException(Dart_NativeArguments args) {
77 78
  UIDartState::ThrowIfUIOperationsProhibited();

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  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));
}

99 100 101
Dart_Handle SendPlatformMessage(Dart_Handle window,
                                const std::string& name,
                                Dart_Handle callback,
102
                                Dart_Handle data_handle) {
103
  UIDartState* dart_state = UIDartState::Current();
A
Adam Barth 已提交
104

105
  if (!dart_state->window()) {
106 107
    return tonic::ToDart(
        "Platform messages can only be sent from the main isolate");
108 109
  }

110
  fml::RefPtr<PlatformMessageResponse> response;
A
Adam Barth 已提交
111
  if (!Dart_IsNull(callback)) {
112
    response = fml::MakeRefCounted<PlatformMessageResponseDart>(
113 114
        tonic::DartPersistentValue(dart_state, callback),
        dart_state->GetTaskRunners().GetUITaskRunner());
A
Adam Barth 已提交
115
  }
116
  if (Dart_IsNull(data_handle)) {
117
    dart_state->window()->client()->HandlePlatformMessage(
118
        fml::MakeRefCounted<PlatformMessage>(name, response));
119
  } else {
120
    tonic::DartByteData data(data_handle);
121
    const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
122
    dart_state->window()->client()->HandlePlatformMessage(
123
        fml::MakeRefCounted<PlatformMessage>(
124 125 126
            name, std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()),
            response));
  }
127 128

  return Dart_Null();
129 130 131 132 133 134
}

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

A
Adam Barth 已提交
135 136 137
void RespondToPlatformMessage(Dart_Handle window,
                              int response_id,
                              const tonic::DartByteData& data) {
138 139 140 141
  if (Dart_IsNull(data.dart_handle())) {
    UIDartState::Current()->window()->CompletePlatformMessageEmptyResponse(
        response_id);
  } else {
142
    // TODO(engine): Avoid this copy.
143 144 145 146 147
    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 已提交
148 149 150 151 152 153
}

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

154
void GetPersistentIsolateData(Dart_NativeArguments args) {
155 156
  UIDartState::ThrowIfUIOperationsProhibited();

157 158 159 160 161 162 163 164 165 166 167 168 169
  auto persistent_isolate_data =
      UIDartState::Current()->window()->client()->GetPersistentIsolateData();

  if (!persistent_isolate_data) {
    Dart_SetReturnValue(args, Dart_Null());
    return;
  }

  Dart_SetReturnValue(
      args, tonic::DartByteData::Create(persistent_isolate_data->GetMapping(),
                                        persistent_isolate_data->GetSize()));
}

170
Dart_Handle ToByteData(const std::vector<uint8_t>& buffer) {
171
  return tonic::DartByteData::Create(buffer.data(), buffer.size());
172 173
}

174 175
}  // namespace

A
Adam Barth 已提交
176
WindowClient::~WindowClient() {}
177

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

A
Adam Barth 已提交
180
Window::~Window() {}
181 182

void Window::DidCreateIsolate() {
183 184
  library_.Set(tonic::DartState::Current(),
               Dart_LookupLibrary(tonic::ToDart("dart:ui")));
185 186
}

187
void Window::UpdateWindowMetrics(const ViewportMetrics& metrics) {
188 189
  viewport_metrics_ = metrics;

190
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
191 192
  if (!dart_state)
    return;
193
  tonic::DartState::Scope scope(dart_state);
194 195 196 197 198 199
  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 已提交
200
          tonic::ToDart(metrics.physical_depth),
201 202 203 204 205 206 207 208
          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),
209 210 211 212
          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),
213
      }));
214 215
}

216
void Window::UpdateLocales(const std::vector<std::string>& locales) {
217
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
218 219
  if (!dart_state)
    return;
220
  tonic::DartState::Scope scope(dart_state);
221 222 223 224 225
  tonic::LogIfError(tonic::DartInvokeField(
      library_.value(), "_updateLocales",
      {
          tonic::ToDart<std::vector<std::string>>(locales),
      }));
226 227
}

228
void Window::UpdateUserSettingsData(const std::string& data) {
229
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
230 231 232 233
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

234 235 236 237 238
  tonic::LogIfError(tonic::DartInvokeField(library_.value(),
                                           "_updateUserSettingsData",
                                           {
                                               tonic::StdStringToDart(data),
                                           }));
239 240
}

241 242 243 244 245 246 247 248 249 250 251 252
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),
                                           }));
}

253
void Window::UpdateSemanticsEnabled(bool enabled) {
254
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
255 256 257
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);
258
  UIDartState::ThrowIfUIOperationsProhibited();
259

260 261
  tonic::LogIfError(tonic::DartInvokeField(
      library_.value(), "_updateSemanticsEnabled", {tonic::ToDart(enabled)}));
262 263
}

264
void Window::UpdateAccessibilityFeatures(int32_t values) {
265
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
266 267 268 269
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

270 271 272
  tonic::LogIfError(tonic::DartInvokeField(library_.value(),
                                           "_updateAccessibilityFeatures",
                                           {tonic::ToDart(values)}));
273 274
}

275
void Window::DispatchPlatformMessage(fml::RefPtr<PlatformMessage> message) {
276
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
277 278 279 280
  if (!dart_state) {
    FML_DLOG(WARNING)
        << "Dropping platform message for lack of DartState on channel: "
        << message->channel();
281
    return;
282
  }
283
  tonic::DartState::Scope scope(dart_state);
284 285
  Dart_Handle data_handle =
      (message->hasData()) ? ToByteData(message->data()) : Dart_Null();
286 287 288 289
  if (Dart_IsError(data_handle)) {
    FML_DLOG(WARNING)
        << "Dropping platform message because of a Dart error on channel: "
        << message->channel();
290
    return;
291
  }
292

A
Adam Barth 已提交
293 294 295 296 297
  int response_id = 0;
  if (auto response = message->response()) {
    response_id = next_response_id_++;
    pending_responses_[response_id] = response;
  }
298

299 300 301 302
  tonic::LogIfError(
      tonic::DartInvokeField(library_.value(), "_dispatchPlatformMessage",
                             {tonic::ToDart(message->channel()), data_handle,
                              tonic::ToDart(response_id)}));
A
Adam Barth 已提交
303
}
304

A
Adam Barth 已提交
305
void Window::DispatchPointerDataPacket(const PointerDataPacket& packet) {
306
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
A
Adam Barth 已提交
307 308 309 310 311 312 313
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

  Dart_Handle data_handle = ToByteData(packet.data());
  if (Dart_IsError(data_handle))
    return;
314 315
  tonic::LogIfError(tonic::DartInvokeField(
      library_.value(), "_dispatchPointerDataPacket", {data_handle}));
316 317
}

318 319 320
void Window::DispatchSemanticsAction(int32_t id,
                                     SemanticsAction action,
                                     std::vector<uint8_t> args) {
321
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
322 323 324 325
  if (!dart_state)
    return;
  tonic::DartState::Scope scope(dart_state);

326 327 328 329 330
  Dart_Handle args_handle = (args.empty()) ? Dart_Null() : ToByteData(args);

  if (Dart_IsError(args_handle))
    return;

331
  tonic::LogIfError(tonic::DartInvokeField(
332
      library_.value(), "_dispatchSemanticsAction",
333 334
      {tonic::ToDart(id), tonic::ToDart(static_cast<int32_t>(action)),
       args_handle}));
335 336
}

337
void Window::BeginFrame(fml::TimePoint frameTime) {
338
  std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
339 340
  if (!dart_state)
    return;
341
  tonic::DartState::Scope scope(dart_state);
342

343
  int64_t microseconds = (frameTime - fml::TimePoint()).ToMicroseconds();
344

345 346 347 348
  tonic::LogIfError(tonic::DartInvokeField(library_.value(), "_beginFrame",
                                           {
                                               Dart_NewInteger(microseconds),
                                           }));
349

350
  UIDartState::Current()->FlushMicrotasksNow();
351

352
  tonic::LogIfError(tonic::DartInvokeField(library_.value(), "_drawFrame", {}));
353 354
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
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,
                                           }));
}

380 381 382 383 384 385 386 387 388 389 390
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 已提交
391
void Window::CompletePlatformMessageResponse(int response_id,
392
                                             std::vector<uint8_t> data) {
A
Adam Barth 已提交
393 394 395 396 397 398 399
  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);
400
  response->Complete(std::make_unique<fml::DataMapping>(std::move(data)));
A
Adam Barth 已提交
401 402
}

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
Dart_Handle ComputePlatformResolvedLocale(Dart_Handle supportedLocalesHandle) {
  std::vector<std::string> supportedLocales =
      tonic::DartConverter<std::vector<std::string>>::FromDart(
          supportedLocalesHandle);

  std::vector<std::string> results =
      *UIDartState::Current()
           ->window()
           ->client()
           ->ComputePlatformResolvedLocale(supportedLocales);

  return tonic::DartConverter<std::vector<std::string>>::ToDart(results);
}

static void _ComputePlatformResolvedLocale(Dart_NativeArguments args) {
  UIDartState::ThrowIfUIOperationsProhibited();
  Dart_Handle result =
      ComputePlatformResolvedLocale(Dart_GetNativeArgument(args, 1));
  Dart_SetReturnValue(args, result);
}

424
void Window::RegisterNatives(tonic::DartLibraryNatives* natives) {
425
  natives->Register({
426
      {"Window_defaultRouteName", DefaultRouteName, 1, true},
427 428
      {"Window_scheduleFrame", ScheduleFrame, 1, true},
      {"Window_sendPlatformMessage", _SendPlatformMessage, 4, true},
A
Adam Barth 已提交
429
      {"Window_respondToPlatformMessage", _RespondToPlatformMessage, 3, true},
430 431
      {"Window_render", Render, 2, true},
      {"Window_updateSemantics", UpdateSemantics, 2, true},
432
      {"Window_setIsolateDebugName", SetIsolateDebugName, 2, true},
433
      {"Window_reportUnhandledException", ReportUnhandledException, 2, true},
434
      {"Window_setNeedsReportTimings", SetNeedsReportTimings, 2, true},
435
      {"Window_getPersistentIsolateData", GetPersistentIsolateData, 1, true},
436 437
      {"Window_computePlatformResolvedLocale", _ComputePlatformResolvedLocale,
       2, true},
438
  });
439 440
}

441
}  // namespace flutter