dart:ui conversion from native to FfiNative (flutter/engine#29607)

This commit is contained in:
Clement Skau 2022-05-04 18:29:05 +02:00 committed by GitHub
parent a42a6c4c48
commit ca1dc06bc1
84 changed files with 1606 additions and 1601 deletions

View File

@ -264,6 +264,7 @@ compile_platform("strong_platform") {
is_runtime_mode_release =
flutter_runtime_mode == "release" || flutter_runtime_mode == "jit_release"
args = [
"--enable-experiment=generic-metadata",
"--nnbd-agnostic",
"--target=flutter",
"-Ddart.vm.product=$is_runtime_mode_release",

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
// TODO(dnfield): Update this if/when we default this to on in the tool,

View File

@ -5,7 +5,7 @@
// KEEP THIS SYNCHRONIZED WITH ../web_ui/lib/channel_buffers.dart
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// Signature for [ChannelBuffers.drain]'s `callback` argument.

View File

@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// An opaque object representing a composited scene.
@ -41,12 +40,17 @@ class Scene extends NativeFieldWrapperClass1 {
);
}
String? _toImage(int width, int height, _Callback<_Image?> callback) native 'Scene_toImage';
@FfiNative<Handle Function(Pointer<Void>, Uint32, Uint32, Handle)>('Scene::toImage')
external String? _toImage(int width, int height, _Callback<_Image?> callback);
/// Releases the resources used by this scene.
///
/// After calling this function, the scene is cannot be used further.
void dispose() native 'Scene_dispose';
///
/// This can't be a leaf call because the native function calls Dart API
/// (Dart_SetNativeInstanceField).
@FfiNative<Void Function(Pointer<Void>)>('Scene::dispose')
external void dispose();
}
// Lightweight wrapper of a native layer object.
@ -211,7 +215,9 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
SceneBuilder() {
_constructor();
}
void _constructor() native 'SceneBuilder_constructor';
@FfiNative<Void Function(Handle)>('SceneBuilder::Create')
external void _constructor();
// Layers used in this scene.
//
@ -307,8 +313,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushTransform(EngineLayer layer, Float64List matrix4, EngineLayer? oldLayer)
native 'SceneBuilder_pushTransform';
@FfiNative<Void Function(Pointer<Void>, Handle, Handle, Handle)>('SceneBuilder::pushTransformHandle')
external void _pushTransform(EngineLayer layer, Float64List matrix4, EngineLayer? oldLayer);
/// Pushes an offset operation onto the operation stack.
///
@ -332,8 +338,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushOffset(EngineLayer layer, double dx, double dy, EngineLayer? oldLayer)
native 'SceneBuilder_pushOffset';
@FfiNative<Void Function(Pointer<Void>, Handle, Double, Double, Handle)>('SceneBuilder::pushOffset')
external void _pushOffset(EngineLayer layer, double dx, double dy, EngineLayer? oldLayer);
/// Pushes a rectangular clip operation onto the operation stack.
///
@ -361,8 +367,15 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushClipRect(EngineLayer outEngineLayer, double left, double right, double top,
double bottom, int clipBehavior, EngineLayer? oldLayer) native 'SceneBuilder_pushClipRect';
@FfiNative<Void Function(Pointer<Void>, Handle, Double, Double, Double, Double, Int32, Handle)>('SceneBuilder::pushClipRect')
external void _pushClipRect(
EngineLayer outEngineLayer,
double left,
double right,
double top,
double bottom,
int clipBehavior,
EngineLayer? oldLayer);
/// Pushes a rounded-rectangular clip operation onto the operation stack.
///
@ -389,8 +402,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushClipRRect(EngineLayer layer, Float32List rrect, int clipBehavior, EngineLayer? oldLayer)
native 'SceneBuilder_pushClipRRect';
@FfiNative<Void Function(Pointer<Void>, Handle, Handle, Int32, Handle)>('SceneBuilder::pushClipRRect')
external void _pushClipRRect(EngineLayer layer, Float32List rrect, int clipBehavior, EngineLayer? oldLayer);
/// Pushes a path clip operation onto the operation stack.
///
@ -417,8 +430,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushClipPath(EngineLayer layer, Path path, int clipBehavior, EngineLayer? oldLayer)
native 'SceneBuilder_pushClipPath';
@FfiNative<Void Function(Pointer<Void>, Handle, Pointer<Void>, Int32, Handle)>('SceneBuilder::pushClipPath')
external void _pushClipPath(EngineLayer layer, Path path, int clipBehavior, EngineLayer? oldLayer);
/// Pushes an opacity operation onto the operation stack.
///
@ -445,8 +458,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushOpacity(EngineLayer layer, int alpha, double dx, double dy, EngineLayer? oldLayer)
native 'SceneBuilder_pushOpacity';
@FfiNative<Void Function(Pointer<Void>, Handle, Int32, Double, Double, Handle)>('SceneBuilder::pushOpacity')
external void _pushOpacity(EngineLayer layer, int alpha, double dx, double dy, EngineLayer? oldLayer);
/// Pushes a color filter operation onto the operation stack.
///
@ -473,8 +486,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushColorFilter(EngineLayer layer, _ColorFilter filter, EngineLayer? oldLayer)
native 'SceneBuilder_pushColorFilter';
@FfiNative<Void Function(Pointer<Void>, Handle, Pointer<Void>, Handle)>('SceneBuilder::pushColorFilter')
external void _pushColorFilter(EngineLayer layer, _ColorFilter filter, EngineLayer? oldLayer);
/// Pushes an image filter operation onto the operation stack.
///
@ -501,8 +514,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushImageFilter(EngineLayer outEngineLayer, _ImageFilter filter, EngineLayer? oldLayer)
native 'SceneBuilder_pushImageFilter';
@FfiNative<Void Function(Pointer<Void>, Handle, Pointer<Void>, Handle)>('SceneBuilder::pushImageFilter')
external void _pushImageFilter(EngineLayer outEngineLayer, _ImageFilter filter, EngineLayer? oldLayer);
/// Pushes a backdrop filter operation onto the operation stack.
///
@ -528,8 +541,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushBackdropFilter(EngineLayer outEngineLayer, _ImageFilter filter, int blendMode, EngineLayer? oldLayer)
native 'SceneBuilder_pushBackdropFilter';
@FfiNative<Void Function(Pointer<Void>, Handle, Pointer<Void>, Int32, Handle)>('SceneBuilder::pushBackdropFilter')
external void _pushBackdropFilter(EngineLayer outEngineLayer, _ImageFilter filter, int blendMode, EngineLayer? oldLayer);
/// Pushes a shader mask operation onto the operation stack.
///
@ -566,7 +579,9 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushShaderMask(
@FfiNative<Void Function(Pointer<Void>, Handle, Pointer<Void>, Double, Double, Double, Double, Int32, Int32, Handle)>(
'SceneBuilder::pushShaderMask')
external void _pushShaderMask(
EngineLayer engineLayer,
Shader shader,
double maskRectLeft,
@ -575,7 +590,7 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
double maskRectBottom,
int blendMode,
int filterQualityIndex,
EngineLayer? oldLayer) native 'SceneBuilder_pushShaderMask';
EngineLayer? oldLayer);
/// Pushes a physical layer operation for an arbitrary shape onto the
/// operation stack.
@ -610,14 +625,15 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return layer;
}
void _pushPhysicalShape(
@FfiNative<Void Function(Pointer<Void>, Handle, Pointer<Void>, Double, Int32, Int32, Int32, Handle)>('SceneBuilder::pushPhysicalShape')
external void _pushPhysicalShape(
EngineLayer outEngineLayer,
Path path,
double elevation,
int color,
int shadowColor,
int clipBehavior,
EngineLayer? oldLayer) native 'SceneBuilder_pushPhysicalShape';
EngineLayer? oldLayer);
/// Ends the effect of the most recently pushed operation.
///
@ -632,7 +648,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
_pop();
}
void _pop() native 'SceneBuilder_pop';
@FfiNative<Void Function(Pointer<Void>)>('SceneBuilder::pop', isLeaf: true)
external void _pop();
/// Add a retained engine layer subtree from previous frames.
///
@ -671,7 +688,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
_addRetained(wrapper._nativeLayer!);
}
void _addRetained(EngineLayer retainedLayer) native 'SceneBuilder_addRetained';
@FfiNative<Void Function(Pointer<Void>, Handle)>('SceneBuilder::addRetained')
external void _addRetained(EngineLayer retainedLayer);
/// Adds an object to the scene that displays performance statistics.
///
@ -701,13 +719,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
_addPerformanceOverlay(enabledOptions, bounds.left, bounds.right, bounds.top, bounds.bottom);
}
void _addPerformanceOverlay(
int enabledOptions,
double left,
double right,
double top,
double bottom,
) native 'SceneBuilder_addPerformanceOverlay';
@FfiNative<Void Function(Pointer<Void>, Uint64, Double, Double, Double, Double)>('SceneBuilder::addPerformanceOverlay', isLeaf: true)
external void _addPerformanceOverlay(int enabledOptions, double left, double right, double top, double bottom);
/// Adds a [Picture] to the scene.
///
@ -723,8 +736,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
_addPicture(offset.dx, offset.dy, picture, hints);
}
void _addPicture(double dx, double dy, Picture picture, int hints)
native 'SceneBuilder_addPicture';
@FfiNative<Void Function(Pointer<Void>, Double, Double, Pointer<Void>, Int32)>('SceneBuilder::addPicture')
external void _addPicture(double dx, double dy, Picture picture, int hints);
/// Adds a backend texture to the scene.
///
@ -749,8 +762,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
_addTexture(offset.dx, offset.dy, width, height, textureId, freeze, filterQuality.index);
}
void _addTexture(double dx, double dy, double width, double height, int textureId, bool freeze,
int filterQuality) native 'SceneBuilder_addTexture';
@FfiNative<Void Function(Pointer<Void>, Double, Double, Double, Double, Int64, Bool, Int32)>('SceneBuilder::addTexture', isLeaf: true)
external void _addTexture(double dx, double dy, double width, double height, int textureId, bool freeze, int filterQuality);
/// Adds a platform view (e.g an iOS UIView) to the scene.
///
@ -778,8 +791,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
_addPlatformView(offset.dx, offset.dy, width, height, viewId);
}
void _addPlatformView(double dx, double dy, double width, double height, int viewId)
native 'SceneBuilder_addPlatformView';
@FfiNative<Void Function(Pointer<Void>, Double, Double, Double, Double, Int64)>('SceneBuilder::addPlatformView', isLeaf: true)
external void _addPlatformView(double dx, double dy, double width, double height, int viewId);
/// Sets a threshold after which additional debugging information should be recorded.
///
@ -787,8 +800,8 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
/// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev).
/// We'll hopefully be able to figure out how to make this feature more useful
/// to you.
void setRasterizerTracingThreshold(int frameInterval)
native 'SceneBuilder_setRasterizerTracingThreshold';
@FfiNative<Void Function(Pointer<Void>, Uint32)>('SceneBuilder::setRasterizerTracingThreshold', isLeaf: true)
external void setRasterizerTracingThreshold(int frameInterval);
/// Sets whether the raster cache should checkerboard cached entries. This is
/// only useful for debugging purposes.
@ -805,15 +818,15 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
///
/// Currently this interface is difficult to use by end-developers. If you're
/// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev).
void setCheckerboardRasterCacheImages(bool checkerboard)
native 'SceneBuilder_setCheckerboardRasterCacheImages';
@FfiNative<Void Function(Pointer<Void>, Bool)>('SceneBuilder::setCheckerboardRasterCacheImages', isLeaf: true)
external void setCheckerboardRasterCacheImages(bool checkerboard);
/// Sets whether the compositor should checkerboard layers that are rendered
/// to offscreen bitmaps.
///
/// This is only useful for debugging purposes.
void setCheckerboardOffscreenLayers(bool checkerboard)
native 'SceneBuilder_setCheckerboardOffscreenLayers';
@FfiNative<Void Function(Pointer<Void>, Bool)>('SceneBuilder::setCheckerboardOffscreenLayers', isLeaf: true)
external void setCheckerboardOffscreenLayers(bool checkerboard);
/// Finishes building the scene.
///
@ -829,5 +842,6 @@ class SceneBuilder extends NativeFieldWrapperClass1 {
return scene;
}
void _build(Scene outScene) native 'SceneBuilder_build';
@FfiNative<Void Function(Pointer<Void>, Handle)>('SceneBuilder::build')
external void _build(Scene outScene);
}

View File

