diff --git a/DEPS b/DEPS index 1837bce255499..0bbbfc8c184f4 100644 --- a/DEPS +++ b/DEPS @@ -18,7 +18,7 @@ vars = { 'llvm_git': 'https://llvm.googlesource.com', # OCMock is for testing only so there is no google clone 'ocmock_git': 'https://github.com/erikdoe/ocmock.git', - 'skia_revision': '40442138ec94df1334ab9a6070ebaa67a3aad223', + 'skia_revision': 'bf6019be75efeee2a6a2aa862bfebc297b449786', # WARNING: DO NOT EDIT canvaskit_cipd_instance MANUALLY # See `lib/web_ui/README.md` for how to roll CanvasKit to a new version. @@ -53,7 +53,7 @@ vars = { # Dart is: https://github.com/dart-lang/sdk/blob/main/DEPS # You can use //tools/dart/create_updated_flutter_deps.py to produce # updated revision list of existing dependencies. - 'dart_revision': '00f6f69187dfe3f0a93c3f9e10517aecee210b60', + 'dart_revision': '3ebf0fedfcebbaffb4397c88f041bc95a1a3912b', # WARNING: DO NOT EDIT MANUALLY # The lines between blank lines above and below are generated by a script. See create_updated_flutter_deps.py @@ -63,7 +63,7 @@ vars = { 'dart_browser_launcher_rev': '27ec600af41b0d0ebe9a3db6ad36e9ed11976b84', 'dart_clock_rev': '263e508a36ed90e4d85b60dd70552d20e71a9ae9', 'dart_collection_rev': '1a9b7eb64be10a8ba4ced7eb36b4b265a49d5d41', - 'dart_devtools_rev': '6f42c1d59d95dcacde130f2910c1d10be8508e61', + 'dart_devtools_rev': '79b5094a0ba523633f69276aa566e53d98c3a067', 'dart_libprotobuf_rev': '24487dd1045c7f3d64a21f38a3f0c06cc4cf2edb', 'dart_perfetto_rev': 'b8da07095979310818f0efde2ef3c69ea70d62c5', 'dart_protobuf_gn_rev': 'ca669f79945418f6229e4fef89b666b2a88cbb10', @@ -332,7 +332,7 @@ deps = { Var('chromium_git') + '/external/github.com/WebAssembly/binaryen.git@cdb7aeab40b4c522de20b242019f7e88641445d5', 'src/third_party/dart/third_party/devtools': - {'dep_type': 'cipd', 'packages': [{'package': 'dart/third_party/flutter/devtools', 'version': 'git_revision:6f42c1d59d95dcacde130f2910c1d10be8508e61'}]}, + {'dep_type': 'cipd', 'packages': [{'package': 'dart/third_party/flutter/devtools', 'version': 'git_revision:79b5094a0ba523633f69276aa566e53d98c3a067'}]}, 'src/third_party/dart/third_party/pkg/args': Var('dart_git') + '/args.git@da56b18ebcb600e050bf57b9c1103b1d2a9fb2ff', @@ -884,7 +884,7 @@ deps = { 'packages': [ { 'package': 'fuchsia/sdk/core/mac-amd64', - 'version': 'DA_PryqcVU6Um3j2knmxFnoY0owmURpknkVTtrPBXXQC' + 'version': 'G25oJMO5jbUi-UN4FM1owc2acv-i0u7MdKqblmI-czMC' } ], 'condition': 'host_os == "mac" and not download_fuchsia_sdk', @@ -894,7 +894,7 @@ deps = { 'packages': [ { 'package': 'fuchsia/sdk/core/linux-amd64', - 'version': 'RVhmZNTYsaIiTyjwPz_v93og9qBqvH0fo75kFNmXe10C' + 'version': 'kKI09su99b0AKs8b3VKTzXDVmeTaKm7ye2chxl9BE0EC' } ], 'condition': 'host_os == "linux" and not download_fuchsia_sdk', diff --git a/ci/licenses_golden/licenses_dart b/ci/licenses_golden/licenses_dart index 1d366080a9ca3..d54be1d72c848 100644 --- a/ci/licenses_golden/licenses_dart +++ b/ci/licenses_golden/licenses_dart @@ -1,4 +1,4 @@ -Signature: be4e90db216cb0cf3c3e2366fe923317 +Signature: 1e850cb6cd4de368cc26a62d37a6a14e ==================================================================================================== LIBRARY: dart diff --git a/ci/licenses_golden/licenses_flutter b/ci/licenses_golden/licenses_flutter index f02a1846afa9f..6af3864bfeb6e 100644 --- a/ci/licenses_golden/licenses_flutter +++ b/ci/licenses_golden/licenses_flutter @@ -717,22 +717,18 @@ ORIGIN: ../../../flutter/display_list/benchmarking/dl_complexity_metal.h + ../.. ORIGIN: ../../../flutter/display_list/benchmarking/dl_region_benchmarks.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/display_list.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/display_list.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/display_list/display_list_builder.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/display_list/display_list_builder.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_attributes.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_blend_mode.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_blend_mode.h + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/display_list/dl_builder.cc + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/display_list/dl_builder.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_canvas.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_canvas.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/display_list/dl_canvas_to_receiver.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/display_list/dl_canvas_to_receiver.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_color.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_op_flags.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_op_flags.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_op_receiver.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_op_receiver.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/display_list/dl_op_recorder.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/display_list/dl_op_recorder.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_op_records.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_op_records.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/display_list/dl_paint.cc + ../../../flutter/LICENSE @@ -1873,12 +1869,10 @@ ORIGIN: ../../../flutter/lib/ui/text/asset_manager_font_provider.cc + ../../../f ORIGIN: ../../../flutter/lib/ui/text/asset_manager_font_provider.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/text/font_collection.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/text/font_collection.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/lib/ui/text/line_metrics.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/text/paragraph.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/text/paragraph.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/text/paragraph_builder.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/text/paragraph_builder.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/lib/ui/text/text_box.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/ui.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/ui_benchmarks.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/ui/ui_dart_state.cc + ../../../flutter/LICENSE @@ -2146,6 +2140,7 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/ui.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/asset_manager.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/benchmarks.dart + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/images.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/initialization.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/navigation/platform_location.dart + ../../../flutter/LICENSE ORIGIN: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart + ../../../flutter/LICENSE @@ -3444,22 +3439,18 @@ FILE: ../../../flutter/display_list/benchmarking/dl_complexity_metal.h FILE: ../../../flutter/display_list/benchmarking/dl_region_benchmarks.cc FILE: ../../../flutter/display_list/display_list.cc FILE: ../../../flutter/display_list/display_list.h -FILE: ../../../flutter/display_list/display_list_builder.cc -FILE: ../../../flutter/display_list/display_list_builder.h FILE: ../../../flutter/display_list/dl_attributes.h FILE: ../../../flutter/display_list/dl_blend_mode.cc FILE: ../../../flutter/display_list/dl_blend_mode.h +FILE: ../../../flutter/display_list/dl_builder.cc +FILE: ../../../flutter/display_list/dl_builder.h FILE: ../../../flutter/display_list/dl_canvas.cc FILE: ../../../flutter/display_list/dl_canvas.h -FILE: ../../../flutter/display_list/dl_canvas_to_receiver.cc -FILE: ../../../flutter/display_list/dl_canvas_to_receiver.h FILE: ../../../flutter/display_list/dl_color.h FILE: ../../../flutter/display_list/dl_op_flags.cc FILE: ../../../flutter/display_list/dl_op_flags.h FILE: ../../../flutter/display_list/dl_op_receiver.cc FILE: ../../../flutter/display_list/dl_op_receiver.h -FILE: ../../../flutter/display_list/dl_op_recorder.cc -FILE: ../../../flutter/display_list/dl_op_recorder.h FILE: ../../../flutter/display_list/dl_op_records.cc FILE: ../../../flutter/display_list/dl_op_records.h FILE: ../../../flutter/display_list/dl_paint.cc @@ -4605,12 +4596,10 @@ FILE: ../../../flutter/lib/ui/text/asset_manager_font_provider.cc FILE: ../../../flutter/lib/ui/text/asset_manager_font_provider.h FILE: ../../../flutter/lib/ui/text/font_collection.cc FILE: ../../../flutter/lib/ui/text/font_collection.h -FILE: ../../../flutter/lib/ui/text/line_metrics.h FILE: ../../../flutter/lib/ui/text/paragraph.cc FILE: ../../../flutter/lib/ui/text/paragraph.h FILE: ../../../flutter/lib/ui/text/paragraph_builder.cc FILE: ../../../flutter/lib/ui/text/paragraph_builder.h -FILE: ../../../flutter/lib/ui/text/text_box.h FILE: ../../../flutter/lib/ui/ui.dart FILE: ../../../flutter/lib/ui/ui_benchmarks.cc FILE: ../../../flutter/lib/ui/ui_dart_state.cc @@ -4878,6 +4867,7 @@ FILE: ../../../flutter/lib/web_ui/lib/ui.dart FILE: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web.dart FILE: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/asset_manager.dart FILE: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/benchmarks.dart +FILE: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/images.dart FILE: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/initialization.dart FILE: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/navigation/platform_location.dart FILE: ../../../flutter/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart diff --git a/ci/licenses_golden/licenses_fuchsia b/ci/licenses_golden/licenses_fuchsia index 3a2074a368f2a..024cdc3d13a0a 100644 --- a/ci/licenses_golden/licenses_fuchsia +++ b/ci/licenses_golden/licenses_fuchsia @@ -1,4 +1,4 @@ -Signature: 062292fe63e1bbf97f5b3720800ba338 +Signature: f5a79e03f71c637e3403cd42714e48b0 ==================================================================================================== LIBRARY: fuchsia_sdk diff --git a/ci/licenses_golden/licenses_skia b/ci/licenses_golden/licenses_skia index 2984358239233..5bf7dc683f320 100644 --- a/ci/licenses_golden/licenses_skia +++ b/ci/licenses_golden/licenses_skia @@ -1,4 +1,4 @@ -Signature: 9370fb648fbb83b4dc91810dcd8eafdf +Signature: 5dad8cab4c7769274c06df254b1bf3cf ==================================================================================================== LIBRARY: etc1 @@ -8900,8 +8900,10 @@ ORIGIN: ../../../third_party/skia/include/private/chromium/SkImageChromium.h + . ORIGIN: ../../../third_party/skia/include/private/gpu/ganesh/GrTextureGenerator.h + ../../../third_party/skia/LICENSE ORIGIN: ../../../third_party/skia/modules/bentleyottmann/include/EventQueue.h + ../../../third_party/skia/LICENSE ORIGIN: ../../../third_party/skia/modules/bentleyottmann/include/Point.h + ../../../third_party/skia/LICENSE +ORIGIN: ../../../third_party/skia/modules/bentleyottmann/include/Segment.h + ../../../third_party/skia/LICENSE ORIGIN: ../../../third_party/skia/modules/bentleyottmann/src/EventQueue.cpp + ../../../third_party/skia/LICENSE ORIGIN: ../../../third_party/skia/modules/bentleyottmann/src/Point.cpp + ../../../third_party/skia/LICENSE +ORIGIN: ../../../third_party/skia/modules/bentleyottmann/src/Segment.cpp + ../../../third_party/skia/LICENSE ORIGIN: ../../../third_party/skia/src/base/SkBezierCurves.h + ../../../third_party/skia/LICENSE ORIGIN: ../../../third_party/skia/src/base/SkCubics.cpp + ../../../third_party/skia/LICENSE ORIGIN: ../../../third_party/skia/src/base/SkCubics.h + ../../../third_party/skia/LICENSE @@ -9138,8 +9140,10 @@ FILE: ../../../third_party/skia/include/private/chromium/SkImageChromium.h FILE: ../../../third_party/skia/include/private/gpu/ganesh/GrTextureGenerator.h FILE: ../../../third_party/skia/modules/bentleyottmann/include/EventQueue.h FILE: ../../../third_party/skia/modules/bentleyottmann/include/Point.h +FILE: ../../../third_party/skia/modules/bentleyottmann/include/Segment.h FILE: ../../../third_party/skia/modules/bentleyottmann/src/EventQueue.cpp FILE: ../../../third_party/skia/modules/bentleyottmann/src/Point.cpp +FILE: ../../../third_party/skia/modules/bentleyottmann/src/Segment.cpp FILE: ../../../third_party/skia/src/base/SkBezierCurves.h FILE: ../../../third_party/skia/src/base/SkCubics.cpp FILE: ../../../third_party/skia/src/base/SkCubics.h diff --git a/display_list/BUILD.gn b/display_list/BUILD.gn index b115f3d24d963..97c9683511b61 100644 --- a/display_list/BUILD.gn +++ b/display_list/BUILD.gn @@ -25,22 +25,18 @@ source_set("display_list") { "benchmarking/dl_complexity_metal.h", "display_list.cc", "display_list.h", - "display_list_builder.cc", - "display_list_builder.h", "dl_attributes.h", "dl_blend_mode.cc", "dl_blend_mode.h", + "dl_builder.cc", + "dl_builder.h", "dl_canvas.cc", "dl_canvas.h", - "dl_canvas_to_receiver.cc", - "dl_canvas_to_receiver.h", "dl_color.h", "dl_op_flags.cc", "dl_op_flags.h", "dl_op_receiver.cc", "dl_op_receiver.h", - "dl_op_recorder.cc", - "dl_op_recorder.h", "dl_op_records.cc", "dl_op_records.h", "dl_paint.cc", diff --git a/display_list/benchmarking/dl_benchmarks.cc b/display_list/benchmarking/dl_benchmarks.cc index 07458b5a96474..b2dcf78a2c3bc 100644 --- a/display_list/benchmarking/dl_benchmarks.cc +++ b/display_list/benchmarking/dl_benchmarks.cc @@ -3,7 +3,7 @@ // found in the LICENSE file. #include "flutter/display_list/benchmarking/dl_benchmarks.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_op_flags.h" #include "flutter/display_list/skia/dl_sk_canvas.h" diff --git a/display_list/benchmarking/dl_complexity_gl.cc b/display_list/benchmarking/dl_complexity_gl.cc index c3738d0dc5cd5..f8dd1c52a1260 100644 --- a/display_list/benchmarking/dl_complexity_gl.cc +++ b/display_list/benchmarking/dl_complexity_gl.cc @@ -503,7 +503,7 @@ void DisplayListGLComplexityCalculator::GLHelper::drawVertices( } void DisplayListGLComplexityCalculator::GLHelper::drawImage( - const sk_sp& image, + const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { @@ -583,7 +583,7 @@ void DisplayListGLComplexityCalculator::GLHelper::ImageRect( } void DisplayListGLComplexityCalculator::GLHelper::drawImageNine( - const sk_sp& image, + const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, @@ -608,7 +608,7 @@ void DisplayListGLComplexityCalculator::GLHelper::drawImageNine( } void DisplayListGLComplexityCalculator::GLHelper::drawDisplayList( - const sk_sp& display_list, + const sk_sp display_list, SkScalar opacity) { if (IsComplex()) { return; @@ -622,7 +622,7 @@ void DisplayListGLComplexityCalculator::GLHelper::drawDisplayList( } void DisplayListGLComplexityCalculator::GLHelper::drawTextBlob( - const sk_sp& blob, + const sk_sp blob, SkScalar x, SkScalar y) { if (IsComplex()) { diff --git a/display_list/benchmarking/dl_complexity_gl.h b/display_list/benchmarking/dl_complexity_gl.h index f08357c0d79a7..9fc7596687051 100644 --- a/display_list/benchmarking/dl_complexity_gl.h +++ b/display_list/benchmarking/dl_complexity_gl.h @@ -56,18 +56,18 @@ class DisplayListGLComplexityCalculator uint32_t count, const SkPoint points[]) override; void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; - void drawImage(const sk_sp& image, + void drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override; - void drawImageNine(const sk_sp& image, + void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override; - void drawDisplayList(const sk_sp& display_list, + void drawDisplayList(const sk_sp display_list, SkScalar opacity) override; - void drawTextBlob(const sk_sp& blob, + void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) override; void drawShadow(const SkPath& path, diff --git a/display_list/benchmarking/dl_complexity_helper.h b/display_list/benchmarking/dl_complexity_helper.h index 464b4675caeeb..759d6e64460ed 100644 --- a/display_list/benchmarking/dl_complexity_helper.h +++ b/display_list/benchmarking/dl_complexity_helper.h @@ -146,7 +146,7 @@ class ComplexityCalculatorHelper } void drawImageRect( - const sk_sp& image, + const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, @@ -159,7 +159,7 @@ class ComplexityCalculatorHelper render_with_attributes, constraint == SrcRectConstraint::kStrict); } - void drawAtlas(const sk_sp& atlas, + void drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], diff --git a/display_list/benchmarking/dl_complexity_metal.cc b/display_list/benchmarking/dl_complexity_metal.cc index dcf6e9fcdf870..56d4f3b406ad9 100644 --- a/display_list/benchmarking/dl_complexity_metal.cc +++ b/display_list/benchmarking/dl_complexity_metal.cc @@ -455,7 +455,7 @@ void DisplayListMetalComplexityCalculator::MetalHelper::drawVertices( } void DisplayListMetalComplexityCalculator::MetalHelper::drawImage( - const sk_sp& image, + const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { @@ -532,7 +532,7 @@ void DisplayListMetalComplexityCalculator::MetalHelper::ImageRect( } void DisplayListMetalComplexityCalculator::MetalHelper::drawImageNine( - const sk_sp& image, + const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, @@ -552,7 +552,7 @@ void DisplayListMetalComplexityCalculator::MetalHelper::drawImageNine( } void DisplayListMetalComplexityCalculator::MetalHelper::drawDisplayList( - const sk_sp& display_list, + const sk_sp display_list, SkScalar opacity) { if (IsComplex()) { return; @@ -566,7 +566,7 @@ void DisplayListMetalComplexityCalculator::MetalHelper::drawDisplayList( } void DisplayListMetalComplexityCalculator::MetalHelper::drawTextBlob( - const sk_sp& blob, + const sk_sp blob, SkScalar x, SkScalar y) { if (IsComplex()) { diff --git a/display_list/benchmarking/dl_complexity_metal.h b/display_list/benchmarking/dl_complexity_metal.h index 16d58aa2b4bff..aa63863fa4d05 100644 --- a/display_list/benchmarking/dl_complexity_metal.h +++ b/display_list/benchmarking/dl_complexity_metal.h @@ -56,18 +56,18 @@ class DisplayListMetalComplexityCalculator uint32_t count, const SkPoint points[]) override; void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; - void drawImage(const sk_sp& image, + void drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override; - void drawImageNine(const sk_sp& image, + void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override; - void drawDisplayList(const sk_sp& display_list, + void drawDisplayList(const sk_sp display_list, SkScalar opacity) override; - void drawTextBlob(const sk_sp& blob, + void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) override; void drawShadow(const SkPath& path, diff --git a/display_list/benchmarking/dl_complexity_unittests.cc b/display_list/benchmarking/dl_complexity_unittests.cc index d349d1ce5afe6..eee77ac9bdf55 100644 --- a/display_list/benchmarking/dl_complexity_unittests.cc +++ b/display_list/benchmarking/dl_complexity_unittests.cc @@ -6,7 +6,7 @@ #include "flutter/display_list/benchmarking/dl_complexity_gl.h" #include "flutter/display_list/benchmarking/dl_complexity_metal.h" #include "flutter/display_list/display_list.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_sampling_options.h" #include "flutter/display_list/testing/dl_test_snippets.h" #include "flutter/testing/testing.h" @@ -102,7 +102,7 @@ TEST(DisplayListComplexity, StrokeWidth) { auto display_list_stroke_0 = builder_stroke_0.Build(); DisplayListBuilder builder_stroke_1; - builder_stroke_1.DrawLine(SkPoint::Make(0, 0), SkPoint::Make(100, 100), + builder_stroke_0.DrawLine(SkPoint::Make(0, 0), SkPoint::Make(100, 100), DlPaint().setStrokeWidth(1.0f)); auto display_list_stroke_1 = builder_stroke_1.Build(); diff --git a/display_list/display_list.cc b/display_list/display_list.cc index 9879a1a41dde4..e06bcf246d3d4 100644 --- a/display_list/display_list.cc +++ b/display_list/display_list.cc @@ -15,7 +15,7 @@ const SaveLayerOptions SaveLayerOptions::kWithAttributes = kNoAttributes.with_renders_with_attributes(); DisplayList::DisplayList() - : storage_(), + : byte_count_(0), op_count_(0), nested_byte_count_(0), nested_op_count_(0), @@ -25,7 +25,8 @@ DisplayList::DisplayList() is_ui_thread_safe_(true), modifies_transparent_black_(false) {} -DisplayList::DisplayList(DlStorage&& storage, +DisplayList::DisplayList(DisplayListStorage&& storage, + size_t byte_count, unsigned int op_count, size_t nested_byte_count, unsigned int nested_op_count, @@ -35,6 +36,7 @@ DisplayList::DisplayList(DlStorage&& storage, bool modifies_transparent_black, sk_sp rtree) : storage_(std::move(storage)), + byte_count_(byte_count), op_count_(op_count), nested_byte_count_(nested_byte_count), nested_op_count_(nested_op_count), @@ -45,65 +47,9 @@ DisplayList::DisplayList(DlStorage&& storage, modifies_transparent_black_(modifies_transparent_black), rtree_(std::move(rtree)) {} -DisplayList::DlStorage::DlStorage(DisplayList::DlStorage&& source) - : ptr_(std::move(source.ptr_)), - used_(source.used_), - allocated_(source.allocated_) { - FML_DCHECK(source.ptr_.get() == nullptr); - FML_DCHECK(!source.disabled_); - source.ptr_ = nullptr; - source.used_ = 0u; - source.allocated_ = 0u; - source.disabled_ = true; -} - -DisplayList::DlStorage::~DlStorage() { - uint8_t* ptr = get(); - if (ptr != nullptr) { - FML_DCHECK(used_ <= allocated_); - DisposeOps(ptr, ptr + used_); - } else { - FML_DCHECK(used_ == 0u); - FML_DCHECK(allocated_ == 0u); - } -} - -static constexpr inline bool is_power_of_two(int value) { - return (value & (value - 1)) == 0; -} - -uint8_t* DisplayList::DlStorage::alloc(size_t bytes) { - if (disabled_) { - FML_DCHECK(is_valid()); - return nullptr; - } - FML_DCHECK(bytes < (1 << 24)); - if (used_ + bytes > allocated_) { - static_assert(is_power_of_two(kPageSize), - "This math needs updating for non-pow2."); - // Next greater multiple of DL_BUILDER_PAGE. - allocated_ = (used_ + bytes + kPageSize) & ~(kPageSize - 1); - realloc(allocated_); - FML_DCHECK(get()); - memset(get() + used_, 0, allocated_ - used_); - } - FML_DCHECK(used_ + bytes <= allocated_); - uint8_t* ret = get() + used_; - used_ += bytes; - return ret; -} - -void DisplayList::DlStorage::realloc(size_t count) { - FML_DCHECK(is_valid()); - FML_DCHECK(count >= used_); - ptr_.reset(static_cast(std::realloc(ptr_.release(), count))); - allocated_ = count; - FML_CHECK(ptr_); -} - -DisplayList::DlStorage DisplayList::DlStorage::take() { - realloc(used_); - return std::move(*this); +DisplayList::~DisplayList() { + uint8_t* ptr = storage_.get(); + DisposeOps(ptr, ptr + byte_count_); } uint32_t DisplayList::next_unique_id() { @@ -166,10 +112,10 @@ class VectorCuller final : public Culler { } } void update(DispatchContext& context) override { - if (context.cur_render_index > context.next_render_index) { + if (++context.cur_index > context.next_render_index) { while (cur_ < end_) { context.next_render_index = rtree_->id(*cur_++); - if (context.next_render_index >= context.cur_render_index) { + if (context.next_render_index >= context.cur_index) { // It should be rare that we have duplicate indices // but if we do, then having a while loop is a cheap // insurance for those cases. @@ -193,7 +139,8 @@ class VectorCuller final : public Culler { }; void DisplayList::Dispatch(DlOpReceiver& receiver) const { - Dispatch(receiver, storage_.get(), storage_.end(), NopCuller::instance); + uint8_t* ptr = storage_.get(); + Dispatch(receiver, ptr, ptr + byte_count_, NopCuller::instance); } void DisplayList::Dispatch(DlOpReceiver& receiver, @@ -217,10 +164,11 @@ void DisplayList::Dispatch(DlOpReceiver& receiver, Dispatch(receiver); return; } + uint8_t* ptr = storage_.get(); std::vector rect_indices; rtree->search(cull_rect, &rect_indices); VectorCuller culler(rtree, rect_indices); - Dispatch(receiver, storage_.get(), storage_.end(), culler); + Dispatch(receiver, ptr, ptr + byte_count_, culler); } void DisplayList::Dispatch(DlOpReceiver& receiver, @@ -229,7 +177,7 @@ void DisplayList::Dispatch(DlOpReceiver& receiver, Culler& culler) const { DispatchContext context = { .receiver = receiver, - .cur_render_index = 0, + .cur_index = 0, // next_render_index will be initialized by culler.init() .next_restore_index = std::numeric_limits::max(), }; @@ -261,7 +209,7 @@ void DisplayList::Dispatch(DlOpReceiver& receiver, } } -void DisplayList::DlStorage::DisposeOps(uint8_t* ptr, uint8_t* end) { +void DisplayList::DisposeOps(uint8_t* ptr, uint8_t* end) { while (ptr < end) { auto op = reinterpret_cast(ptr); ptr += op->size; @@ -361,8 +309,7 @@ bool DisplayList::Equals(const DisplayList* other) const { if (this == other) { return true; } - if (storage_.used() != other->storage_.used() || - op_count_ != other->op_count_) { + if (byte_count_ != other->byte_count_ || op_count_ != other->op_count_) { return false; } uint8_t* ptr = storage_.get(); @@ -370,7 +317,7 @@ bool DisplayList::Equals(const DisplayList* other) const { if (ptr == o_ptr) { return true; } - return CompareOps(ptr, storage_.end(), o_ptr, other->storage_.end()); + return CompareOps(ptr, ptr + byte_count_, o_ptr, o_ptr + other->byte_count_); } } // namespace flutter diff --git a/display_list/display_list.h b/display_list/display_list.h index 3655e539ec82e..668a247d5596f 100644 --- a/display_list/display_list.h +++ b/display_list/display_list.h @@ -150,6 +150,7 @@ enum class DisplayListOpType { #undef DL_OP_TO_ENUM_VALUE class DlOpReceiver; +class DisplayListBuilder; class SaveLayerOptions { public: @@ -201,6 +202,26 @@ class SaveLayerOptions { }; }; +// Manages a buffer allocated with malloc. +class DisplayListStorage { + public: + DisplayListStorage() = default; + DisplayListStorage(DisplayListStorage&&) = default; + + uint8_t* get() const { return ptr_.get(); } + + void realloc(size_t count) { + ptr_.reset(static_cast(std::realloc(ptr_.release(), count))); + FML_CHECK(ptr_); + } + + private: + struct FreeDeleter { + void operator()(uint8_t* p) { std::free(p); } + }; + std::unique_ptr ptr_; +}; + class Culler; // The base class that contains a sequence of rendering operations @@ -210,7 +231,7 @@ class DisplayList : public SkRefCnt { public: DisplayList(); - ~DisplayList() = default; + ~DisplayList(); void Dispatch(DlOpReceiver& ctx) const; void Dispatch(DlOpReceiver& ctx, const SkRect& cull_rect) const; @@ -220,8 +241,7 @@ class DisplayList : public SkRefCnt { // but nested ops are only included if requested. The defaults used // here for these accessors follow that pattern. size_t bytes(bool nested = true) const { - FML_DCHECK(storage_.used() == storage_.allocated()); - return sizeof(DisplayList) + storage_.allocated() + + return sizeof(DisplayList) + byte_count_ + (nested ? nested_byte_count_ : 0); } @@ -259,40 +279,8 @@ class DisplayList : public SkRefCnt { } private: - // Manages a buffer allocated with malloc. - class DlStorage { - public: - DlStorage() = default; - DlStorage(DlStorage&& source); - - ~DlStorage(); - - uint8_t* get() const { return ptr_.get(); } - uint8_t* end() const { return ptr_.get() + used_; } - size_t used() const { return used_; } - size_t allocated() const { return allocated_; } - bool is_valid() const { return !disabled_; } - - uint8_t* alloc(size_t bytes); - void realloc(size_t count); - DlStorage take(); - - private: - static constexpr size_t kPageSize = 4096u; - - static void DisposeOps(uint8_t* ptr, uint8_t* end); - - struct FreeDeleter { - void operator()(uint8_t* p) { std::free(p); } - }; - std::unique_ptr ptr_; - - bool disabled_ = false; - size_t used_ = 0u; - size_t allocated_ = 0u; - }; - - DisplayList(DlStorage&& ptr, + DisplayList(DisplayListStorage&& ptr, + size_t byte_count, unsigned int op_count, size_t nested_byte_count, unsigned int nested_op_count, @@ -304,7 +292,10 @@ class DisplayList : public SkRefCnt { static uint32_t next_unique_id(); - const DlStorage storage_; + static void DisposeOps(uint8_t* ptr, uint8_t* end); + + const DisplayListStorage storage_; + const size_t byte_count_; const unsigned int op_count_; const size_t nested_byte_count_; @@ -324,7 +315,6 @@ class DisplayList : public SkRefCnt { uint8_t* end, Culler& culler) const; - friend class DlOpRecorder; friend class DisplayListBuilder; }; diff --git a/display_list/display_list_builder.cc b/display_list/display_list_builder.cc deleted file mode 100644 index 871f5ee016863..0000000000000 --- a/display_list/display_list_builder.cc +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "flutter/display_list/display_list_builder.h" - -namespace flutter { - -DisplayListBuilder::DisplayListBuilder(const SkRect& cull_rect, - bool prepare_rtree) - : DisplayListBuilder( - std::make_shared(cull_rect, prepare_rtree)) {} - -DisplayListBuilder::DisplayListBuilder( - const std::shared_ptr& recorder) - : DlCanvasToReceiver(recorder), recorder_(recorder) {} - -sk_sp DisplayListBuilder::Build() { - FML_CHECK(recorder_ != nullptr); - FML_CHECK(receiver_ != nullptr); - - RestoreToCount(1); - - sk_sp dl = - recorder_->Build(current_group_opacity_compatibility(), - current_affects_transparent_layer()); - - recorder_ = nullptr; - receiver_ = nullptr; - - return dl; -} - -} // namespace flutter diff --git a/display_list/display_list_builder.h b/display_list/display_list_builder.h deleted file mode 100644 index 3fb50efb9b279..0000000000000 --- a/display_list/display_list_builder.h +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FLUTTER_DISPLAY_LIST_DISPLAY_LIST_BUILDER_H_ -#define FLUTTER_DISPLAY_LIST_DISPLAY_LIST_BUILDER_H_ - -#include "flutter/display_list/dl_canvas.h" -#include "flutter/display_list/dl_canvas_to_receiver.h" -#include "flutter/display_list/dl_op_flags.h" -#include "flutter/display_list/dl_op_receiver.h" -#include "flutter/display_list/dl_op_recorder.h" -#include "flutter/display_list/utils/dl_bounds_accumulator.h" -#include "flutter/display_list/utils/dl_matrix_clip_tracker.h" -#include "flutter/fml/macros.h" - -namespace flutter { - -// The primary class used to build a display list. The list of methods -// here matches the list of methods invoked on a |DlOpReceiver| combined -// with the list of methods invoked on a |DlCanvas|. -class DisplayListBuilder final : public DlCanvasToReceiver, // - public SkRefCnt { - public: - static constexpr SkRect kMaxCullRect = - SkRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F); - - explicit DisplayListBuilder(bool prepare_rtree) - : DisplayListBuilder(kMaxCullRect, prepare_rtree) {} - - explicit DisplayListBuilder(const SkRect& cull_rect = kMaxCullRect, - bool prepare_rtree = false); - - ~DisplayListBuilder() = default; - - sk_sp Build(); - - private: - explicit DisplayListBuilder(const std::shared_ptr& recorder); - - std::shared_ptr recorder_; - - // This method exposes the internal stateful DlOpReceiver implementation - // of the DisplayListBuilder, primarily for testing purposes. Its use - // is obsolete and forbidden in every other case and is only shared to a - // pair of "friend" accessors in the benchmark/unittest files. - DlOpReceiver& asReceiver() { return *receiver_; } - - friend DlOpReceiver& DisplayListBuilderBenchmarkAccessor( - DisplayListBuilder& builder); - friend DlOpReceiver& DisplayListBuilderTestingAccessor( - DisplayListBuilder& builder); - friend DlPaint DisplayListBuilderTestingAttributes( - DisplayListBuilder& builder); -}; - -} // namespace flutter - -#endif // FLUTTER_DISPLAY_LIST_DISPLAY_LIST_BUILDER_H_ diff --git a/display_list/display_list_unittests.cc b/display_list/display_list_unittests.cc index 8d2665a51802f..bef888bcf8633 100644 --- a/display_list/display_list_unittests.cc +++ b/display_list/display_list_unittests.cc @@ -9,8 +9,8 @@ #include #include "flutter/display_list/display_list.h" -#include "flutter/display_list/display_list_builder.h" #include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_paint.h" #include "flutter/display_list/geometry/dl_rtree.h" #include "flutter/display_list/skia/dl_sk_dispatcher.h" @@ -141,9 +141,6 @@ class DisplayListTestBase : public BaseT { setup(builder); renderer(builder, paint, render_rect); auto dl = builder.Build(); - FML_LOG(ERROR) << "dl: " << *dl; - FML_LOG(ERROR) << "ops: " << dl->op_count(); - FML_LOG(ERROR) << "bytes: " << dl->bytes(); EXPECT_EQ(dl->op_count(), 1u) << desc; EXPECT_EQ(dl->bounds(), expected_bounds) << desc; } @@ -236,21 +233,23 @@ TEST_F(DisplayListTest, EmptyBuild) { EXPECT_EQ(dl->bytes(), sizeof(DisplayList)); } -#ifndef NDEBUG -TEST_F(DisplayListTest, SecondBuildDies) { +TEST_F(DisplayListTest, EmptyRebuild) { DisplayListBuilder builder; auto dl1 = builder.Build(); - EXPECT_DEATH_IF_SUPPORTED(builder.Build(), "recorder_ != nullptr"); + auto dl2 = builder.Build(); + auto dl3 = builder.Build(); + ASSERT_TRUE(dl1->Equals(dl2)); + ASSERT_TRUE(dl2->Equals(dl3)); } -TEST_F(DisplayListTest, BuilderCannotBeReused) { +TEST_F(DisplayListTest, BuilderCanBeReused) { DisplayListBuilder builder(kTestBounds); builder.DrawRect(kTestBounds, DlPaint()); auto dl = builder.Build(); - EXPECT_DEATH_IF_SUPPORTED(builder.DrawRect(kTestBounds, DlPaint()), - "receiver_ != nullptr"); + builder.DrawRect(kTestBounds, DlPaint()); + auto dl2 = builder.Build(); + ASSERT_TRUE(dl->Equals(dl2)); } -#endif TEST_F(DisplayListTest, SaveRestoreRestoresTransform) { SkRect cull_rect = SkRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); @@ -301,6 +300,47 @@ TEST_F(DisplayListTest, SaveRestoreRestoresTransform) { check_defaults(builder, cull_rect); } +TEST_F(DisplayListTest, BuildRestoresTransform) { + SkRect cull_rect = SkRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); + DisplayListBuilder builder(cull_rect); + + builder.Translate(10.0f, 10.0f); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.Scale(10.0f, 10.0f); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.Skew(0.1f, 0.1f); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.Rotate(45.0f); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.Transform(SkMatrix::Scale(10.0f, 10.0f)); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.Transform2DAffine(1.0f, 0.0f, 12.0f, // + 0.0f, 1.0f, 35.0f); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.Transform(SkM44(SkMatrix::Scale(10.0f, 10.0f))); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.TransformFullPerspective(1.0f, 0.0f, 0.0f, 12.0f, // + 0.0f, 1.0f, 0.0f, 35.0f, // + 0.0f, 0.0f, 1.0f, 5.0f, // + 0.0f, 0.0f, 0.0f, 1.0f); + builder.Build(); + check_defaults(builder, cull_rect); +} + TEST_F(DisplayListTest, SaveRestoreRestoresClip) { SkRect cull_rect = SkRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); DisplayListBuilder builder(cull_rect); @@ -321,6 +361,89 @@ TEST_F(DisplayListTest, SaveRestoreRestoresClip) { check_defaults(builder, cull_rect); } +TEST_F(DisplayListTest, BuildRestoresClip) { + SkRect cull_rect = SkRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); + DisplayListBuilder builder(cull_rect); + + builder.ClipRect({0.0f, 0.0f, 10.0f, 10.0f}); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.ClipRRect(SkRRect::MakeRectXY({0.0f, 0.0f, 5.0f, 5.0f}, 2.0f, 2.0f)); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.ClipPath(SkPath().addOval({0.0f, 0.0f, 10.0f, 10.0f})); + builder.Build(); + check_defaults(builder, cull_rect); +} + +TEST_F(DisplayListTest, BuildRestoresAttributes) { + SkRect cull_rect = SkRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); + DisplayListBuilder builder(cull_rect); + DlOpReceiver& receiver = ToReceiver(builder); + + receiver.setAntiAlias(true); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setDither(true); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setInvertColors(true); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setColor(DlColor::kRed()); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setBlendMode(DlBlendMode::kColorBurn); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setDrawStyle(DlDrawStyle::kStrokeAndFill); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setStrokeWidth(300.0f); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setStrokeMiter(300.0f); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setStrokeCap(DlStrokeCap::kRound); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setStrokeJoin(DlStrokeJoin::kRound); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setColorSource(&kTestSource1); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setColorFilter(&kTestMatrixColorFilter1); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setImageFilter(&kTestBlurImageFilter1); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setMaskFilter(&kTestMaskFilter1); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setPathEffect(kTestPathEffect1.get()); + builder.Build(); + check_defaults(builder, cull_rect); +} + TEST_F(DisplayListTest, BuilderBoundsTransformComparedToSkia) { const SkRect frame_rect = SkRect::MakeLTRB(10, 10, 100, 100); DisplayListBuilder builder(frame_rect); @@ -452,8 +575,8 @@ TEST_F(DisplayListTest, SingleOpSizes) { auto& invocation = group.variants[i]; sk_sp dl = Build(invocation); auto desc = group.op_name + "(variant " + std::to_string(i + 1) + ")"; - EXPECT_EQ(dl->op_count(false), invocation.op_count()) << desc; - EXPECT_EQ(dl->bytes(false), invocation.byte_count()) << desc; + ASSERT_EQ(dl->op_count(false), invocation.op_count()) << desc; + ASSERT_EQ(dl->bytes(false), invocation.byte_count()) << desc; } } } @@ -561,11 +684,23 @@ TEST_F(DisplayListTest, SingleOpDisplayListsAreEqualWithOrWithoutRtree) { TEST_F(DisplayListTest, FullRotationsAreNop) { DisplayListBuilder builder; - builder.Rotate(0); - builder.Rotate(360); - builder.Rotate(720); - builder.Rotate(1080); - builder.Rotate(1440); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.rotate(0); + receiver.rotate(360); + receiver.rotate(720); + receiver.rotate(1080); + receiver.rotate(1440); + sk_sp dl = builder.Build(); + ASSERT_EQ(dl->bytes(false), sizeof(DisplayList)); + ASSERT_EQ(dl->bytes(true), sizeof(DisplayList)); + ASSERT_EQ(dl->op_count(false), 0u); + ASSERT_EQ(dl->op_count(true), 0u); +} + +TEST_F(DisplayListTest, AllBlendModeNops) { + DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setBlendMode(DlBlendMode::kSrcOver); sk_sp dl = builder.Build(); ASSERT_EQ(dl->bytes(false), sizeof(DisplayList)); ASSERT_EQ(dl->bytes(true), sizeof(DisplayList)); @@ -634,10 +769,10 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { { // No tricky stuff, just verifying drawing a rect produces rect bounds DisplayListBuilder builder(build_bounds); - DlPaint save_paint; - builder.SaveLayer(&save_bounds, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.saveLayer(&save_bounds, SaveLayerOptions::kWithAttributes); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), rect); } @@ -645,11 +780,12 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { { // Now checking that a normal color filter still produces rect bounds DisplayListBuilder builder(build_bounds); - DlPaint save_paint; - save_paint.setColorFilter(&base_color_filter); - builder.SaveLayer(&save_bounds, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColorFilter(&base_color_filter); + receiver.saveLayer(&save_bounds, SaveLayerOptions::kWithAttributes); + receiver.setColorFilter(nullptr); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), rect); } @@ -677,11 +813,12 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { // cull rect of the DisplayListBuilder when it encounters a // save layer that modifies an unbounded region DisplayListBuilder builder(build_bounds); - DlPaint save_paint; - save_paint.setColorFilter(&alpha_color_filter); - builder.SaveLayer(&save_bounds, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColorFilter(&alpha_color_filter); + receiver.saveLayer(&save_bounds, SaveLayerOptions::kWithAttributes); + receiver.setColorFilter(nullptr); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), build_bounds); } @@ -690,11 +827,12 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { // Verifying that the save layer bounds are not relevant // to the behavior in the previous example DisplayListBuilder builder(build_bounds); - DlPaint save_paint; - save_paint.setColorFilter(&alpha_color_filter); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColorFilter(&alpha_color_filter); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setColorFilter(nullptr); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), build_bounds); } @@ -703,12 +841,13 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { // Making sure hiding a ColorFilter as an ImageFilter will // generate the same behavior as setting it as a ColorFilter DisplayListBuilder builder(build_bounds); - DlPaint save_paint; + DlOpReceiver& receiver = ToReceiver(builder); DlColorFilterImageFilter color_filter_image_filter(base_color_filter); - save_paint.setImageFilter(&color_filter_image_filter); - builder.SaveLayer(&save_bounds, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + receiver.setImageFilter(&color_filter_image_filter); + receiver.saveLayer(&save_bounds, SaveLayerOptions::kWithAttributes); + receiver.setImageFilter(nullptr); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), rect); } @@ -717,12 +856,13 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { // Making sure hiding a problematic ColorFilter as an ImageFilter // will generate the same behavior as setting it as a ColorFilter DisplayListBuilder builder(build_bounds); - DlPaint save_paint; + DlOpReceiver& receiver = ToReceiver(builder); DlColorFilterImageFilter color_filter_image_filter(alpha_color_filter); - save_paint.setImageFilter(&color_filter_image_filter); - builder.SaveLayer(&save_bounds, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + receiver.setImageFilter(&color_filter_image_filter); + receiver.saveLayer(&save_bounds, SaveLayerOptions::kWithAttributes); + receiver.setImageFilter(nullptr); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), build_bounds); } @@ -730,12 +870,13 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { { // Same as above (ImageFilter hiding ColorFilter) with no save bounds DisplayListBuilder builder(build_bounds); - DlPaint save_paint; + DlOpReceiver& receiver = ToReceiver(builder); DlColorFilterImageFilter color_filter_image_filter(alpha_color_filter); - save_paint.setImageFilter(&color_filter_image_filter); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + receiver.setImageFilter(&color_filter_image_filter); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setImageFilter(nullptr); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), build_bounds); } @@ -743,11 +884,12 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { { // Testing behavior with an unboundable blend mode DisplayListBuilder builder(build_bounds); - DlPaint save_paint; - save_paint.setBlendMode(DlBlendMode::kClear); - builder.SaveLayer(&save_bounds, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setBlendMode(DlBlendMode::kClear); + receiver.saveLayer(&save_bounds, SaveLayerOptions::kWithAttributes); + receiver.setBlendMode(DlBlendMode::kSrcOver); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), build_bounds); } @@ -755,11 +897,12 @@ TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { { // Same as previous with no save bounds DisplayListBuilder builder(build_bounds); - DlPaint save_paint; - save_paint.setBlendMode(DlBlendMode::kClear); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect(rect, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setBlendMode(DlBlendMode::kClear); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setBlendMode(DlBlendMode::kSrcOver); + receiver.drawRect(rect); + receiver.restore(); sk_sp display_list = builder.Build(); ASSERT_EQ(display_list->bounds(), build_bounds); } @@ -786,14 +929,16 @@ TEST_F(DisplayListTest, NestedOpCountMetricsSameAsSkPicture) { ASSERT_EQ(picture->approximateOpCount(true), 36); DisplayListBuilder builder(SkRect::MakeWH(150, 100)); + DlOpReceiver& receiver = ToReceiver(builder); for (int y = 10; y <= 60; y += 10) { for (int x = 10; x <= 60; x += 10) { - DlColor color = ((x + y) % 20) == 10 ? DlColor::kRed() : DlColor::kBlue(); - builder.DrawRect(SkRect::MakeXYWH(x, y, 80, 80), DlPaint(color)); + receiver.setColor(((x + y) % 20) == 10 ? SK_ColorRED : SK_ColorBLUE); + receiver.drawRect(SkRect::MakeXYWH(x, y, 80, 80)); } } DisplayListBuilder outer_builder(SkRect::MakeWH(150, 100)); - outer_builder.DrawDisplayList(builder.Build()); + DlOpReceiver& outer_receiver = ToReceiver(outer_builder); + outer_receiver.drawDisplayList(builder.Build()); auto display_list = outer_builder.Build(); ASSERT_EQ(display_list->op_count(), 1u); @@ -818,8 +963,9 @@ TEST_F(DisplayListTest, DisplayListFullPerspectiveTransformHandling) { { // First test == DisplayListBuilder builder; - // builder.transformFullPerspective takes row-major order - builder.TransformFullPerspective( + DlOpReceiver& receiver = ToReceiver(builder); + // receiver.transformFullPerspective takes row-major order + receiver.transformFullPerspective( // clang-format off 1, 2, 3, 4, 5, 6, 7, 8, @@ -840,8 +986,9 @@ TEST_F(DisplayListTest, DisplayListFullPerspectiveTransformHandling) { } { // Next test != DisplayListBuilder builder; - // builder.transformFullPerspective takes row-major order - builder.TransformFullPerspective( + DlOpReceiver& receiver = ToReceiver(builder); + // receiver.transformFullPerspective takes row-major order + receiver.transformFullPerspective( // clang-format off 1, 5, 9, 13, 2, 6, 7, 11, @@ -864,8 +1011,9 @@ TEST_F(DisplayListTest, DisplayListFullPerspectiveTransformHandling) { TEST_F(DisplayListTest, DisplayListTransformResetHandling) { DisplayListBuilder builder; - builder.Scale(20.0, 20.0); - builder.TransformReset(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.scale(20.0, 20.0); + receiver.transformReset(); auto display_list = builder.Build(); ASSERT_NE(display_list, nullptr); sk_sp surface = @@ -880,14 +1028,14 @@ TEST_F(DisplayListTest, DisplayListTransformResetHandling) { TEST_F(DisplayListTest, SingleOpsMightSupportGroupOpacityBlendMode) { auto run_tests = [](const std::string& name, - void build(DlCanvas & cv, const DlPaint& paint), - bool expect_for_op, bool expect_with_kSrc) { + void build(DlOpReceiver & receiver), bool expect_for_op, + bool expect_with_kSrc) { { // First test is the draw op, by itself // (usually supports group opacity) DisplayListBuilder builder; - DlPaint paint; - build(builder, paint); + DlOpReceiver& receiver = ToReceiver(builder); + build(receiver); auto display_list = builder.Build(); EXPECT_EQ(display_list->can_apply_group_opacity(), expect_for_op) << "{" << std::endl @@ -895,12 +1043,12 @@ TEST_F(DisplayListTest, SingleOpsMightSupportGroupOpacityBlendMode) { << "}"; } { - // Second test is the draw op with kSrc, + // Second test i the draw op with kSrc, // (usually fails group opacity) DisplayListBuilder builder; - DlPaint paint; - paint.setBlendMode(DlBlendMode::kSrc); - build(builder, paint); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setBlendMode(DlBlendMode::kSrc); + build(receiver); auto display_list = builder.Build(); EXPECT_EQ(display_list->can_apply_group_opacity(), expect_with_kSrc) << "{" << std::endl @@ -912,64 +1060,67 @@ TEST_F(DisplayListTest, SingleOpsMightSupportGroupOpacityBlendMode) { #define RUN_TESTS(body) \ run_tests( \ - #body, [](DlCanvas& cv, const DlPaint& paint) { body }, true, false) + #body, [](DlOpReceiver& receiver) { body }, true, false) #define RUN_TESTS2(body, expect) \ run_tests( \ - #body, [](DlCanvas& cv, const DlPaint& paint) { body }, expect, expect) - - RUN_TESTS(cv.DrawPaint(paint);); - RUN_TESTS(cv.DrawColor(SK_ColorRED, paint.getBlendMode());); - RUN_TESTS2(cv.DrawColor(SK_ColorRED, DlBlendMode::kSrcOver);, true); - RUN_TESTS2(cv.DrawColor(SK_ColorRED, DlBlendMode::kSrc);, false); - RUN_TESTS(cv.DrawLine({0, 0}, {10, 10}, paint);); - RUN_TESTS(cv.DrawRect({0, 0, 10, 10}, paint);); - RUN_TESTS(cv.DrawOval({0, 0, 10, 10}, paint);); - RUN_TESTS(cv.DrawCircle({10, 10}, 5, paint);); - RUN_TESTS(cv.DrawRRect(SkRRect::MakeRectXY({0, 0, 10, 10}, 2, 2), paint);); - RUN_TESTS(cv.DrawDRRect(SkRRect::MakeRectXY({0, 0, 10, 10}, 2, 2), - SkRRect::MakeRectXY({2, 2, 8, 8}, 2, 2), paint);); - RUN_TESTS(cv.DrawPath( - SkPath().addOval({0, 0, 10, 10}).addOval({5, 5, 15, 15}), paint);); - RUN_TESTS(cv.DrawArc({0, 0, 10, 10}, 0, math::kPi, true, paint);); + #body, [](DlOpReceiver& receiver) { body }, expect, expect) + + RUN_TESTS(receiver.drawPaint();); + RUN_TESTS2(receiver.drawColor(SK_ColorRED, DlBlendMode::kSrcOver);, true); + RUN_TESTS2(receiver.drawColor(SK_ColorRED, DlBlendMode::kSrc);, false); + RUN_TESTS(receiver.drawLine({0, 0}, {10, 10});); + RUN_TESTS(receiver.drawRect({0, 0, 10, 10});); + RUN_TESTS(receiver.drawOval({0, 0, 10, 10});); + RUN_TESTS(receiver.drawCircle({10, 10}, 5);); + RUN_TESTS(receiver.drawRRect(SkRRect::MakeRectXY({0, 0, 10, 10}, 2, 2));); + RUN_TESTS(receiver.drawDRRect(SkRRect::MakeRectXY({0, 0, 10, 10}, 2, 2), + SkRRect::MakeRectXY({2, 2, 8, 8}, 2, 2));); + RUN_TESTS(receiver.drawPath( + SkPath().addOval({0, 0, 10, 10}).addOval({5, 5, 15, 15}));); + RUN_TESTS(receiver.drawArc({0, 0, 10, 10}, 0, math::kPi, true);); RUN_TESTS2( - cv.DrawPoints(PointMode::kPoints, TestPointCount, TestPoints, paint); + receiver.drawPoints(PointMode::kPoints, TestPointCount, TestPoints); , false); - RUN_TESTS2(cv.DrawVertices(TestVertices1.get(), DlBlendMode::kSrc, paint); + RUN_TESTS2(receiver.drawVertices(TestVertices1.get(), DlBlendMode::kSrc); , false); - RUN_TESTS(cv.DrawImage(TestImage1, {0, 0}, kLinearSampling, &paint);); - RUN_TESTS(cv.DrawImageRect(TestImage1, SkRect{10.0f, 10.0f, 20.0f, 20.0f}, - {0, 0, 10, 10}, kNearestSampling, &paint, - DlCanvas::SrcRectConstraint::kFast);); - RUN_TESTS2(cv.DrawImageRect(TestImage1, SkRect{10, 10, 20, 20}, - {0, 0, 10, 10}, kNearestSampling, nullptr, - DlCanvas::SrcRectConstraint::kFast); + RUN_TESTS(receiver.drawImage(TestImage1, {0, 0}, kLinearSampling, true);); + RUN_TESTS2(receiver.drawImage(TestImage1, {0, 0}, kLinearSampling, false); , true); - RUN_TESTS(cv.DrawImageNine(TestImage2, {20, 20, 30, 30}, {0, 0, 20, 20}, - DlFilterMode::kLinear, &paint);); - RUN_TESTS2(cv.DrawImageNine(TestImage2, {20, 20, 30, 30}, {0, 0, 20, 20}, - DlFilterMode::kLinear, nullptr); + RUN_TESTS(receiver.drawImageRect(TestImage1, {10, 10, 20, 20}, {0, 0, 10, 10}, + kNearestSampling, true, + DlCanvas::SrcRectConstraint::kFast);); + RUN_TESTS2(receiver.drawImageRect(TestImage1, {10, 10, 20, 20}, + {0, 0, 10, 10}, kNearestSampling, false, + DlCanvas::SrcRectConstraint::kFast); , true); + RUN_TESTS(receiver.drawImageNine(TestImage2, {20, 20, 30, 30}, {0, 0, 20, 20}, + DlFilterMode::kLinear, true);); + RUN_TESTS2( + receiver.drawImageNine(TestImage2, {20, 20, 30, 30}, {0, 0, 20, 20}, + DlFilterMode::kLinear, false); + , true); static SkRSXform xforms[] = {{1, 0, 0, 0}, {0, 1, 0, 0}}; static SkRect texs[] = {{10, 10, 20, 20}, {20, 20, 30, 30}}; RUN_TESTS2( - cv.DrawAtlas(TestImage1, xforms, texs, nullptr, 2, DlBlendMode::kSrcIn, - kNearestSampling, nullptr, &paint); + receiver.drawAtlas(TestImage1, xforms, texs, nullptr, 2, + DlBlendMode::kSrcIn, kNearestSampling, nullptr, true); , false); RUN_TESTS2( - cv.DrawAtlas(TestImage1, xforms, texs, nullptr, 2, DlBlendMode::kSrcIn, - kNearestSampling, nullptr, nullptr); + receiver.drawAtlas(TestImage1, xforms, texs, nullptr, 2, + DlBlendMode::kSrcIn, kNearestSampling, nullptr, false); , false); EXPECT_TRUE(TestDisplayList1->can_apply_group_opacity()); - RUN_TESTS2(cv.DrawDisplayList(TestDisplayList1);, true); + RUN_TESTS2(receiver.drawDisplayList(TestDisplayList1);, true); { static DisplayListBuilder builder; builder.DrawRect({0, 0, 10, 10}, DlPaint()); builder.DrawRect({5, 5, 15, 15}, DlPaint()); static auto display_list = builder.Build(); - RUN_TESTS2(cv.DrawDisplayList(display_list);, false); + RUN_TESTS2(receiver.drawDisplayList(display_list);, false); } - RUN_TESTS2(cv.DrawTextBlob(TestBlob1, 0, 0, paint);, false); - RUN_TESTS2(cv.DrawShadow(kTestPath1, SK_ColorBLACK, 1.0, false, 1.0);, false); + RUN_TESTS2(receiver.drawTextBlob(TestBlob1, 0, 0);, false); + RUN_TESTS2(receiver.drawShadow(kTestPath1, SK_ColorBLACK, 1.0, false, 1.0); + , false); #undef RUN_TESTS2 #undef RUN_TESTS @@ -977,8 +1128,9 @@ TEST_F(DisplayListTest, SingleOpsMightSupportGroupOpacityBlendMode) { TEST_F(DisplayListTest, OverlappingOpsDoNotSupportGroupOpacity) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); for (int i = 0; i < 10; i++) { - builder.DrawRect(SkRect::MakeXYWH(i * 10, 0, 30, 30), DlPaint()); + receiver.drawRect(SkRect::MakeXYWH(i * 10, 0, 30, 30)); } auto display_list = builder.Build(); EXPECT_FALSE(display_list->can_apply_group_opacity()); @@ -986,65 +1138,80 @@ TEST_F(DisplayListTest, OverlappingOpsDoNotSupportGroupOpacity) { TEST_F(DisplayListTest, SaveLayerFalseSupportsGroupOpacityOverlappingChidren) { DisplayListBuilder builder; - builder.SaveLayer(nullptr, nullptr); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.saveLayer(nullptr, SaveLayerOptions::kNoAttributes); for (int i = 0; i < 10; i++) { - builder.DrawRect(SkRect::MakeXYWH(i * 10, 0, 30, 30), DlPaint()); + receiver.drawRect(SkRect::MakeXYWH(i * 10, 0, 30, 30)); } - builder.Restore(); + receiver.restore(); auto display_list = builder.Build(); EXPECT_TRUE(display_list->can_apply_group_opacity()); } TEST_F(DisplayListTest, SaveLayerTrueSupportsGroupOpacityOverlappingChidren) { DisplayListBuilder builder; - DlPaint save_paint; - builder.SaveLayer(nullptr, &save_paint); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); for (int i = 0; i < 10; i++) { - builder.DrawRect(SkRect::MakeXYWH(i * 10, 0, 30, 30), DlPaint()); + receiver.drawRect(SkRect::MakeXYWH(i * 10, 0, 30, 30)); } - builder.Restore(); + receiver.restore(); auto display_list = builder.Build(); EXPECT_TRUE(display_list->can_apply_group_opacity()); } -TEST_F(DisplayListTest, SaveLayerPaintWithSrcBlendDoesNotSupportGroupOpacity) { +TEST_F(DisplayListTest, SaveLayerFalseWithSrcBlendSupportsGroupOpacity) { DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setBlendMode(DlBlendMode::kSrc); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({0, 0, 10, 10}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setBlendMode(DlBlendMode::kSrc); + receiver.saveLayer(nullptr, SaveLayerOptions::kNoAttributes); + receiver.drawRect({0, 0, 10, 10}); + receiver.restore(); + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, SaveLayerTrueWithSrcBlendDoesNotSupportGroupOpacity) { + DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setBlendMode(DlBlendMode::kSrc); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.drawRect({0, 0, 10, 10}); + receiver.restore(); auto display_list = builder.Build(); EXPECT_FALSE(display_list->can_apply_group_opacity()); } TEST_F(DisplayListTest, SaveLayerFalseSupportsGroupOpacityWithChildSrcBlend) { DisplayListBuilder builder; - builder.SaveLayer(nullptr, nullptr); - builder.DrawRect({0, 0, 10, 10}, DlPaint().setBlendMode(DlBlendMode::kSrc)); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.saveLayer(nullptr, SaveLayerOptions::kNoAttributes); + receiver.setBlendMode(DlBlendMode::kSrc); + receiver.drawRect({0, 0, 10, 10}); + receiver.restore(); auto display_list = builder.Build(); EXPECT_TRUE(display_list->can_apply_group_opacity()); } -TEST_F(DisplayListTest, SaveLayerPaintSupportsGroupOpacityWithChildSrcBlend) { +TEST_F(DisplayListTest, SaveLayerTrueSupportsGroupOpacityWithChildSrcBlend) { DisplayListBuilder builder; - DlPaint save_paint; - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({0, 0, 10, 10}, DlPaint().setBlendMode(DlBlendMode::kSrc)); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setBlendMode(DlBlendMode::kSrc); + receiver.drawRect({0, 0, 10, 10}); + receiver.restore(); auto display_list = builder.Build(); EXPECT_TRUE(display_list->can_apply_group_opacity()); } TEST_F(DisplayListTest, SaveLayerBoundsSnapshotsImageFilter) { DisplayListBuilder builder; - DlPaint save_paint; - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({50, 50, 100, 100}, DlPaint()); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.drawRect({50, 50, 100, 100}); // This image filter should be ignored since it was not set before saveLayer - ToReceiver(builder).setImageFilter(&kTestBlurImageFilter1); - builder.Restore(); + receiver.setImageFilter(&kTestBlurImageFilter1); + receiver.restore(); SkRect bounds = builder.Build()->bounds(); EXPECT_EQ(bounds, SkRect::MakeLTRB(50, 50, 100, 100)); } @@ -1082,11 +1249,11 @@ TEST_F(DisplayListTest, SaveLayerOneSimpleOpInheritsOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1098,9 +1265,10 @@ TEST_F(DisplayListTest, SaveLayerNoAttributesInheritsOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - builder.SaveLayer(nullptr, nullptr); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.saveLayer(nullptr, SaveLayerOptions::kNoAttributes); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1111,12 +1279,12 @@ TEST_F(DisplayListTest, SaveLayerTwoOverlappingOpsDoesNotInheritOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.DrawRect({15, 15, 25, 25}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.drawRect({10, 10, 20, 20}); + receiver.drawRect({15, 15, 25, 25}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1131,16 +1299,16 @@ TEST_F(DisplayListTest, NestedSaveLayersMightInheritOpacity) { SaveLayerOptionsExpector expector({expected1, expected2, expected3}); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - builder.SaveLayer(nullptr, &save_paint); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({15, 15, 25, 25}, DlPaint()); - builder.Restore(); - builder.Restore(); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.drawRect({10, 10, 20, 20}); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.drawRect({15, 15, 25, 25}); + receiver.restore(); + receiver.restore(); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 3); @@ -1154,13 +1322,13 @@ TEST_F(DisplayListTest, NestedSaveLayersCanBothSupportOpacityOptimization) { SaveLayerOptionsExpector expector({expected1, expected2}); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - builder.SaveLayer(nullptr, &save_paint); - builder.SaveLayer(nullptr, nullptr); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Restore(); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.saveLayer(nullptr, SaveLayerOptions::kNoAttributes); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 2); @@ -1171,12 +1339,13 @@ TEST_F(DisplayListTest, SaveLayerImageFilterDoesNotInheritOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - save_paint.setImageFilter(&kTestBlurImageFilter1); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.setImageFilter(&kTestBlurImageFilter1); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setImageFilter(nullptr); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1187,12 +1356,13 @@ TEST_F(DisplayListTest, SaveLayerColorFilterDoesNotInheritOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - save_paint.setColorFilter(&kTestMatrixColorFilter1); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.setColorFilter(&kTestMatrixColorFilter1); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setColorFilter(nullptr); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1203,12 +1373,13 @@ TEST_F(DisplayListTest, SaveLayerSrcBlendDoesNotInheritOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - save_paint.setBlendMode(DlBlendMode::kSrc); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.setBlendMode(DlBlendMode::kSrc); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setBlendMode(DlBlendMode::kSrcOver); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1220,12 +1391,12 @@ TEST_F(DisplayListTest, SaveLayerImageFilterOnChildInheritsOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, - DlPaint().setImageFilter(&kTestBlurImageFilter1)); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setImageFilter(&kTestBlurImageFilter1); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1236,12 +1407,12 @@ TEST_F(DisplayListTest, SaveLayerColorFilterOnChildDoesNotInheritOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, - DlPaint().setColorFilter(&kTestMatrixColorFilter1)); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setColorFilter(&kTestMatrixColorFilter1); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1252,11 +1423,12 @@ TEST_F(DisplayListTest, SaveLayerSrcBlendOnChildDoesNotInheritOpacity) { SaveLayerOptionsExpector expector(expected); DisplayListBuilder builder; - DlPaint save_paint; - save_paint.setColor(SkColorSetARGB(127, 255, 255, 255)); - builder.SaveLayer(nullptr, &save_paint); - builder.DrawRect({10, 10, 20, 20}, DlPaint().setBlendMode(DlBlendMode::kSrc)); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setColor(SkColorSetARGB(127, 255, 255, 255)); + receiver.saveLayer(nullptr, SaveLayerOptions::kWithAttributes); + receiver.setBlendMode(DlBlendMode::kSrc); + receiver.drawRect({10, 10, 20, 20}); + receiver.restore(); builder.Build()->Dispatch(expector); EXPECT_EQ(expector.save_layer_count(), 1); @@ -1390,14 +1562,15 @@ TEST_F(DisplayListTest, FlutterSvgIssue661BoundsWereEmpty) { TEST_F(DisplayListTest, TranslateAffectsCurrentTransform) { DisplayListBuilder builder; - builder.Translate(12.3, 14.5); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.translate(12.3, 14.5); SkMatrix matrix = SkMatrix::Translate(12.3, 14.5); SkM44 m44 = SkM44(matrix); SkM44 cur_m44 = builder.GetTransformFullPerspective(); SkMatrix cur_matrix = builder.GetTransform(); ASSERT_EQ(cur_m44, m44); ASSERT_EQ(cur_matrix, matrix); - builder.Translate(10, 10); + receiver.translate(10, 10); // CurrentTransform has changed ASSERT_NE(builder.GetTransformFullPerspective(), m44); ASSERT_NE(builder.GetTransform(), cur_matrix); @@ -1408,14 +1581,15 @@ TEST_F(DisplayListTest, TranslateAffectsCurrentTransform) { TEST_F(DisplayListTest, ScaleAffectsCurrentTransform) { DisplayListBuilder builder; - builder.Scale(12.3, 14.5); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.scale(12.3, 14.5); SkMatrix matrix = SkMatrix::Scale(12.3, 14.5); SkM44 m44 = SkM44(matrix); SkM44 cur_m44 = builder.GetTransformFullPerspective(); SkMatrix cur_matrix = builder.GetTransform(); ASSERT_EQ(cur_m44, m44); ASSERT_EQ(cur_matrix, matrix); - builder.Translate(10, 10); + receiver.translate(10, 10); // CurrentTransform has changed ASSERT_NE(builder.GetTransformFullPerspective(), m44); ASSERT_NE(builder.GetTransform(), cur_matrix); @@ -1426,14 +1600,15 @@ TEST_F(DisplayListTest, ScaleAffectsCurrentTransform) { TEST_F(DisplayListTest, RotateAffectsCurrentTransform) { DisplayListBuilder builder; - builder.Rotate(12.3); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.rotate(12.3); SkMatrix matrix = SkMatrix::RotateDeg(12.3); SkM44 m44 = SkM44(matrix); SkM44 cur_m44 = builder.GetTransformFullPerspective(); SkMatrix cur_matrix = builder.GetTransform(); ASSERT_EQ(cur_m44, m44); ASSERT_EQ(cur_matrix, matrix); - builder.Translate(10, 10); + receiver.translate(10, 10); // CurrentTransform has changed ASSERT_NE(builder.GetTransformFullPerspective(), m44); ASSERT_NE(builder.GetTransform(), cur_matrix); @@ -1444,14 +1619,15 @@ TEST_F(DisplayListTest, RotateAffectsCurrentTransform) { TEST_F(DisplayListTest, SkewAffectsCurrentTransform) { DisplayListBuilder builder; - builder.Skew(12.3, 14.5); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.skew(12.3, 14.5); SkMatrix matrix = SkMatrix::Skew(12.3, 14.5); SkM44 m44 = SkM44(matrix); SkM44 cur_m44 = builder.GetTransformFullPerspective(); SkMatrix cur_matrix = builder.GetTransform(); ASSERT_EQ(cur_m44, m44); ASSERT_EQ(cur_matrix, matrix); - builder.Translate(10, 10); + receiver.translate(10, 10); // CurrentTransform has changed ASSERT_NE(builder.GetTransformFullPerspective(), m44); ASSERT_NE(builder.GetTransform(), cur_matrix); @@ -1462,8 +1638,9 @@ TEST_F(DisplayListTest, SkewAffectsCurrentTransform) { TEST_F(DisplayListTest, TransformAffectsCurrentTransform) { DisplayListBuilder builder; - builder.Transform2DAffine(3, 0, 12.3, // - 1, 5, 14.5); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.transform2DAffine(3, 0, 12.3, // + 1, 5, 14.5); SkMatrix matrix = SkMatrix::MakeAll(3, 0, 12.3, // 1, 5, 14.5, // 0, 0, 1); @@ -1472,7 +1649,7 @@ TEST_F(DisplayListTest, TransformAffectsCurrentTransform) { SkMatrix cur_matrix = builder.GetTransform(); ASSERT_EQ(cur_m44, m44); ASSERT_EQ(cur_matrix, matrix); - builder.Translate(10, 10); + receiver.translate(10, 10); // CurrentTransform has changed ASSERT_NE(builder.GetTransformFullPerspective(), m44); ASSERT_NE(builder.GetTransform(), cur_matrix); @@ -1483,10 +1660,11 @@ TEST_F(DisplayListTest, TransformAffectsCurrentTransform) { TEST_F(DisplayListTest, FullTransformAffectsCurrentTransform) { DisplayListBuilder builder; - builder.TransformFullPerspective(3, 0, 4, 12.3, // - 1, 5, 3, 14.5, // - 0, 0, 7, 16.2, // - 0, 0, 0, 1); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.transformFullPerspective(3, 0, 4, 12.3, // + 1, 5, 3, 14.5, // + 0, 0, 7, 16.2, // + 0, 0, 0, 1); SkMatrix matrix = SkMatrix::MakeAll(3, 0, 12.3, // 1, 5, 14.5, // 0, 0, 1); @@ -1498,7 +1676,7 @@ TEST_F(DisplayListTest, FullTransformAffectsCurrentTransform) { SkMatrix cur_matrix = builder.GetTransform(); ASSERT_EQ(cur_m44, m44); ASSERT_EQ(cur_matrix, matrix); - builder.Translate(10, 10); + receiver.translate(10, 10); // CurrentTransform has changed ASSERT_NE(builder.GetTransformFullPerspective(), m44); ASSERT_NE(builder.GetTransform(), cur_matrix); @@ -1509,8 +1687,9 @@ TEST_F(DisplayListTest, FullTransformAffectsCurrentTransform) { TEST_F(DisplayListTest, ClipRectAffectsClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect clip_bounds = SkRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); - builder.ClipRect(clip_bounds, ClipOp::kIntersect, false); + receiver.clipRect(clip_bounds, ClipOp::kIntersect, false); // Save initial return values for testing restored values SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1518,27 +1697,27 @@ TEST_F(DisplayListTest, ClipRectAffectsClipBounds) { ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.Save(); - builder.ClipRect({0, 0, 15, 15}, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipRect({0, 0, 15, 15}, ClipOp::kIntersect, false); // Both clip bounds have changed ASSERT_NE(builder.GetLocalClipBounds(), clip_bounds); ASSERT_NE(builder.GetDestinationClipBounds(), clip_bounds); // Previous return values have not changed ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); - builder.Save(); - builder.Scale(2, 2); + receiver.save(); + receiver.scale(2, 2); SkRect scaled_clip_bounds = SkRect::MakeLTRB(5.1, 5.65, 10.2, 12.85); ASSERT_EQ(builder.GetLocalClipBounds(), scaled_clip_bounds); // Destination bounds are unaffected by transform ASSERT_EQ(builder.GetDestinationClipBounds(), clip_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); @@ -1547,9 +1726,10 @@ TEST_F(DisplayListTest, ClipRectAffectsClipBounds) { TEST_F(DisplayListTest, ClipRectDoAAAffectsClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect clip_bounds = SkRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); SkRect clip_expanded_bounds = SkRect::MakeLTRB(10, 11, 21, 26); - builder.ClipRect(clip_bounds, ClipOp::kIntersect, true); + receiver.clipRect(clip_bounds, ClipOp::kIntersect, true); // Save initial return values for testing restored values SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1557,27 +1737,27 @@ TEST_F(DisplayListTest, ClipRectDoAAAffectsClipBounds) { ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); - builder.Save(); - builder.ClipRect({0, 0, 15, 15}, ClipOp::kIntersect, true); + receiver.save(); + receiver.clipRect({0, 0, 15, 15}, ClipOp::kIntersect, true); // Both clip bounds have changed ASSERT_NE(builder.GetLocalClipBounds(), clip_expanded_bounds); ASSERT_NE(builder.GetDestinationClipBounds(), clip_expanded_bounds); // Previous return values have not changed ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); - builder.Save(); - builder.Scale(2, 2); + receiver.save(); + receiver.scale(2, 2); SkRect scaled_expanded_bounds = SkRect::MakeLTRB(5, 5.5, 10.5, 13); ASSERT_EQ(builder.GetLocalClipBounds(), scaled_expanded_bounds); // Destination bounds are unaffected by transform ASSERT_EQ(builder.GetDestinationClipBounds(), clip_expanded_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); @@ -1586,28 +1766,30 @@ TEST_F(DisplayListTest, ClipRectDoAAAffectsClipBounds) { TEST_F(DisplayListTest, ClipRectAffectsClipBoundsWithMatrix) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect clip_bounds_1 = SkRect::MakeLTRB(0, 0, 10, 10); SkRect clip_bounds_2 = SkRect::MakeLTRB(10, 10, 20, 20); - builder.Save(); - builder.ClipRect(clip_bounds_1, ClipOp::kIntersect, false); - builder.Translate(10, 0); - builder.ClipRect(clip_bounds_1, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipRect(clip_bounds_1, ClipOp::kIntersect, false); + receiver.translate(10, 0); + receiver.clipRect(clip_bounds_1, ClipOp::kIntersect, false); ASSERT_TRUE(builder.GetDestinationClipBounds().isEmpty()); - builder.Restore(); + receiver.restore(); - builder.Save(); - builder.ClipRect(clip_bounds_1, ClipOp::kIntersect, false); - builder.Translate(-10, -10); - builder.ClipRect(clip_bounds_2, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipRect(clip_bounds_1, ClipOp::kIntersect, false); + receiver.translate(-10, -10); + receiver.clipRect(clip_bounds_2, ClipOp::kIntersect, false); ASSERT_EQ(builder.GetDestinationClipBounds(), clip_bounds_1); - builder.Restore(); + receiver.restore(); } TEST_F(DisplayListTest, ClipRRectAffectsClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect clip_bounds = SkRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); SkRRect clip = SkRRect::MakeRectXY(clip_bounds, 3, 2); - builder.ClipRRect(clip, ClipOp::kIntersect, false); + receiver.clipRRect(clip, ClipOp::kIntersect, false); // Save initial return values for testing restored values SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1615,27 +1797,27 @@ TEST_F(DisplayListTest, ClipRRectAffectsClipBounds) { ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.Save(); - builder.ClipRect({0, 0, 15, 15}, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipRect({0, 0, 15, 15}, ClipOp::kIntersect, false); // Both clip bounds have changed ASSERT_NE(builder.GetLocalClipBounds(), clip_bounds); ASSERT_NE(builder.GetDestinationClipBounds(), clip_bounds); // Previous return values have not changed ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); - builder.Save(); - builder.Scale(2, 2); + receiver.save(); + receiver.scale(2, 2); SkRect scaled_clip_bounds = SkRect::MakeLTRB(5.1, 5.65, 10.2, 12.85); ASSERT_EQ(builder.GetLocalClipBounds(), scaled_clip_bounds); // Destination bounds are unaffected by transform ASSERT_EQ(builder.GetDestinationClipBounds(), clip_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); @@ -1644,10 +1826,11 @@ TEST_F(DisplayListTest, ClipRRectAffectsClipBounds) { TEST_F(DisplayListTest, ClipRRectDoAAAffectsClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect clip_bounds = SkRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); SkRect clip_expanded_bounds = SkRect::MakeLTRB(10, 11, 21, 26); SkRRect clip = SkRRect::MakeRectXY(clip_bounds, 3, 2); - builder.ClipRRect(clip, ClipOp::kIntersect, true); + receiver.clipRRect(clip, ClipOp::kIntersect, true); // Save initial return values for testing restored values SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1655,27 +1838,27 @@ TEST_F(DisplayListTest, ClipRRectDoAAAffectsClipBounds) { ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); - builder.Save(); - builder.ClipRect({0, 0, 15, 15}, ClipOp::kIntersect, true); + receiver.save(); + receiver.clipRect({0, 0, 15, 15}, ClipOp::kIntersect, true); // Both clip bounds have changed ASSERT_NE(builder.GetLocalClipBounds(), clip_expanded_bounds); ASSERT_NE(builder.GetDestinationClipBounds(), clip_expanded_bounds); // Previous return values have not changed ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); - builder.Save(); - builder.Scale(2, 2); + receiver.save(); + receiver.scale(2, 2); SkRect scaled_expanded_bounds = SkRect::MakeLTRB(5, 5.5, 10.5, 13); ASSERT_EQ(builder.GetLocalClipBounds(), scaled_expanded_bounds); // Destination bounds are unaffected by transform ASSERT_EQ(builder.GetDestinationClipBounds(), clip_expanded_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); @@ -1684,31 +1867,33 @@ TEST_F(DisplayListTest, ClipRRectDoAAAffectsClipBounds) { TEST_F(DisplayListTest, ClipRRectAffectsClipBoundsWithMatrix) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect clip_bounds_1 = SkRect::MakeLTRB(0, 0, 10, 10); SkRect clip_bounds_2 = SkRect::MakeLTRB(10, 10, 20, 20); SkRRect clip1 = SkRRect::MakeRectXY(clip_bounds_1, 3, 2); SkRRect clip2 = SkRRect::MakeRectXY(clip_bounds_2, 3, 2); - builder.Save(); - builder.ClipRRect(clip1, ClipOp::kIntersect, false); - builder.Translate(10, 0); - builder.ClipRRect(clip1, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipRRect(clip1, ClipOp::kIntersect, false); + receiver.translate(10, 0); + receiver.clipRRect(clip1, ClipOp::kIntersect, false); ASSERT_TRUE(builder.GetDestinationClipBounds().isEmpty()); - builder.Restore(); + receiver.restore(); - builder.Save(); - builder.ClipRRect(clip1, ClipOp::kIntersect, false); - builder.Translate(-10, -10); - builder.ClipRRect(clip2, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipRRect(clip1, ClipOp::kIntersect, false); + receiver.translate(-10, -10); + receiver.clipRRect(clip2, ClipOp::kIntersect, false); ASSERT_EQ(builder.GetDestinationClipBounds(), clip_bounds_1); - builder.Restore(); + receiver.restore(); } TEST_F(DisplayListTest, ClipPathAffectsClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkPath clip = SkPath().addCircle(10.2, 11.3, 2).addCircle(20.4, 25.7, 2); SkRect clip_bounds = SkRect::MakeLTRB(8.2, 9.3, 22.4, 27.7); - builder.ClipPath(clip, ClipOp::kIntersect, false); + receiver.clipPath(clip, ClipOp::kIntersect, false); // Save initial return values for testing restored values SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1716,27 +1901,27 @@ TEST_F(DisplayListTest, ClipPathAffectsClipBounds) { ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.Save(); - builder.ClipRect({0, 0, 15, 15}, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipRect({0, 0, 15, 15}, ClipOp::kIntersect, false); // Both clip bounds have changed ASSERT_NE(builder.GetLocalClipBounds(), clip_bounds); ASSERT_NE(builder.GetDestinationClipBounds(), clip_bounds); // Previous return values have not changed ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); - builder.Save(); - builder.Scale(2, 2); + receiver.save(); + receiver.scale(2, 2); SkRect scaled_clip_bounds = SkRect::MakeLTRB(4.1, 4.65, 11.2, 13.85); ASSERT_EQ(builder.GetLocalClipBounds(), scaled_clip_bounds); // Destination bounds are unaffected by transform ASSERT_EQ(builder.GetDestinationClipBounds(), clip_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); @@ -1745,9 +1930,10 @@ TEST_F(DisplayListTest, ClipPathAffectsClipBounds) { TEST_F(DisplayListTest, ClipPathDoAAAffectsClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkPath clip = SkPath().addCircle(10.2, 11.3, 2).addCircle(20.4, 25.7, 2); SkRect clip_expanded_bounds = SkRect::MakeLTRB(8, 9, 23, 28); - builder.ClipPath(clip, ClipOp::kIntersect, true); + receiver.clipPath(clip, ClipOp::kIntersect, true); // Save initial return values for testing restored values SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1755,27 +1941,27 @@ TEST_F(DisplayListTest, ClipPathDoAAAffectsClipBounds) { ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); - builder.Save(); - builder.ClipRect({0, 0, 15, 15}, ClipOp::kIntersect, true); + receiver.save(); + receiver.clipRect({0, 0, 15, 15}, ClipOp::kIntersect, true); // Both clip bounds have changed ASSERT_NE(builder.GetLocalClipBounds(), clip_expanded_bounds); ASSERT_NE(builder.GetDestinationClipBounds(), clip_expanded_bounds); // Previous return values have not changed ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); - builder.Save(); - builder.Scale(2, 2); + receiver.save(); + receiver.scale(2, 2); SkRect scaled_expanded_bounds = SkRect::MakeLTRB(4, 4.5, 11.5, 14); ASSERT_EQ(builder.GetLocalClipBounds(), scaled_expanded_bounds); // Destination bounds are unaffected by transform ASSERT_EQ(builder.GetDestinationClipBounds(), clip_expanded_bounds); - builder.Restore(); + receiver.restore(); // save/restore returned the values to their original values ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); @@ -1784,30 +1970,32 @@ TEST_F(DisplayListTest, ClipPathDoAAAffectsClipBounds) { TEST_F(DisplayListTest, ClipPathAffectsClipBoundsWithMatrix) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect clip_bounds = SkRect::MakeLTRB(0, 0, 10, 10); SkPath clip1 = SkPath().addCircle(2.5, 2.5, 2.5).addCircle(7.5, 7.5, 2.5); SkPath clip2 = SkPath().addCircle(12.5, 12.5, 2.5).addCircle(17.5, 17.5, 2.5); - builder.Save(); - builder.ClipPath(clip1, ClipOp::kIntersect, false); - builder.Translate(10, 0); - builder.ClipPath(clip1, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipPath(clip1, ClipOp::kIntersect, false); + receiver.translate(10, 0); + receiver.clipPath(clip1, ClipOp::kIntersect, false); ASSERT_TRUE(builder.GetDestinationClipBounds().isEmpty()); - builder.Restore(); + receiver.restore(); - builder.Save(); - builder.ClipPath(clip1, ClipOp::kIntersect, false); - builder.Translate(-10, -10); - builder.ClipPath(clip2, ClipOp::kIntersect, false); + receiver.save(); + receiver.clipPath(clip1, ClipOp::kIntersect, false); + receiver.translate(-10, -10); + receiver.clipPath(clip2, ClipOp::kIntersect, false); ASSERT_EQ(builder.GetDestinationClipBounds(), clip_bounds); - builder.Restore(); + receiver.restore(); } TEST_F(DisplayListTest, DiffClipRectDoesNotAffectClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRect diff_clip = SkRect::MakeLTRB(0, 0, 15, 15); SkRect clip_bounds = SkRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); - builder.ClipRect(clip_bounds, ClipOp::kIntersect, false); + receiver.clipRect(clip_bounds, ClipOp::kIntersect, false); // Save initial return values for testing after kDifference clip SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1815,17 +2003,18 @@ TEST_F(DisplayListTest, DiffClipRectDoesNotAffectClipBounds) { ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.ClipRect(diff_clip, ClipOp::kDifference, false); + receiver.clipRect(diff_clip, ClipOp::kDifference, false); ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); } TEST_F(DisplayListTest, DiffClipRRectDoesNotAffectClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkRRect diff_clip = SkRRect::MakeRectXY({0, 0, 15, 15}, 1, 1); SkRect clip_bounds = SkRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); SkRRect clip = SkRRect::MakeRectXY({10.2, 11.3, 20.4, 25.7}, 3, 2); - builder.ClipRRect(clip, ClipOp::kIntersect, false); + receiver.clipRRect(clip, ClipOp::kIntersect, false); // Save initial return values for testing after kDifference clip SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1833,17 +2022,18 @@ TEST_F(DisplayListTest, DiffClipRRectDoesNotAffectClipBounds) { ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.ClipRRect(diff_clip, ClipOp::kDifference, false); + receiver.clipRRect(diff_clip, ClipOp::kDifference, false); ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); } TEST_F(DisplayListTest, DiffClipPathDoesNotAffectClipBounds) { DisplayListBuilder builder; + DlOpReceiver& receiver = ToReceiver(builder); SkPath diff_clip = SkPath().addRect({0, 0, 15, 15}); SkPath clip = SkPath().addCircle(10.2, 11.3, 2).addCircle(20.4, 25.7, 2); SkRect clip_bounds = SkRect::MakeLTRB(8.2, 9.3, 22.4, 27.7); - builder.ClipPath(clip, ClipOp::kIntersect, false); + receiver.clipPath(clip, ClipOp::kIntersect, false); // Save initial return values for testing after kDifference clip SkRect initial_local_bounds = builder.GetLocalClipBounds(); @@ -1851,7 +2041,7 @@ TEST_F(DisplayListTest, DiffClipPathDoesNotAffectClipBounds) { ASSERT_EQ(initial_local_bounds, clip_bounds); ASSERT_EQ(initial_destination_bounds, clip_bounds); - builder.ClipPath(diff_clip, ClipOp::kDifference, false); + receiver.clipPath(diff_clip, ClipOp::kDifference, false); ASSERT_EQ(builder.GetLocalClipBounds(), initial_local_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), initial_destination_bounds); } @@ -1859,9 +2049,10 @@ TEST_F(DisplayListTest, DiffClipPathDoesNotAffectClipBounds) { TEST_F(DisplayListTest, ClipPathWithInvertFillTypeDoesNotAffectClipBounds) { SkRect cull_rect = SkRect::MakeLTRB(0, 0, 100.0, 100.0); DisplayListBuilder builder(cull_rect); + DlOpReceiver& receiver = ToReceiver(builder); SkPath clip = SkPath().addCircle(10.2, 11.3, 2).addCircle(20.4, 25.7, 2); clip.setFillType(SkPathFillType::kInverseWinding); - builder.ClipPath(clip, ClipOp::kIntersect, false); + receiver.clipPath(clip, ClipOp::kIntersect, false); ASSERT_EQ(builder.GetLocalClipBounds(), cull_rect); ASSERT_EQ(builder.GetDestinationClipBounds(), cull_rect); @@ -1870,10 +2061,11 @@ TEST_F(DisplayListTest, ClipPathWithInvertFillTypeDoesNotAffectClipBounds) { TEST_F(DisplayListTest, DiffClipPathWithInvertFillTypeAffectsClipBounds) { SkRect cull_rect = SkRect::MakeLTRB(0, 0, 100.0, 100.0); DisplayListBuilder builder(cull_rect); + DlOpReceiver& receiver = ToReceiver(builder); SkPath clip = SkPath().addCircle(10.2, 11.3, 2).addCircle(20.4, 25.7, 2); clip.setFillType(SkPathFillType::kInverseWinding); SkRect clip_bounds = SkRect::MakeLTRB(8.2, 9.3, 22.4, 27.7); - builder.ClipPath(clip, ClipOp::kDifference, false); + receiver.clipPath(clip, ClipOp::kDifference, false); ASSERT_EQ(builder.GetLocalClipBounds(), clip_bounds); ASSERT_EQ(builder.GetDestinationClipBounds(), clip_bounds); @@ -1884,7 +2076,8 @@ TEST_F(DisplayListTest, FlatDrawPointsProducesBounds) { SkPoint vertical_points[2] = {{10, 10}, {10, 20}}; { DisplayListBuilder builder; - builder.DrawPoints(PointMode::kPolygon, 2, horizontal_points, DlPaint()); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawPoints(PointMode::kPolygon, 2, horizontal_points); SkRect bounds = builder.Build()->bounds(); EXPECT_TRUE(bounds.contains(10, 10)); EXPECT_TRUE(bounds.contains(20, 10)); @@ -1892,7 +2085,8 @@ TEST_F(DisplayListTest, FlatDrawPointsProducesBounds) { } { DisplayListBuilder builder; - builder.DrawPoints(PointMode::kPolygon, 2, vertical_points, DlPaint()); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawPoints(PointMode::kPolygon, 2, vertical_points); SkRect bounds = builder.Build()->bounds(); EXPECT_TRUE(bounds.contains(10, 10)); EXPECT_TRUE(bounds.contains(10, 20)); @@ -1900,14 +2094,16 @@ TEST_F(DisplayListTest, FlatDrawPointsProducesBounds) { } { DisplayListBuilder builder; - builder.DrawPoints(PointMode::kPoints, 1, horizontal_points, DlPaint()); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawPoints(PointMode::kPoints, 1, horizontal_points); SkRect bounds = builder.Build()->bounds(); EXPECT_TRUE(bounds.contains(10, 10)); } { DisplayListBuilder builder; - builder.DrawPoints(PointMode::kPolygon, 2, horizontal_points, - DlPaint().setStrokeWidth(2)); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setStrokeWidth(2); + receiver.drawPoints(PointMode::kPolygon, 2, horizontal_points); SkRect bounds = builder.Build()->bounds(); EXPECT_TRUE(bounds.contains(10, 10)); EXPECT_TRUE(bounds.contains(20, 10)); @@ -1915,8 +2111,9 @@ TEST_F(DisplayListTest, FlatDrawPointsProducesBounds) { } { DisplayListBuilder builder; - builder.DrawPoints(PointMode::kPolygon, 2, vertical_points, - DlPaint().setStrokeWidth(2)); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setStrokeWidth(2); + receiver.drawPoints(PointMode::kPolygon, 2, vertical_points); SkRect bounds = builder.Build()->bounds(); EXPECT_TRUE(bounds.contains(10, 10)); EXPECT_TRUE(bounds.contains(10, 20)); @@ -1924,8 +2121,9 @@ TEST_F(DisplayListTest, FlatDrawPointsProducesBounds) { } { DisplayListBuilder builder; - builder.DrawPoints(PointMode::kPoints, 1, horizontal_points, - DlPaint().setStrokeWidth(2)); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.setStrokeWidth(2); + receiver.drawPoints(PointMode::kPoints, 1, horizontal_points); SkRect bounds = builder.Build()->bounds(); EXPECT_TRUE(bounds.contains(10, 10)); EXPECT_EQ(bounds, SkRect::MakeLTRB(9, 9, 11, 11)); @@ -1951,8 +2149,9 @@ static void test_rtree(const sk_sp& rtree, TEST_F(DisplayListTest, RTreeOfSimpleScene) { DisplayListBuilder builder(/*prepare_rtree=*/true); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.DrawRect({50, 50, 60, 60}, DlPaint()); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawRect({10, 10, 20, 20}); + receiver.drawRect({50, 50, 60, 60}); auto display_list = builder.Build(); auto rtree = display_list->rtree(); std::vector rects = { @@ -1978,10 +2177,11 @@ TEST_F(DisplayListTest, RTreeOfSimpleScene) { TEST_F(DisplayListTest, RTreeOfSaveRestoreScene) { DisplayListBuilder builder(/*prepare_rtree=*/true); - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Save(); - builder.DrawRect({50, 50, 60, 60}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawRect({10, 10, 20, 20}); + receiver.save(); + receiver.drawRect({50, 50, 60, 60}); + receiver.restore(); auto display_list = builder.Build(); auto rtree = display_list->rtree(); std::vector rects = { @@ -2042,12 +2242,14 @@ TEST_F(DisplayListTest, RTreeOfSaveLayerFilterScene) { TEST_F(DisplayListTest, NestedDisplayListRTreesAreSparse) { DisplayListBuilder nested_dl_builder(/**prepare_rtree=*/true); - nested_dl_builder.DrawRect({10, 10, 20, 20}, DlPaint()); - nested_dl_builder.DrawRect({50, 50, 60, 60}, DlPaint()); + DlOpReceiver& nested_dl_receiver = ToReceiver(nested_dl_builder); + nested_dl_receiver.drawRect({10, 10, 20, 20}); + nested_dl_receiver.drawRect({50, 50, 60, 60}); auto nested_display_list = nested_dl_builder.Build(); DisplayListBuilder builder(/**prepare_rtree=*/true); - builder.DrawDisplayList(nested_display_list); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawDisplayList(nested_display_list); auto display_list = builder.Build(); auto rtree = display_list->rtree(); @@ -2063,61 +2265,67 @@ TEST_F(DisplayListTest, NestedDisplayListRTreesAreSparse) { TEST_F(DisplayListTest, RemoveUnnecessarySaveRestorePairs) { { DisplayListBuilder builder; - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Save(); // This save op is unnecessary - builder.DrawRect({50, 50, 60, 60}, DlPaint()); - builder.Restore(); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawRect({10, 10, 20, 20}); + receiver.save(); // This save op is unnecessary + receiver.drawRect({50, 50, 60, 60}); + receiver.restore(); DisplayListBuilder builder2; - builder2.DrawRect({10, 10, 20, 20}, DlPaint()); - builder2.DrawRect({50, 50, 60, 60}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({10, 10, 20, 20}); + receiver2.drawRect({50, 50, 60, 60}); ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), builder2.Build())); } { DisplayListBuilder builder; - builder.DrawRect({10, 10, 20, 20}, DlPaint()); - builder.Save(); - builder.Translate(1.0, 1.0); + DlOpReceiver& receiver = ToReceiver(builder); + receiver.drawRect({10, 10, 20, 20}); + receiver.save(); + receiver.translate(1.0, 1.0); { - builder.Save(); // unnecessary - builder.DrawRect({50, 50, 60, 60}, DlPaint()); - builder.Restore(); + receiver.save(); // unnecessary + receiver.drawRect({50, 50, 60, 60}); + receiver.restore(); } - builder.Restore(); + receiver.restore(); DisplayListBuilder builder2; - builder2.DrawRect({10, 10, 20, 20}, DlPaint()); - builder2.Save(); - builder2.Translate(1.0, 1.0); - { builder2.DrawRect({50, 50, 60, 60}, DlPaint()); } - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({10, 10, 20, 20}); + receiver2.save(); + receiver2.translate(1.0, 1.0); + { receiver2.drawRect({50, 50, 60, 60}); } + receiver2.restore(); ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), builder2.Build())); } } TEST_F(DisplayListTest, CollapseMultipleNestedSaveRestore) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Save(); - builder1.Translate(10, 10); - builder1.Scale(2, 2); - builder1.ClipRect({10, 10, 20, 20}, ClipOp::kIntersect, false); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.save(); + receiver1.translate(10, 10); + receiver1.scale(2, 2); + receiver1.clipRect({10, 10, 20, 20}, ClipOp::kIntersect, false); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.Translate(10, 10); - builder2.Scale(2, 2); - builder2.ClipRect({10, 10, 20, 20}, ClipOp::kIntersect, false); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.translate(10, 10); + receiver2.scale(2, 2); + receiver2.clipRect({10, 10, 20, 20}, ClipOp::kIntersect, false); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2125,19 +2333,21 @@ TEST_F(DisplayListTest, CollapseMultipleNestedSaveRestore) { TEST_F(DisplayListTest, CollapseNestedSaveAndSaveLayerRestore) { DisplayListBuilder builder1; - builder1.Save(); - builder1.SaveLayer(nullptr, nullptr); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Scale(2, 2); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.saveLayer(nullptr, SaveLayerOptions::kNoAttributes); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.scale(2, 2); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.SaveLayer(nullptr, nullptr); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Scale(2, 2); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.saveLayer(nullptr, SaveLayerOptions::kNoAttributes); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.scale(2, 2); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2200,37 +2410,39 @@ TEST_F(DisplayListTest, RemoveUnnecessarySaveRestorePairsInSetPaint) { TEST_F(DisplayListTest, TransformTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.TransformFullPerspective(1, 0, 0, 10, // - 0, 1, 0, 100, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.TransformFullPerspective(1, 0, 0, 10, // - 0, 1, 0, 100, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transformFullPerspective(1, 0, 0, 10, // + 0, 1, 0, 100, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.transformFullPerspective(1, 0, 0, 10, // + 0, 1, 0, 100, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.TransformFullPerspective(1, 0, 0, 10, // - 0, 1, 0, 100, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); - builder2.Save(); - builder2.TransformFullPerspective(1, 0, 0, 10, // - 0, 1, 0, 100, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.transformFullPerspective(1, 0, 0, 10, // + 0, 1, 0, 100, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); + receiver2.save(); + receiver2.transformFullPerspective(1, 0, 0, 10, // + 0, 1, 0, 100, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2238,19 +2450,21 @@ TEST_F(DisplayListTest, TransformTriggersDeferredSave) { TEST_F(DisplayListTest, Transform2DTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Transform2DAffine(0, 1, 12, 1, 0, 33); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transform2DAffine(0, 1, 12, 1, 0, 33); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.Transform2DAffine(0, 1, 12, 1, 0, 33); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.transform2DAffine(0, 1, 12, 1, 0, 33); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2258,25 +2472,27 @@ TEST_F(DisplayListTest, Transform2DTriggersDeferredSave) { TEST_F(DisplayListTest, TransformPerspectiveTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.TransformFullPerspective(0, 1, 0, 12, // - 1, 0, 0, 33, // - 3, 2, 5, 29, // - 0, 0, 0, 12); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transformFullPerspective(0, 1, 0, 12, // + 1, 0, 0, 33, // + 3, 2, 5, 29, // + 0, 0, 0, 12); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.TransformFullPerspective(0, 1, 0, 12, // - 1, 0, 0, 33, // - 3, 2, 5, 29, // - 0, 0, 0, 12); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.transformFullPerspective(0, 1, 0, 12, // + 1, 0, 0, 33, // + 3, 2, 5, 29, // + 0, 0, 0, 12); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2284,19 +2500,21 @@ TEST_F(DisplayListTest, TransformPerspectiveTriggersDeferredSave) { TEST_F(DisplayListTest, ResetTransformTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.TransformReset(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transformReset(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.TransformReset(); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.transformReset(); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2304,19 +2522,21 @@ TEST_F(DisplayListTest, ResetTransformTriggersDeferredSave) { TEST_F(DisplayListTest, SkewTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Skew(10, 10); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.skew(10, 10); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.Skew(10, 10); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.skew(10, 10); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2324,19 +2544,21 @@ TEST_F(DisplayListTest, SkewTriggersDeferredSave) { TEST_F(DisplayListTest, TranslateTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Translate(10, 10); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.translate(10, 10); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.Translate(10, 10); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.translate(10, 10); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2344,19 +2566,21 @@ TEST_F(DisplayListTest, TranslateTriggersDeferredSave) { TEST_F(DisplayListTest, ScaleTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Scale(0.5, 0.5); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.scale(0.5, 0.5); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.Scale(0.5, 0.5); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.scale(0.5, 0.5); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2364,29 +2588,33 @@ TEST_F(DisplayListTest, ScaleTriggersDeferredSave) { TEST_F(DisplayListTest, ClipRectTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.ClipRect(SkRect::MakeLTRB(0, 0, 100, 100), ClipOp::kIntersect, true); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.clipRect(SkRect::MakeLTRB(0, 0, 100, 100), ClipOp::kIntersect, + true); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.ClipRect(SkRect::MakeLTRB(0, 0, 100, 100), ClipOp::kIntersect, true); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); - builder2.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.clipRect(SkRect::MakeLTRB(0, 0, 100, 100), ClipOp::kIntersect, + true); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); + receiver2.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2394,31 +2622,33 @@ TEST_F(DisplayListTest, ClipRectTriggersDeferredSave) { TEST_F(DisplayListTest, ClipRRectTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.ClipRRect(kTestRRect, ClipOp::kIntersect, true); - - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.clipRRect(kTestRRect, ClipOp::kIntersect, true); + + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.ClipRRect(kTestRRect, ClipOp::kIntersect, true); - - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); - builder2.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.clipRRect(kTestRRect, ClipOp::kIntersect, true); + + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); + receiver2.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2426,29 +2656,31 @@ TEST_F(DisplayListTest, ClipRRectTriggersDeferredSave) { TEST_F(DisplayListTest, ClipPathTriggersDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.ClipPath(kTestPath1, ClipOp::kIntersect, true); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.clipPath(kTestPath1, ClipOp::kIntersect, true); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.ClipPath(kTestPath1, ClipOp::kIntersect, true); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); - builder2.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.clipPath(kTestPath1, ClipOp::kIntersect, true); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); + receiver2.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2456,18 +2688,20 @@ TEST_F(DisplayListTest, ClipPathTriggersDeferredSave) { TEST_F(DisplayListTest, NOPTranslateDoesNotTriggerDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Translate(0, 0); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.translate(0, 0); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2475,18 +2709,20 @@ TEST_F(DisplayListTest, NOPTranslateDoesNotTriggerDeferredSave) { TEST_F(DisplayListTest, NOPScaleDoesNotTriggerDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Scale(1.0, 1.0); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.scale(1.0, 1.0); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2494,18 +2730,20 @@ TEST_F(DisplayListTest, NOPScaleDoesNotTriggerDeferredSave) { TEST_F(DisplayListTest, NOPRotationDoesNotTriggerDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Rotate(360); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.rotate(360); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2513,18 +2751,20 @@ TEST_F(DisplayListTest, NOPRotationDoesNotTriggerDeferredSave) { TEST_F(DisplayListTest, NOPSkewDoesNotTriggerDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Skew(0, 0); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.skew(0, 0); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2532,25 +2772,27 @@ TEST_F(DisplayListTest, NOPSkewDoesNotTriggerDeferredSave) { TEST_F(DisplayListTest, NOPTransformDoesNotTriggerDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2558,18 +2800,20 @@ TEST_F(DisplayListTest, NOPTransformDoesNotTriggerDeferredSave) { TEST_F(DisplayListTest, NOPTransform2DDoesNotTriggerDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.Transform2DAffine(1, 0, 0, 0, 1, 0); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transform2DAffine(1, 0, 0, 0, 1, 0); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2578,21 +2822,23 @@ TEST_F(DisplayListTest, NOPTransform2DDoesNotTriggerDeferredSave) { TEST_F(DisplayListTest, NOPTransformFullPerspectiveDoesNotTriggerDeferredSave) { { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2600,25 +2846,27 @@ TEST_F(DisplayListTest, NOPTransformFullPerspectiveDoesNotTriggerDeferredSave) { { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.TransformFullPerspective(1, 0, 0, 0, // - 0, 1, 0, 0, // - 0, 0, 1, 0, // - 0, 0, 0, 1); - builder1.TransformReset(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.transformFullPerspective(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1); + receiver1.transformReset(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.Save(); - builder2.TransformReset(); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.Restore(); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.save(); + receiver2.transformReset(); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.restore(); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); @@ -2628,19 +2876,21 @@ TEST_F(DisplayListTest, NOPTransformFullPerspectiveDoesNotTriggerDeferredSave) { TEST_F(DisplayListTest, NOPClipDoesNotTriggerDeferredSave) { DisplayListBuilder builder1; - builder1.Save(); - builder1.Save(); - builder1.ClipRect(SkRect::MakeLTRB(0, SK_ScalarNaN, SK_ScalarNaN, 0), - ClipOp::kIntersect, true); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); - builder1.DrawRect({0, 0, 100, 100}, DlPaint()); - builder1.Restore(); + DlOpReceiver& receiver1 = ToReceiver(builder1); + receiver1.save(); + receiver1.save(); + receiver1.clipRect(SkRect::MakeLTRB(0, SK_ScalarNaN, SK_ScalarNaN, 0), + ClipOp::kIntersect, true); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); + receiver1.drawRect({0, 0, 100, 100}); + receiver1.restore(); auto display_list1 = builder1.Build(); DisplayListBuilder builder2; - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); - builder2.DrawRect({0, 0, 100, 100}, DlPaint()); + DlOpReceiver& receiver2 = ToReceiver(builder2); + receiver2.drawRect({0, 0, 100, 100}); + receiver2.drawRect({0, 0, 100, 100}); auto display_list2 = builder2.Build(); ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); @@ -2685,10 +2935,11 @@ TEST_F(DisplayListTest, RTreeOfClippedSaveLayerFilterScene) { TEST_F(DisplayListTest, RTreeRenderCulling) { DisplayListBuilder main_builder(true); - main_builder.DrawRect({0, 0, 10, 10}, DlPaint()); - main_builder.DrawRect({20, 0, 30, 10}, DlPaint()); - main_builder.DrawRect({0, 20, 10, 30}, DlPaint()); - main_builder.DrawRect({20, 20, 30, 30}, DlPaint()); + DlOpReceiver& main_receiver = ToReceiver(main_builder); + main_receiver.drawRect({0, 0, 10, 10}); + main_receiver.drawRect({20, 0, 30, 10}); + main_receiver.drawRect({0, 20, 10, 30}); + main_receiver.drawRect({20, 20, 30, 30}); auto main = main_builder.Build(); auto test = [main](SkIRect cull_rect, const sk_sp& expected) { @@ -2720,7 +2971,8 @@ TEST_F(DisplayListTest, RTreeRenderCulling) { SkIRect cull_rect = {9, 9, 19, 19}; DisplayListBuilder expected_builder; - expected_builder.DrawRect({0, 0, 10, 10}, DlPaint()); + DlOpReceiver& expected_receiver = ToReceiver(expected_builder); + expected_receiver.drawRect({0, 0, 10, 10}); auto expected = expected_builder.Build(); test(cull_rect, expected); @@ -2730,7 +2982,8 @@ TEST_F(DisplayListTest, RTreeRenderCulling) { SkIRect cull_rect = {11, 9, 21, 19}; DisplayListBuilder expected_builder; - expected_builder.DrawRect({20, 0, 30, 10}, DlPaint()); + DlOpReceiver& expected_receiver = ToReceiver(expected_builder); + expected_receiver.drawRect({20, 0, 30, 10}); auto expected = expected_builder.Build(); test(cull_rect, expected); @@ -2740,7 +2993,8 @@ TEST_F(DisplayListTest, RTreeRenderCulling) { SkIRect cull_rect = {9, 11, 19, 21}; DisplayListBuilder expected_builder; - expected_builder.DrawRect({0, 20, 10, 30}, DlPaint()); + DlOpReceiver& expected_receiver = ToReceiver(expected_builder); + expected_receiver.drawRect({0, 20, 10, 30}); auto expected = expected_builder.Build(); test(cull_rect, expected); @@ -2750,7 +3004,8 @@ TEST_F(DisplayListTest, RTreeRenderCulling) { SkIRect cull_rect = {11, 11, 21, 21}; DisplayListBuilder expected_builder; - expected_builder.DrawRect({20, 20, 30, 30}, DlPaint()); + DlOpReceiver& expected_receiver = ToReceiver(expected_builder); + expected_receiver.drawRect({20, 20, 30, 30}); auto expected = expected_builder.Build(); test(cull_rect, expected); diff --git a/display_list/dl_builder.cc b/display_list/dl_builder.cc new file mode 100644 index 0000000000000..b78145c124f42 --- /dev/null +++ b/display_list/dl_builder.cc @@ -0,0 +1,1619 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/display_list/dl_builder.h" + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_op_flags.h" +#include "flutter/display_list/dl_op_records.h" +#include "flutter/display_list/effects/dl_color_source.h" +#include "flutter/display_list/utils/dl_bounds_accumulator.h" +#include "fml/logging.h" +#include "third_party/skia/include/core/SkScalar.h" + +namespace flutter { + +#define DL_BUILDER_PAGE 4096 + +// CopyV(dst, src,n, src,n, ...) copies any number of typed srcs into dst. +static void CopyV(void* dst) {} + +template +static void CopyV(void* dst, const S* src, int n, Rest&&... rest) { + FML_DCHECK(((uintptr_t)dst & (alignof(S) - 1)) == 0) + << "Expected " << dst << " to be aligned for at least " << alignof(S) + << " bytes."; + // If n is 0, there is nothing to copy into dst from src. + if (n > 0) { + memcpy(dst, src, n * sizeof(S)); + dst = reinterpret_cast(reinterpret_cast(dst) + + n * sizeof(S)); + } + // Repeat for the next items, if any + CopyV(dst, std::forward(rest)...); +} + +static constexpr inline bool is_power_of_two(int value) { + return (value & (value - 1)) == 0; +} + +template +void* DisplayListBuilder::Push(size_t pod, int render_op_inc, Args&&... args) { + size_t size = SkAlignPtr(sizeof(T) + pod); + FML_DCHECK(size < (1 << 24)); + if (used_ + size > allocated_) { + static_assert(is_power_of_two(DL_BUILDER_PAGE), + "This math needs updating for non-pow2."); + // Next greater multiple of DL_BUILDER_PAGE. + allocated_ = (used_ + size + DL_BUILDER_PAGE) & ~(DL_BUILDER_PAGE - 1); + storage_.realloc(allocated_); + FML_DCHECK(storage_.get()); + memset(storage_.get() + used_, 0, allocated_ - used_); + } + FML_DCHECK(used_ + size <= allocated_); + auto op = reinterpret_cast(storage_.get() + used_); + used_ += size; + new (op) T{std::forward(args)...}; + op->type = T::kType; + op->size = size; + render_op_count_ += render_op_inc; + op_index_++; + return op + 1; +} + +sk_sp DisplayListBuilder::Build() { + while (layer_stack_.size() > 1) { + restore(); + } + + size_t bytes = used_; + int count = render_op_count_; + size_t nested_bytes = nested_bytes_; + int nested_count = nested_op_count_; + bool compatible = current_layer_->is_group_opacity_compatible(); + bool is_safe = is_ui_thread_safe_; + bool affects_transparency = current_layer_->affects_transparent_layer(); + + used_ = allocated_ = render_op_count_ = op_index_ = 0; + nested_bytes_ = nested_op_count_ = 0; + is_ui_thread_safe_ = true; + storage_.realloc(bytes); + layer_stack_.pop_back(); + layer_stack_.emplace_back(); + tracker_.reset(); + current_ = DlPaint(); + + return sk_sp(new DisplayList( + std::move(storage_), bytes, count, nested_bytes, nested_count, bounds(), + compatible, is_safe, affects_transparency, rtree())); +} + +DisplayListBuilder::DisplayListBuilder(const SkRect& cull_rect, + bool prepare_rtree) + : tracker_(cull_rect, SkMatrix::I()) { + if (prepare_rtree) { + accumulator_ = std::make_unique(); + } else { + accumulator_ = std::make_unique(); + } + + layer_stack_.emplace_back(); + current_layer_ = &layer_stack_.back(); +} + +DisplayListBuilder::~DisplayListBuilder() { + uint8_t* ptr = storage_.get(); + if (ptr) { + DisplayList::DisposeOps(ptr, ptr + used_); + } +} + +SkISize DisplayListBuilder::GetBaseLayerSize() const { + return tracker_.base_device_cull_rect().roundOut().size(); +} + +SkImageInfo DisplayListBuilder::GetImageInfo() const { + SkISize size = GetBaseLayerSize(); + return SkImageInfo::MakeUnknown(size.width(), size.height()); +} + +void DisplayListBuilder::onSetAntiAlias(bool aa) { + current_.setAntiAlias(aa); + Push(0, 0, aa); +} +void DisplayListBuilder::onSetDither(bool dither) { + current_.setDither(dither); + Push(0, 0, dither); +} +void DisplayListBuilder::onSetInvertColors(bool invert) { + current_.setInvertColors(invert); + Push(0, 0, invert); + UpdateCurrentOpacityCompatibility(); +} +void DisplayListBuilder::onSetStrokeCap(DlStrokeCap cap) { + current_.setStrokeCap(cap); + Push(0, 0, cap); +} +void DisplayListBuilder::onSetStrokeJoin(DlStrokeJoin join) { + current_.setStrokeJoin(join); + Push(0, 0, join); +} +void DisplayListBuilder::onSetDrawStyle(DlDrawStyle style) { + current_.setDrawStyle(style); + Push(0, 0, style); +} +void DisplayListBuilder::onSetStrokeWidth(float width) { + current_.setStrokeWidth(width); + Push(0, 0, width); +} +void DisplayListBuilder::onSetStrokeMiter(float limit) { + current_.setStrokeMiter(limit); + Push(0, 0, limit); +} +void DisplayListBuilder::onSetColor(DlColor color) { + current_.setColor(color); + Push(0, 0, color); +} +void DisplayListBuilder::onSetBlendMode(DlBlendMode mode) { + current_.setBlendMode(mode); + Push(0, 0, mode); + UpdateCurrentOpacityCompatibility(); +} + +void DisplayListBuilder::onSetColorSource(const DlColorSource* source) { + if (source == nullptr) { + current_.setColorSource(nullptr); + Push(0, 0); + } else { + current_.setColorSource(source->shared()); + is_ui_thread_safe_ = is_ui_thread_safe_ && source->isUIThreadSafe(); + switch (source->type()) { + case DlColorSourceType::kColor: { + const DlColorColorSource* color_source = source->asColor(); + current_.setColorSource(nullptr); + setColor(color_source->color()); + break; + } + case DlColorSourceType::kImage: { + const DlImageColorSource* image_source = source->asImage(); + FML_DCHECK(image_source); + Push(0, 0, image_source); + break; + } + case DlColorSourceType::kLinearGradient: { + const DlLinearGradientColorSource* linear = source->asLinearGradient(); + FML_DCHECK(linear); + void* pod = Push(linear->size(), 0); + new (pod) DlLinearGradientColorSource(linear); + break; + } + case DlColorSourceType::kRadialGradient: { + const DlRadialGradientColorSource* radial = source->asRadialGradient(); + FML_DCHECK(radial); + void* pod = Push(radial->size(), 0); + new (pod) DlRadialGradientColorSource(radial); + break; + } + case DlColorSourceType::kConicalGradient: { + const DlConicalGradientColorSource* conical = + source->asConicalGradient(); + FML_DCHECK(conical); + void* pod = Push(conical->size(), 0); + new (pod) DlConicalGradientColorSource(conical); + break; + } + case DlColorSourceType::kSweepGradient: { + const DlSweepGradientColorSource* sweep = source->asSweepGradient(); + FML_DCHECK(sweep); + void* pod = Push(sweep->size(), 0); + new (pod) DlSweepGradientColorSource(sweep); + break; + } + case DlColorSourceType::kRuntimeEffect: { + const DlRuntimeEffectColorSource* effect = source->asRuntimeEffect(); + FML_DCHECK(effect); + Push(0, 0, effect); + break; + } +#ifdef IMPELLER_ENABLE_3D + case DlColorSourceType::kScene: { + const DlSceneColorSource* scene = source->asScene(); + FML_DCHECK(scene); + Push(0, 0, scene); + break; + } +#endif // IMPELLER_ENABLE_3D + } + } +} +void DisplayListBuilder::onSetImageFilter(const DlImageFilter* filter) { + if (filter == nullptr) { + current_.setImageFilter(nullptr); + Push(0, 0); + } else { + current_.setImageFilter(filter->shared()); + switch (filter->type()) { + case DlImageFilterType::kBlur: { + const DlBlurImageFilter* blur_filter = filter->asBlur(); + FML_DCHECK(blur_filter); + void* pod = Push(blur_filter->size(), 0); + new (pod) DlBlurImageFilter(blur_filter); + break; + } + case DlImageFilterType::kDilate: { + const DlDilateImageFilter* dilate_filter = filter->asDilate(); + FML_DCHECK(dilate_filter); + void* pod = Push(dilate_filter->size(), 0); + new (pod) DlDilateImageFilter(dilate_filter); + break; + } + case DlImageFilterType::kErode: { + const DlErodeImageFilter* erode_filter = filter->asErode(); + FML_DCHECK(erode_filter); + void* pod = Push(erode_filter->size(), 0); + new (pod) DlErodeImageFilter(erode_filter); + break; + } + case DlImageFilterType::kMatrix: { + const DlMatrixImageFilter* matrix_filter = filter->asMatrix(); + FML_DCHECK(matrix_filter); + void* pod = Push(matrix_filter->size(), 0); + new (pod) DlMatrixImageFilter(matrix_filter); + break; + } + case DlImageFilterType::kCompose: + case DlImageFilterType::kLocalMatrix: + case DlImageFilterType::kColorFilter: { + Push(0, 0, filter); + break; + } + } + } +} +void DisplayListBuilder::onSetColorFilter(const DlColorFilter* filter) { + if (filter == nullptr) { + current_.setColorFilter(nullptr); + Push(0, 0); + } else { + current_.setColorFilter(filter->shared()); + switch (filter->type()) { + case DlColorFilterType::kBlend: { + const DlBlendColorFilter* blend_filter = filter->asBlend(); + FML_DCHECK(blend_filter); + void* pod = Push(blend_filter->size(), 0); + new (pod) DlBlendColorFilter(blend_filter); + break; + } + case DlColorFilterType::kMatrix: { + const DlMatrixColorFilter* matrix_filter = filter->asMatrix(); + FML_DCHECK(matrix_filter); + void* pod = Push(matrix_filter->size(), 0); + new (pod) DlMatrixColorFilter(matrix_filter); + break; + } + case DlColorFilterType::kSrgbToLinearGamma: { + void* pod = Push(filter->size(), 0); + new (pod) DlSrgbToLinearGammaColorFilter(); + break; + } + case DlColorFilterType::kLinearToSrgbGamma: { + void* pod = Push(filter->size(), 0); + new (pod) DlLinearToSrgbGammaColorFilter(); + break; + } + } + } + UpdateCurrentOpacityCompatibility(); +} +void DisplayListBuilder::onSetPathEffect(const DlPathEffect* effect) { + if (effect == nullptr) { + current_.setPathEffect(nullptr); + Push(0, 0); + } else { + current_.setPathEffect(effect->shared()); + switch (effect->type()) { + case DlPathEffectType::kDash: { + const DlDashPathEffect* dash_effect = effect->asDash(); + void* pod = Push(dash_effect->size(), 0); + new (pod) DlDashPathEffect(dash_effect); + break; + } + } + } +} +void DisplayListBuilder::onSetMaskFilter(const DlMaskFilter* filter) { + if (filter == nullptr) { + current_.setMaskFilter(nullptr); + Push(0, 0); + } else { + current_.setMaskFilter(filter->shared()); + switch (filter->type()) { + case DlMaskFilterType::kBlur: { + const DlBlurMaskFilter* blur_filter = filter->asBlur(); + FML_DCHECK(blur_filter); + void* pod = Push(blur_filter->size(), 0); + new (pod) DlBlurMaskFilter(blur_filter); + break; + } + } + } +} + +void DisplayListBuilder::SetAttributesFromPaint( + const DlPaint& paint, + const DisplayListAttributeFlags flags) { + if (flags.applies_anti_alias()) { + setAntiAlias(paint.isAntiAlias()); + } + if (flags.applies_dither()) { + setDither(paint.isDither()); + } + if (flags.applies_alpha_or_color()) { + setColor(paint.getColor().argb); + } + if (flags.applies_blend()) { + setBlendMode(paint.getBlendMode()); + } + if (flags.applies_style()) { + setDrawStyle(paint.getDrawStyle()); + } + if (flags.is_stroked(paint.getDrawStyle())) { + setStrokeWidth(paint.getStrokeWidth()); + setStrokeMiter(paint.getStrokeMiter()); + setStrokeCap(paint.getStrokeCap()); + setStrokeJoin(paint.getStrokeJoin()); + } + if (flags.applies_shader()) { + setColorSource(paint.getColorSource().get()); + } + if (flags.applies_color_filter()) { + setInvertColors(paint.isInvertColors()); + setColorFilter(paint.getColorFilter().get()); + } + if (flags.applies_image_filter()) { + setImageFilter(paint.getImageFilter().get()); + } + if (flags.applies_path_effect()) { + setPathEffect(paint.getPathEffect().get()); + } + if (flags.applies_mask_filter()) { + setMaskFilter(paint.getMaskFilter().get()); + } +} + +void DisplayListBuilder::checkForDeferredSave() { + if (current_layer_->has_deferred_save_op_) { + size_t save_offset_ = used_; + Push(0, 1); + current_layer_->save_offset_ = save_offset_; + current_layer_->has_deferred_save_op_ = false; + } +} + +void DisplayListBuilder::Save() { + bool is_nop = current_layer_->is_nop_; + layer_stack_.emplace_back(); + current_layer_ = &layer_stack_.back(); + current_layer_->has_deferred_save_op_ = true; + current_layer_->is_nop_ = is_nop; + tracker_.save(); + accumulator()->save(); +} + +void DisplayListBuilder::Restore() { + if (layer_stack_.size() > 1) { + SaveOpBase* op = reinterpret_cast( + storage_.get() + current_layer_->save_offset()); + if (!current_layer_->has_deferred_save_op_) { + op->restore_index = op_index_; + Push(0, 1); + } + // Grab the current layer info before we push the restore + // on the stack. + LayerInfo layer_info = layer_stack_.back(); + + tracker_.restore(); + layer_stack_.pop_back(); + current_layer_ = &layer_stack_.back(); + bool is_unbounded = layer_info.is_unbounded(); + + // Before we pop_back we will get the current layer bounds from the + // current accumulator and adjust it as required based on the filter. + std::shared_ptr filter = layer_info.filter(); + if (filter) { + const SkRect clip = tracker_.device_cull_rect(); + if (!accumulator()->restore( + [filter = filter, matrix = GetTransform()](const SkRect& input, + SkRect& output) { + SkIRect output_bounds; + bool ret = filter->map_device_bounds(input.roundOut(), matrix, + output_bounds); + output.set(output_bounds); + return ret; + }, + &clip)) { + is_unbounded = true; + } + } else { + accumulator()->restore(); + } + + if (is_unbounded) { + AccumulateUnbounded(); + } + + if (layer_info.has_layer()) { + // Layers are never deferred for now, we need to update the + // following code if we ever do saveLayer culling... + FML_DCHECK(!layer_info.has_deferred_save_op_); + if (layer_info.is_group_opacity_compatible()) { + // We are now going to go back and modify the matching saveLayer + // call to add the option indicating it can distribute an opacity + // value to its children. + // + // Note that this operation cannot and does not change the size + // or structure of the SaveLayerOp record. It only sets an option + // flag on an existing field. + // + // Note that these kinds of modification operations on data already + // in the DisplayList are only allowed *during* the build phase. + // Once built, the DisplayList records must remain read only to + // ensure consistency of rendering and |Equals()| behavior. + op->options = op->options.with_can_distribute_opacity(); + } + } else { + // For regular save() ops there was no protecting layer so we have to + // accumulate the values into the enclosing layer. + if (layer_info.cannot_inherit_opacity()) { + current_layer_->mark_incompatible(); + } else if (layer_info.has_compatible_op()) { + current_layer_->add_compatible_op(); + } + } + } +} +void DisplayListBuilder::RestoreToCount(int restore_count) { + FML_DCHECK(restore_count <= GetSaveCount()); + while (restore_count < GetSaveCount() && GetSaveCount() > 1) { + restore(); + } +} +void DisplayListBuilder::saveLayer(const SkRect* bounds, + const SaveLayerOptions in_options, + const DlImageFilter* backdrop) { + SaveLayerOptions options = in_options.without_optimizations(); + DisplayListAttributeFlags flags = options.renders_with_attributes() + ? kSaveLayerWithPaintFlags + : kSaveLayerFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + save(); + current_layer_->is_nop_ = true; + return; + } + size_t save_layer_offset = used_; + if (options.renders_with_attributes()) { + // The actual flood of the outer layer clip will occur after the + // (eventual) corresponding restore is called, but rather than + // remember this information in the LayerInfo until the restore + // method is processed, we just mark the unbounded state up front. + // Another reason to accumulate the clip here rather than in + // restore is so that this savelayer will be tagged in the rtree + // with its full bounds and the right op_index so that it doesn't + // get culled during rendering. + if (!paint_nops_on_transparency()) { + // We will fill the clip of the outer layer when we restore. + // Accumulate should always return true here because if the + // clip was empty then that would have been caught up above + // when we tested the PaintResult. + [[maybe_unused]] bool unclipped = AccumulateUnbounded(); + FML_DCHECK(unclipped); + } + CheckLayerOpacityCompatibility(true); + layer_stack_.emplace_back(save_layer_offset, true, + current_.getImageFilter()); + } else { + CheckLayerOpacityCompatibility(false); + layer_stack_.emplace_back(save_layer_offset, true, nullptr); + } + current_layer_ = &layer_stack_.back(); + + tracker_.save(); + accumulator()->save(); + + if (backdrop) { + // A backdrop will affect up to the entire surface, bounded by the clip + // Accumulate should always return true here because if the + // clip was empty then that would have been caught up above + // when we tested the PaintResult. + [[maybe_unused]] bool unclipped = AccumulateUnbounded(); + FML_DCHECK(unclipped); + bounds // + ? Push(0, 1, options, *bounds, backdrop) + : Push(0, 1, options, backdrop); + } else { + bounds // + ? Push(0, 1, options, *bounds) + : Push(0, 1, options); + } + + if (options.renders_with_attributes()) { + // |current_opacity_compatibility_| does not take an ImageFilter into + // account because an individual primitive with an ImageFilter can apply + // opacity on top of it. But, if the layer is applying the ImageFilter + // then it cannot pass the opacity on. + if (!current_opacity_compatibility_ || + current_.getImageFilter() != nullptr) { + UpdateLayerOpacityCompatibility(false); + } + } + UpdateLayerResult(result); + + if (options.renders_with_attributes() && current_.getImageFilter()) { + // We use |resetCullRect| here because we will be accumulating bounds of + // primitives before applying the filter to those bounds. We might + // encounter a primitive whose bounds are clipped, but whose filtered + // bounds will not be clipped. If the individual rendering ops bounds + // are clipped, it will not contribute to the overall bounds which + // could lead to inaccurate (subset) bounds of the DisplayList. + // We need to reset the cull rect here to avoid this premature clipping. + // The filtered bounds will be clipped to the existing clip rect when + // this layer is restored. + // If bounds is null then the original cull_rect will be used. + tracker_.resetCullRect(bounds); + } else if (bounds) { + // Even though Skia claims that the bounds are only a hint, they actually + // use them as the temporary layer bounds during rendering the layer, so + // we set them as if a clip operation were performed. + tracker_.clipRect(*bounds, ClipOp::kIntersect, false); + } +} +void DisplayListBuilder::SaveLayer(const SkRect* bounds, + const DlPaint* paint, + const DlImageFilter* backdrop) { + if (paint != nullptr) { + SetAttributesFromPaint(*paint, + DisplayListOpFlags::kSaveLayerWithPaintFlags); + saveLayer(bounds, SaveLayerOptions::kWithAttributes, backdrop); + } else { + saveLayer(bounds, SaveLayerOptions::kNoAttributes, backdrop); + } +} + +void DisplayListBuilder::Translate(SkScalar tx, SkScalar ty) { + if (SkScalarIsFinite(tx) && SkScalarIsFinite(ty) && + (tx != 0.0 || ty != 0.0)) { + checkForDeferredSave(); + Push(0, 1, tx, ty); + tracker_.translate(tx, ty); + } +} +void DisplayListBuilder::Scale(SkScalar sx, SkScalar sy) { + if (SkScalarIsFinite(sx) && SkScalarIsFinite(sy) && + (sx != 1.0 || sy != 1.0)) { + checkForDeferredSave(); + Push(0, 1, sx, sy); + tracker_.scale(sx, sy); + } +} +void DisplayListBuilder::Rotate(SkScalar degrees) { + if (SkScalarMod(degrees, 360.0) != 0.0) { + checkForDeferredSave(); + Push(0, 1, degrees); + tracker_.rotate(degrees); + } +} +void DisplayListBuilder::Skew(SkScalar sx, SkScalar sy) { + if (SkScalarIsFinite(sx) && SkScalarIsFinite(sy) && + (sx != 0.0 || sy != 0.0)) { + checkForDeferredSave(); + Push(0, 1, sx, sy); + tracker_.skew(sx, sy); + } +} + +// clang-format off + +// 2x3 2D affine subset of a 4x4 transform in row major order +void DisplayListBuilder::Transform2DAffine( + SkScalar mxx, SkScalar mxy, SkScalar mxt, + SkScalar myx, SkScalar myy, SkScalar myt) { + if (SkScalarsAreFinite(mxx, myx) && + SkScalarsAreFinite(mxy, myy) && + SkScalarsAreFinite(mxt, myt)) { + if (mxx == 1 && mxy == 0 && + myx == 0 && myy == 1) { + Translate(mxt, myt); + } else { + checkForDeferredSave(); + Push(0, 1, + mxx, mxy, mxt, + myx, myy, myt); + tracker_.transform2DAffine(mxx, mxy, mxt, + myx, myy, myt); + } + } +} +// full 4x4 transform in row major order +void DisplayListBuilder::TransformFullPerspective( + SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, + SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, + SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, + SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) { + if ( mxz == 0 && + myz == 0 && + mzx == 0 && mzy == 0 && mzz == 1 && mzt == 0 && + mwx == 0 && mwy == 0 && mwz == 0 && mwt == 1) { + Transform2DAffine(mxx, mxy, mxt, + myx, myy, myt); + } else if (SkScalarsAreFinite(mxx, mxy) && SkScalarsAreFinite(mxz, mxt) && + SkScalarsAreFinite(myx, myy) && SkScalarsAreFinite(myz, myt) && + SkScalarsAreFinite(mzx, mzy) && SkScalarsAreFinite(mzz, mzt) && + SkScalarsAreFinite(mwx, mwy) && SkScalarsAreFinite(mwz, mwt)) { + checkForDeferredSave(); + Push(0, 1, + mxx, mxy, mxz, mxt, + myx, myy, myz, myt, + mzx, mzy, mzz, mzt, + mwx, mwy, mwz, mwt); + tracker_.transformFullPerspective(mxx, mxy, mxz, mxt, + myx, myy, myz, myt, + mzx, mzy, mzz, mzt, + mwx, mwy, mwz, mwt); + } +} +// clang-format on +void DisplayListBuilder::TransformReset() { + checkForDeferredSave(); + Push(0, 0); + tracker_.setIdentity(); +} +void DisplayListBuilder::Transform(const SkMatrix* matrix) { + if (matrix != nullptr) { + Transform(SkM44(*matrix)); + } +} +void DisplayListBuilder::Transform(const SkM44* m44) { + if (m44 != nullptr) { + transformFullPerspective( + m44->rc(0, 0), m44->rc(0, 1), m44->rc(0, 2), m44->rc(0, 3), + m44->rc(1, 0), m44->rc(1, 1), m44->rc(1, 2), m44->rc(1, 3), + m44->rc(2, 0), m44->rc(2, 1), m44->rc(2, 2), m44->rc(2, 3), + m44->rc(3, 0), m44->rc(3, 1), m44->rc(3, 2), m44->rc(3, 3)); + } +} + +void DisplayListBuilder::ClipRect(const SkRect& rect, + ClipOp clip_op, + bool is_aa) { + if (!rect.isFinite()) { + return; + } + tracker_.clipRect(rect, clip_op, is_aa); + if (current_layer_->is_nop_ || tracker_.is_cull_rect_empty()) { + current_layer_->is_nop_ = true; + return; + } + checkForDeferredSave(); + switch (clip_op) { + case ClipOp::kIntersect: + Push(0, 1, rect, is_aa); + break; + case ClipOp::kDifference: + Push(0, 1, rect, is_aa); + break; + } +} +void DisplayListBuilder::ClipRRect(const SkRRect& rrect, + ClipOp clip_op, + bool is_aa) { + if (rrect.isRect()) { + clipRect(rrect.rect(), clip_op, is_aa); + } else { + tracker_.clipRRect(rrect, clip_op, is_aa); + if (current_layer_->is_nop_ || tracker_.is_cull_rect_empty()) { + current_layer_->is_nop_ = true; + return; + } + checkForDeferredSave(); + switch (clip_op) { + case ClipOp::kIntersect: + Push(0, 1, rrect, is_aa); + break; + case ClipOp::kDifference: + Push(0, 1, rrect, is_aa); + break; + } + } +} +void DisplayListBuilder::ClipPath(const SkPath& path, + ClipOp clip_op, + bool is_aa) { + if (!path.isInverseFillType()) { + SkRect rect; + if (path.isRect(&rect)) { + this->clipRect(rect, clip_op, is_aa); + return; + } + SkRRect rrect; + if (path.isOval(&rect)) { + rrect.setOval(rect); + this->clipRRect(rrect, clip_op, is_aa); + return; + } + if (path.isRRect(&rrect)) { + this->clipRRect(rrect, clip_op, is_aa); + return; + } + } + tracker_.clipPath(path, clip_op, is_aa); + if (current_layer_->is_nop_ || tracker_.is_cull_rect_empty()) { + current_layer_->is_nop_ = true; + return; + } + checkForDeferredSave(); + switch (clip_op) { + case ClipOp::kIntersect: + Push(0, 1, path, is_aa); + break; + case ClipOp::kDifference: + Push(0, 1, path, is_aa); + break; + } +} + +bool DisplayListBuilder::QuickReject(const SkRect& bounds) const { + return tracker_.content_culled(bounds); +} + +void DisplayListBuilder::drawPaint() { + OpResult result = PaintResult(current_, kDrawPaintFlags); + if (result != OpResult::kNoEffect && AccumulateUnbounded()) { + Push(0, 1); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawPaint(const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawPaintFlags); + drawPaint(); +} +void DisplayListBuilder::DrawColor(DlColor color, DlBlendMode mode) { + OpResult result = PaintResult(DlPaint(color).setBlendMode(mode)); + if (result != OpResult::kNoEffect && AccumulateUnbounded()) { + Push(0, 1, color, mode); + CheckLayerOpacityCompatibility(mode); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::drawLine(const SkPoint& p0, const SkPoint& p1) { + SkRect bounds = SkRect::MakeLTRB(p0.fX, p0.fY, p1.fX, p1.fY).makeSorted(); + DisplayListAttributeFlags flags = + (bounds.width() > 0.0f && bounds.height() > 0.0f) ? kDrawLineFlags + : kDrawHVLineFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds, flags)) { + Push(0, 1, p0, p1); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawLine(const SkPoint& p0, + const SkPoint& p1, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawLineFlags); + drawLine(p0, p1); +} +void DisplayListBuilder::drawRect(const SkRect& rect) { + DisplayListAttributeFlags flags = kDrawRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(rect.makeSorted(), flags)) { + Push(0, 1, rect); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawRect(const SkRect& rect, const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRectFlags); + drawRect(rect); +} +void DisplayListBuilder::drawOval(const SkRect& bounds) { + DisplayListAttributeFlags flags = kDrawOvalFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(bounds.makeSorted(), flags)) { + Push(0, 1, bounds); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawOval(const SkRect& bounds, const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawOvalFlags); + drawOval(bounds); +} +void DisplayListBuilder::drawCircle(const SkPoint& center, SkScalar radius) { + DisplayListAttributeFlags flags = kDrawCircleFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect) { + SkRect bounds = SkRect::MakeLTRB(center.fX - radius, center.fY - radius, + center.fX + radius, center.fY + radius); + if (AccumulateOpBounds(bounds, flags)) { + Push(0, 1, center, radius); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } + } +} +void DisplayListBuilder::DrawCircle(const SkPoint& center, + SkScalar radius, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawCircleFlags); + drawCircle(center, radius); +} +void DisplayListBuilder::drawRRect(const SkRRect& rrect) { + if (rrect.isRect()) { + drawRect(rrect.rect()); + } else if (rrect.isOval()) { + drawOval(rrect.rect()); + } else { + DisplayListAttributeFlags flags = kDrawRRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(rrect.getBounds(), flags)) { + Push(0, 1, rrect); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } + } +} +void DisplayListBuilder::DrawRRect(const SkRRect& rrect, const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRRectFlags); + drawRRect(rrect); +} +void DisplayListBuilder::drawDRRect(const SkRRect& outer, + const SkRRect& inner) { + DisplayListAttributeFlags flags = kDrawDRRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(outer.getBounds(), flags)) { + Push(0, 1, outer, inner); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawDRRect(const SkRRect& outer, + const SkRRect& inner, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawDRRectFlags); + drawDRRect(outer, inner); +} +void DisplayListBuilder::drawPath(const SkPath& path) { + DisplayListAttributeFlags flags = kDrawPathFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect) { + bool is_visible = path.isInverseFillType() + ? AccumulateUnbounded() + : AccumulateOpBounds(path.getBounds(), flags); + if (is_visible) { + Push(0, 1, path); + CheckLayerOpacityHairlineCompatibility(); + UpdateLayerResult(result); + } + } +} +void DisplayListBuilder::DrawPath(const SkPath& path, const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawPathFlags); + drawPath(path); +} + +void DisplayListBuilder::drawArc(const SkRect& bounds, + SkScalar start, + SkScalar sweep, + bool useCenter) { + DisplayListAttributeFlags flags = // + useCenter // + ? kDrawArcWithCenterFlags + : kDrawArcNoCenterFlags; + OpResult result = PaintResult(current_, flags); + // This could be tighter if we compute where the start and end + // angles are and then also consider the quadrants swept and + // the center if specified. + if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds, flags)) { + Push(0, 1, bounds, start, sweep, useCenter); + if (useCenter) { + CheckLayerOpacityHairlineCompatibility(); + } else { + CheckLayerOpacityCompatibility(); + } + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawArc(const SkRect& bounds, + SkScalar start, + SkScalar sweep, + bool useCenter, + const DlPaint& paint) { + SetAttributesFromPaint( + paint, useCenter ? kDrawArcWithCenterFlags : kDrawArcNoCenterFlags); + drawArc(bounds, start, sweep, useCenter); +} + +DisplayListAttributeFlags DisplayListBuilder::FlagsForPointMode( + PointMode mode) { + switch (mode) { + case DlCanvas::PointMode::kPoints: + return kDrawPointsAsPointsFlags; + case PointMode::kLines: + return kDrawPointsAsLinesFlags; + case PointMode::kPolygon: + return kDrawPointsAsPolygonFlags; + } + FML_UNREACHABLE(); +} +void DisplayListBuilder::drawPoints(PointMode mode, + uint32_t count, + const SkPoint pts[]) { + if (count == 0) { + return; + } + DisplayListAttributeFlags flags = FlagsForPointMode(mode); + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + + FML_DCHECK(count < DlOpReceiver::kMaxDrawPointsCount); + int bytes = count * sizeof(SkPoint); + RectBoundsAccumulator ptBounds; + for (size_t i = 0; i < count; i++) { + ptBounds.accumulate(pts[i]); + } + SkRect point_bounds = ptBounds.bounds(); + if (!AccumulateOpBounds(point_bounds, flags)) { + return; + } + + void* data_ptr; + switch (mode) { + case PointMode::kPoints: + data_ptr = Push(bytes, 1, count); + break; + case PointMode::kLines: + data_ptr = Push(bytes, 1, count); + break; + case PointMode::kPolygon: + data_ptr = Push(bytes, 1, count); + break; + default: + FML_UNREACHABLE(); + return; + } + CopyV(data_ptr, pts, count); + // drawPoints treats every point or line (or segment of a polygon) + // as a completely separate operation meaning we cannot ensure + // distribution of group opacity without analyzing the mode and the + // bounds of every sub-primitive. + // See: https://fiddle.skia.org/c/228459001d2de8db117ce25ef5cedb0c + UpdateLayerOpacityCompatibility(false); + UpdateLayerResult(result); +} +void DisplayListBuilder::DrawPoints(PointMode mode, + uint32_t count, + const SkPoint pts[], + const DlPaint& paint) { + SetAttributesFromPaint(paint, FlagsForPointMode(mode)); + drawPoints(mode, count, pts); +} +void DisplayListBuilder::drawVertices(const DlVertices* vertices, + DlBlendMode mode) { + DisplayListAttributeFlags flags = kDrawVerticesFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(vertices->bounds(), flags)) { + void* pod = Push(vertices->size(), 1, mode); + new (pod) DlVertices(vertices); + // DrawVertices applies its colors to the paint so we have no way + // of controlling opacity using the current paint attributes. + // Although, examination of the |mode| might find some predictable + // cases. + UpdateLayerOpacityCompatibility(false); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawVertices(const DlVertices* vertices, + DlBlendMode mode, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawVerticesFlags); + drawVertices(vertices, mode); +} + +void DisplayListBuilder::drawImage(const sk_sp image, + const SkPoint point, + DlImageSampling sampling, + bool render_with_attributes) { + DisplayListAttributeFlags flags = render_with_attributes // + ? kDrawImageWithPaintFlags + : kDrawImageFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + SkRect bounds = SkRect::MakeXYWH(point.fX, point.fY, // + image->width(), image->height()); + if (AccumulateOpBounds(bounds, flags)) { + render_with_attributes + ? Push(0, 1, image, point, sampling) + : Push(0, 1, image, point, sampling); + CheckLayerOpacityCompatibility(render_with_attributes); + UpdateLayerResult(result); + is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); + } +} +void DisplayListBuilder::DrawImage(const sk_sp& image, + const SkPoint point, + DlImageSampling sampling, + const DlPaint* paint) { + if (paint != nullptr) { + SetAttributesFromPaint(*paint, + DisplayListOpFlags::kDrawImageWithPaintFlags); + drawImage(image, point, sampling, true); + } else { + drawImage(image, point, sampling, false); + } +} +void DisplayListBuilder::drawImageRect(const sk_sp image, + const SkRect& src, + const SkRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + SrcRectConstraint constraint) { + DisplayListAttributeFlags flags = render_with_attributes + ? kDrawImageRectWithPaintFlags + : kDrawImageRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && AccumulateOpBounds(dst, flags)) { + Push(0, 1, image, src, dst, sampling, + render_with_attributes, constraint); + CheckLayerOpacityCompatibility(render_with_attributes); + UpdateLayerResult(result); + is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); + } +} +void DisplayListBuilder::DrawImageRect(const sk_sp& image, + const SkRect& src, + const SkRect& dst, + DlImageSampling sampling, + const DlPaint* paint, + SrcRectConstraint constraint) { + if (paint != nullptr) { + SetAttributesFromPaint(*paint, + DisplayListOpFlags::kDrawImageRectWithPaintFlags); + drawImageRect(image, src, dst, sampling, true, constraint); + } else { + drawImageRect(image, src, dst, sampling, false, constraint); + } +} +void DisplayListBuilder::drawImageNine(const sk_sp image, + const SkIRect& center, + const SkRect& dst, + DlFilterMode filter, + bool render_with_attributes) { + DisplayListAttributeFlags flags = render_with_attributes + ? kDrawImageNineWithPaintFlags + : kDrawImageNineFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && AccumulateOpBounds(dst, flags)) { + render_with_attributes + ? Push(0, 1, image, center, dst, filter) + : Push(0, 1, image, center, dst, filter); + CheckLayerOpacityCompatibility(render_with_attributes); + UpdateLayerResult(result); + is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); + } +} +void DisplayListBuilder::DrawImageNine(const sk_sp& image, + const SkIRect& center, + const SkRect& dst, + DlFilterMode filter, + const DlPaint* paint) { + if (paint != nullptr) { + SetAttributesFromPaint(*paint, + DisplayListOpFlags::kDrawImageNineWithPaintFlags); + drawImageNine(image, center, dst, filter, true); + } else { + drawImageNine(image, center, dst, filter, false); + } +} +void DisplayListBuilder::drawAtlas(const sk_sp atlas, + const SkRSXform xform[], + const SkRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const SkRect* cull_rect, + bool render_with_attributes) { + DisplayListAttributeFlags flags = render_with_attributes // + ? kDrawAtlasWithPaintFlags + : kDrawAtlasFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + SkPoint quad[4]; + RectBoundsAccumulator atlasBounds; + for (int i = 0; i < count; i++) { + const SkRect& src = tex[i]; + xform[i].toQuad(src.width(), src.height(), quad); + for (int j = 0; j < 4; j++) { + atlasBounds.accumulate(quad[j]); + } + } + if (atlasBounds.is_empty() || + !AccumulateOpBounds(atlasBounds.bounds(), flags)) { + return; + } + + int bytes = count * (sizeof(SkRSXform) + sizeof(SkRect)); + void* data_ptr; + if (colors != nullptr) { + bytes += count * sizeof(DlColor); + if (cull_rect != nullptr) { + data_ptr = + Push(bytes, 1, atlas, count, mode, sampling, true, + *cull_rect, render_with_attributes); + } else { + data_ptr = Push(bytes, 1, atlas, count, mode, sampling, true, + render_with_attributes); + } + CopyV(data_ptr, xform, count, tex, count, colors, count); + } else { + if (cull_rect != nullptr) { + data_ptr = + Push(bytes, 1, atlas, count, mode, sampling, false, + *cull_rect, render_with_attributes); + } else { + data_ptr = Push(bytes, 1, atlas, count, mode, sampling, + false, render_with_attributes); + } + CopyV(data_ptr, xform, count, tex, count); + } + // drawAtlas treats each image as a separate operation so we cannot rely + // on it to distribute the opacity without overlap without checking all + // of the transforms and texture rectangles. + UpdateLayerOpacityCompatibility(false); + UpdateLayerResult(result); + is_ui_thread_safe_ = is_ui_thread_safe_ && atlas->isUIThreadSafe(); +} +void DisplayListBuilder::DrawAtlas(const sk_sp& atlas, + const SkRSXform xform[], + const SkRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const SkRect* cull_rect, + const DlPaint* paint) { + if (paint != nullptr) { + SetAttributesFromPaint(*paint, + DisplayListOpFlags::kDrawAtlasWithPaintFlags); + drawAtlas(atlas, xform, tex, colors, count, mode, sampling, cull_rect, + true); + } else { + drawAtlas(atlas, xform, tex, colors, count, mode, sampling, cull_rect, + false); + } +} + +void DisplayListBuilder::DrawDisplayList(const sk_sp display_list, + SkScalar opacity) { + if (!SkScalarIsFinite(opacity) || opacity <= SK_ScalarNearlyZero || + display_list->op_count() == 0 || display_list->bounds().isEmpty() || + current_layer_->is_nop_) { + return; + } + const SkRect bounds = display_list->bounds(); + bool accumulated; + switch (accumulator()->type()) { + case BoundsAccumulatorType::kRect: + accumulated = AccumulateOpBounds(bounds, kDrawDisplayListFlags); + break; + case BoundsAccumulatorType::kRTree: + auto rtree = display_list->rtree(); + if (rtree) { + std::list rects = + rtree->searchAndConsolidateRects(bounds, false); + accumulated = false; + for (const SkRect& rect : rects) { + // TODO (https://github.com/flutter/flutter/issues/114919): Attributes + // are not necessarily `kDrawDisplayListFlags`. + if (AccumulateOpBounds(rect, kDrawDisplayListFlags)) { + accumulated = true; + } + } + } else { + accumulated = AccumulateOpBounds(bounds, kDrawDisplayListFlags); + } + break; + } + if (!accumulated) { + return; + } + + DlPaint current_paint = current_; + Push(0, 1, display_list, + opacity < SK_Scalar1 ? opacity : SK_Scalar1); + is_ui_thread_safe_ = is_ui_thread_safe_ && display_list->isUIThreadSafe(); + // Not really necessary if the developer is interacting with us via + // our attribute-state-less DlCanvas methods, but this avoids surprises + // for those who may have been using the stateful Dispatcher methods. + SetAttributesFromPaint(current_paint, + DisplayListOpFlags::kSaveLayerWithPaintFlags); + + // The non-nested op count accumulated in the |Push| method will include + // this call to |drawDisplayList| for non-nested op count metrics. + // But, for nested op count metrics we want the |drawDisplayList| call itself + // to be transparent. So we subtract 1 from our accumulated nested count to + // balance out against the 1 that was accumulated into the regular count. + // This behavior is identical to the way SkPicture computed nested op counts. + nested_op_count_ += display_list->op_count(true) - 1; + nested_bytes_ += display_list->bytes(true); + UpdateLayerOpacityCompatibility(display_list->can_apply_group_opacity()); + // Nop DisplayLists are eliminated above so we either affect transparent + // pixels or we do not. We should not have [kNoEffect]. + UpdateLayerResult(display_list->modifies_transparent_black() + ? OpResult::kAffectsAll + : OpResult::kPreservesTransparency); +} +void DisplayListBuilder::drawTextBlob(const sk_sp blob, + SkScalar x, + SkScalar y) { + DisplayListAttributeFlags flags = kDrawTextBlobFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + bool unclipped = AccumulateOpBounds(blob->bounds().makeOffset(x, y), flags); + // TODO(https://github.com/flutter/flutter/issues/82202): Remove once the + // unit tests can use Fuchsia's font manager instead of the empty default. + // Until then we might encounter empty bounds for otherwise valid text and + // thus we ignore the results from AccumulateOpBounds. +#if defined(OS_FUCHSIA) + unclipped = true; +#endif // OS_FUCHSIA + if (unclipped) { + Push(0, 1, blob, x, y); + // There is no way to query if the glyphs of a text blob overlap and + // there are no current guarantees from either Skia or Impeller that + // they will protect overlapping glyphs from the effects of overdraw + // so we must make the conservative assessment that this DL layer is + // not compatible with group opacity inheritance. + UpdateLayerOpacityCompatibility(false); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawTextBlob(const sk_sp& blob, + SkScalar x, + SkScalar y, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawTextBlobFlags); + drawTextBlob(blob, x, y); +} +void DisplayListBuilder::DrawShadow(const SkPath& path, + const DlColor color, + const SkScalar elevation, + bool transparent_occluder, + SkScalar dpr) { + OpResult result = PaintResult(DlPaint(color)); + if (result != OpResult::kNoEffect) { + SkRect shadow_bounds = + DlCanvas::ComputeShadowBounds(path, elevation, dpr, GetTransform()); + if (AccumulateOpBounds(shadow_bounds, kDrawShadowFlags)) { + transparent_occluder // + ? Push(0, 1, path, color, elevation, + dpr) + : Push(0, 1, path, color, elevation, dpr); + UpdateLayerOpacityCompatibility(false); + UpdateLayerResult(result); + } + } +} + +bool DisplayListBuilder::ComputeFilteredBounds(SkRect& bounds, + const DlImageFilter* filter) { + if (filter) { + if (!filter->map_local_bounds(bounds, bounds)) { + return false; + } + } + return true; +} + +bool DisplayListBuilder::AdjustBoundsForPaint(SkRect& bounds, + DisplayListAttributeFlags flags) { + if (flags.ignores_paint()) { + return true; + } + + if (flags.is_geometric()) { + bool is_stroked = flags.is_stroked(current_.getDrawStyle()); + + // Path effect occurs before stroking... + DisplayListSpecialGeometryFlags special_flags = + flags.WithPathEffect(current_.getPathEffectPtr(), is_stroked); + if (current_.getPathEffect()) { + auto effect_bounds = current_.getPathEffect()->effect_bounds(bounds); + if (!effect_bounds.has_value()) { + return false; + } + bounds = effect_bounds.value(); + } + + if (is_stroked) { + // Determine the max multiplier to the stroke width first. + SkScalar pad = 1.0f; + if (current_.getStrokeJoin() == DlStrokeJoin::kMiter && + special_flags.may_have_acute_joins()) { + pad = std::max(pad, current_.getStrokeMiter()); + } + if (current_.getStrokeCap() == DlStrokeCap::kSquare && + special_flags.may_have_diagonal_caps()) { + pad = std::max(pad, SK_ScalarSqrt2); + } + SkScalar min_stroke_width = 0.01; + pad *= std::max(current_.getStrokeWidth() * 0.5f, min_stroke_width); + bounds.outset(pad, pad); + } + } + + if (flags.applies_mask_filter()) { + auto filter = current_.getMaskFilter(); + if (filter) { + switch (filter->type()) { + case DlMaskFilterType::kBlur: { + FML_DCHECK(filter->asBlur()); + SkScalar mask_sigma_pad = filter->asBlur()->sigma() * 3.0; + bounds.outset(mask_sigma_pad, mask_sigma_pad); + } + } + } + } + + if (flags.applies_image_filter()) { + return ComputeFilteredBounds(bounds, current_.getImageFilter().get()); + } + + return true; +} + +bool DisplayListBuilder::AccumulateUnbounded() { + SkRect clip = tracker_.device_cull_rect(); + if (clip.isEmpty()) { + return false; + } + accumulator()->accumulate(clip, op_index_); + return true; +} + +bool DisplayListBuilder::AccumulateOpBounds(SkRect& bounds, + DisplayListAttributeFlags flags) { + if (AdjustBoundsForPaint(bounds, flags)) { + return AccumulateBounds(bounds); + } else { + return AccumulateUnbounded(); + } +} +bool DisplayListBuilder::AccumulateBounds(SkRect& bounds) { + if (!bounds.isEmpty()) { + tracker_.mapRect(&bounds); + if (bounds.intersect(tracker_.device_cull_rect())) { + accumulator()->accumulate(bounds, op_index_); + return true; + } + } + return false; +} + +bool DisplayListBuilder::paint_nops_on_transparency() { + // SkImageFilter::canComputeFastBounds tests for transparency behavior + // This test assumes that the blend mode checked down below will + // NOP on transparent black. + if (current_.getImageFilterPtr() && + current_.getImageFilterPtr()->modifies_transparent_black()) { + return false; + } + + // We filter the transparent black that is used for the background of a + // saveLayer and make sure it returns transparent black. If it does, then + // the color filter will leave all area surrounding the contents of the + // save layer untouched out to the edge of the output surface. + // This test assumes that the blend mode checked down below will + // NOP on transparent black. + if (current_.getColorFilterPtr() && + current_.getColorFilterPtr()->modifies_transparent_black()) { + return false; + } + + // Unusual blendmodes require us to process a saved layer + // even with operations outside the clip. + // For example, DstIn is used by masking layers. + // https://code.google.com/p/skia/issues/detail?id=1291 + // https://crbug.com/401593 + switch (current_.getBlendMode()) { + // For each of the following transfer modes, if the source + // alpha is zero (our transparent black), the resulting + // blended pixel is not necessarily equal to the original + // destination pixel. + // Mathematically, any time in the following equations where + // the result is not d assuming source is 0 + case DlBlendMode::kClear: // r = 0 + case DlBlendMode::kSrc: // r = s + case DlBlendMode::kSrcIn: // r = s * da + case DlBlendMode::kDstIn: // r = d * sa + case DlBlendMode::kSrcOut: // r = s * (1-da) + case DlBlendMode::kDstATop: // r = d*sa + s*(1-da) + case DlBlendMode::kModulate: // r = s*d + return false; + break; + + // And in these equations, the result must be d if the + // source is 0 + case DlBlendMode::kDst: // r = d + case DlBlendMode::kSrcOver: // r = s + (1-sa)*d + case DlBlendMode::kDstOver: // r = d + (1-da)*s + case DlBlendMode::kDstOut: // r = d * (1-sa) + case DlBlendMode::kSrcATop: // r = s*da + d*(1-sa) + case DlBlendMode::kXor: // r = s*(1-da) + d*(1-sa) + case DlBlendMode::kPlus: // r = min(s + d, 1) + case DlBlendMode::kScreen: // r = s + d - s*d + case DlBlendMode::kOverlay: // multiply or screen, depending on dest + case DlBlendMode::kDarken: // rc = s + d - max(s*da, d*sa), + // ra = kSrcOver + case DlBlendMode::kLighten: // rc = s + d - min(s*da, d*sa), + // ra = kSrcOver + case DlBlendMode::kColorDodge: // brighten destination to reflect source + case DlBlendMode::kColorBurn: // darken destination to reflect source + case DlBlendMode::kHardLight: // multiply or screen, depending on source + case DlBlendMode::kSoftLight: // lighten or darken, depending on source + case DlBlendMode::kDifference: // rc = s + d - 2*(min(s*da, d*sa)), + // ra = kSrcOver + case DlBlendMode::kExclusion: // rc = s + d - two(s*d), ra = kSrcOver + case DlBlendMode::kMultiply: // r = s*(1-da) + d*(1-sa) + s*d + case DlBlendMode::kHue: // ra = kSrcOver + case DlBlendMode::kSaturation: // ra = kSrcOver + case DlBlendMode::kColor: // ra = kSrcOver + case DlBlendMode::kLuminosity: // ra = kSrcOver + return true; + break; + } +} + +DlColor DisplayListBuilder::GetEffectiveColor(const DlPaint& paint, + DisplayListAttributeFlags flags) { + DlColor color; + if (flags.applies_color()) { + const DlColorSource* source = paint.getColorSourcePtr(); + if (source) { + if (source->asColor()) { + color = source->asColor()->color(); + } else { + color = source->is_opaque() ? DlColor::kBlack() : kAnyColor; + } + } else { + color = paint.getColor(); + } + } else if (flags.applies_alpha()) { + // If the operation applies alpha, but not color, then the only impact + // of the alpha is to modulate the output towards transparency. + // We can not guarantee an opaque source even if the alpha is opaque + // since that would require knowing something about the colors that + // the alpha is modulating, but we can guarantee a transparent source + // if the alpha is 0. + color = (paint.getAlpha() == 0) ? DlColor::kTransparent() : kAnyColor; + } else { + color = kAnyColor; + } + if (flags.applies_image_filter()) { + auto filter = paint.getImageFilterPtr(); + if (filter) { + if (!color.isTransparent() || filter->modifies_transparent_black()) { + color = kAnyColor; + } + } + } + if (flags.applies_color_filter()) { + auto filter = paint.getColorFilterPtr(); + if (filter) { + if (!color.isTransparent() || filter->modifies_transparent_black()) { + color = kAnyColor; + } + } + } + return color; +} + +DisplayListBuilder::OpResult DisplayListBuilder::PaintResult( + const DlPaint& paint, + DisplayListAttributeFlags flags) { + if (current_layer_->is_nop_) { + return OpResult::kNoEffect; + } + if (flags.applies_blend()) { + switch (paint.getBlendMode()) { + // Nop blend mode (singular, there is only one) + case DlBlendMode::kDst: + return OpResult::kNoEffect; + + // Always clears pixels blend mode (singular, there is only one) + case DlBlendMode::kClear: + return OpResult::kPreservesTransparency; + + case DlBlendMode::kHue: + case DlBlendMode::kSaturation: + case DlBlendMode::kColor: + case DlBlendMode::kLuminosity: + case DlBlendMode::kColorBurn: + return GetEffectiveColor(paint, flags).isTransparent() + ? OpResult::kNoEffect + : OpResult::kAffectsAll; + + // kSrcIn modifies pixels towards transparency + case DlBlendMode::kSrcIn: + return OpResult::kPreservesTransparency; + + // These blend modes preserve destination alpha + case DlBlendMode::kSrcATop: + case DlBlendMode::kDstOut: + return GetEffectiveColor(paint, flags).isTransparent() + ? OpResult::kNoEffect + : OpResult::kPreservesTransparency; + + // Always destructive blend modes, potentially not affecting transparency + case DlBlendMode::kSrc: + case DlBlendMode::kSrcOut: + case DlBlendMode::kDstATop: + return GetEffectiveColor(paint, flags).isTransparent() + ? OpResult::kPreservesTransparency + : OpResult::kAffectsAll; + + // The kDstIn blend mode modifies the destination unless the + // source color is opaque. + case DlBlendMode::kDstIn: + return GetEffectiveColor(paint, flags).isOpaque() + ? OpResult::kNoEffect + : OpResult::kPreservesTransparency; + + // The next group of blend modes modifies the destination unless the + // source color is transparent. + case DlBlendMode::kSrcOver: + case DlBlendMode::kDstOver: + case DlBlendMode::kXor: + case DlBlendMode::kPlus: + case DlBlendMode::kScreen: + case DlBlendMode::kMultiply: + case DlBlendMode::kOverlay: + case DlBlendMode::kDarken: + case DlBlendMode::kLighten: + case DlBlendMode::kColorDodge: + case DlBlendMode::kHardLight: + case DlBlendMode::kSoftLight: + case DlBlendMode::kDifference: + case DlBlendMode::kExclusion: + return GetEffectiveColor(paint, flags).isTransparent() + ? OpResult::kNoEffect + : OpResult::kAffectsAll; + + // Modulate only leaves the pixel alone when the source is white. + case DlBlendMode::kModulate: + return GetEffectiveColor(paint, flags) == DlColor::kWhite() + ? OpResult::kNoEffect + : OpResult::kPreservesTransparency; + } + } + return OpResult::kAffectsAll; +} + +} // namespace flutter diff --git a/display_list/dl_builder.h b/display_list/dl_builder.h new file mode 100644 index 0000000000000..ab0bce0db3c38 --- /dev/null +++ b/display_list/dl_builder.h @@ -0,0 +1,780 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_DISPLAY_LIST_DISPLAY_LIST_BUILDER_H_ +#define FLUTTER_DISPLAY_LIST_DISPLAY_LIST_BUILDER_H_ + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_canvas.h" +#include "flutter/display_list/dl_op_flags.h" +#include "flutter/display_list/dl_op_receiver.h" +#include "flutter/display_list/dl_paint.h" +#include "flutter/display_list/dl_sampling_options.h" +#include "flutter/display_list/effects/dl_path_effect.h" +#include "flutter/display_list/image/dl_image.h" +#include "flutter/display_list/utils/dl_bounds_accumulator.h" +#include "flutter/display_list/utils/dl_comparable.h" +#include "flutter/display_list/utils/dl_matrix_clip_tracker.h" +#include "flutter/fml/macros.h" + +namespace flutter { + +// The primary class used to build a display list. The list of methods +// here matches the list of methods invoked on a |DlOpReceiver| combined +// with the list of methods invoked on a |DlCanvas|. +class DisplayListBuilder final : public virtual DlCanvas, + public SkRefCnt, + virtual DlOpReceiver, + DisplayListOpFlags { + public: + static constexpr SkRect kMaxCullRect = + SkRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F); + + explicit DisplayListBuilder(bool prepare_rtree) + : DisplayListBuilder(kMaxCullRect, prepare_rtree) {} + + explicit DisplayListBuilder(const SkRect& cull_rect = kMaxCullRect, + bool prepare_rtree = false); + + ~DisplayListBuilder(); + + // |DlCanvas| + SkISize GetBaseLayerSize() const override; + // |DlCanvas| + SkImageInfo GetImageInfo() const override; + + // |DlCanvas| + void Save() override; + + // |DlCanvas| + void SaveLayer(const SkRect* bounds, + const DlPaint* paint = nullptr, + const DlImageFilter* backdrop = nullptr) override; + // |DlCanvas| + void Restore() override; + // |DlCanvas| + int GetSaveCount() const override { return layer_stack_.size(); } + // |DlCanvas| + void RestoreToCount(int restore_count) override; + + // |DlCanvas| + void Translate(SkScalar tx, SkScalar ty) override; + // |DlCanvas| + void Scale(SkScalar sx, SkScalar sy) override; + // |DlCanvas| + void Rotate(SkScalar degrees) override; + // |DlCanvas| + void Skew(SkScalar sx, SkScalar sy) override; + + // clang-format off + // 2x3 2D affine subset of a 4x4 transform in row major order + // |DlCanvas| + void Transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, + SkScalar myx, SkScalar myy, SkScalar myt) override; + // full 4x4 transform in row major order + // |DlCanvas| + void TransformFullPerspective( + SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, + SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, + SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, + SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override; + // clang-format on + // |DlCanvas| + void TransformReset() override; + // |DlCanvas| + void Transform(const SkMatrix* matrix) override; + // |DlCanvas| + void Transform(const SkM44* matrix44) override; + // |DlCanvas| + void SetTransform(const SkMatrix* matrix) override { + TransformReset(); + Transform(matrix); + } + // |DlCanvas| + void SetTransform(const SkM44* matrix44) override { + TransformReset(); + Transform(matrix44); + } + using DlCanvas::Transform; + + /// Returns the 4x4 full perspective transform representing all transform + /// operations executed so far in this DisplayList within the enclosing + /// save stack. + // |DlCanvas| + SkM44 GetTransformFullPerspective() const override { + return tracker_.matrix_4x4(); + } + /// Returns the 3x3 partial perspective transform representing all transform + /// operations executed so far in this DisplayList within the enclosing + /// save stack. + // |DlCanvas| + SkMatrix GetTransform() const override { return tracker_.matrix_3x3(); } + + // |DlCanvas| + void ClipRect(const SkRect& rect, + ClipOp clip_op = ClipOp::kIntersect, + bool is_aa = false) override; + // |DlCanvas| + void ClipRRect(const SkRRect& rrect, + ClipOp clip_op = ClipOp::kIntersect, + bool is_aa = false) override; + // |DlCanvas| + void ClipPath(const SkPath& path, + ClipOp clip_op = ClipOp::kIntersect, + bool is_aa = false) override; + + /// Conservative estimate of the bounds of all outstanding clip operations + /// measured in the coordinate space within which this DisplayList will + /// be rendered. + // |DlCanvas| + SkRect GetDestinationClipBounds() const override { + return tracker_.device_cull_rect(); + } + /// Conservative estimate of the bounds of all outstanding clip operations + /// transformed into the local coordinate space in which currently + /// recorded rendering operations are interpreted. + // |DlCanvas| + SkRect GetLocalClipBounds() const override { + return tracker_.local_cull_rect(); + } + + /// Return true iff the supplied bounds are easily shown to be outside + /// of the current clip bounds. This method may conservatively return + /// false if it cannot make the determination. + // |DlCanvas| + bool QuickReject(const SkRect& bounds) const override; + + // |DlCanvas| + void DrawPaint(const DlPaint& paint) override; + // |DlCanvas| + void DrawColor(DlColor color, DlBlendMode mode) override; + // |DlCanvas| + void DrawLine(const SkPoint& p0, + const SkPoint& p1, + const DlPaint& paint) override; + // |DlCanvas| + void DrawRect(const SkRect& rect, const DlPaint& paint) override; + // |DlCanvas| + void DrawOval(const SkRect& bounds, const DlPaint& paint) override; + // |DlCanvas| + void DrawCircle(const SkPoint& center, + SkScalar radius, + const DlPaint& paint) override; + // |DlCanvas| + void DrawRRect(const SkRRect& rrect, const DlPaint& paint) override; + // |DlCanvas| + void DrawDRRect(const SkRRect& outer, + const SkRRect& inner, + const DlPaint& paint) override; + // |DlCanvas| + void DrawPath(const SkPath& path, const DlPaint& paint) override; + // |DlCanvas| + void DrawArc(const SkRect& bounds, + SkScalar start, + SkScalar sweep, + bool useCenter, + const DlPaint& paint) override; + // |DlCanvas| + void DrawPoints(PointMode mode, + uint32_t count, + const SkPoint pts[], + const DlPaint& paint) override; + // |DlCanvas| + void DrawVertices(const DlVertices* vertices, + DlBlendMode mode, + const DlPaint& paint) override; + using DlCanvas::DrawVertices; + // |DlCanvas| + void DrawImage(const sk_sp& image, + const SkPoint point, + DlImageSampling sampling, + const DlPaint* paint = nullptr) override; + // |DlCanvas| + void DrawImageRect( + const sk_sp& image, + const SkRect& src, + const SkRect& dst, + DlImageSampling sampling, + const DlPaint* paint = nullptr, + SrcRectConstraint constraint = SrcRectConstraint::kFast) override; + using DlCanvas::DrawImageRect; + // |DlCanvas| + void DrawImageNine(const sk_sp& image, + const SkIRect& center, + const SkRect& dst, + DlFilterMode filter, + const DlPaint* paint = nullptr) override; + // |DlCanvas| + void DrawAtlas(const sk_sp& atlas, + const SkRSXform xform[], + const SkRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const SkRect* cullRect, + const DlPaint* paint = nullptr) override; + // |DlCanvas| + void DrawDisplayList(const sk_sp display_list, + SkScalar opacity = SK_Scalar1) override; + // |DlCanvas| + void DrawTextBlob(const sk_sp& blob, + SkScalar x, + SkScalar y, + const DlPaint& paint) override; + // |DlCanvas| + void DrawShadow(const SkPath& path, + const DlColor color, + const SkScalar elevation, + bool transparent_occluder, + SkScalar dpr) override; + + // |DlCanvas| + void Flush() override {} + + sk_sp Build(); + + private: + // This method exposes the internal stateful DlOpReceiver implementation + // of the DisplayListBuilder, primarily for testing purposes. Its use + // is obsolete and forbidden in every other case and is only shared to a + // pair of "friend" accessors in the benchmark/unittest files. + DlOpReceiver& asReceiver() { return *this; } + + friend DlOpReceiver& DisplayListBuilderBenchmarkAccessor( + DisplayListBuilder& builder); + friend DlOpReceiver& DisplayListBuilderTestingAccessor( + DisplayListBuilder& builder); + friend DlPaint DisplayListBuilderTestingAttributes( + DisplayListBuilder& builder); + + void SetAttributesFromPaint(const DlPaint& paint, + const DisplayListAttributeFlags flags); + + // |DlOpReceiver| + void setAntiAlias(bool aa) override { + if (current_.isAntiAlias() != aa) { + onSetAntiAlias(aa); + } + } + // |DlOpReceiver| + void setDither(bool dither) override { + if (current_.isDither() != dither) { + onSetDither(dither); + } + } + // |DlOpReceiver| + void setInvertColors(bool invert) override { + if (current_.isInvertColors() != invert) { + onSetInvertColors(invert); + } + } + // |DlOpReceiver| + void setStrokeCap(DlStrokeCap cap) override { + if (current_.getStrokeCap() != cap) { + onSetStrokeCap(cap); + } + } + // |DlOpReceiver| + void setStrokeJoin(DlStrokeJoin join) override { + if (current_.getStrokeJoin() != join) { + onSetStrokeJoin(join); + } + } + // |DlOpReceiver| + void setDrawStyle(DlDrawStyle style) override { + if (current_.getDrawStyle() != style) { + onSetDrawStyle(style); + } + } + // |DlOpReceiver| + void setStrokeWidth(float width) override { + if (current_.getStrokeWidth() != width) { + onSetStrokeWidth(width); + } + } + // |DlOpReceiver| + void setStrokeMiter(float limit) override { + if (current_.getStrokeMiter() != limit) { + onSetStrokeMiter(limit); + } + } + // |DlOpReceiver| + void setColor(DlColor color) override { + if (current_.getColor() != color) { + onSetColor(color); + } + } + // |DlOpReceiver| + void setBlendMode(DlBlendMode mode) override { + if (current_.getBlendMode() != mode) { + onSetBlendMode(mode); + } + } + // |DlOpReceiver| + void setColorSource(const DlColorSource* source) override { + if (NotEquals(current_.getColorSource(), source)) { + onSetColorSource(source); + } + } + // |DlOpReceiver| + void setImageFilter(const DlImageFilter* filter) override { + if (NotEquals(current_.getImageFilter(), filter)) { + onSetImageFilter(filter); + } + } + // |DlOpReceiver| + void setColorFilter(const DlColorFilter* filter) override { + if (NotEquals(current_.getColorFilter(), filter)) { + onSetColorFilter(filter); + } + } + // |DlOpReceiver| + void setPathEffect(const DlPathEffect* effect) override { + if (NotEquals(current_.getPathEffect(), effect)) { + onSetPathEffect(effect); + } + } + // |DlOpReceiver| + void setMaskFilter(const DlMaskFilter* filter) override { + if (NotEquals(current_.getMaskFilter(), filter)) { + onSetMaskFilter(filter); + } + } + + DlPaint CurrentAttributes() const { return current_; } + + // |DlOpReceiver| + void save() override { Save(); } + // Only the |renders_with_attributes()| option will be accepted here. Any + // other flags will be ignored and calculated anew as the DisplayList is + // built. Alternatively, use the |saveLayer(SkRect, bool)| method. + // |DlOpReceiver| + void saveLayer(const SkRect* bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop) override; + // |DlOpReceiver| + void restore() override { Restore(); } + + // |DlOpReceiver| + void translate(SkScalar tx, SkScalar ty) override { Translate(tx, ty); } + // |DlOpReceiver| + void scale(SkScalar sx, SkScalar sy) override { Scale(sx, sy); } + // |DlOpReceiver| + void rotate(SkScalar degrees) override { Rotate(degrees); } + // |DlOpReceiver| + void skew(SkScalar sx, SkScalar sy) override { Skew(sx, sy); } + + // clang-format off + // |DlOpReceiver| + void transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, + SkScalar myx, SkScalar myy, SkScalar myt) override { + Transform2DAffine(mxx, mxy, mxt, myx, myy, myt); + } + // |DlOpReceiver| + void transformFullPerspective( + SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, + SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, + SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, + SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override { + TransformFullPerspective(mxx, mxy, mxz, mxt, + myx, myy, myz, myt, + mzx, mzy, mzz, mzt, + mwx, mwy, mwz, mwt); + } + // clang-format off + // |DlOpReceiver| + void transformReset() override { TransformReset(); } + + // |DlOpReceiver| + void clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) override { + ClipRect(rect, clip_op, is_aa); + } + // |DlOpReceiver| + void clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) override { + ClipRRect(rrect, clip_op, is_aa); + } + // |DlOpReceiver| + void clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) override { + ClipPath(path, clip_op, is_aa); + } + + // |DlOpReceiver| + void drawPaint() override; + // |DlOpReceiver| + void drawColor(DlColor color, DlBlendMode mode) override { + DrawColor(color, mode); + } + // |DlOpReceiver| + void drawLine(const SkPoint& p0, const SkPoint& p1) override; + // |DlOpReceiver| + void drawRect(const SkRect& rect) override; + // |DlOpReceiver| + void drawOval(const SkRect& bounds) override; + // |DlOpReceiver| + void drawCircle(const SkPoint& center, SkScalar radius) override; + // |DlOpReceiver| + void drawRRect(const SkRRect& rrect) override; + // |DlOpReceiver| + void drawDRRect(const SkRRect& outer, const SkRRect& inner) override; + // |DlOpReceiver| + void drawPath(const SkPath& path) override; + // |DlOpReceiver| + void drawArc(const SkRect& bounds, + SkScalar start, + SkScalar sweep, + bool useCenter) override; + // |DlOpReceiver| + void drawPoints(PointMode mode, uint32_t count, const SkPoint pts[]) override; + // |DlOpReceiver| + void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; + + // |DlOpReceiver| + void drawImage(const sk_sp image, + const SkPoint point, + DlImageSampling sampling, + bool render_with_attributes) override; + // |DlOpReceiver| + void drawImageRect( + const sk_sp image, + const SkRect& src, + const SkRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + SrcRectConstraint constraint = SrcRectConstraint::kFast) override; + // |DlOpReceiver| + void drawImageNine(const sk_sp image, + const SkIRect& center, + const SkRect& dst, + DlFilterMode filter, + bool render_with_attributes) override; + // |DlOpReceiver| + void drawAtlas(const sk_sp atlas, + const SkRSXform xform[], + const SkRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const SkRect* cullRect, + bool render_with_attributes) override; + + // |DlOpReceiver| + void drawDisplayList(const sk_sp display_list, + SkScalar opacity) override { + DrawDisplayList(display_list, opacity); + } + // |DlOpReceiver| + void drawTextBlob(const sk_sp blob, + SkScalar x, + SkScalar y) override; + // |DlOpReceiver| + void drawShadow(const SkPath& path, + const DlColor color, + const SkScalar elevation, + bool transparent_occluder, + SkScalar dpr) override { + DrawShadow(path, color, elevation, transparent_occluder, dpr); + } + + void checkForDeferredSave(); + + DisplayListStorage storage_; + size_t used_ = 0; + size_t allocated_ = 0; + int render_op_count_ = 0; + int op_index_ = 0; + + // bytes and ops from |drawPicture| and |drawDisplayList| + size_t nested_bytes_ = 0; + int nested_op_count_ = 0; + + bool is_ui_thread_safe_ = true; + + template + void* Push(size_t extra, int op_inc, Args&&... args); + + void intersect(const SkRect& rect); + + // kInvalidSigma is used to indicate that no MaskBlur is currently set. + static constexpr SkScalar kInvalidSigma = 0.0; + static bool mask_sigma_valid(SkScalar sigma) { + return SkScalarIsFinite(sigma) && sigma > 0.0; + } + + class LayerInfo { + public: + explicit LayerInfo( + size_t save_offset = 0, + bool has_layer = false, + const std::shared_ptr& filter = nullptr) + : save_offset_(save_offset), + has_layer_(has_layer), + filter_(filter) {} + + // The offset into the memory buffer where the saveLayer DLOp record + // for this saveLayer() call is placed. This may be needed if the + // eventual restore() call has discovered important information about + // the records inside the saveLayer that may impact how the saveLayer + // is handled (e.g., |cannot_inherit_opacity| == false). + // This offset is only valid if |has_layer| is true. + size_t save_offset() const { return save_offset_; } + + bool has_layer() const { return has_layer_; } + bool cannot_inherit_opacity() const { return cannot_inherit_opacity_; } + bool has_compatible_op() const { return has_compatible_op_; } + bool affects_transparent_layer() const { + return affects_transparent_layer_; + } + + bool is_group_opacity_compatible() const { + return !cannot_inherit_opacity_; + } + + void mark_incompatible() { cannot_inherit_opacity_ = true; } + + // For now this only allows a single compatible op to mark the + // layer as being compatible with group opacity. If we start + // computing bounds of ops in the Builder methods then we + // can upgrade this to checking for overlapping ops. + // See https://github.com/flutter/flutter/issues/93899 + void add_compatible_op() { + if (!cannot_inherit_opacity_) { + if (has_compatible_op_) { + cannot_inherit_opacity_ = true; + } else { + has_compatible_op_ = true; + } + } + } + + // Records that the current layer contains an op that produces visible + // output on a transparent surface. + void add_visible_op() { + affects_transparent_layer_ = true; + } + + // The filter to apply to the layer bounds when it is restored + std::shared_ptr filter() { return filter_; } + + // is_unbounded should be set to true if we ever encounter an operation + // on a layer that either is unrestricted (|drawColor| or |drawPaint|) + // or cannot compute its bounds (some effects and filters) and there + // was no outstanding clip op at the time. + // When the layer is restored, the outer layer may then process this + // unbounded state by accumulating its own clip or transferring the + // unbounded state to its own outer layer. + // Typically the DisplayList will have been constructed with a cull + // rect which will act as a default clip for the outermost layer and + // the unbounded state of all sub layers will eventually be caught by + // that cull rect so that the overall unbounded state of the entire + // DisplayList will never be true. + // + // For historical consistency it is worth noting that SkPicture used + // to treat these same conditions as a Nop (they accumulate the + // SkPicture cull rect, but if no cull rect was specified then it is + // an empty Rect and so has no effect on the bounds). + // + // Flutter is unlikely to ever run into this as the Dart mechanisms + // all supply a non-null cull rect for all Dart Picture objects, + // even if that cull rect is kGiantRect. + void set_unbounded() { is_unbounded_ = true; } + + // |is_unbounded| should be called after |getLayerBounds| in case + // a problem was found during the computation of those bounds, + // the layer will have one last chance to flag an unbounded state. + bool is_unbounded() const { return is_unbounded_; } + + private: + size_t save_offset_; + bool has_layer_; + bool cannot_inherit_opacity_ = false; + bool has_compatible_op_ = false; + std::shared_ptr filter_; + bool is_unbounded_ = false; + bool has_deferred_save_op_ = false; + bool is_nop_ = false; + bool affects_transparent_layer_ = false; + + friend class DisplayListBuilder; + }; + + std::vector layer_stack_; + LayerInfo* current_layer_; + DisplayListMatrixClipTracker tracker_; + std::unique_ptr accumulator_; + BoundsAccumulator* accumulator() { return accumulator_.get(); } + + // This flag indicates whether or not the current rendering attributes + // are compatible with rendering ops applying an inherited opacity. + bool current_opacity_compatibility_ = true; + + // Returns the compatibility of a given blend mode for applying an + // inherited opacity value to modulate the visibility of the op. + // For now we only accept SrcOver blend modes but this could be expanded + // in the future to include other (rarely used) modes that also modulate + // the opacity of a rendering operation at the cost of a switch statement + // or lookup table. + static bool IsOpacityCompatible(DlBlendMode mode) { + return (mode == DlBlendMode::kSrcOver); + } + + void UpdateCurrentOpacityCompatibility() { + current_opacity_compatibility_ = // + current_.getColorFilter() == nullptr && // + !current_.isInvertColors() && // + IsOpacityCompatible(current_.getBlendMode()); + } + + // Update the opacity compatibility flags of the current layer for an op + // that has determined its compatibility as indicated by |compatible|. + void UpdateLayerOpacityCompatibility(bool compatible) { + if (compatible) { + current_layer_->add_compatible_op(); + } else { + current_layer_->mark_incompatible(); + } + } + + // Check for opacity compatibility for an op that may or may not use the + // current rendering attributes as indicated by |uses_blend_attribute|. + // If the flag is false then the rendering op will be able to substitute + // a default Paint object with the opacity applied using the default SrcOver + // blend mode which is always compatible with applying an inherited opacity. + void CheckLayerOpacityCompatibility(bool uses_blend_attribute = true) { + UpdateLayerOpacityCompatibility(!uses_blend_attribute || + current_opacity_compatibility_); + } + + void CheckLayerOpacityHairlineCompatibility() { + UpdateLayerOpacityCompatibility( + current_opacity_compatibility_ && + (current_.getDrawStyle() == DlDrawStyle::kFill || + current_.getStrokeWidth() > 0)); + } + + // Check for opacity compatibility for an op that ignores the current + // attributes and uses the indicated blend |mode| to render to the layer. + // This is only used by |drawColor| currently. + void CheckLayerOpacityCompatibility(DlBlendMode mode) { + UpdateLayerOpacityCompatibility(IsOpacityCompatible(mode)); + } + + void onSetAntiAlias(bool aa); + void onSetDither(bool dither); + void onSetInvertColors(bool invert); + void onSetStrokeCap(DlStrokeCap cap); + void onSetStrokeJoin(DlStrokeJoin join); + void onSetDrawStyle(DlDrawStyle style); + void onSetStrokeWidth(SkScalar width); + void onSetStrokeMiter(SkScalar limit); + void onSetColor(DlColor color); + void onSetBlendMode(DlBlendMode mode); + void onSetColorSource(const DlColorSource* source); + void onSetImageFilter(const DlImageFilter* filter); + void onSetColorFilter(const DlColorFilter* filter); + void onSetPathEffect(const DlPathEffect* effect); + void onSetMaskFilter(const DlMaskFilter* filter); + + // The DisplayList had an unbounded call with no cull rect or clip + // to contain it. Should only be called after the stream is fully + // built. + // Unbounded operations are calls like |drawColor| which are defined + // to flood the entire surface, or calls that relied on a rendering + // attribute which is unable to compute bounds (should be rare). + // In those cases the bounds will represent only the accumulation + // of the bounded calls and this flag will be set to indicate that + // condition. + bool is_unbounded() const { + FML_DCHECK(layer_stack_.size() == 1); + return layer_stack_.front().is_unbounded(); + } + + SkRect bounds() const { + FML_DCHECK(layer_stack_.size() == 1); + if (is_unbounded()) { + FML_LOG(INFO) << "returning partial bounds for unbounded DisplayList"; + } + + return accumulator_->bounds(); + } + + sk_sp rtree() { + FML_DCHECK(layer_stack_.size() == 1); + if (is_unbounded()) { + FML_LOG(INFO) << "returning partial rtree for unbounded DisplayList"; + } + + return accumulator_->rtree(); + } + + static DisplayListAttributeFlags FlagsForPointMode(PointMode mode); + + enum class OpResult { + kNoEffect, + kPreservesTransparency, + kAffectsAll, + }; + + bool paint_nops_on_transparency(); + OpResult PaintResult(const DlPaint& paint, + DisplayListAttributeFlags flags = kDrawPaintFlags); + + void UpdateLayerResult(OpResult result) { + switch (result) { + case OpResult::kNoEffect: + case OpResult::kPreservesTransparency: + break; + case OpResult::kAffectsAll: + current_layer_->add_visible_op(); + break; + } + } + + // kAnyColor is a non-opaque and non-transparent color that will not + // trigger any short-circuit tests about the results of a blend. + static constexpr DlColor kAnyColor = DlColor::kMidGrey().withAlpha(0x80); + static_assert(!kAnyColor.isOpaque()); + static_assert(!kAnyColor.isTransparent()); + static DlColor GetEffectiveColor(const DlPaint& paint, + DisplayListAttributeFlags flags); + + // Computes the bounds of an operation adjusted for a given ImageFilter + // and returns whether the computation was possible. If the method + // returns false then the caller should assume the worst about the bounds. + static bool ComputeFilteredBounds(SkRect& bounds, + const DlImageFilter* filter); + + // Adjusts the indicated bounds for the given flags and returns true if + // the calculation was possible, or false if it could not be estimated. + bool AdjustBoundsForPaint(SkRect& bounds, DisplayListAttributeFlags flags); + + // Records the fact that we encountered an op that either could not + // estimate its bounds or that fills all of the destination space. + bool AccumulateUnbounded(); + + // Records the bounds for an op after modifying them according to the + // supplied attribute flags and transforming by the current matrix. + bool AccumulateOpBounds(const SkRect& bounds, + DisplayListAttributeFlags flags) { + SkRect safe_bounds = bounds; + return AccumulateOpBounds(safe_bounds, flags); + } + + // Records the bounds for an op after modifying them according to the + // supplied attribute flags and transforming by the current matrix + // and clipping against the current clip. + bool AccumulateOpBounds(SkRect& bounds, DisplayListAttributeFlags flags); + + // Records the given bounds after transforming by the current matrix + // and clipping against the current clip. + bool AccumulateBounds(SkRect& bounds); + + DlPaint current_; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DISPLAY_LIST_BUILDER_H_ diff --git a/display_list/dl_canvas_to_receiver.cc b/display_list/dl_canvas_to_receiver.cc deleted file mode 100644 index e5d185a46c71a..0000000000000 --- a/display_list/dl_canvas_to_receiver.cc +++ /dev/null @@ -1,1132 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "flutter/display_list/dl_canvas_to_receiver.h" - -#include "flutter/display_list/display_list.h" -#include "flutter/display_list/dl_blend_mode.h" -#include "flutter/display_list/dl_op_flags.h" -#include "flutter/display_list/dl_op_records.h" -#include "flutter/display_list/effects/dl_color_source.h" -#include "flutter/display_list/utils/dl_bounds_accumulator.h" -#include "fml/logging.h" -#include "third_party/skia/include/core/SkScalar.h" - -namespace flutter { - -DlCanvasToReceiver::DlCanvasToReceiver( - std::shared_ptr receiver) - : receiver_(std::move(receiver)) { - layer_stack_.emplace_back(); - current_layer_ = &layer_stack_.back(); -} - -SkISize DlCanvasToReceiver::GetBaseLayerSize() const { - CheckAlive(); - return receiver_->base_device_cull_rect().roundOut().size(); -} - -SkImageInfo DlCanvasToReceiver::GetImageInfo() const { - CheckAlive(); - SkISize size = GetBaseLayerSize(); - return SkImageInfo::MakeUnknown(size.width(), size.height()); -} - -bool DlCanvasToReceiver::SetAttributesFromPaint( - const DlPaint* paint, - const DisplayListAttributeFlags flags) { - if (paint == nullptr) { - return true; - } - - bool can_inherit_opacity = true; - if (flags.applies_anti_alias()) { - bool aa = paint->isAntiAlias(); - if (current_.isAntiAlias() != aa) { - current_.setAntiAlias(aa); - receiver_->setAntiAlias(aa); - } - } - if (flags.applies_dither()) { - bool dither = paint->isDither(); - if (current_.isDither() != dither) { - current_.setDither(dither); - receiver_->setDither(dither); - } - } - if (flags.applies_alpha_or_color()) { - DlColor color = paint->getColor(); - if (current_.getColor() != color) { - current_.setColor(color); - receiver_->setColor(color); - } - } - if (flags.applies_blend()) { - DlBlendMode mode = paint->getBlendMode(); - if (current_.getBlendMode() != mode) { - current_.setBlendMode(mode); - receiver_->setBlendMode(mode); - } - if (!IsOpacityCompatible(mode)) { - can_inherit_opacity = false; - } - } - if (flags.applies_style()) { - DlDrawStyle style = paint->getDrawStyle(); - if (current_.getDrawStyle() != style) { - current_.setDrawStyle(style); - receiver_->setDrawStyle(style); - } - } - if (flags.is_stroked(paint->getDrawStyle())) { - SkScalar width = paint->getStrokeWidth(); - if (current_.getStrokeWidth() != width) { - current_.setStrokeWidth(width); - receiver_->setStrokeWidth(width); - } - if (flags.may_have_trouble_with_hairlines() && width <= 0) { - can_inherit_opacity = false; - } - SkScalar miter = paint->getStrokeMiter(); - if (current_.getStrokeMiter() != miter) { - current_.setStrokeMiter(miter); - receiver_->setStrokeMiter(miter); - } - DlStrokeCap cap = paint->getStrokeCap(); - if (current_.getStrokeCap() != cap) { - current_.setStrokeCap(cap); - receiver_->setStrokeCap(cap); - } - DlStrokeJoin join = paint->getStrokeJoin(); - if (current_.getStrokeJoin() != join) { - current_.setStrokeJoin(join); - receiver_->setStrokeJoin(join); - } - } - if (flags.applies_shader()) { - auto source = paint->getColorSourcePtr(); - if (NotEquals(current_.getColorSourcePtr(), source)) { - current_.setColorSource(paint->getColorSource()); - receiver_->setColorSource(source); - } - } - if (flags.applies_color_filter()) { - bool invert = paint->isInvertColors(); - if (current_.isInvertColors() != invert) { - current_.setInvertColors(invert); - receiver_->setInvertColors(invert); - } - auto filter = paint->getColorFilterPtr(); - if (NotEquals(current_.getColorFilterPtr(), filter)) { - current_.setColorFilter(paint->getColorFilter()); - receiver_->setColorFilter(filter); - } - if (invert || filter) { - can_inherit_opacity = false; - } - } - if (flags.applies_image_filter()) { - auto filter = paint->getImageFilterPtr(); - if (NotEquals(current_.getImageFilterPtr(), filter)) { - current_.setImageFilter(paint->getImageFilter()); - receiver_->setImageFilter(filter); - } - } - if (flags.applies_path_effect()) { - auto effect = paint->getPathEffectPtr(); - if (NotEquals(current_.getPathEffectPtr(), effect)) { - current_.setPathEffect(paint->getPathEffect()); - receiver_->setPathEffect(effect); - } - } - if (flags.applies_mask_filter()) { - auto filter = paint->getMaskFilterPtr(); - if (NotEquals(current_.getMaskFilterPtr(), filter)) { - current_.setMaskFilter(paint->getMaskFilter()); - receiver_->setMaskFilter(filter); - } - } - return can_inherit_opacity; -} - -void DlCanvasToReceiver::Save() { - CheckAlive(); - bool is_nop = current_layer_->state_is_nop_; - layer_stack_.emplace_back(); - current_layer_ = &layer_stack_.back(); - current_layer_->state_is_nop_ = is_nop; - receiver_->save(); -} -void DlCanvasToReceiver::SaveLayer(const SkRect* bounds, - const DlPaint* paint, - const DlImageFilter* backdrop) { - CheckAlive(); - SaveLayerOptions options = paint ? SaveLayerOptions::kWithAttributes // - : SaveLayerOptions::kNoAttributes; - DisplayListAttributeFlags flags = paint ? kSaveLayerWithPaintFlags // - : kSaveLayerFlags; - OpResult result = PaintResult(paint, flags); - if (result == OpResult::kNoEffect) { - Save(); - current_layer_->state_is_nop_ = true; - return; - } - - bool unbounded = false; - if (backdrop) { - // A backdrop will pre-fill up to the entire surface, bounded by - // the clip. - unbounded = true; - } else if (!paint_nops_on_transparency(paint)) { - // The actual flood of the outer layer clip based on the paint - // will occur after the (eventual) corresponding restore is called, - // but rather than remember this information in the LayerInfo - // until the restore method is processed, we just mark the unbounded - // state up front. Another reason to accumulate the clip here rather - // than in restore is so that this savelayer will be tagged in the - // rtree with its full bounds and the right op_index so that it doesn't - // get culled during rendering. - unbounded = true; - } - if (unbounded) { - // Accumulate should always return true here because if the clip - // was empty then that would have been caught up above when we - // tested the PaintResult. - [[maybe_unused]] bool unclipped = AccumulateUnbounded(); - FML_DCHECK(unclipped); - } - - auto image_filter = paint ? paint->getImageFilter() : nullptr; - - bool layer_can_inherit_opacity = SetAttributesFromPaint(paint, flags); - receiver_->saveLayer(bounds, options, backdrop); - current_layer_->Update(result, layer_can_inherit_opacity); - - layer_stack_.emplace_back(true, image_filter); - current_layer_ = &layer_stack_.back(); - - if (image_filter != nullptr || !layer_can_inherit_opacity) { - // The compatibility computed by SetAttributes does not take an - // ImageFilter into account because an individual primitive with - // an ImageFilter can apply opacity on top of it. But, if the layer - // is applying the ImageFilter then it cannot pass the opacity on - // to its children even if they are compatible. - // Also, if a layer cannot itself inherit opacity then it cannot - // pass it along to its children. Arguably this information is - // not interesting because the saveLayer will have informed its - // enclosing layers not to send it an opacity to apply in the - // first place. But some tests check to see if the layer has - // noticed this situation by testing the inheritance property on - // the layer itself. Better tests wouldn't expect this property - // to be recorded there, but we will mark our children incompatible - // to be explicit about this situation. - current_layer_->mark_incompatible(); - } - - if (image_filter != nullptr) { - // We use |resetCullRect| here because we will be accumulating bounds of - // primitives before applying the filter to those bounds. We might - // encounter a primitive whose bounds are clipped, but whose filtered - // bounds will not be clipped. If the individual rendering ops bounds - // are clipped, it will not contribute to the overall bounds which - // could lead to inaccurate (subset) bounds of the DisplayList. - // We need to reset the cull rect here to avoid this premature clipping. - // The filtered bounds will be clipped to the existing clip rect when - // this layer is restored. - // If bounds is null then the original cull_rect will be used. - receiver_->resetCullRect(bounds); - } else if (bounds != nullptr) { - // Even though Skia claims that the bounds are only a hint, they actually - // use them as the temporary layer bounds during rendering the layer, so - // we set them as if a clip operation were performed. - receiver_->intersectCullRect(*bounds); - } -} - -void DlCanvasToReceiver::Restore() { - CheckAlive(); - if (layer_stack_.size() > 1) { - // Grab the current layer info before we push the restore - // on the stack. - LayerInfo layer_info = layer_stack_.back(); - layer_stack_.pop_back(); - current_layer_ = &layer_stack_.back(); - - if (layer_info.has_layer()) { - bool can_distribute_opacity = - layer_info.has_layer() && layer_info.is_group_opacity_compatible(); - receiver_->restoreLayer(layer_info.filter().get(), - layer_info.is_unbounded(), - can_distribute_opacity); - } else { - receiver_->restore(); - - // For regular save() ops there was no protecting layer so we have to - // accumulate the opacity compatibility values into the enclosing layer. - if (layer_info.cannot_inherit_opacity()) { - current_layer_->mark_incompatible(); - } else if (layer_info.has_compatible_op()) { - current_layer_->add_compatible_op(); - } - } - } -} -void DlCanvasToReceiver::RestoreToCount(int restore_count) { - CheckAlive(); - FML_DCHECK(restore_count <= GetSaveCount()); - while (restore_count < GetSaveCount() && GetSaveCount() > 1) { - Restore(); - } -} - -void DlCanvasToReceiver::Translate(SkScalar tx, SkScalar ty) { - CheckAlive(); - if (SkScalarIsFinite(tx) && SkScalarIsFinite(ty) && - (tx != 0.0 || ty != 0.0)) { - receiver_->translate(tx, ty); - current_layer_->state_is_nop_ = receiver_->is_nop(); - } -} -void DlCanvasToReceiver::Scale(SkScalar sx, SkScalar sy) { - CheckAlive(); - if (SkScalarIsFinite(sx) && SkScalarIsFinite(sy) && - (sx != 1.0 || sy != 1.0)) { - receiver_->scale(sx, sy); - current_layer_->state_is_nop_ = receiver_->is_nop(); - } -} -void DlCanvasToReceiver::Rotate(SkScalar degrees) { - CheckAlive(); - if (SkScalarMod(degrees, 360.0) != 0.0) { - receiver_->rotate(degrees); - current_layer_->state_is_nop_ = receiver_->is_nop(); - } -} -void DlCanvasToReceiver::Skew(SkScalar sx, SkScalar sy) { - CheckAlive(); - if (SkScalarIsFinite(sx) && SkScalarIsFinite(sy) && - (sx != 0.0 || sy != 0.0)) { - receiver_->skew(sx, sy); - current_layer_->state_is_nop_ = receiver_->is_nop(); - } -} - -// clang-format off - -// 2x3 2D affine subset of a 4x4 transform in row major order -void DlCanvasToReceiver::Transform2DAffine( - SkScalar mxx, SkScalar mxy, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myt) { - CheckAlive(); - if (SkScalarsAreFinite(mxx, myx) && - SkScalarsAreFinite(mxy, myy) && - SkScalarsAreFinite(mxt, myt)) { - if (mxx == 1 && mxy == 0 && - myx == 0 && myy == 1) { - Translate(mxt, myt); - } else { - receiver_->transform2DAffine(mxx, mxy, mxt, - myx, myy, myt); - current_layer_->state_is_nop_ = receiver_->is_nop(); - } - } -} -// full 4x4 transform in row major order -void DlCanvasToReceiver::TransformFullPerspective( - SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, - SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, - SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) { - CheckAlive(); - if ( mxz == 0 && - myz == 0 && - mzx == 0 && mzy == 0 && mzz == 1 && mzt == 0 && - mwx == 0 && mwy == 0 && mwz == 0 && mwt == 1) { - Transform2DAffine(mxx, mxy, mxt, - myx, myy, myt); - } else if (SkScalarsAreFinite(mxx, mxy) && SkScalarsAreFinite(mxz, mxt) && - SkScalarsAreFinite(myx, myy) && SkScalarsAreFinite(myz, myt) && - SkScalarsAreFinite(mzx, mzy) && SkScalarsAreFinite(mzz, mzt) && - SkScalarsAreFinite(mwx, mwy) && SkScalarsAreFinite(mwz, mwt)) { - receiver_->transformFullPerspective(mxx, mxy, mxz, mxt, - myx, myy, myz, myt, - mzx, mzy, mzz, mzt, - mwx, mwy, mwz, mwt); - current_layer_->state_is_nop_ = receiver_->is_nop(); - } -} -void DlCanvasToReceiver::TransformReset() { - CheckAlive(); - receiver_->transformReset(); - current_layer_->state_is_nop_ = receiver_->is_nop(); -} -void DlCanvasToReceiver::Transform(const SkMatrix* matrix) { - CheckAlive(); - if (matrix != nullptr) { - if (matrix->hasPerspective()) { - Transform2DAffine( - matrix->getScaleX(), matrix->getSkewX(), matrix->getTranslateX(), - matrix->getSkewY(), matrix->getScaleY(), matrix->getTranslateY()); - } else { - TransformFullPerspective( - matrix->rc(0, 0), matrix->rc(0, 1), 0.0f, matrix->rc(0, 2), - matrix->rc(1, 0), matrix->rc(1, 1), 0.0f, matrix->rc(1, 2), - 0.0f, 0.0f, 1.0f, 0.0f, - matrix->rc(2, 0), matrix->rc(2, 1), 0.0f, matrix->rc(2, 2)); - } - } -} -void DlCanvasToReceiver::Transform(const SkM44* m44) { - CheckAlive(); - if (m44 != nullptr) { - TransformFullPerspective( - m44->rc(0, 0), m44->rc(0, 1), m44->rc(0, 2), m44->rc(0, 3), - m44->rc(1, 0), m44->rc(1, 1), m44->rc(1, 2), m44->rc(1, 3), - m44->rc(2, 0), m44->rc(2, 1), m44->rc(2, 2), m44->rc(2, 3), - m44->rc(3, 0), m44->rc(3, 1), m44->rc(3, 2), m44->rc(3, 3)); - } -} -// clang-format on - -void DlCanvasToReceiver::ClipRect(const SkRect& rect, - ClipOp clip_op, - bool is_aa) { - CheckAlive(); - if (!rect.isFinite()) { - return; - } - receiver_->clipRect(rect, clip_op, is_aa); - current_layer_->state_is_nop_ = receiver_->is_nop(); -} -void DlCanvasToReceiver::ClipRRect(const SkRRect& rrect, - ClipOp clip_op, - bool is_aa) { - CheckAlive(); - if (rrect.isRect()) { - ClipRect(rrect.rect(), clip_op, is_aa); - } else { - receiver_->clipRRect(rrect, clip_op, is_aa); - current_layer_->state_is_nop_ = receiver_->is_nop(); - } -} -void DlCanvasToReceiver::ClipPath(const SkPath& path, - ClipOp clip_op, - bool is_aa) { - CheckAlive(); - if (!path.isInverseFillType()) { - SkRect rect; - if (path.isRect(&rect)) { - this->ClipRect(rect, clip_op, is_aa); - return; - } - SkRRect rrect; - if (path.isOval(&rect)) { - rrect.setOval(rect); - this->ClipRRect(rrect, clip_op, is_aa); - return; - } - if (path.isRRect(&rrect)) { - this->ClipRRect(rrect, clip_op, is_aa); - return; - } - } - receiver_->clipPath(path, clip_op, is_aa); - current_layer_->state_is_nop_ = receiver_->is_nop(); -} - -bool DlCanvasToReceiver::QuickReject(const SkRect& bounds) const { - CheckAlive(); - return receiver_->content_culled(bounds); -} - -void DlCanvasToReceiver::DrawPaint(const DlPaint& paint) { - CheckAlive(); - OpResult result = PaintResult(paint, kDrawPaintFlags); - if (result != OpResult::kNoEffect && AccumulateUnbounded()) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, kDrawPaintFlags); - receiver_->drawPaint(); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawColor(DlColor color, DlBlendMode mode) { - CheckAlive(); - // We use DrawPaint flags here because the DrawColor flags indicate - // that they will ignore the values in the paint that we are creating. - // But we need the PaintResult to actually look at this paint object - // so DrawPaint flags tell it to check all the required values. - // Alternately, we could just call |DrawPaint(DlPaint(...));| which - // is the equivalent call and the same thing would happen. - OpResult result = - PaintResult(DlPaint(color).setBlendMode(mode), kDrawPaintFlags); - if (result != OpResult::kNoEffect && AccumulateUnbounded()) { - receiver_->drawColor(color, mode); - current_layer_->Update(result, IsOpacityCompatible(mode)); - } -} -void DlCanvasToReceiver::DrawLine(const SkPoint& p0, - const SkPoint& p1, - const DlPaint& paint) { - CheckAlive(); - SkRect bounds = SkRect::MakeLTRB(p0.fX, p0.fY, p1.fX, p1.fY).makeSorted(); - DisplayListAttributeFlags flags = - (bounds.width() > 0.0f && bounds.height() > 0.0f) ? kDrawLineFlags - : kDrawHVLineFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && - AccumulateOpBounds(bounds, &paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawLine(p0, p1); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawRect(const SkRect& rect, const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = kDrawRectFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && - AccumulateOpBounds(rect.makeSorted(), &paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawRect(rect); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawOval(const SkRect& bounds, const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = kDrawOvalFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && - AccumulateOpBounds(bounds.makeSorted(), &paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawOval(bounds); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawCircle(const SkPoint& center, - SkScalar radius, - const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = kDrawCircleFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect) { - SkRect bounds = SkRect::MakeLTRB(center.fX - radius, center.fY - radius, - center.fX + radius, center.fY + radius); - if (AccumulateOpBounds(bounds, &paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawCircle(center, radius); - current_layer_->Update(result, can_inherit_opacity); - } - } -} -void DlCanvasToReceiver::DrawRRect(const SkRRect& rrect, const DlPaint& paint) { - CheckAlive(); - if (rrect.isRect()) { - DrawRect(rrect.rect(), paint); - } else if (rrect.isOval()) { - DrawOval(rrect.rect(), paint); - } else { - DisplayListAttributeFlags flags = kDrawRRectFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && - AccumulateOpBounds(rrect.getBounds(), &paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawRRect(rrect); - current_layer_->Update(result, can_inherit_opacity); - } - } -} -void DlCanvasToReceiver::DrawDRRect(const SkRRect& outer, - const SkRRect& inner, - const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = kDrawDRRectFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && - AccumulateOpBounds(outer.getBounds(), &paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawDRRect(outer, inner); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawPath(const SkPath& path, const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = kDrawPathFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect) { - bool is_visible = path.isInverseFillType() - ? AccumulateUnbounded() - : AccumulateOpBounds(path.getBounds(), &paint, flags); - if (is_visible) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawPath(path); - current_layer_->Update(result, can_inherit_opacity); - } - } -} - -void DlCanvasToReceiver::DrawArc(const SkRect& bounds, - SkScalar start, - SkScalar sweep, - bool useCenter, - const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = // - useCenter // - ? kDrawArcWithCenterFlags - : kDrawArcNoCenterFlags; - OpResult result = PaintResult(paint, flags); - // This could be tighter if we compute where the start and end - // angles are and then also consider the quadrants swept and - // the center if specified. - if (result != OpResult::kNoEffect && - AccumulateOpBounds(bounds, &paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(&paint, flags); - receiver_->drawArc(bounds, start, sweep, useCenter); - current_layer_->Update(result, can_inherit_opacity); - } -} - -DisplayListAttributeFlags DlCanvasToReceiver::FlagsForPointMode( - PointMode mode) { - switch (mode) { - case DlCanvas::PointMode::kPoints: - return kDrawPointsAsPointsFlags; - case PointMode::kLines: - return kDrawPointsAsLinesFlags; - case PointMode::kPolygon: - return kDrawPointsAsPolygonFlags; - } - FML_UNREACHABLE(); -} -void DlCanvasToReceiver::DrawPoints(PointMode mode, - uint32_t count, - const SkPoint pts[], - const DlPaint& paint) { - CheckAlive(); - if (count == 0) { - return; - } - DisplayListAttributeFlags flags = FlagsForPointMode(mode); - OpResult result = PaintResult(paint, flags); - if (result == OpResult::kNoEffect) { - return; - } - - FML_DCHECK(count < DlOpReceiver::kMaxDrawPointsCount); - RectBoundsAccumulator ptBounds; - for (size_t i = 0; i < count; i++) { - ptBounds.accumulate(pts[i]); - } - SkRect point_bounds = ptBounds.bounds(); - if (!AccumulateOpBounds(point_bounds, &paint, flags)) { - return; - } - - (void)SetAttributesFromPaint(&paint, flags); - receiver_->drawPoints(mode, count, pts); - // drawPoints treats every point or line (or segment of a polygon) - // as a completely separate operation meaning we cannot ensure - // distribution of group opacity without analyzing the mode and the - // bounds of every sub-primitive. - // See: https://fiddle.skia.org/c/228459001d2de8db117ce25ef5cedb0c - current_layer_->Update(result, false); -} -void DlCanvasToReceiver::DrawVertices(const DlVertices* vertices, - DlBlendMode mode, - const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = kDrawVerticesFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && - AccumulateOpBounds(vertices->bounds(), &paint, flags)) { - (void)SetAttributesFromPaint(&paint, flags); - receiver_->drawVertices(vertices, mode); - // DrawVertices applies its colors to the paint so we have no way - // of controlling opacity using the current paint attributes. - // Although, examination of the |mode| might find some predictable - // cases. - current_layer_->Update(result, false); - } -} - -void DlCanvasToReceiver::DrawImage(const sk_sp& image, - const SkPoint point, - DlImageSampling sampling, - const DlPaint* paint) { - CheckAlive(); - DisplayListAttributeFlags flags = paint ? kDrawImageWithPaintFlags // - : kDrawImageFlags; - OpResult result = PaintResult(paint, flags); - if (result == OpResult::kNoEffect) { - return; - } - SkRect bounds = SkRect::MakeXYWH(point.fX, point.fY, // - image->width(), image->height()); - if (AccumulateOpBounds(bounds, paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(paint, flags); - receiver_->drawImage(image, point, sampling, paint != nullptr); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawImageRect(const sk_sp& image, - const SkRect& src, - const SkRect& dst, - DlImageSampling sampling, - const DlPaint* paint, - SrcRectConstraint constraint) { - CheckAlive(); - DisplayListAttributeFlags flags = paint ? kDrawImageRectWithPaintFlags // - : kDrawImageRectFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && AccumulateOpBounds(dst, paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(paint, flags); - receiver_->drawImageRect(image, src, dst, sampling, paint != nullptr, - constraint); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawImageNine(const sk_sp& image, - const SkIRect& center, - const SkRect& dst, - DlFilterMode filter, - const DlPaint* paint) { - CheckAlive(); - DisplayListAttributeFlags flags = paint ? kDrawImageNineWithPaintFlags // - : kDrawImageNineFlags; - OpResult result = PaintResult(paint, flags); - if (result != OpResult::kNoEffect && AccumulateOpBounds(dst, paint, flags)) { - bool can_inherit_opacity = SetAttributesFromPaint(paint, flags); - receiver_->drawImageNine(image, center, dst, filter, paint != nullptr); - current_layer_->Update(result, can_inherit_opacity); - } -} -void DlCanvasToReceiver::DrawAtlas(const sk_sp& atlas, - const SkRSXform xform[], - const SkRect tex[], - const DlColor colors[], - int count, - DlBlendMode mode, - DlImageSampling sampling, - const SkRect* cull_rect, - const DlPaint* paint) { - CheckAlive(); - DisplayListAttributeFlags flags = paint ? kDrawAtlasWithPaintFlags // - : kDrawAtlasFlags; - OpResult result = PaintResult(paint, flags); - if (result == OpResult::kNoEffect) { - return; - } - SkPoint quad[4]; - RectBoundsAccumulator atlasBounds; - for (int i = 0; i < count; i++) { - const SkRect& src = tex[i]; - xform[i].toQuad(src.width(), src.height(), quad); - for (int j = 0; j < 4; j++) { - atlasBounds.accumulate(quad[j]); - } - } - if (atlasBounds.is_empty() || - !AccumulateOpBounds(atlasBounds.bounds(), paint, flags)) { - return; - } - - (void)SetAttributesFromPaint(paint, flags); - receiver_->drawAtlas(atlas, xform, tex, colors, count, mode, sampling, - cull_rect, paint != nullptr); - // drawAtlas treats each image as a separate operation so we cannot rely - // on it to distribute the opacity without overlap without checking all - // of the transforms and texture rectangles. - current_layer_->Update(result, false); -} - -void DlCanvasToReceiver::DrawDisplayList(const sk_sp display_list, - SkScalar opacity) { - CheckAlive(); - if (!SkScalarIsFinite(opacity) || opacity <= SK_ScalarNearlyZero || - display_list->op_count() == 0 || display_list->bounds().isEmpty() || - current_layer_->state_is_nop_) { - return; - } - - const SkRect bounds = display_list->bounds(); - bool accumulated; - if (receiver_->wants_granular_bounds()) { - auto rtree = display_list->rtree(); - if (rtree) { - std::list rects = rtree->searchAndConsolidateRects(bounds, false); - accumulated = false; - for (const SkRect& rect : rects) { - // TODO (https://github.com/flutter/flutter/issues/114919): Attributes - // are not necessarily `kDrawDisplayListFlags`. - if (AccumulateOpBounds(rect, nullptr, kDrawDisplayListFlags)) { - accumulated = true; - } - } - } else { - accumulated = AccumulateOpBounds(bounds, nullptr, kDrawDisplayListFlags); - } - } else { - accumulated = AccumulateOpBounds(bounds, nullptr, kDrawDisplayListFlags); - } - if (!accumulated) { - return; - } - - receiver_->drawDisplayList(display_list, - opacity < SK_Scalar1 ? opacity : SK_Scalar1); - - // The non-nested op count accumulated in the |Push| method will include - // this call to |drawDisplayList| for non-nested op count metrics. - // But, for nested op count metrics we want the |drawDisplayList| call itself - // to be transparent. So we subtract 1 from our accumulated nested count to - // balance out against the 1 that was accumulated into the regular count. - // This behavior is identical to the way SkPicture computed nested op counts. - // nested_op_count_ += display_list->op_count(true) - 1; - // nested_bytes_ += display_list->bytes(true); - current_layer_->Update( - // Nop DisplayLists are eliminated above so we either affect transparent - // pixels or we do not. We should not have [kNoEffect]. - display_list->modifies_transparent_black() - ? OpResult::kAffectsAll - : OpResult::kPreservesTransparency, - display_list->can_apply_group_opacity()); -} -void DlCanvasToReceiver::DrawTextBlob(const sk_sp& blob, - SkScalar x, - SkScalar y, - const DlPaint& paint) { - CheckAlive(); - DisplayListAttributeFlags flags = kDrawTextBlobFlags; - OpResult result = PaintResult(paint, flags); - if (result == OpResult::kNoEffect) { - return; - } - bool unclipped = - AccumulateOpBounds(blob->bounds().makeOffset(x, y), &paint, flags); - // TODO(https://github.com/flutter/flutter/issues/82202): Remove once the - // unit tests can use Fuchsia's font manager instead of the empty default. - // Until then we might encounter empty bounds for otherwise valid text and - // thus we ignore the results from AccumulateOpBounds. -#if defined(OS_FUCHSIA) - unclipped = true; -#endif // OS_FUCHSIA - if (unclipped) { - (void)SetAttributesFromPaint(&paint, flags); - receiver_->drawTextBlob(blob, x, y); - // There is no way to query if the glyphs of a text blob overlap and - // there are no current guarantees from either Skia or Impeller that - // they will protect overlapping glyphs from the effects of overdraw - // so we must make the conservative assessment that this DL layer is - // not compatible with group opacity inheritance. - current_layer_->Update(result, false); - } -} -void DlCanvasToReceiver::DrawShadow(const SkPath& path, - const DlColor color, - const SkScalar elevation, - bool transparent_occluder, - SkScalar dpr) { - CheckAlive(); - OpResult result = PaintResult(DlPaint(color)); - if (result != OpResult::kNoEffect) { - SkRect shadow_bounds = - DlCanvas::ComputeShadowBounds(path, elevation, dpr, GetTransform()); - if (AccumulateOpBounds(shadow_bounds, nullptr, kDrawShadowFlags)) { - receiver_->drawShadow(path, color, elevation, transparent_occluder, dpr); - current_layer_->Update(result, false); - } - } -} - -bool DlCanvasToReceiver::ComputeFilteredBounds(SkRect& bounds, - const DlImageFilter* filter) { - if (filter) { - if (!filter->map_local_bounds(bounds, bounds)) { - return false; - } - } - return true; -} - -bool DlCanvasToReceiver::AdjustBoundsForPaint(SkRect& bounds, - const DlPaint* in_paint, - DisplayListAttributeFlags flags) { - if (flags.ignores_paint()) { - return true; - } - - const DlPaint& paint = in_paint ? *in_paint : kDefaultPaint_; - if (flags.is_geometric()) { - bool is_stroked = flags.is_stroked(paint.getDrawStyle()); - - // Path effect occurs before stroking... - DisplayListSpecialGeometryFlags special_flags = - flags.WithPathEffect(paint.getPathEffectPtr(), is_stroked); - if (paint.getPathEffect()) { - auto effect_bounds = paint.getPathEffect()->effect_bounds(bounds); - if (!effect_bounds.has_value()) { - return false; - } - bounds = effect_bounds.value(); - } - - if (is_stroked) { - // Determine the max multiplier to the stroke width first. - SkScalar pad = 1.0f; - if (paint.getStrokeJoin() == DlStrokeJoin::kMiter && - special_flags.may_have_acute_joins()) { - pad = std::max(pad, paint.getStrokeMiter()); - } - if (paint.getStrokeCap() == DlStrokeCap::kSquare && - special_flags.may_have_diagonal_caps()) { - pad = std::max(pad, SK_ScalarSqrt2); - } - SkScalar min_stroke_width = 0.01; - pad *= std::max(paint.getStrokeWidth() * 0.5f, min_stroke_width); - bounds.outset(pad, pad); - } - } - - if (flags.applies_mask_filter()) { - auto filter = paint.getMaskFilter(); - if (filter) { - switch (filter->type()) { - case DlMaskFilterType::kBlur: { - FML_DCHECK(filter->asBlur()); - SkScalar mask_sigma_pad = filter->asBlur()->sigma() * 3.0; - bounds.outset(mask_sigma_pad, mask_sigma_pad); - } - } - } - } - - if (flags.applies_image_filter()) { - return ComputeFilteredBounds(bounds, paint.getImageFilter().get()); - } - - return true; -} - -bool DlCanvasToReceiver::AccumulateUnbounded() { - return receiver_->accumulateUnboundedForNextOp(); -} - -bool DlCanvasToReceiver::AccumulateOpBounds(SkRect& bounds, - const DlPaint* paint, - DisplayListAttributeFlags flags) { - if (AdjustBoundsForPaint(bounds, paint, flags)) { - return AccumulateBounds(bounds); - } else { - return AccumulateUnbounded(); - } -} -bool DlCanvasToReceiver::AccumulateBounds(SkRect& bounds) { - return receiver_->accumulateLocalBoundsForNextOp(bounds); -} - -bool DlCanvasToReceiver::paint_nops_on_transparency(const DlPaint* paint) { - if (paint == nullptr) { - return true; - } - - // SkImageFilter::canComputeFastBounds tests for transparency behavior - // This test assumes that the blend mode checked down below will - // NOP on transparent black. - if (paint->getImageFilterPtr() && - paint->getImageFilterPtr()->modifies_transparent_black()) { - return false; - } - - // We filter the transparent black that is used for the background of a - // saveLayer and make sure it returns transparent black. If it does, then - // the color filter will leave all area surrounding the contents of the - // save layer untouched out to the edge of the output surface. - // This test assumes that the blend mode checked down below will - // NOP on transparent black. - if (paint->getColorFilterPtr() && - paint->getColorFilterPtr()->modifies_transparent_black()) { - return false; - } - - // Unusual blendmodes require us to process a saved layer - // even with operations outside the clip. - // For example, DstIn is used by masking layers. - // https://code.google.com/p/skia/issues/detail?id=1291 - // https://crbug.com/401593 - switch (paint->getBlendMode()) { - // For each of the following transfer modes, if the source - // alpha is zero (our transparent black), the resulting - // blended pixel is not necessarily equal to the original - // destination pixel. - // Mathematically, any time in the following equations where - // the result is not d assuming source is 0 - case DlBlendMode::kClear: // r = 0 - case DlBlendMode::kSrc: // r = s - case DlBlendMode::kSrcIn: // r = s * da - case DlBlendMode::kDstIn: // r = d * sa - case DlBlendMode::kSrcOut: // r = s * (1-da) - case DlBlendMode::kDstATop: // r = d*sa + s*(1-da) - case DlBlendMode::kModulate: // r = s*d - return false; - break; - - // And in these equations, the result must be d if the - // source is 0 - case DlBlendMode::kDst: // r = d - case DlBlendMode::kSrcOver: // r = s + (1-sa)*d - case DlBlendMode::kDstOver: // r = d + (1-da)*s - case DlBlendMode::kDstOut: // r = d * (1-sa) - case DlBlendMode::kSrcATop: // r = s*da + d*(1-sa) - case DlBlendMode::kXor: // r = s*(1-da) + d*(1-sa) - case DlBlendMode::kPlus: // r = min(s + d, 1) - case DlBlendMode::kScreen: // r = s + d - s*d - case DlBlendMode::kOverlay: // multiply or screen, depending on dest - case DlBlendMode::kDarken: // rc = s + d - max(s*da, d*sa), - // ra = kSrcOver - case DlBlendMode::kLighten: // rc = s + d - min(s*da, d*sa), - // ra = kSrcOver - case DlBlendMode::kColorDodge: // brighten destination to reflect source - case DlBlendMode::kColorBurn: // darken destination to reflect source - case DlBlendMode::kHardLight: // multiply or screen, depending on source - case DlBlendMode::kSoftLight: // lighten or darken, depending on source - case DlBlendMode::kDifference: // rc = s + d - 2*(min(s*da, d*sa)), - // ra = kSrcOver - case DlBlendMode::kExclusion: // rc = s + d - two(s*d), ra = kSrcOver - case DlBlendMode::kMultiply: // r = s*(1-da) + d*(1-sa) + s*d - case DlBlendMode::kHue: // ra = kSrcOver - case DlBlendMode::kSaturation: // ra = kSrcOver - case DlBlendMode::kColor: // ra = kSrcOver - case DlBlendMode::kLuminosity: // ra = kSrcOver - return true; - break; - } -} - -DlColor DlCanvasToReceiver::GetEffectiveColor(const DlPaint& paint, - DisplayListAttributeFlags flags) { - DlColor color; - if (flags.applies_color()) { - const DlColorSource* source = paint.getColorSourcePtr(); - if (source) { - if (source->asColor()) { - color = source->asColor()->color(); - } else { - color = source->is_opaque() ? DlColor::kBlack() : kAnyColor; - } - } else { - color = paint.getColor(); - } - } else if (flags.applies_alpha()) { - // If the operation applies alpha, but not color, then the only impact - // of the alpha is to modulate the output towards transparency. - // We can not guarantee an opaque source even if the alpha is opaque - // since that would require knowing something about the colors that - // the alpha is modulating, but we can guarantee a transparent source - // if the alpha is 0. - color = (paint.getAlpha() == 0) ? DlColor::kTransparent() : kAnyColor; - } else { - color = kAnyColor; - } - if (flags.applies_image_filter()) { - auto filter = paint.getImageFilterPtr(); - if (filter) { - if (!color.isTransparent() || filter->modifies_transparent_black()) { - color = kAnyColor; - } - } - } - if (flags.applies_color_filter()) { - auto filter = paint.getColorFilterPtr(); - if (filter) { - if (!color.isTransparent() || filter->modifies_transparent_black()) { - color = kAnyColor; - } - } - } - return color; -} - -DlCanvasToReceiver::OpResult DlCanvasToReceiver::PaintResult( - const DlPaint& paint, - DisplayListAttributeFlags flags) { - if (current_layer_->state_is_nop_) { - return OpResult::kNoEffect; - } - if (flags.applies_blend()) { - switch (paint.getBlendMode()) { - // Nop blend mode (singular, there is only one) - case DlBlendMode::kDst: - return OpResult::kNoEffect; - - // Always clears pixels blend mode (singular, there is only one) - case DlBlendMode::kClear: - return OpResult::kPreservesTransparency; - - case DlBlendMode::kHue: - case DlBlendMode::kSaturation: - case DlBlendMode::kColor: - case DlBlendMode::kLuminosity: - case DlBlendMode::kColorBurn: - return GetEffectiveColor(paint, flags).isTransparent() - ? OpResult::kNoEffect - : OpResult::kAffectsAll; - - // kSrcIn modifies pixels towards transparency - case DlBlendMode::kSrcIn: - return OpResult::kPreservesTransparency; - - // These blend modes preserve destination alpha - case DlBlendMode::kSrcATop: - case DlBlendMode::kDstOut: - return GetEffectiveColor(paint, flags).isTransparent() - ? OpResult::kNoEffect - : OpResult::kPreservesTransparency; - - // Always destructive blend modes, potentially not affecting transparency - case DlBlendMode::kSrc: - case DlBlendMode::kSrcOut: - case DlBlendMode::kDstATop: - return GetEffectiveColor(paint, flags).isTransparent() - ? OpResult::kPreservesTransparency - : OpResult::kAffectsAll; - - // The kDstIn blend mode modifies the destination unless the - // source color is opaque. - case DlBlendMode::kDstIn: - return GetEffectiveColor(paint, flags).isOpaque() - ? OpResult::kNoEffect - : OpResult::kPreservesTransparency; - - // The next group of blend modes modifies the destination unless the - // source color is transparent. - case DlBlendMode::kSrcOver: - case DlBlendMode::kDstOver: - case DlBlendMode::kXor: - case DlBlendMode::kPlus: - case DlBlendMode::kScreen: - case DlBlendMode::kMultiply: - case DlBlendMode::kOverlay: - case DlBlendMode::kDarken: - case DlBlendMode::kLighten: - case DlBlendMode::kColorDodge: - case DlBlendMode::kHardLight: - case DlBlendMode::kSoftLight: - case DlBlendMode::kDifference: - case DlBlendMode::kExclusion: - return GetEffectiveColor(paint, flags).isTransparent() - ? OpResult::kNoEffect - : OpResult::kAffectsAll; - - // Modulate only leaves the pixel alone when the source is white. - case DlBlendMode::kModulate: - return GetEffectiveColor(paint, flags) == DlColor::kWhite() - ? OpResult::kNoEffect - : OpResult::kPreservesTransparency; - } - } - return OpResult::kAffectsAll; -} - -DlPaint DlCanvasToReceiver::kDefaultPaint_; - -} // namespace flutter diff --git a/display_list/dl_canvas_to_receiver.h b/display_list/dl_canvas_to_receiver.h deleted file mode 100644 index fdd499cea993d..0000000000000 --- a/display_list/dl_canvas_to_receiver.h +++ /dev/null @@ -1,565 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FLUTTER_DISPLAY_LIST_DL_CANVAS_TO_RECEIVER_H_ -#define FLUTTER_DISPLAY_LIST_DL_CANVAS_TO_RECEIVER_H_ - -#include "flutter/display_list/dl_canvas.h" -#include "flutter/display_list/dl_op_flags.h" -#include "flutter/display_list/dl_op_receiver.h" -#include "flutter/fml/macros.h" - -namespace flutter { - -class DlCanvasReceiver : public DlOpReceiver { - private: - using ClipOp = DlCanvas::ClipOp; - - public: - virtual ~DlCanvasReceiver() = default; - - virtual SkRect base_device_cull_rect() const = 0; - - virtual SkM44 matrix_4x4() const = 0; - virtual SkMatrix matrix_3x3() const { return matrix_4x4().asM33(); } - - virtual SkRect device_cull_rect() const = 0; - virtual SkRect local_cull_rect() const = 0; - virtual bool is_cull_rect_empty() const = 0; - virtual bool content_culled(const SkRect& content_bounds) const = 0; - - /*--------- Methods below here are optional optimizations --------*/ - - /// Optional - only needed if performing bounds culling via the accumulate - /// methods - /// Note: The bounds are only advisory for implementing bounds culling - /// and should not trigger an actual clip operation. - /// The default implementation ignores the advisory information. - /// - /// This method should almost never be used as it breaks the encapsulation - /// of the enclosing clips. However it is needed for practical purposes in - /// some rare cases - such as when a saveLayer is collecting rendering - /// operations prior to applying a filter on the entire layer bounds and - /// some of those operations fall outside the enclosing clip, but their - /// filtered content will spread out from where they were rendered on the - /// layer into the enclosing clipped area. - /// Omitting the |cull_rect| argument, or passing nullptr, will restore the - /// cull rect to the initial value it had when the tracker was constructed. - virtual void resetCullRect(const SkRect* cull_rect = nullptr) {} - - /// Optional - only needed if performing bounds culling via the accumulate - /// methods - /// Note: The bounds are only advisory for implementing bounds culling - /// and should not trigger an actual clip operation. - /// The default implementation ignores the advisory information. - /// - /// This method is used to add an additional culling bounds without - /// actually performing a clip on the destination. The bounds will - /// help avoid recording content of a saveLayer that lies entirely - /// outside the save layer bounds if it had them. - virtual void intersectCullRect(const SkRect& cull_rect) {} - - /// Optional - only needed if implementing the accumulate methods - /// The default implementation returns false to prevent extra work in - /// the adapter. - /// - /// If the receiver is accumulating bounds into, say, an rtree format, - /// or wants granular bounds for any other reason, this query will let - /// the adapter know that it should deliver the bounds of methods such - /// as DrawDisplayList granularly if possible (i.e. if the DL being - /// drawn itself has an RTree for its bounds). - /// - /// Returns: true if the implementation can make use of granular bounds - virtual bool wants_granular_bounds() const { return false; } - - /// Optional - only needed if accumulating bounds or implementing bounds - /// culling - /// The default implementation ignores the bounds and returns true to - /// prevent culling. - /// - /// The indicated bounds were calculated for the next rendering op call. - /// The receiver can ignore them if it is not accumulating the bounds, - /// and can tag them appropriately if recording the bounds per rendering op. - /// The receiver can also indicate if the bounds are clipped out with - /// the returned boolean. - /// - /// Returns: true if the bounds were not clipped - /// or false if there is no way for these bounds to be visible - virtual bool accumulateLocalBoundsForNextOp(const SkRect& r) { return true; } - - /// Optional - only needed if accumulating bounds or implementing bounds - /// culling - /// The default implementation ignores the condition and returns true to - /// prevent culling. - /// - /// The bounds for the next rendering op will be "unbounded" by anything - /// other than the current clip, whether because it is a |drawPaint| or - /// |drawColor| call or because it is rendered with a filter that modifies - /// all pixels (even transparent) out to infinity (or the clip). - /// The receiver can ignore the information if it is not accumulating - /// the bounds, and can tag them appropriately if recording the bounds - /// per rendering op. - /// The receiver can also indicate if the bounds are clipped out with - /// the returned boolean. - /// - /// Returns: true if the bounds were not clipped - /// or false if there is no way for these bounds to be visible - virtual bool accumulateUnboundedForNextOp() { return true; } - - /// Optional - only needed if the provided information is useful to the - /// implementation - /// By default this method will simply call the regular |restore| method - /// and the information will be ignored. - /// - /// Called in lieue of a call to |restore| when the upstream code calls - /// a restore on a |saveLayer| and there is information about the contents - /// of the layer that the receiver might find interesting. - virtual void restoreLayer(const DlImageFilter* filter, - bool layer_content_was_unbounded, - bool layer_could_distribute_opacity) { - restore(); - } - - /// Optional - useful to indicate non-renderable state such as an empty - /// clip or collapsed transform to suspend rendering calls - /// until the state is overridden or popped by a |restore|. - /// By default this method returns false to prevent state culling. - /// - /// The |is_nop| method will be called after any of the clip or - /// transform methods to detect if the current conditions are - /// now a NOP. The receiver will receive no more calls until the - /// associated restore() call which will be dispatched to it, or - /// a subsequent clip or transform "reset" operation. - /// - /// Returns: true if either the clip or transform prevent rendering - virtual bool is_nop() { return false; } -}; - -// The primary class used to build a display list. The list of methods -// here matches the list of methods invoked on a |DlOpReceiver| combined -// with the list of methods invoked on a |DlCanvas|. -class DlCanvasToReceiver : public virtual DlCanvas, // - DisplayListOpFlags { - public: - explicit DlCanvasToReceiver(std::shared_ptr receiver); - - ~DlCanvasToReceiver() = default; - - // |DlCanvas| - SkISize GetBaseLayerSize() const override; - // |DlCanvas| - SkImageInfo GetImageInfo() const override; - - // |DlCanvas| - void Save() override; - - // |DlCanvas| - void SaveLayer(const SkRect* bounds, - const DlPaint* paint = nullptr, - const DlImageFilter* backdrop = nullptr) override; - // |DlCanvas| - void Restore() override; - // |DlCanvas| - int GetSaveCount() const override { - CheckAlive(); - return layer_stack_.size(); - } - // |DlCanvas| - void RestoreToCount(int restore_count) override; - - // |DlCanvas| - void Translate(SkScalar tx, SkScalar ty) override; - // |DlCanvas| - void Scale(SkScalar sx, SkScalar sy) override; - // |DlCanvas| - void Rotate(SkScalar degrees) override; - // |DlCanvas| - void Skew(SkScalar sx, SkScalar sy) override; - - // clang-format off - // 2x3 2D affine subset of a 4x4 transform in row major order - // |DlCanvas| - void Transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myt) override; - // full 4x4 transform in row major order - // |DlCanvas| - void TransformFullPerspective( - SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, - SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, - SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override; - // clang-format on - // |DlCanvas| - void TransformReset() override; - // |DlCanvas| - void Transform(const SkMatrix* matrix) override; - // |DlCanvas| - void Transform(const SkM44* matrix44) override; - // |DlCanvas| - void SetTransform(const SkMatrix* matrix) override { - CheckAlive(); - TransformReset(); - Transform(matrix); - } - // |DlCanvas| - void SetTransform(const SkM44* matrix44) override { - CheckAlive(); - TransformReset(); - Transform(matrix44); - } - using DlCanvas::Transform; - - /// Returns the 4x4 full perspective transform representing all transform - /// operations executed so far in this DisplayList within the enclosing - /// save stack. - // |DlCanvas| - SkM44 GetTransformFullPerspective() const override { - CheckAlive(); - return receiver_->matrix_4x4(); - } - /// Returns the 3x3 partial perspective transform representing all transform - /// operations executed so far in this DisplayList within the enclosing - /// save stack. - // |DlCanvas| - SkMatrix GetTransform() const override { - CheckAlive(); - return receiver_->matrix_3x3(); - } - - // |DlCanvas| - void ClipRect(const SkRect& rect, - ClipOp clip_op = ClipOp::kIntersect, - bool is_aa = false) override; - // |DlCanvas| - void ClipRRect(const SkRRect& rrect, - ClipOp clip_op = ClipOp::kIntersect, - bool is_aa = false) override; - // |DlCanvas| - void ClipPath(const SkPath& path, - ClipOp clip_op = ClipOp::kIntersect, - bool is_aa = false) override; - - /// Conservative estimate of the bounds of all outstanding clip operations - /// measured in the coordinate space within which this DisplayList will - /// be rendered. - // |DlCanvas| - SkRect GetDestinationClipBounds() const override { - CheckAlive(); - return receiver_->device_cull_rect(); - } - /// Conservative estimate of the bounds of all outstanding clip operations - /// transformed into the local coordinate space in which currently - /// recorded rendering operations are interpreted. - // |DlCanvas| - SkRect GetLocalClipBounds() const override { - CheckAlive(); - return receiver_->local_cull_rect(); - } - - /// Return true iff the supplied bounds are easily shown to be outside - /// of the current clip bounds. This method may conservatively return - /// false if it cannot make the determination. - // |DlCanvas| - bool QuickReject(const SkRect& bounds) const override; - - // |DlCanvas| - void DrawPaint(const DlPaint& paint) override; - // |DlCanvas| - void DrawColor(DlColor color, DlBlendMode mode) override; - // |DlCanvas| - void DrawLine(const SkPoint& p0, - const SkPoint& p1, - const DlPaint& paint) override; - // |DlCanvas| - void DrawRect(const SkRect& rect, const DlPaint& paint) override; - // |DlCanvas| - void DrawOval(const SkRect& bounds, const DlPaint& paint) override; - // |DlCanvas| - void DrawCircle(const SkPoint& center, - SkScalar radius, - const DlPaint& paint) override; - // |DlCanvas| - void DrawRRect(const SkRRect& rrect, const DlPaint& paint) override; - // |DlCanvas| - void DrawDRRect(const SkRRect& outer, - const SkRRect& inner, - const DlPaint& paint) override; - // |DlCanvas| - void DrawPath(const SkPath& path, const DlPaint& paint) override; - // |DlCanvas| - void DrawArc(const SkRect& bounds, - SkScalar start, - SkScalar sweep, - bool useCenter, - const DlPaint& paint) override; - // |DlCanvas| - void DrawPoints(PointMode mode, - uint32_t count, - const SkPoint pts[], - const DlPaint& paint) override; - // |DlCanvas| - void DrawVertices(const DlVertices* vertices, - DlBlendMode mode, - const DlPaint& paint) override; - using DlCanvas::DrawVertices; - // |DlCanvas| - void DrawImage(const sk_sp& image, - const SkPoint point, - DlImageSampling sampling, - const DlPaint* paint = nullptr) override; - // |DlCanvas| - void DrawImageRect( - const sk_sp& image, - const SkRect& src, - const SkRect& dst, - DlImageSampling sampling, - const DlPaint* paint = nullptr, - SrcRectConstraint constraint = SrcRectConstraint::kFast) override; - using DlCanvas::DrawImageRect; - // |DlCanvas| - void DrawImageNine(const sk_sp& image, - const SkIRect& center, - const SkRect& dst, - DlFilterMode filter, - const DlPaint* paint = nullptr) override; - // |DlCanvas| - void DrawAtlas(const sk_sp& atlas, - const SkRSXform xform[], - const SkRect tex[], - const DlColor colors[], - int count, - DlBlendMode mode, - DlImageSampling sampling, - const SkRect* cullRect, - const DlPaint* paint = nullptr) override; - // |DlCanvas| - void DrawDisplayList(const sk_sp display_list, - SkScalar opacity = SK_Scalar1) override; - // |DlCanvas| - void DrawTextBlob(const sk_sp& blob, - SkScalar x, - SkScalar y, - const DlPaint& paint) override; - // |DlCanvas| - void DrawShadow(const SkPath& path, - const DlColor color, - const SkScalar elevation, - bool transparent_occluder, - SkScalar dpr) override; - - // |DlCanvas| - void Flush() override { CheckAlive(); } - - protected: - inline void CheckAlive() const { FML_CHECK(receiver_ != nullptr); } - - std::shared_ptr receiver_; - - bool current_group_opacity_compatibility() { - return current_layer_->is_group_opacity_compatible(); - } - bool current_affects_transparent_layer() { - return current_layer_->affects_transparent_layer(); - } - - DlPaint CurrentAttributes() const { return current_; } - - private: - // Returns whether or not the paint was compatible with opacity inheritance - [[nodiscard]] bool SetAttributesFromPaint( - const DlPaint* paint, - const DisplayListAttributeFlags flags); - - enum class OpResult { - kNoEffect, - kPreservesTransparency, - kAffectsAll, - }; - - class LayerInfo { - public: - explicit LayerInfo( - bool has_layer = false, - const std::shared_ptr& filter = nullptr) - : has_layer_(has_layer), filter_(filter) {} - - bool has_layer() const { return has_layer_; } - bool cannot_inherit_opacity() const { return cannot_inherit_opacity_; } - bool has_compatible_op() const { return has_compatible_op_; } - bool affects_transparent_layer() const { - return affects_transparent_layer_; - } - - void Update(OpResult result, bool can_inherit_opacity) { - switch (result) { - case OpResult::kNoEffect: - // We should have stopped processing the rendering operation - // well before we tried to update the layer information. - FML_DCHECK(result != OpResult::kNoEffect); - return; - - case OpResult::kPreservesTransparency: - break; - - case OpResult::kAffectsAll: - add_visible_op(); - break; - } - - if (can_inherit_opacity) { - add_compatible_op(); - } else { - mark_incompatible(); - } - } - - bool is_group_opacity_compatible() const { - return !cannot_inherit_opacity_; - } - - void mark_incompatible() { cannot_inherit_opacity_ = true; } - - // For now this only allows a single compatible op to mark the - // layer as being compatible with group opacity. If we start - // computing bounds of ops in the Builder methods then we - // can upgrade this to checking for overlapping ops. - // See https://github.com/flutter/flutter/issues/93899 - void add_compatible_op() { - if (!cannot_inherit_opacity_) { - if (has_compatible_op_) { - cannot_inherit_opacity_ = true; - } else { - has_compatible_op_ = true; - } - } - } - - // Records that the current layer contains an op that produces visible - // output on a transparent surface. - void add_visible_op() { affects_transparent_layer_ = true; } - - // The filter to apply to the layer bounds when it is restored - std::shared_ptr filter() { return filter_; } - - // is_unbounded should be set to true if we ever encounter an operation - // on a layer that either is unrestricted (|drawColor| or |drawPaint|) - // or cannot compute its bounds (some effects and filters) and there - // was no outstanding clip op at the time. - // When the layer is restored, the outer layer may then process this - // unbounded state by accumulating its own clip or transferring the - // unbounded state to its own outer layer. - // Typically the DisplayList will have been constructed with a cull - // rect which will act as a default clip for the outermost layer and - // the unbounded state of all sub layers will eventually be caught by - // that cull rect so that the overall unbounded state of the entire - // DisplayList will never be true. - // - // For historical consistency it is worth noting that SkPicture used - // to treat these same conditions as a Nop (they accumulate the - // SkPicture cull rect, but if no cull rect was specified then it is - // an empty Rect and so has no effect on the bounds). - // - // Flutter is unlikely to ever run into this as the Dart mechanisms - // all supply a non-null cull rect for all Dart Picture objects, - // even if that cull rect is kGiantRect. - void set_unbounded() { is_unbounded_ = true; } - - // |is_unbounded| should be called after |getLayerBounds| in case - // a problem was found during the computation of those bounds, - // the layer will have one last chance to flag an unbounded state. - bool is_unbounded() const { return is_unbounded_; } - - private: - bool has_layer_; - bool cannot_inherit_opacity_ = false; - bool has_compatible_op_ = false; - std::shared_ptr filter_; - bool is_unbounded_ = false; - bool state_is_nop_ = false; - bool affects_transparent_layer_ = false; - - friend class DlCanvasToReceiver; - }; - - std::vector layer_stack_; - LayerInfo* current_layer_; - - // Returns the compatibility of a given blend mode for applying an - // inherited opacity value to modulate the visibility of the op. - // For now we only accept SrcOver blend modes but this could be expanded - // in the future to include other (rarely used) modes that also modulate - // the opacity of a rendering operation at the cost of a switch statement - // or lookup table. - static inline bool IsOpacityCompatible(DlBlendMode mode) { - return (mode == DlBlendMode::kSrcOver); - } - - static DisplayListAttributeFlags FlagsForPointMode(PointMode mode); - - bool paint_nops_on_transparency(const DlPaint* paint); - OpResult PaintResult(const DlPaint& paint, - DisplayListAttributeFlags flags = kDrawPaintFlags); - OpResult PaintResult(const DlPaint* paint, - DisplayListAttributeFlags flags = kDrawPaintFlags) { - if (paint) { - return PaintResult(*paint, flags); - } else if (current_layer_->state_is_nop_) { - return OpResult::kNoEffect; - } else { - FML_DCHECK(PaintResult(kDefaultPaint_, flags) == OpResult::kAffectsAll); - return OpResult::kAffectsAll; - } - } - - // kAnyColor is a non-opaque and non-transparent color that will not - // trigger any short-circuit tests about the results of a blend. - static constexpr DlColor kAnyColor = DlColor::kMidGrey().withAlpha(0x80); - static_assert(!kAnyColor.isOpaque()); - static_assert(!kAnyColor.isTransparent()); - static DlColor GetEffectiveColor(const DlPaint& paint, - DisplayListAttributeFlags flags); - - // Computes the bounds of an operation adjusted for a given ImageFilter - // and returns whether the computation was possible. If the method - // returns false then the caller should assume the worst about the bounds. - static bool ComputeFilteredBounds(SkRect& bounds, - const DlImageFilter* filter); - - // Adjusts the indicated bounds for the given flags and returns true if - // the calculation was possible, or false if it could not be estimated. - bool AdjustBoundsForPaint(SkRect& bounds, - const DlPaint* paint, - DisplayListAttributeFlags flags); - - // Records the fact that we encountered an op that either could not - // estimate its bounds or that fills all of the destination space. - bool AccumulateUnbounded(); - - // Records the bounds for an op after modifying them according to the - // supplied attribute flags and transforming by the current matrix. - bool AccumulateOpBounds(const SkRect& bounds, - const DlPaint* paint, - DisplayListAttributeFlags flags) { - SkRect safe_bounds = bounds; - return AccumulateOpBounds(safe_bounds, paint, flags); - } - - // Records the bounds for an op after modifying them according to the - // supplied attribute flags and transforming by the current matrix - // and clipping against the current clip. - bool AccumulateOpBounds(SkRect& bounds, - const DlPaint* paint, - DisplayListAttributeFlags flags); - - // Records the given bounds after transforming by the current matrix - // and clipping against the current clip. - bool AccumulateBounds(SkRect& bounds); - - DlPaint current_; - static DlPaint kDefaultPaint_; -}; - -} // namespace flutter - -#endif // FLUTTER_DISPLAY_LIST_DL_CANVAS_TO_RECEIVER_H_ diff --git a/display_list/dl_op_flags.h b/display_list/dl_op_flags.h index df6aa23990649..9bb6c013f8203 100644 --- a/display_list/dl_op_flags.h +++ b/display_list/dl_op_flags.h @@ -75,13 +75,6 @@ class DisplayListFlags { // mitered extensions outside the pre-transformed bounding box. static constexpr int kMayHaveAcuteJoins_ = 1 << 8; - // Some primitives render with a different algorithm on Skia - // when the line width is a hairline and that algorithm does - // not apply inherited opacity appropriately. We mark these - // operations with a flag so that we only disallow opacity - // inheritance on hairlines for those primitives. - static constexpr int kMayHaveTroubleWithHairlines_ = 1 << 9; - static constexpr int kAnySpecialGeometryMask_ = // kMayHaveCaps_ | kMayHaveJoins_ | kButtCapIsSquare_ | // kMayHaveDiagonalCaps_ | kMayHaveAcuteJoins_; @@ -227,12 +220,6 @@ class DisplayListAttributeFlags : DisplayListFlagsBase { (style != DlDrawStyle::kFill && has_any(kIsDrawnGeometry_))); } - /// The operation may use an implementation for hairlines that - /// does not inherit opacity properly - constexpr bool may_have_trouble_with_hairlines() const { - return has_any(kMayHaveTroubleWithHairlines_); - } - constexpr bool is_flood() const { return has_any(kFloodsSurface_); } constexpr bool operator==(DisplayListAttributeFlags const& other) const { @@ -349,13 +336,12 @@ class DisplayListOpFlags : DisplayListFlags { kBASE_StrokeOrFillFlags_ // }; static constexpr DisplayListAttributeFlags kDrawPathFlags{ - kBASE_PaintFlags_ | // - kBASE_StrokeOrFillFlags_ | // - kMayHaveCaps_ | // - kMayHaveDiagonalCaps_ | // - kMayHaveJoins_ | // - kMayHaveAcuteJoins_ | // - kMayHaveTroubleWithHairlines_ // + kBASE_PaintFlags_ | // + kBASE_StrokeOrFillFlags_ | // + kMayHaveCaps_ | // + kMayHaveDiagonalCaps_ | // + kMayHaveJoins_ | // + kMayHaveAcuteJoins_ // }; static constexpr DisplayListAttributeFlags kDrawArcNoCenterFlags{ kBASE_PaintFlags_ | // @@ -364,11 +350,10 @@ class DisplayListOpFlags : DisplayListFlags { kMayHaveDiagonalCaps_ // }; static constexpr DisplayListAttributeFlags kDrawArcWithCenterFlags{ - kBASE_PaintFlags_ | // - kBASE_StrokeOrFillFlags_ | // - kMayHaveJoins_ | // - kMayHaveAcuteJoins_ | // - kMayHaveTroubleWithHairlines_ // + kBASE_PaintFlags_ | // + kBASE_StrokeOrFillFlags_ | // + kMayHaveJoins_ | // + kMayHaveAcuteJoins_ // }; static constexpr DisplayListAttributeFlags kDrawPointsAsPointsFlags{ kBASE_PaintFlags_ | // diff --git a/display_list/dl_op_receiver.h b/display_list/dl_op_receiver.h index 36bdaef69cf1d..491af9f99f028 100644 --- a/display_list/dl_op_receiver.h +++ b/display_list/dl_op_receiver.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_H_ -#define FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_H_ +#ifndef FLUTTER_DISPLAY_LIST_DISPLAY_LIST_DISPATCHER_H_ +#define FLUTTER_DISPLAY_LIST_DISPLAY_LIST_DISPATCHER_H_ #include "flutter/display_list/display_list.h" #include "flutter/display_list/dl_blend_mode.h" @@ -38,8 +38,6 @@ class DlOpReceiver { // MaxDrawPointsCount * sizeof(SkPoint) must be less than 1 << 32 static constexpr int kMaxDrawPointsCount = ((1 << 29) - 1); - virtual ~DlOpReceiver() = default; - // The following methods are nearly 1:1 with the methods on DlPaint and // carry the same meanings. Each method sets a persistent value for the // attribute for the rest of the display list or until it is reset by @@ -218,23 +216,23 @@ class DlOpReceiver { uint32_t count, const SkPoint points[]) = 0; virtual void drawVertices(const DlVertices* vertices, DlBlendMode mode) = 0; - virtual void drawImage(const sk_sp& image, + virtual void drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) = 0; virtual void drawImageRect( - const sk_sp& image, + const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint = SrcRectConstraint::kFast) = 0; - virtual void drawImageNine(const sk_sp& image, + virtual void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) = 0; - virtual void drawAtlas(const sk_sp& atlas, + virtual void drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -243,9 +241,9 @@ class DlOpReceiver { DlImageSampling sampling, const SkRect* cull_rect, bool render_with_attributes) = 0; - virtual void drawDisplayList(const sk_sp& display_list, + virtual void drawDisplayList(const sk_sp display_list, SkScalar opacity = SK_Scalar1) = 0; - virtual void drawTextBlob(const sk_sp& blob, + virtual void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) = 0; virtual void drawShadow(const SkPath& path, @@ -257,4 +255,4 @@ class DlOpReceiver { } // namespace flutter -#endif // FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_H_ +#endif // FLUTTER_DISPLAY_LIST_DISPLAY_LIST_DISPATCHER_H_ diff --git a/display_list/dl_op_recorder.cc b/display_list/dl_op_recorder.cc deleted file mode 100644 index accd0ae03f182..0000000000000 --- a/display_list/dl_op_recorder.cc +++ /dev/null @@ -1,691 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "flutter/display_list/dl_op_recorder.h" - -#include "flutter/display_list/dl_attributes.h" -#include "flutter/display_list/dl_op_records.h" -#include "flutter/display_list/effects/dl_color_source.h" - -namespace flutter { - -#define DL_BUILDER_PAGE 4096 - -// CopyV(dst, src,n, src,n, ...) copies any number of typed srcs into dst. -static void CopyV(void* dst) {} - -template -static void CopyV(void* dst, const S* src, int n, Rest&&... rest) { - FML_DCHECK(((uintptr_t)dst & (alignof(S) - 1)) == 0) - << "Expected " << dst << " to be aligned for at least " << alignof(S) - << " bytes."; - // If n is 0, there is nothing to copy into dst from src. - if (n > 0) { - memcpy(dst, src, n * sizeof(S)); - dst = reinterpret_cast(reinterpret_cast(dst) + - n * sizeof(S)); - } - // Repeat for the next items, if any - CopyV(dst, std::forward(rest)...); -} - -DlOpRecorder::DlOpRecorder(const SkRect& cull_rect, bool keep_rtree) { - tracker_ = - std::make_shared(cull_rect, SkMatrix::I()); - if (keep_rtree) { - accumulator_ = std::make_shared(); - } else { - accumulator_ = std::make_shared(); - } - save_infos_.push_back({ - .offset = 0u, - .deferred = false, - .is_layer = false, - }); -} - -template -void* DlOpRecorder::Push(size_t pod, int render_op_inc, Args&&... args) { - size_t size = SkAlignPtr(sizeof(T) + pod); - auto op = reinterpret_cast(storage_.alloc(size)); - new (op) T{std::forward(args)...}; - op->type = T::kType; - op->size = size; - render_op_count_ += render_op_inc; - op_index_++; - return op + 1; -} - -void DlOpRecorder::setAntiAlias(bool aa) { - Push(0, 0, aa); -} -void DlOpRecorder::setDither(bool dither) { - Push(0, 0, dither); -} -void DlOpRecorder::setInvertColors(bool invert) { - Push(0, 0, invert); -} -void DlOpRecorder::setStrokeCap(DlStrokeCap cap) { - Push(0, 0, cap); -} -void DlOpRecorder::setStrokeJoin(DlStrokeJoin join) { - Push(0, 0, join); -} -void DlOpRecorder::setDrawStyle(DlDrawStyle style) { - Push(0, 0, style); -} -void DlOpRecorder::setStrokeWidth(float width) { - Push(0, 0, width); -} -void DlOpRecorder::setStrokeMiter(float limit) { - Push(0, 0, limit); -} -void DlOpRecorder::setColor(DlColor color) { - Push(0, 0, color); -} -void DlOpRecorder::setBlendMode(DlBlendMode mode) { - Push(0, 0, mode); -} - -void DlOpRecorder::setColorSource(const DlColorSource* source) { - if (source == nullptr) { - Push(0, 0); - } else { - is_ui_thread_safe_ = is_ui_thread_safe_ && source->isUIThreadSafe(); - switch (source->type()) { - case DlColorSourceType::kColor: { - const DlColorColorSource* color_source = source->asColor(); - setColor(color_source->color()); - break; - } - case DlColorSourceType::kImage: { - const DlImageColorSource* image_source = source->asImage(); - FML_DCHECK(image_source); - Push(0, 0, image_source); - break; - } - case DlColorSourceType::kLinearGradient: { - const DlLinearGradientColorSource* linear = source->asLinearGradient(); - FML_DCHECK(linear); - void* pod = Push(linear->size(), 0); - new (pod) DlLinearGradientColorSource(linear); - break; - } - case DlColorSourceType::kRadialGradient: { - const DlRadialGradientColorSource* radial = source->asRadialGradient(); - FML_DCHECK(radial); - void* pod = Push(radial->size(), 0); - new (pod) DlRadialGradientColorSource(radial); - break; - } - case DlColorSourceType::kConicalGradient: { - const DlConicalGradientColorSource* conical = - source->asConicalGradient(); - FML_DCHECK(conical); - void* pod = Push(conical->size(), 0); - new (pod) DlConicalGradientColorSource(conical); - break; - } - case DlColorSourceType::kSweepGradient: { - const DlSweepGradientColorSource* sweep = source->asSweepGradient(); - FML_DCHECK(sweep); - void* pod = Push(sweep->size(), 0); - new (pod) DlSweepGradientColorSource(sweep); - break; - } - case DlColorSourceType::kRuntimeEffect: { - const DlRuntimeEffectColorSource* effect = source->asRuntimeEffect(); - FML_DCHECK(effect); - Push(0, 0, effect); - break; - } -#ifdef IMPELLER_ENABLE_3D - case DlColorSourceType::kScene: { - const DlSceneColorSource* scene = source->asScene(); - FML_DCHECK(scene); - Push(0, 0, scene); - break; - } -#endif // IMPELLER_ENABLE_3D - } - } -} -void DlOpRecorder::setImageFilter(const DlImageFilter* filter) { - if (filter == nullptr) { - Push(0, 0); - } else { - switch (filter->type()) { - case DlImageFilterType::kBlur: { - const DlBlurImageFilter* blur_filter = filter->asBlur(); - FML_DCHECK(blur_filter); - void* pod = Push(blur_filter->size(), 0); - new (pod) DlBlurImageFilter(blur_filter); - break; - } - case DlImageFilterType::kDilate: { - const DlDilateImageFilter* dilate_filter = filter->asDilate(); - FML_DCHECK(dilate_filter); - void* pod = Push(dilate_filter->size(), 0); - new (pod) DlDilateImageFilter(dilate_filter); - break; - } - case DlImageFilterType::kErode: { - const DlErodeImageFilter* erode_filter = filter->asErode(); - FML_DCHECK(erode_filter); - void* pod = Push(erode_filter->size(), 0); - new (pod) DlErodeImageFilter(erode_filter); - break; - } - case DlImageFilterType::kMatrix: { - const DlMatrixImageFilter* matrix_filter = filter->asMatrix(); - FML_DCHECK(matrix_filter); - void* pod = Push(matrix_filter->size(), 0); - new (pod) DlMatrixImageFilter(matrix_filter); - break; - } - case DlImageFilterType::kCompose: - case DlImageFilterType::kLocalMatrix: - case DlImageFilterType::kColorFilter: { - Push(0, 0, filter); - break; - } - } - } -} -void DlOpRecorder::setColorFilter(const DlColorFilter* filter) { - if (filter == nullptr) { - Push(0, 0); - } else { - switch (filter->type()) { - case DlColorFilterType::kBlend: { - const DlBlendColorFilter* blend_filter = filter->asBlend(); - FML_DCHECK(blend_filter); - void* pod = Push(blend_filter->size(), 0); - new (pod) DlBlendColorFilter(blend_filter); - break; - } - case DlColorFilterType::kMatrix: { - const DlMatrixColorFilter* matrix_filter = filter->asMatrix(); - FML_DCHECK(matrix_filter); - void* pod = Push(matrix_filter->size(), 0); - new (pod) DlMatrixColorFilter(matrix_filter); - break; - } - case DlColorFilterType::kSrgbToLinearGamma: { - void* pod = Push(filter->size(), 0); - new (pod) DlSrgbToLinearGammaColorFilter(); - break; - } - case DlColorFilterType::kLinearToSrgbGamma: { - void* pod = Push(filter->size(), 0); - new (pod) DlLinearToSrgbGammaColorFilter(); - break; - } - } - } -} -void DlOpRecorder::setPathEffect(const DlPathEffect* effect) { - if (effect == nullptr) { - Push(0, 0); - } else { - switch (effect->type()) { - case DlPathEffectType::kDash: { - const DlDashPathEffect* dash_effect = effect->asDash(); - void* pod = Push(dash_effect->size(), 0); - new (pod) DlDashPathEffect(dash_effect); - break; - } - } - } -} -void DlOpRecorder::setMaskFilter(const DlMaskFilter* filter) { - if (filter == nullptr) { - Push(0, 0); - } else { - switch (filter->type()) { - case DlMaskFilterType::kBlur: { - const DlBlurMaskFilter* blur_filter = filter->asBlur(); - FML_DCHECK(blur_filter); - void* pod = Push(blur_filter->size(), 0); - new (pod) DlBlurMaskFilter(blur_filter); - break; - } - } - } -} - -void DlOpRecorder::save() { - save_infos_.push_back({ - .offset = 0u, - .deferred = true, - .is_layer = false, - }); - tracker_->save(); - accumulator_->save(); -} -void DlOpRecorder::ResolveDeferredSave() { - SaveInfo& save_info_ref = save_infos_.back(); - if (save_info_ref.deferred) { - FML_DCHECK(save_info_ref.is_layer == false); - FML_DCHECK(save_info_ref.offset == 0u); - save_info_ref.offset = storage_.used(); - save_info_ref.deferred = false; - Push(0, 1); - } -} -void DlOpRecorder::saveLayer(const SkRect* bounds, - const SaveLayerOptions options, - const DlImageFilter* backdrop) { - save_infos_.push_back({ - .offset = storage_.used(), - .deferred = false, - .is_layer = true, - }); - tracker_->save(); - accumulator_->save(); - if (backdrop) { - bounds // - ? Push(0, 1, options, *bounds, backdrop) - : Push(0, 1, options, backdrop); - } else { - bounds // - ? Push(0, 1, options, *bounds) - : Push(0, 1, options); - } -} - -void DlOpRecorder::restore() { - FML_DCHECK(!save_infos_.empty()); - { // Ensure all uses of save_info_ref occur before pop_back() - const SaveInfo& save_info_ref = save_infos_.back(); - if (save_info_ref.is_layer) { - // This should only happen when unrolling the save stack - // in the Build() method. - restoreLayer(nullptr, false, false); - return; - } - - if (!save_info_ref.deferred) { - SaveOpBase* op = - reinterpret_cast(storage_.get() + save_info_ref.offset); - FML_DCHECK(op->type == DisplayListOpType::kSave); - op->restore_index = op_index_; - - Push(0, 1); - } - } // save_info_ref no longer accessible - save_infos_.pop_back(); - - tracker_->restore(); - accumulator_->restore(); -} -void DlOpRecorder::restoreLayer(const DlImageFilter* filter, - bool layer_content_was_unbounded, - bool layer_could_distribute_opacity) { - FML_DCHECK(!save_infos_.empty()); - { // Ensure all uses of save_info_ref occur before pop_back() - SaveInfo& save_info_ref = save_infos_.back(); - FML_DCHECK(save_info_ref.is_layer == true); - FML_DCHECK(save_info_ref.deferred == false); - - SaveOpBase* op = - reinterpret_cast(storage_.get() + save_info_ref.offset); - FML_DCHECK(op->type == DisplayListOpType::kSaveLayer || - op->type == DisplayListOpType::kSaveLayerBounds || - op->type == DisplayListOpType::kSaveLayerBackdrop || - op->type == DisplayListOpType::kSaveLayerBackdropBounds); - op->restore_index = op_index_; - if (layer_could_distribute_opacity) { - op->options = op->options.with_can_distribute_opacity(); - } - } // save_info_ref no longer accessible - save_infos_.pop_back(); - - Push(0, 1); - - // Manage the layer bounds before we push the restore op so that any - // bounds we need to adjust get tagged on the RestoreOp rather than - // the rendering op that follows it. - - // Restore the tracker before we manage the layer bounds so that we use - // the enclosing cull_rect and transform for filtering bounds. - tracker_->restore(); - const SkRect clip = tracker_->device_cull_rect(); - - // As we pop the accumulator we will adjust the bounds associated with - // the layer content by the layer filter. - // We have already restored the tracker so that the cull_rect information - // we use in the adjustment is from the environment outside of the layer. - // If there is a failure in converting the bounds within the layer due - // to an issue with the layer filter, or if the content of the layer - // was already unbounded, we will propagate the unbounded status to the - // enclosing layer. - if (filter) { - const SkMatrix matrix = tracker_->matrix_3x3(); - if (!accumulator_->restore( - [filter, matrix](const SkRect& input, SkRect& output) { - SkIRect output_bounds; - bool ret = filter->map_device_bounds(input.roundOut(), matrix, - output_bounds); - output.set(output_bounds); - return ret; - }, - &clip)) { - layer_content_was_unbounded = true; - } - } else { - accumulator_->restore(); - } - - if (layer_content_was_unbounded) { - // Ideally we would insert this back in the list of rects with the - // OpID of the original SaveLayer... - if (!clip.isEmpty()) { - accumulator_->accumulate(clip, op_index_); - } - } -} - -void DlOpRecorder::translate(SkScalar tx, SkScalar ty) { - ResolveDeferredSave(); - tracker_->translate(tx, ty); - Push(0, 1, tx, ty); -} -void DlOpRecorder::scale(SkScalar sx, SkScalar sy) { - ResolveDeferredSave(); - tracker_->scale(sx, sy); - Push(0, 1, sx, sy); -} -void DlOpRecorder::rotate(SkScalar degrees) { - ResolveDeferredSave(); - tracker_->rotate(degrees); - Push(0, 1, degrees); -} -void DlOpRecorder::skew(SkScalar sx, SkScalar sy) { - ResolveDeferredSave(); - tracker_->skew(sx, sy); - Push(0, 1, sx, sy); -} - -// clang-format off - -// 2x3 2D affine subset of a 4x4 transform in row major order -void DlOpRecorder::transform2DAffine( - SkScalar mxx, SkScalar mxy, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myt) { - ResolveDeferredSave(); - tracker_->transform2DAffine(mxx, mxy, mxt, - myx, myy, myt); - Push(0, 1, - mxx, mxy, mxt, - myx, myy, myt); -} -// full 4x4 transform in row major order -void DlOpRecorder::transformFullPerspective( - SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, - SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, - SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) { - ResolveDeferredSave(); - tracker_->transformFullPerspective(mxx, mxy, mxz, mxt, - myx, myy, myz, myt, - mzx, mzy, mzz, mzt, - mwx, mwy, mwz, mwt); - Push(0, 1, - mxx, mxy, mxz, mxt, - myx, myy, myz, myt, - mzx, mzy, mzz, mzt, - mwx, mwy, mwz, mwt); -} -// clang-format on -void DlOpRecorder::transformReset() { - ResolveDeferredSave(); - tracker_->setIdentity(); - Push(0, 0); -} - -void DlOpRecorder::clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) { - ResolveDeferredSave(); - tracker_->clipRect(rect, clip_op, is_aa); - if (!tracker_->is_cull_rect_empty()) { - switch (clip_op) { - case ClipOp::kIntersect: - Push(0, 1, rect, is_aa); - break; - case ClipOp::kDifference: - Push(0, 1, rect, is_aa); - break; - } - } -} - -void DlOpRecorder::clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) { - ResolveDeferredSave(); - tracker_->clipRRect(rrect, clip_op, is_aa); - if (!tracker_->is_cull_rect_empty()) { - switch (clip_op) { - case ClipOp::kIntersect: - Push(0, 1, rrect, is_aa); - break; - case ClipOp::kDifference: - Push(0, 1, rrect, is_aa); - break; - } - } -} - -void DlOpRecorder::clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) { - ResolveDeferredSave(); - tracker_->clipPath(path, clip_op, is_aa); - if (!tracker_->is_cull_rect_empty()) { - switch (clip_op) { - case ClipOp::kIntersect: - Push(0, 1, path, is_aa); - break; - case ClipOp::kDifference: - Push(0, 1, path, is_aa); - break; - } - } -} -void DlOpRecorder::resetCullRect(const SkRect* cull_rect) { - tracker_->resetCullRect(cull_rect); -} -void DlOpRecorder::intersectCullRect(const SkRect& cull_rect) { - tracker_->clipRect(cull_rect, DlCanvas::ClipOp::kIntersect, false); -} - -void DlOpRecorder::drawPaint() { - Push(0, 1); -} -void DlOpRecorder::drawColor(DlColor color, DlBlendMode mode) { - Push(0, 1, color, mode); -} -void DlOpRecorder::drawLine(const SkPoint& p0, const SkPoint& p1) { - Push(0, 1, p0, p1); -} -void DlOpRecorder::drawRect(const SkRect& rect) { - Push(0, 1, rect); -} -void DlOpRecorder::drawOval(const SkRect& bounds) { - Push(0, 1, bounds); -} -void DlOpRecorder::drawCircle(const SkPoint& center, SkScalar radius) { - Push(0, 1, center, radius); -} -void DlOpRecorder::drawRRect(const SkRRect& rrect) { - Push(0, 1, rrect); -} -void DlOpRecorder::drawDRRect(const SkRRect& outer, const SkRRect& inner) { - Push(0, 1, outer, inner); -} -void DlOpRecorder::drawPath(const SkPath& path) { - Push(0, 1, path); -} - -void DlOpRecorder::drawArc(const SkRect& bounds, - SkScalar start, - SkScalar sweep, - bool useCenter) { - Push(0, 1, bounds, start, sweep, useCenter); -} - -void DlOpRecorder::drawPoints(PointMode mode, - uint32_t count, - const SkPoint pts[]) { - FML_DCHECK(count > 0); - FML_DCHECK(count < DlOpReceiver::kMaxDrawPointsCount); - int bytes = count * sizeof(SkPoint); - void* data_ptr; - switch (mode) { - case PointMode::kPoints: - data_ptr = Push(bytes, 1, count); - break; - case PointMode::kLines: - data_ptr = Push(bytes, 1, count); - break; - case PointMode::kPolygon: - data_ptr = Push(bytes, 1, count); - break; - default: - FML_UNREACHABLE(); - return; - } - CopyV(data_ptr, pts, count); -} -void DlOpRecorder::drawVertices(const DlVertices* vertices, DlBlendMode mode) { - void* pod = Push(vertices->size(), 1, mode); - new (pod) DlVertices(vertices); -} - -void DlOpRecorder::drawImage(const sk_sp& image, - const SkPoint point, - DlImageSampling sampling, - bool render_with_attributes) { - render_with_attributes - ? Push(0, 1, image, point, sampling) - : Push(0, 1, image, point, sampling); - is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); -} -void DlOpRecorder::drawImageRect(const sk_sp& image, - const SkRect& src, - const SkRect& dst, - DlImageSampling sampling, - bool render_with_attributes, - SrcRectConstraint constraint) { - Push(0, 1, image, src, dst, sampling, // - render_with_attributes, constraint); - is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); -} -void DlOpRecorder::drawImageNine(const sk_sp& image, - const SkIRect& center, - const SkRect& dst, - DlFilterMode filter, - bool render_with_attributes) { - render_with_attributes - ? Push(0, 1, image, center, dst, filter) - : Push(0, 1, image, center, dst, filter); - is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); -} -void DlOpRecorder::drawAtlas(const sk_sp& atlas, - const SkRSXform xform[], - const SkRect tex[], - const DlColor colors[], - int count, - DlBlendMode mode, - DlImageSampling sampling, - const SkRect* cull_rect, - bool render_with_attributes) { - int bytes = count * (sizeof(SkRSXform) + sizeof(SkRect)); - void* data_ptr; - if (colors != nullptr) { - bytes += count * sizeof(DlColor); - if (cull_rect != nullptr) { - data_ptr = - Push(bytes, 1, atlas, count, mode, sampling, true, - *cull_rect, render_with_attributes); - } else { - data_ptr = Push(bytes, 1, atlas, count, mode, sampling, true, - render_with_attributes); - } - CopyV(data_ptr, xform, count, tex, count, colors, count); - } else { - if (cull_rect != nullptr) { - data_ptr = - Push(bytes, 1, atlas, count, mode, sampling, false, - *cull_rect, render_with_attributes); - } else { - data_ptr = Push(bytes, 1, atlas, count, mode, sampling, - false, render_with_attributes); - } - CopyV(data_ptr, xform, count, tex, count); - } - is_ui_thread_safe_ = is_ui_thread_safe_ && atlas->isUIThreadSafe(); -} - -void DlOpRecorder::drawDisplayList(const sk_sp& display_list, - SkScalar opacity) { - Push(0, 1, display_list, opacity); - nested_op_count_ += display_list->op_count(true) - 1; - nested_bytes_ += display_list->bytes(true); - is_ui_thread_safe_ = is_ui_thread_safe_ && display_list->isUIThreadSafe(); -} -void DlOpRecorder::drawTextBlob(const sk_sp& blob, - SkScalar x, - SkScalar y) { - Push(0, 1, blob, x, y); -} -void DlOpRecorder::drawShadow(const SkPath& path, - const DlColor color, - const SkScalar elevation, - bool transparent_occluder, - SkScalar dpr) { - transparent_occluder // - ? Push(0, 1, path, color, elevation, dpr) - : Push(0, 1, path, color, elevation, dpr); -} - -bool DlOpRecorder::accumulateLocalBoundsForNextOp(const SkRect& r) { - if (!r.isEmpty()) { - SkRect bounds = r; - tracker_->mapRect(&bounds); - if (bounds.intersect(tracker_->device_cull_rect())) { - accumulator_->accumulate(bounds, render_op_count_); - return true; - } - } - return false; -} -bool DlOpRecorder::accumulateUnboundedForNextOp() { - SkRect clip = tracker_->device_cull_rect(); - if (!clip.isEmpty()) { - accumulator_->accumulate(clip, render_op_count_); - return true; - } - return false; -} - -sk_sp DlOpRecorder::Build(bool can_distribute_opacity, - bool affects_transparent_layer) { - if (!storage_.is_valid()) { - FML_DCHECK(storage_.is_valid()); - return nullptr; - } - - while (save_infos_.size() > 1u) { - restore(); - } - - auto rtree = accumulator_->rtree(); - // It is faster to ask the completed rtree for bounds than to ask - // the accumulator to run through all of its rects for the bounds. - auto bounds = rtree ? rtree->bounds() : accumulator_->bounds(); - - return sk_sp( - new DisplayList(storage_.take(), render_op_count_, nested_bytes_, - nested_op_count_, bounds, can_distribute_opacity, - is_ui_thread_safe_, affects_transparent_layer, rtree)); -} - -} // namespace flutter diff --git a/display_list/dl_op_recorder.h b/display_list/dl_op_recorder.h deleted file mode 100644 index 438fcfeebbb29..0000000000000 --- a/display_list/dl_op_recorder.h +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FLUTTER_DISPLAY_LIST_DL_OP_RECORDER_H_ -#define FLUTTER_DISPLAY_LIST_DL_OP_RECORDER_H_ - -#include "flutter/display_list/dl_canvas_to_receiver.h" -#include "flutter/display_list/dl_op_receiver.h" -#include "flutter/display_list/utils/dl_bounds_accumulator.h" -#include "flutter/display_list/utils/dl_matrix_clip_tracker.h" - -namespace flutter { - -class DisplayList; - -//------------------------------------------------------------------------------ -/// @brief An implementation of DlOpReceiver that records the calls into -/// a buffer, typically driven from a DisplayListBuilder. -/// -class DlOpRecorder : public DlCanvasReceiver { - private: - using ClipOp = DlCanvas::ClipOp; - - public: - static constexpr SkRect kMaxCullRect = - SkRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F); - - DlOpRecorder(const SkRect& cull_rect = kMaxCullRect, bool keep_rtree = false); - - ~DlOpRecorder() = default; - - // | DlCanvasReceiver| - SkRect base_device_cull_rect() const override { - return tracker_->base_device_cull_rect(); - } - SkRect device_cull_rect() const override { - return tracker_->device_cull_rect(); - } - SkRect local_cull_rect() const override { - return tracker_->local_cull_rect(); - } - bool is_cull_rect_empty() const override { - return tracker_->is_cull_rect_empty(); - } - bool content_culled(const SkRect& content_bounds) const override { - return tracker_->content_culled(content_bounds); - } - - // | DlCanvasReceiver| - SkM44 matrix_4x4() const override { return tracker_->matrix_4x4(); } - SkMatrix matrix_3x3() const override { return tracker_->matrix_3x3(); } - - // | DlCanvasReceiver| - void resetCullRect(const SkRect* cull_rect = nullptr) override; - void intersectCullRect(const SkRect& cull_rect) override; - - // | DlCanvasReceiver| - bool wants_granular_bounds() const override { - return accumulator_->type() == BoundsAccumulator::Type::kRTree; - } - - // |DlOpReceiver| all set methods - void setAntiAlias(bool aa) override; - void setDither(bool dither) override; - void setDrawStyle(DlDrawStyle style) override; - void setColor(DlColor color) override; - void setStrokeWidth(float width) override; - void setStrokeMiter(float limit) override; - void setStrokeCap(DlStrokeCap cap) override; - void setStrokeJoin(DlStrokeJoin join) override; - void setColorSource(const DlColorSource* source) override; - void setColorFilter(const DlColorFilter* filter) override; - void setInvertColors(bool invert) override; - void setBlendMode(DlBlendMode mode) override; - void setPathEffect(const DlPathEffect* effect) override; - void setMaskFilter(const DlMaskFilter* filter) override; - void setImageFilter(const DlImageFilter* filter) override; - - // |DlOpReceiver| - void save() override; - // |DlOpReceiver| - void saveLayer(const SkRect* bounds, - const SaveLayerOptions options, - const DlImageFilter* backdrop = nullptr) override; - - // |DlOpReceiver| - void restore() override; - // |DlCanvasReceiver| - void restoreLayer(const DlImageFilter*, - bool layer_content_was_unbounded, - bool layer_could_distribute_opacity) override; - - // |DlOpReceiver| all transform methods - void translate(SkScalar tx, SkScalar ty) override; - void scale(SkScalar sx, SkScalar sy) override; - void rotate(SkScalar degrees) override; - void skew(SkScalar sx, SkScalar sy) override; - - // clang-format off - // |DlOpReceiver| - void transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myt) override; - // |DlOpReceiver| - void transformFullPerspective( - SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, - SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, - SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, - SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override; - // clang-format on - - // |DlOpReceiver| - void transformReset() override; - - // |DlOpReceiver| all clip methods - void clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) override; - void clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) override; - void clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) override; - - // |DlOpReceiver| all render methods - void drawColor(DlColor color, DlBlendMode mode) override; - void drawPaint() override; - void drawLine(const SkPoint& p0, const SkPoint& p1) override; - void drawRect(const SkRect& rect) override; - void drawOval(const SkRect& bounds) override; - void drawCircle(const SkPoint& center, SkScalar radius) override; - void drawRRect(const SkRRect& rrect) override; - void drawDRRect(const SkRRect& outer, const SkRRect& inner) override; - void drawPath(const SkPath& path) override; - void drawArc(const SkRect& oval_bounds, - SkScalar start_degrees, - SkScalar sweep_degrees, - bool use_center) override; - void drawPoints(PointMode mode, - uint32_t count, - const SkPoint points[]) override; - void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; - void drawImage(const sk_sp& image, - const SkPoint point, - DlImageSampling sampling, - bool render_with_attributes) override; - void drawImageRect( - const sk_sp& image, - const SkRect& src, - const SkRect& dst, - DlImageSampling sampling, - bool render_with_attributes, - SrcRectConstraint constraint = SrcRectConstraint::kFast) override; - void drawImageNine(const sk_sp& image, - const SkIRect& center, - const SkRect& dst, - DlFilterMode filter, - bool render_with_attributes) override; - void drawAtlas(const sk_sp& atlas, - const SkRSXform xform[], - const SkRect tex[], - const DlColor colors[], - int count, - DlBlendMode mode, - DlImageSampling sampling, - const SkRect* cull_rect, - bool render_with_attributes) override; - void drawDisplayList(const sk_sp& display_list, - SkScalar opacity = SK_Scalar1) override; - void drawTextBlob(const sk_sp& blob, - SkScalar x, - SkScalar y) override; - void drawShadow(const SkPath& path, - const DlColor color, - const SkScalar elevation, - bool transparent_occluder, - SkScalar dpr) override; - - bool accumulateLocalBoundsForNextOp(const SkRect& r) override; - bool accumulateUnboundedForNextOp() override; - - bool is_nop() override { return tracker_->is_cull_rect_empty(); } - - sk_sp Build(bool can_distribute_opacity = false, - bool affects_transparent_layer = true); - - private: - std::shared_ptr tracker_; - std::shared_ptr accumulator_; - DisplayList::DlStorage storage_; - - struct SaveInfo { - size_t offset; - bool deferred; - bool is_layer; - }; - std::vector save_infos_; - void ResolveDeferredSave(); - - int render_op_count_ = 0; - int op_index_ = 0; - - // bytes and ops from |drawPicture| and |drawDisplayList| - size_t nested_bytes_ = 0; - int nested_op_count_ = 0; - - bool is_ui_thread_safe_ = true; - - template - void* Push(size_t extra, int op_inc, Args&&... args); -}; - -} // namespace flutter - -#endif // FLUTTER_DISPLAY_LIST_DL_OP_RECORDER_H_ diff --git a/display_list/dl_op_records.h b/display_list/dl_op_records.h index 88876f3956141..47cdeb9d0e6fb 100644 --- a/display_list/dl_op_records.h +++ b/display_list/dl_op_records.h @@ -19,7 +19,7 @@ namespace flutter { // Structure holding the information necessary to dispatch and // potentially cull the DLOps during playback. // -// Generally drawing ops will execute as long as |cur_render_index| +// Generally drawing ops will execute as long as |cur_index| // is at or after |next_render_index|, so setting the latter // to 0 will render all primitives and setting it to MAX_INT // will skip all remaining rendering primitives. @@ -40,7 +40,7 @@ namespace flutter { struct DispatchContext { DlOpReceiver& receiver; - int cur_render_index; + int cur_index; int next_render_index; int next_restore_index; @@ -328,7 +328,6 @@ struct SaveOpBase : DLOp { bool needed = ctx.next_render_index <= restore_index; ctx.save_infos.emplace_back(ctx.next_restore_index, needed); ctx.next_restore_index = restore_index; - ctx.cur_render_index++; return needed; } }; @@ -418,44 +417,25 @@ struct SaveLayerBackdropBoundsOp final : SaveOpBase { : DisplayListCompare::kNotEqual; } }; -// The base object for the restore() op // 4 byte header + no payload uses minimum 8 bytes (4 bytes unused) -struct RestoreOpBase : DLOp { - RestoreOpBase() {} - - inline bool restore_needed(DispatchContext& ctx) const { - bool restore_needed; - { - // ensure all use of save_infos.back happens before the pop - DispatchContext::SaveInfo& info = ctx.save_infos.back(); - restore_needed = info.save_was_needed; - ctx.next_restore_index = info.previous_restore_index; - } - ctx.cur_render_index++; - ctx.save_infos.pop_back(); - return restore_needed; - } -}; -// 4 byte header + no payload uses minimum 8 bytes (4 bytes unused) -struct RestoreOp final : RestoreOpBase { +struct RestoreOp final : DLOp { static const auto kType = DisplayListOpType::kRestore; RestoreOp() {} void dispatch(DispatchContext& ctx) const { - if (restore_needed(ctx)) { + DispatchContext::SaveInfo& info = ctx.save_infos.back(); + if (info.save_was_needed) { ctx.receiver.restore(); } + ctx.next_restore_index = info.previous_restore_index; + ctx.save_infos.pop_back(); } }; struct TransformClipOpBase : DLOp { - inline bool tx_clip_needed(DispatchContext& ctx) const { - // We only dispatch a transform or clip if we are going to render - // something before it gets erased by the next restore. - bool tx_clip_needed = (ctx.next_render_index <= ctx.next_restore_index); - ctx.cur_render_index++; - return tx_clip_needed; + inline bool op_needed(const DispatchContext& context) const { + return context.next_render_index <= context.next_restore_index; } }; // 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes @@ -469,7 +449,7 @@ struct TranslateOp final : TransformClipOpBase { const SkScalar ty; void dispatch(DispatchContext& ctx) const { - if (tx_clip_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.translate(tx, ty); } } @@ -485,7 +465,7 @@ struct ScaleOp final : TransformClipOpBase { const SkScalar sy; void dispatch(DispatchContext& ctx) const { - if (tx_clip_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.scale(sx, sy); } } @@ -499,7 +479,7 @@ struct RotateOp final : TransformClipOpBase { const SkScalar degrees; void dispatch(DispatchContext& ctx) const { - if (tx_clip_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.rotate(degrees); } } @@ -515,7 +495,7 @@ struct SkewOp final : TransformClipOpBase { const SkScalar sy; void dispatch(DispatchContext& ctx) const { - if (tx_clip_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.skew(sx, sy); } } @@ -535,7 +515,7 @@ struct Transform2DAffineOp final : TransformClipOpBase { const SkScalar myx, myy, myt; void dispatch(DispatchContext& ctx) const { - if (tx_clip_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.transform2DAffine(mxx, mxy, mxt, // myx, myy, myt); } @@ -564,7 +544,7 @@ struct TransformFullPerspectiveOp final : TransformClipOpBase { const SkScalar mwx, mwy, mwz, mwt; void dispatch(DispatchContext& ctx) const { - if (tx_clip_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.transformFullPerspective(mxx, mxy, mxz, mxt, // myx, myy, myz, myt, // mzx, mzy, mzz, mzt, // @@ -580,7 +560,7 @@ struct TransformResetOp final : TransformClipOpBase { TransformResetOp() = default; void dispatch(DispatchContext& ctx) const { - if (tx_clip_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.transformReset(); } } @@ -607,7 +587,7 @@ struct TransformResetOp final : TransformClipOpBase { const Sk##shapetype shape; \ \ void dispatch(DispatchContext& ctx) const { \ - if (tx_clip_needed(ctx)) { \ + if (op_needed(ctx)) { \ ctx.receiver.clip##shapetype(shape, DlCanvas::ClipOp::k##clipop, \ is_aa); \ } \ @@ -630,7 +610,7 @@ DEFINE_CLIP_SHAPE_OP(RRect, Difference) const SkPath path; \ \ void dispatch(DispatchContext& ctx) const { \ - if (tx_clip_needed(ctx)) { \ + if (op_needed(ctx)) { \ ctx.receiver.clipPath(path, DlCanvas::ClipOp::k##clipop, is_aa); \ } \ } \ @@ -646,8 +626,8 @@ DEFINE_CLIP_PATH_OP(Difference) #undef DEFINE_CLIP_PATH_OP struct DrawOpBase : DLOp { - inline bool draw_needed(DispatchContext& ctx) const { - return ctx.cur_render_index++ >= ctx.next_render_index; + inline bool op_needed(const DispatchContext& ctx) const { + return ctx.cur_index >= ctx.next_render_index; } }; @@ -658,7 +638,7 @@ struct DrawPaintOp final : DrawOpBase { DrawPaintOp() {} void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.drawPaint(); } } @@ -674,7 +654,7 @@ struct DrawColorOp final : DrawOpBase { const DlBlendMode mode; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.drawColor(color, mode); } } @@ -694,7 +674,7 @@ struct DrawColorOp final : DrawOpBase { const arg_type arg_name; \ \ void dispatch(DispatchContext& ctx) const { \ - if (draw_needed(ctx)) { \ + if (op_needed(ctx)) { \ ctx.receiver.draw##op_name(arg_name); \ } \ } \ @@ -714,7 +694,7 @@ struct DrawPathOp final : DrawOpBase { const SkPath path; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.drawPath(path); } } @@ -742,7 +722,7 @@ struct DrawPathOp final : DrawOpBase { const type2 name2; \ \ void dispatch(DispatchContext& ctx) const { \ - if (draw_needed(ctx)) { \ + if (op_needed(ctx)) { \ ctx.receiver.draw##op_name(name1, name2); \ } \ } \ @@ -765,7 +745,7 @@ struct DrawArcOp final : DrawOpBase { const bool center; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.drawArc(bounds, start, sweep, center); } } @@ -786,7 +766,7 @@ struct DrawArcOp final : DrawOpBase { const uint32_t count; \ \ void dispatch(DispatchContext& ctx) const { \ - if (draw_needed(ctx)) { \ + if (op_needed(ctx)) { \ const SkPoint* pts = reinterpret_cast(this + 1); \ ctx.receiver.drawPoints(DlCanvas::PointMode::mode, count, pts); \ } \ @@ -812,7 +792,7 @@ struct DrawVerticesOp final : DrawOpBase { const DlBlendMode mode; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { const DlVertices* vertices = reinterpret_cast(this + 1); ctx.receiver.drawVertices(vertices, mode); @@ -836,7 +816,7 @@ struct DrawVerticesOp final : DrawOpBase { const sk_sp image; \ \ void dispatch(DispatchContext& ctx) const { \ - if (draw_needed(ctx)) { \ + if (op_needed(ctx)) { \ ctx.receiver.drawImage(image, point, sampling, with_attributes); \ } \ } \ @@ -878,7 +858,7 @@ struct DrawImageRectOp final : DrawOpBase { const sk_sp image; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.drawImageRect(image, src, dst, sampling, render_with_attributes, constraint); } @@ -911,7 +891,7 @@ struct DrawImageRectOp final : DrawOpBase { const sk_sp image; \ \ void dispatch(DispatchContext& ctx) const { \ - if (draw_needed(ctx)) { \ + if (op_needed(ctx)) { \ ctx.receiver.drawImageNine(image, center, dst, mode, \ render_with_attributes); \ } \ @@ -993,7 +973,7 @@ struct DrawAtlasOp final : DrawAtlasBaseOp { render_with_attributes) {} void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { const SkRSXform* xform = reinterpret_cast(this + 1); const SkRect* tex = reinterpret_cast(xform + count); const DlColor* colors = @@ -1038,7 +1018,7 @@ struct DrawAtlasCulledOp final : DrawAtlasBaseOp { const SkRect cull_rect; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { const SkRSXform* xform = reinterpret_cast(this + 1); const SkRect* tex = reinterpret_cast(xform + count); const DlColor* colors = @@ -1072,7 +1052,7 @@ struct DrawDisplayListOp final : DrawOpBase { const sk_sp display_list; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.drawDisplayList(display_list, opacity); } } @@ -1098,7 +1078,7 @@ struct DrawTextBlobOp final : DrawOpBase { const sk_sp blob; void dispatch(DispatchContext& ctx) const { - if (draw_needed(ctx)) { + if (op_needed(ctx)) { ctx.receiver.drawTextBlob(blob, x, y); } } @@ -1121,7 +1101,7 @@ struct DrawTextBlobOp final : DrawOpBase { const SkPath path; \ \ void dispatch(DispatchContext& ctx) const { \ - if (draw_needed(ctx)) { \ + if (op_needed(ctx)) { \ ctx.receiver.drawShadow(path, color, elevation, transparent_occluder, \ dpr); \ } \ diff --git a/display_list/dl_paint.h b/display_list/dl_paint.h index 88be6ccea9638..3d9220f57e3d6 100644 --- a/display_list/dl_paint.h +++ b/display_list/dl_paint.h @@ -176,7 +176,7 @@ class DlPaint { return maskFilter_; } const DlMaskFilter* getMaskFilterPtr() const { return maskFilter_.get(); } - DlPaint& setMaskFilter(std::shared_ptr filter) { + DlPaint& setMaskFilter(std::shared_ptr filter) { maskFilter_ = filter; return *this; } @@ -189,7 +189,7 @@ class DlPaint { return pathEffect_; } const DlPathEffect* getPathEffectPtr() const { return pathEffect_.get(); } - DlPaint& setPathEffect(std::shared_ptr pathEffect) { + DlPaint& setPathEffect(std::shared_ptr pathEffect) { pathEffect_ = pathEffect; return *this; } diff --git a/display_list/dl_vertices.h b/display_list/dl_vertices.h index b6749fcfe960c..7c3ed34253713 100644 --- a/display_list/dl_vertices.h +++ b/display_list/dl_vertices.h @@ -279,7 +279,7 @@ class DlVertices { return static_cast(base) + offset; } - friend class DlOpRecorder; + friend class DisplayListBuilder; }; } // namespace flutter diff --git a/display_list/dl_vertices_unittests.cc b/display_list/dl_vertices_unittests.cc index 4a18db7d2f903..f30f473b1c31f 100644 --- a/display_list/dl_vertices_unittests.cc +++ b/display_list/dl_vertices_unittests.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_vertices.h" #include "flutter/display_list/testing/dl_test_equality.h" #include "flutter/display_list/utils/dl_comparable.h" diff --git a/display_list/effects/dl_color_source.h b/display_list/effects/dl_color_source.h index 343e36031f462..11a141da9c905 100644 --- a/display_list/effects/dl_color_source.h +++ b/display_list/effects/dl_color_source.h @@ -418,7 +418,7 @@ class DlLinearGradientColorSource final : public DlGradientColorSourceBase { SkPoint end_point_; friend class DlColorSource; - friend class DlOpRecorder; + friend class DisplayListBuilder; FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlLinearGradientColorSource); }; @@ -481,7 +481,7 @@ class DlRadialGradientColorSource final : public DlGradientColorSourceBase { SkScalar radius_; friend class DlColorSource; - friend class DlOpRecorder; + friend class DisplayListBuilder; FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlRadialGradientColorSource); }; @@ -557,7 +557,7 @@ class DlConicalGradientColorSource final : public DlGradientColorSourceBase { SkScalar end_radius_; friend class DlColorSource; - friend class DlOpRecorder; + friend class DisplayListBuilder; FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlConicalGradientColorSource); }; @@ -625,7 +625,7 @@ class DlSweepGradientColorSource final : public DlGradientColorSourceBase { SkScalar end_; friend class DlColorSource; - friend class DlOpRecorder; + friend class DisplayListBuilder; FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlSweepGradientColorSource); }; diff --git a/display_list/effects/dl_path_effect.h b/display_list/effects/dl_path_effect.h index 5d27ada061655..0f9d0be60fa54 100644 --- a/display_list/effects/dl_path_effect.h +++ b/display_list/effects/dl_path_effect.h @@ -114,7 +114,7 @@ class DlDashPathEffect final : public DlPathEffect { int count_; SkScalar phase_; - friend class DlOpRecorder; + friend class DisplayListBuilder; friend class DlPathEffect; FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlDashPathEffect); diff --git a/display_list/skia/dl_sk_dispatcher.cc b/display_list/skia/dl_sk_dispatcher.cc index 41bb175296325..def08fa8886a3 100644 --- a/display_list/skia/dl_sk_dispatcher.cc +++ b/display_list/skia/dl_sk_dispatcher.cc @@ -182,14 +182,14 @@ void DlSkCanvasDispatcher::drawVertices(const DlVertices* vertices, DlBlendMode mode) { canvas_->drawVertices(ToSk(vertices), ToSk(mode), paint()); } -void DlSkCanvasDispatcher::drawImage(const sk_sp& image, +void DlSkCanvasDispatcher::drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { canvas_->drawImage(image ? image->skia_image() : nullptr, point.fX, point.fY, ToSk(sampling), safe_paint(render_with_attributes)); } -void DlSkCanvasDispatcher::drawImageRect(const sk_sp& image, +void DlSkCanvasDispatcher::drawImageRect(const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, @@ -199,7 +199,7 @@ void DlSkCanvasDispatcher::drawImageRect(const sk_sp& image, ToSk(sampling), safe_paint(render_with_attributes), ToSk(constraint)); } -void DlSkCanvasDispatcher::drawImageNine(const sk_sp& image, +void DlSkCanvasDispatcher::drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, @@ -214,7 +214,7 @@ void DlSkCanvasDispatcher::drawImageNine(const sk_sp& image, canvas_->drawImageNine(skia_image.get(), center, dst, ToSk(filter), safe_paint(render_with_attributes)); } -void DlSkCanvasDispatcher::drawAtlas(const sk_sp& atlas, +void DlSkCanvasDispatcher::drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -236,7 +236,7 @@ void DlSkCanvasDispatcher::drawAtlas(const sk_sp& atlas, safe_paint(render_with_attributes)); } void DlSkCanvasDispatcher::drawDisplayList( - const sk_sp& display_list, + const sk_sp display_list, SkScalar opacity) { const int restore_count = canvas_->getSaveCount(); @@ -264,7 +264,7 @@ void DlSkCanvasDispatcher::drawDisplayList( // Restore canvas state to what it was before dispatching. canvas_->restoreToCount(restore_count); } -void DlSkCanvasDispatcher::drawTextBlob(const sk_sp& blob, +void DlSkCanvasDispatcher::drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) { canvas_->drawTextBlob(blob, x, y, paint()); diff --git a/display_list/skia/dl_sk_dispatcher.h b/display_list/skia/dl_sk_dispatcher.h index 3ae32170028fe..fca84838df470 100644 --- a/display_list/skia/dl_sk_dispatcher.h +++ b/display_list/skia/dl_sk_dispatcher.h @@ -71,22 +71,22 @@ class DlSkCanvasDispatcher : public virtual DlOpReceiver, bool useCenter) override; void drawPoints(PointMode mode, uint32_t count, const SkPoint pts[]) override; void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; - void drawImage(const sk_sp& image, + void drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override; - void drawImageRect(const sk_sp& image, + void drawImageRect(const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint) override; - void drawImageNine(const sk_sp& image, + void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override; - void drawAtlas(const sk_sp& atlas, + void drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -95,9 +95,9 @@ class DlSkCanvasDispatcher : public virtual DlOpReceiver, DlImageSampling sampling, const SkRect* cullRect, bool render_with_attributes) override; - void drawDisplayList(const sk_sp& display_list, + void drawDisplayList(const sk_sp display_list, SkScalar opacity) override; - void drawTextBlob(const sk_sp& blob, + void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) override; void drawShadow(const SkPath& path, diff --git a/display_list/testing/dl_rendering_unittests.cc b/display_list/testing/dl_rendering_unittests.cc index a5a95b6d85004..23a80c2f13d92 100644 --- a/display_list/testing/dl_rendering_unittests.cc +++ b/display_list/testing/dl_rendering_unittests.cc @@ -5,7 +5,7 @@ #include #include "flutter/display_list/display_list.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_op_flags.h" #include "flutter/display_list/dl_sampling_options.h" #include "flutter/display_list/skia/dl_sk_canvas.h" diff --git a/display_list/testing/dl_test_snippets.cc b/display_list/testing/dl_test_snippets.cc index bd7cb1a288e7c..0a53f0337afd9 100644 --- a/display_list/testing/dl_test_snippets.cc +++ b/display_list/testing/dl_test_snippets.cc @@ -3,7 +3,7 @@ // found in the LICENSE file. #include "flutter/display_list/testing/dl_test_snippets.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_op_receiver.h" namespace flutter { @@ -46,17 +46,17 @@ std::vector CreateAllAttributesOps() { {"SetAntiAlias", { {0, 8, 0, 0, [](DlOpReceiver& r) { r.setAntiAlias(true); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setAntiAlias(false); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setAntiAlias(false); }}, }}, {"SetDither", { {0, 8, 0, 0, [](DlOpReceiver& r) { r.setDither(true); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setDither(false); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setDither(false); }}, }}, {"SetInvertColors", { {0, 8, 0, 0, [](DlOpReceiver& r) { r.setInvertColors(true); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setInvertColors(false); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setInvertColors(false); }}, }}, {"SetStrokeCap", { @@ -64,7 +64,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setStrokeCap(DlStrokeCap::kRound); }}, {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeCap(DlStrokeCap::kSquare); }}, - {0, 8, 0, 0, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setStrokeCap(DlStrokeCap::kButt); }}, }}, {"SetStrokeJoin", @@ -73,7 +73,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setStrokeJoin(DlStrokeJoin::kBevel); }}, {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeJoin(DlStrokeJoin::kRound); }}, - {0, 8, 0, 0, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setStrokeJoin(DlStrokeJoin::kMiter); }}, }}, {"SetStyle", @@ -84,26 +84,26 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setDrawStyle(DlDrawStyle::kStrokeAndFill); }}, - {0, 8, 0, 0, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setDrawStyle(DlDrawStyle::kFill); }}, }}, {"SetStrokeWidth", { {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeWidth(1.0); }}, {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeWidth(5.0); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeWidth(0.0); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setStrokeWidth(0.0); }}, }}, {"SetStrokeMiter", { {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeMiter(0.0); }}, {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeMiter(5.0); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setStrokeMiter(4.0); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setStrokeMiter(4.0); }}, }}, {"SetColor", { {0, 8, 0, 0, [](DlOpReceiver& r) { r.setColor(SK_ColorGREEN); }}, {0, 8, 0, 0, [](DlOpReceiver& r) { r.setColor(SK_ColorBLUE); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setColor(SK_ColorBLACK); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setColor(SK_ColorBLACK); }}, }}, {"SetBlendMode", { @@ -111,7 +111,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setBlendMode(DlBlendMode::kSrcIn); }}, {0, 8, 0, 0, [](DlOpReceiver& r) { r.setBlendMode(DlBlendMode::kDstIn); }}, - {0, 8, 0, 0, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setBlendMode(DlBlendMode::kSrcOver); }}, }}, {"SetColorSource", @@ -127,7 +127,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setColorSource(kTestSource4.get()); }}, {0, 80 + 6 * 4, 0, 0, [](DlOpReceiver& r) { r.setColorSource(kTestSource5.get()); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setColorSource(nullptr); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setColorSource(nullptr); }}, }}, {"SetImageFilter", { @@ -185,7 +185,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setImageFilter(&kTestCFImageFilter1); }}, {0, 24, 0, 0, [](DlOpReceiver& r) { r.setImageFilter(&kTestCFImageFilter2); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setImageFilter(nullptr); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setImageFilter(nullptr); }}, {0, 24, 0, 0, [](DlOpReceiver& r) { r.setImageFilter( @@ -218,7 +218,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setColorFilter(DlLinearToSrgbGammaColorFilter::instance.get()); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setColorFilter(nullptr); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setColorFilter(nullptr); }}, }}, {"SetPathEffect", { @@ -227,7 +227,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setPathEffect(kTestPathEffect1.get()); }}, {0, 32, 0, 0, [](DlOpReceiver& r) { r.setPathEffect(kTestPathEffect2.get()); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setPathEffect(nullptr); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setPathEffect(nullptr); }}, }}, {"SetMaskFilter", { @@ -241,7 +241,7 @@ std::vector CreateAllAttributesOps() { [](DlOpReceiver& r) { r.setMaskFilter(&kTestMaskFilter4); }}, {0, 32, 0, 0, [](DlOpReceiver& r) { r.setMaskFilter(&kTestMaskFilter5); }}, - {0, 8, 0, 0, [](DlOpReceiver& r) { r.setMaskFilter(nullptr); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.setMaskFilter(nullptr); }}, }}, }; } @@ -354,7 +354,7 @@ std::vector CreateAllTransformOps() { {1, 16, 1, 16, [](DlOpReceiver& r) { r.translate(10, 10); }}, {1, 16, 1, 16, [](DlOpReceiver& r) { r.translate(10, 15); }}, {1, 16, 1, 16, [](DlOpReceiver& r) { r.translate(15, 10); }}, - {1, 16, 1, 16, [](DlOpReceiver& r) { r.translate(0, 0); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.translate(0, 0); }}, }}, {"Scale", { @@ -362,15 +362,15 @@ std::vector CreateAllTransformOps() { {1, 16, 1, 16, [](DlOpReceiver& r) { r.scale(2, 2); }}, {1, 16, 1, 16, [](DlOpReceiver& r) { r.scale(2, 3); }}, {1, 16, 1, 16, [](DlOpReceiver& r) { r.scale(3, 2); }}, - {1, 16, 1, 16, [](DlOpReceiver& r) { r.scale(1, 1); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.scale(1, 1); }}, }}, {"Rotate", { // cv.rotate(0) is ignored, otherwise expressed as concat(rotmatrix) {1, 8, 1, 32, [](DlOpReceiver& r) { r.rotate(30); }}, {1, 8, 1, 32, [](DlOpReceiver& r) { r.rotate(45); }}, - {1, 8, 1, 32, [](DlOpReceiver& r) { r.rotate(0); }}, - {1, 8, 1, 32, [](DlOpReceiver& r) { r.rotate(360); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.rotate(0); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.rotate(360); }}, }}, {"Skew", { @@ -379,14 +379,14 @@ std::vector CreateAllTransformOps() { {1, 16, 1, 32, [](DlOpReceiver& r) { r.skew(0.1, 0.1); }}, {1, 16, 1, 32, [](DlOpReceiver& r) { r.skew(0.1, 0.2); }}, {1, 16, 1, 32, [](DlOpReceiver& r) { r.skew(0.2, 0.1); }}, - {1, 16, 1, 32, [](DlOpReceiver& r) { r.skew(0, 0); }}, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.skew(0, 0); }}, }}, {"Transform2DAffine", { {1, 32, 1, 32, [](DlOpReceiver& r) { r.transform2DAffine(0, 1, 12, 1, 0, 33); }}, // r.transform(identity) is ignored - {1, 32, 1, 32, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.transform2DAffine(1, 0, 0, 0, 1, 0); }}, }}, {"TransformFullPerspective", @@ -397,13 +397,13 @@ std::vector CreateAllTransformOps() { 0, 0, 0, 12); }}, // r.transform(2D affine) is reduced to 2x3 - {1, 72, 1, 72, + {1, 32, 1, 32, [](DlOpReceiver& r) { r.transformFullPerspective(2, 1, 0, 4, 1, 3, 0, 5, 0, 0, 1, 0, 0, 0, 0, 1); }}, // r.transform(identity) is ignored - {1, 72, 1, 72, + {0, 0, 0, 0, [](DlOpReceiver& r) { r.transformFullPerspective(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); @@ -488,11 +488,13 @@ std::vector CreateAllClipOps() { [](DlOpReceiver& r) { r.clipPath(kTestPath1, DlCanvas::ClipOp::kDifference, false); }}, + // clipPath(rect) becomes clipRect {1, 24, 1, 24, [](DlOpReceiver& r) { r.clipPath(kTestPathRect, DlCanvas::ClipOp::kIntersect, true); }}, - {1, 24, 1, 24, + // clipPath(oval) becomes clipRRect + {1, 64, 1, 64, [](DlOpReceiver& r) { r.clipPath(kTestPathOval, DlCanvas::ClipOp::kIntersect, true); }}, diff --git a/display_list/testing/dl_test_snippets.h b/display_list/testing/dl_test_snippets.h index b9f9f52b606e8..536cb224e8ef9 100644 --- a/display_list/testing/dl_test_snippets.h +++ b/display_list/testing/dl_test_snippets.h @@ -6,7 +6,7 @@ #define FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SNIPPETS_H_ #include "flutter/display_list/display_list.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSurface.h" diff --git a/display_list/utils/dl_bounds_accumulator.h b/display_list/utils/dl_bounds_accumulator.h index 674f5e120c44a..db4ceda2698b6 100644 --- a/display_list/utils/dl_bounds_accumulator.h +++ b/display_list/utils/dl_bounds_accumulator.h @@ -7,7 +7,6 @@ #include -#include "flutter/display_list/dl_canvas_to_receiver.h" #include "flutter/display_list/geometry/dl_rtree.h" #include "flutter/fml/logging.h" @@ -22,13 +21,13 @@ namespace flutter { +enum class BoundsAccumulatorType { + kRect, + kRTree, +}; + class BoundsAccumulator { public: - enum class Type { - kRect, - kRTree, - }; - /// function definition for modifying the bounds of a rectangle /// during a restore operation. The function is used primarily /// to account for the bounds impact of an ImageFilter on a @@ -49,8 +48,6 @@ class BoundsAccumulator { virtual ~BoundsAccumulator() = default; - virtual Type type() const = 0; - virtual void accumulate(const SkRect& r, int index = 0) = 0; /// Save aside the rects/bounds currently being accumulated and start @@ -88,6 +85,8 @@ class BoundsAccumulator { virtual SkRect bounds() const = 0; virtual sk_sp rtree() const = 0; + + virtual BoundsAccumulatorType type() const = 0; }; class RectBoundsAccumulator final : public virtual BoundsAccumulator { @@ -109,7 +108,9 @@ class RectBoundsAccumulator final : public virtual BoundsAccumulator { return rect_.bounds(); } - Type type() const override { return Type::kRect; } + BoundsAccumulatorType type() const override { + return BoundsAccumulatorType::kRect; + } sk_sp rtree() const override { return nullptr; } @@ -152,7 +153,9 @@ class RTreeBoundsAccumulator final : public virtual BoundsAccumulator { sk_sp rtree() const override; - Type type() const override { return Type::kRTree; } + BoundsAccumulatorType type() const override { + return BoundsAccumulatorType::kRTree; + } private: std::vector rects_; diff --git a/display_list/utils/dl_matrix_clip_tracker.cc b/display_list/utils/dl_matrix_clip_tracker.cc index f9e30590303d2..2dd0e8fa31a39 100644 --- a/display_list/utils/dl_matrix_clip_tracker.cc +++ b/display_list/utils/dl_matrix_clip_tracker.cc @@ -4,7 +4,7 @@ #include "flutter/display_list/utils/dl_matrix_clip_tracker.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/fml/logging.h" namespace flutter { diff --git a/display_list/utils/dl_receiver_utils.h b/display_list/utils/dl_receiver_utils.h index 26c3db8ef774b..e2d07310368ae 100644 --- a/display_list/utils/dl_receiver_utils.h +++ b/display_list/utils/dl_receiver_utils.h @@ -100,22 +100,22 @@ class IgnoreDrawDispatchHelper : public virtual DlOpReceiver { uint32_t count, const SkPoint points[]) override {} void drawVertices(const DlVertices* vertices, DlBlendMode mode) override {} - void drawImage(const sk_sp& image, + void drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override {} - void drawImageRect(const sk_sp& image, + void drawImageRect(const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint) override {} - void drawImageNine(const sk_sp& image, + void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override {} - void drawAtlas(const sk_sp& atlas, + void drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -124,9 +124,9 @@ class IgnoreDrawDispatchHelper : public virtual DlOpReceiver { DlImageSampling sampling, const SkRect* cull_rect, bool render_with_attributes) override {} - void drawDisplayList(const sk_sp& display_list, + void drawDisplayList(const sk_sp display_list, SkScalar opacity) override {} - void drawTextBlob(const sk_sp& blob, + void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) override {} void drawShadow(const SkPath& path, diff --git a/flow/embedded_views.h b/flow/embedded_views.h index d6292f13ec034..6985c37e5b8c0 100644 --- a/flow/embedded_views.h +++ b/flow/embedded_views.h @@ -8,7 +8,7 @@ #include #include -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/skia/dl_sk_canvas.h" #include "flutter/flow/surface_frame.h" #include "flutter/fml/memory/ref_counted.h" diff --git a/flow/layers/checkerboard_layertree_unittests.cc b/flow/layers/checkerboard_layertree_unittests.cc index 32f8396536512..61489a6ad38c8 100644 --- a/flow/layers/checkerboard_layertree_unittests.cc +++ b/flow/layers/checkerboard_layertree_unittests.cc @@ -68,6 +68,7 @@ TEST_F(CheckerBoardLayerTest, ClipRectSaveLayerCheckBoard) { DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } + reset_display_list(); layer->Paint(checkerboard_context()); { DisplayListBuilder expected_builder; @@ -88,8 +89,8 @@ TEST_F(CheckerBoardLayerTest, ClipRectSaveLayerCheckBoard) { } expected_builder.Restore(); } - EXPECT_TRUE(DisplayListsEQ_Verbose(checkerboard_display_list(), - expected_builder.Build())); + EXPECT_TRUE( + DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } @@ -144,6 +145,7 @@ TEST_F(CheckerBoardLayerTest, ClipPathSaveLayerCheckBoard) { DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } + reset_display_list(); layer->Paint(checkerboard_context()); { DisplayListBuilder expected_builder; @@ -164,8 +166,8 @@ TEST_F(CheckerBoardLayerTest, ClipPathSaveLayerCheckBoard) { } expected_builder.Restore(); } - EXPECT_TRUE(DisplayListsEQ_Verbose(checkerboard_display_list(), - expected_builder.Build())); + EXPECT_TRUE( + DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } @@ -219,6 +221,7 @@ TEST_F(CheckerBoardLayerTest, ClipRRectSaveLayerCheckBoard) { DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } + reset_display_list(); layer->Paint(checkerboard_context()); { DisplayListBuilder expected_builder; @@ -239,8 +242,8 @@ TEST_F(CheckerBoardLayerTest, ClipRRectSaveLayerCheckBoard) { } expected_builder.Restore(); } - EXPECT_TRUE(DisplayListsEQ_Verbose(checkerboard_display_list(), - expected_builder.Build())); + EXPECT_TRUE( + DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } diff --git a/flow/layers/display_list_layer.cc b/flow/layers/display_list_layer.cc index 5987dbecae7ea..543af526be64d 100644 --- a/flow/layers/display_list_layer.cc +++ b/flow/layers/display_list_layer.cc @@ -6,6 +6,7 @@ #include +#include "flutter/display_list/dl_builder.h" #include "flutter/flow/layer_snapshot_store.h" #include "flutter/flow/layers/cacheable_layer.h" #include "flutter/flow/layers/offscreen_surface.h" diff --git a/flow/layers/display_list_layer_unittests.cc b/flow/layers/display_list_layer_unittests.cc index e884fb6b10d0a..2791577666b8d 100644 --- a/flow/layers/display_list_layer_unittests.cc +++ b/flow/layers/display_list_layer_unittests.cc @@ -6,7 +6,7 @@ #include "flutter/flow/layers/display_list_layer.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/flow/layers/layer_tree.h" #include "flutter/flow/testing/diff_context_test.h" #include "flutter/fml/macros.h" diff --git a/flow/layers/image_filter_layer_unittests.cc b/flow/layers/image_filter_layer_unittests.cc index 8d9e2e9ab5091..ee8f08c8491be 100644 --- a/flow/layers/image_filter_layer_unittests.cc +++ b/flow/layers/image_filter_layer_unittests.cc @@ -525,11 +525,9 @@ TEST_F(ImageFilterLayerTest, CacheImageFilterLayerSelf) { } // frame 2. - reset_display_list(); layer->Preroll(preroll_context()); layer->Paint(display_list_paint_context()); // frame 3. - reset_display_list(); layer->Preroll(preroll_context()); layer->Paint(display_list_paint_context()); diff --git a/flow/raster_cache_unittests.cc b/flow/raster_cache_unittests.cc index 41604b681f215..e0dfda6593c8c 100644 --- a/flow/raster_cache_unittests.cc +++ b/flow/raster_cache_unittests.cc @@ -4,7 +4,7 @@ #include "flutter/display_list/benchmarking/dl_complexity.h" #include "flutter/display_list/display_list.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/testing/dl_test_snippets.h" #include "flutter/flow/layers/container_layer.h" #include "flutter/flow/layers/display_list_layer.h" diff --git a/flow/surface_frame.h b/flow/surface_frame.h index a3d6d1e523efa..1abf75e573223 100644 --- a/flow/surface_frame.h +++ b/flow/surface_frame.h @@ -9,7 +9,7 @@ #include #include "flutter/common/graphics/gl_context_switch.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/skia/dl_sk_canvas.h" #include "flutter/fml/macros.h" #include "flutter/fml/time/time_point.h" diff --git a/flow/testing/diff_context_test.cc b/flow/testing/diff_context_test.cc index 74ba1b6746e88..26b2a67f28d09 100644 --- a/flow/testing/diff_context_test.cc +++ b/flow/testing/diff_context_test.cc @@ -5,8 +5,7 @@ #include "diff_context_test.h" #include - -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" namespace flutter { namespace testing { diff --git a/flow/testing/layer_test.h b/flow/testing/layer_test.h index a85dd6f936559..178c307426c19 100644 --- a/flow/testing/layer_test.h +++ b/flow/testing/layer_test.h @@ -72,11 +72,11 @@ class LayerTestBase : public CanvasTestBase { .raster_cache = nullptr, // clang-format on }, + display_list_builder_(kDlBounds), display_list_paint_context_{ // clang-format off .state_stack = display_list_state_stack_, - // canvas is set below by resetting the display_list - .canvas = nullptr, + .canvas = &display_list_builder_, .gr_context = nullptr, .view_embedder = nullptr, .raster_time = raster_time_, @@ -88,8 +88,7 @@ class LayerTestBase : public CanvasTestBase { checkerboard_context_{ // clang-format off .state_stack = checkerboard_state_stack_, - // canvas is set below by resetting the display_list - .canvas = nullptr, + .canvas = &display_list_builder_, .gr_context = nullptr, .view_embedder = nullptr, .raster_time = raster_time_, @@ -101,8 +100,8 @@ class LayerTestBase : public CanvasTestBase { use_null_raster_cache(); preroll_state_stack_.set_preroll_delegate(kGiantRect, SkMatrix::I()); paint_state_stack_.set_delegate(&TestT::mock_canvas()); - reset_display_list(); - reset_checkerboard_display_list(); + display_list_state_stack_.set_delegate(&display_list_builder_); + checkerboard_state_stack_.set_delegate(&display_list_builder_); checkerboard_state_stack_.set_checkerboard_func(draw_checkerboard); checkerboard_paint_.setColor(checkerboard_color_); } @@ -171,44 +170,19 @@ class LayerTestBase : public CanvasTestBase { PaintContext& checkerboard_context() { return checkerboard_context_; } LayerSnapshotStore& layer_snapshot_store() { return snapshot_store_; } - sk_sp checkerboard_display_list() { - if (checkerboard_display_list_ == nullptr) { - if (checkerboard_builder_.get()) { - checkerboard_state_stack_.clear_delegate(); - checkerboard_display_list_ = checkerboard_builder_->Build(); - checkerboard_builder_.reset(); - checkerboard_context_.canvas = nullptr; - } - } - return checkerboard_display_list_; - } - sk_sp display_list() { if (display_list_ == nullptr) { - if (display_list_builder_.get()) { - display_list_state_stack_.clear_delegate(); - display_list_ = display_list_builder_->Build(); - display_list_builder_.reset(); - display_list_paint_context_.canvas = nullptr; - } + display_list_ = display_list_builder_.Build(); } return display_list_; } - void reset_checkerboard_display_list() { - checkerboard_display_list_ = nullptr; - checkerboard_state_stack_.clear_delegate(); - checkerboard_builder_.reset(new DisplayListBuilder(kDlBounds)); - checkerboard_state_stack_.set_delegate(checkerboard_builder_.get()); - checkerboard_context_.canvas = checkerboard_builder_.get(); - } - void reset_display_list() { display_list_ = nullptr; - display_list_state_stack_.clear_delegate(); - display_list_builder_.reset(new DisplayListBuilder(kDlBounds)); - display_list_state_stack_.set_delegate(display_list_builder_.get()); - display_list_paint_context_.canvas = display_list_builder_.get(); + // Build() will leave the builder in a state to start recording a new DL + display_list_builder_.Build(); + // Make sure we are starting from a fresh state stack + FML_DCHECK(display_list_state_stack_.is_empty()); } void enable_leaf_layer_tracing() { @@ -246,7 +220,6 @@ class LayerTestBase : public CanvasTestBase { } LayerStateStack preroll_state_stack_; - LayerStateStack display_list_state_stack_; LayerStateStack paint_state_stack_; LayerStateStack checkerboard_state_stack_; FixedRefreshRateStopwatch raster_time_; @@ -256,11 +229,10 @@ class LayerTestBase : public CanvasTestBase { std::unique_ptr raster_cache_; PrerollContext preroll_context_; PaintContext paint_context_; - std::unique_ptr display_list_builder_; + DisplayListBuilder display_list_builder_; + LayerStateStack display_list_state_stack_; sk_sp display_list_; PaintContext display_list_paint_context_; - std::unique_ptr checkerboard_builder_; - sk_sp checkerboard_display_list_; DlPaint checkerboard_paint_; PaintContext checkerboard_context_; LayerSnapshotStore snapshot_store_; diff --git a/flow/testing/mock_texture_unittests.cc b/flow/testing/mock_texture_unittests.cc index 6226446a5fd90..5f5bab254dd6e 100644 --- a/flow/testing/mock_texture_unittests.cc +++ b/flow/testing/mock_texture_unittests.cc @@ -4,7 +4,7 @@ #include "flutter/flow/testing/mock_texture.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/testing/display_list_testing.h" #include "gtest/gtest.h" diff --git a/impeller/aiks/aiks_context.cc b/impeller/aiks/aiks_context.cc index e724ac597af9a..fc0a3efc45557 100644 --- a/impeller/aiks/aiks_context.cc +++ b/impeller/aiks/aiks_context.cc @@ -5,16 +5,19 @@ #include "impeller/aiks/aiks_context.h" #include "impeller/aiks/picture.h" +#include "impeller/typographer/text_render_context.h" namespace impeller { -AiksContext::AiksContext(std::shared_ptr context) +AiksContext::AiksContext(std::shared_ptr context, + std::shared_ptr text_render_context) : context_(std::move(context)) { if (!context_ || !context_->IsValid()) { return; } - content_context_ = std::make_unique(context_); + content_context_ = std::make_unique( + context_, std::move(text_render_context)); if (!content_context_->IsValid()) { return; } diff --git a/impeller/aiks/aiks_context.h b/impeller/aiks/aiks_context.h index fe62ebca47b45..9564a8a19cbab 100644 --- a/impeller/aiks/aiks_context.h +++ b/impeller/aiks/aiks_context.h @@ -10,6 +10,7 @@ #include "impeller/entity/contents/content_context.h" #include "impeller/renderer/context.h" #include "impeller/renderer/render_target.h" +#include "impeller/typographer/text_render_context.h" namespace impeller { @@ -18,7 +19,17 @@ class RenderPass; class AiksContext { public: - AiksContext(std::shared_ptr context); + /// Construct a new AiksContext. + /// + /// @param context The Impeller context that Aiks should use for + /// allocating resources and executing device + /// commands. Required. + /// @param text_render_context The text backend to use for rendering text. If + /// `nullptr` is supplied, then attempting to draw + /// text with Aiks will result in validation + /// errors. + AiksContext(std::shared_ptr context, + std::shared_ptr text_render_context); ~AiksContext(); diff --git a/impeller/aiks/aiks_playground.cc b/impeller/aiks/aiks_playground.cc index 5fc3124f283f8..cb39ce7647182 100644 --- a/impeller/aiks/aiks_playground.cc +++ b/impeller/aiks/aiks_playground.cc @@ -4,16 +4,25 @@ #include "impeller/aiks/aiks_playground.h" -#include "impeller/aiks/aiks_context.h" +#include +#include "impeller/aiks/aiks_context.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" +#include "impeller/typographer/text_render_context.h" #include "third_party/imgui/imgui.h" namespace impeller { -AiksPlayground::AiksPlayground() = default; +AiksPlayground::AiksPlayground() + : text_render_context_(TextRenderContextSkia::Make()) {} AiksPlayground::~AiksPlayground() = default; +void AiksPlayground::SetTextRenderContext( + std::shared_ptr text_render_context) { + text_render_context_ = std::move(text_render_context); +} + bool AiksPlayground::OpenPlaygroundHere(const Picture& picture) { return OpenPlaygroundHere( [&picture](AiksContext& renderer, RenderTarget& render_target) -> bool { @@ -26,7 +35,7 @@ bool AiksPlayground::OpenPlaygroundHere(AiksPlaygroundCallback callback) { return true; } - AiksContext renderer(GetContext()); + AiksContext renderer(GetContext(), text_render_context_); if (!renderer.IsValid()) { return false; diff --git a/impeller/aiks/aiks_playground.h b/impeller/aiks/aiks_playground.h index 02647faa7e3b1..f391ea4d87776 100644 --- a/impeller/aiks/aiks_playground.h +++ b/impeller/aiks/aiks_playground.h @@ -8,6 +8,7 @@ #include "impeller/aiks/aiks_context.h" #include "impeller/aiks/picture.h" #include "impeller/playground/playground_test.h" +#include "impeller/typographer/text_render_context.h" namespace impeller { @@ -20,11 +21,16 @@ class AiksPlayground : public PlaygroundTest { ~AiksPlayground(); + void SetTextRenderContext( + std::shared_ptr text_render_context); + bool OpenPlaygroundHere(const Picture& picture); bool OpenPlaygroundHere(AiksPlaygroundCallback callback); private: + std::shared_ptr text_render_context_; + FML_DISALLOW_COPY_AND_ASSIGN(AiksPlayground); }; diff --git a/impeller/aiks/aiks_unittests.cc b/impeller/aiks/aiks_unittests.cc index d1dcadac7f105..557e122b62f24 100644 --- a/impeller/aiks/aiks_unittests.cc +++ b/impeller/aiks/aiks_unittests.cc @@ -1002,7 +1002,7 @@ TEST_P(AiksTest, CanPictureConvertToImage) { recorder_canvas.DrawRect({200.0, 200.0, 600, 600}, paint); Canvas canvas; - AiksContext renderer(GetContext()); + AiksContext renderer(GetContext(), nullptr); paint.color = Color::BlackTransparent(); canvas.DrawPaint(paint); Picture picture = recorder_canvas.EndRecordingAsPicture(); @@ -2139,7 +2139,7 @@ TEST_P(AiksTest, DrawPaintAbsorbsClears) { std::shared_ptr spy = ContextSpy::Make(); std::shared_ptr real_context = GetContext(); std::shared_ptr mock_context = spy->MakeContext(real_context); - AiksContext renderer(mock_context); + AiksContext renderer(mock_context, nullptr); std::shared_ptr image = picture.ToImage(renderer, {300, 300}); ASSERT_EQ(spy->render_passes_.size(), 1llu); @@ -2159,7 +2159,7 @@ TEST_P(AiksTest, DrawRectAbsorbsClears) { Picture picture = canvas.EndRecordingAsPicture(); std::shared_ptr real_context = GetContext(); std::shared_ptr mock_context = spy->MakeContext(real_context); - AiksContext renderer(mock_context); + AiksContext renderer(mock_context, nullptr); std::shared_ptr image = picture.ToImage(renderer, {300, 300}); ASSERT_EQ(spy->render_passes_.size(), 1llu); @@ -2179,7 +2179,7 @@ TEST_P(AiksTest, DrawRectAbsorbsClearsNegativeRRect) { Picture picture = canvas.EndRecordingAsPicture(); std::shared_ptr real_context = GetContext(); std::shared_ptr mock_context = spy->MakeContext(real_context); - AiksContext renderer(mock_context); + AiksContext renderer(mock_context, nullptr); std::shared_ptr image = picture.ToImage(renderer, {300, 300}); ASSERT_EQ(spy->render_passes_.size(), 1llu); @@ -2199,7 +2199,7 @@ TEST_P(AiksTest, DrawRectAbsorbsClearsNegativeRotation) { Picture picture = canvas.EndRecordingAsPicture(); std::shared_ptr real_context = GetContext(); std::shared_ptr mock_context = spy->MakeContext(real_context); - AiksContext renderer(mock_context); + AiksContext renderer(mock_context, nullptr); std::shared_ptr image = picture.ToImage(renderer, {300, 300}); ASSERT_EQ(spy->render_passes_.size(), 1llu); @@ -2219,7 +2219,7 @@ TEST_P(AiksTest, DrawRectAbsorbsClearsNegative) { Picture picture = canvas.EndRecordingAsPicture(); std::shared_ptr real_context = GetContext(); std::shared_ptr mock_context = spy->MakeContext(real_context); - AiksContext renderer(mock_context); + AiksContext renderer(mock_context, nullptr); std::shared_ptr image = picture.ToImage(renderer, {301, 301}); ASSERT_EQ(spy->render_passes_.size(), 1llu); @@ -2243,7 +2243,7 @@ TEST_P(AiksTest, ClipRectElidesNoOpClips) { std::shared_ptr spy = ContextSpy::Make(); std::shared_ptr real_context = GetContext(); std::shared_ptr mock_context = spy->MakeContext(real_context); - AiksContext renderer(mock_context); + AiksContext renderer(mock_context, nullptr); std::shared_ptr image = picture.ToImage(renderer, {300, 300}); ASSERT_EQ(spy->render_passes_.size(), 1llu); diff --git a/impeller/aiks/canvas.cc b/impeller/aiks/canvas.cc index 4a4fc7ad4bf5f..62b63ed26ea9b 100644 --- a/impeller/aiks/canvas.cc +++ b/impeller/aiks/canvas.cc @@ -542,7 +542,7 @@ void Canvas::DrawTextFrame(const TextFrame& text_frame, entity.SetBlendMode(paint.blend_mode); auto text_contents = std::make_shared(); - text_contents->SetTextFrame(text_frame); + text_contents->SetTextFrame(TextFrame(text_frame)); if (paint.color_source.GetType() != ColorSource::Type::kColor) { auto color_text_contents = std::make_shared(); diff --git a/impeller/display_list/dl_dispatcher.cc b/impeller/display_list/dl_dispatcher.cc index 4e98a996e24f8..4ddaee6eb1795 100644 --- a/impeller/display_list/dl_dispatcher.cc +++ b/impeller/display_list/dl_dispatcher.cc @@ -969,7 +969,7 @@ void DlDispatcher::drawVertices(const flutter::DlVertices* vertices, } // |flutter::DlOpReceiver| -void DlDispatcher::drawImage(const sk_sp& image, +void DlDispatcher::drawImage(const sk_sp image, const SkPoint point, flutter::DlImageSampling sampling, bool render_with_attributes) { @@ -998,7 +998,7 @@ void DlDispatcher::drawImage(const sk_sp& image, // |flutter::DlOpReceiver| void DlDispatcher::drawImageRect( - const sk_sp& image, + const sk_sp image, const SkRect& src, const SkRect& dst, flutter::DlImageSampling sampling, @@ -1014,7 +1014,7 @@ void DlDispatcher::drawImageRect( } // |flutter::DlOpReceiver| -void DlDispatcher::drawImageNine(const sk_sp& image, +void DlDispatcher::drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, flutter::DlFilterMode filter, @@ -1028,7 +1028,7 @@ void DlDispatcher::drawImageNine(const sk_sp& image, } // |flutter::DlOpReceiver| -void DlDispatcher::drawAtlas(const sk_sp& atlas, +void DlDispatcher::drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const flutter::DlColor colors[], @@ -1047,7 +1047,7 @@ void DlDispatcher::drawAtlas(const sk_sp& atlas, // |flutter::DlOpReceiver| void DlDispatcher::drawDisplayList( - const sk_sp& display_list, + const sk_sp display_list, SkScalar opacity) { // Save all values that must remain untouched after the operation. Paint saved_paint = paint_; @@ -1105,7 +1105,7 @@ void DlDispatcher::drawDisplayList( } // |flutter::DlOpReceiver| -void DlDispatcher::drawTextBlob(const sk_sp& blob, +void DlDispatcher::drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) { const auto text_frame = TextFrameFromTextBlob(blob); diff --git a/impeller/display_list/dl_dispatcher.h b/impeller/display_list/dl_dispatcher.h index 150ad8c36b524..d9a36e2239980 100644 --- a/impeller/display_list/dl_dispatcher.h +++ b/impeller/display_list/dl_dispatcher.h @@ -172,13 +172,13 @@ class DlDispatcher final : public flutter::DlOpReceiver { flutter::DlBlendMode dl_mode) override; // |flutter::DlOpReceiver| - void drawImage(const sk_sp& image, + void drawImage(const sk_sp image, const SkPoint point, flutter::DlImageSampling sampling, bool render_with_attributes) override; // |flutter::DlOpReceiver| - void drawImageRect(const sk_sp& image, + void drawImageRect(const sk_sp image, const SkRect& src, const SkRect& dst, flutter::DlImageSampling sampling, @@ -186,14 +186,14 @@ class DlDispatcher final : public flutter::DlOpReceiver { SrcRectConstraint constraint) override; // |flutter::DlOpReceiver| - void drawImageNine(const sk_sp& image, + void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, flutter::DlFilterMode filter, bool render_with_attributes) override; // |flutter::DlOpReceiver| - void drawAtlas(const sk_sp& atlas, + void drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const flutter::DlColor colors[], @@ -204,11 +204,11 @@ class DlDispatcher final : public flutter::DlOpReceiver { bool render_with_attributes) override; // |flutter::DlOpReceiver| - void drawDisplayList(const sk_sp& display_list, + void drawDisplayList(const sk_sp display_list, SkScalar opacity) override; // |flutter::DlOpReceiver| - void drawTextBlob(const sk_sp& blob, + void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) override; diff --git a/impeller/display_list/dl_playground.cc b/impeller/display_list/dl_playground.cc index 539b32f6a7a6b..b6d1f5468fe1e 100644 --- a/impeller/display_list/dl_playground.cc +++ b/impeller/display_list/dl_playground.cc @@ -7,6 +7,7 @@ #include "flutter/testing/testing.h" #include "impeller/aiks/aiks_context.h" #include "impeller/display_list/dl_dispatcher.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" #include "third_party/imgui/imgui.h" #include "third_party/skia/include/core/SkData.h" @@ -29,7 +30,7 @@ bool DlPlayground::OpenPlaygroundHere(DisplayListPlaygroundCallback callback) { return true; } - AiksContext context(GetContext()); + AiksContext context(GetContext(), TextRenderContextSkia::Make()); if (!context.IsValid()) { return false; } diff --git a/impeller/display_list/dl_playground.h b/impeller/display_list/dl_playground.h index b7c1730ced436..f6ad193eb0241 100644 --- a/impeller/display_list/dl_playground.h +++ b/impeller/display_list/dl_playground.h @@ -5,7 +5,7 @@ #pragma once #include "flutter/display_list/display_list.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/fml/macros.h" #include "impeller/playground/playground_test.h" #include "third_party/skia/include/core/SkFont.h" diff --git a/impeller/display_list/dl_unittests.cc b/impeller/display_list/dl_unittests.cc index 204578a4dd893..a902668baa277 100644 --- a/impeller/display_list/dl_unittests.cc +++ b/impeller/display_list/dl_unittests.cc @@ -7,8 +7,8 @@ #include #include -#include "flutter/display_list/display_list_builder.h" #include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/display_list/dl_color.h" #include "flutter/display_list/dl_paint.h" #include "flutter/display_list/dl_tile_mode.h" diff --git a/impeller/entity/contents/content_context.cc b/impeller/entity/contents/content_context.cc index 94fd796a7eed2..6f76a60ab8eb2 100644 --- a/impeller/entity/contents/content_context.cc +++ b/impeller/entity/contents/content_context.cc @@ -16,6 +16,7 @@ #include "impeller/renderer/render_pass.h" #include "impeller/renderer/render_target.h" #include "impeller/tessellator/tessellator.h" +#include "impeller/typographer/text_render_context.h" namespace impeller { @@ -159,9 +160,12 @@ static std::unique_ptr CreateDefaultPipeline( return std::make_unique(context, desc); } -ContentContext::ContentContext(std::shared_ptr context) +ContentContext::ContentContext( + std::shared_ptr context, + std::shared_ptr text_render_context) : context_(std::move(context)), - lazy_glyph_atlas_(std::make_shared()), + lazy_glyph_atlas_( + std::make_shared(std::move(text_render_context))), tessellator_(std::make_shared()), scene_context_(std::make_shared(context_)), render_target_cache_(std::make_shared( diff --git a/impeller/entity/contents/content_context.h b/impeller/entity/contents/content_context.h index 86da8f98b2287..3c67f85c66fc4 100644 --- a/impeller/entity/contents/content_context.h +++ b/impeller/entity/contents/content_context.h @@ -19,6 +19,7 @@ #include "impeller/renderer/pipeline.h" #include "impeller/renderer/render_target.h" #include "impeller/scene/scene_context.h" +#include "impeller/typographer/text_render_context.h" #ifdef IMPELLER_DEBUG #include "impeller/entity/checkerboard.frag.h" @@ -339,7 +340,9 @@ class RenderTargetCache; class ContentContext { public: - explicit ContentContext(std::shared_ptr context); + explicit ContentContext( + std::shared_ptr context, + std::shared_ptr text_render_context); ~ContentContext(); diff --git a/impeller/entity/contents/text_contents.cc b/impeller/entity/contents/text_contents.cc index 26a5db145c258..d8e68b2929e65 100644 --- a/impeller/entity/contents/text_contents.cc +++ b/impeller/entity/contents/text_contents.cc @@ -12,10 +12,8 @@ #include "impeller/core/sampler_descriptor.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/entity.h" -#include "impeller/geometry/path_builder.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/sampler_library.h" -#include "impeller/tessellator/tessellator.h" #include "impeller/typographer/glyph_atlas.h" #include "impeller/typographer/lazy_glyph_atlas.h" @@ -25,17 +23,17 @@ TextContents::TextContents() = default; TextContents::~TextContents() = default; -void TextContents::SetTextFrame(const TextFrame& frame) { - frame_ = frame; +void TextContents::SetTextFrame(TextFrame&& frame) { + frame_ = std::move(frame); } std::shared_ptr TextContents::ResolveAtlas( + Context& context, GlyphAtlas::Type type, - const std::shared_ptr& lazy_atlas, - std::shared_ptr context) const { + const std::shared_ptr& lazy_atlas) const { FML_DCHECK(lazy_atlas); if (lazy_atlas) { - return lazy_atlas->CreateOrGetGlyphAtlas(type, std::move(context)); + return lazy_atlas->CreateOrGetGlyphAtlas(context, type); } return nullptr; @@ -90,7 +88,7 @@ bool TextContents::Render(const ContentContext& renderer, auto type = frame_.GetAtlasType(); auto atlas = - ResolveAtlas(type, renderer.GetLazyGlyphAtlas(), renderer.GetContext()); + ResolveAtlas(*renderer.GetContext(), type, renderer.GetLazyGlyphAtlas()); if (!atlas || !atlas->IsValid()) { VALIDATION_LOG << "Cannot render glyphs without prepared atlas."; @@ -170,22 +168,24 @@ bool TextContents::Render(const ContentContext& renderer, vertex_count * sizeof(VS::PerVertexData), alignof(VS::PerVertexData), [&](uint8_t* contents) { VS::PerVertexData vtx; - size_t vertex_offset = 0; - for (const auto& run : frame_.GetRuns()) { + VS::PerVertexData* vtx_contents = + reinterpret_cast(contents); + for (const TextRun& run : frame_.GetRuns()) { const Font& font = run.GetFont(); - auto rounded_scale = TextFrame::RoundScaledFontSize( + Scalar rounded_scale = TextFrame::RoundScaledFontSize( scale_, font.GetMetrics().point_size); - for (const auto& glyph_position : run.GetGlyphPositions()) { + for (const TextRun::GlyphPosition& glyph_position : + run.GetGlyphPositions()) { FontGlyphPair font_glyph_pair{font, glyph_position.glyph, rounded_scale}; - auto maybe_atlas_glyph_bounds = + std::optional maybe_atlas_glyph_bounds = atlas->FindFontGlyphBounds(font_glyph_pair); if (!maybe_atlas_glyph_bounds.has_value()) { VALIDATION_LOG << "Could not find glyph position in the atlas."; continue; } - auto atlas_glyph_bounds = maybe_atlas_glyph_bounds.value(); + const Rect& atlas_glyph_bounds = maybe_atlas_glyph_bounds.value(); vtx.atlas_glyph_bounds = Vector4( atlas_glyph_bounds.origin.x, atlas_glyph_bounds.origin.y, atlas_glyph_bounds.size.width, atlas_glyph_bounds.size.height); @@ -195,11 +195,9 @@ bool TextContents::Render(const ContentContext& renderer, glyph_position.glyph.bounds.size.height); vtx.glyph_position = glyph_position.position; - for (const auto& point : unit_points) { + for (const Point& point : unit_points) { vtx.unit_position = point; - ::memcpy(contents + vertex_offset, &vtx, - sizeof(VS::PerVertexData)); - vertex_offset += sizeof(VS::PerVertexData); + ::memcpy(vtx_contents++, &vtx, sizeof(VS::PerVertexData)); } } } diff --git a/impeller/entity/contents/text_contents.h b/impeller/entity/contents/text_contents.h index 4499586735a7d..6e3b89d558e61 100644 --- a/impeller/entity/contents/text_contents.h +++ b/impeller/entity/contents/text_contents.h @@ -26,7 +26,7 @@ class TextContents final : public Contents { ~TextContents(); - void SetTextFrame(const TextFrame& frame); + void SetTextFrame(TextFrame&& frame); void SetColor(Color color); @@ -63,9 +63,9 @@ class TextContents final : public Contents { Vector2 offset_; std::shared_ptr ResolveAtlas( + Context& context, GlyphAtlas::Type type, - const std::shared_ptr& lazy_atlas, - std::shared_ptr context) const; + const std::shared_ptr& lazy_atlas) const; FML_DISALLOW_COPY_AND_ASSIGN(TextContents); }; diff --git a/impeller/entity/entity_playground.cc b/impeller/entity/entity_playground.cc index abdb428e200da..103dfab02f4f6 100644 --- a/impeller/entity/entity_playground.cc +++ b/impeller/entity/entity_playground.cc @@ -5,21 +5,27 @@ #include "impeller/entity/entity_playground.h" #include "impeller/entity/contents/content_context.h" - +#include "impeller/typographer/backends/skia/text_render_context_skia.h" #include "third_party/imgui/imgui.h" namespace impeller { -EntityPlayground::EntityPlayground() = default; +EntityPlayground::EntityPlayground() + : text_render_context_(TextRenderContextSkia::Make()) {} EntityPlayground::~EntityPlayground() = default; +void EntityPlayground::SetTextRenderContext( + std::shared_ptr text_render_context) { + text_render_context_ = std::move(text_render_context); +} + bool EntityPlayground::OpenPlaygroundHere(EntityPass& entity_pass) { if (!switches_.enable_playground) { return true; } - ContentContext content_context(GetContext()); + ContentContext content_context(GetContext(), text_render_context_); if (!content_context.IsValid()) { return false; } @@ -35,7 +41,7 @@ bool EntityPlayground::OpenPlaygroundHere(Entity entity) { return true; } - ContentContext content_context(GetContext()); + ContentContext content_context(GetContext(), text_render_context_); if (!content_context.IsValid()) { return false; } @@ -50,7 +56,7 @@ bool EntityPlayground::OpenPlaygroundHere(EntityPlaygroundCallback callback) { return true; } - ContentContext content_context(GetContext()); + ContentContext content_context(GetContext(), text_render_context_); if (!content_context.IsValid()) { return false; } diff --git a/impeller/entity/entity_playground.h b/impeller/entity/entity_playground.h index a2f05876497c3..d9d83259b710f 100644 --- a/impeller/entity/entity_playground.h +++ b/impeller/entity/entity_playground.h @@ -4,12 +4,13 @@ #pragma once +#include "impeller/playground/playground_test.h" + #include "flutter/fml/macros.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/entity.h" #include "impeller/entity/entity_pass.h" - -#include "impeller/playground/playground_test.h" +#include "impeller/typographer/text_render_context.h" namespace impeller { @@ -22,6 +23,9 @@ class EntityPlayground : public PlaygroundTest { ~EntityPlayground(); + void SetTextRenderContext( + std::shared_ptr text_render_context); + bool OpenPlaygroundHere(Entity entity); bool OpenPlaygroundHere(EntityPass& entity_pass); @@ -29,6 +33,8 @@ class EntityPlayground : public PlaygroundTest { bool OpenPlaygroundHere(EntityPlaygroundCallback callback); private: + std::shared_ptr text_render_context_; + FML_DISALLOW_COPY_AND_ASSIGN(EntityPlayground); }; diff --git a/impeller/entity/entity_unittests.cc b/impeller/entity/entity_unittests.cc index 35194d5541d0a..2c7e34e83f536 100644 --- a/impeller/entity/entity_unittests.cc +++ b/impeller/entity/entity_unittests.cc @@ -2175,11 +2175,12 @@ TEST_P(EntityTest, InheritOpacityTest) { font.setSize(30); auto blob = SkTextBlob::MakeFromString("A", font); auto frame = TextFrameFromTextBlob(blob); - auto lazy_glyph_atlas = std::make_shared(); + auto lazy_glyph_atlas = + std::make_shared(TextRenderContextSkia::Make()); lazy_glyph_atlas->AddTextFrame(frame, 1.0f); auto text_contents = std::make_shared(); - text_contents->SetTextFrame(frame); + text_contents->SetTextFrame(std::move(frame)); text_contents->SetColor(Color::Blue().WithAlpha(0.5)); ASSERT_TRUE(text_contents->CanInheritOpacity(entity)); diff --git a/impeller/golden_tests/golden_playground_test.h b/impeller/golden_tests/golden_playground_test.h index a165fdd103189..34f879c0d225f 100644 --- a/impeller/golden_tests/golden_playground_test.h +++ b/impeller/golden_tests/golden_playground_test.h @@ -11,6 +11,7 @@ #include "flutter/impeller/playground/playground.h" #include "flutter/impeller/renderer/render_target.h" #include "flutter/testing/testing.h" +#include "impeller/typographer/text_render_context.h" #if FML_OS_MACOSX #include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" @@ -26,12 +27,17 @@ class GoldenPlaygroundTest GoldenPlaygroundTest(); + ~GoldenPlaygroundTest() override; + void SetUp(); void TearDown(); PlaygroundBackend GetBackend() const; + void SetTextRenderContext( + std::shared_ptr text_render_context); + bool OpenPlaygroundHere(const Picture& picture); bool OpenPlaygroundHere(const AiksPlaygroundCallback& callback); @@ -58,6 +64,8 @@ class GoldenPlaygroundTest fml::ScopedNSAutoreleasePool autorelease_pool_; #endif + std::shared_ptr text_render_context_; + struct GoldenPlaygroundTestImpl; // This is only a shared_ptr so it can work with a forward declared type. std::shared_ptr pimpl_; diff --git a/impeller/golden_tests/golden_playground_test_mac.cc b/impeller/golden_tests/golden_playground_test_mac.cc index 55209e7836746..0b57755dba6e8 100644 --- a/impeller/golden_tests/golden_playground_test_mac.cc +++ b/impeller/golden_tests/golden_playground_test_mac.cc @@ -4,12 +4,15 @@ #include #include +#include #include "flutter/impeller/golden_tests/golden_playground_test.h" #include "flutter/impeller/aiks/picture.h" #include "flutter/impeller/golden_tests/golden_digest.h" #include "flutter/impeller/golden_tests/metal_screenshoter.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" +#include "impeller/typographer/text_render_context.h" namespace impeller { @@ -85,7 +88,15 @@ struct GoldenPlaygroundTest::GoldenPlaygroundTestImpl { }; GoldenPlaygroundTest::GoldenPlaygroundTest() - : pimpl_(new GoldenPlaygroundTest::GoldenPlaygroundTestImpl()) {} + : text_render_context_(TextRenderContextSkia::Make()), + pimpl_(new GoldenPlaygroundTest::GoldenPlaygroundTestImpl()) {} + +GoldenPlaygroundTest::~GoldenPlaygroundTest() = default; + +void GoldenPlaygroundTest::SetTextRenderContext( + std::shared_ptr text_render_context) { + text_render_context_ = std::move(text_render_context); +}; void GoldenPlaygroundTest::TearDown() { ASSERT_FALSE(dlopen("/usr/local/lib/libMoltenVK.dylib", RTLD_NOLOAD)); @@ -124,8 +135,10 @@ PlaygroundBackend GoldenPlaygroundTest::GetBackend() const { } bool GoldenPlaygroundTest::OpenPlaygroundHere(const Picture& picture) { - auto screenshot = - pimpl_->screenshoter->MakeScreenshot(picture, pimpl_->window_size); + AiksContext renderer(GetContext(), text_render_context_); + + auto screenshot = pimpl_->screenshoter->MakeScreenshot(renderer, picture, + pimpl_->window_size); return SaveScreenshot(std::move(screenshot)); } @@ -161,7 +174,7 @@ std::shared_ptr GoldenPlaygroundTest::OpenAssetAsRuntimeStage( } std::shared_ptr GoldenPlaygroundTest::GetContext() const { - return pimpl_->screenshoter->GetContext().GetContext(); + return pimpl_->screenshoter->GetPlayground().GetContext(); } Point GoldenPlaygroundTest::GetContentScale() const { diff --git a/impeller/golden_tests/golden_playground_test_stub.cc b/impeller/golden_tests/golden_playground_test_stub.cc index 054dc5553e624..44da5a642e0b2 100644 --- a/impeller/golden_tests/golden_playground_test_stub.cc +++ b/impeller/golden_tests/golden_playground_test_stub.cc @@ -6,7 +6,14 @@ namespace impeller { -GoldenPlaygroundTest::GoldenPlaygroundTest() {} +GoldenPlaygroundTest::GoldenPlaygroundTest() = default; + +GoldenPlaygroundTest::~GoldenPlaygroundTest() = default; + +void GoldenPlaygroundTest::SetTextRenderContext( + std::shared_ptr text_render_context) { + text_render_context_ = std::move(text_render_context); +}; void GoldenPlaygroundTest::TearDown() {} diff --git a/impeller/golden_tests/golden_tests.cc b/impeller/golden_tests/golden_tests.cc index c99d9abc05852..d57bbf751d5d5 100644 --- a/impeller/golden_tests/golden_tests.cc +++ b/impeller/golden_tests/golden_tests.cc @@ -7,6 +7,7 @@ #include #include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" +#include "impeller/aiks/aiks_context.h" #include "impeller/aiks/canvas.h" #include "impeller/entity/contents/conical_gradient_contents.h" #include "impeller/geometry/path_builder.h" @@ -56,7 +57,7 @@ class GoldenTests : public ::testing::Test { void SetUp() override { testing::GoldenDigest::Instance()->AddDimension( "gpu_string", - Screenshoter().GetContext().GetContext()->DescribeGpuModel()); + Screenshoter().GetPlayground().GetContext()->DescribeGpuModel()); } private: @@ -79,7 +80,10 @@ TEST_F(GoldenTests, ConicalGradient) { paint.style = Paint::Style::kFill; canvas.DrawRect(Rect(10, 10, 250, 250), paint); Picture picture = canvas.EndRecordingAsPicture(); - auto screenshot = Screenshoter().MakeScreenshot(picture); + + auto aiks_context = + AiksContext(Screenshoter().GetPlayground().GetContext(), nullptr); + auto screenshot = Screenshoter().MakeScreenshot(aiks_context, picture); ASSERT_TRUE(SaveScreenshot(std::move(screenshot))); } } // namespace testing diff --git a/impeller/golden_tests/metal_screenshoter.h b/impeller/golden_tests/metal_screenshoter.h index 217c5bc774b3d..961d3186f5c81 100644 --- a/impeller/golden_tests/metal_screenshoter.h +++ b/impeller/golden_tests/metal_screenshoter.h @@ -12,24 +12,20 @@ namespace impeller { namespace testing { -/// Converts `Picture`'s to `MetalScreenshot`'s with the playground backend. +/// Converts `Picture`s to `MetalScreenshot`s with the playground backend. class MetalScreenshoter { public: MetalScreenshoter(); - std::unique_ptr MakeScreenshot(const Picture& picture, + std::unique_ptr MakeScreenshot(AiksContext& aiks_context, + const Picture& picture, const ISize& size = {300, 300}); - AiksContext& GetContext() { return *aiks_context_; } - - const AiksContext& GetContext() const { return *aiks_context_; } - const PlaygroundImpl& GetPlayground() const { return *playground_; } private: std::unique_ptr playground_; - std::unique_ptr aiks_context_; }; } // namespace testing diff --git a/impeller/golden_tests/metal_screenshoter.mm b/impeller/golden_tests/metal_screenshoter.mm index acf41f07a200c..1d01b65386a8a 100644 --- a/impeller/golden_tests/metal_screenshoter.mm +++ b/impeller/golden_tests/metal_screenshoter.mm @@ -17,15 +17,15 @@ FML_CHECK(::glfwInit() == GLFW_TRUE); playground_ = PlaygroundImpl::Create(PlaygroundBackend::kMetal, PlaygroundSwitches{}); - aiks_context_.reset(new AiksContext(playground_->GetContext())); } std::unique_ptr MetalScreenshoter::MakeScreenshot( + AiksContext& aiks_context, const Picture& picture, const ISize& size) { Vector2 content_scale = playground_->GetContentScale(); std::shared_ptr image = picture.ToImage( - *aiks_context_, + aiks_context, ISize(size.width * content_scale.x, size.height * content_scale.y)); std::shared_ptr texture = image->GetTexture(); id metal_texture = diff --git a/impeller/renderer/compute_subgroup_unittests.cc b/impeller/renderer/compute_subgroup_unittests.cc index 8c9cc4fba14ec..bec4030735911 100644 --- a/impeller/renderer/compute_subgroup_unittests.cc +++ b/impeller/renderer/compute_subgroup_unittests.cc @@ -125,7 +125,7 @@ TEST_P(ComputeSubgroupTest, PathPlayground) { } ImGui::End(); - ContentContext renderer(context); + ContentContext renderer(context, nullptr); if (!renderer.IsValid()) { return false; } @@ -329,7 +329,7 @@ TEST_P(ComputeSubgroupTest, LargePath) { ->count; }); - ContentContext renderer(context); + ContentContext renderer(context, nullptr); if (!renderer.IsValid()) { return false; } @@ -413,7 +413,7 @@ TEST_P(ComputeSubgroupTest, QuadAndCubicInOnePath) { ASSERT_EQ(status, ComputeTessellator::Status::kOk); auto callback = [&](RenderPass& pass) -> bool { - ContentContext renderer(context); + ContentContext renderer(context, nullptr); if (!renderer.IsValid()) { return false; } diff --git a/impeller/typographer/backends/skia/text_frame_skia.cc b/impeller/typographer/backends/skia/text_frame_skia.cc index d458499c9d771..02dfab82aa955 100644 --- a/impeller/typographer/backends/skia/text_frame_skia.cc +++ b/impeller/typographer/backends/skia/text_frame_skia.cc @@ -97,7 +97,7 @@ TextFrame TextFrameFromTextBlob(const sk_sp& blob) { FML_DLOG(ERROR) << "Unimplemented."; continue; } - frame.AddTextRun(text_run); + frame.AddTextRun(std::move(text_run)); } return frame; diff --git a/impeller/typographer/backends/skia/text_render_context_skia.cc b/impeller/typographer/backends/skia/text_render_context_skia.cc index 1dca003c66a23..89554e555f8ea 100644 --- a/impeller/typographer/backends/skia/text_render_context_skia.cc +++ b/impeller/typographer/backends/skia/text_render_context_skia.cc @@ -12,11 +12,10 @@ #include "impeller/core/allocator.h" #include "impeller/typographer/backends/skia/typeface_skia.h" #include "impeller/typographer/rectangle_packer.h" +#include "impeller/typographer/text_render_context.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkFont.h" -#include "third_party/skia/include/core/SkFontMetrics.h" -#include "third_party/skia/include/core/SkRSXform.h" #include "third_party/skia/include/core/SkSurface.h" namespace impeller { @@ -24,19 +23,16 @@ namespace impeller { using FontGlyphPairRefVector = std::vector>; -std::unique_ptr TextRenderContext::Create( - std::shared_ptr context) { - // There is only one backend today. - return std::make_unique(std::move(context)); -} - // TODO(bdero): We might be able to remove this per-glyph padding if we fix // the underlying causes of the overlap. // https://github.com/flutter/flutter/issues/114563 constexpr auto kPadding = 2; -TextRenderContextSkia::TextRenderContextSkia(std::shared_ptr context) - : TextRenderContext(std::move(context)) {} +std::shared_ptr TextRenderContextSkia::Make() { + return std::make_shared(); +} + +TextRenderContextSkia::TextRenderContextSkia() = default; TextRenderContextSkia::~TextRenderContextSkia() = default; @@ -310,6 +306,7 @@ static std::shared_ptr UploadGlyphTextureAtlas( } std::shared_ptr TextRenderContextSkia::CreateGlyphAtlas( + Context& context, GlyphAtlas::Type type, std::shared_ptr atlas_context, const FontGlyphPair::Set& font_glyph_pairs) const { @@ -429,8 +426,8 @@ std::shared_ptr TextRenderContextSkia::CreateGlyphAtlas( format = PixelFormat::kR8G8B8A8UNormInt; break; } - auto texture = UploadGlyphTextureAtlas(GetContext()->GetResourceAllocator(), - bitmap, atlas_size, format); + auto texture = UploadGlyphTextureAtlas(context.GetResourceAllocator(), bitmap, + atlas_size, format); if (!texture) { return nullptr; } diff --git a/impeller/typographer/backends/skia/text_render_context_skia.h b/impeller/typographer/backends/skia/text_render_context_skia.h index 2e2e6ad97cf8b..32d5a083c2dd9 100644 --- a/impeller/typographer/backends/skia/text_render_context_skia.h +++ b/impeller/typographer/backends/skia/text_render_context_skia.h @@ -11,12 +11,15 @@ namespace impeller { class TextRenderContextSkia : public TextRenderContext { public: - TextRenderContextSkia(std::shared_ptr context); + static std::shared_ptr Make(); + + TextRenderContextSkia(); ~TextRenderContextSkia() override; // |TextRenderContext| std::shared_ptr CreateGlyphAtlas( + Context& context, GlyphAtlas::Type type, std::shared_ptr atlas_context, const FontGlyphPair::Set& font_glyph_pairs) const override; diff --git a/impeller/typographer/lazy_glyph_atlas.cc b/impeller/typographer/lazy_glyph_atlas.cc index f98f8af6d62b3..85f7c5dce0da2 100644 --- a/impeller/typographer/lazy_glyph_atlas.cc +++ b/impeller/typographer/lazy_glyph_atlas.cc @@ -11,8 +11,10 @@ namespace impeller { -LazyGlyphAtlas::LazyGlyphAtlas() - : alpha_context_(std::make_shared()), +LazyGlyphAtlas::LazyGlyphAtlas( + std::shared_ptr text_render_context) + : text_render_context_(std::move(text_render_context)), + alpha_context_(std::make_shared()), color_context_(std::make_shared()) {} LazyGlyphAtlas::~LazyGlyphAtlas() = default; @@ -33,8 +35,8 @@ void LazyGlyphAtlas::ResetTextFrames() { } std::shared_ptr LazyGlyphAtlas::CreateOrGetGlyphAtlas( - GlyphAtlas::Type type, - std::shared_ptr context) const { + Context& context, + GlyphAtlas::Type type) const { { auto atlas_it = atlas_map_.find(type); if (atlas_it != atlas_map_.end()) { @@ -42,14 +44,22 @@ std::shared_ptr LazyGlyphAtlas::CreateOrGetGlyphAtlas( } } - auto text_context = TextRenderContext::Create(std::move(context)); - if (!text_context || !text_context->IsValid()) { + if (!text_render_context_) { + VALIDATION_LOG << "Unable to render text because a TextRenderContext has " + "not been set."; return nullptr; } + if (!text_render_context_->IsValid()) { + VALIDATION_LOG + << "Unable to render text because the TextRenderContext is invalid."; + return nullptr; + } + auto& set = type == GlyphAtlas::Type::kAlphaBitmap ? alpha_set_ : color_set_; auto atlas_context = type == GlyphAtlas::Type::kAlphaBitmap ? alpha_context_ : color_context_; - auto atlas = text_context->CreateGlyphAtlas(type, atlas_context, set); + auto atlas = + text_render_context_->CreateGlyphAtlas(context, type, atlas_context, set); if (!atlas || !atlas->IsValid()) { VALIDATION_LOG << "Could not create valid atlas."; return nullptr; diff --git a/impeller/typographer/lazy_glyph_atlas.h b/impeller/typographer/lazy_glyph_atlas.h index 7289538eb4be9..f29dbfea6e506 100644 --- a/impeller/typographer/lazy_glyph_atlas.h +++ b/impeller/typographer/lazy_glyph_atlas.h @@ -10,12 +10,14 @@ #include "impeller/renderer/context.h" #include "impeller/typographer/glyph_atlas.h" #include "impeller/typographer/text_frame.h" +#include "impeller/typographer/text_render_context.h" namespace impeller { class LazyGlyphAtlas { public: - LazyGlyphAtlas(); + explicit LazyGlyphAtlas( + std::shared_ptr text_render_context); ~LazyGlyphAtlas(); @@ -24,10 +26,12 @@ class LazyGlyphAtlas { void ResetTextFrames(); std::shared_ptr CreateOrGetGlyphAtlas( - GlyphAtlas::Type type, - std::shared_ptr context) const; + Context& context, + GlyphAtlas::Type type) const; private: + std::shared_ptr text_render_context_; + FontGlyphPair::Set alpha_set_; FontGlyphPair::Set color_set_; std::shared_ptr alpha_context_; diff --git a/impeller/typographer/text_frame.cc b/impeller/typographer/text_frame.cc index c62023666e93a..898f69bdfe5e1 100644 --- a/impeller/typographer/text_frame.cc +++ b/impeller/typographer/text_frame.cc @@ -25,12 +25,12 @@ std::optional TextFrame::GetBounds() const { return result; } -bool TextFrame::AddTextRun(const TextRun& run) { +bool TextFrame::AddTextRun(TextRun&& run) { if (!run.IsValid()) { return false; } has_color_ |= run.HasColor(); - runs_.emplace_back(run); + runs_.emplace_back(std::move(run)); return true; } diff --git a/impeller/typographer/text_frame.h b/impeller/typographer/text_frame.h index 834528c72b0c1..54ea12df30f6b 100644 --- a/impeller/typographer/text_frame.h +++ b/impeller/typographer/text_frame.h @@ -48,7 +48,7 @@ class TextFrame { /// /// @return If the text run could be added to this frame. /// - bool AddTextRun(const TextRun& run); + bool AddTextRun(TextRun&& run); //---------------------------------------------------------------------------- /// @brief Returns a reference to all the text runs in this frame. @@ -71,6 +71,10 @@ class TextFrame { /// @brief The type of atlas this run should be emplaced in. GlyphAtlas::Type GetAtlasType() const; + TextFrame& operator=(TextFrame&& other) = default; + + TextFrame(const TextFrame& other) = default; + private: std::vector runs_; bool has_color_ = false; diff --git a/impeller/typographer/text_render_context.cc b/impeller/typographer/text_render_context.cc index 1b7aba10a7b74..8476b62c7b6aa 100644 --- a/impeller/typographer/text_render_context.cc +++ b/impeller/typographer/text_render_context.cc @@ -8,11 +8,7 @@ namespace impeller { -TextRenderContext::TextRenderContext(std::shared_ptr context) - : context_(std::move(context)) { - if (!context_ || !context_->IsValid()) { - return; - } +TextRenderContext::TextRenderContext() { is_valid_ = true; } @@ -22,8 +18,4 @@ bool TextRenderContext::IsValid() const { return is_valid_; } -const std::shared_ptr& TextRenderContext::GetContext() const { - return context_; -} - } // namespace impeller diff --git a/impeller/typographer/text_render_context.h b/impeller/typographer/text_render_context.h index d909388105f93..754e9c26bb5c0 100644 --- a/impeller/typographer/text_render_context.h +++ b/impeller/typographer/text_render_context.h @@ -10,7 +10,6 @@ #include "flutter/fml/macros.h" #include "impeller/renderer/context.h" #include "impeller/typographer/glyph_atlas.h" -#include "impeller/typographer/text_frame.h" namespace impeller { @@ -23,24 +22,15 @@ namespace impeller { /// class TextRenderContext { public: - static std::unique_ptr Create( - std::shared_ptr context); - virtual ~TextRenderContext(); virtual bool IsValid() const; - //---------------------------------------------------------------------------- - /// @brief Get the underlying graphics context. - /// - /// @return The context. - /// - const std::shared_ptr& GetContext() const; - // TODO(dnfield): Callers should not need to know which type of atlas to // create. https://github.com/flutter/flutter/issues/111640 virtual std::shared_ptr CreateGlyphAtlas( + Context& context, GlyphAtlas::Type type, std::shared_ptr atlas_context, const FontGlyphPair::Set& font_glyph_pairs) const = 0; @@ -50,12 +40,9 @@ class TextRenderContext { /// @brief Create a new context to render text that talks to an /// underlying graphics context. /// - /// @param[in] context The graphics context - /// - TextRenderContext(std::shared_ptr context); + TextRenderContext(); private: - std::shared_ptr context_; bool is_valid_ = false; FML_DISALLOW_COPY_AND_ASSIGN(TextRenderContext); diff --git a/impeller/typographer/typographer_unittests.cc b/impeller/typographer/typographer_unittests.cc index 02e8e790f8367..09c78daea06b3 100644 --- a/impeller/typographer/typographer_unittests.cc +++ b/impeller/typographer/typographer_unittests.cc @@ -8,7 +8,6 @@ #include "impeller/typographer/backends/skia/text_render_context_skia.h" #include "impeller/typographer/lazy_glyph_atlas.h" #include "impeller/typographer/rectangle_packer.h" -#include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkFontMgr.h" #include "third_party/skia/include/core/SkRect.h" @@ -24,14 +23,16 @@ using TypographerTest = PlaygroundTest; INSTANTIATE_PLAYGROUND_SUITE(TypographerTest); static std::shared_ptr CreateGlyphAtlas( - const TextRenderContext* context, + Context& context, + const TextRenderContext* text_render_context, GlyphAtlas::Type type, Scalar scale, const std::shared_ptr& atlas_context, const TextFrame& frame) { FontGlyphPair::Set set; frame.CollectUniqueFontGlyphPairs(set, scale); - return context->CreateGlyphAtlas(type, atlas_context, set); + return text_render_context->CreateGlyphAtlas(context, type, atlas_context, + set); } TEST_P(TypographerTest, CanConvertTextBlob) { @@ -48,20 +49,20 @@ TEST_P(TypographerTest, CanConvertTextBlob) { } TEST_P(TypographerTest, CanCreateRenderContext) { - auto context = TextRenderContext::Create(GetContext()); + auto context = TextRenderContextSkia::Make(); ASSERT_TRUE(context && context->IsValid()); } TEST_P(TypographerTest, CanCreateGlyphAtlas) { - auto context = TextRenderContext::Create(GetContext()); + auto context = TextRenderContextSkia::Make(); auto atlas_context = std::make_shared(); ASSERT_TRUE(context && context->IsValid()); SkFont sk_font; auto blob = SkTextBlob::MakeFromString("hello", sk_font); ASSERT_TRUE(blob); - auto atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob)); + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), + GlyphAtlas::Type::kAlphaBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob)); ASSERT_NE(atlas, nullptr); ASSERT_NE(atlas->GetTexture(), nullptr); ASSERT_EQ(atlas->GetType(), GlyphAtlas::Type::kAlphaBitmap); @@ -111,7 +112,7 @@ TEST_P(TypographerTest, LazyAtlasTracksColor) { ASSERT_FALSE(frame.GetAtlasType() == GlyphAtlas::Type::kColorBitmap); - LazyGlyphAtlas lazy_atlas; + LazyGlyphAtlas lazy_atlas(TextRenderContextSkia::Make()); lazy_atlas.AddTextFrame(frame, 1.0f); @@ -123,24 +124,24 @@ TEST_P(TypographerTest, LazyAtlasTracksColor) { // Creates different atlases for color and alpha bitmap. auto color_atlas = lazy_atlas.CreateOrGetGlyphAtlas( - GlyphAtlas::Type::kColorBitmap, GetContext()); + *GetContext(), GlyphAtlas::Type::kColorBitmap); auto bitmap_atlas = lazy_atlas.CreateOrGetGlyphAtlas( - GlyphAtlas::Type::kAlphaBitmap, GetContext()); + *GetContext(), GlyphAtlas::Type::kAlphaBitmap); ASSERT_FALSE(color_atlas == bitmap_atlas); } TEST_P(TypographerTest, GlyphAtlasWithOddUniqueGlyphSize) { - auto context = TextRenderContext::Create(GetContext()); + auto context = TextRenderContextSkia::Make(); auto atlas_context = std::make_shared(); ASSERT_TRUE(context && context->IsValid()); SkFont sk_font; auto blob = SkTextBlob::MakeFromString("AGH", sk_font); ASSERT_TRUE(blob); - auto atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob)); + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), + GlyphAtlas::Type::kAlphaBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob)); ASSERT_NE(atlas, nullptr); ASSERT_NE(atlas->GetTexture(), nullptr); @@ -149,30 +150,30 @@ TEST_P(TypographerTest, GlyphAtlasWithOddUniqueGlyphSize) { } TEST_P(TypographerTest, GlyphAtlasIsRecycledIfUnchanged) { - auto context = TextRenderContext::Create(GetContext()); + auto context = TextRenderContextSkia::Make(); auto atlas_context = std::make_shared(); ASSERT_TRUE(context && context->IsValid()); SkFont sk_font; auto blob = SkTextBlob::MakeFromString("spooky skellingtons", sk_font); ASSERT_TRUE(blob); - auto atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob)); + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), + GlyphAtlas::Type::kAlphaBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob)); ASSERT_NE(atlas, nullptr); ASSERT_NE(atlas->GetTexture(), nullptr); ASSERT_EQ(atlas, atlas_context->GetGlyphAtlas()); // now attempt to re-create an atlas with the same text blob. - auto next_atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob)); + auto next_atlas = CreateGlyphAtlas( + *GetContext(), context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob)); ASSERT_EQ(atlas, next_atlas); ASSERT_EQ(atlas_context->GetGlyphAtlas(), atlas); } TEST_P(TypographerTest, GlyphAtlasWithLotsOfdUniqueGlyphSize) { - auto context = TextRenderContext::Create(GetContext()); + auto context = TextRenderContextSkia::Make(); auto atlas_context = std::make_shared(); ASSERT_TRUE(context && context->IsValid()); @@ -191,8 +192,9 @@ TEST_P(TypographerTest, GlyphAtlasWithLotsOfdUniqueGlyphSize) { for (size_t index = 0; index < size_count; index += 1) { TextFrameFromTextBlob(blob).CollectUniqueFontGlyphPairs(set, 0.6 * index); }; - auto atlas = context->CreateGlyphAtlas(GlyphAtlas::Type::kAlphaBitmap, - std::move(atlas_context), set); + auto atlas = + context->CreateGlyphAtlas(*GetContext(), GlyphAtlas::Type::kAlphaBitmap, + std::move(atlas_context), set); ASSERT_NE(atlas, nullptr); ASSERT_NE(atlas->GetTexture(), nullptr); @@ -213,15 +215,15 @@ TEST_P(TypographerTest, GlyphAtlasWithLotsOfdUniqueGlyphSize) { } TEST_P(TypographerTest, GlyphAtlasTextureIsRecycledIfUnchanged) { - auto context = TextRenderContext::Create(GetContext()); + auto context = TextRenderContextSkia::Make(); auto atlas_context = std::make_shared(); ASSERT_TRUE(context && context->IsValid()); SkFont sk_font; auto blob = SkTextBlob::MakeFromString("spooky 1", sk_font); ASSERT_TRUE(blob); - auto atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob)); + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), + GlyphAtlas::Type::kAlphaBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob)); auto old_packer = atlas_context->GetRectPacker(); ASSERT_NE(atlas, nullptr); @@ -233,9 +235,9 @@ TEST_P(TypographerTest, GlyphAtlasTextureIsRecycledIfUnchanged) { // Now create a new glyph atlas with a nearly identical blob. auto blob2 = SkTextBlob::MakeFromString("spooky 2", sk_font); - auto next_atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob2)); + auto next_atlas = CreateGlyphAtlas( + *GetContext(), context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob2)); ASSERT_EQ(atlas, next_atlas); auto* second_texture = next_atlas->GetTexture().get(); @@ -246,15 +248,15 @@ TEST_P(TypographerTest, GlyphAtlasTextureIsRecycledIfUnchanged) { } TEST_P(TypographerTest, GlyphAtlasTextureIsRecreatedIfTypeChanges) { - auto context = TextRenderContext::Create(GetContext()); + auto context = TextRenderContextSkia::Make(); auto atlas_context = std::make_shared(); ASSERT_TRUE(context && context->IsValid()); SkFont sk_font; auto blob = SkTextBlob::MakeFromString("spooky 1", sk_font); ASSERT_TRUE(blob); - auto atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kAlphaBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob)); + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), + GlyphAtlas::Type::kAlphaBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob)); auto old_packer = atlas_context->GetRectPacker(); ASSERT_NE(atlas, nullptr); @@ -267,9 +269,9 @@ TEST_P(TypographerTest, GlyphAtlasTextureIsRecreatedIfTypeChanges) { // but change the type. auto blob2 = SkTextBlob::MakeFromString("spooky 1", sk_font); - auto next_atlas = - CreateGlyphAtlas(context.get(), GlyphAtlas::Type::kColorBitmap, 1.0f, - atlas_context, TextFrameFromTextBlob(blob2)); + auto next_atlas = CreateGlyphAtlas( + *GetContext(), context.get(), GlyphAtlas::Type::kColorBitmap, 1.0f, + atlas_context, TextFrameFromTextBlob(blob2)); ASSERT_NE(atlas, next_atlas); auto* second_texture = next_atlas->GetTexture().get(); diff --git a/lib/ui/BUILD.gn b/lib/ui/BUILD.gn index 8ad0197bb1d8d..1c985fc3763c3 100644 --- a/lib/ui/BUILD.gn +++ b/lib/ui/BUILD.gn @@ -123,12 +123,10 @@ source_set("ui") { "text/asset_manager_font_provider.h", "text/font_collection.cc", "text/font_collection.h", - "text/line_metrics.h", "text/paragraph.cc", "text/paragraph.h", "text/paragraph_builder.cc", "text/paragraph_builder.h", - "text/text_box.h", "ui_dart_state.cc", "ui_dart_state.h", "volatile_path_tracker.cc", diff --git a/lib/ui/painting/canvas.cc b/lib/ui/painting/canvas.cc index de6363e4f4e9d..0b090b68c9a7b 100644 --- a/lib/ui/painting/canvas.cc +++ b/lib/ui/painting/canvas.cc @@ -6,7 +6,7 @@ #include -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/lib/ui/floating_point.h" #include "flutter/lib/ui/painting/image.h" #include "flutter/lib/ui/painting/image_filter.h" diff --git a/lib/ui/painting/paint.cc b/lib/ui/painting/paint.cc index 2c72fb90b05e8..592643bee7d82 100644 --- a/lib/ui/painting/paint.cc +++ b/lib/ui/painting/paint.cc @@ -4,6 +4,7 @@ #include "flutter/lib/ui/painting/paint.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/fml/logging.h" #include "flutter/lib/ui/floating_point.h" #include "flutter/lib/ui/painting/color_filter.h" diff --git a/lib/ui/painting/picture_recorder.h b/lib/ui/painting/picture_recorder.h index 34a11fe0cc192..c5046a424a6ac 100644 --- a/lib/ui/painting/picture_recorder.h +++ b/lib/ui/painting/picture_recorder.h @@ -5,7 +5,7 @@ #ifndef FLUTTER_LIB_UI_PAINTING_PICTURE_RECORDER_H_ #define FLUTTER_LIB_UI_PAINTING_PICTURE_RECORDER_H_ -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/lib/ui/dart_wrapper.h" namespace flutter { diff --git a/lib/ui/text.dart b/lib/ui/text.dart index 45f86ce3c76ba..20cd759382f2d 100644 --- a/lib/ui/text.dart +++ b/lib/ui/text.dart @@ -13,41 +13,38 @@ enum FontStyle { } /// The thickness of the glyphs used to draw the text -class FontWeight { - const FontWeight._(this.index, this.value); - - /// The encoded integer value of this font weight. - final int index; - - /// The thickness value of this font weight. - final int value; - +enum FontWeight { /// Thin, the least thick - static const FontWeight w100 = FontWeight._(0, 100); + w100._(100), /// Extra-light - static const FontWeight w200 = FontWeight._(1, 200); + w200._(200), /// Light - static const FontWeight w300 = FontWeight._(2, 300); + w300._(300), /// Normal / regular / plain - static const FontWeight w400 = FontWeight._(3, 400); + w400._(400), /// Medium - static const FontWeight w500 = FontWeight._(4, 500); + w500._(500), /// Semi-bold - static const FontWeight w600 = FontWeight._(5, 600); + w600._(600), /// Bold - static const FontWeight w700 = FontWeight._(6, 700); + w700._(700), /// Extra-bold - static const FontWeight w800 = FontWeight._(7, 800); + w800._(800), /// Black, the most thick - static const FontWeight w900 = FontWeight._(8, 900); + w900._(900); + + const FontWeight._(this.value); + + /// The thickness value of this font weight. + final int value; /// The default font weight. static const FontWeight normal = w400; @@ -55,11 +52,6 @@ class FontWeight { /// A commonly used font weight that is heavier than normal. static const FontWeight bold = w700; - /// A list of all the font weights. - static const List values = [ - w100, w200, w300, w400, w500, w600, w700, w800, w900 - ]; - /// Linearly interpolates between two font weights. /// /// Rather than using fractional weights, the interpolation rounds to the @@ -87,21 +79,6 @@ class FontWeight { } return values[_lerpInt((a ?? normal).index, (b ?? normal).index, t).round().clamp(0, 8)]; } - - @override - String toString() { - return const { - 0: 'FontWeight.w100', - 1: 'FontWeight.w200', - 2: 'FontWeight.w300', - 3: 'FontWeight.w400', - 4: 'FontWeight.w500', - 5: 'FontWeight.w600', - 6: 'FontWeight.w700', - 7: 'FontWeight.w800', - 8: 'FontWeight.w900', - }[index]!; - } } /// A feature tag and value that affect the selection of glyphs in a font. diff --git a/lib/ui/text/line_metrics.h b/lib/ui/text/line_metrics.h deleted file mode 100644 index f5f656cd816f9..0000000000000 --- a/lib/ui/text/line_metrics.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_ -#define FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_ - -#include "third_party/dart/runtime/include/dart_api.h" -#include "third_party/tonic/converter/dart_converter.h" - -namespace flutter { - -struct LineMetrics { - const bool* hard_break; - - // The final computed ascent and descent for the line. This can be impacted by - // the strut, height, scaling, as well as outlying runs that are very tall. - // - // The top edge is `baseline - ascent` and the bottom edge is `baseline + - // descent`. Ascent and descent are provided as positive numbers. Raw numbers - // for specific runs of text can be obtained in run_metrics_map. These values - // are the cumulative metrics for the entire line. - const double* ascent; - const double* descent; - const double* unscaled_ascent; - // Height of the line. - const double* height; - // Width of the line. - const double* width; - // The left edge of the line. The right edge can be obtained with `left + - // width` - const double* left; - // The y position of the baseline for this line from the top of the paragraph. - const double* baseline; - // Zero indexed line number. - const size_t* line_number; - - LineMetrics(); - - LineMetrics(const bool* hard_break, - const double* ascent, - const double* descent, - const double* unscaled_ascent, - const double* height, - const double* width, - const double* left, - const double* baseline, - const size_t* line_number) - : hard_break(hard_break), - ascent(ascent), - descent(descent), - unscaled_ascent(unscaled_ascent), - height(height), - width(width), - left(left), - baseline(baseline), - line_number(line_number) {} -}; - -} // namespace flutter - -#endif // FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_ diff --git a/lib/ui/text/paragraph.h b/lib/ui/text/paragraph.h index 1a5d8217aafc4..3a0523a580827 100644 --- a/lib/ui/text/paragraph.h +++ b/lib/ui/text/paragraph.h @@ -8,8 +8,6 @@ #include "flutter/fml/message_loop.h" #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/painting/canvas.h" -#include "flutter/lib/ui/text/line_metrics.h" -#include "flutter/lib/ui/text/text_box.h" #include "flutter/third_party/txt/src/txt/paragraph.h" namespace flutter { diff --git a/lib/ui/text/text_box.h b/lib/ui/text/text_box.h deleted file mode 100644 index 27f60670f232f..0000000000000 --- a/lib/ui/text/text_box.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FLUTTER_LIB_UI_TEXT_TEXT_BOX_H_ -#define FLUTTER_LIB_UI_TEXT_TEXT_BOX_H_ - -#include "third_party/dart/runtime/include/dart_api.h" -#include "third_party/skia/include/core/SkRect.h" -#include "third_party/tonic/converter/dart_converter.h" - -namespace flutter { - -enum class TextDirection { - rtl, - ltr, -}; - -struct TextBox { - SkRect rect; - TextDirection direction; - - TextBox(SkRect r, TextDirection d) : rect(r), direction(d) {} -}; - -} // namespace flutter - -#endif // FLUTTER_LIB_UI_TEXT_TEXT_BOX_H_ diff --git a/lib/web_ui/lib/initialization.dart b/lib/web_ui/lib/initialization.dart index f3f0208a0981a..9e1641186b3df 100644 --- a/lib/web_ui/lib/initialization.dart +++ b/lib/web_ui/lib/initialization.dart @@ -31,6 +31,13 @@ part of ui; // TODO(mdebbar): Deprecate this and remove it. // https://github.com/flutter/flutter/issues/127395 Future webOnlyInitializePlatform() async { + assert(() { + engine.printWarning( + 'The webOnlyInitializePlatform API is deprecated and will be removed in a ' + 'future release. Please use `bootstrapEngine` from `dart:ui_web` instead.', + ); + return true; + }()); await engine.initializeEngine(); } diff --git a/lib/web_ui/lib/painting.dart b/lib/web_ui/lib/painting.dart index b974b4868968d..24261b30e03a1 100644 --- a/lib/web_ui/lib/painting.dart +++ b/lib/web_ui/lib/painting.dart @@ -533,9 +533,22 @@ class TargetImageSize { final int? height; } -Future webOnlyInstantiateImageCodecFromUrl(Uri uri, - {engine.WebOnlyImageCodecChunkCallback? chunkCallback}) => - engine.renderer.instantiateImageCodecFromUrl(uri, chunkCallback: chunkCallback); +// TODO(mdebbar): Deprecate this and remove it. +// https://github.com/flutter/flutter/issues/127395 +Future webOnlyInstantiateImageCodecFromUrl( + Uri uri, { + ui_web.ImageCodecChunkCallback? chunkCallback, +}) { + assert(() { + engine.printWarning( + 'The webOnlyInstantiateImageCodecFromUrl API is deprecated and will be ' + 'removed in a future release. Please use `createImageCodecFromUrl` from ' + '`dart:ui_web` instead.', + ); + return true; + }()); + return ui_web.createImageCodecFromUrl(uri, chunkCallback: chunkCallback); +} void decodeImageFromList(Uint8List list, ImageDecoderCallback callback) { _decodeImageFromListAsync(list, callback); diff --git a/lib/web_ui/lib/src/engine/canvaskit/image.dart b/lib/web_ui/lib/src/engine/canvaskit/image.dart index 11af8b8a3d59b..fd822860c1d0f 100644 --- a/lib/web_ui/lib/src/engine/canvaskit/image.dart +++ b/lib/web_ui/lib/src/engine/canvaskit/image.dart @@ -8,6 +8,7 @@ import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; /// Instantiates a [ui.Codec] backed by an `SkAnimatedImage` from Skia. FutureOr skiaInstantiateImageCodec(Uint8List list, @@ -159,7 +160,7 @@ const String _kNetworkImageMessage = 'Failed to load network image.'; /// Instantiates a [ui.Codec] backed by an `SkAnimatedImage` from Skia after /// requesting from URI. Future skiaInstantiateWebImageCodec( - String url, WebOnlyImageCodecChunkCallback? chunkCallback) async { + String url, ui_web.ImageCodecChunkCallback? chunkCallback) async { final Uint8List list = await fetchImage(url, chunkCallback); if (browserSupportsImageDecoder) { return CkBrowserImageDecoder.create(data: list, debugSource: url); @@ -169,7 +170,7 @@ Future skiaInstantiateWebImageCodec( } /// Sends a request to fetch image data. -Future fetchImage(String url, WebOnlyImageCodecChunkCallback? chunkCallback) async { +Future fetchImage(String url, ui_web.ImageCodecChunkCallback? chunkCallback) async { try { final HttpFetchResponse response = await httpFetch(url); final int? contentLength = response.contentLength; @@ -200,7 +201,7 @@ Future fetchImage(String url, WebOnlyImageCodecChunkCallback? chunkCa /// Reads the [payload] in chunks using the browser's Streams API /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API -Future readChunked(HttpFetchPayload payload, int contentLength, WebOnlyImageCodecChunkCallback chunkCallback) async { +Future readChunked(HttpFetchPayload payload, int contentLength, ui_web.ImageCodecChunkCallback chunkCallback) async { final JSUint8Array result = createUint8ArrayFromLength(contentLength); int position = 0; int cumulativeBytesLoaded = 0; diff --git a/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart b/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart index 9048c857a584b..d6f732e9bae24 100644 --- a/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart +++ b/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart @@ -81,7 +81,6 @@ class LayerSceneBuilder implements ui.SceneBuilder { ui.Offset offset = ui.Offset.zero, double width = 0.0, double height = 0.0, - Object? webOnlyPaintedBy, }) { currentLayer.add(PlatformViewLayer(viewId, offset, width, height)); } diff --git a/lib/web_ui/lib/src/engine/canvaskit/renderer.dart b/lib/web_ui/lib/src/engine/canvaskit/renderer.dart index 96da491f69af4..b94f75047e607 100644 --- a/lib/web_ui/lib/src/engine/canvaskit/renderer.dart +++ b/lib/web_ui/lib/src/engine/canvaskit/renderer.dart @@ -209,7 +209,7 @@ class CanvasKitRenderer implements Renderer { @override Future instantiateImageCodecFromUrl( Uri uri, { - WebOnlyImageCodecChunkCallback? chunkCallback + ui_web.ImageCodecChunkCallback? chunkCallback }) => skiaInstantiateWebImageCodec(uri.toString(), chunkCallback); @override diff --git a/lib/web_ui/lib/src/engine/html/renderer.dart b/lib/web_ui/lib/src/engine/html/renderer.dart index 728c8bc367ce2..5084a202d4de0 100644 --- a/lib/web_ui/lib/src/engine/html/renderer.dart +++ b/lib/web_ui/lib/src/engine/html/renderer.dart @@ -8,6 +8,7 @@ import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; class HtmlRenderer implements Renderer { static HtmlRenderer get instance => _instance; @@ -176,11 +177,9 @@ class HtmlRenderer implements Renderer { @override Future instantiateImageCodecFromUrl( Uri uri, { - WebOnlyImageCodecChunkCallback? chunkCallback}) { - return futurize((Callback callback) { - callback(HtmlCodec(uri.toString(), chunkCallback: chunkCallback)); - return null; - }); + ui_web.ImageCodecChunkCallback? chunkCallback, + }) async { + return HtmlCodec(uri.toString(), chunkCallback: chunkCallback); } @override diff --git a/lib/web_ui/lib/src/engine/html/scene_builder.dart b/lib/web_ui/lib/src/engine/html/scene_builder.dart index e77e7d47928f9..5f1a7c687474c 100644 --- a/lib/web_ui/lib/src/engine/html/scene_builder.dart +++ b/lib/web_ui/lib/src/engine/html/scene_builder.dart @@ -329,7 +329,7 @@ class SurfaceSceneBuilder implements ui.SceneBuilder { /// overlay or not. /// /// We use this to avoid spamming the console with redundant warning messages. - static bool _webOnlyDidWarnAboutPerformanceOverlay = false; + static bool _didWarnAboutPerformanceOverlay = false; void _addPerformanceOverlay( int enabledOptions, @@ -338,8 +338,8 @@ class SurfaceSceneBuilder implements ui.SceneBuilder { double top, double bottom, ) { - if (!_webOnlyDidWarnAboutPerformanceOverlay) { - _webOnlyDidWarnAboutPerformanceOverlay = true; + if (!_didWarnAboutPerformanceOverlay) { + _didWarnAboutPerformanceOverlay = true; printWarning("The performance overlay isn't supported on the web"); } } diff --git a/lib/web_ui/lib/src/engine/html_image_codec.dart b/lib/web_ui/lib/src/engine/html_image_codec.dart index 5c7935816cb58..e5cdad6b7b309 100644 --- a/lib/web_ui/lib/src/engine/html_image_codec.dart +++ b/lib/web_ui/lib/src/engine/html_image_codec.dart @@ -6,6 +6,7 @@ import 'dart:async'; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import 'browser_detection.dart'; import 'dom.dart'; @@ -20,14 +21,15 @@ Object? get _jsImageDecodeFunction => getJsProperty( ); final bool _supportsDecode = _jsImageDecodeFunction != null; -typedef WebOnlyImageCodecChunkCallback = void Function( - int cumulativeBytesLoaded, int expectedTotalBytes); +// TODO(mdebbar): Deprecate this and remove it. +// https://github.com/flutter/flutter/issues/127395 +typedef WebOnlyImageCodecChunkCallback = ui_web.ImageCodecChunkCallback; class HtmlCodec implements ui.Codec { HtmlCodec(this.src, {this.chunkCallback}); final String src; - final WebOnlyImageCodecChunkCallback? chunkCallback; + final ui_web.ImageCodecChunkCallback? chunkCallback; @override int get frameCount => 1; diff --git a/lib/web_ui/lib/src/engine/renderer.dart b/lib/web_ui/lib/src/engine/renderer.dart index 20fd055b1c13d..c6a84ab959600 100644 --- a/lib/web_ui/lib/src/engine/renderer.dart +++ b/lib/web_ui/lib/src/engine/renderer.dart @@ -8,6 +8,7 @@ import 'dart:typed_data'; import 'package:ui/src/engine/skwasm/skwasm_stub.dart' if (dart.library.ffi) 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import 'browser_detection.dart'; import 'canvaskit/renderer.dart'; @@ -15,7 +16,6 @@ import 'configuration.dart'; import 'embedder.dart'; import 'fonts.dart'; import 'html/renderer.dart'; -import 'html_image_codec.dart'; final Renderer _renderer = Renderer._internal(); Renderer get renderer => _renderer; @@ -131,7 +131,7 @@ abstract class Renderer { Future instantiateImageCodecFromUrl( Uri uri, { - WebOnlyImageCodecChunkCallback? chunkCallback, + ui_web.ImageCodecChunkCallback? chunkCallback, }); void decodeImageFromPixels( diff --git a/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/renderer.dart b/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/renderer.dart index 71fc79ad335a9..08c86b269458e 100644 --- a/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/renderer.dart +++ b/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/renderer.dart @@ -389,7 +389,7 @@ class SkwasmRenderer implements Renderer { @override Future instantiateImageCodecFromUrl( Uri uri, { - WebOnlyImageCodecChunkCallback? chunkCallback + ui_web.ImageCodecChunkCallback? chunkCallback }) async { final DomResponse response = await rawHttpGet(uri.toString()); final String? contentType = response.headers.get('Content-Type'); diff --git a/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart b/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart index 3d4823f49cc2c..314cf0b616f95 100644 --- a/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart +++ b/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart @@ -145,7 +145,7 @@ class SkwasmRenderer implements Renderer { } @override - Future instantiateImageCodecFromUrl(Uri uri, {WebOnlyImageCodecChunkCallback? chunkCallback}) { + Future instantiateImageCodecFromUrl(Uri uri, {ui_web.ImageCodecChunkCallback? chunkCallback}) { throw UnimplementedError('Skwasm not implemented on this platform.'); } diff --git a/lib/web_ui/lib/src/engine/window.dart b/lib/web_ui/lib/src/engine/window.dart index 707be6b38ee76..834027100e32a 100644 --- a/lib/web_ui/lib/src/engine/window.dart +++ b/lib/web_ui/lib/src/engine/window.dart @@ -255,8 +255,8 @@ class EngineFlutterWindow extends ui.SingletonFlutterWindow { bool override = false; assert(() { - if (webOnlyDebugPhysicalSizeOverride != null) { - _physicalSize = webOnlyDebugPhysicalSizeOverride; + if (debugPhysicalSizeOverride != null) { + _physicalSize = debugPhysicalSizeOverride; override = true; } return true; @@ -319,8 +319,37 @@ class EngineFlutterWindow extends ui.SingletonFlutterWindow { /// Lazily populated and cleared at the end of the frame. ui.Size? _physicalSize; - /// Overrides the value of [physicalSize] in tests. - ui.Size? webOnlyDebugPhysicalSizeOverride; + // TODO(mdebbar): Deprecate this and remove it. + // https://github.com/flutter/flutter/issues/127395 + ui.Size? get webOnlyDebugPhysicalSizeOverride { + assert(() { + printWarning( + 'The webOnlyDebugPhysicalSizeOverride API is deprecated and will be ' + 'removed in a future release. Please use ' + '`SingletonFlutterWindow.debugPhysicalSizeOverride` from `dart:ui_web` ' + 'instead.', + ); + return true; + }()); + return debugPhysicalSizeOverride; + } + + // TODO(mdebbar): Deprecate this and remove it. + // https://github.com/flutter/flutter/issues/127395 + set webOnlyDebugPhysicalSizeOverride(ui.Size? value) { + assert(() { + printWarning( + 'The webOnlyDebugPhysicalSizeOverride API is deprecated and will be ' + 'removed in a future release. Please use ' + '`SingletonFlutterWindow.debugPhysicalSizeOverride` from `dart:ui_web` ' + 'instead.', + ); + return true; + }()); + debugPhysicalSizeOverride = value; + } + + ui.Size? debugPhysicalSizeOverride; } /// The Web implementation of [ui.SingletonFlutterWindow]. @@ -336,7 +365,7 @@ class EngineSingletonFlutterWindow extends EngineFlutterWindow { /// Overrides the default device pixel ratio. /// /// This is useful in tests to emulate screens of different dimensions. - void debugOverrideDevicePixelRatio(double value) { + void debugOverrideDevicePixelRatio(double? value) { _debugDevicePixelRatio = value; } diff --git a/lib/web_ui/lib/ui_web/src/ui_web.dart b/lib/web_ui/lib/ui_web/src/ui_web.dart index 02ec39b539595..3d4a9262d60c4 100644 --- a/lib/web_ui/lib/ui_web/src/ui_web.dart +++ b/lib/web_ui/lib/ui_web/src/ui_web.dart @@ -10,6 +10,7 @@ library ui_web; export 'ui_web/asset_manager.dart'; export 'ui_web/benchmarks.dart'; +export 'ui_web/images.dart'; export 'ui_web/initialization.dart'; export 'ui_web/navigation/platform_location.dart'; export 'ui_web/navigation/url_strategy.dart'; diff --git a/lib/web_ui/lib/ui_web/src/ui_web/images.dart b/lib/web_ui/lib/ui_web/src/ui_web/images.dart new file mode 100644 index 0000000000000..d8e4de718111d --- /dev/null +++ b/lib/web_ui/lib/ui_web/src/ui_web/images.dart @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:ui/src/engine.dart'; +import 'package:ui/ui.dart' as ui; + +/// Signature of the callback that receives progress updates as image chunks are +/// loaded. +typedef ImageCodecChunkCallback = void Function( + int cumulativeBytesLoaded, + int expectedTotalBytes, +); + +/// Creates a [ui.Codec] for the image located at [uri]. +/// +/// The [chunkCallback] is called with progress updates as image chunks are +/// loaded. +Future createImageCodecFromUrl( + Uri uri, { + ImageCodecChunkCallback? chunkCallback, +}) { + return renderer.instantiateImageCodecFromUrl( + uri, + chunkCallback: chunkCallback, + ); +} diff --git a/lib/web_ui/lib/ui_web/src/ui_web/testing.dart b/lib/web_ui/lib/ui_web/src/ui_web/testing.dart index ae5b6e88e34e7..5af1694a3aba4 100644 --- a/lib/web_ui/lib/ui_web/src/ui_web/testing.dart +++ b/lib/web_ui/lib/ui_web/src/ui_web/testing.dart @@ -5,6 +5,18 @@ import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +extension SingletonFlutterWindowExtension on ui.SingletonFlutterWindow { + /// Overrides the value of [physicalSize] in tests. + set debugPhysicalSizeOverride(ui.Size? value) { + (this as EngineFlutterWindow).debugPhysicalSizeOverride = value; + } +} + +/// Overrides the value of [ui.FlutterView.devicePixelRatio] in tests. +void debugOverrideDevicePixelRatio(double? value) { + (ui.window as EngineSingletonFlutterWindow).debugOverrideDevicePixelRatio(value); +} + /// Whether the Flutter engine is running in `flutter test` emulation mode. /// /// When true, the engine will emulate a specific screen size, and always @@ -18,8 +30,7 @@ set debugEmulateFlutterTesterEnvironment(bool value) { _debugEmulateFlutterTesterEnvironment = value; if (_debugEmulateFlutterTesterEnvironment) { const ui.Size logicalSize = ui.Size(800.0, 600.0); - window.webOnlyDebugPhysicalSizeOverride = - logicalSize * window.devicePixelRatio; + window.debugPhysicalSizeOverride = logicalSize * window.devicePixelRatio; } debugDisableFontFallbacks = value; } diff --git a/lib/web_ui/test/canvaskit/embedded_views_test.dart b/lib/web_ui/test/canvaskit/embedded_views_test.dart index 1187f02e5e19e..58b34661fcb4d 100644 --- a/lib/web_ui/test/canvaskit/embedded_views_test.dart +++ b/lib/web_ui/test/canvaskit/embedded_views_test.dart @@ -644,7 +644,7 @@ void testMain() { sb.addPicture(ui.Offset.zero, picture); sb.addPlatformView(0, width: 10, height: 10); - window.webOnlyDebugPhysicalSizeOverride = const ui.Size(100, 100); + window.debugPhysicalSizeOverride = const ui.Size(100, 100); window.debugForceResize(); CanvasKitRenderer.instance.rasterizer.draw(sb.build().layerTree); _expectSceneMatches(<_EmbeddedViewMarker>[ @@ -653,7 +653,7 @@ void testMain() { _overlay, ]); - window.webOnlyDebugPhysicalSizeOverride = const ui.Size(200, 200); + window.debugPhysicalSizeOverride = const ui.Size(200, 200); window.debugForceResize(); CanvasKitRenderer.instance.rasterizer.draw(sb.build().layerTree); _expectSceneMatches(<_EmbeddedViewMarker>[ @@ -662,7 +662,7 @@ void testMain() { _overlay, ]); - window.webOnlyDebugPhysicalSizeOverride = null; + window.debugPhysicalSizeOverride = null; window.debugForceResize(); // ImageDecoder is not supported in Safari or Firefox. }, skip: isSafari || isFirefox); diff --git a/lib/web_ui/test/canvaskit/fragment_program_test.dart b/lib/web_ui/test/canvaskit/fragment_program_test.dart index f9c00901e98a1..e7eaf228f8402 100644 --- a/lib/web_ui/test/canvaskit/fragment_program_test.dart +++ b/lib/web_ui/test/canvaskit/fragment_program_test.dart @@ -10,6 +10,7 @@ import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; void main() { internalBootstrapBrowserTest(() => testMain); @@ -182,7 +183,7 @@ const String kJsonIPLR = r''' void testMain() { setUpAll(() async { - await ui.webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); }); test('FragmentProgram can be created from JSON IPLR bundle', () { diff --git a/lib/web_ui/test/canvaskit/scene_test.dart b/lib/web_ui/test/canvaskit/scene_test.dart index 9395c067bb3d7..4bad3c70c1da6 100644 --- a/lib/web_ui/test/canvaskit/scene_test.dart +++ b/lib/web_ui/test/canvaskit/scene_test.dart @@ -7,6 +7,7 @@ import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; void main() { internalBootstrapBrowserTest(() => testMain); @@ -15,7 +16,7 @@ void main() { void testMain() { group('$LayerScene', () { setUpAll(() async { - await ui.webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); }); test('toImage returns an image', () async { diff --git a/lib/web_ui/test/common/test_initialization.dart b/lib/web_ui/test/common/test_initialization.dart index 38420e1489bcd..a7714f0230774 100644 --- a/lib/web_ui/test/common/test_initialization.dart +++ b/lib/web_ui/test/common/test_initialization.dart @@ -32,7 +32,7 @@ void setUpUnitTests({ // this stuff in. const double devicePixelRatio = 3.0; engine.window.debugOverrideDevicePixelRatio(devicePixelRatio); - engine.window.webOnlyDebugPhysicalSizeOverride = + engine.window.debugPhysicalSizeOverride = const ui.Size(800 * devicePixelRatio, 600 * devicePixelRatio); engine.scheduleFrameCallback = () {}; } diff --git a/lib/web_ui/test/engine/dom_http_fetch_test.dart b/lib/web_ui/test/engine/dom_http_fetch_test.dart index 2433d67058cb6..48ed06a7666e5 100644 --- a/lib/web_ui/test/engine/dom_http_fetch_test.dart +++ b/lib/web_ui/test/engine/dom_http_fetch_test.dart @@ -8,14 +8,14 @@ import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; -import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; void main() { internalBootstrapBrowserTest(() => testMain); } Future testMain() async { - await ui.webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); // Test successful HTTP roundtrips where the server returns a happy status // code and a payload. diff --git a/lib/web_ui/test/engine/image/html_image_codec_test.dart b/lib/web_ui/test/engine/image/html_image_codec_test.dart index 1e0381ee0ec5f..e161cea5fb25e 100644 --- a/lib/web_ui/test/engine/image/html_image_codec_test.dart +++ b/lib/web_ui/test/engine/image/html_image_codec_test.dart @@ -9,6 +9,7 @@ import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine/html_image_codec.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../../common/test_initialization.dart'; @@ -104,7 +105,7 @@ Future testMain() async { group('ImageCodecUrl', () { test('loads sample image from web', () async { final Uri uri = Uri.base.resolve('sample_image1.png'); - final HtmlCodec codec = await ui.webOnlyInstantiateImageCodecFromUrl(uri) as HtmlCodec; + final HtmlCodec codec = await ui_web.createImageCodecFromUrl(uri) as HtmlCodec; final ui.FrameInfo frameInfo = await codec.getNextFrame(); expect(frameInfo.image, isNotNull); expect(frameInfo.image.width, 100); @@ -112,7 +113,7 @@ Future testMain() async { test('provides image loading progress from web', () async { final Uri uri = Uri.base.resolve('sample_image1.png'); final StringBuffer buffer = StringBuffer(); - final HtmlCodec codec = await ui.webOnlyInstantiateImageCodecFromUrl(uri, + final HtmlCodec codec = await ui_web.createImageCodecFromUrl(uri, chunkCallback: (int loaded, int total) { buffer.write('$loaded/$total,'); }) as HtmlCodec; diff --git a/lib/web_ui/test/engine/semantics/semantics_test.dart b/lib/web_ui/test/engine/semantics/semantics_test.dart index 84ab72b21ca74..e5f652ea623ad 100644 --- a/lib/web_ui/test/engine/semantics/semantics_test.dart +++ b/lib/web_ui/test/engine/semantics/semantics_test.dart @@ -29,7 +29,7 @@ void main() { } Future testMain() async { - await ui.webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); runSemanticsTests(); } diff --git a/lib/web_ui/test/engine/surface/platform_view_test.dart b/lib/web_ui/test/engine/surface/platform_view_test.dart index e03b3d6a16ea1..34758cb46b7a5 100644 --- a/lib/web_ui/test/engine/surface/platform_view_test.dart +++ b/lib/web_ui/test/engine/surface/platform_view_test.dart @@ -20,7 +20,7 @@ void main() { } Future testMain() async { - await ui.webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); late PersistedPlatformView view; diff --git a/lib/web_ui/test/engine/surface/scene_builder_test.dart b/lib/web_ui/test/engine/surface/scene_builder_test.dart index 375a5887a6052..2469e81649858 100644 --- a/lib/web_ui/test/engine/surface/scene_builder_test.dart +++ b/lib/web_ui/test/engine/surface/scene_builder_test.dart @@ -13,6 +13,7 @@ import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../../common/matchers.dart'; @@ -22,7 +23,7 @@ void main() { void testMain() { setUpAll(() async { - await ui.webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); }); group('SceneBuilder', () { diff --git a/lib/web_ui/test/engine/surface/shaders/shader_builder_test.dart b/lib/web_ui/test/engine/surface/shaders/shader_builder_test.dart index add593d18d5d4..02ddbfafb2e94 100644 --- a/lib/web_ui/test/engine/surface/shaders/shader_builder_test.dart +++ b/lib/web_ui/test/engine/surface/shaders/shader_builder_test.dart @@ -5,7 +5,7 @@ import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; -import 'package:ui/ui.dart' hide window; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; void main() { internalBootstrapBrowserTest(() => testMain); @@ -24,7 +24,7 @@ void testMain() { ')'; setUpAll(() async { - await webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); }); group('Shader Declarations', () { diff --git a/lib/web_ui/test/engine/surface/surface_test.dart b/lib/web_ui/test/engine/surface/surface_test.dart index ac807c8656370..0b43c7911eeaf 100644 --- a/lib/web_ui/test/engine/surface/surface_test.dart +++ b/lib/web_ui/test/engine/surface/surface_test.dart @@ -6,6 +6,7 @@ import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; void main() { internalBootstrapBrowserTest(() => testMain); @@ -14,7 +15,7 @@ void main() { void testMain() { group('Surface', () { setUpAll(() async { - await webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); }); setUp(() { diff --git a/lib/web_ui/test/engine/window_test.dart b/lib/web_ui/test/engine/window_test.dart index 9c957f8c9b048..85f40e1662c3a 100644 --- a/lib/web_ui/test/engine/window_test.dart +++ b/lib/web_ui/test/engine/window_test.dart @@ -10,6 +10,7 @@ import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; +import 'package:ui/ui_web/src/ui_web.dart' as ui_web; const int kPhysicalKeyA = 0x00070004; const int kLogicalKeyA = 0x00000000061; @@ -19,7 +20,7 @@ void main() { } Future testMain() async { - await ui.webOnlyInitializePlatform(); + await ui_web.bootstrapEngine(); test('onTextScaleFactorChanged preserves the zone', () { final Zone innerZone = Zone.current.fork(); diff --git a/shell/common/dl_op_spy.cc b/shell/common/dl_op_spy.cc index 006ca10adcdd2..15910fc2e85de 100644 --- a/shell/common/dl_op_spy.cc +++ b/shell/common/dl_op_spy.cc @@ -81,13 +81,13 @@ void DlOpSpy::drawVertices(const DlVertices* vertices, DlBlendMode mode) { // transparent needs examine all the pixels in the image object, which is slow. // Drawing a completely transparent image is not a valid use case, thus, such // case is ignored. -void DlOpSpy::drawImage(const sk_sp& image, +void DlOpSpy::drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { did_draw_ = true; } -void DlOpSpy::drawImageRect(const sk_sp& image, +void DlOpSpy::drawImageRect(const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, @@ -95,14 +95,14 @@ void DlOpSpy::drawImageRect(const sk_sp& image, SrcRectConstraint constraint) { did_draw_ = true; } -void DlOpSpy::drawImageNine(const sk_sp& image, +void DlOpSpy::drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) { did_draw_ = true; } -void DlOpSpy::drawAtlas(const sk_sp& atlas, +void DlOpSpy::drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -113,7 +113,7 @@ void DlOpSpy::drawAtlas(const sk_sp& atlas, bool render_with_attributes) { did_draw_ = true; } -void DlOpSpy::drawDisplayList(const sk_sp& display_list, +void DlOpSpy::drawDisplayList(const sk_sp display_list, SkScalar opacity) { if (did_draw_ || opacity == 0) { return; @@ -122,7 +122,7 @@ void DlOpSpy::drawDisplayList(const sk_sp& display_list, display_list->Dispatch(receiver); did_draw_ |= receiver.did_draw(); } -void DlOpSpy::drawTextBlob(const sk_sp& blob, +void DlOpSpy::drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) { did_draw_ |= will_draw_; diff --git a/shell/common/dl_op_spy.h b/shell/common/dl_op_spy.h index f81ca435fca7d..1cb29ff7219aa 100644 --- a/shell/common/dl_op_spy.h +++ b/shell/common/dl_op_spy.h @@ -60,23 +60,23 @@ class DlOpSpy final : public virtual DlOpReceiver, uint32_t count, const SkPoint points[]) override; void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; - void drawImage(const sk_sp& image, + void drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override; void drawImageRect( - const sk_sp& image, + const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint = SrcRectConstraint::kFast) override; - void drawImageNine(const sk_sp& image, + void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override; - void drawAtlas(const sk_sp& atlas, + void drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -85,9 +85,9 @@ class DlOpSpy final : public virtual DlOpReceiver, DlImageSampling sampling, const SkRect* cull_rect, bool render_with_attributes) override; - void drawDisplayList(const sk_sp& display_list, + void drawDisplayList(const sk_sp display_list, SkScalar opacity = SK_Scalar1) override; - void drawTextBlob(const sk_sp& blob, + void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) override; void drawShadow(const SkPath& path, diff --git a/shell/common/dl_op_spy_unittests.cc b/shell/common/dl_op_spy_unittests.cc index dcdddd6162ca2..7aaac1cbe52a8 100644 --- a/shell/common/dl_op_spy_unittests.cc +++ b/shell/common/dl_op_spy_unittests.cc @@ -3,7 +3,7 @@ // found in the LICENSE file. #include "flutter/display_list/display_list.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/shell/common/dl_op_spy.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkBitmap.h" diff --git a/shell/common/rasterizer.h b/shell/common/rasterizer.h index bb05e4475f998..d413edf6ac2cb 100644 --- a/shell/common/rasterizer.h +++ b/shell/common/rasterizer.h @@ -25,9 +25,10 @@ #include "flutter/fml/time/time_point.h" #if IMPELLER_SUPPORTS_RENDERING // GN is having trouble understanding how this works in the Fuchsia builds. -#include "flutter/impeller/aiks/aiks_context.h" // nogncheck -#include "flutter/impeller/renderer/context.h" // nogncheck -#endif // IMPELLER_SUPPORTS_RENDERING +#include "impeller/aiks/aiks_context.h" // nogncheck +#include "impeller/renderer/context.h" // nogncheck +#include "impeller/typographer/backends/skia/text_render_context_skia.h" // nogncheck +#endif // IMPELLER_SUPPORTS_RENDERING #include "flutter/lib/ui/snapshot_delegate.h" #include "flutter/shell/common/pipeline.h" #include "flutter/shell/common/snapshot_controller.h" @@ -544,7 +545,8 @@ class Rasterizer final : public SnapshotDelegate, return surface_->GetAiksContext(); } if (auto context = impeller_context_.lock()) { - return std::make_shared(context); + return std::make_shared( + context, impeller::TextRenderContextSkia::Make()); } #endif return nullptr; diff --git a/shell/gpu/gpu_surface_gl_impeller.cc b/shell/gpu/gpu_surface_gl_impeller.cc index 84372944eb6d4..6cb4faa8dbed1 100644 --- a/shell/gpu/gpu_surface_gl_impeller.cc +++ b/shell/gpu/gpu_surface_gl_impeller.cc @@ -5,9 +5,10 @@ #include "flutter/shell/gpu/gpu_surface_gl_impeller.h" #include "flutter/fml/make_copyable.h" -#include "flutter/impeller/display_list/dl_dispatcher.h" -#include "flutter/impeller/renderer/backend/gles/surface_gles.h" -#include "flutter/impeller/renderer/renderer.h" +#include "impeller/display_list/dl_dispatcher.h" +#include "impeller/renderer/backend/gles/surface_gles.h" +#include "impeller/renderer/renderer.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" namespace flutter { @@ -28,7 +29,8 @@ GPUSurfaceGLImpeller::GPUSurfaceGLImpeller( return; } - auto aiks_context = std::make_shared(context); + auto aiks_context = std::make_shared( + context, impeller::TextRenderContextSkia::Make()); if (!aiks_context->IsValid()) { return; diff --git a/shell/gpu/gpu_surface_metal_impeller.mm b/shell/gpu/gpu_surface_metal_impeller.mm index 2db00a25dc4fd..c95e53599b57e 100644 --- a/shell/gpu/gpu_surface_metal_impeller.mm +++ b/shell/gpu/gpu_surface_metal_impeller.mm @@ -11,8 +11,9 @@ #include "flutter/fml/make_copyable.h" #include "flutter/fml/mapping.h" #include "flutter/fml/trace_event.h" -#include "flutter/impeller/display_list/dl_dispatcher.h" -#include "flutter/impeller/renderer/backend/metal/surface_mtl.h" +#include "impeller/display_list/dl_dispatcher.h" +#include "impeller/renderer/backend/metal/surface_mtl.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" static_assert(!__has_feature(objc_arc), "ARC must be disabled."); @@ -35,7 +36,8 @@ render_target_type_(delegate->GetRenderTargetType()), impeller_renderer_(CreateImpellerRenderer(context)), aiks_context_( - std::make_shared(impeller_renderer_ ? context : nullptr)), + std::make_shared(impeller_renderer_ ? context : nullptr, + impeller::TextRenderContextSkia::Make())), render_to_surface_(render_to_surface) { // If this preference is explicitly set, we allow for disabling partial repaint. NSNumber* disablePartialRepaint = diff --git a/shell/gpu/gpu_surface_vulkan_impeller.cc b/shell/gpu/gpu_surface_vulkan_impeller.cc index 42c5f1d53c61e..4ffc92afdb10d 100644 --- a/shell/gpu/gpu_surface_vulkan_impeller.cc +++ b/shell/gpu/gpu_surface_vulkan_impeller.cc @@ -5,10 +5,11 @@ #include "flutter/shell/gpu/gpu_surface_vulkan_impeller.h" #include "flutter/fml/make_copyable.h" -#include "flutter/impeller/display_list/dl_dispatcher.h" -#include "flutter/impeller/renderer/renderer.h" +#include "impeller/display_list/dl_dispatcher.h" #include "impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "impeller/renderer/renderer.h" #include "impeller/renderer/surface.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" namespace flutter { @@ -23,7 +24,8 @@ GPUSurfaceVulkanImpeller::GPUSurfaceVulkanImpeller( return; } - auto aiks_context = std::make_shared(context); + auto aiks_context = std::make_shared( + context, impeller::TextRenderContextSkia::Make()); if (!aiks_context->IsValid()) { return; } diff --git a/shell/platform/android/io/flutter/embedding/android/AndroidTouchProcessor.java b/shell/platform/android/io/flutter/embedding/android/AndroidTouchProcessor.java index de60256fccd40..f3a75a991b309 100644 --- a/shell/platform/android/io/flutter/embedding/android/AndroidTouchProcessor.java +++ b/shell/platform/android/io/flutter/embedding/android/AndroidTouchProcessor.java @@ -1,9 +1,13 @@ package io.flutter.embedding.android; +import android.annotation.TargetApi; +import android.content.Context; import android.graphics.Matrix; import android.os.Build; +import android.util.TypedValue; import android.view.InputDevice; import android.view.MotionEvent; +import android.view.ViewConfiguration; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; @@ -80,6 +84,10 @@ public class AndroidTouchProcessor { private static final int POINTER_DATA_FIELD_COUNT = 35; @VisibleForTesting static final int BYTES_PER_FIELD = 8; + // Default if context is null, chosen to ensure reasonable speed scrolling. + @VisibleForTesting static final int DEFAULT_VERTICAL_SCROLL_FACTOR = 48; + @VisibleForTesting static final int DEFAULT_HORIZONTAL_SCROLL_FACTOR = 48; + // This value must match the value in framework's platform_view.dart. // This flag indicates whether the original Android pointer events were batched together. private static final int POINTER_DATA_FLAG_BATCHED = 1; @@ -93,6 +101,9 @@ public class AndroidTouchProcessor { private final Map ongoingPans = new HashMap<>(); + // Only used on api 25 and below to avoid requerying display metrics. + private int cachedVerticalScrollFactor; + /** * Constructs an {@code AndroidTouchProcessor} that will send touch event data to the Flutter * execution context represented by the given {@link FlutterRenderer}. @@ -181,9 +192,10 @@ public boolean onTouchEvent(@NonNull MotionEvent event, @NonNull Matrix transfor * wheel movements, etc. * * @param event The generic motion event being processed. + * @param context For use by ViewConfiguration.get(context) to scale input. * @return True if the event was handled. */ - public boolean onGenericMotionEvent(@NonNull MotionEvent event) { + public boolean onGenericMotionEvent(@NonNull MotionEvent event, @NonNull Context context) { // Method isFromSource is only available in API 18+ (Jelly Bean MR2) // Mouse hover support is not implemented for API < 18. boolean isPointerEvent = @@ -192,7 +204,9 @@ public boolean onGenericMotionEvent(@NonNull MotionEvent event) { boolean isMovementEvent = (event.getActionMasked() == MotionEvent.ACTION_HOVER_MOVE || event.getActionMasked() == MotionEvent.ACTION_SCROLL); - if (!isPointerEvent || !isMovementEvent) { + if (isPointerEvent && isMovementEvent) { + // Continue. + } else { return false; } @@ -203,7 +217,8 @@ public boolean onGenericMotionEvent(@NonNull MotionEvent event) { packet.order(ByteOrder.LITTLE_ENDIAN); // ACTION_HOVER_MOVE always applies to a single pointer only. - addPointerForIndex(event, event.getActionIndex(), pointerChange, 0, IDENTITY_TRANSFORM, packet); + addPointerForIndex( + event, event.getActionIndex(), pointerChange, 0, IDENTITY_TRANSFORM, packet, context); if (packet.position() % (POINTER_DATA_FIELD_COUNT * BYTES_PER_FIELD) != 0) { throw new AssertionError("Packet position is not on field boundary."); } @@ -211,8 +226,9 @@ public boolean onGenericMotionEvent(@NonNull MotionEvent event) { return true; } - // TODO(mattcarroll): consider creating a PointerPacket class instead of using a procedure that - // mutates inputs. + /// Calls addPointerForIndex with null for context. + /// + /// Without context the scroll wheel will not mimick android's scroll speed. private void addPointerForIndex( MotionEvent event, int pointerIndex, @@ -220,9 +236,24 @@ private void addPointerForIndex( int pointerData, Matrix transformMatrix, ByteBuffer packet) { + addPointerForIndex( + event, pointerIndex, pointerChange, pointerData, transformMatrix, packet, null); + } + + // TODO: consider creating a PointerPacket class instead of using a procedure that + // mutates inputs. https://github.com/flutter/flutter/issues/132853 + private void addPointerForIndex( + MotionEvent event, + int pointerIndex, + int pointerChange, + int pointerData, + Matrix transformMatrix, + ByteBuffer packet, + Context context) { if (pointerChange == -1) { return; } + final int pointerId = event.getPointerId(pointerIndex); int pointerKind = getPointerDeviceTypeForToolType(event.getToolType(pointerIndex)); // We use this in lieu of using event.getRawX and event.getRawY as we wish to support @@ -238,16 +269,21 @@ private void addPointerForIndex( // Some implementations translate trackpad scrolling into a mouse down-move-up event // sequence with buttons: 0, such as ARC on a Chromebook. See #11420, a legacy // implementation that uses the same condition but converts differently. - ongoingPans.put(event.getPointerId(pointerIndex), viewToScreenCoords); + ongoingPans.put(pointerId, viewToScreenCoords); } } else if (pointerKind == PointerDeviceKind.STYLUS) { + // Returns converted android button state into flutter framework normalized state + // and updates ongoingPans for chromebook trackpad scrolling. + // See + // https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/gestures/events.dart + // for target button constants. buttons = (event.getButtonState() >> 4) & 0xF; } else { buttons = 0; } int panZoomType = -1; - boolean isTrackpadPan = ongoingPans.containsKey(event.getPointerId(pointerIndex)); + boolean isTrackpadPan = ongoingPans.containsKey(pointerId); if (isTrackpadPan) { panZoomType = getPointerChangeForPanZoom(pointerChange); if (panZoomType == -1) { @@ -278,13 +314,13 @@ private void addPointerForIndex( packet.putLong(pointerKind); // kind } packet.putLong(signalKind); // signal_kind - packet.putLong(event.getPointerId(pointerIndex)); // device + packet.putLong(pointerId); // device packet.putLong(0); // pointer_identifier, will be generated in pointer_data_packet_converter.cc. if (isTrackpadPan) { - float[] panStart = ongoingPans.get(event.getPointerId(pointerIndex)); - packet.putDouble(panStart[0]); - packet.putDouble(panStart[1]); + float[] panStart = ongoingPans.get(pointerId); + packet.putDouble(panStart[0]); // physical_x + packet.putDouble(panStart[1]); // physical_y } else { packet.putDouble(viewToScreenCoords[0]); // physical_x packet.putDouble(viewToScreenCoords[1]); // physical_y @@ -341,16 +377,30 @@ private void addPointerForIndex( packet.putLong(pointerData); // platformData + // See android scrollview for inspiration. + // https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/widget/ScrollView.java?q=function:onGenericMotionEvent%20filepath:widget%2FScrollView.java&ss=android%2Fplatform%2Fsuperproject%2Fmain if (signalKind == PointerSignalKind.SCROLL) { - packet.putDouble(-event.getAxisValue(MotionEvent.AXIS_HSCROLL)); // scroll_delta_x - packet.putDouble(-event.getAxisValue(MotionEvent.AXIS_VSCROLL)); // scroll_delta_y + double horizontalScaleFactor = DEFAULT_HORIZONTAL_SCROLL_FACTOR; + double verticalScaleFactor = DEFAULT_VERTICAL_SCROLL_FACTOR; + if (context != null) { + horizontalScaleFactor = getHorizontalScrollFactor(context); + verticalScaleFactor = getVerticalScrollFactor(context); + } + // We flip the sign of the scroll value below because it aligns the pixel value with the + // scroll direction in native android. + final double horizontalScrollPixels = + horizontalScaleFactor * -event.getAxisValue(MotionEvent.AXIS_HSCROLL, pointerIndex); + final double verticalScrollPixels = + verticalScaleFactor * -event.getAxisValue(MotionEvent.AXIS_VSCROLL, pointerIndex); + packet.putDouble(horizontalScrollPixels); // scroll_delta_x + packet.putDouble(verticalScrollPixels); // scroll_delta_y } else { packet.putDouble(0.0); // scroll_delta_x - packet.putDouble(0.0); // scroll_delta_x + packet.putDouble(0.0); // scroll_delta_y } if (isTrackpadPan) { - float[] panStart = ongoingPans.get(event.getPointerId(pointerIndex)); + float[] panStart = ongoingPans.get(pointerId); packet.putDouble(viewToScreenCoords[0] - panStart[0]); packet.putDouble(viewToScreenCoords[1] - panStart[1]); } else { @@ -363,8 +413,46 @@ private void addPointerForIndex( packet.putDouble(0.0); // rotation if (isTrackpadPan && (panZoomType == PointerChange.PAN_ZOOM_END)) { - ongoingPans.remove(event.getPointerId(pointerIndex)); + ongoingPans.remove(pointerId); + } + } + + private float getHorizontalScrollFactor(@NonNull Context context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + return ViewConfiguration.get(context).getScaledHorizontalScrollFactor(); + } else { + // Vertical scroll factor is not a typo. This is what View.java does in android. + return getVerticalScrollFactorPre26(context); + } + } + + private float getVerticalScrollFactor(@NonNull Context context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + return getVerticalScrollFactorAbove26(context); + } else { + return getVerticalScrollFactorPre26(context); + } + } + + @TargetApi(26) + private float getVerticalScrollFactorAbove26(@NonNull Context context) { + return ViewConfiguration.get(context).getScaledVerticalScrollFactor(); + } + + // See + // https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/view/View.java?q=function:getVerticalScrollFactor%20filepath:android%2Fview%2FView.java&ss=android%2Fplatform%2Fsuperproject%2Fmain + private int getVerticalScrollFactorPre26(@NonNull Context context) { + if (cachedVerticalScrollFactor == 0) { + TypedValue outValue = new TypedValue(); + if (!context + .getTheme() + .resolveAttribute(android.R.attr.listPreferredItemHeight, outValue, true)) { + return DEFAULT_VERTICAL_SCROLL_FACTOR; + } + cachedVerticalScrollFactor = + (int) outValue.getDimension(context.getResources().getDisplayMetrics()); } + return cachedVerticalScrollFactor; } @PointerChange diff --git a/shell/platform/android/io/flutter/embedding/android/FlutterView.java b/shell/platform/android/io/flutter/embedding/android/FlutterView.java index e248f324a872e..5e4f1d44f4d21 100644 --- a/shell/platform/android/io/flutter/embedding/android/FlutterView.java +++ b/shell/platform/android/io/flutter/embedding/android/FlutterView.java @@ -952,7 +952,8 @@ public boolean onTouchEvent(@NonNull MotionEvent event) { @Override public boolean onGenericMotionEvent(@NonNull MotionEvent event) { boolean handled = - isAttachedToFlutterEngine() && androidTouchProcessor.onGenericMotionEvent(event); + isAttachedToFlutterEngine() + && androidTouchProcessor.onGenericMotionEvent(event, getContext()); return handled ? true : super.onGenericMotionEvent(event); } diff --git a/shell/platform/android/io/flutter/view/FlutterView.java b/shell/platform/android/io/flutter/view/FlutterView.java index 7d15aab7ad89d..46d91eefe6420 100644 --- a/shell/platform/android/io/flutter/view/FlutterView.java +++ b/shell/platform/android/io/flutter/view/FlutterView.java @@ -482,7 +482,8 @@ public boolean onHoverEvent(MotionEvent event) { */ @Override public boolean onGenericMotionEvent(MotionEvent event) { - boolean handled = isAttached() && androidTouchProcessor.onGenericMotionEvent(event); + boolean handled = + isAttached() && androidTouchProcessor.onGenericMotionEvent(event, getContext()); return handled ? true : super.onGenericMotionEvent(event); } diff --git a/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java b/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java index 09e53be9b0a07..68e1e7f167ff6 100644 --- a/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java +++ b/shell/platform/android/test/io/flutter/embedding/android/AndroidTouchProcessorTest.java @@ -8,11 +8,16 @@ import static org.mockito.Mockito.when; import android.annotation.TargetApi; +import android.content.Context; +import android.os.Build; import android.view.InputDevice; import android.view.MotionEvent; +import android.view.ViewConfiguration; +import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.renderer.FlutterRenderer; import java.nio.ByteBuffer; +import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,6 +36,12 @@ public class AndroidTouchProcessorTest { AndroidTouchProcessor touchProcessor; @Captor ArgumentCaptor packetCaptor; @Captor ArgumentCaptor packetSizeCaptor; + // Used for mock events in SystemClock.uptimeMillis() time base. + // 2 days in milliseconds + final long eventTimeMilliseconds = 172800000; + final float pressure = 0.8f; + // https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/gestures/events.dart + final int enginePrimaryStylusButton = 0x02; @Before public void setUp() { @@ -38,6 +49,10 @@ public void setUp() { touchProcessor = new AndroidTouchProcessor(mockRenderer, false); } + private long readTimeStamp(ByteBuffer buffer) { + return buffer.getLong(1 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + private long readPointerChange(ByteBuffer buffer) { return buffer.getLong(2 * AndroidTouchProcessor.BYTES_PER_FIELD); } @@ -50,6 +65,10 @@ private long readPointerSignalKind(ByteBuffer buffer) { return buffer.getLong(4 * AndroidTouchProcessor.BYTES_PER_FIELD); } + private long readDevice(ByteBuffer buffer) { + return buffer.getLong(5 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + private double readPointerPhysicalX(ByteBuffer buffer) { return buffer.getDouble(7 * AndroidTouchProcessor.BYTES_PER_FIELD); } @@ -58,6 +77,70 @@ private double readPointerPhysicalY(ByteBuffer buffer) { return buffer.getDouble(8 * AndroidTouchProcessor.BYTES_PER_FIELD); } + private long readButtons(ByteBuffer buffer) { + return buffer.getLong(11 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readObscured(ByteBuffer buffer) { + return buffer.getDouble(12 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readSynthesized(ByteBuffer buffer) { + return buffer.getDouble(13 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPressure(ByteBuffer buffer) { + return buffer.getDouble(14 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPressureMin(ByteBuffer buffer) { + return buffer.getDouble(15 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPressureMax(ByteBuffer buffer) { + return buffer.getDouble(16 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readDistance(ByteBuffer buffer) { + return buffer.getDouble(17 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readDistanceMax(ByteBuffer buffer) { + return buffer.getDouble(18 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readSize(ByteBuffer buffer) { + return buffer.getDouble(19 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMajor(ByteBuffer buffer) { + return buffer.getDouble(20 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMinor(ByteBuffer buffer) { + return buffer.getDouble(21 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMin(ByteBuffer buffer) { + return buffer.getDouble(22 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRadiusMax(ByteBuffer buffer) { + return buffer.getDouble(23 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readStylusTilt(ByteBuffer buffer) { + return buffer.getDouble(25 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readScrollDeltaX(ByteBuffer buffer) { + return buffer.getDouble(27 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readScrollDeltaY(ByteBuffer buffer) { + return buffer.getDouble(28 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + private double readPointerPanX(ByteBuffer buffer) { return buffer.getDouble(29 * AndroidTouchProcessor.BYTES_PER_FIELD); } @@ -66,6 +149,22 @@ private double readPointerPanY(ByteBuffer buffer) { return buffer.getDouble(30 * AndroidTouchProcessor.BYTES_PER_FIELD); } + private double readPointerPanDeltaX(ByteBuffer buffer) { + return buffer.getDouble(31 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readPointerPanDeltaY(ByteBuffer buffer) { + return buffer.getDouble(32 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readScale(ByteBuffer buffer) { + return buffer.getDouble(33 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + + private double readRotation(ByteBuffer buffer) { + return buffer.getDouble(34 * AndroidTouchProcessor.BYTES_PER_FIELD); + } + private class MotionEventMocker { int pointerId; int source; @@ -78,18 +177,43 @@ private class MotionEventMocker { } MotionEvent mockEvent(int action, float x, float y, int buttonState) { + return mockEvent(action, x, y, buttonState, x, y, x, y, x, x, y); + } + + MotionEvent mockEvent( + int action, + float x, + float y, + int buttonState, + float hScroll, + float vScroll, + float axisDistance, + float axisTilt, + float size, + float toolMajor, + float toolMinor) { MotionEvent event = mock(MotionEvent.class); when(event.getDevice()).thenReturn(null); when(event.getSource()).thenReturn(source); + when(event.getEventTime()).thenReturn(eventTimeMilliseconds); when(event.getPointerCount()).thenReturn(1); when(event.getActionMasked()).thenReturn(action); - when(event.getActionIndex()).thenReturn(0); + final int actionIndex = 0; + when(event.getActionIndex()).thenReturn(actionIndex); when(event.getButtonState()).thenReturn(buttonState); - when(event.getPointerId(0)).thenReturn(pointerId); - when(event.getX(0)).thenReturn(x); - when(event.getY(0)).thenReturn(y); - when(event.getToolType(0)).thenReturn(toolType); + when(event.getPointerId(actionIndex)).thenReturn(pointerId); + when(event.getX(actionIndex)).thenReturn(x); + when(event.getY(actionIndex)).thenReturn(y); + when(event.getToolType(actionIndex)).thenReturn(toolType); when(event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)).thenReturn(true); + when(event.getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId)).thenReturn(hScroll); + when(event.getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId)).thenReturn(vScroll); + when(event.getAxisValue(MotionEvent.AXIS_DISTANCE, pointerId)).thenReturn(axisDistance); + when(event.getAxisValue(MotionEvent.AXIS_TILT, pointerId)).thenReturn(axisTilt); + when(event.getPressure(actionIndex)).thenReturn(pressure); + when(event.getSize(actionIndex)).thenReturn(size); + when(event.getToolMajor(actionIndex)).thenReturn(toolMajor); + when(event.getToolMinor(actionIndex)).thenReturn(toolMinor); return event; } } @@ -159,6 +283,12 @@ public void trackpadGesture() { assertEquals(0.0, readPointerPhysicalY(packet)); assertEquals(10.0, readPointerPanX(packet)); assertEquals(5.0, readPointerPanY(packet)); + // Always zero. + assertEquals(0.0, readPointerPanDeltaX(packet)); + assertEquals(0.0, readPointerPanDeltaY(packet)); + assertEquals(0.0, readRotation(packet)); + // Always 1. + assertEquals(1.0, readScale(packet)); touchProcessor.onTouchEvent(mocker.mockEvent(MotionEvent.ACTION_UP, 10.0f, 5.0f, 0)); inOrder .verify(mockRenderer) @@ -220,10 +350,317 @@ public void unexpectedMaskedAction() { verify(mockRenderer, never()).dispatchPointerDataPacket(ByteBuffer.allocate(0), 0); } + @Test + @Config(minSdk = Build.VERSION_CODES.O) + public void scrollWheelAbove26() { + // Pointer id must be zero to match actionIndex in mocked event. + final int pointerId = 0; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final float horizontalScrollValue = -1f; + final float verticalScrollValue = .5f; + final Context context = ApplicationProvider.getApplicationContext(); + final double horizontalScaleFactor = + ViewConfiguration.get(context).getScaledHorizontalScrollFactor(); + final double verticalScaleFactor = + ViewConfiguration.get(context).getScaledVerticalScrollFactor(); + // Zero verticalScaleFactor will cause this test to miss bugs. + assertEquals("zero horizontal scale factor", true, horizontalScaleFactor != 0); + assertEquals("zero vertical scale factor", true, verticalScaleFactor != 0); + + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_SCROLL, + 0.0f, + 0.0f, + 1, + horizontalScrollValue, + verticalScrollValue, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + 0.0f); + boolean handled = touchProcessor.onGenericMotionEvent(event, context); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals(-horizontalScrollValue * horizontalScaleFactor, readScrollDeltaX(packet)); + assertEquals(-verticalScrollValue * verticalScaleFactor, readScrollDeltaY(packet)); + verify(event).getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId); + verify(event).getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + @Config(sdk = {Build.VERSION_CODES.N_MR1}) + public void scrollWheelBelow26() { + // Pointer id must be zero to match actionIndex in mocked event. + final int pointerId = 0; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final float horizontalScrollValue = -1f; + final float verticalScrollValue = .5f; + final Context context = ApplicationProvider.getApplicationContext(); + + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_SCROLL, + 0.0f, + 0.0f, + 1, + horizontalScrollValue, + verticalScrollValue, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + 0.0f); + boolean handled = touchProcessor.onGenericMotionEvent(event, context); + assertEquals(true, handled); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Magic number from roboletric's theme. + final double magicScrollFactor = 64; + assertEquals(-horizontalScrollValue * magicScrollFactor, readScrollDeltaX(packet)); + assertEquals(-verticalScrollValue * magicScrollFactor, readScrollDeltaY(packet)); + verify(event).getAxisValue(MotionEvent.AXIS_HSCROLL, pointerId); + verify(event).getAxisValue(MotionEvent.AXIS_VSCROLL, pointerId); + + // Trigger default values. + touchProcessor.onGenericMotionEvent(event, null); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + packet = packetCaptor.getValue(); + + assertEquals( + (double) -horizontalScrollValue * AndroidTouchProcessor.DEFAULT_HORIZONTAL_SCROLL_FACTOR, + readScrollDeltaX(packet)); + assertEquals( + (double) -verticalScrollValue * AndroidTouchProcessor.DEFAULT_VERTICAL_SCROLL_FACTOR, + readScrollDeltaY(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void timeStamp() { + final int pointerId = 0; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_SCROLL, 1f, 1f, 1); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals(TimeUnit.MILLISECONDS.toMicros(eventTimeMilliseconds), readTimeStamp(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void device() { + final int pointerId = 2; + MotionEventMocker mocker = + new MotionEventMocker( + pointerId, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_SCROLL, 1f, 1f, 1); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals(pointerId, readDevice(packet)); + verify(event).getPointerId(0); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void physicalXPhysicalY() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final float x = 10.0f; + final float y = 20.0f; + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, x, y, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + assertEquals((double) x, readPointerPhysicalX(packet)); + assertEquals((double) y, readPointerPhysicalY(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void obscured() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Always zero. + assertEquals(0.0, readObscured(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void synthesized() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Always zero. + assertEquals(0.0, readSynthesized(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void pressure() { + MotionEventMocker mocker = + new MotionEventMocker(1, InputDevice.SOURCE_CLASS_POINTER, MotionEvent.TOOL_TYPE_MOUSE); + final MotionEvent event = mocker.mockEvent(MotionEvent.ACTION_DOWN, 10.0f, 20.0f, 0); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + // Always zero. + assertEquals((double) pressure, readPressure(packet)); + // Verify default range with null device. + assertEquals(0.0, readPressureMin(packet)); + assertEquals(1.0, readPressureMax(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void stylusDistance() { + MotionEventMocker mocker = + new MotionEventMocker(0, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS); + final float distance = 10.0f; + final float tilt = 20.0f; + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_DOWN, + 0.0f, + 0.0f, + MotionEvent.BUTTON_STYLUS_PRIMARY, + 0.0f, + 0.0f, + distance, + tilt, + 0.0f, + 0.0f, + 0.0f); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + assertEquals(AndroidTouchProcessor.PointerDeviceKind.STYLUS, readPointerDeviceKind(packet)); + assertEquals((double) distance, readDistance(packet)); + // Always zero. + assertEquals(0.0, readDistanceMax(packet)); + assertEquals((double) tilt, readStylusTilt(packet)); + assertEquals(enginePrimaryStylusButton, readButtons(packet)); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void sizeAndRadius() { + MotionEventMocker mocker = + new MotionEventMocker(0, InputDevice.SOURCE_STYLUS, MotionEvent.TOOL_TYPE_STYLUS); + final float size = 10.0f; + final float radiusMajor = 20.0f; + final float radiusMinor = 30.0f; + final MotionEvent event = + mocker.mockEvent( + MotionEvent.ACTION_DOWN, + 0.0f, + 0.0f, + 0, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + size, + radiusMajor, + radiusMinor); + boolean handled = touchProcessor.onTouchEvent(event); + + InOrder inOrder = inOrder(mockRenderer); + inOrder + .verify(mockRenderer) + .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); + ByteBuffer packet = packetCaptor.getValue(); + + verify(event).getSize(0); + verify(event).getToolMajor(0); + verify(event).getToolMinor(0); + + assertEquals((double) size, readSize(packet)); + assertEquals((double) radiusMajor, readRadiusMajor(packet)); + assertEquals((double) radiusMinor, readRadiusMinor(packet)); + // Always zero. + assertEquals(0.0, readRadiusMin(packet)); + assertEquals(0.0, readRadiusMax(packet)); + + inOrder.verifyNoMoreInteractions(); + } + @Test public void unexpectedPointerChange() { // Regression test for https://github.com/flutter/flutter/issues/129765 - MotionEventMocker mocker = new MotionEventMocker(0, InputDevice.SOURCE_MOUSE, MotionEvent.TOOL_TYPE_MOUSE); @@ -252,7 +689,9 @@ public void unexpectedPointerChange() { assertEquals(10.0, readPointerPanX(packet)); assertEquals(5.0, readPointerPanY(packet)); - touchProcessor.onGenericMotionEvent(mocker.mockEvent(MotionEvent.ACTION_SCROLL, 0.0f, 0.0f, 0)); + touchProcessor.onGenericMotionEvent( + mocker.mockEvent(MotionEvent.ACTION_SCROLL, 0.0f, 0.0f, 0), + ApplicationProvider.getApplicationContext()); inOrder .verify(mockRenderer) .dispatchPointerDataPacket(packetCaptor.capture(), packetSizeCaptor.capture()); diff --git a/shell/platform/embedder/embedder_external_view.cc b/shell/platform/embedder/embedder_external_view.cc index 4261366efa235..4075b3875cf7f 100644 --- a/shell/platform/embedder/embedder_external_view.cc +++ b/shell/platform/embedder/embedder_external_view.cc @@ -4,7 +4,7 @@ #include "flutter/shell/platform/embedder/embedder_external_view.h" -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/common/dl_op_spy.h" diff --git a/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc b/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc index aa8e47bd22764..e020291ff6faa 100644 --- a/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc +++ b/shell/platform/embedder/tests/embedder_test_backingstore_producer.cc @@ -15,6 +15,7 @@ #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" +#include "third_party/skia/include/gpu/vk/GrVkTypes.h" #include #include diff --git a/shell/platform/linux/BUILD.gn b/shell/platform/linux/BUILD.gn index 4af1f89fe6bd3..eeff5e2585838 100644 --- a/shell/platform/linux/BUILD.gn +++ b/shell/platform/linux/BUILD.gn @@ -158,6 +158,7 @@ source_set("flutter_linux_sources") { ] deps = [ + "//flutter/fml", "//flutter/shell/platform/common:common_cpp_enums", "//flutter/shell/platform/common:common_cpp_input", "//flutter/shell/platform/common:common_cpp_switches", diff --git a/shell/platform/linux/fl_binary_messenger.cc b/shell/platform/linux/fl_binary_messenger.cc index 7793e9df0040a..892c477f65108 100644 --- a/shell/platform/linux/fl_binary_messenger.cc +++ b/shell/platform/linux/fl_binary_messenger.cc @@ -5,11 +5,20 @@ #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" +#include "flutter/fml/logging.h" #include "flutter/shell/platform/linux/fl_engine_private.h" +#include "flutter/shell/platform/linux/fl_method_codec_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" #include +static constexpr char kControlChannelName[] = "dev.flutter/channel-buffers"; +static constexpr char kResizeMethod[] = "resize"; +static constexpr char kOverflowMethod[] = "overflow"; + G_DEFINE_QUARK(fl_binary_messenger_codec_error_quark, fl_binary_messenger_codec_error) @@ -311,6 +320,67 @@ static GBytes* send_on_channel_finish(FlBinaryMessenger* messenger, return fl_engine_send_platform_message_finish(engine, r, error); } +// Completes method call and returns TRUE if the call was successful. +static gboolean finish_method(GObject* object, + GAsyncResult* result, + GError** error) { + g_autoptr(FlMethodResponse) response = fl_method_channel_invoke_method_finish( + FL_METHOD_CHANNEL(object), result, error); + if (response == nullptr) { + return FALSE; + } + return fl_method_response_get_result(response, error) != nullptr; +} + +// Called when a response is received for the resize channel message. +static void resize_channel_response_cb(GObject* object, + GAsyncResult* result, + gpointer user_data) { + g_autoptr(GError) error = nullptr; + if (!finish_method(object, result, &error)) { + g_warning("Failed to resize channel: %s", error->message); + } +} + +static void resize_channel(FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size) { + FML_DCHECK(new_size >= 0); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + g_autoptr(FlValue) args = fl_value_new_list(); + fl_value_append_take(args, fl_value_new_string(channel)); + fl_value_append_take(args, fl_value_new_int(new_size)); + g_autoptr(GBytes) message = fl_method_codec_encode_method_call( + FL_METHOD_CODEC(codec), kResizeMethod, args, nullptr); + fl_binary_messenger_send_on_channel(messenger, kControlChannelName, message, + nullptr, resize_channel_response_cb, + nullptr); +} + +// Called when a response is received for the allow channel overflow message. +static void set_allow_channel_overflowl_response_cb(GObject* object, + GAsyncResult* result, + gpointer user_data) { + g_autoptr(GError) error = nullptr; + if (!finish_method(object, result, &error)) { + g_warning("Failed to set allow channel overflow: %s", error->message); + } +} + +static void set_allow_channel_overflow(FlBinaryMessenger* messenger, + const gchar* channel, + bool allowed) { + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + g_autoptr(FlValue) args = fl_value_new_list(); + fl_value_append_take(args, fl_value_new_string(channel)); + fl_value_append_take(args, fl_value_new_bool(allowed)); + g_autoptr(GBytes) message = fl_method_codec_encode_method_call( + FL_METHOD_CODEC(codec), kOverflowMethod, args, nullptr); + fl_binary_messenger_send_on_channel( + messenger, kControlChannelName, message, nullptr, + set_allow_channel_overflowl_response_cb, nullptr); +} + static void fl_binary_messenger_impl_class_init( FlBinaryMessengerImplClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_binary_messenger_impl_dispose; @@ -322,6 +392,8 @@ static void fl_binary_messenger_impl_iface_init( iface->send_response = send_response; iface->send_on_channel = send_on_channel; iface->send_on_channel_finish = send_on_channel_finish; + iface->resize_channel = resize_channel; + iface->set_allow_channel_overflow = set_allow_channel_overflow; } static void fl_binary_messenger_impl_init(FlBinaryMessengerImpl* self) { @@ -397,3 +469,22 @@ G_MODULE_EXPORT GBytes* fl_binary_messenger_send_on_channel_finish( return FL_BINARY_MESSENGER_GET_IFACE(self)->send_on_channel_finish( self, result, error); } + +G_MODULE_EXPORT void fl_binary_messenger_resize_channel(FlBinaryMessenger* self, + const gchar* channel, + int64_t new_size) { + g_return_if_fail(FL_IS_BINARY_MESSENGER(self)); + + return FL_BINARY_MESSENGER_GET_IFACE(self)->resize_channel(self, channel, + new_size); +} + +G_MODULE_EXPORT void fl_binary_messenger_set_allow_channel_overflow( + FlBinaryMessenger* self, + const gchar* channel, + bool allowed) { + g_return_if_fail(FL_IS_BINARY_MESSENGER(self)); + + return FL_BINARY_MESSENGER_GET_IFACE(self)->set_allow_channel_overflow( + self, channel, allowed); +} diff --git a/shell/platform/linux/fl_binary_messenger_test.cc b/shell/platform/linux/fl_binary_messenger_test.cc index a95ed318ae6fc..3f445e9d9f9df 100644 --- a/shell/platform/linux/fl_binary_messenger_test.cc +++ b/shell/platform/linux/fl_binary_messenger_test.cc @@ -8,9 +8,13 @@ #include #include +#include "flutter/shell/platform/embedder/embedder.h" +#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" +#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_binary_messenger_response_handle.h" #include "flutter/shell/platform/linux/testing/mock_renderer.h" @@ -126,12 +130,26 @@ static GBytes* send_on_channel_finish(FlBinaryMessenger* messenger, return g_bytes_new(text, strlen(text)); } +static void resize_channel(FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size) { + // Fake implementation. Do nothing. +} + +static void set_allow_channel_overflow(FlBinaryMessenger* messenger, + const gchar* channel, + bool allowed) { + // Fake implementation. Do nothing. +} + static void fl_fake_binary_messenger_iface_init( FlBinaryMessengerInterface* iface) { iface->set_message_handler_on_channel = set_message_handler_on_channel; iface->send_response = send_response; iface->send_on_channel = send_on_channel; iface->send_on_channel_finish = send_on_channel_finish; + iface->resize_channel = resize_channel; + iface->set_allow_channel_overflow = set_allow_channel_overflow; } static void fl_fake_binary_messenger_init(FlFakeBinaryMessenger* self) {} @@ -386,6 +404,105 @@ TEST(FlBinaryMessengerTest, ReceiveMessage) { g_main_loop_run(loop); } +// MOCK_ENGINE_PROC is leaky by design. +// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) + +// Checks if the 'resize' command is sent and is well-formed. +TEST(FlBinaryMessengerTest, ResizeChannel) { + g_autoptr(FlEngine) engine = make_mock_engine(); + FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); + + bool called = false; + + FlutterEngineSendPlatformMessageFnPtr old_handler = + embedder_api->SendPlatformMessage; + embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC( + SendPlatformMessage, + ([&called, old_handler](auto engine, + const FlutterPlatformMessage* message) { + // Expect to receive a message on the "control" channel. + if (strcmp(message->channel, "dev.flutter/channel-buffers") != 0) { + return old_handler(engine, message); + } + + called = true; + + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('resize', ['flutter/test',3]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const int expected_message_size = 29; + EXPECT_EQ(message->message_size, + static_cast(expected_message_size)); + int expected[expected_message_size] = { + 7, 6, 114, 101, 115, 105, 122, 101, 12, 2, + 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, + 116, 101, 115, 116, 3, 3, 0, 0, 0}; + for (size_t i = 0; i < expected_message_size; i++) { + EXPECT_EQ(message->message[i], expected[i]); + } + + return kSuccess; + })); + + g_autoptr(GError) error = nullptr; + EXPECT_TRUE(fl_engine_start(engine, &error)); + EXPECT_EQ(error, nullptr); + + FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); + fl_binary_messenger_resize_channel(messenger, "flutter/test", 3); + + EXPECT_TRUE(called); +} + +// Checks if the 'overflow' command is sent and is well-formed. +TEST(FlBinaryMessengerTest, AllowOverflowChannel) { + g_autoptr(FlEngine) engine = make_mock_engine(); + FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); + + bool called = false; + + FlutterEngineSendPlatformMessageFnPtr old_handler = + embedder_api->SendPlatformMessage; + embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC( + SendPlatformMessage, + ([&called, old_handler](auto engine, + const FlutterPlatformMessage* message) { + // Expect to receive a message on the "control" channel. + if (strcmp(message->channel, "dev.flutter/channel-buffers") != 0) { + return old_handler(engine, message); + } + + called = true; + + // The expected content was created from the following Dart code: + // MethodCall call = MethodCall('overflow',['flutter/test', true]); + // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); + const int expected_message_size = 27; + EXPECT_EQ(message->message_size, + static_cast(expected_message_size)); + int expected[expected_message_size] = { + 7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, + 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1}; + for (size_t i = 0; i < expected_message_size; i++) { + EXPECT_EQ(message->message[i], expected[i]); + } + + return kSuccess; + })); + + g_autoptr(GError) error = nullptr; + EXPECT_TRUE(fl_engine_start(engine, &error)); + EXPECT_EQ(error, nullptr); + + FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); + fl_binary_messenger_set_allow_channel_overflow(messenger, "flutter/test", + true); + + EXPECT_TRUE(called); +} + +// NOLINTEND(clang-analyzer-core.StackAddressEscape) + struct RespondsOnBackgroundThreadInfo { FlBinaryMessenger* messenger; FlBinaryMessengerResponseHandle* response_handle; diff --git a/shell/platform/linux/fl_keyboard_manager_test.cc b/shell/platform/linux/fl_keyboard_manager_test.cc index de45994e94850..89beae62e8ca6 100644 --- a/shell/platform/linux/fl_keyboard_manager_test.cc +++ b/shell/platform/linux/fl_keyboard_manager_test.cc @@ -215,6 +215,20 @@ static GBytes* fl_mock_key_binary_messenger_send_on_channel_finish( return static_cast(g_task_propagate_pointer(G_TASK(result), error)); } +static void fl_mock_binary_messenger_resize_channel( + FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size) { + // Mock implementation. Do nothing. +} + +static void fl_mock_binary_messenger_set_allow_channel_overflow( + FlBinaryMessenger* messenger, + const gchar* channel, + bool allowed) { + // Mock implementation. Do nothing. +} + static void fl_mock_key_binary_messenger_iface_init( FlBinaryMessengerInterface* iface) { iface->set_message_handler_on_channel = @@ -236,6 +250,9 @@ static void fl_mock_key_binary_messenger_iface_init( iface->send_on_channel = fl_mock_key_binary_messenger_send_on_channel; iface->send_on_channel_finish = fl_mock_key_binary_messenger_send_on_channel_finish; + iface->resize_channel = fl_mock_binary_messenger_resize_channel; + iface->set_allow_channel_overflow = + fl_mock_binary_messenger_set_allow_channel_overflow; } static void fl_mock_key_binary_messenger_init(FlMockKeyBinaryMessenger* self) {} diff --git a/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h b/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h index f98bca70088b1..e9f202d0db5f7 100644 --- a/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h +++ b/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h @@ -9,6 +9,8 @@ #error "Only can be included directly." #endif +#include "fl_value.h" + #include #include #include @@ -91,6 +93,14 @@ struct _FlBinaryMessengerInterface { GBytes* (*send_on_channel_finish)(FlBinaryMessenger* messenger, GAsyncResult* result, GError** error); + + void (*resize_channel)(FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size); + + void (*set_allow_channel_overflow)(FlBinaryMessenger* messenger, + const gchar* channel, + bool allowed); }; struct _FlBinaryMessengerResponseHandleClass { @@ -174,7 +184,7 @@ void fl_binary_messenger_send_on_channel(FlBinaryMessenger* messenger, /** * fl_binary_messenger_send_on_channel_finish: - * @binary_messenger: an #FlBinaryMessenger. + * @messenger: an #FlBinaryMessenger. * @result: a #GAsyncResult. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. @@ -187,6 +197,33 @@ GBytes* fl_binary_messenger_send_on_channel_finish(FlBinaryMessenger* messenger, GAsyncResult* result, GError** error); +/** + * fl_binary_messenger_resize_channel: + * @binary_messenger: an #FlBinaryMessenger. + * @channel: channel to be resize. + * @new_size: the new size for the channel buffer. + * + * Sends a message to the control channel asking to resize a channel buffer. + */ +void fl_binary_messenger_resize_channel(FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size); + +/** + * fl_binary_messenger_set_allow_channel_overflow: + * @messenger: an #FlBinaryMessenger. + * @channel: channel to be allowed to overflow silently. + * @allowed: when true the channel is expected to overflow and warning messages + * will not be shown. + * + * Sends a message to the control channel asking to allow or disallow a channel + * to overflow silently. + */ +void fl_binary_messenger_set_allow_channel_overflow( + FlBinaryMessenger* messenger, + const gchar* channel, + bool allowed); + G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_BINARY_MESSENGER_H_ diff --git a/shell/platform/linux/testing/mock_binary_messenger.cc b/shell/platform/linux/testing/mock_binary_messenger.cc index cc9b54f696dce..b836a49cc6e98 100644 --- a/shell/platform/linux/testing/mock_binary_messenger.cc +++ b/shell/platform/linux/testing/mock_binary_messenger.cc @@ -122,6 +122,25 @@ static GBytes* fl_mock_binary_messenger_send_on_channel_finish( result, error); } +static void fl_mock_binary_messenger_resize_channel( + FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger)); + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); + self->mock->fl_binary_messenger_resize_channel(messenger, channel, new_size); +} + +static void fl_mock_binary_messenger_set_allow_channel_overflow( + FlBinaryMessenger* messenger, + const gchar* channel, + bool allowed) { + g_return_if_fail(FL_IS_MOCK_BINARY_MESSENGER(messenger)); + FlMockBinaryMessenger* self = FL_MOCK_BINARY_MESSENGER(messenger); + self->mock->fl_binary_messenger_set_allow_channel_overflow(messenger, channel, + allowed); +} + static void fl_mock_binary_messenger_iface_init( FlBinaryMessengerInterface* iface) { iface->set_message_handler_on_channel = @@ -130,6 +149,9 @@ static void fl_mock_binary_messenger_iface_init( iface->send_on_channel = fl_mock_binary_messenger_send_on_channel; iface->send_on_channel_finish = fl_mock_binary_messenger_send_on_channel_finish; + iface->resize_channel = fl_mock_binary_messenger_resize_channel; + iface->set_allow_channel_overflow = + fl_mock_binary_messenger_set_allow_channel_overflow; } static void fl_mock_binary_messenger_init(FlMockBinaryMessenger* self) {} diff --git a/shell/platform/linux/testing/mock_binary_messenger.h b/shell/platform/linux/testing/mock_binary_messenger.h index 50385279efdec..f48a8999a4e4d 100644 --- a/shell/platform/linux/testing/mock_binary_messenger.h +++ b/shell/platform/linux/testing/mock_binary_messenger.h @@ -48,6 +48,16 @@ class MockBinaryMessenger { GAsyncResult* result, GError** error)); + MOCK_METHOD3(fl_binary_messenger_resize_channel, + void(FlBinaryMessenger* messenger, + const gchar* channel, + int64_t new_size)); + + MOCK_METHOD3(fl_binary_messenger_set_allow_channel_overflow, + void(FlBinaryMessenger* messenger, + const gchar* channel, + bool allowed)); + bool HasMessageHandler(const gchar* channel) const; void SetMessageHandler(const gchar* channel, diff --git a/testing/display_list_testing.cc b/testing/display_list_testing.cc index 7b6102306355d..f54a90c192d19 100644 --- a/testing/display_list_testing.cc +++ b/testing/display_list_testing.cc @@ -791,7 +791,7 @@ void DisplayListStreamDispatcher::drawVertices(const DlVertices* vertices, out_array("indices", vertices->index_count(), vertices->indices()) << "), " << mode << ");" << std::endl; } -void DisplayListStreamDispatcher::drawImage(const sk_sp& image, +void DisplayListStreamDispatcher::drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { @@ -801,7 +801,7 @@ void DisplayListStreamDispatcher::drawImage(const sk_sp& image, << "with attributes: " << render_with_attributes << ");" << std::endl; } -void DisplayListStreamDispatcher::drawImageRect(const sk_sp& image, +void DisplayListStreamDispatcher::drawImageRect(const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, @@ -815,7 +815,7 @@ void DisplayListStreamDispatcher::drawImageRect(const sk_sp& image, << constraint << ");" << std::endl; } -void DisplayListStreamDispatcher::drawImageNine(const sk_sp& image, +void DisplayListStreamDispatcher::drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, @@ -827,7 +827,7 @@ void DisplayListStreamDispatcher::drawImageNine(const sk_sp& image, << "with attributes: " << render_with_attributes << ");" << std::endl; } -void DisplayListStreamDispatcher::drawAtlas(const sk_sp& atlas, +void DisplayListStreamDispatcher::drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -845,14 +845,14 @@ void DisplayListStreamDispatcher::drawAtlas(const sk_sp& atlas, << ");" << std::endl; } void DisplayListStreamDispatcher::drawDisplayList( - const sk_sp& display_list, SkScalar opacity) { + const sk_sp display_list, SkScalar opacity) { startl() << "drawDisplayList(" << "ID: " << display_list->unique_id() << ", " << "bounds: " << display_list->bounds() << ", " << "opacity: " << opacity << ");" << std::endl; } -void DisplayListStreamDispatcher::drawTextBlob(const sk_sp& blob, +void DisplayListStreamDispatcher::drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) { startl() << "drawTextBlob(" diff --git a/testing/display_list_testing.h b/testing/display_list_testing.h index 3fde199fa271e..4f3830a204b44 100644 --- a/testing/display_list_testing.h +++ b/testing/display_list_testing.h @@ -115,22 +115,22 @@ class DisplayListStreamDispatcher final : public DlOpReceiver { uint32_t count, const SkPoint points[]) override; void drawVertices(const DlVertices* vertices, DlBlendMode mode) override; - void drawImage(const sk_sp& image, + void drawImage(const sk_sp image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) override; - void drawImageRect(const sk_sp& image, + void drawImageRect(const sk_sp image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint) override; - void drawImageNine(const sk_sp& image, + void drawImageNine(const sk_sp image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) override; - void drawAtlas(const sk_sp& atlas, + void drawAtlas(const sk_sp atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], @@ -139,9 +139,9 @@ class DisplayListStreamDispatcher final : public DlOpReceiver { DlImageSampling sampling, const SkRect* cull_rect, bool render_with_attributes) override; - void drawDisplayList(const sk_sp& display_list, + void drawDisplayList(const sk_sp display_list, SkScalar opacity) override; - void drawTextBlob(const sk_sp& blob, + void drawTextBlob(const sk_sp blob, SkScalar x, SkScalar y) override; void drawShadow(const SkPath& path, diff --git a/testing/mock_canvas.h b/testing/mock_canvas.h index 4f27ddb75b483..71260d5b8755f 100644 --- a/testing/mock_canvas.h +++ b/testing/mock_canvas.h @@ -27,7 +27,7 @@ namespace flutter { namespace testing { -[[maybe_unused]] static constexpr SkRect kEmptyRect = SkRect::MakeEmpty(); +static constexpr SkRect kEmptyRect = SkRect::MakeEmpty(); // Mock |SkCanvas|, useful for writing tests that use Skia but do not interact // with the GPU. diff --git a/third_party/txt/src/txt/paragraph.h b/third_party/txt/src/txt/paragraph.h index 2bc726c9a6e19..2d736fb3935c5 100644 --- a/third_party/txt/src/txt/paragraph.h +++ b/third_party/txt/src/txt/paragraph.h @@ -18,7 +18,7 @@ #ifndef LIB_TXT_SRC_PARAGRAPH_H_ #define LIB_TXT_SRC_PARAGRAPH_H_ -#include "flutter/display_list/display_list_builder.h" +#include "flutter/display_list/dl_builder.h" #include "line_metrics.h" #include "paragraph_style.h" #include "third_party/skia/include/core/SkRect.h" diff --git a/tools/gn b/tools/gn index 4ddaf65919e24..649a0da30002f 100755 --- a/tools/gn +++ b/tools/gn @@ -299,6 +299,17 @@ def to_gn_args(args): gn_args['full_dart_sdk'] = args.full_dart_sdk if args.enable_unittests: + # Ensure that Android and iOS are *not* used with --enable-unittests. + # https://github.com/flutter/flutter/issues/132611 + if args.target_os == 'android' or args.target_os == 'ios': + raise Exception( + 'Cannot use --enable-unittests with --target-os=android or ios. If ' + + 'you are trying to create an output directory to use for clangd ' + + '(i.e. for VSCode integration), use a host build instead.\n\n' + + 'See https://github.com/flutter/flutter/wiki/' + + 'Setting-up-the-Engine-development-environment' + + '#vscode-with-cc-intellisense-cc' + ) gn_args['enable_unittests'] = True if args.no_enable_unittests: gn_args['enable_unittests'] = False diff --git a/tools/gn_test.py b/tools/gn_test.py index a399d7e779c8d..9e623e1e86b3e 100644 --- a/tools/gn_test.py +++ b/tools/gn_test.py @@ -35,6 +35,14 @@ def test_to_gn_args(self): ) self.assertEquals(self._gn_args(['--ios'])['target_cpu'], 'arm') + def test_cannot_use_android_and_enable_unittests(self): + with self.assertRaises(SystemExit): + self._gn_args(['--android', '--enable-unittests']) + + def test_cannot_use_ios_and_enable_unittests(self): + with self.assertRaises(SystemExit): + self._gn_args(['--ios', '--enable-unittests']) + if __name__ == '__main__': unittest.main()