diff --git a/engine/src/flutter/common/BUILD.gn b/engine/src/flutter/common/BUILD.gn index 8ae4a18e3d..43f04a8cb0 100644 --- a/engine/src/flutter/common/BUILD.gn +++ b/engine/src/flutter/common/BUILD.gn @@ -2,6 +2,12 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("config.gni") + +config("flutter_config") { + defines = feature_defines_list +} + source_set("common") { sources = [ "settings.cc", @@ -13,4 +19,8 @@ source_set("common") { deps = [ "//lib/ftl", ] + + public_configs = [ + ":flutter_config" + ] } diff --git a/engine/src/flutter/common/config.gni b/engine/src/flutter/common/config.gni new file mode 100644 index 0000000000..0f50113027 --- /dev/null +++ b/engine/src/flutter/common/config.gni @@ -0,0 +1,59 @@ +# Copyright 2014 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. + +if (is_android) { + import("//build/config/android/config.gni") +} + +if (target_cpu == "arm" || target_cpu == "arm64") { + import("//build/config/arm.gni") +} + +declare_args() { + # Enable asserts, even in release builds. + flutter_asserts_always_on = false + + # Enable ahead-of-time compilation on platforms where AOT is optional. + flutter_aot = false + + # The runtime mode ("debug", "profile", or "release") + flutter_runtime_mode = "debug" +} + +# feature_defines_list --------------------------------------------------------- + +feature_defines_list = [ + "FLUTTER_RUNTIME_MODE_DEBUG=1", + "FLUTTER_RUNTIME_MODE_PROFILE=2", + "FLUTTER_RUNTIME_MODE_RELEASE=3", +] + +if (flutter_runtime_mode == "debug") { + feature_defines_list += [ "FLUTTER_RUNTIME_MODE=1" ] +} else if (flutter_runtime_mode == "profile") { + feature_defines_list += [ "FLUTTER_RUNTIME_MODE=2" ] +} else if (flutter_runtime_mode == "release") { + feature_defines_list += [ "FLUTTER_RUNTIME_MODE=3" ] +} else { + feature_defines_list += [ "FLUTTER_RUNTIME_MODE=0" ] +} + +if (is_debug) { + # TODO(GYP) this should also be set when release_valgrind_build is set, + # but we don't have that flag in the GN build yet. + feature_defines_list += [ "WTF_USE_DYNAMIC_ANNOTATIONS=1" ] +} + +if (!is_mac) { + # Mac OS X has not implemented support for ENABLE(OPENTYPE_VERTICAL) yet. + feature_defines_list += [ "ENABLE_OPENTYPE_VERTICAL=1" ] +} + +if (flutter_asserts_always_on) { + feature_defines_list += [ "ENABLE_ASSERT=1" ] +} + +if (flutter_aot) { + feature_defines_list += [ "FLUTTER_AOT=1" ] +} diff --git a/engine/src/flutter/lib/ui/BUILD.gn b/engine/src/flutter/lib/ui/BUILD.gn index b6806dd6b1..d9f0c7e246 100644 --- a/engine/src/flutter/lib/ui/BUILD.gn +++ b/engine/src/flutter/lib/ui/BUILD.gn @@ -10,6 +10,10 @@ source_set("ui") { "compositing/scene.h", "dart_runtime_hooks.cc", "dart_runtime_hooks.h", + "dart_ui.cc", + "dart_ui.h", + "mojo_services.cc", + "mojo_services.h", "painting/canvas.cc", "painting/canvas.h", "painting/gradient.cc", @@ -40,6 +44,16 @@ source_set("ui") { "painting/rrect.h", "painting/shader.cc", "painting/shader.h", + "text/paragraph_builder.cc", + "text/paragraph_builder.h", + "text/paragraph.cc", + "text/paragraph.h", + "text/text_box.cc", + "text/text_box.h", + "ui_dart_state.cc", + "ui_dart_state.h", + "window/window.cc", + "window/window.h", ] deps = [ @@ -47,8 +61,22 @@ source_set("ui") { "//flutter/common", "//flutter/flow", "//flutter/glue", + "//flutter/services/engine:interfaces", + "//flutter/services/pointer:interfaces", "//flutter/skia", + "//flutter/sky/engine", "//lib/tonic", "//lib/tonic/mojo", + "//mojo/public/cpp/application", + "//mojo/public/cpp/bindings", + "//mojo/public/interfaces/application", + "//mojo/services/asset_bundle/interfaces", ] + + if (is_android) { + deps += [ + # TODO(abarth): In principle, these libraries should be fully independent. + "//flutter/lib/jni", + ] + } } diff --git a/engine/src/flutter/lib/ui/dart_ui.cc b/engine/src/flutter/lib/ui/dart_ui.cc new file mode 100644 index 0000000000..39c3357534 --- /dev/null +++ b/engine/src/flutter/lib/ui/dart_ui.cc @@ -0,0 +1,75 @@ +// Copyright 2014 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. + +#include "flutter/lib/ui/dart_ui.h" + +#include "flutter/lib/ui/compositing/scene_builder.h" +#include "flutter/lib/ui/compositing/scene.h" +#include "flutter/lib/ui/dart_runtime_hooks.h" +#include "flutter/lib/ui/mojo_services.h" +#include "flutter/lib/ui/painting/canvas.h" +#include "flutter/lib/ui/painting/gradient.h" +#include "flutter/lib/ui/painting/image_decoding.h" +#include "flutter/lib/ui/painting/image_filter.h" +#include "flutter/lib/ui/painting/image_shader.h" +#include "flutter/lib/ui/painting/image.h" +#include "flutter/lib/ui/painting/mask_filter.h" +#include "flutter/lib/ui/painting/path.h" +#include "flutter/lib/ui/painting/picture_recorder.h" +#include "flutter/lib/ui/painting/picture.h" +#include "flutter/lib/ui/text/paragraph_builder.h" +#include "flutter/lib/ui/text/paragraph.h" +#include "flutter/lib/ui/window/window.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/logging/dart_error.h" + +using tonic::ToDart; + +namespace blink { +namespace { + +static tonic::DartLibraryNatives* g_natives; + +Dart_NativeFunction GetNativeFunction(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope); +} + +const uint8_t* GetSymbol(Dart_NativeFunction native_function) { + return g_natives->GetSymbol(native_function); +} + +} // namespace + +void DartUI::InitForGlobal() { + if (!g_natives) { + g_natives = new tonic::DartLibraryNatives(); + Canvas::RegisterNatives(g_natives); + CanvasGradient::RegisterNatives(g_natives); + CanvasImage::RegisterNatives(g_natives); + CanvasPath::RegisterNatives(g_natives); + DartRuntimeHooks::RegisterNatives(g_natives); + ImageDecoding::RegisterNatives(g_natives); + ImageFilter::RegisterNatives(g_natives); + ImageShader::RegisterNatives(g_natives); + MaskFilter::RegisterNatives(g_natives); + MojoServices::RegisterNatives(g_natives); + Paragraph::RegisterNatives(g_natives); + ParagraphBuilder::RegisterNatives(g_natives); + Picture::RegisterNatives(g_natives); + PictureRecorder::RegisterNatives(g_natives); + Scene::RegisterNatives(g_natives); + SceneBuilder::RegisterNatives(g_natives); + Window::RegisterNatives(g_natives); + } +} + +void DartUI::InitForIsolate() { + DCHECK(g_natives); + DART_CHECK_VALID(Dart_SetNativeResolver(Dart_LookupLibrary(ToDart("dart:ui")), + GetNativeFunction, GetSymbol)); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/dart_ui.h b/engine/src/flutter/lib/ui/dart_ui.h new file mode 100644 index 0000000000..6460444960 --- /dev/null +++ b/engine/src/flutter/lib/ui/dart_ui.h @@ -0,0 +1,23 @@ +// Copyright 2014 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. + +#ifndef FLUTTER_LIB_UI_DART_UI_H_ +#define FLUTTER_LIB_UI_DART_UI_H_ + +#include "lib/ftl/macros.h" + +namespace blink { + +class DartUI { + public: + static void InitForGlobal(); + static void InitForIsolate(); + + private: + FTL_DISALLOW_IMPLICIT_CONSTRUCTORS(DartUI); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_DART_UI_H_ diff --git a/engine/src/flutter/lib/ui/mojo_services.cc b/engine/src/flutter/lib/ui/mojo_services.cc new file mode 100644 index 0000000000..381a24572e --- /dev/null +++ b/engine/src/flutter/lib/ui/mojo_services.cc @@ -0,0 +1,118 @@ +// Copyright 2016 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. + +#include "flutter/lib/ui/mojo_services.h" + +#include "flutter/lib/ui/ui_dart_state.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "lib/tonic/dart_state.h" +#include "lib/tonic/logging/dart_error.h" +#include "mojo/public/cpp/application/connect.h" +#include "mojo/public/cpp/bindings/array.h" + +using tonic::DartState; + +namespace blink { +namespace { + +MojoServices* GetMojoServices() { + return static_cast(DartState::Current())->mojo_services(); +} + +void DartTakeRootBundle(Dart_NativeArguments args) { + Dart_SetIntegerReturnValue(args, GetMojoServices()->TakeRootBundle()); +} + +void DartTakeIncomingServices(Dart_NativeArguments args) { + Dart_SetIntegerReturnValue(args, GetMojoServices()->TakeIncomingServices()); +} + +void DartTakeOutgoingServices(Dart_NativeArguments args) { + Dart_SetIntegerReturnValue(args, GetMojoServices()->TakeOutgoingServices()); +} + +void DartTakeShell(Dart_NativeArguments args) { + Dart_SetIntegerReturnValue(args, GetMojoServices()->TakeShell()); +} + +void DartTakeView(Dart_NativeArguments args) { + Dart_SetIntegerReturnValue(args, GetMojoServices()->TakeView()); +} + +void DartTakeViewServices(Dart_NativeArguments args) { + Dart_SetIntegerReturnValue(args, GetMojoServices()->TakeViewServices()); +} + +} // namespace + +void MojoServices::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({ + {"MojoServices_takeRootBundle", DartTakeRootBundle, 0, true}, + {"MojoServices_takeIncomingServices", DartTakeIncomingServices, 0, true}, + {"MojoServices_takeOutgoingServices", DartTakeOutgoingServices, 0, true}, + {"MojoServices_takeShell", DartTakeShell, 0, true}, + {"MojoServices_takeView", DartTakeView, 0, true}, + {"MojoServices_takeViewServices", DartTakeViewServices, 0, true}, + }); +} + +void MojoServices::Create(Dart_Isolate isolate, + sky::ServicesDataPtr services, + mojo::ServiceProviderPtr incoming_services, + mojo::asset_bundle::AssetBundlePtr root_bundle) { + UIDartState* state = static_cast(DartState::From(isolate)); + state->set_mojo_services(std::unique_ptr(new MojoServices( + services.Pass(), incoming_services.Pass(), root_bundle.Pass()))); +} + +MojoServices::MojoServices(sky::ServicesDataPtr services, + mojo::ServiceProviderPtr incoming_services, + mojo::asset_bundle::AssetBundlePtr root_bundle) + : services_(services.Pass()), + root_bundle_(root_bundle.Pass()), + incoming_services_(incoming_services.Pass()) { + if (services_ && services_->outgoing_services.is_pending()) { + outgoing_services_ = services_->outgoing_services.Pass(); + } else { + outgoing_services_ = GetProxy(&services_from_dart_); + } +} + +MojoServices::~MojoServices() {} + +int MojoServices::TakeRootBundle() { + return root_bundle_.PassInterfaceHandle().PassHandle().release().value(); +} + +int MojoServices::TakeIncomingServices() { + return incoming_services_.PassInterfaceHandle() + .PassHandle() + .release() + .value(); +} + +int MojoServices::TakeOutgoingServices() { + return outgoing_services_.PassMessagePipe().release().value(); +} + +int MojoServices::TakeShell() { + if (services_) + return services_->shell.PassHandle().release().value(); + return MOJO_HANDLE_INVALID; +} + +int MojoServices::TakeView() { + if (services_) + return services_->view.PassHandle().release().value(); + return MOJO_HANDLE_INVALID; +} + +int MojoServices::TakeViewServices() { + if (services_) + return services_->view_services.PassHandle().release().value(); + return MOJO_HANDLE_INVALID; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/mojo_services.h b/engine/src/flutter/lib/ui/mojo_services.h new file mode 100644 index 0000000000..8865494920 --- /dev/null +++ b/engine/src/flutter/lib/ui/mojo_services.h @@ -0,0 +1,63 @@ +// Copyright 2016 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. + +#ifndef SKY_ENGINE_BINDINGS_MOJO_SERVICES_H_ +#define SKY_ENGINE_BINDINGS_MOJO_SERVICES_H_ + +#include "dart/runtime/include/dart_api.h" +#include "lib/ftl/macros.h" +#include "mojo/public/cpp/application/service_provider_impl.h" +#include "mojo/public/interfaces/application/service_provider.mojom.h" +#include "mojo/services/asset_bundle/interfaces/asset_bundle.mojom.h" +#include "flutter/services/engine/sky_engine.mojom.h" + +namespace mojo { +class ApplicationConnection; +} + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class MojoServices { + public: + ~MojoServices(); + + static void Create(Dart_Isolate isolate, + sky::ServicesDataPtr services, + mojo::ServiceProviderPtr incoming_services, + mojo::asset_bundle::AssetBundlePtr root_bundle); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + int TakeRootBundle(); + int TakeIncomingServices(); + int TakeOutgoingServices(); + int TakeShell(); + int TakeView(); + int TakeViewServices(); + + private: + explicit MojoServices(sky::ServicesDataPtr services, + mojo::ServiceProviderPtr incoming_services, + mojo::asset_bundle::AssetBundlePtr root_bundle); + + sky::ServicesDataPtr services_; + + mojo::asset_bundle::AssetBundlePtr root_bundle_; + mojo::ServiceProviderPtr incoming_services_; + mojo::InterfaceRequest outgoing_services_; + + // We need to hold this object to work around + // https://github.com/domokit/mojo/issues/536 + mojo::ServiceProviderPtr services_from_dart_; + + FTL_DISALLOW_COPY_AND_ASSIGN(MojoServices); +}; + +} // namespace blink + +#endif // SKY_ENGINE_BINDINGS_MOJO_SERVICES_H_ diff --git a/engine/src/flutter/lib/ui/text/paragraph.cc b/engine/src/flutter/lib/ui/text/paragraph.cc new file mode 100644 index 0000000000..6b7dc3a146 --- /dev/null +++ b/engine/src/flutter/lib/ui/text/paragraph.cc @@ -0,0 +1,184 @@ +// 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. + +#include "flutter/lib/ui/text/paragraph.h" + +#include "flutter/common/threads.h" +#include "flutter/sky/engine/core/rendering/PaintInfo.h" +#include "flutter/sky/engine/core/rendering/RenderText.h" +#include "flutter/sky/engine/core/rendering/style/RenderStyle.h" +#include "flutter/sky/engine/platform/fonts/FontCache.h" +#include "flutter/sky/engine/platform/graphics/GraphicsContext.h" +#include "flutter/sky/engine/platform/text/TextBoundaries.h" +#include "lib/ftl/tasks/task_runner.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/dart_library_natives.h" + +using tonic::ToDart; + +namespace blink { + +IMPLEMENT_WRAPPERTYPEINFO(ui, Paragraph); + +#define FOR_EACH_BINDING(V) \ + V(Paragraph, width) \ + V(Paragraph, height) \ + V(Paragraph, minIntrinsicWidth) \ + V(Paragraph, maxIntrinsicWidth) \ + V(Paragraph, alphabeticBaseline) \ + V(Paragraph, ideographicBaseline) \ + V(Paragraph, layout) \ + V(Paragraph, paint) \ + V(Paragraph, getWordBoundary) \ + V(Paragraph, getRectsForRange) \ + V(Paragraph, getPositionForOffset) + +DART_BIND_ALL(Paragraph, FOR_EACH_BINDING) + +Paragraph::Paragraph(PassOwnPtr renderView) + : m_renderView(renderView) {} + +Paragraph::~Paragraph() { + PassOwnPtr renderView = m_renderView.release(); + Threads::UI()->PostTask( + [renderView]() { /* renderView's destructor runs. */ }); +} + +double Paragraph::width() { + return firstChildBox()->width(); +} + +double Paragraph::height() { + return firstChildBox()->height(); +} + +double Paragraph::minIntrinsicWidth() { + return firstChildBox()->minPreferredLogicalWidth(); +} + +double Paragraph::maxIntrinsicWidth() { + return firstChildBox()->maxPreferredLogicalWidth(); +} + +double Paragraph::alphabeticBaseline() { + return firstChildBox()->firstLineBoxBaseline( + FontBaselineOrAuto(AlphabeticBaseline)); +} + +double Paragraph::ideographicBaseline() { + return firstChildBox()->firstLineBoxBaseline( + FontBaselineOrAuto(IdeographicBaseline)); +} + +void Paragraph::layout(double width) { + FontCachePurgePreventer fontCachePurgePreventer; + + int maxWidth = LayoutUnit(width); // Handles infinity properly. + m_renderView->setFrameViewSize(IntSize(maxWidth, intMaxForLayoutUnit)); + m_renderView->layout(); +} + +void Paragraph::paint(Canvas* canvas, double x, double y) { + SkCanvas* skCanvas = canvas->canvas(); + if (!skCanvas) + return; + + FontCachePurgePreventer fontCachePurgePreventer; + + // Very simplified painting to allow painting an arbitrary (layer-less) + // subtree. + RenderBox* box = firstChildBox(); + skCanvas->translate(x, y); + + GraphicsContext context(skCanvas); + Vector layers; + LayoutRect bounds = box->absoluteBoundingBoxRect(); + FTL_DCHECK(bounds.x() == 0 && bounds.y() == 0); + PaintInfo paintInfo(&context, enclosingIntRect(bounds), box); + box->paint(paintInfo, LayoutPoint(), layers); + // Note we're ignoring any layers encountered. + // TODO(abarth): Remove the concept of RenderLayers. + + skCanvas->translate(-x, -y); +} + +std::vector Paragraph::getRectsForRange(unsigned start, unsigned end) { + if (end <= start || start == end) + return std::vector(); + + unsigned offset = 0; + std::vector boxes; + for (RenderObject* object = m_renderView.get(); object; + object = object->nextInPreOrder()) { + if (!object->isText()) + continue; + RenderText* text = toRenderText(object); + unsigned length = text->textLength(); + if (offset + length > start) { + unsigned startOffset = offset > start ? 0 : start - offset; + unsigned endOffset = end - offset; + text->appendAbsoluteTextBoxesForRange(boxes, startOffset, endOffset); + } + offset += length; + if (offset >= end) + break; + } + + return boxes; +} + +int Paragraph::absoluteOffsetForPosition(const PositionWithAffinity& position) { + FTL_DCHECK(position.renderer()); + unsigned offset = 0; + for (RenderObject* object = m_renderView.get(); object; + object = object->nextInPreOrder()) { + if (object == position.renderer()) + return offset + position.offset(); + if (object->isText()) { + RenderText* text = toRenderText(object); + offset += text->textLength(); + } + } + FTL_DCHECK(false); + return 0; +} + +Dart_Handle Paragraph::getPositionForOffset(double dx, double dy) { + LayoutPoint point(dx, dy); + PositionWithAffinity position = m_renderView->positionForPoint(point); + Dart_Handle result = Dart_NewList(2); + Dart_ListSetAt(result, 0, ToDart(absoluteOffsetForPosition(position))); + Dart_ListSetAt(result, 1, ToDart(static_cast(position.affinity()))); + return result; +} + +Dart_Handle Paragraph::getWordBoundary(unsigned offset) { + String text; + int start = 0, end = 0; + + for (RenderObject* object = m_renderView.get(); object; + object = object->nextInPreOrder()) { + if (!object->isText()) + continue; + RenderText* renderText = toRenderText(object); + text.append(renderText->text()); + } + + TextBreakIterator* it = wordBreakIterator(text, 0, text.length()); + if (it) { + end = it->following(offset); + if (end < 0) + end = it->last(); + start = it->previous(); + } + + Dart_Handle result = Dart_NewList(2); + Dart_ListSetAt(result, 0, ToDart(start)); + Dart_ListSetAt(result, 1, ToDart(end)); + return result; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/text/paragraph.h b/engine/src/flutter/lib/ui/text/paragraph.h new file mode 100644 index 0000000000..be4e555ec8 --- /dev/null +++ b/engine/src/flutter/lib/ui/text/paragraph.h @@ -0,0 +1,61 @@ +// 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. + +#ifndef FLUTTER_LIB_UI_TEXT_PARAGRAPH_H_ +#define FLUTTER_LIB_UI_TEXT_PARAGRAPH_H_ + +#include "flutter/lib/ui/painting/canvas.h" +#include "flutter/lib/ui/text/text_box.h" +#include "flutter/sky/engine/core/rendering/RenderView.h" +#include "lib/tonic/dart_wrappable.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class Paragraph : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(Paragraph); + + public: + static ftl::RefPtr create(PassOwnPtr renderView) { + return ftl::MakeRefCounted(renderView); + } + + ~Paragraph() override; + + double width(); + double height(); + double minIntrinsicWidth(); + double maxIntrinsicWidth(); + double alphabeticBaseline(); + double ideographicBaseline(); + + void layout(double width); + void paint(Canvas* canvas, double x, double y); + + std::vector getRectsForRange(unsigned start, unsigned end); + Dart_Handle getPositionForOffset(double dx, double dy); + Dart_Handle getWordBoundary(unsigned offset); + + RenderView* renderView() const { return m_renderView.get(); } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + RenderBox* firstChildBox() const { return m_renderView->firstChildBox(); } + + int absoluteOffsetForPosition(const PositionWithAffinity& position); + + explicit Paragraph(PassOwnPtr renderView); + + OwnPtr m_renderView; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_TEXT_PARAGRAPH_H_ diff --git a/engine/src/flutter/lib/ui/text/paragraph_builder.cc b/engine/src/flutter/lib/ui/text/paragraph_builder.cc new file mode 100644 index 0000000000..64e7a0ce37 --- /dev/null +++ b/engine/src/flutter/lib/ui/text/paragraph_builder.cc @@ -0,0 +1,305 @@ +// 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. + +#include "flutter/lib/ui/text/paragraph_builder.h" + +#include "flutter/common/threads.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "flutter/sky/engine/core/rendering/RenderInline.h" +#include "flutter/sky/engine/core/rendering/RenderParagraph.h" +#include "flutter/sky/engine/core/rendering/RenderText.h" +#include "flutter/sky/engine/core/rendering/style/RenderStyle.h" +#include "flutter/sky/engine/platform/text/LocaleToScriptMapping.h" +#include "lib/ftl/tasks/task_runner.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/dart_library_natives.h" + +namespace blink { +namespace { + +RenderParagraph* createRenderParagraph(RenderStyle* parentStyle) { + RefPtr style = RenderStyle::create(); + style->inheritFrom(parentStyle); + style->setDisplay(PARAGRAPH); + + RenderParagraph* renderParagraph = new RenderParagraph(); + renderParagraph->setStyle(style.release()); + return renderParagraph; +} + +float getComputedSizeFromSpecifiedSize(float specifiedSize) { + if (specifiedSize < std::numeric_limits::epsilon()) + return 0.0f; + return specifiedSize; +} + +void createFontForDocument(RenderStyle* style) { + FontDescription fontDescription = FontDescription(); + fontDescription.setScript( + localeToScriptCodeForFontSelection(style->locale())); + + // Using 14px default to match Material Design English Body1: + // http://www.google.com/design/spec/style/typography.html#typography-typeface + const float defaultFontSize = 14.0; + + fontDescription.setSpecifiedSize(defaultFontSize); + fontDescription.setComputedSize(defaultFontSize); + + FontOrientation fontOrientation = Horizontal; + NonCJKGlyphOrientation glyphOrientation = NonCJKGlyphOrientationVerticalRight; + + fontDescription.setOrientation(fontOrientation); + fontDescription.setNonCJKGlyphOrientation(glyphOrientation); + style->setFontDescription(fontDescription); + style->font().update(UIDartState::Current()->font_selector()); +} + +Color getColorFromARGB(int argb) { + return Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, + (argb & 0x000000FF) >> 0, (argb & 0xFF000000) >> 24); +} + +// TextStyle + +const int tsColorIndex = 1; +const int tsTextDecorationIndex = 2; +const int tsTextDecorationColorIndex = 3; +const int tsTextDecorationStyleIndex = 4; +const int tsFontWeightIndex = 5; +const int tsFontStyleIndex = 6; +const int tsFontFamilyIndex = 7; +const int tsFontSizeIndex = 8; +const int tsLetterSpacingIndex = 9; +const int tsWordSpacingIndex = 10; +const int tsHeightIndex = 11; + +const int tsColorMask = 1 << tsColorIndex; +const int tsTextDecorationMask = 1 << tsTextDecorationIndex; +const int tsTextDecorationColorMask = 1 << tsTextDecorationColorIndex; +const int tsTextDecorationStyleMask = 1 << tsTextDecorationStyleIndex; +const int tsFontWeightMask = 1 << tsFontWeightIndex; +const int tsFontStyleMask = 1 << tsFontStyleIndex; +const int tsFontFamilyMask = 1 << tsFontFamilyIndex; +const int tsFontSizeMask = 1 << tsFontSizeIndex; +const int tsLetterSpacingMask = 1 << tsLetterSpacingIndex; +const int tsWordSpacingMask = 1 << tsWordSpacingIndex; +const int tsHeightMask = 1 << tsHeightIndex; + +// ParagraphStyle + +const int psTextAlignIndex = 1; +const int psTextBaselineIndex = 2; +const int psFontWeightIndex = 3; +const int psFontStyleIndex = 4; +const int psFontFamilyIndex = 5; +const int psFontSizeIndex = 6; +const int psLineHeightIndex = 7; + +const int psTextAlignMask = 1 << psTextAlignIndex; +const int psTextBaselineMask = 1 << psTextBaselineIndex; +const int psFontWeightMask = 1 << psFontWeightIndex; +const int psFontStyleMask = 1 << psFontStyleIndex; +const int psFontFamilyMask = 1 << psFontFamilyIndex; +const int psFontSizeMask = 1 << psFontSizeIndex; +const int psLineHeightMask = 1 << psLineHeightIndex; + +} // namespace + +static void ParagraphBuilder_constructor(Dart_NativeArguments args) { + DartCallConstructor(&ParagraphBuilder::create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, ParagraphBuilder); + +#define FOR_EACH_BINDING(V) \ + V(ParagraphBuilder, pushStyle) \ + V(ParagraphBuilder, pop) \ + V(ParagraphBuilder, addText) \ + V(ParagraphBuilder, build) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void ParagraphBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register( + {{"ParagraphBuilder_constructor", ParagraphBuilder_constructor, 1, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +ParagraphBuilder::ParagraphBuilder() { + createRenderView(); + m_renderParagraph = createRenderParagraph(m_renderView->style()); + m_currentRenderObject = m_renderParagraph; + m_renderView->addChild(m_currentRenderObject); +} + +ParagraphBuilder::~ParagraphBuilder() { + PassOwnPtr renderView = m_renderView.release(); + Threads::UI()->PostTask( + [renderView]() { /* renderView's destructor runs. */ }); +} + +void ParagraphBuilder::pushStyle(tonic::Int32List& encoded, + const std::string& fontFamily, + double fontSize, + double letterSpacing, + double wordSpacing, + double height) { + FTL_DCHECK(encoded.num_elements() == 7); + RefPtr style = RenderStyle::create(); + style->inheritFrom(m_currentRenderObject->style()); + + int32_t mask = encoded[0]; + + if (mask & tsColorMask) + style->setColor(getColorFromARGB(encoded[tsColorIndex])); + + if (mask & tsTextDecorationMask) { + style->setTextDecoration( + static_cast(encoded[tsTextDecorationIndex])); + style->applyTextDecorations(); + } + + if (mask & tsTextDecorationColorMask) + style->setTextDecorationColor( + StyleColor(getColorFromARGB(encoded[tsTextDecorationColorIndex]))); + + if (mask & tsTextDecorationStyleMask) + style->setTextDecorationStyle( + static_cast(encoded[tsTextDecorationStyleIndex])); + + if (mask & (tsFontWeightMask | tsFontStyleMask | tsFontFamilyMask | + tsFontSizeMask | tsLetterSpacingMask | tsWordSpacingMask)) { + FontDescription fontDescription = style->fontDescription(); + + if (mask & tsFontWeightMask) + fontDescription.setWeight( + static_cast(encoded[tsFontWeightIndex])); + + if (mask & tsFontStyleMask) + fontDescription.setStyle( + static_cast(encoded[tsFontStyleIndex])); + + if (mask & tsFontFamilyMask) { + FontFamily family; + family.setFamily(String::fromUTF8(fontFamily)); + fontDescription.setFamily(family); + } + + if (mask & tsFontSizeMask) { + fontDescription.setSpecifiedSize(fontSize); + fontDescription.setIsAbsoluteSize(true); + fontDescription.setComputedSize( + getComputedSizeFromSpecifiedSize(fontSize)); + } + + if (mask & tsLetterSpacingMask) + fontDescription.setLetterSpacing(letterSpacing); + + if (mask & tsWordSpacingMask) + fontDescription.setWordSpacing(wordSpacing); + + style->setFontDescription(fontDescription); + style->font().update(UIDartState::Current()->font_selector()); + } + + if (mask & tsHeightMask) { + style->setLineHeight(Length(height * 100.0, Percent)); + } + + encoded.Release(); + + RenderObject* span = new RenderInline(); + span->setStyle(style.release()); + m_currentRenderObject->addChild(span); + m_currentRenderObject = span; +} + +void ParagraphBuilder::pop() { + if (m_currentRenderObject) + m_currentRenderObject = m_currentRenderObject->parent(); +} + +void ParagraphBuilder::addText(const std::string& text) { + if (!m_currentRenderObject) + return; + RenderText* renderText = new RenderText(String::fromUTF8(text).impl()); + RefPtr style = RenderStyle::create(); + style->inheritFrom(m_currentRenderObject->style()); + renderText->setStyle(style.release()); + m_currentRenderObject->addChild(renderText); +} + +ftl::RefPtr ParagraphBuilder::build(tonic::Int32List& encoded, + const std::string& fontFamily, + double fontSize, + double lineHeight) { + FTL_DCHECK(encoded.num_elements() == 5); + int32_t mask = encoded[0]; + + if (mask) { + RefPtr style = RenderStyle::clone(m_renderParagraph->style()); + + if (mask & psTextAlignMask) + style->setTextAlign(static_cast(encoded[psTextAlignIndex])); + + if (mask & psTextBaselineMask) { + // TODO(abarth): Implement TextBaseline. The CSS version of this + // property wasn't wired up either. + } + + if (mask & (psFontWeightMask | psFontStyleMask | psFontFamilyMask | + psFontSizeMask)) { + FontDescription fontDescription = style->fontDescription(); + + if (mask & psFontWeightMask) + fontDescription.setWeight( + static_cast(encoded[psFontWeightIndex])); + + if (mask & psFontStyleMask) + fontDescription.setStyle( + static_cast(encoded[psFontStyleIndex])); + + if (mask & psFontFamilyMask) { + FontFamily family; + family.setFamily(String::fromUTF8(fontFamily)); + fontDescription.setFamily(family); + } + + if (mask & psFontSizeMask) { + fontDescription.setSpecifiedSize(fontSize); + fontDescription.setIsAbsoluteSize(true); + fontDescription.setComputedSize( + getComputedSizeFromSpecifiedSize(fontSize)); + } + + style->setFontDescription(fontDescription); + style->font().update(UIDartState::Current()->font_selector()); + } + + if (mask & psLineHeightMask) + style->setLineHeight(Length(lineHeight * 100.0, Percent)); + + m_renderParagraph->setStyle(style.release()); + } + + encoded.Release(); + + m_currentRenderObject = nullptr; + return Paragraph::create(m_renderView.release()); +} + +void ParagraphBuilder::createRenderView() { + RefPtr style = RenderStyle::create(); + style->setRTLOrdering(LogicalOrder); + style->setZIndex(0); + style->setUserModify(READ_ONLY); + createFontForDocument(style.get()); + + m_renderView = adoptPtr(new RenderView()); + m_renderView->setStyle(style.release()); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/text/paragraph_builder.h b/engine/src/flutter/lib/ui/text/paragraph_builder.h new file mode 100644 index 0000000000..ddd72d00be --- /dev/null +++ b/engine/src/flutter/lib/ui/text/paragraph_builder.h @@ -0,0 +1,59 @@ +// 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. + +#ifndef FLUTTER_LIB_UI_TEXT_PARAGRAPH_BUILDER_H_ +#define FLUTTER_LIB_UI_TEXT_PARAGRAPH_BUILDER_H_ + +#include "flutter/lib/ui/text/paragraph.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/typed_data/int32_list.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class ParagraphBuilder : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(ParagraphBuilder); + + public: + static ftl::RefPtr create() { + return ftl::MakeRefCounted(); + } + + ~ParagraphBuilder() override; + + void pushStyle(tonic::Int32List& encoded, + const std::string& fontFamily, + double fontSize, + double letterSpacing, + double wordSpacing, + double height); + void pop(); + + void addText(const std::string& text); + + ftl::RefPtr build(tonic::Int32List& encoded, + const std::string& fontFamily, + double fontSize, + double lineHeight); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit ParagraphBuilder(); + + void createRenderView(); + + OwnPtr m_renderView; + RenderObject* m_renderParagraph; + RenderObject* m_currentRenderObject; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_TEXT_PARAGRAPH_BUILDER_H_ diff --git a/engine/src/flutter/lib/ui/text/text_box.cc b/engine/src/flutter/lib/ui/text/text_box.cc new file mode 100644 index 0000000000..511615aead --- /dev/null +++ b/engine/src/flutter/lib/ui/text/text_box.cc @@ -0,0 +1,34 @@ +// 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. + +#include "flutter/lib/ui/text/text_box.h" + +#include "lib/ftl/logging.h" +#include "lib/tonic/dart_class_library.h" +#include "lib/tonic/dart_state.h" +#include "lib/tonic/logging/dart_error.h" + +using namespace blink; + +namespace tonic { + +Dart_Handle DartConverter::ToDart(const TextBox& val) { + if (val.is_null) + return Dart_Null(); + DartClassLibrary& class_library = DartState::Current()->class_library(); + Dart_Handle type = + Dart_HandleFromPersistent(class_library.GetClass("ui", "TextBox")); + FTL_DCHECK(!LogIfError(type)); + constexpr int argc = 5; + Dart_Handle argv[argc] = { + tonic::ToDart(val.sk_rect.fLeft), + tonic::ToDart(val.sk_rect.fTop), + tonic::ToDart(val.sk_rect.fRight), + tonic::ToDart(val.sk_rect.fBottom), + tonic::ToDart(static_cast(val.direction)), + }; + return Dart_New(type, tonic::ToDart("_"), argc, argv); +} + +} // namespace tonic diff --git a/engine/src/flutter/lib/ui/text/text_box.h b/engine/src/flutter/lib/ui/text/text_box.h new file mode 100644 index 0000000000..ddbb039da0 --- /dev/null +++ b/engine/src/flutter/lib/ui/text/text_box.h @@ -0,0 +1,21 @@ +// Copyright 2016 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. + +#ifndef FLUTTER_LIB_UI_TEXT_TEXT_BOX_H_ +#define FLUTTER_LIB_UI_TEXT_TEXT_BOX_H_ + +#include "dart/runtime/include/dart_api.h" +#include "flutter/sky/engine/platform/text/TextBox.h" +#include "lib/tonic/converter/dart_converter.h" + +namespace tonic { + +template <> +struct DartConverter { + static Dart_Handle ToDart(const blink::TextBox& val); +}; + +} // namespace tonic + +#endif // FLUTTER_LIB_UI_TEXT_TEXT_BOX_H_ diff --git a/engine/src/flutter/lib/ui/ui_dart_state.cc b/engine/src/flutter/lib/ui/ui_dart_state.cc new file mode 100644 index 0000000000..026749e452 --- /dev/null +++ b/engine/src/flutter/lib/ui/ui_dart_state.cc @@ -0,0 +1,76 @@ +// 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. + +#include "flutter/lib/ui/ui_dart_state.h" + +#include "flutter/lib/ui/mojo_services.h" +#include "flutter/lib/ui/window/window.h" +#include "flutter/sky/engine/platform/fonts/FontSelector.h" +#include "lib/tonic/converter/dart_converter.h" + +#ifdef OS_ANDROID +#include "flutter/lib/jni/dart_jni.h" +#endif + +using tonic::ToDart; + +namespace blink { + +IsolateClient::~IsolateClient() {} + +UIDartState::UIDartState(IsolateClient* isolate_client, + std::unique_ptr window) + : isolate_client_(isolate_client), + main_port_(ILLEGAL_PORT), + window_(std::move(window)) { +#ifdef OS_ANDROID + jni_data_.reset(new DartJniIsolateData()); +#endif +} + +UIDartState::~UIDartState() { + main_port_ = ILLEGAL_PORT; + // We've already destroyed the isolate. Revoke any weak ptrs held by + // DartPersistentValues so they don't try to enter the destroyed isolate to + // clean themselves up. + // TODO(abarth): Can we do this work in the base class? + weak_factory_.InvalidateWeakPtrs(); +} + +UIDartState* UIDartState::CreateForChildIsolate() { + return new UIDartState(isolate_client_, nullptr); +} + +void UIDartState::DidSetIsolate() { + main_port_ = Dart_GetMainPortId(); +} + +UIDartState* UIDartState::Current() { + return static_cast(DartState::Current()); +} + +void UIDartState::set_mojo_services( + std::unique_ptr mojo_services) { + mojo_services_ = std::move(mojo_services); +} + +MojoServices* UIDartState::mojo_services() { + return mojo_services_.get(); +} + +#ifdef OS_ANDROID +DartJniIsolateData* UIDartState::jni_data() { + return jni_data_.get(); +} +#endif + +void UIDartState::set_font_selector(PassRefPtr selector) { + font_selector_ = selector; +} + +PassRefPtr UIDartState::font_selector() { + return font_selector_; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/ui_dart_state.h b/engine/src/flutter/lib/ui/ui_dart_state.h new file mode 100644 index 0000000000..cc60b37fcb --- /dev/null +++ b/engine/src/flutter/lib/ui/ui_dart_state.h @@ -0,0 +1,67 @@ +// 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. + +#ifndef FLUTTER_LIB_UI_UI_DART_STATE_H_ +#define FLUTTER_LIB_UI_UI_DART_STATE_H_ + +#include "dart/runtime/include/dart_api.h" +#include "flutter/sky/engine/wtf/RefPtr.h" +#include "lib/ftl/build_config.h" +#include "lib/tonic/dart_persistent_value.h" +#include "lib/tonic/dart_state.h" + +namespace blink { +class FontSelector; +class DartJniIsolateData; +class MojoServices; +class Window; + +class IsolateClient { + public: + virtual void DidCreateSecondaryIsolate(Dart_Isolate isolate) = 0; + + protected: + virtual ~IsolateClient(); +}; + +class UIDartState : public tonic::DartState { + public: + UIDartState(IsolateClient* isolate_client, std::unique_ptr window); + ~UIDartState() override; + + static UIDartState* Current(); + + UIDartState* CreateForChildIsolate(); + + IsolateClient* isolate_client() { return isolate_client_; } + Dart_Port main_port() const { return main_port_; } + + Window* window() const { return window_.get(); } + + void set_mojo_services(std::unique_ptr mojo_services); + MojoServices* mojo_services(); + +#ifdef OS_ANDROID + DartJniIsolateData* jni_data(); +#endif + + void set_font_selector(PassRefPtr selector); + PassRefPtr font_selector(); + + private: + void DidSetIsolate() override; + + IsolateClient* isolate_client_; + Dart_Port main_port_; + std::unique_ptr mojo_services_; +#ifdef OS_ANDROID + std::unique_ptr jni_data_; +#endif + std::unique_ptr window_; + RefPtr font_selector_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_UI_DART_STATE_H_ diff --git a/engine/src/flutter/lib/ui/window/window.cc b/engine/src/flutter/lib/ui/window/window.cc new file mode 100644 index 0000000000..ca5c8c6a97 --- /dev/null +++ b/engine/src/flutter/lib/ui/window/window.cc @@ -0,0 +1,161 @@ +// 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. + +#include "flutter/lib/ui/window/window.h" + +#include "flutter/lib/ui/compositing/scene.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "lib/tonic/logging/dart_invoke.h" + +using tonic::DartInvokeField; +using tonic::DartState; +using tonic::StdStringToDart; +using tonic::ToDart; + +namespace blink { +namespace { + +void ScheduleFrame(Dart_NativeArguments args) { + UIDartState::Current()->window()->client()->ScheduleFrame(); +} + +void Render(Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + Scene* scene = + tonic::DartConverter::FromArguments(args, 1, exception); + if (exception) { + Dart_ThrowException(exception); + return; + } + UIDartState::Current()->window()->client()->Render(scene); +} + +void FlushRealTimeEvents(Dart_NativeArguments args) { + UIDartState::Current()->window()->client()->FlushRealTimeEvents(); +} + +} // namespace + +WindowClient::~WindowClient() {} + +Window::Window(WindowClient* client) : client_(client) {} + +Window::~Window() {} + +void Window::DidCreateIsolate() { + library_.Set(DartState::Current(), Dart_LookupLibrary(ToDart("dart:ui"))); +} + +void Window::UpdateWindowMetrics(const sky::ViewportMetricsPtr& metrics) { + tonic::DartState* dart_state = library_.dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + double device_pixel_ratio = metrics->device_pixel_ratio; + DartInvokeField( + library_.value(), "_updateWindowMetrics", + { + ToDart(device_pixel_ratio), + ToDart(metrics->physical_width / device_pixel_ratio), + ToDart(metrics->physical_height / device_pixel_ratio), + ToDart(metrics->physical_padding_top / device_pixel_ratio), + ToDart(metrics->physical_padding_right / device_pixel_ratio), + ToDart(metrics->physical_padding_bottom / device_pixel_ratio), + ToDart(metrics->physical_padding_left / device_pixel_ratio), + }); +} + +void Window::UpdateLocale(const std::string& language_code, + const std::string& country_code) { + tonic::DartState* dart_state = library_.dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + + DartInvokeField( + library_.value(), "_updateLocale", + { + StdStringToDart(language_code), StdStringToDart(country_code), + }); +} + +void Window::PushRoute(const std::string& route) { + tonic::DartState* dart_state = library_.dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + + DartInvokeField(library_.value(), "_pushRoute", { + StdStringToDart(route), + }); +} + +void Window::PopRoute() { + tonic::DartState* dart_state = library_.dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + + DartInvokeField(library_.value(), "_popRoute", {}); +} + +void Window::DispatchPointerPacket(const pointer::PointerPacketPtr& packet) { + tonic::DartState* dart_state = library_.dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + + Dart_Handle data_handle = + Dart_NewTypedData(Dart_TypedData_kByteData, packet->GetSerializedSize()); + if (Dart_IsError(data_handle)) + return; + + Dart_TypedData_Type type; + void* data; + intptr_t len; + if (Dart_IsError(Dart_TypedDataAcquireData(data_handle, &type, &data, &len))) + return; + + packet->Serialize(data, len); + + Dart_TypedDataReleaseData(data_handle); + + DartInvokeField(library_.value(), "_dispatchPointerPacket", {data_handle}); +} + +void Window::BeginFrame(ftl::TimePoint frameTime) { + tonic::DartState* dart_state = library_.dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + + int64_t microseconds = (frameTime - ftl::TimePoint()).ToMicroseconds(); + + DartInvokeField(library_.value(), "_beginFrame", + { + Dart_NewInteger(microseconds), + }); +} + +void Window::OnAppLifecycleStateChanged(sky::AppLifecycleState state) { + tonic::DartState* dart_state = library_.dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + + DartInvokeField(library_.value(), "_onAppLifecycleStateChanged", + {ToDart(static_cast(state))}); +} + +void Window::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({ + {"Window_scheduleFrame", ScheduleFrame, 1, true}, + {"Window_render", Render, 2, true}, + {"Scheduler_FlushRealTimeEvents", FlushRealTimeEvents, 1, true}, + }); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/window/window.h b/engine/src/flutter/lib/ui/window/window.h new file mode 100644 index 0000000000..1fd5d36f6d --- /dev/null +++ b/engine/src/flutter/lib/ui/window/window.h @@ -0,0 +1,58 @@ +// Copyright 2014 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. + +#ifndef FLUTTER_LIB_UI_WINDOW_WINDOW_H_ +#define FLUTTER_LIB_UI_WINDOW_WINDOW_H_ + +#include "lib/ftl/time/time_point.h" +#include "lib/tonic/dart_persistent_value.h" +#include "flutter/services/engine/sky_engine.mojom.h" +#include "flutter/services/pointer/pointer.mojom.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { +class Scene; + +class WindowClient { + public: + virtual void ScheduleFrame() = 0; + virtual void FlushRealTimeEvents() = 0; + virtual void Render(Scene* scene) = 0; + + protected: + virtual ~WindowClient(); +}; + +class Window { + public: + explicit Window(WindowClient* client); + ~Window(); + + WindowClient* client() const { return client_; } + + void DidCreateIsolate(); + void UpdateWindowMetrics(const sky::ViewportMetricsPtr& metrics); + void UpdateLocale(const std::string& language_code, + const std::string& country_code); + void DispatchPointerPacket(const pointer::PointerPacketPtr& packet); + void BeginFrame(ftl::TimePoint frameTime); + + void PushRoute(const std::string& route); + void PopRoute(); + + void OnAppLifecycleStateChanged(sky::AppLifecycleState state); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + WindowClient* client_; + tonic::DartPersistentValue library_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_WINDOW_WINDOW_H_ diff --git a/engine/src/flutter/runtime/BUILD.gn b/engine/src/flutter/runtime/BUILD.gn new file mode 100644 index 0000000000..5e5e0622e1 --- /dev/null +++ b/engine/src/flutter/runtime/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright 2016 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. + +source_set("runtime") { + sources = [ + "dart_controller.cc", + "dart_controller.h", + "dart_init.cc", + "dart_init.h", + "dart_service_isolate.cc", + "dart_service_isolate.h", + "embedder_resources.cc", + "embedder_resources.h", + "sky_view.cc", + "sky_view_client.cc", + "sky_view_client.h", + "sky_view.h", + "start_up.cc", + "start_up.h", + ] + + deps = [ + "//dart/runtime:libdart", + "//dart/runtime/bin:embedded_dart_io", + "//flutter/assets", + "//flutter/common", + "//flutter/flow", + "//flutter/glue", + "//flutter/lib/io", + "//flutter/lib/mojo", + "//flutter/lib/ui", + "//flutter/services/engine:interfaces", + "//flutter/services/pointer:interfaces", + "//flutter/skia", + "//lib/ftl", + "//lib/tonic", + "//lib/tonic/debugger", + "//mojo/public/platform/dart:mojo_internal_impl", + ] + + if (is_android) { + deps += [ + "//flutter/lib/jni", + ] + } + + # On iOS (device), precompiled snapshots contain the instruction buffer. + # Generation of the same requires all application specific script code to be + # specified up front. In such cases, there can be no generic snapshot. + if (!is_ios || use_ios_simulator) { + deps += [ + "//flutter/lib/snapshot", + ] + } +} diff --git a/engine/src/flutter/runtime/dart_controller.cc b/engine/src/flutter/runtime/dart_controller.cc new file mode 100644 index 0000000000..929e3beae3 --- /dev/null +++ b/engine/src/flutter/runtime/dart_controller.cc @@ -0,0 +1,175 @@ +// 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. + +#include "flutter/runtime/dart_controller.h" + +#include + +#include "dart/runtime/include/dart_tools_api.h" +#include "flutter/common/settings.h" +#include "flutter/common/threads.h" +#include "flutter/glue/trace_event.h" +#include "flutter/lib/io/dart_io.h" +#include "flutter/lib/mojo/dart_mojo_internal.h" +#include "flutter/lib/ui/dart_runtime_hooks.h" +#include "flutter/lib/ui/dart_ui.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "flutter/runtime/dart_init.h" +#include "flutter/runtime/dart_service_isolate.h" +#include "lib/ftl/files/directory.h" +#include "lib/ftl/files/path.h" +#include "lib/tonic/dart_class_library.h" +#include "lib/tonic/dart_message_handler.h" +#include "lib/tonic/dart_state.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/debugger/dart_debugger.h" +#include "lib/tonic/file_loader/file_loader.h" +#include "lib/tonic/logging/dart_error.h" +#include "lib/tonic/logging/dart_invoke.h" +#include "lib/tonic/scopes/dart_api_scope.h" +#include "lib/tonic/scopes/dart_isolate_scope.h" + +#ifdef OS_ANDROID +#include "flutter/lib/jni/dart_jni.h" +#endif + +using tonic::LogIfError; +using tonic::ToDart; + +namespace blink { +namespace { + +// TODO(abarth): Consider adding this to //lib/ftl. +std::string ResolvePath(std::string path) { + if (!path.empty() && path[0] == '/') + return path; + return files::SimplifyPath(files::GetCurrentDirectory() + "/" + path); +} + +} // namespace + +DartController::DartController() : ui_dart_state_(nullptr) {} + +DartController::~DartController() { + if (ui_dart_state_) { + // Don't use a tonic::DartIsolateScope here since we never exit the isolate. + Dart_EnterIsolate(ui_dart_state_->isolate()); + // Clear the message notify callback. + Dart_SetMessageNotifyCallback(nullptr); + Dart_ShutdownIsolate(); // deletes ui_dart_state_ + ui_dart_state_ = nullptr; + } +} + +bool DartController::SendStartMessage(Dart_Handle root_library) { + if (LogIfError(root_library)) + return true; + + { + // Temporarily exit the isolate while we make it runnable. + Dart_Isolate isolate = dart_state()->isolate(); + FTL_DCHECK(Dart_CurrentIsolate() == isolate); + Dart_ExitIsolate(); + Dart_IsolateMakeRunnable(isolate); + Dart_EnterIsolate(isolate); + } + + // In order to support pausing the isolate at start, we indirectly invoke + // main by sending a message to the isolate. + // Grab the 'dart:ui' library. + Dart_Handle ui_library = Dart_LookupLibrary(ToDart("dart:ui")); + DART_CHECK_VALID(ui_library); + + // Grab the 'dart:isolate' library. + Dart_Handle isolate_lib = Dart_LookupLibrary(ToDart("dart:isolate")); + DART_CHECK_VALID(isolate_lib); + + // Import the root library into the 'dart:ui' library so that we can + // reach main. + Dart_LibraryImportLibrary(ui_library, root_library, Dart_Null()); + + // Get the closure of main(). + Dart_Handle main_closure = + Dart_Invoke(ui_library, ToDart("_getMainClosure"), 0, NULL); + if (LogIfError(main_closure)) + return true; + + // Send the start message containing the entry point by calling + // _startMainIsolate in dart:isolate. + const intptr_t kNumIsolateArgs = 2; + Dart_Handle isolate_args[kNumIsolateArgs]; + isolate_args[0] = main_closure; + isolate_args[1] = Dart_Null(); + Dart_Handle result = Dart_Invoke(isolate_lib, ToDart("_startMainIsolate"), + kNumIsolateArgs, isolate_args); + return LogIfError(result); +} + +void DartController::RunFromPrecompiledSnapshot() { + TRACE_EVENT0("flutter", "DartController::RunFromPrecompiledSnapshot"); + FTL_DCHECK(Dart_CurrentIsolate() == nullptr); + tonic::DartState::Scope scope(dart_state()); + if (SendStartMessage(Dart_RootLibrary())) + exit(1); +} + +void DartController::RunFromSnapshot(const uint8_t* buffer, size_t size) { + tonic::DartState::Scope scope(dart_state()); + LogIfError(Dart_LoadScriptFromSnapshot(buffer, size)); + if (SendStartMessage(Dart_RootLibrary())) + exit(1); +} + +void DartController::RunFromSource(const std::string& main, + const std::string& packages) { + tonic::DartState::Scope scope(dart_state()); + tonic::FileLoader& loader = dart_state()->file_loader(); + if (!packages.empty() && !loader.LoadPackagesMap(ResolvePath(packages))) + FTL_LOG(WARNING) << "Failed to load package map: " << packages; + LogIfError(loader.LoadScript(main)); + if (SendStartMessage(Dart_RootLibrary())) + exit(1); +} + +void DartController::CreateIsolateFor(const std::string& script_uri, + std::unique_ptr state) { + char* error = nullptr; + Dart_Isolate isolate = Dart_CreateIsolate( + script_uri.c_str(), "main", + reinterpret_cast(DART_SYMBOL(kDartIsolateSnapshotBuffer)), + nullptr, static_cast(state.get()), &error); + FTL_CHECK(isolate) << error; + ui_dart_state_ = state.release(); + dart_state()->message_handler().Initialize(blink::Threads::UI()); + + Dart_SetShouldPauseOnStart(Settings::Get().start_paused); + + ui_dart_state_->SetIsolate(isolate); + FTL_CHECK(!LogIfError( + Dart_SetLibraryTagHandler(tonic::DartState::HandleLibraryTag))); + + { + tonic::DartApiScope dart_api_scope; + DartIO::InitForIsolate(); + DartUI::InitForIsolate(); + DartMojoInternal::InitForIsolate(); + DartRuntimeHooks::Install(DartRuntimeHooks::MainIsolate, script_uri); + + std::unique_ptr ui_class_provider( + new tonic::DartClassProvider(dart_state(), "dart:ui")); + dart_state()->class_library().add_provider("ui", + std::move(ui_class_provider)); + +#ifdef OS_ANDROID + DartJni::InitForIsolate(); + std::unique_ptr jni_class_provider( + new tonic::DartClassProvider(dart_state(), "dart:jni")); + dart_state()->class_library().add_provider("jni", + std::move(jni_class_provider)); +#endif + } + Dart_ExitIsolate(); +} + +} // namespace blink diff --git a/engine/src/flutter/runtime/dart_controller.h b/engine/src/flutter/runtime/dart_controller.h new file mode 100644 index 0000000000..20cccaebf2 --- /dev/null +++ b/engine/src/flutter/runtime/dart_controller.h @@ -0,0 +1,43 @@ +// 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. + +#ifndef FLUTTER_RUNTIME_DART_CONTROLLER_H_ +#define FLUTTER_RUNTIME_DART_CONTROLLER_H_ + +#include + +#include "dart/runtime/include/dart_api.h" +#include "lib/ftl/macros.h" + +namespace blink { +class UIDartState; + +class DartController { + public: + DartController(); + ~DartController(); + + static void InitVM(); + + void RunFromPrecompiledSnapshot(); + void RunFromSnapshot(const uint8_t* buffer, size_t size); + void RunFromSource(const std::string& main, const std::string& packages); + + void CreateIsolateFor(const std::string& script_uri, + std::unique_ptr ui_dart_state); + + UIDartState* dart_state() const { return ui_dart_state_; } + + private: + bool SendStartMessage(Dart_Handle root_library); + + // The DartState associated with the main isolate. This will be deleted + // during isolate shutdown. + UIDartState* ui_dart_state_; + + FTL_DISALLOW_COPY_AND_ASSIGN(DartController); +}; +} + +#endif // FLUTTER_RUNTIME_DART_CONTROLLER_H_ diff --git a/engine/src/flutter/runtime/dart_init.cc b/engine/src/flutter/runtime/dart_init.cc new file mode 100644 index 0000000000..f2ac25ea62 --- /dev/null +++ b/engine/src/flutter/runtime/dart_init.cc @@ -0,0 +1,636 @@ +// 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. + +#include "flutter/runtime/dart_init.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "dart/runtime/bin/embedded_dart_io.h" +#include "dart/runtime/include/dart_mirrors_api.h" +#include "flutter/assets/zip_asset_store.h" +#include "flutter/common/settings.h" +#include "flutter/glue/trace_event.h" +#include "flutter/lib/io/dart_io.h" +#include "flutter/lib/mojo/dart_mojo_internal.h" +#include "flutter/lib/ui/dart_runtime_hooks.h" +#include "flutter/lib/ui/dart_ui.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "flutter/runtime/dart_service_isolate.h" +#include "flutter/runtime/start_up.h" +#include "lib/ftl/files/eintr_wrapper.h" +#include "lib/ftl/files/unique_fd.h" +#include "lib/ftl/logging.h" +#include "lib/ftl/time/time_delta.h" +#include "lib/tonic/dart_class_library.h" +#include "lib/tonic/dart_state.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/debugger/dart_debugger.h" +#include "lib/tonic/logging/dart_error.h" +#include "lib/tonic/logging/dart_invoke.h" +#include "lib/tonic/scopes/dart_api_scope.h" +#include "lib/tonic/scopes/dart_isolate_scope.h" +#include "lib/tonic/typed_data/uint8_list.h" +#include "mojo/public/platform/dart/dart_handle_watcher.h" + +#ifdef OS_ANDROID +#include "flutter/lib/jni/dart_jni.h" +#endif + +using tonic::DartClassProvider; +using tonic::LogIfError; +using tonic::ToDart; + +namespace dart { +namespace observatory { + +#if FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_RELEASE + +// These two symbols are defined in |observatory_archive.cc| which is generated +// by the |//dart/runtime/observatory:archive_observatory| rule. Both of these +// symbols will be part of the data segment and therefore are read only. +extern unsigned int observatory_assets_archive_len; +extern const uint8_t* observatory_assets_archive; + +#endif // FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_RELEASE + +} // namespace observatory +} // namespace dart + +namespace blink { + +const char kSnapshotAssetKey[] = "snapshot_blob.bin"; + +namespace { + +static const char* kDartProfilingArgs[] = { + // Dart assumes ARM devices are insufficiently powerful and sets the + // default profile period to 100Hz. This number is suitable for older + // Raspberry Pi devices but quite low for current smartphones. + "--profile_period=1000", +#if (WTF_OS_IOS || WTF_OS_MACOSX) + // On platforms where LLDB is the primary debugger, SIGPROF signals + // overwhelm LLDB. + "--no-profiler", +#endif +}; + +static const char* kDartMirrorsArgs[] = { + "--enable_mirrors=false", +}; + +static const char* kDartPrecompilationArgs[] = { + "--precompilation", +}; + +static const char* kDartBackgroundCompilationArgs[] = { + "--background_compilation", +}; + +static const char* kDartCheckedModeArgs[] = { + // clang-format off + "--enable_asserts", + "--enable_type_checks", + "--error_on_bad_type", + "--error_on_bad_override", + // clang-format on +}; + +static const char* kDartStartPausedArgs[]{ + "--pause_isolates_on_start", +}; + +static const char* kDartTraceStartupArgs[]{ + "--timeline_streams=Compiler,Dart,Embedder,GC", + "--timeline_recorder=endless", +}; + +constexpr char kFileUriPrefix[] = "file://"; +constexpr size_t kFileUriPrefixLength = sizeof(kFileUriPrefix) - 1; + +bool g_service_isolate_initialized = false; +ServiceIsolateHook g_service_isolate_hook = nullptr; +RegisterNativeServiceProtocolExtensionHook + g_register_native_service_protocol_extensions_hook = nullptr; + +void IsolateShutdownCallback(void* callback_data) { + tonic::DartState* dart_state = static_cast(callback_data); + delete dart_state; +} + +bool DartFileModifiedCallback(const char* source_url, int64_t since_ms) { + if (strncmp(source_url, kFileUriPrefix, kFileUriPrefixLength) != 0u) { + // Assume modified. + return true; + } + + const char* path = source_url + kFileUriPrefixLength; + struct stat info; + if (stat(path, &info) < 0) + return true; + + // If st_mtime is zero, it's more likely that the file system doesn't support + // mtime than that the file was actually modified in the 1970s. + if (!info.st_mtime) + return true; + + // It's very unclear what time bases we're with here. The Dart API doesn't + // document the time base for since_ms. Reading the code, the value varies by + // platform, with a typical source being something like gettimeofday. + // + // We add one to st_mtime because st_mtime has less precision than since_ms + // and we want to treat the file as modified if the since time is between + // ticks of the mtime. + ftl::TimeDelta mtime = ftl::TimeDelta::FromSeconds(info.st_mtime + 1); + ftl::TimeDelta since = ftl::TimeDelta::FromMilliseconds(since_ms); + + return mtime > since; +} + +void ThreadExitCallback() { +#ifdef OS_ANDROID + DartJni::OnThreadExit(); +#endif +} + +bool IsServiceIsolateURL(const char* url_name) { + return url_name != nullptr && + std::string(url_name) == DART_VM_SERVICE_ISOLATE_NAME; +} + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_RELEASE + +Dart_Isolate ServiceIsolateCreateCallback(const char* script_uri, + char** error) { + return nullptr; +} + +#else // FLUTTER_RUNTIME_MODE + +Dart_Isolate ServiceIsolateCreateCallback(const char* script_uri, + char** error) { + tonic::DartState* dart_state = new tonic::DartState(); + Dart_Isolate isolate = Dart_CreateIsolate( + script_uri, "main", + reinterpret_cast(DART_SYMBOL(kDartIsolateSnapshotBuffer)), + nullptr, dart_state, error); + FTL_CHECK(isolate) << error; + dart_state->SetIsolate(isolate); + FTL_CHECK(Dart_IsServiceIsolate(isolate)); + FTL_CHECK(!LogIfError( + Dart_SetLibraryTagHandler(tonic::DartState::HandleLibraryTag))); + { + tonic::DartApiScope dart_api_scope; + DartIO::InitForIsolate(); + DartUI::InitForIsolate(); + DartMojoInternal::InitForIsolate(); + DartRuntimeHooks::Install(DartRuntimeHooks::SecondaryIsolate, script_uri); + const Settings& settings = Settings::Get(); + if (settings.enable_observatory) { + std::string ip = "127.0.0.1"; + const intptr_t port = settings.observatory_port; + const bool disable_websocket_origin_check = false; + const bool service_isolate_booted = DartServiceIsolate::Startup( + ip, port, tonic::DartState::HandleLibraryTag, + IsRunningPrecompiledCode(), disable_websocket_origin_check, error); + FTL_CHECK(service_isolate_booted) << error; + } + + if (g_service_isolate_hook) + g_service_isolate_hook(IsRunningPrecompiledCode()); + } + Dart_ExitIsolate(); + + g_service_isolate_initialized = true; + // Register any native service protocol extensions. + if (g_register_native_service_protocol_extensions_hook) { + g_register_native_service_protocol_extensions_hook( + IsRunningPrecompiledCode()); + } + return isolate; +} + +#endif // FLUTTER_RUNTIME_MODE + +Dart_Isolate IsolateCreateCallback(const char* script_uri, + const char* main, + const char* package_root, + const char* package_config, + Dart_IsolateFlags* flags, + void* callback_data, + char** error) { + TRACE_EVENT0("flutter", __func__); + + if (IsServiceIsolateURL(script_uri)) { + return ServiceIsolateCreateCallback(script_uri, error); + } + + std::vector snapshot_data; + if (!IsRunningPrecompiledCode()) { + std::string uri = script_uri; + FTL_CHECK(uri.find(kFileUriPrefix) == 0u); + std::string bundle_path(script_uri + strlen(kFileUriPrefix)); + ftl::RefPtr zip_asset_store = + ftl::MakeRefCounted(std::move(bundle_path), + ftl::RefPtr()); + FTL_CHECK(zip_asset_store->GetAsBuffer(kSnapshotAssetKey, &snapshot_data)); + } + + UIDartState* parent_dart_state = static_cast(callback_data); + UIDartState* dart_state = parent_dart_state->CreateForChildIsolate(); + + Dart_Isolate isolate = Dart_CreateIsolate( + script_uri, main, + reinterpret_cast(DART_SYMBOL(kDartIsolateSnapshotBuffer)), + nullptr, dart_state, error); + FTL_CHECK(isolate) << error; + dart_state->SetIsolate(isolate); + FTL_CHECK(!LogIfError( + Dart_SetLibraryTagHandler(tonic::DartState::HandleLibraryTag))); + + { + tonic::DartApiScope dart_api_scope; + DartIO::InitForIsolate(); + DartUI::InitForIsolate(); + DartMojoInternal::InitForIsolate(); + DartRuntimeHooks::Install(DartRuntimeHooks::SecondaryIsolate, script_uri); + + std::unique_ptr ui_class_provider( + new DartClassProvider(dart_state, "dart:ui")); + dart_state->class_library().add_provider("ui", + std::move(ui_class_provider)); + +#ifdef OS_ANDROID + DartJni::InitForIsolate(); + std::unique_ptr jni_class_provider( + new DartClassProvider(dart_state, "dart:jni")); + dart_state->class_library().add_provider("jni", + std::move(jni_class_provider)); +#endif + + if (!snapshot_data.empty()) { + FTL_CHECK(!LogIfError(Dart_LoadScriptFromSnapshot(snapshot_data.data(), + snapshot_data.size()))); + } + + dart_state->isolate_client()->DidCreateSecondaryIsolate(isolate); + } + + Dart_ExitIsolate(); + + FTL_CHECK(Dart_IsolateMakeRunnable(isolate)); + return isolate; +} + +Dart_Handle GetVMServiceAssetsArchiveCallback() { +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_RELEASE + return nullptr; +#else // FLUTTER_RUNTIME_MODE + return tonic::DartConverter::ToDart( + ::dart::observatory::observatory_assets_archive, + ::dart::observatory::observatory_assets_archive_len); +#endif // FLUTTER_RUNTIME_MODE +} + +static const char kStdoutStreamId[] = "Stdout"; +static const char kStderrStreamId[] = "Stderr"; + +static bool ServiceStreamListenCallback(const char* stream_id) { + if (strcmp(stream_id, kStdoutStreamId) == 0) { + dart::bin::SetCaptureStdout(true); + return true; + } else if (strcmp(stream_id, kStderrStreamId) == 0) { + dart::bin::SetCaptureStderr(true); + return true; + } + return false; +} + +static void ServiceStreamCancelCallback(const char* stream_id) { + if (strcmp(stream_id, kStdoutStreamId) == 0) { + dart::bin::SetCaptureStdout(false); + } else if (strcmp(stream_id, kStderrStreamId) == 0) { + dart::bin::SetCaptureStderr(false); + } +} + +#ifdef OS_ANDROID + +DartJniIsolateData* GetDartJniDataForCurrentIsolate() { + return UIDartState::Current()->jni_data(); +} + +#endif + +} // namespace + +#if DART_ALLOW_DYNAMIC_RESOLUTION + +const char* kDartVmIsolateSnapshotBufferName = "kDartVmIsolateSnapshotBuffer"; +const char* kDartIsolateSnapshotBufferName = "kDartIsolateSnapshotBuffer"; +const char* kInstructionsSnapshotName = "kInstructionsSnapshot"; +const char* kDataSnapshotName = "kDataSnapshot"; + +#if OS(IOS) + +const char* kDartApplicationLibraryPath = "app.dylib"; + +static void* DartLookupSymbolInLibrary(const char* symbol_name, + const char* library) { + TRACE_EVENT0("flutter", __func__); + if (symbol_name == nullptr) { + return nullptr; + } + dlerror(); // clear previous errors on thread + void* library_handle = dlopen(library, RTLD_NOW); + if (dlerror() != nullptr) { + return nullptr; + } + void* sym = dlsym(library_handle, symbol_name); + return dlerror() != nullptr ? nullptr : sym; +} + +void* _DartSymbolLookup(const char* symbol_name) { + TRACE_EVENT0("flutter", __func__); + if (symbol_name == nullptr) { + return nullptr; + } + + // First the application library is checked for the valid symbols. This + // library may not necessarily exist. If it does exist, it is loaded and the + // symbols resolved. Once the application library is loaded, there is + // currently no provision to unload the same. + void* symbol = + DartLookupSymbolInLibrary(symbol_name, kDartApplicationLibraryPath); + if (symbol != nullptr) { + return symbol; + } + + // Check inside the default library + return DartLookupSymbolInLibrary(symbol_name, nullptr); +} + +#elif OS(ANDROID) + +// Describes an asset file that holds a part of the precompiled snapshot. +struct SymbolAsset { + const char* symbol_name; + const char* file_name; + bool is_executable; + void* mapping; +}; + +static SymbolAsset g_symbol_assets[] = { + {kDartVmIsolateSnapshotBufferName, "snapshot_aot_vmisolate", false}, + {kDartIsolateSnapshotBufferName, "snapshot_aot_isolate", false}, + {kInstructionsSnapshotName, "snapshot_aot_instr", true}, + {kDataSnapshotName, "snapshot_aot_rodata", false}, +}; + +// Resolve a precompiled snapshot symbol by mapping the corresponding asset +// file into memory. +void* _DartSymbolLookup(const char* symbol_name) { + for (SymbolAsset& symbol_asset : g_symbol_assets) { + if (strcmp(symbol_name, symbol_asset.symbol_name)) + continue; + + if (symbol_asset.mapping) { + return symbol_asset.mapping; + } + + const std::string& aot_snapshot_path = Settings::Get().aot_snapshot_path; + FTL_CHECK(!aot_snapshot_path.empty()); + + std::string asset_path = aot_snapshot_path + "/" + symbol_asset.file_name; + struct stat info; + if (stat(asset_path.c_str(), &info) < 0) + return nullptr; + int64_t asset_size = info.st_size; + + ftl::UniqueFD fd(HANDLE_EINTR(open(asset_path.c_str(), O_RDONLY))); + if (fd.get() == -1) + return nullptr; + + int mmap_flags = PROT_READ; + if (symbol_asset.is_executable) + mmap_flags |= PROT_EXEC; + + void* symbol = mmap(NULL, asset_size, mmap_flags, MAP_PRIVATE, fd.get(), 0); + symbol_asset.mapping = symbol == MAP_FAILED ? nullptr : symbol; + + return symbol_asset.mapping; + } + + return nullptr; +} + +#else + +#error "AOT mode is not supported on this platform" + +#endif + +static const uint8_t* PrecompiledInstructionsSymbolIfPresent() { + return reinterpret_cast(DART_SYMBOL(kInstructionsSnapshot)); +} + +static const uint8_t* PrecompiledDataSnapshotSymbolIfPresent() { + return reinterpret_cast(DART_SYMBOL(kDataSnapshot)); +} + +bool IsRunningPrecompiledCode() { + TRACE_EVENT0("flutter", __func__); + return PrecompiledInstructionsSymbolIfPresent() != nullptr; +} + +#else // DART_ALLOW_DYNAMIC_RESOLUTION + +static const uint8_t* PrecompiledInstructionsSymbolIfPresent() { + return nullptr; +} + +static const uint8_t* PrecompiledDataSnapshotSymbolIfPresent() { + return nullptr; +} + +bool IsRunningPrecompiledCode() { + return false; +} + +#endif // DART_ALLOW_DYNAMIC_RESOLUTION + +EmbedderTracingCallbacks* g_tracing_callbacks = nullptr; + +EmbedderTracingCallbacks::EmbedderTracingCallbacks( + EmbedderTracingCallback start, + EmbedderTracingCallback stop) + : start_tracing_callback(start), stop_tracing_callback(stop) {} + +void SetEmbedderTracingCallbacks( + std::unique_ptr callbacks) { + g_tracing_callbacks = callbacks.release(); +} + +static void EmbedderTimelineStartRecording() { + if (g_tracing_callbacks) + g_tracing_callbacks->start_tracing_callback(); +} + +static void EmbedderTimelineStopRecording() { + if (g_tracing_callbacks) + g_tracing_callbacks->stop_tracing_callback(); +} + +void SetServiceIsolateHook(ServiceIsolateHook hook) { + FTL_CHECK(!g_service_isolate_initialized); + g_service_isolate_hook = hook; +} + +void SetRegisterNativeServiceProtocolExtensionHook( + RegisterNativeServiceProtocolExtensionHook hook) { + CHECK(!g_service_isolate_initialized); + g_register_native_service_protocol_extensions_hook = hook; +} + +static bool ShouldEnableCheckedMode() { + if (IsRunningPrecompiledCode()) { + // Checked mode is never enabled during precompilation. Even snapshot + // generation disables checked mode arguments. + return false; + } + +#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG + return true; +#else + return Settings::Get().enable_dart_checked_mode; +#endif +} + +void PushBackAll(std::vector* args, + const char** argv, + size_t argc) { + for (size_t i = 0; i < argc; ++i) { + args->push_back(argv[i]); + } +} + +void InitDartVM() { + TRACE_EVENT0("flutter", __func__); + + const Settings& settings = Settings::Get(); + + { + TRACE_EVENT0("flutter", "dart::bin::BootstrapDartIo"); + dart::bin::BootstrapDartIo(); + + if (!settings.temp_directory_path.empty()) { + dart::bin::SetSystemTempDirectory(settings.temp_directory_path.c_str()); + } + } + + DartMojoInternal::SetHandleWatcherProducerHandle( + mojo::dart::HandleWatcher::Start()); + + std::vector args; + + // Instruct the VM to ignore unrecognized flags. + // There is a lot of diversity in a lot of combinations when it + // comes to the arguments the VM supports. And, if the VM comes across a flag + // it does not recognize, it exits immediately. + args.push_back("--ignore-unrecognized-flags"); + + PushBackAll(&args, kDartProfilingArgs, arraysize(kDartProfilingArgs)); + PushBackAll(&args, kDartMirrorsArgs, arraysize(kDartMirrorsArgs)); + PushBackAll(&args, kDartBackgroundCompilationArgs, + arraysize(kDartBackgroundCompilationArgs)); + + if (IsRunningPrecompiledCode()) { + PushBackAll(&args, kDartPrecompilationArgs, + arraysize(kDartPrecompilationArgs)); + } + + if (ShouldEnableCheckedMode()) + PushBackAll(&args, kDartCheckedModeArgs, arraysize(kDartCheckedModeArgs)); + + if (settings.start_paused) + PushBackAll(&args, kDartStartPausedArgs, arraysize(kDartStartPausedArgs)); + + if (settings.trace_startup) + PushBackAll(&args, kDartTraceStartupArgs, arraysize(kDartTraceStartupArgs)); + + for (size_t i = 0; i < settings.dart_flags.size(); i++) + args.push_back(settings.dart_flags[i].c_str()); + + FTL_CHECK(Dart_SetVMFlags(args.size(), args.data())); + +#if FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_RELEASE + { + TRACE_EVENT0("flutter", "DartDebugger::InitDebugger"); + // This should be called before calling Dart_Initialize. + tonic::DartDebugger::InitDebugger(); + } +#endif + + DartUI::InitForGlobal(); +#ifdef OS_ANDROID + DartJni::InitForGlobal(GetDartJniDataForCurrentIsolate); +#endif + + // Setup embedder tracing hooks. To avoid data races, it is recommended that + // these hooks be installed before the DartInitialize, so do that setup now. + Dart_SetEmbedderTimelineCallbacks(&EmbedderTimelineStartRecording, + &EmbedderTimelineStopRecording); + + Dart_SetFileModifiedCallback(&DartFileModifiedCallback); + + { + TRACE_EVENT0("flutter", "Dart_Initialize"); + Dart_InitializeParams params = {}; + params.version = DART_INITIALIZE_PARAMS_CURRENT_VERSION; + params.vm_isolate_snapshot = + reinterpret_cast(DART_SYMBOL(kDartVmIsolateSnapshotBuffer)); + params.instructions_snapshot = PrecompiledInstructionsSymbolIfPresent(); + params.data_snapshot = PrecompiledDataSnapshotSymbolIfPresent(); + params.create = IsolateCreateCallback; + params.shutdown = IsolateShutdownCallback; + params.thread_exit = ThreadExitCallback; + params.get_service_assets = GetVMServiceAssetsArchiveCallback; + char* init_error = Dart_Initialize(¶ms); + if (init_error != nullptr) + FTL_LOG(FATAL) << "Error while initializing the Dart VM: " << init_error; + free(init_error); + + // Send the earliest available timestamp in the application lifecycle to + // timeline. The difference between this timestamp and the time we render + // the very first frame gives us a good idea about Flutter's startup time. + // Use a duration event so about:tracing will consider this event when + // deciding the earliest event to use as time 0. + if (blink::engine_main_enter_ts != 0) { + Dart_TimelineEvent("FlutterEngineMainEnter", // label + blink::engine_main_enter_ts, // timestamp0 + blink::engine_main_enter_ts, // timestamp1_or_async_id + Dart_Timeline_Event_Duration, // event type + 0, // argument_count + nullptr, // argument_names + nullptr // argument_values + ); + } + } + + // Allow streaming of stdout and stderr by the Dart vm. + Dart_SetServiceStreamCallbacks(&ServiceStreamListenCallback, + &ServiceStreamCancelCallback); +} + +} // namespace blink diff --git a/engine/src/flutter/runtime/dart_init.h b/engine/src/flutter/runtime/dart_init.h new file mode 100644 index 0000000000..a4e12558c3 --- /dev/null +++ b/engine/src/flutter/runtime/dart_init.h @@ -0,0 +1,72 @@ +// 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. + +#ifndef FLUTTER_RUNTIME_DART_INIT_H_ +#define FLUTTER_RUNTIME_DART_INIT_H_ + +#include "dart/runtime/include/dart_api.h" +#include "lib/ftl/functional/closure.h" +#include "lib/ftl/build_config.h" + +#include +#include + +namespace blink { + +#define DART_ALLOW_DYNAMIC_RESOLUTION (defined(OS_IOS) || FLUTTER_AOT) + +#if DART_ALLOW_DYNAMIC_RESOLUTION + +extern const char* kDartIsolateSnapshotBufferName; + +void* _DartSymbolLookup(const char* symbol_name); + +#define DART_SYMBOL(symbol) _DartSymbolLookup(symbol##Name) + +#else // DART_ALLOW_DYNAMIC_RESOLUTION + +extern "C" { +extern void* kDartVmIsolateSnapshotBuffer; +extern void* kDartIsolateSnapshotBuffer; +} + +#define DART_SYMBOL(symbol) (&symbol) + +#endif // DART_ALLOW_DYNAMIC_RESOLUTION + +// Name of the snapshot blob asset within the FLX bundle. +extern const char kSnapshotAssetKey[]; + +bool IsRunningPrecompiledCode(); + +using EmbedderTracingCallback = ftl::Closure; + +typedef void (*ServiceIsolateHook)(bool); +typedef void (*RegisterNativeServiceProtocolExtensionHook)(bool); + +struct EmbedderTracingCallbacks { + EmbedderTracingCallback start_tracing_callback; + EmbedderTracingCallback stop_tracing_callback; + + EmbedderTracingCallbacks(EmbedderTracingCallback start, + EmbedderTracingCallback stop); +}; + +void InitDartVM(); + +void SetEmbedderTracingCallbacks( + std::unique_ptr callbacks); + +// Provide a function that will be called during initialization of the +// service isolate. +void SetServiceIsolateHook(ServiceIsolateHook hook); + +// Provide a function that will be called to register native service protocol +// extensions. +void SetRegisterNativeServiceProtocolExtensionHook( + RegisterNativeServiceProtocolExtensionHook hook); + +} // namespace blink + +#endif // FLUTTER_RUNTIME_DART_INIT_H_ diff --git a/engine/src/flutter/runtime/dart_service_isolate.cc b/engine/src/flutter/runtime/dart_service_isolate.cc new file mode 100644 index 0000000000..81a42e145f --- /dev/null +++ b/engine/src/flutter/runtime/dart_service_isolate.cc @@ -0,0 +1,288 @@ +// 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. + +#include "flutter/runtime/dart_service_isolate.h" + +#include + +#include "dart/runtime/include/dart_api.h" +#include "flutter/runtime/embedder_resources.h" +#include "lib/ftl/logging.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "lib/tonic/logging/dart_error.h" + +#define RETURN_ERROR_HANDLE(handle) \ + if (Dart_IsError(handle)) { \ + return handle; \ + } + +#define SHUTDOWN_ON_ERROR(handle) \ + if (Dart_IsError(handle)) { \ + *error = strdup(Dart_GetError(handle)); \ + Dart_ExitScope(); \ + Dart_ShutdownIsolate(); \ + return false; \ + } + +#define kLibrarySourceNamePrefix "/vmservice" +static const char* kServiceIsolateScript = "vmservice_io.dart"; + +namespace mojo { +namespace dart { +extern ResourcesEntry __sky_embedder_service_isolate_resources_[]; +} +} + +namespace blink { +namespace { + +static Dart_LibraryTagHandler g_embedder_tag_handler; +static tonic::DartLibraryNatives* g_natives; +static EmbedderResources* g_resources; +static int observatory_port_; + +Dart_NativeFunction GetNativeFunction(Dart_Handle name, + int argument_count, + bool* auto_setup_scope) { + FTL_CHECK(g_natives); + return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope); +} + +const uint8_t* GetSymbol(Dart_NativeFunction native_function) { + FTL_CHECK(g_natives); + return g_natives->GetSymbol(native_function); +} + +} // namespace + +void DartServiceIsolate::TriggerResourceLoad(Dart_NativeArguments args) { + Dart_Handle library = Dart_RootLibrary(); + FTL_DCHECK(!Dart_IsError(library)); + Dart_Handle result = LoadResources(library); + FTL_DCHECK(!Dart_IsError(result)); +} + +void DartServiceIsolate::NotifyServerState(Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + int port = tonic::DartConverter::FromArguments(args, 1, exception); + if (!exception) { + observatory_port_ = port; + } +} + +int DartServiceIsolate::GetObservatoryPort() { + return observatory_port_; +} + +void DartServiceIsolate::Shutdown(Dart_NativeArguments args) { + // NO-OP. +} + +bool DartServiceIsolate::Startup(std::string server_ip, + intptr_t server_port, + Dart_LibraryTagHandler embedder_tag_handler, + bool running_precompiled, + bool disable_origin_check, + char** error) { + Dart_Isolate isolate = Dart_CurrentIsolate(); + FTL_CHECK(isolate); + + // Remember the embedder's library tag handler. + g_embedder_tag_handler = embedder_tag_handler; + FTL_CHECK(g_embedder_tag_handler); + + // Setup native entries. + if (!g_natives) { + g_natives = new tonic::DartLibraryNatives(); + g_natives->Register({ + {"VMServiceIO_NotifyServerState", NotifyServerState, 2, true}, + {"VMServiceIO_Shutdown", Shutdown, 0, true}, + }); + } + + if (!g_resources) { + g_resources = new EmbedderResources( + &mojo::dart::__sky_embedder_service_isolate_resources_[0]); + } + + Dart_Handle result; + + if (running_precompiled) { + Dart_Handle uri = Dart_NewStringFromCString("dart:vmservice_sky"); + Dart_Handle library = Dart_LookupLibrary(uri); + SHUTDOWN_ON_ERROR(library); + result = Dart_SetRootLibrary(library); + SHUTDOWN_ON_ERROR(result); + result = Dart_SetNativeResolver(library, GetNativeFunction, GetSymbol); + SHUTDOWN_ON_ERROR(result); + } else { + // Use our own library tag handler when loading service isolate sources. + Dart_SetLibraryTagHandler(DartServiceIsolate::LibraryTagHandler); + // Load main script. + Dart_Handle library = LoadScript(kServiceIsolateScript); + FTL_DCHECK(library != Dart_Null()); + SHUTDOWN_ON_ERROR(library); + // Setup native entry resolution. + result = Dart_SetNativeResolver(library, GetNativeFunction, GetSymbol); + + SHUTDOWN_ON_ERROR(result); + // Finalize loading. + result = Dart_FinalizeLoading(false); + SHUTDOWN_ON_ERROR(result); + } + + // Make runnable. + Dart_ExitScope(); + Dart_ExitIsolate(); + bool retval = Dart_IsolateMakeRunnable(isolate); + if (!retval) { + Dart_EnterIsolate(isolate); + Dart_ShutdownIsolate(); + *error = strdup("Invalid isolate state - Unable to make it runnable."); + return false; + } + Dart_EnterIsolate(isolate); + Dart_EnterScope(); + + Dart_Handle library = Dart_RootLibrary(); + SHUTDOWN_ON_ERROR(library); + + // Set the HTTP server's ip. + result = Dart_SetField(library, Dart_NewStringFromCString("_ip"), + Dart_NewStringFromCString(server_ip.c_str())); + SHUTDOWN_ON_ERROR(result); + // If we have a port specified, start the server immediately. + bool auto_start = server_port >= 0; + if (server_port < 0) { + // Adjust server_port to port 0 which will result in the first available + // port when the HTTP server is started. + server_port = 0; + } + // Set the HTTP's servers port. + result = Dart_SetField(library, Dart_NewStringFromCString("_port"), + Dart_NewInteger(server_port)); + SHUTDOWN_ON_ERROR(result); + result = Dart_SetField(library, Dart_NewStringFromCString("_autoStart"), + Dart_NewBoolean(auto_start)); + SHUTDOWN_ON_ERROR(result); + result = + Dart_SetField(library, Dart_NewStringFromCString("_originCheckDisabled"), + Dart_NewBoolean(disable_origin_check)); + SHUTDOWN_ON_ERROR(result); + return true; +} + +Dart_Handle DartServiceIsolate::GetSource(const char* name) { + const intptr_t kBufferSize = 512; + char buffer[kBufferSize]; + snprintf(&buffer[0], kBufferSize - 1, "%s/%s", kLibrarySourceNamePrefix, + name); + const char* vmservice_source = NULL; + int r = g_resources->ResourceLookup(buffer, &vmservice_source); + FTL_DCHECK(r != EmbedderResources::kNoSuchInstance); + return Dart_NewStringFromCString(vmservice_source); +} + +Dart_Handle DartServiceIsolate::LoadScript(const char* name) { + Dart_Handle url = Dart_NewStringFromCString("dart:vmservice_sky"); + Dart_Handle source = GetSource(name); + return Dart_LoadScript(url, Dart_Null(), source, 0, 0); +} + +Dart_Handle DartServiceIsolate::LoadSource(Dart_Handle library, + const char* name) { + Dart_Handle url = Dart_NewStringFromCString(name); + Dart_Handle source = GetSource(name); + return Dart_LoadSource(library, url, Dart_Null(), source, 0, 0); +} + +Dart_Handle DartServiceIsolate::LoadResource(Dart_Handle library, + const char* resource_name) { + // Prepare for invoke call. + Dart_Handle name = Dart_NewStringFromCString(resource_name); + RETURN_ERROR_HANDLE(name); + const char* data_buffer = NULL; + int data_buffer_length = + g_resources->ResourceLookup(resource_name, &data_buffer); + FTL_DCHECK(data_buffer_length != EmbedderResources::kNoSuchInstance); + Dart_Handle data_list = + Dart_NewTypedData(Dart_TypedData_kUint8, data_buffer_length); + RETURN_ERROR_HANDLE(data_list); + Dart_TypedData_Type type = Dart_TypedData_kInvalid; + void* data_list_buffer = NULL; + intptr_t data_list_buffer_length = 0; + Dart_Handle result = Dart_TypedDataAcquireData( + data_list, &type, &data_list_buffer, &data_list_buffer_length); + RETURN_ERROR_HANDLE(result); + FTL_DCHECK(data_buffer_length == data_list_buffer_length); + FTL_DCHECK(data_list_buffer != NULL); + FTL_DCHECK(type = Dart_TypedData_kUint8); + memmove(data_list_buffer, &data_buffer[0], data_buffer_length); + result = Dart_TypedDataReleaseData(data_list); + RETURN_ERROR_HANDLE(result); + + // Make invoke call. + const intptr_t kNumArgs = 2; + Dart_Handle args[kNumArgs] = {name, data_list}; + result = Dart_Invoke(library, Dart_NewStringFromCString("_addResource"), + kNumArgs, args); + return result; +} + +Dart_Handle DartServiceIsolate::LoadResources(Dart_Handle library) { + Dart_Handle result = Dart_Null(); + intptr_t prefixLen = strlen(kLibrarySourceNamePrefix); + for (intptr_t i = 0; g_resources->Path(i) != NULL; i++) { + const char* path = g_resources->Path(i); + // If it doesn't begin with kLibrarySourceNamePrefix it is a frontend + // resource. + if (strncmp(path, kLibrarySourceNamePrefix, prefixLen) != 0) { + result = LoadResource(library, path); + if (Dart_IsError(result)) { + break; + } + } + } + return result; +} + +Dart_Handle DartServiceIsolate::LibraryTagHandler(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url) { + if (!Dart_IsLibrary(library)) { + return Dart_NewApiError("not a library"); + } + if (!Dart_IsString(url)) { + return Dart_NewApiError("url is not a string"); + } + const char* url_string = NULL; + Dart_Handle result = Dart_StringToCString(url, &url_string); + if (Dart_IsError(result)) { + return result; + } + Dart_Handle library_url = Dart_LibraryUrl(library); + const char* library_url_string = NULL; + result = Dart_StringToCString(library_url, &library_url_string); + if (Dart_IsError(result)) { + return result; + } + if (tag == Dart_kImportTag) { + // Embedder handles all requests for external libraries. + return g_embedder_tag_handler(tag, library, url); + } + FTL_DCHECK((tag == Dart_kSourceTag) || (tag == Dart_kCanonicalizeUrl)); + if (tag == Dart_kCanonicalizeUrl) { + // url is already canonicalized. + return url; + } + // Get source from builtin resources. + Dart_Handle source = GetSource(url_string); + if (Dart_IsError(source)) { + return source; + } + return Dart_LoadSource(library, url, Dart_Null(), source, 0, 0); +} + +} // namespace blink diff --git a/engine/src/flutter/runtime/dart_service_isolate.h b/engine/src/flutter/runtime/dart_service_isolate.h new file mode 100644 index 0000000000..aeaaba292e --- /dev/null +++ b/engine/src/flutter/runtime/dart_service_isolate.h @@ -0,0 +1,48 @@ +// 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. + +#ifndef FLUTTER_RUNTIME_DART_SERVICE_ISOLATE_H_ +#define FLUTTER_RUNTIME_DART_SERVICE_ISOLATE_H_ + +#include + +#include "dart/runtime/include/dart_api.h" + +namespace blink { + +class DartServiceIsolate { + public: + static bool Bootstrap(); + + static bool Startup(std::string server_ip, + intptr_t server_port, + Dart_LibraryTagHandler embedder_tag_handler, + bool running_precompiled, + bool disable_origin_check, + char** error); + + static int GetObservatoryPort(); + + private: + // Native entries. + static void TriggerResourceLoad(Dart_NativeArguments args); + static void NotifyServerState(Dart_NativeArguments args); + static void Shutdown(Dart_NativeArguments args); + + // Script loading. + static Dart_Handle GetSource(const char* name); + static Dart_Handle LoadScript(const char* name); + static Dart_Handle LoadSource(Dart_Handle library, const char* name); + static Dart_Handle LibraryTagHandler(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url); + + // Observatory resource loading. + static Dart_Handle LoadResources(Dart_Handle library); + static Dart_Handle LoadResource(Dart_Handle library, const char* name); +}; + +} // namespace blink + +#endif // FLUTTER_RUNTIME_DART_SERVICE_ISOLATE_H_ diff --git a/engine/src/flutter/runtime/dart_vm_entry_points.txt b/engine/src/flutter/runtime/dart_vm_entry_points.txt new file mode 100644 index 0000000000..609b3ed386 --- /dev/null +++ b/engine/src/flutter/runtime/dart_vm_entry_points.txt @@ -0,0 +1,31 @@ +dart:io,::,_setupHooks +dart:io,_Platform,set:_nativeScript +dart:isolate,::,_startMainIsolate +dart:mojo.internal,MojoHandleWatcher,mojoControlHandle +dart:ui,::,_beginFrame +dart:ui,::,_dispatchPointerPacket +dart:ui,::,_getGetBaseURLClosure +dart:ui,::,_getMainClosure +dart:ui,::,_getPrintClosure +dart:ui,::,_getScheduleMicrotaskClosure +dart:ui,::,_onAppLifecycleStateChanged +dart:ui,::,_popRoute +dart:ui,::,_pushRoute +dart:ui,::,_setupHooks +dart:ui,::,_updateLocale +dart:ui,::,_updateWindowMetrics +dart:ui,Canvas,Canvas. +dart:ui,Color,Color. +dart:ui,Image,Image. +dart:ui,ImageShader,ImageShader. +dart:ui,Paragraph,Paragraph. +dart:ui,ParagraphBuilder,ParagraphBuilder. +dart:ui,Path,Path. +dart:ui,Picture,Picture. +dart:ui,PictureRecorder,PictureRecorder. +dart:ui,Rect,Rect.fromLTRB +dart:ui,Scene,Scene. +dart:ui,SceneBuilder,SceneBuilder. +dart:ui,Shader,Shader. +dart:ui,TextBox,TextBox._ +dart:vmservice_sky,::,main diff --git a/engine/src/flutter/runtime/dart_vm_entry_points_android.txt b/engine/src/flutter/runtime/dart_vm_entry_points_android.txt new file mode 100644 index 0000000000..78ec6617e8 --- /dev/null +++ b/engine/src/flutter/runtime/dart_vm_entry_points_android.txt @@ -0,0 +1,3 @@ +dart:jni,JniObject,JniObject. +dart:jni,JniFloat,JniFloat. +dart:jni,JniFloat,get:value diff --git a/engine/src/flutter/runtime/embedder_resources.cc b/engine/src/flutter/runtime/embedder_resources.cc new file mode 100644 index 0000000000..851a71b448 --- /dev/null +++ b/engine/src/flutter/runtime/embedder_resources.cc @@ -0,0 +1,52 @@ +// Copyright 2016 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. + +#include "flutter/runtime/embedder_resources.h" + +#include + +#include "lib/ftl/logging.h" + +namespace blink { + +using mojo::dart::ResourcesEntry; + +EmbedderResources::EmbedderResources(ResourcesEntry* resources_table) + : resources_table_(resources_table) {} + +const int EmbedderResources::kNoSuchInstance = -1; + +int EmbedderResources::ResourceLookup(const char* path, const char** resource) { + for (int i = 0; resources_table_[i].path_ != nullptr; i++) { + const ResourcesEntry& entry = resources_table_[i]; + if (strcmp(path, entry.path_) == 0) { + *resource = entry.resource_; + FTL_DCHECK(entry.length_ > 0); + return entry.length_; + } + } + return kNoSuchInstance; +} + +const char* EmbedderResources::Path(int idx) { + FTL_DCHECK(idx >= 0); + ResourcesEntry* entry = At(idx); + if (entry == nullptr) { + return nullptr; + } + FTL_DCHECK(entry->path_ != nullptr); + return entry->path_; +} + +ResourcesEntry* EmbedderResources::At(int idx) { + FTL_DCHECK(idx >= 0); + for (int i = 0; resources_table_[i].path_ != nullptr; i++) { + if (idx == i) { + return &resources_table_[i]; + } + } + return nullptr; +} + +} // namespace blink diff --git a/engine/src/flutter/runtime/embedder_resources.h b/engine/src/flutter/runtime/embedder_resources.h new file mode 100644 index 0000000000..2bc25177c2 --- /dev/null +++ b/engine/src/flutter/runtime/embedder_resources.h @@ -0,0 +1,39 @@ +// Copyright 2016 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. + +#ifndef FLUTTER_RUNTIME_EMBEDDER_RESOURCES_H_ +#define FLUTTER_RUNTIME_EMBEDDER_RESOURCES_H_ + +namespace mojo { +namespace dart { + +struct ResourcesEntry { + const char* path_; + const char* resource_; + int length_; +}; + +} // namespace dart +} // namespace mojo + +namespace blink { + +class EmbedderResources { + public: + EmbedderResources(mojo::dart::ResourcesEntry* resources_table); + + static const int kNoSuchInstance; + + int ResourceLookup(const char* path, const char** resource); + const char* Path(int idx); + + private: + mojo::dart::ResourcesEntry* At(int idx); + + mojo::dart::ResourcesEntry* resources_table_; +}; + +} // namespace blink + +#endif // FLUTTER_RUNTIME_EMBEDDER_RESOURCES_H_ diff --git a/engine/src/flutter/runtime/sky_view.cc b/engine/src/flutter/runtime/sky_view.cc new file mode 100644 index 0000000000..dadc3366e0 --- /dev/null +++ b/engine/src/flutter/runtime/sky_view.cc @@ -0,0 +1,114 @@ +// 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. + +#include "flutter/runtime/sky_view.h" + +#include "flutter/glue/trace_event.h" +#include "flutter/lib/ui/compositing/scene.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "flutter/lib/ui/window/window.h" +#include "flutter/runtime/dart_controller.h" +#include "flutter/runtime/sky_view_client.h" + +using tonic::DartState; + +namespace blink { + +std::unique_ptr SkyView::Create(SkyViewClient* client) { + return std::unique_ptr(new SkyView(client)); +} + +SkyView::SkyView(SkyViewClient* client) : client_(client) {} + +SkyView::~SkyView() {} + +void SkyView::SetViewportMetrics(const sky::ViewportMetricsPtr& metrics) { + if (metrics) { + viewport_metrics_ = metrics->Clone(); + GetWindow()->UpdateWindowMetrics(viewport_metrics_); + } else { + viewport_metrics_ = nullptr; + } +} + +void SkyView::SetLocale(const std::string& language_code, + const std::string& country_code) { + if (language_code_ == language_code && country_code_ == country_code) + return; + + language_code_ = language_code; + country_code_ = country_code; + GetWindow()->UpdateLocale(language_code_, country_code_); +} + +void SkyView::PushRoute(const std::string& route) { + GetWindow()->PushRoute(route); +} + +void SkyView::PopRoute() { + GetWindow()->PopRoute(); +} + +void SkyView::CreateView(const std::string& script_uri) { + DCHECK(!dart_controller_); + + dart_controller_.reset(new DartController()); + std::unique_ptr window(new Window(this)); + std::unique_ptr dart_state( + new UIDartState(this, std::move(window))); + dart_controller_->CreateIsolateFor(script_uri, std::move(dart_state)); + + DartState::Scope scope(dart_state.get()); + dart_state->window()->DidCreateIsolate(); + client_->DidCreateMainIsolate(dart_state->isolate()); + + if (viewport_metrics_) + GetWindow()->UpdateWindowMetrics(viewport_metrics_); + GetWindow()->UpdateLocale(language_code_, country_code_); +} + +void SkyView::BeginFrame(ftl::TimePoint frame_time) { + GetWindow()->BeginFrame(frame_time); +} + +void SkyView::HandlePointerPacket(const pointer::PointerPacketPtr& packet) { + TRACE_EVENT0("input", "SkyView::HandlePointerPacket"); + GetWindow()->DispatchPointerPacket(packet); +} + +Window* SkyView::GetWindow() { + return dart_controller_->dart_state()->window(); +} + +void SkyView::ScheduleFrame() { + client_->ScheduleFrame(); +} + +void SkyView::FlushRealTimeEvents() { + client_->FlushRealTimeEvents(); +} + +void SkyView::Render(Scene* scene) { + client_->Render(scene->takeLayerTree()); +} + +void SkyView::DidCreateSecondaryIsolate(Dart_Isolate isolate) { + client_->DidCreateSecondaryIsolate(isolate); +} + +void SkyView::OnAppLifecycleStateChanged(sky::AppLifecycleState state) { + GetWindow()->OnAppLifecycleStateChanged(state); +} + +Dart_Port SkyView::GetMainPort() { + if (!dart_controller_) { + return ILLEGAL_PORT; + } + if (!dart_controller_->dart_state()) { + return ILLEGAL_PORT; + } + return dart_controller_->dart_state()->main_port(); +} + +} // namespace blink diff --git a/engine/src/flutter/runtime/sky_view.h b/engine/src/flutter/runtime/sky_view.h new file mode 100644 index 0000000000..5f0e7bd07d --- /dev/null +++ b/engine/src/flutter/runtime/sky_view.h @@ -0,0 +1,69 @@ +// 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. + +#ifndef FLUTTER_RUNTIME_SKY_VIEW_H_ +#define FLUTTER_RUNTIME_SKY_VIEW_H_ + +#include + +#include "flutter/flow/layers/layer_tree.h" +#include "flutter/lib/ui/ui_dart_state.h" +#include "flutter/lib/ui/window/window.h" +#include "flutter/services/engine/sky_engine.mojom.h" +#include "flutter/services/pointer/pointer.mojom.h" +#include "lib/ftl/macros.h" + +namespace blink { +class DartController; +class DartLibraryProvider; +class Scene; +class SkyViewClient; +class View; +class Window; + +class SkyView : public WindowClient, public IsolateClient { + public: + static std::unique_ptr Create(SkyViewClient* client); + ~SkyView(); + + void SetViewportMetrics(const sky::ViewportMetricsPtr& metrics); + void SetLocale(const std::string& language_code, + const std::string& country_code); + void PushRoute(const std::string& route); + void PopRoute(); + + void BeginFrame(ftl::TimePoint frame_time); + + void CreateView(const std::string& script_uri); + DartController* dart_controller() const { return dart_controller_.get(); } + + void HandlePointerPacket(const pointer::PointerPacketPtr& packet); + + void OnAppLifecycleStateChanged(sky::AppLifecycleState state); + + Dart_Port GetMainPort(); + + private: + explicit SkyView(SkyViewClient* client); + + Window* GetWindow(); + + void ScheduleFrame() override; + void FlushRealTimeEvents() override; + void Render(Scene* scene) override; + + void DidCreateSecondaryIsolate(Dart_Isolate isolate) override; + + SkyViewClient* client_; + sky::ViewportMetricsPtr viewport_metrics_; + std::string language_code_; + std::string country_code_; + std::unique_ptr dart_controller_; + + FTL_DISALLOW_COPY_AND_ASSIGN(SkyView); +}; + +} // namespace blink + +#endif // FLUTTER_RUNTIME_SKY_VIEW_H_ diff --git a/engine/src/flutter/runtime/sky_view_client.cc b/engine/src/flutter/runtime/sky_view_client.cc new file mode 100644 index 0000000000..0bdb61cdb3 --- /dev/null +++ b/engine/src/flutter/runtime/sky_view_client.cc @@ -0,0 +1,11 @@ +// 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. + +#include "flutter/runtime/sky_view_client.h" + +namespace blink { + +SkyViewClient::~SkyViewClient() {} + +} // namespace blink diff --git a/engine/src/flutter/runtime/sky_view_client.h b/engine/src/flutter/runtime/sky_view_client.h new file mode 100644 index 0000000000..e0fc129139 --- /dev/null +++ b/engine/src/flutter/runtime/sky_view_client.h @@ -0,0 +1,30 @@ +// 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. + +#ifndef FLUTTER_RUNTIME_SKY_VIEW_CLIENT_H_ +#define FLUTTER_RUNTIME_SKY_VIEW_CLIENT_H_ + +#include + +#include "dart/runtime/include/dart_api.h" +#include "flutter/flow/layers/layer_tree.h" + +namespace blink { + +class SkyViewClient { + public: + virtual void ScheduleFrame() = 0; + virtual void FlushRealTimeEvents() = 0; + virtual void Render(std::unique_ptr layer_tree) = 0; + + virtual void DidCreateMainIsolate(Dart_Isolate isolate) = 0; + virtual void DidCreateSecondaryIsolate(Dart_Isolate isolate) = 0; + + protected: + virtual ~SkyViewClient(); +}; + +} // namespace blink + +#endif // FLUTTER_RUNTIME_SKY_VIEW_CLIENT_H_ diff --git a/engine/src/flutter/runtime/start_up.cc b/engine/src/flutter/runtime/start_up.cc new file mode 100644 index 0000000000..22a4b966d3 --- /dev/null +++ b/engine/src/flutter/runtime/start_up.cc @@ -0,0 +1,11 @@ +// Copyright 2016 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. + +#include "flutter/runtime/start_up.h" + +namespace blink { + +int64_t engine_main_enter_ts = 0; + +} // namespace blink diff --git a/engine/src/flutter/runtime/start_up.h b/engine/src/flutter/runtime/start_up.h new file mode 100644 index 0000000000..49e0726239 --- /dev/null +++ b/engine/src/flutter/runtime/start_up.h @@ -0,0 +1,24 @@ +// Copyright 2016 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. + +#ifndef FLUTTER_RUNTIME_START_UP_H_ +#define FLUTTER_RUNTIME_START_UP_H_ + +#include + +namespace blink { + +// The earliest available timestamp in the application's lifecycle. The +// difference between this timestamp and the time we render the very first +// frame gives us a good idea about Flutter's startup time. +// +// This timestamp only covers Flutter's own startup. In an upside-down model +// it is possible that the first Flutter view is not initialized until some +// time later. In this case the timestamp may not cover the time spent in the +// user code prior to initializing Flutter. +extern int64_t engine_main_enter_ts; + +} // namespace blink + +#endif // FLUTTER_RUNTIME_START_UP_H_ diff --git a/engine/src/flutter/sky/packages/sky_engine/BUILD.gn b/engine/src/flutter/sky/packages/sky_engine/BUILD.gn index 9fc89de138..53981238ed 100644 --- a/engine/src/flutter/sky/packages/sky_engine/BUILD.gn +++ b/engine/src/flutter/sky/packages/sky_engine/BUILD.gn @@ -107,13 +107,11 @@ dart_pkg("sky_engine") { ":copy_dart_sdk", ":copy_dart_ui", ":copy_sky_engine_authors", - "//flutter/sky/engine/bindings", ] service_isolate_dir = "//dart/runtime/bin/vmservice" sdk_ext_directory = "$root_gen_dir/sky/bindings" sdk_ext_files = [ - "//flutter/sky/engine/bindings/internals.dart", "$service_isolate_dir/vmservice_io.dart", "$service_isolate_dir/loader.dart", "$service_isolate_dir/server.dart",