@ -21,12 +21,6 @@ namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, Scene);
#define FOR_EACH_BINDING(V) \
V(Scene, toImage) \
V(Scene, dispose)
DART_BIND_ALL(Scene, FOR_EACH_BINDING)
void Scene::create(Dart_Handle scene_handle,
std::shared_ptr<flutter::Layer> rootLayer,
uint32_t rasterizerTracingThreshold,

View File

@ -12,10 +12,6 @@
#include "flutter/lib/ui/dart_wrapper.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class Scene : public RefCountedDartWrappable<Scene> {
@ -38,8 +34,6 @@ class Scene : public RefCountedDartWrappable<Scene> {
void dispose();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
explicit Scene(std::shared_ptr<flutter::Layer> rootLayer,
uint32_t rasterizerTracingThreshold,

View File

@ -33,44 +33,8 @@
namespace flutter {
static void SceneBuilder_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&SceneBuilder::create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder);
#define FOR_EACH_BINDING(V) \
V(SceneBuilder, pushOffset) \
V(SceneBuilder, pushTransform) \
V(SceneBuilder, pushClipRect) \
V(SceneBuilder, pushClipRRect) \
V(SceneBuilder, pushClipPath) \
V(SceneBuilder, pushOpacity) \
V(SceneBuilder, pushColorFilter) \
V(SceneBuilder, pushImageFilter) \
V(SceneBuilder, pushBackdropFilter) \
V(SceneBuilder, pushShaderMask) \
V(SceneBuilder, pushPhysicalShape) \
V(SceneBuilder, pop) \
V(SceneBuilder, addPlatformView) \
V(SceneBuilder, addRetained) \
V(SceneBuilder, addPicture) \
V(SceneBuilder, addTexture) \
V(SceneBuilder, addPerformanceOverlay) \
V(SceneBuilder, setRasterizerTracingThreshold) \
V(SceneBuilder, setCheckerboardOffscreenLayers) \
V(SceneBuilder, setCheckerboardRasterCacheImages) \
V(SceneBuilder, build)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void SceneBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"SceneBuilder_constructor", SceneBuilder_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
SceneBuilder::SceneBuilder() {
// Add a ContainerLayer as the root layer, so that AddLayer operations are
// always valid.

View File

@ -28,11 +28,20 @@ class SceneBuilder : public RefCountedDartWrappable<SceneBuilder> {
FML_FRIEND_MAKE_REF_COUNTED(SceneBuilder);
public:
static fml::RefPtr<SceneBuilder> create() {
return fml::MakeRefCounted<SceneBuilder>();
static void Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<SceneBuilder>();
res->AssociateWithDartWrapper(wrapper);
}
~SceneBuilder() override;
void pushTransformHandle(Dart_Handle layer_handle,
Dart_Handle matrix4_handle,
fml::RefPtr<EngineLayer> oldLayer) {
tonic::Float64List matrix4(matrix4_handle);
pushTransform(layer_handle, matrix4, oldLayer);
}
void pushTransform(Dart_Handle layer_handle,
tonic::Float64List& matrix4,
fml::RefPtr<EngineLayer> oldLayer);
@ -123,8 +132,6 @@ class SceneBuilder : public RefCountedDartWrappable<SceneBuilder> {
return layer_stack_;
}
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
SceneBuilder();

View File

@ -33,24 +33,6 @@ using tonic::ToDart;
namespace flutter {
#define REGISTER_FUNCTION(name, count) {"" #name, name, count, true},
#define DECLARE_FUNCTION(name, count) \
extern void name(Dart_NativeArguments args);
#define BUILTIN_NATIVE_LIST(V) \
V(Logger_PrintString, 1) \
V(Logger_PrintDebugString, 1) \
V(DartPluginRegistrant_EnsureInitialized, 0) \
V(ScheduleMicrotask, 1) \
V(GetCallbackHandle, 1) \
V(GetCallbackFromHandle, 1)
BUILTIN_NATIVE_LIST(DECLARE_FUNCTION);
void DartRuntimeHooks::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)});
}
static void PropagateIfError(Dart_Handle result) {
if (Dart_IsError(result)) {
FML_LOG(ERROR) << "Dart Error: " << ::Dart_GetError(result);
@ -156,32 +138,13 @@ void DartRuntimeHooks::Install(bool is_ui_isolate,
InitDartIO(builtin, script_uri);
}
void Logger_PrintDebugString(Dart_NativeArguments args) {
void DartRuntimeHooks::Logger_PrintDebugString(std::string message) {
#ifndef NDEBUG
Logger_PrintString(args);
DartRuntimeHooks::Logger_PrintString(message);
#endif
}
// Implementation of native functions which are used for some
// test/debug functionality in standalone dart mode.
void Logger_PrintString(Dart_NativeArguments args) {
// Obtain the log buffer from Dart code.
std::string message;
{
Dart_Handle str = Dart_GetNativeArgument(args, 0);
uint8_t* chars = nullptr;
intptr_t length = 0;
Dart_Handle result = Dart_StringToUTF8(str, &chars, &length);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
return;
}
if (length > 0) {
message = std::string{reinterpret_cast<const char*>(chars),
static_cast<size_t>(length)};
}
}
void DartRuntimeHooks::Logger_PrintString(std::string message) {
const auto& tag = UIDartState::Current()->logger_prefix();
UIDartState::Current()->LogMessage(tag, message);
@ -202,8 +165,7 @@ void Logger_PrintString(Dart_NativeArguments args) {
}
}
void ScheduleMicrotask(Dart_NativeArguments args) {
Dart_Handle closure = Dart_GetNativeArgument(args, 0);
void DartRuntimeHooks::ScheduleMicrotask(Dart_Handle closure) {
UIDartState::Current()->ScheduleMicrotask(closure);
}
@ -280,8 +242,7 @@ static std::string GetFunctionName(Dart_Handle func) {
return DartConverter<std::string>::FromDart(result);
}
void GetCallbackHandle(Dart_NativeArguments args) {
Dart_Handle func = Dart_GetNativeArgument(args, 0);
Dart_Handle DartRuntimeHooks::GetCallbackHandle(Dart_Handle func) {
std::string name = GetFunctionName(func);
std::string class_name = GetFunctionClassName(func);
std::string library_path = GetFunctionLibraryUrl(func);
@ -291,21 +252,18 @@ void GetCallbackHandle(Dart_NativeArguments args) {
// closures (e.g. `(int a, int b) => a + b;`) also cannot be used as
// callbacks, so `func` must be a tear-off of a named static function.
if (!Dart_IsTearOff(func) || name.empty()) {
Dart_SetReturnValue(args, Dart_Null());
return;
return Dart_Null();
}
Dart_SetReturnValue(
args, DartConverter<int64_t>::ToDart(DartCallbackCache::GetCallbackHandle(
name, class_name, library_path)));
return DartConverter<int64_t>::ToDart(
DartCallbackCache::GetCallbackHandle(name, class_name, library_path));
}
void GetCallbackFromHandle(Dart_NativeArguments args) {
Dart_Handle h = Dart_GetNativeArgument(args, 0);
int64_t handle = DartConverter<int64_t>::FromDart(h);
Dart_SetReturnValue(args, DartCallbackCache::GetCallback(handle));
Dart_Handle DartRuntimeHooks::GetCallbackFromHandle(int64_t handle) {
return DartCallbackCache::GetCallback(handle);
}
void DartPluginRegistrant_EnsureInitialized(Dart_NativeArguments args) {
void DartPluginRegistrant_EnsureInitialized() {
tonic::DartApiScope api_scope;
FindAndInvokeDartPluginRegistrant();
}

View File

@ -14,12 +14,23 @@ namespace flutter {
class DartRuntimeHooks {
public:
static void Install(bool is_ui_isolate, const std::string& script_uri);
static void RegisterNatives(tonic::DartLibraryNatives* natives);
static void Logger_PrintDebugString(std::string message);
static void Logger_PrintString(std::string message);
static void ScheduleMicrotask(Dart_Handle closure);
static Dart_Handle GetCallbackHandle(Dart_Handle func);
static Dart_Handle GetCallbackFromHandle(int64_t handle);
private:
FML_DISALLOW_IMPLICIT_CONSTRUCTORS(DartRuntimeHooks);
};
void DartPluginRegistrant_EnsureInitialized();
} // namespace flutter
#endif // FLUTTER_LIB_UI_DART_RUNTIME_HOOKS_H_

View File

@ -34,70 +34,271 @@
#include "flutter/lib/ui/text/paragraph_builder.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/logging/dart_error.h"
using tonic::ToDart;
namespace flutter {
namespace {
static tonic::DartLibraryNatives* g_natives;
typedef CanvasImage Image;
typedef CanvasPathMeasure PathMeasure;
typedef CanvasGradient Gradient;
typedef CanvasPath Path;
Dart_NativeFunction GetNativeFunction(Dart_Handle name,
int argument_count,
bool* auto_setup_scope) {
return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope);
}
// List of native static functions used as @FfiNative functions.
// Items are tuples of ('function_name', 'parameter_count'), where:
// 'function_name' is the fully qualified name of the native function.
// 'parameter_count' is the number of parameters the function has.
//
// These are used to:
// - Instantiate FfiDispatcher templates to automatically create FFI Native
// bindings.
// If the name does not match a native function, the template will fail to
// instatiate, resulting in a compile time error.
// - Resolve the native function pointer associated with an @FfiNative function.
// If there is a mismatch between name or parameter count an @FfiNative is
// trying to resolve, an exception will be thrown.
#define FFI_FUNCTION_LIST(V) \
/* Constructors */ \
V(Canvas::Create, 6) \
V(ColorFilter::Create, 1) \
V(FragmentProgram::Create, 1) \
V(Gradient::Create, 1) \
V(ImageFilter::Create, 1) \
V(ImageShader::Create, 1) \
V(ParagraphBuilder::Create, 9) \
V(PathMeasure::Create, 3) \
V(Path::Create, 1) \
V(PictureRecorder::Create, 1) \
V(SceneBuilder::Create, 1) \
V(SemanticsUpdateBuilder::Create, 1) \
/* Other */ \
V(FontCollection::LoadFontFromList, 3) \
V(ImageDescriptor::initEncoded, 3) \
V(ImmutableBuffer::init, 3) \
V(ImageDescriptor::initRaw, 6) \
V(IsolateNameServerNatives::LookupPortByName, 1) \
V(IsolateNameServerNatives::RegisterPortWithName, 2) \
V(IsolateNameServerNatives::RemovePortNameMapping, 1) \
V(NativeStringAttribute::initLocaleStringAttribute, 4) \
V(NativeStringAttribute::initSpellOutStringAttribute, 3) \
V(PlatformConfigurationNativeApi::DefaultRouteName, 0) \
V(PlatformConfigurationNativeApi::ScheduleFrame, 0) \
V(PlatformConfigurationNativeApi::Render, 1) \
V(PlatformConfigurationNativeApi::UpdateSemantics, 1) \
V(PlatformConfigurationNativeApi::SetNeedsReportTimings, 1) \
V(PlatformConfigurationNativeApi::SetIsolateDebugName, 1) \
V(PlatformConfigurationNativeApi::GetPersistentIsolateData, 0) \
V(PlatformConfigurationNativeApi::ComputePlatformResolvedLocale, 1) \
V(PlatformConfigurationNativeApi::SendPlatformMessage, 3) \
V(PlatformConfigurationNativeApi::RespondToPlatformMessage, 2) \
V(DartRuntimeHooks::Logger_PrintDebugString, 1) \
V(DartRuntimeHooks::Logger_PrintString, 1) \
V(DartRuntimeHooks::ScheduleMicrotask, 1) \
V(DartRuntimeHooks::GetCallbackHandle, 1) \
V(DartRuntimeHooks::GetCallbackFromHandle, 1) \
V(DartPluginRegistrant_EnsureInitialized, 0) \
V(Vertices::init, 6)
const uint8_t* GetSymbol(Dart_NativeFunction native_function) {
return g_natives->GetSymbol(native_function);
}
// List of native instance methods used as @FfiNative functions.
// Items are tuples of ('class_name', 'method_name', 'parameter_count'), where:
// 'class_name' is the name of the class containing the method.
// 'method_name' is the name of the method.
// 'parameter_count' is the number of parameters the method has.
//
// These are used to:
// - Instantiate FfiDispatcher templates to automatically create FFI Native
// bindings.
// If the name does not match a native function, the template will fail to
// instatiate, resulting in a compile time error.
// - Resolve the native function pointer associated with an @FfiNative function.
// If there is a mismatch between names or parameter count an @FfiNative is
// trying to resolve, an exception will be thrown.
#define FFI_METHOD_LIST(V) \
V(Image, dispose, 1) \
V(Image, width, 1) \
V(Image, height, 1) \
V(Image, toByteData, 3) \
V(Canvas, clipPath, 3) \
V(Canvas, clipRect, 7) \
V(Canvas, clipRRect, 3) \
V(Canvas, drawArc, 10) \
V(Canvas, drawAtlas, 10) \
V(Canvas, drawCircle, 6) \
V(Canvas, drawColor, 3) \
V(Canvas, drawDRRect, 5) \
V(Canvas, drawImage, 7) \
V(Canvas, drawImageNine, 13) \
V(Canvas, drawImageRect, 13) \
V(Canvas, drawLine, 7) \
V(Canvas, drawOval, 7) \
V(Canvas, drawPaint, 3) \
V(Canvas, drawPath, 4) \
V(Canvas, drawPicture, 2) \
V(Canvas, drawPoints, 5) \
V(Canvas, drawRRect, 4) \
V(Canvas, drawRect, 7) \
V(Canvas, drawShadow, 5) \
V(Canvas, drawVertices, 5) \
V(Canvas, getSaveCount, 1) \
V(Canvas, restore, 1) \
V(Canvas, rotate, 2) \
V(Canvas, save, 1) \
V(Canvas, saveLayer, 7) \
V(Canvas, saveLayerWithoutBounds, 3) \
V(Canvas, scale, 3) \
V(Canvas, skew, 3) \
V(Canvas, transform, 2) \
V(Canvas, translate, 3) \
V(Codec, dispose, 1) \
V(Codec, frameCount, 1) \
V(Codec, getNextFrame, 2) \
V(Codec, repetitionCount, 1) \
V(ColorFilter, initLinearToSrgbGamma, 1) \
V(ColorFilter, initMatrix, 2) \
V(ColorFilter, initMode, 3) \
V(ColorFilter, initSrgbToLinearGamma, 1) \
V(EngineLayer, dispose, 1) \
V(FragmentProgram, init, 3) \
V(FragmentProgram, shader, 4) \
V(Gradient, initLinear, 6) \
V(Gradient, initRadial, 8) \
V(Gradient, initSweep, 9) \
V(Gradient, initTwoPointConical, 11) \
V(ImageDescriptor, bytesPerPixel, 1) \
V(ImageDescriptor, dispose, 1) \
V(ImageDescriptor, height, 1) \
V(ImageDescriptor, instantiateCodec, 4) \
V(ImageDescriptor, width, 1) \
V(ImageFilter, initBlur, 4) \
V(ImageFilter, initDilate, 3) \
V(ImageFilter, initErode, 3) \
V(ImageFilter, initColorFilter, 2) \
V(ImageFilter, initComposeFilter, 3) \
V(ImageFilter, initMatrix, 3) \
V(ImageShader, initWithImage, 6) \
V(ImmutableBuffer, dispose, 1) \
V(ImmutableBuffer, length, 1) \
V(ParagraphBuilder, addPlaceholder, 6) \
V(ParagraphBuilder, addText, 2) \
V(ParagraphBuilder, build, 2) \
V(ParagraphBuilder, pop, 1) \
V(ParagraphBuilder, pushStyle, 16) \
V(Paragraph, alphabeticBaseline, 1) \
V(Paragraph, computeLineMetrics, 1) \
V(Paragraph, didExceedMaxLines, 1) \
V(Paragraph, getLineBoundary, 2) \
V(Paragraph, getPositionForOffset, 3) \
V(Paragraph, getRectsForPlaceholders, 1) \
V(Paragraph, getRectsForRange, 5) \
V(Paragraph, getWordBoundary, 2) \
V(Paragraph, height, 1) \
V(Paragraph, ideographicBaseline, 1) \
V(Paragraph, layout, 2) \
V(Paragraph, longestLine, 1) \
V(Paragraph, maxIntrinsicWidth, 1) \
V(Paragraph, minIntrinsicWidth, 1) \
V(Paragraph, paint, 4) \
V(Paragraph, width, 1) \
V(PathMeasure, setPath, 3) \
V(PathMeasure, getLength, 2) \
V(PathMeasure, getPosTan, 3) \
V(PathMeasure, getSegment, 6) \
V(PathMeasure, isClosed, 2) \
V(PathMeasure, nextContour, 1) \
V(Path, addArc, 7) \
V(Path, addOval, 5) \
V(Path, addPath, 4) \
V(Path, addPathWithMatrix, 5) \
V(Path, addPolygon, 3) \
V(Path, addRRect, 2) \
V(Path, addRect, 5) \
V(Path, arcTo, 8) \
V(Path, arcToPoint, 8) \
V(Path, clone, 2) \
V(Path, close, 1) \
V(Path, conicTo, 6) \
V(Path, contains, 3) \
V(Path, cubicTo, 7) \
V(Path, extendWithPath, 4) \
V(Path, extendWithPathAndMatrix, 5) \
V(Path, getBounds, 1) \
V(Path, getFillType, 1) \
V(Path, lineTo, 3) \
V(Path, moveTo, 3) \
V(Path, op, 4) \
V(Path, quadraticBezierTo, 5) \
V(Path, relativeArcToPoint, 5) \
V(Path, relativeConicTo, 8) \
V(Path, relativeCubicTo, 7) \
V(Path, relativeLineTo, 3) \
V(Path, relativeMoveTo, 3) \
V(Path, relativeQuadraticBezierTo, 5) \
V(Path, reset, 1) \
V(Path, setFillType, 2) \
V(Path, shift, 4) \
V(Path, transform, 3) \
V(PictureRecorder, endRecording, 2) \
V(Picture, GetAllocationSize, 1) \
V(Picture, dispose, 1) \
V(Picture, toImage, 4) \
V(SceneBuilder, addPerformanceOverlay, 6) \
V(SceneBuilder, addPicture, 5) \
V(SceneBuilder, addPlatformView, 6) \
V(SceneBuilder, addRetained, 2) \
V(SceneBuilder, addTexture, 8) \
V(SceneBuilder, build, 2) \
V(SceneBuilder, pop, 1) \
V(SceneBuilder, pushBackdropFilter, 5) \
V(SceneBuilder, pushClipPath, 5) \
V(SceneBuilder, pushClipRRect, 5) \
V(SceneBuilder, pushClipRect, 8) \
V(SceneBuilder, pushColorFilter, 4) \
V(SceneBuilder, pushImageFilter, 4) \
V(SceneBuilder, pushOffset, 5) \
V(SceneBuilder, pushOpacity, 6) \
V(SceneBuilder, pushPhysicalShape, 8) \
V(SceneBuilder, pushShaderMask, 10) \
V(SceneBuilder, pushTransformHandle, 4) \
V(SceneBuilder, setCheckerboardOffscreenLayers, 2) \
V(SceneBuilder, setCheckerboardRasterCacheImages, 2) \
V(SceneBuilder, setRasterizerTracingThreshold, 2) \
V(Scene, dispose, 1) \
V(Scene, toImage, 4) \
V(SemanticsUpdateBuilder, build, 2) \
V(SemanticsUpdateBuilder, updateCustomAction, 5) \
V(SemanticsUpdateBuilder, updateNode, 36) \
V(SemanticsUpdate, dispose, 1)
} // 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);
CanvasPathMeasure::RegisterNatives(g_natives);
Codec::RegisterNatives(g_natives);
ColorFilter::RegisterNatives(g_natives);
DartRuntimeHooks::RegisterNatives(g_natives);
EngineLayer::RegisterNatives(g_natives);
FontCollection::RegisterNatives(g_natives);
FragmentProgram::RegisterNatives(g_natives);
ImageDescriptor::RegisterNatives(g_natives);
ImageFilter::RegisterNatives(g_natives);
ImageShader::RegisterNatives(g_natives);
ImmutableBuffer::RegisterNatives(g_natives);
IsolateNameServerNatives::RegisterNatives(g_natives);
NativeStringAttribute::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);
SemanticsUpdate::RegisterNatives(g_natives);
SemanticsUpdateBuilder::RegisterNatives(g_natives);
Vertices::RegisterNatives(g_natives);
PlatformConfiguration::RegisterNatives(g_natives);
#define FFI_FUNCTION_MATCH(FUNCTION, ARGS) \
if (strcmp(name, #FUNCTION) == 0 && args == ARGS) { \
return reinterpret_cast<void*>( \
tonic::FfiDispatcher<void, decltype(&FUNCTION), &FUNCTION>::Call); \
}
#define FFI_METHOD_MATCH(CLASS, METHOD, ARGS) \
if (strcmp(name, #CLASS "::" #METHOD) == 0 && args == ARGS) { \
return reinterpret_cast<void*>( \
tonic::FfiDispatcher<CLASS, decltype(&CLASS::METHOD), \
&CLASS::METHOD>::Call); \
}
void* ResolveFfiNativeFunction(const char* name, uintptr_t args) {
FFI_FUNCTION_LIST(FFI_FUNCTION_MATCH)
FFI_METHOD_LIST(FFI_METHOD_MATCH)
return nullptr;
}
void DartUI::InitForIsolate(const Settings& settings) {
FML_DCHECK(g_natives);
Dart_Handle dart_ui = Dart_LookupLibrary(ToDart("dart:ui"));
auto dart_ui = Dart_LookupLibrary(ToDart("dart:ui"));
if (Dart_IsError(dart_ui)) {
Dart_PropagateError(dart_ui);
}
// Set up FFI Native resolver for dart:ui.
Dart_Handle result =
Dart_SetNativeResolver(dart_ui, GetNativeFunction, GetSymbol);
Dart_SetFfiNativeResolver(dart_ui, ResolveFfiNativeFunction);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}

View File

@ -12,7 +12,6 @@ namespace flutter {
class DartUI {
public:
static void InitForGlobal();
static void InitForIsolate(const Settings& settings);
private:

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// Base class for [Size] and [Offset], which are both ways to describe

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
class _HashEnd { const _HashEnd(); }

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
@pragma('vm:entry-point')

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// Static methods to allow for simple sharing of [SendPort]s across [Isolate]s.
@ -72,10 +72,12 @@ class IsolateNameServer {
return _removePortNameMapping(name);
}
static SendPort? _lookupPortByName(String name)
native 'IsolateNameServerNatives_LookupPortByName';
static bool _registerPortWithName(SendPort port, String name)
native 'IsolateNameServerNatives_RegisterPortWithName';
static bool _removePortNameMapping(String name)
native 'IsolateNameServerNatives_RemovePortNameMapping';
@FfiNative<Handle Function(Handle)>('IsolateNameServerNatives::LookupPortByName')
external static SendPort? _lookupPortByName(String name);
@FfiNative<Bool Function(Handle, Handle)>('IsolateNameServerNatives::RegisterPortWithName')
external static bool _registerPortWithName(SendPort port, String name);
@FfiNative<Bool Function(Handle)>('IsolateNameServerNatives::RemovePortNameMapping')
external static bool _removePortNameMapping(String name);
}

View File

@ -26,46 +26,26 @@ Dart_Handle IsolateNameServerNatives::LookupPortByName(
return Dart_NewSendPort(port);
}
Dart_Handle IsolateNameServerNatives::RegisterPortWithName(
Dart_Handle port_handle,
const std::string& name) {
bool IsolateNameServerNatives::RegisterPortWithName(Dart_Handle port_handle,
const std::string& name) {
auto name_server = UIDartState::Current()->GetIsolateNameServer();
if (!name_server) {
return Dart_False();
return false;
}
Dart_Port port = ILLEGAL_PORT;
Dart_SendPortGetId(port_handle, &port);
if (!name_server->RegisterIsolatePortWithName(port, name)) {
return Dart_False();
return false;
}
return Dart_True();
return true;
}
Dart_Handle IsolateNameServerNatives::RemovePortNameMapping(
const std::string& name) {
bool IsolateNameServerNatives::RemovePortNameMapping(const std::string& name) {
auto name_server = UIDartState::Current()->GetIsolateNameServer();
if (!name_server) {
return Dart_False();
if (!name_server || !name_server->RemoveIsolateNameMapping(name)) {
return false;
}
if (!name_server->RemoveIsolateNameMapping(name)) {
return Dart_False();
}
return Dart_True();
}
#define FOR_EACH_BINDING(V) \
V(IsolateNameServerNatives, LookupPortByName) \
V(IsolateNameServerNatives, RegisterPortWithName) \
V(IsolateNameServerNatives, RemovePortNameMapping)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK_STATIC)
#define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \
DART_REGISTER_NATIVE_STATIC(CLASS, METHOD),
void IsolateNameServerNatives::RegisterNatives(
tonic::DartLibraryNatives* natives) {
natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE_STATIC_)});
return true;
}
} // namespace flutter

View File

@ -9,19 +9,14 @@
#include "third_party/dart/runtime/include/dart_api.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class IsolateNameServerNatives {
public:
static Dart_Handle LookupPortByName(const std::string& name);
static Dart_Handle RegisterPortWithName(Dart_Handle port_handle,
const std::string& name);
static Dart_Handle RemovePortNameMapping(const std::string& name);
static void RegisterNatives(tonic::DartLibraryNatives* natives);
static bool RegisterPortWithName(Dart_Handle port_handle,
const std::string& name);
static bool RemovePortNameMapping(const std::string& name);
};
} // namespace flutter

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// Linearly interpolate between two numbers, `a` and `b`, by an extrapolation

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
// ignore_for_file: avoid_classes_with_only_static_members
@ -20,7 +20,8 @@ class DartPluginRegistrant {
_ensureInitialized();
}
}
static void _ensureInitialized() native 'DartPluginRegistrant_EnsureInitialized';
@FfiNative<Void Function()>('DartPluginRegistrant_EnsureInitialized')
external static void _ensureInitialized();
}
// Corelib 'print' implementation.
@ -33,8 +34,11 @@ void _printDebug(Object? arg) {
}
class _Logger {
static void _printString(String? s) native 'Logger_PrintString';
static void _printDebugString(String? s) native 'Logger_PrintDebugString';
@FfiNative<Void Function(Handle)>('DartRuntimeHooks::Logger_PrintString')
external static void _printString(String? s);
@FfiNative<Void Function(Handle)>('DartRuntimeHooks::Logger_PrintDebugString')
external static void _printDebugString(String? s);
}
// If we actually run on big endian machines, we'll need to do something smarter
@ -88,10 +92,14 @@ List<int> saveCompilationTrace() {
throw UnimplementedError();
}
void _scheduleMicrotask(void Function() callback) native 'ScheduleMicrotask';
@FfiNative<Void Function(Handle)>('DartRuntimeHooks::ScheduleMicrotask')
external void _scheduleMicrotask(void Function() callback);
int? _getCallbackHandle(Function closure) native 'GetCallbackHandle';
Function? _getCallbackFromHandle(int handle) native 'GetCallbackFromHandle';
@FfiNative<Handle Function(Handle)>('DartRuntimeHooks::GetCallbackHandle')
external int? _getCallbackHandle(Function closure);
@FfiNative<Handle Function(Int64)>('DartRuntimeHooks::GetCallbackFromHandle')
external Function? _getCallbackFromHandle(int handle);
typedef _PrintClosure = void Function(String line);

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@
#include "flutter/flow/layers/physical_shape_layer.h"
#include "flutter/lib/ui/painting/image.h"
#include "flutter/lib/ui/painting/matrix.h"
#include "flutter/lib/ui/painting/paint.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "flutter/lib/ui/window/window.h"
@ -28,62 +29,20 @@ using tonic::ToDart;
namespace flutter {
static void Canvas_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&Canvas::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, Canvas);
#define FOR_EACH_BINDING(V) \
V(Canvas, save) \
V(Canvas, saveLayerWithoutBounds) \
V(Canvas, saveLayer) \
V(Canvas, restore) \
V(Canvas, getSaveCount) \
V(Canvas, translate) \
V(Canvas, scale) \
V(Canvas, rotate) \
V(Canvas, skew) \
V(Canvas, transform) \
V(Canvas, clipRect) \
V(Canvas, clipRRect) \
V(Canvas, clipPath) \
V(Canvas, drawColor) \
V(Canvas, drawLine) \
V(Canvas, drawPaint) \
V(Canvas, drawRect) \
V(Canvas, drawRRect) \
V(Canvas, drawDRRect) \
V(Canvas, drawOval) \
V(Canvas, drawCircle) \
V(Canvas, drawArc) \
V(Canvas, drawPath) \
V(Canvas, drawImage) \
V(Canvas, drawImageRect) \
V(Canvas, drawImageNine) \
V(Canvas, drawPicture) \
V(Canvas, drawPoints) \
V(Canvas, drawVertices) \
V(Canvas, drawAtlas) \
V(Canvas, drawShadow)
void Canvas::Create(Dart_Handle wrapper,
PictureRecorder* recorder,
double left,
double top,
double right,
double bottom) {
UIDartState::ThrowIfUIOperationsProhibited();
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void Canvas::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({{"Canvas_constructor", Canvas_constructor, 6, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<Canvas> Canvas::Create(PictureRecorder* recorder,
double left,
double top,
double right,
double bottom) {
if (!recorder) {
Dart_ThrowException(
ToDart("Canvas constructor called with non-genuine PictureRecorder."));
return nullptr;
return;
}
// This call will implicitly initialize the |canvas_| field with an SkCanvas
@ -98,7 +57,7 @@ fml::RefPtr<Canvas> Canvas::Create(PictureRecorder* recorder,
recorder->BeginRecording(SkRect::MakeLTRB(left, top, right, bottom)));
recorder->set_canvas(canvas);
canvas->display_list_recorder_ = recorder->display_list_recorder();
return canvas;
canvas->AssociateWithDartWrapper(wrapper);
}
Canvas::Canvas(SkCanvas* canvas) : canvas_(canvas) {}
@ -113,8 +72,10 @@ void Canvas::save() {
}
}
void Canvas::saveLayerWithoutBounds(const Paint& paint,
const PaintData& paint_data) {
void Canvas::saveLayerWithoutBounds(Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
bool restore_with_paint =
@ -133,8 +94,10 @@ void Canvas::saveLayer(double left,
double top,
double right,
double bottom,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
SkRect bounds = SkRect::MakeLTRB(left, top, right, bottom);
if (display_list_recorder_) {
@ -267,8 +230,10 @@ void Canvas::drawLine(double x1,
double y1,
double x2,
double y2,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(), kDrawLineFlags);
@ -279,7 +244,9 @@ void Canvas::drawLine(double x1,
}
}
void Canvas::drawPaint(const Paint& paint, const PaintData& paint_data) {
void Canvas::drawPaint(Dart_Handle paint_objects, Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(), kDrawPaintFlags);
@ -307,8 +274,10 @@ void Canvas::drawRect(double left,
double top,
double right,
double bottom,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(), kDrawRectFlags);
@ -321,8 +290,10 @@ void Canvas::drawRect(double left,
}
void Canvas::drawRRect(const RRect& rrect,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(), kDrawRRectFlags);
@ -335,8 +306,10 @@ void Canvas::drawRRect(const RRect& rrect,
void Canvas::drawDRRect(const RRect& outer,
const RRect& inner,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(), kDrawDRRectFlags);
@ -351,8 +324,10 @@ void Canvas::drawOval(double left,
double top,
double right,
double bottom,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(), kDrawOvalFlags);
@ -367,8 +342,10 @@ void Canvas::drawOval(double left,
void Canvas::drawCircle(double x,
double y,
double radius,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(), kDrawCircleFlags);
@ -386,8 +363,10 @@ void Canvas::drawArc(double left,
double startAngle,
double sweepAngle,
bool useCenter,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (display_list_recorder_) {
paint.sync_to(builder(),
@ -406,8 +385,10 @@ void Canvas::drawArc(double left,
}
void Canvas::drawPath(const CanvasPath* path,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (!path) {
Dart_ThrowException(
@ -426,9 +407,11 @@ void Canvas::drawPath(const CanvasPath* path,
void Canvas::drawImage(const CanvasImage* image,
double x,
double y,
const Paint& paint,
const PaintData& paint_data,
Dart_Handle paint_objects,
Dart_Handle paint_data,
int filterQualityIndex) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (!image) {
Dart_ThrowException(
@ -463,9 +446,11 @@ void Canvas::drawImageRect(const CanvasImage* image,
double dst_top,
double dst_right,
double dst_bottom,
const Paint& paint,
const PaintData& paint_data,
Dart_Handle paint_objects,
Dart_Handle paint_data,
int filterQualityIndex) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (!image) {
Dart_ThrowException(
@ -505,9 +490,11 @@ void Canvas::drawImageNine(const CanvasImage* image,
double dst_top,
double dst_right,
double dst_bottom,
const Paint& paint,
const PaintData& paint_data,
Dart_Handle paint_objects,
Dart_Handle paint_data,
int bitmapSamplingIndex) {
Paint paint(paint_objects, paint_data);
FML_DCHECK(paint.isNotNull());
if (!image) {
Dart_ThrowException(
@ -563,10 +550,12 @@ void Canvas::drawPicture(Picture* picture) {
}
}
void Canvas::drawPoints(const Paint& paint,
const PaintData& paint_data,
void Canvas::drawPoints(Dart_Handle paint_objects,
Dart_Handle paint_data,
SkCanvas::PointMode point_mode,
const tonic::Float32List& points) {
Paint paint(paint_objects, paint_data);
static_assert(sizeof(SkPoint) == sizeof(float) * 2,
"SkPoint doesn't use floats.");
@ -597,8 +586,10 @@ void Canvas::drawPoints(const Paint& paint,
void Canvas::drawVertices(const Vertices* vertices,
DlBlendMode blend_mode,
const Paint& paint,
const PaintData& paint_data) {
Dart_Handle paint_objects,
Dart_Handle paint_data) {
Paint paint(paint_objects, paint_data);
if (!vertices) {
Dart_ThrowException(
ToDart("Canvas.drawVertices called with non-genuine Vertices."));
@ -615,8 +606,8 @@ void Canvas::drawVertices(const Vertices* vertices,
}
}
void Canvas::drawAtlas(const Paint& paint,
const PaintData& paint_data,
void Canvas::drawAtlas(Dart_Handle paint_objects,
Dart_Handle paint_data,
int filterQualityIndex,
CanvasImage* atlas,
const tonic::Float32List& transforms,
@ -624,6 +615,8 @@ void Canvas::drawAtlas(const Paint& paint,
const tonic::Int32List& colors,
DlBlendMode blend_mode,
const tonic::Float32List& cull_rect) {
Paint paint(paint_objects, paint_data);
if (!atlas) {
Dart_ThrowException(
ToDart("Canvas.drawAtlas or Canvas.drawRawAtlas called with "

View File

@ -13,14 +13,11 @@
#include "flutter/lib/ui/painting/picture_recorder.h"
#include "flutter/lib/ui/painting/rrect.h"
#include "flutter/lib/ui/painting/vertices.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/utils/SkShadowUtils.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class CanvasImage;
@ -29,22 +26,26 @@ class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags {
FML_FRIEND_MAKE_REF_COUNTED(Canvas);
public:
static fml::RefPtr<Canvas> Create(PictureRecorder* recorder,
double left,
double top,
double right,
double bottom);
static void Create(Dart_Handle wrapper,
PictureRecorder* recorder,
double left,
double top,
double right,
double bottom);
~Canvas() override;
void save();
void saveLayerWithoutBounds(const Paint& paint, const PaintData& paint_data);
void saveLayerWithoutBounds(Dart_Handle paint_objects,
Dart_Handle paint_data);
void saveLayer(double left,
double top,
double right,
double bottom,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void restore();
int getSaveCount();
@ -64,37 +65,45 @@ class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags {
void clipPath(const CanvasPath* path, bool doAntiAlias = true);
void drawColor(SkColor color, DlBlendMode blend_mode);
void drawLine(double x1,
double y1,
double x2,
double y2,
const Paint& paint,
const PaintData& paint_data);
void drawPaint(const Paint& paint, const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawPaint(Dart_Handle paint_objects, Dart_Handle paint_data);
void drawRect(double left,
double top,
double right,
double bottom,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawRRect(const RRect& rrect,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawDRRect(const RRect& outer,
const RRect& inner,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawOval(double left,
double top,
double right,
double bottom,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawCircle(double x,
double y,
double radius,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawArc(double left,
double top,
double right,
@ -102,17 +111,20 @@ class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags {
double startAngle,
double sweepAngle,
bool useCenter,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawPath(const CanvasPath* path,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawImage(const CanvasImage* image,
double x,
double y,
const Paint& paint,
const PaintData& paint_data,
Dart_Handle paint_objects,
Dart_Handle paint_data,
int filterQualityIndex);
void drawImageRect(const CanvasImage* image,
double src_left,
double src_top,
@ -122,9 +134,10 @@ class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags {
double dst_top,
double dst_right,
double dst_bottom,
const Paint& paint,
const PaintData& paint_data,
Dart_Handle paint_objects,
Dart_Handle paint_data,
int filterQualityIndex);
void drawImageNine(const CanvasImage* image,
double center_left,
double center_top,
@ -134,9 +147,10 @@ class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags {
double dst_top,
double dst_right,
double dst_bottom,
const Paint& paint,
const PaintData& paint_data,
Dart_Handle paint_objects,
Dart_Handle paint_data,
int bitmapSamplingIndex);
void drawPicture(Picture* picture);
// The paint argument is first for the following functions because Paint
@ -144,18 +158,18 @@ class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags {
// Float32List, we cannot re-enter the VM to unwrap objects. That means we
// either need to process the paint argument first.
void drawPoints(const Paint& paint,
const PaintData& paint_data,
void drawPoints(Dart_Handle paint_objects,
Dart_Handle paint_data,
SkCanvas::PointMode point_mode,
const tonic::Float32List& points);
void drawVertices(const Vertices* vertices,
DlBlendMode blend_mode,
const Paint& paint,
const PaintData& paint_data);
Dart_Handle paint_objects,
Dart_Handle paint_data);
void drawAtlas(const Paint& paint,
const PaintData& paint_data,
void drawAtlas(Dart_Handle paint_objects,
Dart_Handle paint_data,
int filterQualityIndex,
CanvasImage* atlas,
const tonic::Float32List& transforms,
@ -172,8 +186,6 @@ class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags {
SkCanvas* canvas() const { return canvas_; }
void Invalidate();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
explicit Canvas(SkCanvas* canvas);

View File

@ -10,28 +10,12 @@
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/typed_list.h"
using tonic::DartInvoke;
using tonic::DartPersistentValue;
using tonic::ToDart;
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, Codec);
#define FOR_EACH_BINDING(V) \
V(Codec, getNextFrame) \
V(Codec, frameCount) \
V(Codec, repetitionCount) \
V(Codec, dispose)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void Codec::dispose() {
ClearDartWrapper();
}
void Codec::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
} // namespace flutter

View File

@ -11,12 +11,6 @@
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkImage.h"
using tonic::DartPersistentValue;
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
// A handle to an SkCodec object.
@ -33,8 +27,6 @@ class Codec : public RefCountedDartWrappable<Codec> {
virtual Dart_Handle getNextFrame(Dart_Handle callback_handle) = 0;
void dispose();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
};
} // namespace flutter

View File

@ -14,29 +14,12 @@
namespace flutter {
static void ColorFilter_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&ColorFilter::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, ColorFilter);
#define FOR_EACH_BINDING(V) \
V(ColorFilter, initMode) \
V(ColorFilter, initMatrix) \
V(ColorFilter, initSrgbToLinearGamma) \
V(ColorFilter, initLinearToSrgbGamma)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void ColorFilter::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"ColorFilter_constructor", ColorFilter_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<ColorFilter> ColorFilter::Create() {
return fml::MakeRefCounted<ColorFilter>();
void ColorFilter::Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<ColorFilter>();
res->AssociateWithDartWrapper(wrapper);
}
void ColorFilter::initMode(int color, int blend_mode) {

View File

@ -11,10 +11,6 @@
using tonic::DartPersistentValue;
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
// A handle to an SkCodec object.
@ -25,7 +21,7 @@ class ColorFilter : public RefCountedDartWrappable<ColorFilter> {
FML_FRIEND_MAKE_REF_COUNTED(ColorFilter);
public:
static fml::RefPtr<ColorFilter> Create();
static void Create(Dart_Handle wrapper);
void initMode(int color, int blend_mode);
void initMatrix(const tonic::Float32List& color_matrix);
@ -39,8 +35,6 @@ class ColorFilter : public RefCountedDartWrappable<ColorFilter> {
return (filter_ && filter_->skia_object()) ? filter_.get() : nullptr;
}
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
std::shared_ptr<const DlColorFilter> filter_;
};

View File

@ -10,16 +10,10 @@
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
using tonic::ToDart;
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, EngineLayer);
#define FOR_EACH_BINDING(V) V(EngineLayer, dispose)
DART_BIND_ALL(EngineLayer, FOR_EACH_BINDING)
EngineLayer::EngineLayer(std::shared_ptr<flutter::ContainerLayer> layer)
: layer_(layer) {}

View File

@ -8,10 +8,6 @@
#include "flutter/flow/layers/container_layer.h"
#include "flutter/lib/ui/dart_wrapper.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class EngineLayer;
@ -28,8 +24,6 @@ class EngineLayer : public RefCountedDartWrappable<EngineLayer> {
engine_layer->AssociateWithDartWrapper(dart_handle);
}
static void RegisterNatives(tonic::DartLibraryNatives* natives);
void dispose();
std::shared_ptr<flutter::ContainerLayer> Layer() const { return layer_; }

View File

@ -15,28 +15,10 @@
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/typed_data/typed_list.h"
using tonic::ToDart;
namespace flutter {
static void FragmentProgram_constructor(Dart_NativeArguments args) {
DartCallConstructor(&FragmentProgram::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, FragmentProgram);
#define FOR_EACH_BINDING(V) \
V(FragmentProgram, init) \
V(FragmentProgram, shader)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void FragmentProgram::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"FragmentProgram_constructor", FragmentProgram_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
void FragmentProgram::init(std::string sksl, bool debugPrintSksl) {
SkRuntimeEffect::Result result =
SkRuntimeEffect::MakeForShader(SkString(sksl));
@ -53,12 +35,12 @@ void FragmentProgram::init(std::string sksl, bool debugPrintSksl) {
}
}
fml::RefPtr<FragmentShader> FragmentProgram::shader(
Dart_Handle shader,
tonic::Float32List& uniforms,
Dart_Handle samplers) {
fml::RefPtr<FragmentShader> FragmentProgram::shader(Dart_Handle shader,
Dart_Handle uniforms_handle,
Dart_Handle samplers) {
auto sampler_shaders =
tonic::DartConverter<std::vector<ImageShader*>>::FromDart(samplers);
tonic::Float32List uniforms(uniforms_handle);
size_t uniform_count = uniforms.num_elements();
size_t uniform_data_size =
(uniform_count + 2 * sampler_shaders.size()) * sizeof(float);
@ -86,8 +68,9 @@ fml::RefPtr<FragmentShader> FragmentProgram::shader(
return FragmentShader::Create(shader, std::move(sk_shader));
}
fml::RefPtr<FragmentProgram> FragmentProgram::Create() {
return fml::MakeRefCounted<FragmentProgram>();
void FragmentProgram::Create(Dart_Handle wrapper) {
auto res = fml::MakeRefCounted<FragmentProgram>();
res->AssociateWithDartWrapper(wrapper);
}
FragmentProgram::FragmentProgram() = default;

View File

@ -14,10 +14,6 @@
#include <string>
#include <vector>
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class FragmentProgram : public RefCountedDartWrappable<FragmentProgram> {
@ -26,16 +22,14 @@ class FragmentProgram : public RefCountedDartWrappable<FragmentProgram> {
public:
~FragmentProgram() override;
static fml::RefPtr<FragmentProgram> Create();
static void Create(Dart_Handle wrapper);
void init(std::string sksl, bool debugPrintSksl);
fml::RefPtr<FragmentShader> shader(Dart_Handle shader,
tonic::Float32List& uniforms,
Dart_Handle uniforms_handle,
Dart_Handle samplers);
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
FragmentProgram();
sk_sp<SkRuntimeEffect> runtime_effect_;

View File

@ -15,8 +15,6 @@
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/typed_data/typed_list.h"
using tonic::ToDart;
namespace flutter {
// Since _FragmentShader is a private class, we can't use
@ -29,12 +27,8 @@ static const tonic::DartWrapperInfo kDartWrapperInfo_ui_FragmentShader = {
const tonic::DartWrapperInfo& FragmentShader::dart_wrapper_info_ =
kDartWrapperInfo_ui_FragmentShader;
void FragmentShader::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({});
}
std::shared_ptr<DlColorSource> FragmentShader::shader(
SkSamplingOptions& sampling) {
const SkSamplingOptions& sampling) {
// Sampling options are ignored, since sampling options don't make sense for
// generative shaders.
return source_;

View File

@ -17,10 +17,6 @@
#include <string>
#include <vector>
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class FragmentShader : public Shader {
@ -32,9 +28,7 @@ class FragmentShader : public Shader {
static fml::RefPtr<FragmentShader> Create(Dart_Handle dart_handle,
sk_sp<SkShader> shader);
std::shared_ptr<DlColorSource> shader(SkSamplingOptions&) override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
std::shared_ptr<DlColorSource> shader(const SkSamplingOptions&) override;
private:
explicit FragmentShader(sk_sp<SkShader> shader);

View File

@ -14,28 +14,12 @@ namespace flutter {
typedef CanvasGradient
Gradient; // Because the C++ name doesn't match the Dart name.
static void Gradient_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&CanvasGradient::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, Gradient);
#define FOR_EACH_BINDING(V) \
V(Gradient, initLinear) \
V(Gradient, initRadial) \
V(Gradient, initSweep) \
V(Gradient, initTwoPointConical)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void CanvasGradient::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({{"Gradient_constructor", Gradient_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<CanvasGradient> CanvasGradient::Create() {
return fml::MakeRefCounted<CanvasGradient>();
void CanvasGradient::Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<CanvasGradient>();
res->AssociateWithDartWrapper(wrapper);
}
void CanvasGradient::initLinear(const tonic::Float32List& end_points,

View File

@ -10,10 +10,6 @@
#include "flutter/lib/ui/painting/shader.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
// TODO: update this if/when Skia adds Decal mode skbug.com/7638
@ -25,7 +21,7 @@ class CanvasGradient : public Shader {
public:
~CanvasGradient() override;
static fml::RefPtr<CanvasGradient> Create();
static void Create(Dart_Handle wrapper);
void initLinear(const tonic::Float32List& end_points,
const tonic::Int32List& colors,
@ -61,12 +57,11 @@ class CanvasGradient : public Shader {
SkTileMode tile_mode,
const tonic::Float64List& matrix4);
std::shared_ptr<DlColorSource> shader(SkSamplingOptions& sampling) override {
std::shared_ptr<DlColorSource> shader(
const SkSamplingOptions& sampling) override {
return dl_shader_->with_sampling(sampling);
}
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
CanvasGradient();
std::shared_ptr<DlColorSource> dl_shader_;

View File

@ -23,18 +23,6 @@ static const tonic::DartWrapperInfo kDartWrapperInfo_ui_Image = {
const tonic::DartWrapperInfo& Image::dart_wrapper_info_ =
kDartWrapperInfo_ui_Image;
#define FOR_EACH_BINDING(V) \
V(Image, width) \
V(Image, height) \
V(Image, toByteData) \
V(Image, dispose)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void CanvasImage::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
CanvasImage::CanvasImage() = default;
CanvasImage::~CanvasImage() = default;

View File

@ -12,10 +12,6 @@
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/skia/include/core/SkImage.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class CanvasImage final : public RefCountedDartWrappable<CanvasImage> {
@ -43,8 +39,6 @@ class CanvasImage final : public RefCountedDartWrappable<CanvasImage> {
size_t GetAllocationSize() const override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
CanvasImage();

View File

@ -17,22 +17,6 @@ namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, ImageDescriptor);
#define FOR_EACH_BINDING(V) \
V(ImageDescriptor, initRaw) \
V(ImageDescriptor, instantiateCodec) \
V(ImageDescriptor, width) \
V(ImageDescriptor, height) \
V(ImageDescriptor, bytesPerPixel) \
V(ImageDescriptor, dispose)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void ImageDescriptor::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"ImageDescriptor_initEncoded", ImageDescriptor::initEncoded, 3, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
const SkImageInfo ImageDescriptor::CreateImageInfo() const {
FML_DCHECK(generator_);
return generator_->GetInfo();
@ -53,22 +37,15 @@ ImageDescriptor::ImageDescriptor(sk_sp<SkData> buffer,
image_info_(CreateImageInfo()),
row_bytes_(std::nullopt) {}
void ImageDescriptor::initEncoded(Dart_NativeArguments args) {
Dart_Handle callback_handle = Dart_GetNativeArgument(args, 2);
Dart_Handle ImageDescriptor::initEncoded(Dart_Handle descriptor_handle,
ImmutableBuffer* immutable_buffer,
Dart_Handle callback_handle) {
if (!Dart_IsClosure(callback_handle)) {
Dart_SetReturnValue(args, tonic::ToDart("Callback must be a function"));
return;
return tonic::ToDart("Callback must be a function");
}
Dart_Handle descriptor_handle = Dart_GetNativeArgument(args, 0);
ImmutableBuffer* immutable_buffer =
tonic::DartConverter<ImmutableBuffer*>::FromDart(
Dart_GetNativeArgument(args, 1));
if (!immutable_buffer) {
Dart_SetReturnValue(args,
tonic::ToDart("Buffer parameter must not be null"));
return;
return tonic::ToDart("Buffer parameter must not be null");
}
// This has to be valid because this method is called from Dart.
@ -76,11 +53,10 @@ void ImageDescriptor::initEncoded(Dart_NativeArguments args) {
auto registry = dart_state->GetImageGeneratorRegistry();
if (!registry) {
Dart_SetReturnValue(
args, tonic::ToDart("Failed to access the internal image decoder "
"registry on this isolate. Please file a bug on "
"https://github.com/flutter/flutter/issues."));
return;
return tonic::ToDart(
"Failed to access the internal image decoder "
"registry on this isolate. Please file a bug on "
"https://github.com/flutter/flutter/issues.");
}
auto generator =
@ -88,8 +64,7 @@ void ImageDescriptor::initEncoded(Dart_NativeArguments args) {
if (!generator) {
// No compatible image decoder was found.
Dart_SetReturnValue(args, tonic::ToDart("Invalid image data"));
return;
return tonic::ToDart("Invalid image data");
}
auto descriptor = fml::MakeRefCounted<ImageDescriptor>(
@ -99,6 +74,8 @@ void ImageDescriptor::initEncoded(Dart_NativeArguments args) {
descriptor->AssociateWithDartWrapper(descriptor_handle);
tonic::DartInvoke(callback_handle, {Dart_TypeVoid()});
return Dart_Null();
}
void ImageDescriptor::initRaw(Dart_Handle descriptor_handle,

View File

@ -44,7 +44,9 @@ class ImageDescriptor : public RefCountedDartWrappable<ImageDescriptor> {
/// an `ImageGenerator` and read EXIF corrected dimensions from the
/// image data.
/// @see `ImageGeneratorRegistry`
static void initEncoded(Dart_NativeArguments args);
static Dart_Handle initEncoded(Dart_Handle descriptor_handle,
ImmutableBuffer* immutable_buffer,
Dart_Handle callback_handle);
/// @brief Synchronously initializes an `ImageDescriptor` for decompressed
/// image data as specified by the `PixelFormat`.
@ -116,8 +118,6 @@ class ImageDescriptor : public RefCountedDartWrappable<ImageDescriptor> {
return sizeof(ImageDescriptor) + sizeof(SkImageInfo) + buffer_->size();
}
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
ImageDescriptor(sk_sp<SkData> buffer,
const SkImageInfo& image_info,

View File

@ -13,31 +13,12 @@
namespace flutter {
static void ImageFilter_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&ImageFilter::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, ImageFilter);
#define FOR_EACH_BINDING(V) \
V(ImageFilter, initBlur) \
V(ImageFilter, initDilate) \
V(ImageFilter, initErode) \
V(ImageFilter, initMatrix) \
V(ImageFilter, initColorFilter) \
V(ImageFilter, initComposeFilter)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void ImageFilter::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"ImageFilter_constructor", ImageFilter_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<ImageFilter> ImageFilter::Create() {
return fml::MakeRefCounted<ImageFilter>();
void ImageFilter::Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<ImageFilter>();
res->AssociateWithDartWrapper(wrapper);
}
static const std::array<SkSamplingOptions, 4> filter_qualities = {

View File

@ -24,7 +24,7 @@ class ImageFilter : public RefCountedDartWrappable<ImageFilter> {
public:
~ImageFilter() override;
static fml::RefPtr<ImageFilter> Create();
static void Create(Dart_Handle wrapper);
static SkSamplingOptions SamplingFromIndex(int filterQualityIndex);
static SkFilterMode FilterModeFromIndex(int index);

View File

@ -15,24 +15,11 @@ using tonic::ToDart;
namespace flutter {
static void ImageShader_constructor(Dart_NativeArguments args) {
DartCallConstructor(&ImageShader::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, ImageShader);
#define FOR_EACH_BINDING(V) V(ImageShader, initWithImage)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void ImageShader::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"ImageShader_constructor", ImageShader_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<ImageShader> ImageShader::Create() {
return fml::MakeRefCounted<ImageShader>();
void ImageShader::Create(Dart_Handle wrapper) {
auto res = fml::MakeRefCounted<ImageShader>();
res->AssociateWithDartWrapper(wrapper);
}
void ImageShader::initWithImage(CanvasImage* image,
@ -62,9 +49,10 @@ void ImageShader::initWithImage(CanvasImage* image,
}
std::shared_ptr<DlColorSource> ImageShader::shader(
SkSamplingOptions& sampling) {
const SkSamplingOptions& sampling) {
if (sampling_is_locked_) {
sampling = cached_shader_.skia_object()->sampling();
return cached_shader_.skia_object()->with_sampling(
cached_shader_.skia_object()->sampling());
}
// It might seem that if the sampling is locked we can just return the
// cached version, but since we need to hold the cached shader in a

View File

@ -14,10 +14,6 @@
#include "third_party/skia/include/core/SkShader.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class ImageShader : public Shader {
@ -26,7 +22,7 @@ class ImageShader : public Shader {
public:
~ImageShader() override;
static fml::RefPtr<ImageShader> Create();
static void Create(Dart_Handle wrapper);
void initWithImage(CanvasImage* image,
SkTileMode tmx,
@ -34,9 +30,7 @@ class ImageShader : public Shader {
int filter_quality_index,
const tonic::Float64List& matrix4);
std::shared_ptr<DlColorSource> shader(SkSamplingOptions&) override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
std::shared_ptr<DlColorSource> shader(const SkSamplingOptions&) override;
int width();
int height();

View File

@ -19,34 +19,24 @@ namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, ImmutableBuffer);
#define FOR_EACH_BINDING(V) \
V(ImmutableBuffer, dispose) \
V(ImmutableBuffer, length)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
ImmutableBuffer::~ImmutableBuffer() {}
void ImmutableBuffer::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({{"ImmutableBuffer_init", ImmutableBuffer::init, 3, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
void ImmutableBuffer::init(Dart_NativeArguments args) {
Dart_Handle callback_handle = Dart_GetNativeArgument(args, 2);
Dart_Handle ImmutableBuffer::init(Dart_Handle buffer_handle,
Dart_Handle data,
Dart_Handle callback_handle) {
if (!Dart_IsClosure(callback_handle)) {
Dart_SetReturnValue(args, tonic::ToDart("Callback must be a function"));
return;
return tonic::ToDart("Callback must be a function");
}
Dart_Handle buffer_handle = Dart_GetNativeArgument(args, 0);
tonic::Uint8List data = tonic::Uint8List(Dart_GetNativeArgument(args, 1));
tonic::Uint8List dataList = tonic::Uint8List(data);
auto sk_data = MakeSkDataWithCopy(data.data(), data.num_elements());
data.Release();
auto sk_data = MakeSkDataWithCopy(dataList.data(), dataList.num_elements());
dataList.Release();
auto buffer = fml::MakeRefCounted<ImmutableBuffer>(sk_data);
buffer->AssociateWithDartWrapper(buffer_handle);
tonic::DartInvoke(callback_handle, {Dart_TypeVoid()});
return Dart_Null();
}
size_t ImmutableBuffer::GetAllocationSize() const {

View File

@ -30,14 +30,16 @@ class ImmutableBuffer : public RefCountedDartWrappable<ImmutableBuffer> {
/// Initializes a new ImmutableData from a Dart Uint8List.
///
/// The zero indexed argument is the caller that will be registered as the
/// Dart peer of the native ImmutableBuffer object.
/// `buffer_handle` is the caller that will be registered as the Dart peer of
/// the native ImmutableBuffer object.
///
/// The first indexed argumented is a tonic::Uint8List of bytes to copy.
/// `data` is a tonic::Uint8List of bytes to copy.
///
/// The second indexed argument is expected to be a void callback to signal
/// when the copy has completed.
static void init(Dart_NativeArguments args);
/// `callback_handle` is expected to be a void callback to signal when the
/// copy has completed.
static Dart_Handle init(Dart_Handle buffer_handle,
Dart_Handle data,
Dart_Handle callback_handle);
/// The length of the data in bytes.
size_t length() const {
@ -60,8 +62,6 @@ class ImmutableBuffer : public RefCountedDartWrappable<ImmutableBuffer> {
size_t GetAllocationSize() const override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
explicit ImmutableBuffer(sk_sp<SkData> data) : data_(std::move(data)) {}

View File

@ -9,6 +9,8 @@
#include "flutter/lib/ui/painting/codec.h"
#include "flutter/lib/ui/painting/image_generator.h"
using tonic::DartPersistentValue;
namespace flutter {
class MultiFrameCodec : public Codec {

View File

@ -19,54 +19,8 @@ namespace flutter {
typedef CanvasPath Path;
static void Path_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&CanvasPath::CreateNew, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, Path);
#define FOR_EACH_BINDING(V) \
V(Path, addArc) \
V(Path, addOval) \
V(Path, addPath) \
V(Path, addPolygon) \
V(Path, addRect) \
V(Path, addRRect) \
V(Path, arcTo) \
V(Path, arcToPoint) \
V(Path, close) \
V(Path, conicTo) \
V(Path, contains) \
V(Path, cubicTo) \
V(Path, extendWithPath) \
V(Path, extendWithPathAndMatrix) \
V(Path, getFillType) \
V(Path, lineTo) \
V(Path, moveTo) \
V(Path, quadraticBezierTo) \
V(Path, relativeArcToPoint) \
V(Path, relativeConicTo) \
V(Path, relativeCubicTo) \
V(Path, relativeLineTo) \
V(Path, relativeMoveTo) \
V(Path, relativeQuadraticBezierTo) \
V(Path, reset) \
V(Path, setFillType) \
V(Path, shift) \
V(Path, transform) \
V(Path, getBounds) \
V(Path, addPathWithMatrix) \
V(Path, op) \
V(Path, clone)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void CanvasPath::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({{"Path_constructor", Path_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
CanvasPath::CanvasPath()
: path_tracker_(UIDartState::Current()->GetVolatilePathTracker()),
tracked_path_(std::make_shared<VolatilePathTracker::TrackedPath>()) {
@ -251,7 +205,9 @@ void CanvasPath::addPath(CanvasPath* path, double dx, double dy) {
void CanvasPath::addPathWithMatrix(CanvasPath* path,
double dx,
double dy,
tonic::Float64List& matrix4) {
Dart_Handle matrix4_handle) {
tonic::Float64List matrix4(matrix4_handle);
if (!path) {
matrix4.Release();
Dart_ThrowException(
@ -280,7 +236,9 @@ void CanvasPath::extendWithPath(CanvasPath* path, double dx, double dy) {
void CanvasPath::extendWithPathAndMatrix(CanvasPath* path,
double dx,
double dy,
tonic::Float64List& matrix4) {
Dart_Handle matrix4_handle) {
tonic::Float64List matrix4(matrix4_handle);
if (!path) {
matrix4.Release();
Dart_ThrowException(
@ -311,17 +269,18 @@ bool CanvasPath::contains(double x, double y) {
}
void CanvasPath::shift(Dart_Handle path_handle, double dx, double dy) {
fml::RefPtr<CanvasPath> path = CanvasPath::Create(path_handle);
fml::RefPtr<CanvasPath> path = Create(path_handle);
auto& other_mutable_path = path->mutable_path();
mutable_path().offset(dx, dy, &other_mutable_path);
resetVolatility();
}
void CanvasPath::transform(Dart_Handle path_handle,
tonic::Float64List& matrix4) {
Dart_Handle matrix4_handle) {
tonic::Float64List matrix4(matrix4_handle);
auto sk_matrix = ToSkMatrix(matrix4);
matrix4.Release();
fml::RefPtr<CanvasPath> path = CanvasPath::Create(path_handle);
fml::RefPtr<CanvasPath> path = Create(path_handle);
auto& other_mutable_path = path->mutable_path();
mutable_path().transform(sk_matrix, &other_mutable_path);
}
@ -343,7 +302,7 @@ bool CanvasPath::op(CanvasPath* path1, CanvasPath* path2, int operation) {
}
void CanvasPath::clone(Dart_Handle path_handle) {
fml::RefPtr<CanvasPath> path = CanvasPath::Create(path_handle);
fml::RefPtr<CanvasPath> path = Create(path_handle);
// per Skia docs, this will create a fast copy
// data is shared until the source path or dest path are mutated
path->mutable_path() = this->path();

View File

@ -7,15 +7,12 @@
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/painting/rrect.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/volatile_path_tracker.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/pathops/SkPathOps.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class CanvasPath : public RefCountedDartWrappable<CanvasPath> {
@ -24,21 +21,18 @@ class CanvasPath : public RefCountedDartWrappable<CanvasPath> {
public:
~CanvasPath() override;
static fml::RefPtr<CanvasPath> CreateNew() {
return fml::MakeRefCounted<CanvasPath>();
}
static fml::RefPtr<CanvasPath> Create(Dart_Handle path_handle) {
static void CreateFrom(Dart_Handle path_handle, const SkPath& src) {
auto path = fml::MakeRefCounted<CanvasPath>();
path->AssociateWithDartWrapper(path_handle);
return path;
path->tracked_path_->path = src;
}
static fml::RefPtr<CanvasPath> CreateFrom(Dart_Handle path_handle,
const SkPath& src) {
fml::RefPtr<CanvasPath> path = CanvasPath::Create(path_handle);
path->tracked_path_->path = src;
return path;
static fml::RefPtr<CanvasPath> Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<CanvasPath>();
res->AssociateWithDartWrapper(wrapper);
return res;
}
int getFillType();
@ -91,20 +85,26 @@ class CanvasPath : public RefCountedDartWrappable<CanvasPath> {
void addPolygon(const tonic::Float32List& points, bool close);
void addRRect(const RRect& rrect);
void addPath(CanvasPath* path, double dx, double dy);
void addPathWithMatrix(CanvasPath* path,
double dx,
double dy,
tonic::Float64List& matrix4);
Dart_Handle matrix4_handle);
void extendWithPath(CanvasPath* path, double dx, double dy);
void extendWithPathAndMatrix(CanvasPath* path,
double dx,
double dy,
tonic::Float64List& matrix4);
Dart_Handle matrix4_handle);
void close();
void reset();
bool contains(double x, double y);
void shift(Dart_Handle path_handle, double dx, double dy);
void transform(Dart_Handle path_handle, tonic::Float64List& matrix4);
void transform(Dart_Handle path_handle, Dart_Handle matrix4_handle);
tonic::Float32List getBounds();
bool op(CanvasPath* path1, CanvasPath* path2, int operation);
void clone(Dart_Handle path_handle);
@ -113,8 +113,6 @@ class CanvasPath : public RefCountedDartWrappable<CanvasPath> {
size_t GetAllocationSize() const override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
CanvasPath();

View File

@ -13,37 +13,16 @@
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
using tonic::ToDart;
namespace flutter {
typedef CanvasPathMeasure PathMeasure;
static void PathMeasure_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&CanvasPathMeasure::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, PathMeasure);
#define FOR_EACH_BINDING(V) \
V(PathMeasure, setPath) \
V(PathMeasure, getLength) \
V(PathMeasure, getPosTan) \
V(PathMeasure, getSegment) \
V(PathMeasure, isClosed) \
V(PathMeasure, nextContour)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void CanvasPathMeasure::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"PathMeasure_constructor", PathMeasure_constructor, 3, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<CanvasPathMeasure> CanvasPathMeasure::Create(const CanvasPath* path,
bool forceClosed) {
void CanvasPathMeasure::Create(Dart_Handle wrapper,
const CanvasPath* path,
bool forceClosed) {
UIDartState::ThrowIfUIOperationsProhibited();
fml::RefPtr<CanvasPathMeasure> pathMeasure =
fml::MakeRefCounted<CanvasPathMeasure>();
if (path) {
@ -54,7 +33,7 @@ fml::RefPtr<CanvasPathMeasure> CanvasPathMeasure::Create(const CanvasPath* path,
} else {
pathMeasure->path_measure_ = std::make_unique<SkContourMeasureIter>();
}
return pathMeasure;
pathMeasure->AssociateWithDartWrapper(wrapper);
}
CanvasPathMeasure::CanvasPathMeasure() {}

View File

@ -13,10 +13,6 @@
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
// Be sure that the client doesn't modify a path on us before Skia finishes
// See AOSP's reasoning in PathMeasure.cpp
@ -28,8 +24,9 @@ class CanvasPathMeasure : public RefCountedDartWrappable<CanvasPathMeasure> {
public:
~CanvasPathMeasure() override;
static fml::RefPtr<CanvasPathMeasure> Create(const CanvasPath* path,
bool forceClosed);
static void Create(Dart_Handle wrapper,
const CanvasPath* path,
bool forceClosed);
void setPath(const CanvasPath* path, bool isClosed);
float getLength(int contour_index);
@ -42,8 +39,6 @@ class CanvasPathMeasure : public RefCountedDartWrappable<CanvasPathMeasure> {
bool isClosed(int contour_index);
bool nextContour();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
const SkContourMeasureIter& pathMeasure() const { return *path_measure_; }
private:

View File

@ -21,13 +21,6 @@ namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, Picture);
#define FOR_EACH_BINDING(V) \
V(Picture, toImage) \
V(Picture, dispose) \
V(Picture, GetAllocationSize)
DART_BIND_ALL(Picture, FOR_EACH_BINDING)
fml::RefPtr<Picture> Picture::Create(
Dart_Handle dart_handle,
flutter::SkiaGPUObject<SkPicture> picture) {

View File

@ -12,10 +12,6 @@
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class Canvas;
@ -44,8 +40,6 @@ class Picture : public RefCountedDartWrappable<Picture> {
size_t GetAllocationSize() const override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
static Dart_Handle RasterizeToImage(sk_sp<SkPicture> picture,
uint32_t width,
uint32_t height,

View File

@ -14,25 +14,12 @@
namespace flutter {
static void PictureRecorder_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&PictureRecorder::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, PictureRecorder);
#define FOR_EACH_BINDING(V) V(PictureRecorder, endRecording)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void PictureRecorder::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"PictureRecorder_constructor", PictureRecorder_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<PictureRecorder> PictureRecorder::Create() {
return fml::MakeRefCounted<PictureRecorder>();
void PictureRecorder::Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<PictureRecorder>();
res->AssociateWithDartWrapper(wrapper);
}
PictureRecorder::PictureRecorder() {}

View File

@ -9,10 +9,6 @@
#include "flutter/lib/ui/dart_wrapper.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class Canvas;
class Picture;
@ -22,7 +18,7 @@ class PictureRecorder : public RefCountedDartWrappable<PictureRecorder> {
FML_FRIEND_MAKE_REF_COUNTED(PictureRecorder);
public:
static fml::RefPtr<PictureRecorder> Create();
static void Create(Dart_Handle wrapper);
~PictureRecorder() override;
@ -35,8 +31,6 @@ class PictureRecorder : public RefCountedDartWrappable<PictureRecorder> {
void set_canvas(fml::RefPtr<Canvas> canvas) { canvas_ = std::move(canvas); }
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
PictureRecorder();

View File

@ -17,7 +17,7 @@ class Shader : public RefCountedDartWrappable<Shader> {
public:
~Shader() override;
virtual std::shared_ptr<DlColorSource> shader(SkSamplingOptions&) = 0;
virtual std::shared_ptr<DlColorSource> shader(const SkSamplingOptions&) = 0;
protected:
Shader() {}

View File

@ -11,6 +11,8 @@
#include "flutter/lib/ui/painting/image_decoder.h"
#include "flutter/lib/ui/painting/image_descriptor.h"
using tonic::DartPersistentValue;
namespace flutter {
class SingleFrameCodec : public Codec {

View File

@ -14,26 +14,23 @@ namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, Vertices);
#define FOR_EACH_BINDING(V) V(Vertices, init)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
Vertices::Vertices() {}
Vertices::~Vertices() {}
void Vertices::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
bool Vertices::init(Dart_Handle vertices_handle,
DlVertexMode vertex_mode,
tonic::Float32List& positions,
tonic::Float32List& texture_coordinates,
tonic::Int32List& colors,
tonic::Uint16List& indices) {
Dart_Handle positions_handle,
Dart_Handle texture_coordinates_handle,
Dart_Handle colors_handle,
Dart_Handle indices_handle) {
UIDartState::ThrowIfUIOperationsProhibited();
tonic::Float32List positions(positions_handle);
tonic::Float32List texture_coordinates(texture_coordinates_handle);
tonic::Int32List colors(colors_handle);
tonic::Uint16List indices(indices_handle);
if (!positions.data()) {
return false;
}

View File

@ -10,10 +10,6 @@
#include "third_party/skia/include/core/SkVertices.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class Vertices : public RefCountedDartWrappable<Vertices> {
@ -23,14 +19,12 @@ class Vertices : public RefCountedDartWrappable<Vertices> {
public:
~Vertices() override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
static bool init(Dart_Handle vertices_handle,
DlVertexMode vertex_mode,
tonic::Float32List& positions,
tonic::Float32List& texture_coordinates,
tonic::Int32List& colors,
tonic::Uint16List& indices);
Dart_Handle positions_handle,
Dart_Handle texture_coordinates_handle,
Dart_Handle colors_handle,
Dart_Handle indices_handle);
const DlVertices* vertices() const { return vertices_.get(); }

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// Signature of callbacks that have no arguments and return no data.
@ -255,7 +255,7 @@ class PlatformDispatcher {
assert(bounds.length / 4 == type.length, 'Bounds are rectangles, requiring 4 measurements each');
assert(type.length == state.length);
final List<DisplayFeature> result = <DisplayFeature>[];
for(int i = 0; i < type.length; i++){
for(int i = 0; i < type.length; i++) {
final int rectOffset = i * 4;
result.add(DisplayFeature(
bounds: Rect.fromLTRB(
@ -497,8 +497,11 @@ class PlatformDispatcher {
}
late _SetNeedsReportTimingsFunc _setNeedsReportTimings;
void _nativeSetNeedsReportTimings(bool value)
native 'PlatformConfiguration_setNeedsReportTimings';
void _nativeSetNeedsReportTimings(bool value) => __nativeSetNeedsReportTimings(value);
@FfiNative<Void Function(Bool)>('PlatformConfigurationNativeApi::SetNeedsReportTimings')
external static void __nativeSetNeedsReportTimings(bool value);
// Called from the engine, via hooks.dart
void _reportTimings(List<int> timings) {
@ -526,8 +529,11 @@ class PlatformDispatcher {
throw Exception(error);
}
String? _sendPlatformMessage(String name, PlatformMessageResponseCallback? callback, ByteData? data)
native 'PlatformConfiguration_sendPlatformMessage';
String? _sendPlatformMessage(String name,PlatformMessageResponseCallback? callback, ByteData? data) =>
__sendPlatformMessage(name, callback, data);
@FfiNative<Handle Function(Handle, Handle, Handle)>('PlatformConfigurationNativeApi::SendPlatformMessage')
external static String? __sendPlatformMessage(String name, PlatformMessageResponseCallback? callback, ByteData? data);
/// Called whenever this platform dispatcher receives a message from a
/// platform-specific plugin.
@ -553,8 +559,10 @@ class PlatformDispatcher {
}
/// Called by [_dispatchPlatformMessage].
void _respondToPlatformMessage(int responseId, ByteData? data)
native 'PlatformConfiguration_respondToPlatformMessage';
void _respondToPlatformMessage(int responseId, ByteData? data) => __respondToPlatformMessage(responseId, data);
@FfiNative<Void Function(IntPtr, Handle)>('PlatformConfigurationNativeApi::RespondToPlatformMessage')
external static void __respondToPlatformMessage(int responseId, ByteData? data);
/// Wraps the given [callback] in another callback that ensures that the
/// original callback is called in the zone it was registered in.
@ -611,7 +619,10 @@ class PlatformDispatcher {
/// This can be combined with flutter tools `--isolate-filter` flag to debug
/// specific root isolates. For example: `flutter attach --isolate-filter=[name]`.
/// Note that this does not rename any child isolates of the root.
void setIsolateDebugName(String name) native 'PlatformConfiguration_setIsolateDebugName';
void setIsolateDebugName(String name) => _setIsolateDebugName(name);
@FfiNative<Void Function(Handle)>('PlatformConfigurationNativeApi::SetIsolateDebugName')
external static void _setIsolateDebugName(String name);
/// The embedder can specify data that the isolate can request synchronously
/// on launch. This accessor fetches that data.
@ -622,7 +633,10 @@ class PlatformDispatcher {
///
/// For asynchronous communication between the embedder and isolate, a
/// platform channel may be used.
ByteData? getPersistentIsolateData() native 'PlatformConfiguration_getPersistentIsolateData';
ByteData? getPersistentIsolateData() => _getPersistentIsolateData();
@FfiNative<Handle Function()>('PlatformConfigurationNativeApi::GetPersistentIsolateData')
external static ByteData? _getPersistentIsolateData();
/// Requests that, at the next appropriate opportunity, the [onBeginFrame] and
/// [onDrawFrame] callbacks be invoked.
@ -631,7 +645,10 @@ class PlatformDispatcher {
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
void scheduleFrame() native 'PlatformConfiguration_scheduleFrame';
void scheduleFrame() => _scheduleFrame();
@FfiNative<Void Function()>('PlatformConfigurationNativeApi::ScheduleFrame')
external static void _scheduleFrame();
/// Additional accessibility features that may be enabled by the platform.
AccessibilityFeatures get accessibilityFeatures => configuration.accessibilityFeatures;
@ -671,7 +688,10 @@ class PlatformDispatcher {
///
/// In either case, this function disposes the given update, which means the
/// semantics update cannot be used further.
void updateSemantics(SemanticsUpdate update) native 'PlatformConfiguration_updateSemantics';
void updateSemantics(SemanticsUpdate update) => _updateSemantics(update);
@FfiNative<Void Function(Pointer<Void>)>('PlatformConfigurationNativeApi::UpdateSemantics')
external static void _updateSemantics(SemanticsUpdate update);
/// The system-reported default locale of the device.
///
@ -729,7 +749,11 @@ class PlatformDispatcher {
}
return null;
}
List<String> _computePlatformResolvedLocale(List<String?> supportedLocalesData) native 'PlatformConfiguration_computePlatformResolvedLocale';
List<String> _computePlatformResolvedLocale(List<String?> supportedLocalesData) => __computePlatformResolvedLocale(supportedLocalesData);
@FfiNative<Handle Function(Handle)>('PlatformConfigurationNativeApi::ComputePlatformResolvedLocale')
external static List<String> __computePlatformResolvedLocale(List<String?> supportedLocalesData);
/// A callback that is invoked whenever [locale] changes value.
///
@ -912,8 +936,7 @@ class PlatformDispatcher {
data['platformBrightness']! as String == 'dark' ? Brightness.dark : Brightness.light;
final String? systemFontFamily = data['systemFontFamily'] as String?;
final PlatformConfiguration previousConfiguration = configuration;
final bool platformBrightnessChanged =
previousConfiguration.platformBrightness != platformBrightness;
final bool platformBrightnessChanged = previousConfiguration.platformBrightness != platformBrightness;
final bool textScaleFactorChanged = previousConfiguration.textScaleFactor != textScaleFactor;
final bool alwaysUse24HourFormatChanged =
previousConfiguration.alwaysUse24HourFormat != alwaysUse24HourFormat;
@ -1097,7 +1120,9 @@ class PlatformDispatcher {
/// * [SystemChannels.navigation], which handles subsequent navigation
/// requests from the embedder.
String get defaultRouteName => _defaultRouteName();
String _defaultRouteName() native 'PlatformConfiguration_defaultRouteName';
@FfiNative<Handle Function()>('PlatformConfigurationNativeApi::DefaultRouteName')
external static String _defaultRouteName();
}
/// Configuration of the platform.
@ -1505,7 +1530,7 @@ class FrameTiming {
/// The frame key associated with this frame measurement.
int get frameNumber => _data.last;
final List<int> _data; // some elements in microseconds, some in bytes, some are counts
final List<int> _data; // some elements in microseconds, some in bytes, some are counts
String _formatMS(Duration duration) => '${duration.inMicroseconds * 0.001}ms';
@ -1670,8 +1695,10 @@ class DisplayFeature {
return true;
if (other.runtimeType != runtimeType)
return false;
return other is DisplayFeature && bounds == other.bounds &&
type == other.type && state == other.state;
return other is DisplayFeature
&& bounds == other.bounds
&& type == other.type
&& state == other.state;
}
@override

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// A wrapper for a raw callback handle.

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// How the pointer has changed since the last report.

View File

@ -3,7 +3,7 @@
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// The possible actions that can be conveyed from the operating system
@ -694,11 +694,8 @@ class SpellOutStringAttribute extends StringAttribute {
_initSpellOutStringAttribute(this, range.start, range.end);
}
void _initSpellOutStringAttribute(
SpellOutStringAttribute instance,
int start,
int end,
) native 'NativeStringAttribute_initSpellOutStringAttribute';
@FfiNative<Void Function(Handle, Int32, Int32)>('NativeStringAttribute::initSpellOutStringAttribute')
external static void _initSpellOutStringAttribute(SpellOutStringAttribute instance, int start, int end);
@override
StringAttribute copy({required TextRange range}) {
@ -733,12 +730,8 @@ class LocaleStringAttribute extends StringAttribute {
/// The lanuage of this attribute.
final Locale locale;
void _initLocaleStringAttribute(
LocaleStringAttribute instance,
int start,
int end,
String locale,
) native 'NativeStringAttribute_initLocaleStringAttribute';
@FfiNative<Void Function(Handle, Int32, Int32, Handle)>('NativeStringAttribute::initLocaleStringAttribute')
external static void _initLocaleStringAttribute(LocaleStringAttribute instance, int start, int end, String locale);
@override
StringAttribute copy({required TextRange range}) {
@ -761,7 +754,9 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass1 {
/// Creates an empty [SemanticsUpdateBuilder] object.
@pragma('vm:entry-point')
SemanticsUpdateBuilder() { _constructor(); }
void _constructor() native 'SemanticsUpdateBuilder_constructor';
@FfiNative<Void Function(Handle)>('SemanticsUpdateBuilder::Create')
external void _constructor();
/// Update the information associated with the node with the given `id`.
///
@ -921,43 +916,80 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass1 {
additionalActions,
);
}
void _updateNode(
int id,
int flags,
int actions,
int maxValueLength,
int currentValueLength,
int textSelectionBase,
int textSelectionExtent,
int platformViewId,
int scrollChildren,
int scrollIndex,
double scrollPosition,
double scrollExtentMax,
double scrollExtentMin,
double left,
double top,
double right,
double bottom,
double elevation,
double thickness,
String label,
List<StringAttribute> labelAttributes,
String value,
List<StringAttribute> valueAttributes,
String increasedValue,
List<StringAttribute> increasedValueAttributes,
String decreasedValue,
List<StringAttribute> decreasedValueAttributes,
String hint,
List<StringAttribute> hintAttributes,
String? tooltip,
int textDirection,
Float64List transform,
Int32List childrenInTraversalOrder,
Int32List childrenInHitTestOrder,
Int32List additionalActions,
) native 'SemanticsUpdateBuilder_updateNode';
@FfiNative<
Void Function(
Pointer<Void>,
Int32,
Int32,
Int32,
Int32,
Int32,
Int32,
Int32,
Int32,
Int32,
Int32,
Double,
Double,
Double,
Double,
Double,
Double,
Double,
Double,
Double,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Int32,
Handle,
Handle,
Handle,
Handle)>('SemanticsUpdateBuilder::updateNode')
external void _updateNode(
int id,
int flags,
int actions,
int maxValueLength,
int currentValueLength,
int textSelectionBase,
int textSelectionExtent,
int platformViewId,
int scrollChildren,
int scrollIndex,
double scrollPosition,
double scrollExtentMax,
double scrollExtentMin,
double left,
double top,
double right,
double bottom,
double elevation,
double thickness,
String label,
List<StringAttribute> labelAttributes,
String value,
List<StringAttribute> valueAttributes,
String increasedValue,
List<StringAttribute> increasedValueAttributes,
String decreasedValue,
List<StringAttribute> decreasedValueAttributes,
String hint,
List<StringAttribute> hintAttributes,
String? tooltip,
int textDirection,
Float64List transform,
Int32List childrenInTraversalOrder,
Int32List childrenInHitTestOrder,
Int32List additionalActions);
/// Update the custom semantics action associated with the given `id`.
///
@ -979,11 +1011,8 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass1 {
assert(overrideId != null);
_updateCustomAction(id, label, hint, overrideId);
}
void _updateCustomAction(
int id,
String? label,
String? hint,
int overrideId) native 'SemanticsUpdateBuilder_updateCustomAction';
@FfiNative<Void Function(Pointer<Void>, Int32, Handle, Handle, Int32)>('SemanticsUpdateBuilder::updateCustomAction')
external void _updateCustomAction(int id, String? label, String? hint, int overrideId);
/// Creates a [SemanticsUpdate] object that encapsulates the updates recorded
/// by this object.
@ -995,7 +1024,8 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass1 {
_build(semanticsUpdate);
return semanticsUpdate;
}
void _build(SemanticsUpdate outSemanticsUpdate) native 'SemanticsUpdateBuilder_build';
@FfiNative<Void Function(Pointer<Void>, Handle)>('SemanticsUpdateBuilder::build')
external void _build(SemanticsUpdate outSemanticsUpdate);
}
/// An opaque object representing a batch of semantics updates.
@ -1017,5 +1047,9 @@ class SemanticsUpdate extends NativeFieldWrapperClass1 {
///
/// After calling this function, the semantics update is cannot be used
/// further.
void dispose() native 'SemanticsUpdate_dispose';
///
/// This can't be a leaf call because the native function calls Dart API
/// (Dart_SetNativeInstanceField).
@FfiNative<Void Function(Pointer<Void>)>('SemanticsUpdate::dispose')
external void dispose();
}

View File

@ -18,10 +18,6 @@ namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, SemanticsUpdate);
#define FOR_EACH_BINDING(V) V(SemanticsUpdate, dispose)
DART_BIND_ALL(SemanticsUpdate, FOR_EACH_BINDING)
void SemanticsUpdate::create(Dart_Handle semantics_update_handle,
SemanticsNodeUpdates nodes,
CustomAccessibilityActionUpdates actions) {

View File

@ -9,10 +9,6 @@
#include "flutter/lib/ui/semantics/custom_accessibility_action.h"
#include "flutter/lib/ui/semantics/semantics_node.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class SemanticsUpdate : public RefCountedDartWrappable<SemanticsUpdate> {
@ -31,8 +27,6 @@ class SemanticsUpdate : public RefCountedDartWrappable<SemanticsUpdate> {
void dispose();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
explicit SemanticsUpdate(SemanticsNodeUpdates nodes,
CustomAccessibilityActionUpdates updates);

View File

@ -21,27 +21,8 @@ void pushStringAttributes(
}
}
static void SemanticsUpdateBuilder_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&SemanticsUpdateBuilder::create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, SemanticsUpdateBuilder);
#define FOR_EACH_BINDING(V) \
V(SemanticsUpdateBuilder, updateNode) \
V(SemanticsUpdateBuilder, updateCustomAction) \
V(SemanticsUpdateBuilder, build)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void SemanticsUpdateBuilder::RegisterNatives(
tonic::DartLibraryNatives* natives) {
natives->Register({{"SemanticsUpdateBuilder_constructor",
SemanticsUpdateBuilder_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
SemanticsUpdateBuilder::SemanticsUpdateBuilder() = default;
SemanticsUpdateBuilder::~SemanticsUpdateBuilder() = default;

View File

@ -10,6 +10,7 @@
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/semantics/semantics_update.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace flutter {
@ -20,8 +21,10 @@ class SemanticsUpdateBuilder
FML_FRIEND_MAKE_REF_COUNTED(SemanticsUpdateBuilder);
public:
static fml::RefPtr<SemanticsUpdateBuilder> create() {
return fml::MakeRefCounted<SemanticsUpdateBuilder>();
static void Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<SemanticsUpdateBuilder>();
res->AssociateWithDartWrapper(wrapper);
}
~SemanticsUpdateBuilder() override;
@ -69,8 +72,6 @@ class SemanticsUpdateBuilder
void build(Dart_Handle semantics_update_handle);
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
explicit SemanticsUpdateBuilder();
SemanticsNodeUpdates nodes_;

View File

@ -15,17 +15,6 @@ namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, NativeStringAttribute);
#define FOR_EACH_BINDING(V) \
V(NativeStringAttribute, initLocaleStringAttribute) \
V(NativeStringAttribute, initSpellOutStringAttribute)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void NativeStringAttribute::RegisterNatives(
tonic::DartLibraryNatives* natives) {
natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
NativeStringAttribute::NativeStringAttribute() {}
NativeStringAttribute::~NativeStringAttribute() {}

View File

@ -77,8 +77,6 @@ class NativeStringAttribute
/// Returns the c++ representataion of StringAttribute.
const StringAttributePtr GetAttribute() const;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
NativeStringAttribute();
StringAttributePtr attribute_;

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// Whether to slant the glyphs in the font
@ -1670,7 +1670,7 @@ class ParagraphStyle {
/// paragraph. If the last line is ellipsized (see `ellipsis` below), the
/// alignment is applied to that line after it has been truncated but before
/// the ellipsis has been added.
// See: https://github.com/flutter/flutter/issues/9819
/// See: https://github.com/flutter/flutter/issues/9819
///
/// * `textDirection`: The directionality of the text, left-to-right (e.g.
/// Norwegian) or right-to-left (e.g. Hebrew). This controls the overall
@ -1849,7 +1849,7 @@ ByteData _encodeStrut(
data.setInt8(byteCount, fontStyle.index);
byteCount += 1;
}
if (fontFamily != null || (fontFamilyFallback != null && fontFamilyFallback.isNotEmpty)){
if (fontFamily != null || (fontFamilyFallback != null && fontFamilyFallback.isNotEmpty)) {
bitmask |= 1 << 2;
// passed separately to native
}
@ -1865,7 +1865,6 @@ ByteData _encodeStrut(
bitmask |= 1 << 5;
data.setFloat32(byteCount, height, _kFakeHostEndian);
byteCount += 4;
}
if (leading != null) {
bitmask |= 1 << 6;
@ -1880,7 +1879,7 @@ ByteData _encodeStrut(
assert(byteCount <= 16);
assert(bitmask >> 8 == 0, 'strut bitmask overflow: $bitmask');
return ByteData.view(data.buffer, 0, byteCount);
return ByteData.view(data.buffer, 0, byteCount);
}
/// See also:
@ -1980,7 +1979,6 @@ class StrutStyle {
@override
int get hashCode => hashValues(hashList(_encoded.buffer.asInt8List()), _fontFamily, _leadingDistribution);
}
/// A direction in which text flows.
@ -2276,7 +2274,7 @@ class TextRange {
required this.start,
required this.end,
}) : assert(start != null && start >= -1),
assert(end != null && end >= -1);
assert(end != null && end >= -1);
/// A text range that starts and ends at offset.
///
@ -2656,38 +2654,45 @@ class Paragraph extends NativeFieldWrapperClass1 {
/// The amount of horizontal space this paragraph occupies.
///
/// Valid only after [layout] has been called.
double get width native 'Paragraph_width';
@FfiNative<Double Function(Pointer<Void>)>('Paragraph::width', isLeaf: true)
external double get width;
/// The amount of vertical space this paragraph occupies.
///
/// Valid only after [layout] has been called.
double get height native 'Paragraph_height';
@FfiNative<Double Function(Pointer<Void>)>('Paragraph::height', isLeaf: true)
external double get height;
/// The distance from the left edge of the leftmost glyph to the right edge of
/// the rightmost glyph in the paragraph.
///
/// Valid only after [layout] has been called.
double get longestLine native 'Paragraph_longestLine';
@FfiNative<Double Function(Pointer<Void>)>('Paragraph::longestLine', isLeaf: true)
external double get longestLine;
/// The minimum width that this paragraph could be without failing to paint
/// its contents within itself.
///
/// Valid only after [layout] has been called.
double get minIntrinsicWidth native 'Paragraph_minIntrinsicWidth';
@FfiNative<Double Function(Pointer<Void>)>('Paragraph::minIntrinsicWidth', isLeaf: true)
external double get minIntrinsicWidth;
/// Returns the smallest width beyond which increasing the width never
/// decreases the height.
///
/// Valid only after [layout] has been called.
double get maxIntrinsicWidth native 'Paragraph_maxIntrinsicWidth';
@FfiNative<Double Function(Pointer<Void>)>('Paragraph::maxIntrinsicWidth', isLeaf: true)
external double get maxIntrinsicWidth;
/// The distance from the top of the paragraph to the alphabetic
/// baseline of the first line, in logical pixels.
double get alphabeticBaseline native 'Paragraph_alphabeticBaseline';
@FfiNative<Double Function(Pointer<Void>)>('Paragraph::alphabeticBaseline', isLeaf: true)
external double get alphabeticBaseline;
/// The distance from the top of the paragraph to the ideographic
/// baseline of the first line, in logical pixels.
double get ideographicBaseline native 'Paragraph_ideographicBaseline';
@FfiNative<Double Function(Pointer<Void>)>('Paragraph::ideographicBaseline', isLeaf: true)
external double get ideographicBaseline;
/// True if there is more vertical content, but the text was truncated, either
/// because we reached `maxLines` lines of text or because the `maxLines` was
@ -2696,13 +2701,15 @@ class Paragraph extends NativeFieldWrapperClass1 {
///
/// See the discussion of the `maxLines` and `ellipsis` arguments at
/// [new ParagraphStyle].
bool get didExceedMaxLines native 'Paragraph_didExceedMaxLines';
@FfiNative<Bool Function(Pointer<Void>)>('Paragraph::didExceedMaxLines', isLeaf: true)
external bool get didExceedMaxLines;
/// Computes the size and position of each glyph in the paragraph.
///
/// The [ParagraphConstraints] control how wide the text is allowed to be.
void layout(ParagraphConstraints constraints) => _layout(constraints.width);
void _layout(double width) native 'Paragraph_layout';
@FfiNative<Void Function(Pointer<Void>, Double)>('Paragraph::layout', isLeaf: true)
external void _layout(double width);
List<TextBox> _decodeTextBoxes(Float32List encoded) {
final int count = encoded.length ~/ 5;
@ -2738,8 +2745,10 @@ class Paragraph extends NativeFieldWrapperClass1 {
assert(boxWidthStyle != null);
return _decodeTextBoxes(_getBoxesForRange(start, end, boxHeightStyle.index, boxWidthStyle.index));
}
// See paragraph.cc for the layout of this return value.
Float32List _getBoxesForRange(int start, int end, int boxHeightStyle, int boxWidthStyle) native 'Paragraph_getRectsForRange';
@FfiNative<Handle Function(Pointer<Void>, Uint32, Uint32, Uint32, Uint32)>('Paragraph::getRectsForRange')
external Float32List _getBoxesForRange(int start, int end, int boxHeightStyle, int boxWidthStyle);
/// Returns a list of text boxes that enclose all placeholders in the paragraph.
///
@ -2751,14 +2760,18 @@ class Paragraph extends NativeFieldWrapperClass1 {
List<TextBox> getBoxesForPlaceholders() {
return _decodeTextBoxes(_getBoxesForPlaceholders());
}
Float32List _getBoxesForPlaceholders() native 'Paragraph_getRectsForPlaceholders';
@FfiNative<Handle Function(Pointer<Void>)>('Paragraph::getRectsForPlaceholders')
external Float32List _getBoxesForPlaceholders();
/// Returns the text position closest to the given offset.
TextPosition getPositionForOffset(Offset offset) {
final List<int> encoded = _getPositionForOffset(offset.dx, offset.dy);
return TextPosition(offset: encoded[0], affinity: TextAffinity.values[encoded[1]]);
}
List<int> _getPositionForOffset(double dx, double dy) native 'Paragraph_getPositionForOffset';
@FfiNative<Handle Function(Pointer<Void>, Double, Double)>('Paragraph::getPositionForOffset')
external List<int> _getPositionForOffset(double dx, double dy);
/// Returns the [TextRange] of the word at the given [TextPosition].
///
@ -2770,7 +2783,9 @@ class Paragraph extends NativeFieldWrapperClass1 {
final List<int> boundary = _getWordBoundary(position.offset);
return TextRange(start: boundary[0], end: boundary[1]);
}
List<int> _getWordBoundary(int offset) native 'Paragraph_getWordBoundary';
@FfiNative<Handle Function(Pointer<Void>, Uint32)>('Paragraph::getWordBoundary')
external List<int> _getWordBoundary(int offset);
/// Returns the [TextRange] of the line at the given [TextPosition].
///
@ -2802,12 +2817,15 @@ class Paragraph extends NativeFieldWrapperClass1 {
}
return line;
}
List<int> _getLineBoundary(int offset) native 'Paragraph_getLineBoundary';
@FfiNative<Handle Function(Pointer<Void>, Uint32)>('Paragraph::getLineBoundary')
external List<int> _getLineBoundary(int offset);
// Redirecting the paint function in this way solves some dependency problems
// in the C++ code. If we straighten out the C++ dependencies, we can remove
// this indirection.
void _paint(Canvas canvas, double x, double y) native 'Paragraph_paint';
@FfiNative<Void Function(Pointer<Void>, Pointer<Void>, Double, Double)>('Paragraph::paint')
external void _paint(Canvas canvas, double x, double y);
/// Returns the full list of [LineMetrics] that describe in detail the various
/// metrics of each laid out line.
@ -2836,7 +2854,9 @@ class Paragraph extends NativeFieldWrapperClass1 {
];
return metrics;
}
Float64List _computeLineMetrics() native 'Paragraph_computeLineMetrics';
@FfiNative<Handle Function(Pointer<Void>)>('Paragraph::computeLineMetrics')
external Float64List _computeLineMetrics();
}
/// Builds a [Paragraph] containing text with the given styling information.
@ -2881,27 +2901,26 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
encodedStrutStyle = null;
}
_constructor(
style._encoded,
encodedStrutStyle,
style._fontFamily,
strutFontFamilies,
style._fontSize,
style._height,
style._ellipsis,
_encodeLocale(style._locale)
);
style._encoded,
encodedStrutStyle,
style._fontFamily,
strutFontFamilies,
style._fontSize ?? 0,
style._height ?? 0,
style._ellipsis,
_encodeLocale(style._locale));
}
void _constructor(
Int32List encoded,
ByteData? strutData,
String? fontFamily,
List<Object?>? strutFontFamily,
double? fontSize,
double? height,
String? ellipsis,
String locale
) native 'ParagraphBuilder_constructor';
@FfiNative<Void Function(Handle, Handle, Handle, Handle, Handle, Double, Double, Handle, Handle)>('ParagraphBuilder::Create')
external void _constructor(
Int32List encoded,
ByteData? strutData,
String? fontFamily,
List<Object?>? strutFontFamily,
double fontSize,
double height,
String? ellipsis,
String locale);
/// The number of placeholders currently in the paragraph.
int get placeholderCount => _placeholderCount;
@ -2955,11 +2974,11 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
_pushStyle(
encoded,
fullFontFamilies,
style._fontSize,
style._letterSpacing,
style._wordSpacing,
style._height,
style._decorationThickness,
style._fontSize ?? 0,
style._letterSpacing ?? 0,
style._wordSpacing ?? 0,
style._height ?? 0,
style._decorationThickness ?? 0,
_encodeLocale(style._locale),
style._background?._objects,
style._background?._data,
@ -2971,14 +2990,32 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
);
}
void _pushStyle(
@FfiNative<
Void Function(
Pointer<Void>,
Handle,
Handle,
Double,
Double,
Double,
Double,
Double,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle,
Handle)>('ParagraphBuilder::pushStyle')
external void _pushStyle(
Int32List encoded,
List<Object?> fontFamilies,
double? fontSize,
double? letterSpacing,
double? wordSpacing,
double? height,
double? decorationThickness,
double fontSize,
double letterSpacing,
double wordSpacing,
double height,
double decorationThickness,
String locale,
List<Object?>? backgroundObjects,
ByteData? backgroundData,
@ -2987,7 +3024,7 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
ByteData shadowsData,
ByteData? fontFeaturesData,
ByteData? fontVariationsData,
) native 'ParagraphBuilder_pushStyle';
);
static String _encodeLocale(Locale? locale) => locale?.toString() ?? '';
@ -2997,7 +3034,8 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
/// added to the paragraph is affected by all the styles in the stack. Calling
/// [pop] removes the topmost style in the stack, leaving the remaining styles
/// in effect.
void pop() native 'ParagraphBuilder_pop';
@FfiNative<Void Function(Pointer<Void>)>('ParagraphBuilder::pop', isLeaf: true)
external void pop();
/// Adds the given text to the paragraph.
///
@ -3007,7 +3045,9 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
if (error != null)
throw ArgumentError(error);
}
String? _addText(String text) native 'ParagraphBuilder_addText';
@FfiNative<Handle Function(Pointer<Void>, Handle)>('ParagraphBuilder::addText')
external String? _addText(String text);
/// Adds an inline placeholder space to the paragraph.
///
@ -3068,11 +3108,13 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
// Default the baselineOffset to height if null. This will place the placeholder
// fully above the baseline, similar to [PlaceholderAlignment.aboveBaseline].
baselineOffset = baselineOffset ?? height;
_addPlaceholder(width * scale, height * scale, alignment.index, baselineOffset * scale, baseline?.index);
_addPlaceholder(width * scale, height * scale, alignment.index, baselineOffset * scale, baseline?.index ?? 0);
_placeholderCount++;
_placeholderScales.add(scale);
}
String? _addPlaceholder(double width, double height, int alignment, double baselineOffset, int? baseline) native 'ParagraphBuilder_addPlaceholder';
@FfiNative<Handle Function(Pointer<Void>, Double, Double, Uint32, Double, Uint32)>('ParagraphBuilder::addPlaceholder')
external String? _addPlaceholder(double width, double height, int alignment, double baselineOffset, int baseline);
/// Applies the given paragraph style and returns a [Paragraph] containing the
/// added text and associated styling.
@ -3084,7 +3126,9 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
_build(paragraph);
return paragraph;
}
void _build(Paragraph outParagraph) native 'ParagraphBuilder_build';
@FfiNative<Void Function(Pointer<Void>, Handle)>('ParagraphBuilder::build')
external void _build(Paragraph outParagraph);
}
/// Loads a font from a buffer and makes it available for rendering text.
@ -3119,4 +3163,5 @@ FutureOr<void> _sendFontChangeMessage() async {
}
}
void _loadFontFromList(Uint8List list, _Callback<void> callback, String? fontFamily) native 'loadFontFromList';
@FfiNative<Void Function(Handle, Handle, Handle)>('FontCollection::LoadFontFromList')
external void _loadFontFromList(Uint8List list, _Callback<void> callback, String? fontFamily);

View File

@ -25,28 +25,6 @@
namespace flutter {
namespace {
void LoadFontFromList(tonic::Uint8List& font_data, // NOLINT
Dart_Handle callback,
std::string family_name) {
FontCollection& font_collection = UIDartState::Current()
->platform_configuration()
->client()
->GetFontCollection();
font_collection.LoadFontFromList(font_data.data(), font_data.num_elements(),
family_name);
font_data.Release();
tonic::DartInvoke(callback, {tonic::ToDart(0)});
}
void _LoadFontFromList(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
tonic::DartCallStatic(LoadFontFromList, args);
}
} // namespace
FontCollection::FontCollection()
: collection_(std::make_shared<txt::FontCollection>()) {
dynamic_font_manager_ = sk_make_sp<txt::DynamicFontManager>();
@ -58,12 +36,6 @@ FontCollection::~FontCollection() {
SkGraphics::PurgeFontCache();
}
void FontCollection::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({
{"loadFontFromList", _LoadFontFromList, 3, true},
});
}
std::shared_ptr<txt::FontCollection> FontCollection::GetFontCollection() const {
return collection_;
}
@ -157,21 +129,31 @@ void FontCollection::RegisterTestFonts() {
collection_->DisableFontFallback();
}
void FontCollection::LoadFontFromList(const uint8_t* font_data,
int length,
void FontCollection::LoadFontFromList(Dart_Handle font_data_handle,
Dart_Handle callback,
std::string family_name) {
std::unique_ptr<SkStreamAsset> font_stream =
std::make_unique<SkMemoryStream>(font_data, length, true);
tonic::Uint8List font_data(font_data_handle);
UIDartState::ThrowIfUIOperationsProhibited();
FontCollection& font_collection = UIDartState::Current()
->platform_configuration()
->client()
->GetFontCollection();
std::unique_ptr<SkStreamAsset> font_stream = std::make_unique<SkMemoryStream>(
font_data.data(), font_data.num_elements(), true);
sk_sp<SkTypeface> typeface =
SkTypeface::MakeFromStream(std::move(font_stream));
txt::TypefaceFontAssetProvider& font_provider =
dynamic_font_manager_->font_provider();
font_collection.dynamic_font_manager_->font_provider();
if (family_name.empty()) {
font_provider.RegisterTypeface(typeface);
} else {
font_provider.RegisterTypeface(typeface, family_name);
}
collection_->ClearFontFamilyCache();
font_collection.collection_->ClearFontFamilyCache();
font_data.Release();
tonic::DartInvoke(callback, {tonic::ToDart(0)});
}
} // namespace flutter

View File

@ -11,12 +11,9 @@
#include "flutter/assets/asset_manager.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "third_party/tonic/typed_data/typed_list.h"
#include "txt/font_collection.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class FontCollection {
@ -25,8 +22,6 @@ class FontCollection {
~FontCollection();
static void RegisterNatives(tonic::DartLibraryNatives* natives);
std::shared_ptr<txt::FontCollection> GetFontCollection() const;
void SetupDefaultFontManager(uint32_t font_initialization_data);
@ -35,9 +30,9 @@ class FontCollection {
void RegisterTestFonts();
void LoadFontFromList(const uint8_t* font_data,
int length,
std::string family_name);
static void LoadFontFromList(Dart_Handle font_data_handle,
Dart_Handle callback,
std::string family_name);
private:
std::shared_ptr<txt::FontCollection> collection_;

View File

@ -13,32 +13,10 @@
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
using tonic::ToDart;
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, Paragraph);
#define FOR_EACH_BINDING(V) \
V(Paragraph, width) \
V(Paragraph, height) \
V(Paragraph, longestLine) \
V(Paragraph, minIntrinsicWidth) \
V(Paragraph, maxIntrinsicWidth) \
V(Paragraph, alphabeticBaseline) \
V(Paragraph, ideographicBaseline) \
V(Paragraph, didExceedMaxLines) \
V(Paragraph, layout) \
V(Paragraph, paint) \
V(Paragraph, getWordBoundary) \
V(Paragraph, getLineBoundary) \
V(Paragraph, getRectsForRange) \
V(Paragraph, getRectsForPlaceholders) \
V(Paragraph, getPositionForOffset) \
V(Paragraph, computeLineMetrics)
DART_BIND_ALL(Paragraph, FOR_EACH_BINDING)
Paragraph::Paragraph(std::unique_ptr<txt::Paragraph> paragraph)
: m_paragraph(std::move(paragraph)) {}

View File

@ -12,10 +12,6 @@
#include "flutter/lib/ui/text/text_box.h"
#include "flutter/third_party/txt/src/txt/paragraph.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class Paragraph : public RefCountedDartWrappable<Paragraph> {
@ -55,8 +51,6 @@ class Paragraph : public RefCountedDartWrappable<Paragraph> {
size_t GetAllocationSize() const override;
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
std::unique_ptr<txt::Paragraph> m_paragraph;

View File

@ -141,40 +141,22 @@ const int sForceStrutHeightMask = 1 << sForceStrutHeightIndex;
} // namespace
static void ParagraphBuilder_constructor(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
DartCallConstructor(&ParagraphBuilder::create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, ParagraphBuilder);
#define FOR_EACH_BINDING(V) \
V(ParagraphBuilder, pushStyle) \
V(ParagraphBuilder, pop) \
V(ParagraphBuilder, addText) \
V(ParagraphBuilder, addPlaceholder) \
V(ParagraphBuilder, build)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void ParagraphBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register(
{{"ParagraphBuilder_constructor", ParagraphBuilder_constructor, 9, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fml::RefPtr<ParagraphBuilder> ParagraphBuilder::create(
tonic::Int32List& encoded,
Dart_Handle strutData,
const std::string& fontFamily,
const std::vector<std::string>& strutFontFamilies,
double fontSize,
double height,
const std::u16string& ellipsis,
const std::string& locale) {
return fml::MakeRefCounted<ParagraphBuilder>(encoded, strutData, fontFamily,
strutFontFamilies, fontSize,
height, ellipsis, locale);
void ParagraphBuilder::Create(Dart_Handle wrapper,
Dart_Handle encoded_handle,
Dart_Handle strutData,
const std::string& fontFamily,
const std::vector<std::string>& strutFontFamilies,
double fontSize,
double height,
const std::u16string& ellipsis,
const std::string& locale) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<ParagraphBuilder>(
encoded_handle, strutData, fontFamily, strutFontFamilies, fontSize,
height, ellipsis, locale);
res->AssociateWithDartWrapper(wrapper);
}
// returns true if there is a font family defined. Font family is the only
@ -241,7 +223,7 @@ void decodeStrut(Dart_Handle strut_data,
}
ParagraphBuilder::ParagraphBuilder(
tonic::Int32List& encoded,
Dart_Handle encoded_data,
Dart_Handle strutData,
const std::string& fontFamily,
const std::vector<std::string>& strutFontFamilies,
@ -249,51 +231,56 @@ ParagraphBuilder::ParagraphBuilder(
double height,
const std::u16string& ellipsis,
const std::string& locale) {
int32_t mask = encoded[0];
int32_t mask = 0;
txt::ParagraphStyle style;
{
tonic::Int32List encoded(encoded_data);
if (mask & psTextAlignMask) {
style.text_align = txt::TextAlign(encoded[psTextAlignIndex]);
}
mask = encoded[0];
if (mask & psTextDirectionMask) {
style.text_direction = txt::TextDirection(encoded[psTextDirectionIndex]);
}
if (mask & psTextAlignMask) {
style.text_align = txt::TextAlign(encoded[psTextAlignIndex]);
}
if (mask & psFontWeightMask) {
style.font_weight =
static_cast<txt::FontWeight>(encoded[psFontWeightIndex]);
}
if (mask & psTextDirectionMask) {
style.text_direction = txt::TextDirection(encoded[psTextDirectionIndex]);
}
if (mask & psFontStyleMask) {
style.font_style = static_cast<txt::FontStyle>(encoded[psFontStyleIndex]);
}
if (mask & psFontWeightMask) {
style.font_weight =
static_cast<txt::FontWeight>(encoded[psFontWeightIndex]);
}
if (mask & psFontFamilyMask) {
style.font_family = fontFamily;
}
if (mask & psFontStyleMask) {
style.font_style = static_cast<txt::FontStyle>(encoded[psFontStyleIndex]);
}
if (mask & psFontSizeMask) {
style.font_size = fontSize;
}
if (mask & psFontFamilyMask) {
style.font_family = fontFamily;
}
if (mask & psHeightMask) {
style.height = height;
style.has_height_override = true;
}
if (mask & psFontSizeMask) {
style.font_size = fontSize;
}
if (mask & psTextHeightBehaviorMask) {
style.text_height_behavior = encoded[psTextHeightBehaviorIndex];
if (mask & psHeightMask) {
style.height = height;
style.has_height_override = true;
}
if (mask & psTextHeightBehaviorMask) {
style.text_height_behavior = encoded[psTextHeightBehaviorIndex];
}
if (mask & psMaxLinesMask) {
style.max_lines = encoded[psMaxLinesIndex];
}
}
if (mask & psStrutStyleMask) {
decodeStrut(strutData, strutFontFamilies, style);
}
if (mask & psMaxLinesMask) {
style.max_lines = encoded[psMaxLinesIndex];
}
if (mask & psEllipsisMask) {
style.ellipsis = ellipsis;
}
@ -389,7 +376,7 @@ void decodeFontVariations(Dart_Handle font_variations_data,
}
}
void ParagraphBuilder::pushStyle(tonic::Int32List& encoded,
void ParagraphBuilder::pushStyle(const tonic::Int32List& encoded,
const std::vector<std::string>& fontFamilies,
double fontSize,
double letterSpacing,

View File

@ -13,10 +13,6 @@
#include "flutter/third_party/txt/src/txt/paragraph_builder.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class Paragraph;
@ -26,19 +22,19 @@ class ParagraphBuilder : public RefCountedDartWrappable<ParagraphBuilder> {
FML_FRIEND_MAKE_REF_COUNTED(ParagraphBuilder);
public:
static fml::RefPtr<ParagraphBuilder> create(
tonic::Int32List& encoded,
Dart_Handle strutData,
const std::string& fontFamily,
const std::vector<std::string>& strutFontFamilies,
double fontSize,
double height,
const std::u16string& ellipsis,
const std::string& locale);
static void Create(Dart_Handle wrapper,
Dart_Handle encoded_handle,
Dart_Handle strutData,
const std::string& fontFamily,
const std::vector<std::string>& strutFontFamilies,
double fontSize,
double height,
const std::u16string& ellipsis,
const std::string& locale);
~ParagraphBuilder() override;
void pushStyle(tonic::Int32List& encoded,
void pushStyle(const tonic::Int32List& encoded,
const std::vector<std::string>& fontFamilies,
double fontSize,
double letterSpacing,
@ -72,10 +68,8 @@ class ParagraphBuilder : public RefCountedDartWrappable<ParagraphBuilder> {
void build(Dart_Handle paragraph_handle);
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
explicit ParagraphBuilder(tonic::Int32List& encoded,
explicit ParagraphBuilder(Dart_Handle encoded,
Dart_Handle strutData,
const std::string& fontFamily,
const std::vector<std::string>& strutFontFamilies,

View File

@ -9,7 +9,7 @@
/// This library exposes the lowest-level services that Flutter frameworks use
/// to bootstrap applications, such as classes for driving the input, graphics
/// text, layout, and rendering subsystems.
// @dart = 2.12
// @dart = 2.14
library dart.ui;
import 'dart:_spirv' as spv;
@ -17,6 +17,7 @@ import 'dart:async';
import 'dart:collection' as collection;
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:ffi';
import 'dart:io'; // ignore: unused_import
import 'dart:isolate' show SendPort;
import 'dart:math' as math;

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.12
// @dart = 2.14
part of dart.ui;
/// A view into which a Flutter [Scene] is drawn.
@ -264,8 +264,10 @@ abstract class FlutterView {
/// scheduling of frames.
/// * [RendererBinding], the Flutter framework class which manages layout and
/// painting.
void render(Scene scene) => _render(scene, this);
void _render(Scene scene, FlutterView view) native 'PlatformConfiguration_render';
void render(Scene scene) => _render(scene);
@FfiNative<Void Function(Pointer<Void>)>('PlatformConfigurationNativeApi::Render')
external static void _render(Scene scene);
}
/// A top-level platform window displaying a Flutter layer tree drawn from a

View File

@ -21,143 +21,6 @@
namespace flutter {
namespace {
void DefaultRouteName(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
std::string routeName = UIDartState::Current()
->platform_configuration()
->client()
->DefaultRouteName();
Dart_SetReturnValue(args, tonic::StdStringToDart(routeName));
}
void ScheduleFrame(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->ScheduleFrame();
}
void Render(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
Dart_Handle exception = nullptr;
Scene* scene =
tonic::DartConverter<Scene*>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->platform_configuration()->client()->Render(scene);
}
void UpdateSemantics(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
Dart_Handle exception = nullptr;
SemanticsUpdate* update =
tonic::DartConverter<SemanticsUpdate*>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->platform_configuration()->client()->UpdateSemantics(
update);
}
void SetIsolateDebugName(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
Dart_Handle exception = nullptr;
const std::string name =
tonic::DartConverter<std::string>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->SetDebugName(name);
}
void SetNeedsReportTimings(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
Dart_Handle exception = nullptr;
bool value = tonic::DartConverter<bool>::FromArguments(args, 1, exception);
UIDartState::Current()
->platform_configuration()
->client()
->SetNeedsReportTimings(value);
}
Dart_Handle SendPlatformMessage(Dart_Handle window,
const std::string& name,
Dart_Handle callback,
Dart_Handle data_handle) {
UIDartState* dart_state = UIDartState::Current();
if (!dart_state->platform_configuration()) {
return tonic::ToDart(
"Platform messages can only be sent from the main isolate");
}
fml::RefPtr<PlatformMessageResponse> response;
if (!Dart_IsNull(callback)) {
response = fml::MakeRefCounted<PlatformMessageResponseDart>(
tonic::DartPersistentValue(dart_state, callback),
dart_state->GetTaskRunners().GetUITaskRunner());
}
if (Dart_IsNull(data_handle)) {
dart_state->platform_configuration()->client()->HandlePlatformMessage(
std::make_unique<PlatformMessage>(name, response));
} else {
tonic::DartByteData data(data_handle);
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
dart_state->platform_configuration()->client()->HandlePlatformMessage(
std::make_unique<PlatformMessage>(
name, fml::MallocMapping::Copy(buffer, data.length_in_bytes()),
response));
}
return Dart_Null();
}
void _SendPlatformMessage(Dart_NativeArguments args) {
tonic::DartCallStatic(&SendPlatformMessage, args);
}
void RespondToPlatformMessage(Dart_Handle window,
int response_id,
const tonic::DartByteData& data) {
if (Dart_IsNull(data.dart_handle())) {
UIDartState::Current()
->platform_configuration()
->CompletePlatformMessageEmptyResponse(response_id);
} else {
// TODO(engine): Avoid this copy.
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
UIDartState::Current()
->platform_configuration()
->CompletePlatformMessageResponse(
response_id,
std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()));
}
}
void _RespondToPlatformMessage(Dart_NativeArguments args) {
tonic::DartCallStatic(&RespondToPlatformMessage, args);
}
void GetPersistentIsolateData(Dart_NativeArguments args) {
UIDartState::ThrowIfUIOperationsProhibited();
auto persistent_isolate_data = UIDartState::Current()
->platform_configuration()
->client()
->GetPersistentIsolateData();
if (!persistent_isolate_data) {
Dart_SetReturnValue(args, Dart_Null());
return;
}
Dart_SetReturnValue(
args, tonic::DartByteData::Create(persistent_isolate_data->GetMapping(),
persistent_isolate_data->GetSize()));
}
Dart_Handle ToByteData(const fml::Mapping& buffer) {
return tonic::DartByteData::Create(buffer.GetMapping(), buffer.GetSize());
}
@ -408,7 +271,105 @@ void PlatformConfiguration::CompletePlatformMessageResponse(
response->Complete(std::make_unique<fml::DataMapping>(std::move(data)));
}
Dart_Handle ComputePlatformResolvedLocale(Dart_Handle supportedLocalesHandle) {
void PlatformConfigurationNativeApi::Render(Scene* scene) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->Render(scene);
}
void PlatformConfigurationNativeApi::SetNeedsReportTimings(bool value) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()
->platform_configuration()
->client()
->SetNeedsReportTimings(value);
}
Dart_Handle PlatformConfigurationNativeApi::SendPlatformMessage(
const std::string& name,
Dart_Handle callback,
Dart_Handle data_handle) {
UIDartState* dart_state = UIDartState::Current();
if (!dart_state->platform_configuration()) {
return tonic::ToDart(
"Platform messages can only be sent from the main isolate");
}
fml::RefPtr<PlatformMessageResponse> response;
if (!Dart_IsNull(callback)) {
response = fml::MakeRefCounted<PlatformMessageResponseDart>(
tonic::DartPersistentValue(dart_state, callback),
dart_state->GetTaskRunners().GetUITaskRunner());
}
if (Dart_IsNull(data_handle)) {
dart_state->platform_configuration()->client()->HandlePlatformMessage(
std::make_unique<PlatformMessage>(name, response));
} else {
tonic::DartByteData data(data_handle);
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
dart_state->platform_configuration()->client()->HandlePlatformMessage(
std::make_unique<PlatformMessage>(
name, fml::MallocMapping::Copy(buffer, data.length_in_bytes()),
response));
}
return Dart_Null();
}
void PlatformConfigurationNativeApi::RespondToPlatformMessage(
int response_id,
const tonic::DartByteData& data) {
if (Dart_IsNull(data.dart_handle())) {
UIDartState::Current()
->platform_configuration()
->CompletePlatformMessageEmptyResponse(response_id);
} else {
// TODO(engine): Avoid this copy.
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
UIDartState::Current()
->platform_configuration()
->CompletePlatformMessageResponse(
response_id,
std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()));
}
}
void PlatformConfigurationNativeApi::SetIsolateDebugName(
const std::string name) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->SetDebugName(name);
}
Dart_Handle PlatformConfigurationNativeApi::GetPersistentIsolateData() {
UIDartState::ThrowIfUIOperationsProhibited();
auto persistent_isolate_data = UIDartState::Current()
->platform_configuration()
->client()
->GetPersistentIsolateData();
if (!persistent_isolate_data) {
return Dart_Null();
}
return tonic::DartByteData::Create(persistent_isolate_data->GetMapping(),
persistent_isolate_data->GetSize());
}
void PlatformConfigurationNativeApi::ScheduleFrame() {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->ScheduleFrame();
}
void PlatformConfigurationNativeApi::UpdateSemantics(SemanticsUpdate* update) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->UpdateSemantics(
update);
}
Dart_Handle PlatformConfigurationNativeApi::ComputePlatformResolvedLocale(
Dart_Handle supportedLocalesHandle) {
UIDartState::ThrowIfUIOperationsProhibited();
std::vector<std::string> supportedLocales =
tonic::DartConverter<std::vector<std::string>>::FromDart(
supportedLocalesHandle);
@ -422,33 +383,12 @@ Dart_Handle ComputePlatformResolvedLocale(Dart_Handle supportedLocalesHandle) {
return tonic::DartConverter<std::vector<std::string>>::ToDart(results);
}
static void _ComputePlatformResolvedLocale(Dart_NativeArguments args) {
std::string PlatformConfigurationNativeApi::DefaultRouteName() {
UIDartState::ThrowIfUIOperationsProhibited();
Dart_Handle result =
ComputePlatformResolvedLocale(Dart_GetNativeArgument(args, 1));
Dart_SetReturnValue(args, result);
}
void PlatformConfiguration::RegisterNatives(
tonic::DartLibraryNatives* natives) {
natives->Register({
{"PlatformConfiguration_defaultRouteName", DefaultRouteName, 1, true},
{"PlatformConfiguration_scheduleFrame", ScheduleFrame, 1, true},
{"PlatformConfiguration_sendPlatformMessage", _SendPlatformMessage, 4,
true},
{"PlatformConfiguration_respondToPlatformMessage",
_RespondToPlatformMessage, 3, true},
{"PlatformConfiguration_render", Render, 3, true},
{"PlatformConfiguration_updateSemantics", UpdateSemantics, 2, true},
{"PlatformConfiguration_setIsolateDebugName", SetIsolateDebugName, 2,
true},
{"PlatformConfiguration_setNeedsReportTimings", SetNeedsReportTimings, 2,
true},
{"PlatformConfiguration_getPersistentIsolateData",
GetPersistentIsolateData, 1, true},
{"PlatformConfiguration_computePlatformResolvedLocale",
_ComputePlatformResolvedLocale, 2, true},
});
return UIDartState::Current()
->platform_configuration()
->client()
->DefaultRouteName();
}
} // namespace flutter

View File

@ -17,6 +17,7 @@
#include "flutter/lib/ui/window/viewport_metrics.h"
#include "flutter/lib/ui/window/window.h"
#include "third_party/tonic/dart_persistent_value.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
namespace flutter {
class FontCollection;
@ -381,15 +382,6 @@ class PlatformConfiguration final {
///
void ReportTimings(std::vector<int64_t> timings);
//----------------------------------------------------------------------------
/// @brief Registers the native handlers for Dart functions that this
/// class handles.
///
/// @param[in] natives The natives registry that the functions will be
/// registered with.
///
static void RegisterNatives(tonic::DartLibraryNatives* natives);
//----------------------------------------------------------------------------
/// @brief Retrieves the Window with the given ID managed by the
/// `PlatformConfiguration`.
@ -444,6 +436,43 @@ class PlatformConfiguration final {
pending_responses_;
};
//----------------------------------------------------------------------------
// API exposed as FFI calls in Dart.
//
// These are probably not supposed to be called directly, and should instead
// be called through their sibling API in `PlatformConfiguration` or
// `PlatformConfigurationClient`.
//
// These are intentionally undocumented. Refer instead to the sibling methods
// above.
//----------------------------------------------------------------------------
class PlatformConfigurationNativeApi {
public:
static std::string DefaultRouteName();
static void ScheduleFrame();
static void Render(Scene* scene);
static void UpdateSemantics(SemanticsUpdate* update);
static void SetNeedsReportTimings(bool value);
static Dart_Handle GetPersistentIsolateData();
static Dart_Handle ComputePlatformResolvedLocale(
Dart_Handle supportedLocalesHandle);
static void SetIsolateDebugName(const std::string name);
static Dart_Handle SendPlatformMessage(const std::string& name,
Dart_Handle callback,
Dart_Handle data_handle);
static void RespondToPlatformMessage(int response_id,
const tonic::DartByteData& data);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_WINDOW_PLATFORM_CONFIGURATION_H_

View File

@ -434,8 +434,6 @@ DartVM::DartVM(std::shared_ptr<const DartVMData> vm_data,
::free(flags_error);
}
DartUI::InitForGlobal();
{
TRACE_EVENT0("flutter", "Dart_Initialize");
Dart_InitializeParams params = {};

View File

@ -309,6 +309,9 @@ struct DartConverter<std::string> {
}
static NativeType FromDart(Dart_Handle handle) {
if (Dart_IsNull(handle)) {
return std::string();
}
uint8_t* data = nullptr;
intptr_t length = 0;
if (Dart_IsError(Dart_StringToUTF8(handle, &data, &length)))
@ -347,6 +350,9 @@ struct DartConverter<std::u16string> {
}
static NativeType FromDart(Dart_Handle handle) {
if (Dart_IsNull(handle)) {
return std::u16string();
}
intptr_t length = 0;
Dart_StringLength(handle, &length);
std::vector<uint16_t> data(length);
@ -378,6 +384,9 @@ struct DartConverter<const char*> {
}
static const char* FromDart(Dart_Handle handle) {
if (Dart_IsNull(handle)) {
return nullptr;
}
const char* result = nullptr;
Dart_StringToCString(handle, &result);
return result;

View File

@ -89,6 +89,9 @@ Dart_PersistentHandle DartWrappable::GetTypeForWrapper(
}
DartWrappable* DartConverterWrappable::FromDart(Dart_Handle handle) {
if (Dart_IsNull(handle)) {
return nullptr;
}
intptr_t peer = 0;
Dart_Handle result =
Dart_GetNativeInstanceField(handle, DartWrappable::kPeerIndex, &peer);

View File

@ -42,10 +42,15 @@ class DartByteData {
template <>
struct DartConverter<DartByteData> {
using FfiType = Dart_Handle;
static void SetReturnValue(Dart_NativeArguments args, DartByteData val);
static DartByteData FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception);
static DartByteData FromFfi(FfiType val) { return DartByteData(val); }
static FfiType ToFfi(DartByteData val) { return val.dart_handle(); }
};
} // namespace tonic