diff --git a/flutter/engine/src/flutter/common/BUILD.gn b/flutter/engine/src/flutter/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5eecc637f9ba72d36cde684c1664a011ee1184ba --- /dev/null +++ b/flutter/engine/src/flutter/common/BUILD.gn @@ -0,0 +1,26 @@ +# 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("config.gni") + +config("flutter_config") { + defines = feature_defines_list +} + +source_set("common") { + sources = [ + "macros.h", + "settings.cc", + "settings.h", + "task_runners.cc", + "task_runners.h", + ] + + deps = [ "//flutter/fml" ] + + public_configs = [ + ":flutter_config", + "//flutter:config", + ] +} diff --git a/flutter/engine/src/flutter/common/README.md b/flutter/engine/src/flutter/common/README.md new file mode 100644 index 0000000000000000000000000000000000000000..63d2f9231688defe0bdab298b7e99383716857a8 --- /dev/null +++ b/flutter/engine/src/flutter/common/README.md @@ -0,0 +1,5 @@ +Flutter Common +============== + +The bottom of the dependency graph for Flutter. Useful for static constants. +Please don't put too much in here. diff --git a/flutter/engine/src/flutter/common/config.gni b/flutter/engine/src/flutter/common/config.gni new file mode 100644 index 0000000000000000000000000000000000000000..318d305bd37fcc9a50f2510f9fd769b9d97c3b74 --- /dev/null +++ b/flutter/engine/src/flutter/common/config.gni @@ -0,0 +1,162 @@ +# 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. + +if (is_android) { + import("//build/config/android/config.gni") +} + +if (target_cpu == "arm" || target_cpu == "arm64") { + import("//build/config/arm.gni") +} + +declare_args() { + # The runtime mode ("debug", "profile", "release", or "jit_release") + flutter_runtime_mode = "debug" + + # Whether to use a prebuilt Dart SDK instead of building one. + flutter_prebuilt_dart_sdk = false + + # Whether to build host-side development artifacts. + flutter_build_engine_artifacts = true + + # Whether to include backtrace support. + enable_backtrace = true + + # Whether binary size optimizations with the assumption that Impeller is the + # only supported rendering engine are enabled. + # + # See [go/slimpeller-dashboard](https://github.com/orgs/flutter/projects/21) + # for details. + slimpeller = false +} + +# feature_defines_list --------------------------------------------------------- + +feature_defines_list = [ + "FLUTTER_RUNTIME_MODE_DEBUG=1", + "FLUTTER_RUNTIME_MODE_PROFILE=2", + "FLUTTER_RUNTIME_MODE_RELEASE=3", + "FLUTTER_RUNTIME_MODE_JIT_RELEASE=4", + "DART_LEGACY_API=[[deprecated]]", +] + +if (flutter_runtime_mode == "debug") { + feature_defines_list += [ + "FLUTTER_RUNTIME_MODE=1", + "FLUTTER_JIT_RUNTIME=1", + ] +} else if (flutter_runtime_mode == "profile") { + feature_defines_list += [ "FLUTTER_RUNTIME_MODE=2" ] +} else if (flutter_runtime_mode == "release") { + feature_defines_list += [ + "FLUTTER_RUNTIME_MODE=3", + "FLUTTER_RELEASE=1", + ] +} else if (flutter_runtime_mode == "jit_release") { + feature_defines_list += [ + "FLUTTER_RUNTIME_MODE=4", + "FLUTTER_RELEASE=1", + "FLUTTER_JIT_RUNTIME=1", + ] +} else { + feature_defines_list += [ "FLUTTER_RUNTIME_MODE=0" ] +} + +if (slimpeller) { + feature_defines_list += [ "SLIMPELLER=1" ] +} + +if (is_ios || is_mac) { + flutter_cflags_objc = [ + "-Werror=overriding-method-mismatch", + "-Werror=undeclared-selector", + "-fobjc-arc", + ] + if (is_mac) { + flutter_cflags_objc += [ "-fapplication-extension" ] + } + + flutter_cflags_objcc = flutter_cflags_objc +} + +# A combo of host os name and cpu is used in several locations to +# generate the names of the archived artifacts. +platform_name = host_os +if (platform_name == "mac") { + platform_name = "darwin" +} else if (platform_name == "win") { + platform_name = "windows" +} + +full_platform_name = "$platform_name-$host_cpu" + +target_platform_name = target_os +if (target_platform_name == "mac") { + platform_target_name = "darwin" +} else if (target_platform_name == "win") { + target_platform_name = "windows" +} + +full_target_platform_name = "$target_platform_name-$target_cpu" + +# Prebuilt Dart SDK location +_target_os_name = target_os +if (_target_os_name == "mac") { + _target_os_name = "macos" +} else if (_target_os_name == "win") { + _target_os_name = "windows" +} + +_host_os_name = host_os +if (_host_os_name == "mac") { + _host_os_name = "macos" +} else if (_host_os_name == "win") { + _host_os_name = "windows" +} + +# When building 32-bit Android development artifacts for Windows host (like +# gen_snapshot), the host_cpu is set to x86. However, the correct prebuilt +# Dart SDK to use during this build is still the 64-bit one. +_host_cpu = host_cpu +if (host_os == "win" && host_cpu == "x86") { + _host_cpu = "x64" +} + +_target_prebuilt_config = "$_target_os_name-$target_cpu" +_host_prebuilt_config = "$_host_os_name-$_host_cpu" + +target_prebuilts_path = "//flutter/prebuilts/$_target_prebuilt_config" +host_prebuilts_path = "//flutter/prebuilts/$_host_prebuilt_config" + +if (flutter_prebuilt_dart_sdk) { + target_prebuilt_dart_sdk = "$target_prebuilts_path/dart-sdk" + host_prebuilt_dart_sdk = "$host_prebuilts_path/dart-sdk" + + # There is no prebuilt Dart SDK targeting Fuchsia, iOS, and Android, but we + # also don't need one, so even when the build is targeting one of these + # platforms, we use the prebuilt Dart SDK for the host. + if (current_toolchain == host_toolchain || target_os == "android" || + target_os == "fuchsia" || target_os == "ios" || target_os == "wasm") { + prebuilt_dart_sdk = host_prebuilt_dart_sdk + prebuilt_dart_sdk_config = _host_prebuilt_config + } else { + prebuilt_dart_sdk = target_prebuilt_dart_sdk + prebuilt_dart_sdk_config = _target_prebuilt_config + } +} + +# Flutter SDK artifacts should only be built when either doing host builds, or +# for cross-compiled desktop targets. +# +# !is_android is necessary because of the way that Android 32-bit arm +# gen_snapshot is built on Windows using the host toolchain, since we have no +# 32-bit arm toolchain for Windows. See comments in //flutter/tools/gn for +# details. +# +# TODO: We can't build the engine artifacts for arm (32-bit) right now; +# see https://github.com/flutter/flutter/issues/74322. +build_engine_artifacts = + flutter_build_engine_artifacts && !is_android && + (current_toolchain == host_toolchain || + (is_linux && !is_chromeos && current_cpu != "arm") || is_mac || is_win) diff --git a/flutter/engine/src/flutter/common/constants.h b/flutter/engine/src/flutter/common/constants.h new file mode 100644 index 0000000000000000000000000000000000000000..668aa4f64ebd207432946adb50d451204f8a235a --- /dev/null +++ b/flutter/engine/src/flutter/common/constants.h @@ -0,0 +1,38 @@ +// 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_COMMON_CONSTANTS_H_ +#define FLUTTER_COMMON_CONSTANTS_H_ + +namespace flutter { +constexpr double kMegaByteSizeInBytes = (1 << 20); + +// The ID for the implicit view if the implicit view is enabled. +// +// The implicit view is a compatibility mechanism to help the transition from +// the older single-view APIs to the newer multi-view APIs. The two sets of APIs +// use different models for view management. The implicit view mechanism allows +// single-view APIs to operate a special view as if other views don't exist. +// +// In the regular multi-view model, all views should be created by +// `Shell::AddView` before being used, and removed by `Shell::RemoveView` to +// signify that they are gone. If a view is added or removed, the framework +// (`PlatformDispatcher`) will be notified. New view IDs are always unique, +// never reused. Operating a non-existing view is an error. +// +// The implicit view is another special view in addition to the "regular views" +// as above. The shell starts up having the implicit view, which has a fixed +// view ID of `kFlutterImplicitViewId` and is available throughout the lifetime +// of the shell. `Shell::AddView` or `RemoveView` must not be called for this +// view. Even when the window that shows the view is closed, the framework is +// unaware and might continue rendering into or operating this view. +// +// The single-view APIs, which are APIs that do not specify view IDs, operate +// the implicit view. The multi-view APIs can operate all views, including the +// implicit view if the target ID is `kFlutterImplicitViewId`, unless specified +// otherwise. +constexpr int64_t kFlutterImplicitViewId = 0; +} // namespace flutter + +#endif // FLUTTER_COMMON_CONSTANTS_H_ diff --git a/flutter/engine/src/flutter/common/exported_symbols.sym b/flutter/engine/src/flutter/common/exported_symbols.sym new file mode 100644 index 0000000000000000000000000000000000000000..c9ad42cd3350ed76ced86a22e902803dfac14163 --- /dev/null +++ b/flutter/engine/src/flutter/common/exported_symbols.sym @@ -0,0 +1,10 @@ +# These symbols are looked up from within the executable at runtime and must +# be exported in the dynamic symbol table. +{ + kDartVmSnapshotData; + kDartVmSnapshotInstructions; + kDartIsolateSnapshotData; + kDartIsolateSnapshotInstructions; + InternalFlutterGpu*; + kInternalFlutterGpu*; +}; diff --git a/flutter/engine/src/flutter/common/exported_symbols_mac.sym b/flutter/engine/src/flutter/common/exported_symbols_mac.sym new file mode 100644 index 0000000000000000000000000000000000000000..09687a75427f50975962bd2e80103bb4d821c23b --- /dev/null +++ b/flutter/engine/src/flutter/common/exported_symbols_mac.sym @@ -0,0 +1,8 @@ +# These symbols are looked up from within the executable at runtime and must +# be exported in the dynamic symbol table. +_kDartVmSnapshotData +_kDartVmSnapshotInstructions +_kDartIsolateSnapshotData +_kDartIsolateSnapshotInstructions +_InternalFlutterGpu* +_kInternalFlutterGpu* diff --git a/flutter/engine/src/flutter/common/exported_test_symbols.sym b/flutter/engine/src/flutter/common/exported_test_symbols.sym new file mode 100644 index 0000000000000000000000000000000000000000..12da485f23a4a1504d407bd24e8957507a6007ad --- /dev/null +++ b/flutter/engine/src/flutter/common/exported_test_symbols.sym @@ -0,0 +1,14 @@ +# These symbols are looked up from within the executable at runtime and must +# be exported in the dynamic symbol table. +{ + kDartVmSnapshotData; + kDartVmSnapshotInstructions; + kDartIsolateSnapshotData; + kDartIsolateSnapshotInstructions; + InternalFlutterGpu*; + kInternalFlutterGpu*; + Spawn; + LoadLibraryFromKernel; + LookupEntryPoint; + ForceShutdownIsolate; +}; diff --git a/flutter/engine/src/flutter/common/exported_test_symbols_mac.sym b/flutter/engine/src/flutter/common/exported_test_symbols_mac.sym new file mode 100644 index 0000000000000000000000000000000000000000..83992eeeb9d8917e4827a57a3a418cdc03ee28b7 --- /dev/null +++ b/flutter/engine/src/flutter/common/exported_test_symbols_mac.sym @@ -0,0 +1,12 @@ +# These symbols are looked up from within the executable at runtime and must +# be exported in the dynamic symbol table. +_kDartVmSnapshotData +_kDartVmSnapshotInstructions +_kDartIsolateSnapshotData +_kDartIsolateSnapshotInstructions +_InternalFlutterGpu* +_kInternalFlutterGpu* +_Spawn +_LoadLibraryFromKernel +_LookupEntryPoint +_ForceShutdownIsolate diff --git a/flutter/engine/src/flutter/common/fuchsia_config.gni b/flutter/engine/src/flutter/common/fuchsia_config.gni new file mode 100644 index 0000000000000000000000000000000000000000..96e120fba29d73211b5dddb666cd612a0f833f8e --- /dev/null +++ b/flutter/engine/src/flutter/common/fuchsia_config.gni @@ -0,0 +1,12 @@ +# 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("config.gni") + +if (is_fuchsia) { + dart_tools_root = "//flutter/tools/fuchsia/dart" + fuchsia_base = "//flutter/shell/platform/fuchsia" + flutter_runner_base = "$fuchsia_base/flutter/" + dart_runner_base = "$fuchsia_base/dart_runner/" +} diff --git a/flutter/engine/src/flutter/common/macros.h b/flutter/engine/src/flutter/common/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..162e2652a2e89dc6590b3d48558df7254d791211 --- /dev/null +++ b/flutter/engine/src/flutter/common/macros.h @@ -0,0 +1,20 @@ +// 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_COMMON_MACROS_H_ +#define FLUTTER_COMMON_MACROS_H_ + +#if SLIMPELLER + +#define ONLY_IN_SLIMPELLER(code) code +#define NOT_SLIMPELLER(code) + +#else // SLIMPELLER + +#define ONLY_IN_SLIMPELLER(code) +#define NOT_SLIMPELLER(code) code + +#endif // SLIMPELLER + +#endif // FLUTTER_COMMON_MACROS_H_ diff --git a/flutter/engine/src/flutter/common/settings.cc b/flutter/engine/src/flutter/common/settings.cc new file mode 100644 index 0000000000000000000000000000000000000000..055d1ec54da57e7d68041033031e1ef8b1dbd79f --- /dev/null +++ b/flutter/engine/src/flutter/common/settings.cc @@ -0,0 +1,19 @@ +// 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/common/settings.h" + +#include + +namespace flutter { + +constexpr FrameTiming::Phase FrameTiming::kPhases[FrameTiming::kCount]; + +Settings::Settings() = default; + +Settings::Settings(const Settings& other) = default; + +Settings::~Settings() = default; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/common/settings.h b/flutter/engine/src/flutter/common/settings.h new file mode 100644 index 0000000000000000000000000000000000000000..8f41eb29e5b16969ddf01cdbb42cdde2ccf20650 --- /dev/null +++ b/flutter/engine/src/flutter/common/settings.h @@ -0,0 +1,367 @@ +// 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_COMMON_SETTINGS_H_ +#define FLUTTER_COMMON_SETTINGS_H_ + +#include + +#include +#include +#include +#include +#include + +#include "flutter/fml/build_config.h" +#include "flutter/fml/closure.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/time/time_point.h" +#include "flutter/fml/unique_fd.h" + +namespace flutter { + +class FrameTiming { + public: + enum Phase { + kVsyncStart, + kBuildStart, + kBuildFinish, + kRasterStart, + kRasterFinish, + kRasterFinishWallTime, + kCount + }; + + static constexpr Phase kPhases[kCount] = { + kVsyncStart, kBuildStart, kBuildFinish, + kRasterStart, kRasterFinish, kRasterFinishWallTime}; + + static constexpr int kStatisticsCount = kCount + 5; + + fml::TimePoint Get(Phase phase) const { return data_[phase]; } + fml::TimePoint Set(Phase phase, fml::TimePoint value) { + return data_[phase] = value; + } + + uint64_t GetFrameNumber() const { return frame_number_; } + void SetFrameNumber(uint64_t frame_number) { frame_number_ = frame_number; } + uint64_t GetLayerCacheCount() const { return layer_cache_count_; } + uint64_t GetLayerCacheBytes() const { return layer_cache_bytes_; } + uint64_t GetPictureCacheCount() const { return picture_cache_count_; } + uint64_t GetPictureCacheBytes() const { return picture_cache_bytes_; } + void SetRasterCacheStatistics(size_t layer_cache_count, + size_t layer_cache_bytes, + size_t picture_cache_count, + size_t picture_cache_bytes) { + layer_cache_count_ = layer_cache_count; + layer_cache_bytes_ = layer_cache_bytes; + picture_cache_count_ = picture_cache_count; + picture_cache_bytes_ = picture_cache_bytes; + } + + private: + fml::TimePoint data_[kCount]; + uint64_t frame_number_; + size_t layer_cache_count_; + size_t layer_cache_bytes_; + size_t picture_cache_count_; + size_t picture_cache_bytes_; +}; + +using TaskObserverAdd = + std::function; +using TaskObserverRemove = std::function; +using UnhandledExceptionCallback = + std::function; +using LogMessageCallback = + std::function; + +// TODO(26783): Deprecate all the "path" struct members in favor of the +// callback that generates the mapping from these paths. +using MappingCallback = std::function(void)>; +using Mappings = std::vector>; +using MappingsCallback = std::function; + +using FrameRasterizedCallback = std::function; + +class DartIsolate; + +// TODO(https://github.com/flutter/flutter/issues/138750): Re-order fields to +// reduce padding. +// NOLINTNEXTLINE(clang-analyzer-optin.performance.Padding) +struct Settings { + Settings(); + + Settings(const Settings& other); + + ~Settings(); + + /// Determines if attempts at grabbing the Surface's SurfaceData can be + /// attempted. + static constexpr bool kSurfaceDataAccessible = +#ifdef _NDEBUG + false; +#else + true; +#endif + + // VM settings + std::string vm_snapshot_data_path; // deprecated + MappingCallback vm_snapshot_data; + std::string vm_snapshot_instr_path; // deprecated + MappingCallback vm_snapshot_instr; + + std::string isolate_snapshot_data_path; // deprecated + MappingCallback isolate_snapshot_data; + std::string isolate_snapshot_instr_path; // deprecated + MappingCallback isolate_snapshot_instr; + + std::string route; + + // Returns the Mapping to a kernel buffer which contains sources for dart:* + // libraries. + MappingCallback dart_library_sources_kernel; + + // Path to a library containing the application's compiled Dart code. + // This is a vector so that the embedder can provide fallback paths in + // case the primary path to the library can not be loaded. + std::vector application_library_path; + + // Path to a library containing compiled Dart code usable for launching + // the VM service isolate. + std::vector vmservice_snapshot_library_path; + + std::string application_kernel_asset; // deprecated + std::string application_kernel_list_asset; // deprecated + MappingsCallback application_kernels; + + std::string temp_directory_path; + std::vector dart_flags; + // Isolate settings + bool enable_checked_mode = false; + bool start_paused = false; + bool trace_skia = false; + std::vector trace_allowlist; + std::optional> trace_skia_allowlist; + bool trace_startup = false; + bool trace_systrace = false; + std::string trace_to_file; + bool enable_timeline_event_handler = true; + bool dump_skp_on_shader_compilation = false; + bool cache_sksl = false; + bool purge_persistent_cache = false; + bool endless_trace_buffer = false; + bool enable_dart_profiling = false; + bool disable_dart_asserts = false; + bool enable_serial_gc = false; + + // Whether embedder only allows secure connections. + bool may_insecurely_connect_to_all_domains = true; + // JSON-formatted domain network policy. + std::string domain_network_policy; + + // Used as the script URI in debug messages. Does not affect how the Dart code + // is executed. + std::string advisory_script_uri = "main.dart"; + // Used as the script entrypoint in debug messages. Does not affect how the + // Dart code is executed. + std::string advisory_script_entrypoint = "main"; + + // The executable path associated with this process. This is returned by + // Platform.executable from dart:io. If unknown, defaults to "Flutter". + std::string executable_name = "Flutter"; + + // VM Service settings + + // Whether the Dart VM service should be enabled. + bool enable_vm_service = false; + + // Whether to publish the VM Service URL over mDNS. + // On iOS 14 this prompts a local network permission dialog, + // which cannot be accepted or dismissed in a CI environment. + bool enable_vm_service_publication = true; + + // The IP address to which the Dart VM service is bound. + std::string vm_service_host; + + // The port to which the Dart VM service is bound. When set to `0`, a free + // port will be automatically selected by the OS. A message is logged on the + // target indicating the URL at which the VM service can be accessed. + uint32_t vm_service_port = 0; + + // Determines whether an authentication code is required to communicate with + // the VM service. + bool disable_service_auth_codes = true; + + // Determine whether the vmservice should fallback to automatic port selection + // after failing to bind to a specified port. + bool enable_service_port_fallback = false; + + // Font settings + bool use_test_fonts = false; + + bool use_asset_fonts = true; + + // Indicates whether the embedding started a prefetch of the default font + // manager before creating the engine. + bool prefetched_default_font_manager = false; + + // Enable the rendering of colors outside of the sRGB gamut. + bool enable_wide_gamut = false; + + // Enable the Impeller renderer on supported platforms. Ignored if Impeller is + // not supported on the platform. +#if FML_OS_ANDROID || FML_OS_IOS || FML_OS_IOS_SIMULATOR + // On iOS devices, Impeller is the default with no opt-out and this field is + // const. +#if FML_OS_IOS || FML_OS_IOS_SIMULATOR + static constexpr const +#endif // FML_OS_IOS && !FML_OS_IOS_SIMULATOR + bool enable_impeller = true; // NOLINT(readability-identifier-naming) +#else + bool enable_impeller = false; +#endif + + // Enable android surface control swapchains where supported. + bool enable_surface_control = false; + + // Whether to lazily initialize impeller PSO state. + bool impeller_enable_lazy_shader_mode = false; + + // An experimental mode that antialiases lines. + bool impeller_antialiased_lines = false; + + // Log a warning during shell initialization if Impeller is not enabled. + bool warn_on_impeller_opt_out = false; + + // Requests a specific rendering backend. + std::optional requested_rendering_backend; + + // Enable Vulkan validation on backends that support it. The validation layers + // must be available to the application. + bool enable_vulkan_validation = false; + + // Enable GPU tracing in GLES backends. + // Some devices claim to support the required APIs but crash on their usage. + bool enable_opengl_gpu_tracing = false; + + // Enable GPU tracing in Vulkan backends. + bool enable_vulkan_gpu_tracing = false; + + // Data set by platform-specific embedders for use in font initialization. + uint32_t font_initialization_data = 0; + + // All shells in the process share the same VM. The last shell to shutdown + // should typically shut down the VM as well. However, applications depend on + // the behavior of "warming-up" the VM by creating a shell that does not do + // anything. This used to work earlier when the VM could not be shut down (and + // hence never was). Shutting down the VM now breaks such assumptions in + // existing embedders. To keep this behavior consistent and allow existing + // embedders the chance to migrate, this flag defaults to true. Any shell + // launched with this flag set to true will leak the VM in the process. There + // is no way to shut down the VM once such a shell has been started. All + // shells in the platform (via their embedding APIs) should cooperate to make + // sure this flag is never set if they want the VM to shutdown and free all + // associated resources. + // It can be customized by application, more detail: + // https://github.com/flutter/flutter/issues/95903 + bool leak_vm = true; + + // Engine settings + TaskObserverAdd task_observer_add; + TaskObserverRemove task_observer_remove; + // The main isolate is current when this callback is made. This is a good spot + // to perform native Dart bindings for libraries not built in. + std::function root_isolate_create_callback; + // TODO(68738): Update isolate callbacks in settings to accept an additional + // DartIsolate parameter. + fml::closure isolate_create_callback; + // The isolate is not current and may have already been destroyed when this + // call is made. + fml::closure root_isolate_shutdown_callback; + fml::closure isolate_shutdown_callback; + // A callback made in the isolate scope of the service isolate when it is + // launched. Care must be taken to ensure that callers are assigning callbacks + // to the settings object used to launch the VM. If an existing VM is used to + // launch an isolate using these settings, the callback will be ignored as the + // service isolate has already been launched. Also, this callback will only be + // made in the modes in which the service isolate is eligible for launch + // (debug and profile). + fml::closure service_isolate_create_callback; + // The callback made on the UI thread in an isolate scope when the engine + // detects that the framework is idle. The VM also uses this time to perform + // tasks suitable when idling. Due to this, embedders are still advised to be + // as fast as possible in returning from this callback. Long running + // operations in this callback do have the capability of introducing jank. + std::function idle_notification_callback; + // A callback given to the embedder to react to unhandled exceptions in the + // running Flutter application. This callback is made on an internal engine + // managed thread and embedders must re-thread as necessary. Performing + // blocking calls in this callback will cause applications to jank. + UnhandledExceptionCallback unhandled_exception_callback; + // A callback given to the embedder to log print messages from the running + // Flutter application. This callback is made on an internal engine managed + // thread and embedders must re-thread if necessary. Performing blocking + // calls in this callback will cause applications to jank. + LogMessageCallback log_message_callback; + bool enable_software_rendering = false; + bool skia_deterministic_rendering_on_cpu = false; + bool verbose_logging = false; + std::string log_tag = "flutter"; + + // The icu_initialization_required setting does not have a corresponding + // switch because it is intended to be decided during build time, not runtime. + // Some companies apply source modification here because their build system + // brings its own ICU data files. + bool icu_initialization_required = true; + std::string icu_data_path; + MappingCallback icu_mapper; + + // Assets settings + fml::UniqueFD::element_type assets_dir = + fml::UniqueFD::traits_type::InvalidValue(); + std::string assets_path; + + // Callback to handle the timings of a rasterized frame. This is called as + // soon as a frame is rasterized. + FrameRasterizedCallback frame_rasterized_callback; + + // This data will be available to the isolate immediately on launch via the + // PlatformDispatcher.getPersistentIsolateData callback. This is meant for + // information that the isolate cannot request asynchronously (platform + // messages can be used for that purpose). This data is held for the lifetime + // of the shell and is available on isolate restarts in the shell instance. + // Due to this, the buffer must be as small as possible. + std::shared_ptr persistent_isolate_data; + + /// Max size of old gen heap size in MB, or 0 for unlimited, -1 for default + /// value. + /// + /// See also: + /// https://github.com/dart-lang/sdk/blob/ca64509108b3e7219c50d6c52877c85ab6a35ff2/runtime/vm/flag_list.h#L150 + int64_t old_gen_heap_size = -1; + + // Max bytes threshold of resource cache, or 0 for unlimited. + size_t resource_cache_max_bytes_threshold = 0; + + /// Enable embedder api on the embedder. + /// + /// This is currently only used by iOS. + bool enable_embedder_api = false; + + /// Enable support for isolates that run on the platform thread. + /// + /// This is used by the runOnPlatformThread API. + bool enable_platform_isolates = false; + + // If true, the UI thread is the platform thread on supported + // platforms. + bool merged_platform_ui_thread = true; +}; + +} // namespace flutter + +#endif // FLUTTER_COMMON_SETTINGS_H_ diff --git a/flutter/engine/src/flutter/common/task_runners.cc b/flutter/engine/src/flutter/common/task_runners.cc new file mode 100644 index 0000000000000000000000000000000000000000..867fce72e3a119e7539c3cb7c3f820d0e1dd76e1 --- /dev/null +++ b/flutter/engine/src/flutter/common/task_runners.cc @@ -0,0 +1,50 @@ +// 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/common/task_runners.h" + +#include + +namespace flutter { + +TaskRunners::TaskRunners(std::string label, + fml::RefPtr platform, + fml::RefPtr raster, + fml::RefPtr ui, + fml::RefPtr io) + : label_(std::move(label)), + platform_(std::move(platform)), + raster_(std::move(raster)), + ui_(std::move(ui)), + io_(std::move(io)) {} + +TaskRunners::TaskRunners(const TaskRunners& other) = default; + +TaskRunners::~TaskRunners() = default; + +const std::string& TaskRunners::GetLabel() const { + return label_; +} + +fml::RefPtr TaskRunners::GetPlatformTaskRunner() const { + return platform_; +} + +fml::RefPtr TaskRunners::GetUITaskRunner() const { + return ui_; +} + +fml::RefPtr TaskRunners::GetIOTaskRunner() const { + return io_; +} + +fml::RefPtr TaskRunners::GetRasterTaskRunner() const { + return raster_; +} + +bool TaskRunners::IsValid() const { + return platform_ && raster_ && ui_ && io_; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/common/task_runners.h b/flutter/engine/src/flutter/common/task_runners.h new file mode 100644 index 0000000000000000000000000000000000000000..291372b785325503c55b3f108cf01e077461c3dc --- /dev/null +++ b/flutter/engine/src/flutter/common/task_runners.h @@ -0,0 +1,49 @@ +// 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_COMMON_TASK_RUNNERS_H_ +#define FLUTTER_COMMON_TASK_RUNNERS_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/task_runner.h" + +namespace flutter { + +class TaskRunners { + public: + TaskRunners(std::string label, + fml::RefPtr platform, + fml::RefPtr raster, + fml::RefPtr ui, + fml::RefPtr io); + + TaskRunners(const TaskRunners& other); + + ~TaskRunners(); + + const std::string& GetLabel() const; + + fml::RefPtr GetPlatformTaskRunner() const; + + fml::RefPtr GetUITaskRunner() const; + + fml::RefPtr GetIOTaskRunner() const; + + fml::RefPtr GetRasterTaskRunner() const; + + bool IsValid() const; + + private: + const std::string label_; + fml::RefPtr platform_; + fml::RefPtr raster_; + fml::RefPtr ui_; + fml::RefPtr io_; +}; + +} // namespace flutter + +#endif // FLUTTER_COMMON_TASK_RUNNERS_H_ diff --git a/flutter/engine/src/flutter/display_list/BUILD.gn b/flutter/engine/src/flutter/display_list/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..04121176a75092bd0dd5c53ac80780e9e5bb3abe --- /dev/null +++ b/flutter/engine/src/flutter/display_list/BUILD.gn @@ -0,0 +1,316 @@ +# 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("//flutter/common/config.gni") +import("//flutter/impeller/tools/impeller.gni") +import("//flutter/testing/testing.gni") + +if (is_fuchsia) { + import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") +} + +config("display_list_config") { + defines = [] +} + +source_set("display_list") { + sources = [ + "benchmarking/dl_complexity.cc", + "benchmarking/dl_complexity.h", + "benchmarking/dl_complexity_gl.cc", + "benchmarking/dl_complexity_gl.h", + "benchmarking/dl_complexity_metal.cc", + "benchmarking/dl_complexity_metal.h", + "display_list.cc", + "display_list.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_color.cc", + "dl_color.h", + "dl_op_flags.cc", + "dl_op_flags.h", + "dl_op_receiver.cc", + "dl_op_receiver.h", + "dl_op_records.cc", + "dl_op_records.h", + "dl_paint.cc", + "dl_paint.h", + "dl_sampling_options.h", + "dl_storage.cc", + "dl_storage.h", + "dl_tile_mode.h", + "dl_types.cc", + "dl_types.h", + "dl_vertices.cc", + "dl_vertices.h", + "effects/color_filters/dl_blend_color_filter.cc", + "effects/color_filters/dl_blend_color_filter.h", + "effects/color_filters/dl_linear_to_srgb_gamma_color_filter.cc", + "effects/color_filters/dl_linear_to_srgb_gamma_color_filter.h", + "effects/color_filters/dl_matrix_color_filter.cc", + "effects/color_filters/dl_matrix_color_filter.h", + "effects/color_filters/dl_srgb_to_linear_gamma_color_filter.cc", + "effects/color_filters/dl_srgb_to_linear_gamma_color_filter.h", + "effects/color_sources/dl_conical_gradient_color_source.cc", + "effects/color_sources/dl_conical_gradient_color_source.h", + "effects/color_sources/dl_image_color_source.cc", + "effects/color_sources/dl_image_color_source.h", + "effects/color_sources/dl_linear_gradient_color_source.cc", + "effects/color_sources/dl_linear_gradient_color_source.h", + "effects/color_sources/dl_radial_gradient_color_source.cc", + "effects/color_sources/dl_radial_gradient_color_source.h", + "effects/color_sources/dl_runtime_effect_color_source.cc", + "effects/color_sources/dl_runtime_effect_color_source.h", + "effects/color_sources/dl_sweep_gradient_color_source.cc", + "effects/color_sources/dl_sweep_gradient_color_source.h", + "effects/dl_color_filter.cc", + "effects/dl_color_filter.h", + "effects/dl_color_filters.h", + "effects/dl_color_source.cc", + "effects/dl_color_source.h", + "effects/dl_color_sources.h", + "effects/dl_image_filter.cc", + "effects/dl_image_filter.h", + "effects/dl_image_filters.h", + "effects/dl_mask_filter.cc", + "effects/dl_mask_filter.h", + "effects/dl_runtime_effect.cc", + "effects/dl_runtime_effect.h", + "effects/image_filters/dl_blur_image_filter.cc", + "effects/image_filters/dl_blur_image_filter.h", + "effects/image_filters/dl_color_filter_image_filter.cc", + "effects/image_filters/dl_color_filter_image_filter.h", + "effects/image_filters/dl_compose_image_filter.cc", + "effects/image_filters/dl_compose_image_filter.h", + "effects/image_filters/dl_dilate_image_filter.cc", + "effects/image_filters/dl_dilate_image_filter.h", + "effects/image_filters/dl_erode_image_filter.cc", + "effects/image_filters/dl_erode_image_filter.h", + "effects/image_filters/dl_local_matrix_image_filter.cc", + "effects/image_filters/dl_local_matrix_image_filter.h", + "effects/image_filters/dl_matrix_image_filter.cc", + "effects/image_filters/dl_matrix_image_filter.h", + "effects/image_filters/dl_runtime_effect_image_filter.cc", + "effects/image_filters/dl_runtime_effect_image_filter.h", + "geometry/dl_geometry_types.h", + "geometry/dl_path.cc", + "geometry/dl_path.h", + "geometry/dl_region.cc", + "geometry/dl_region.h", + "geometry/dl_rtree.cc", + "geometry/dl_rtree.h", + "image/dl_image.cc", + "image/dl_image.h", + "image/dl_image_skia.cc", + "image/dl_image_skia.h", + "skia/dl_sk_canvas.cc", + "skia/dl_sk_canvas.h", + "skia/dl_sk_conversions.cc", + "skia/dl_sk_conversions.h", + "skia/dl_sk_dispatcher.cc", + "skia/dl_sk_dispatcher.h", + "skia/dl_sk_paint_dispatcher.cc", + "skia/dl_sk_paint_dispatcher.h", + "skia/dl_sk_types.h", + "utils/dl_accumulation_rect.cc", + "utils/dl_accumulation_rect.h", + "utils/dl_matrix_clip_tracker.cc", + "utils/dl_matrix_clip_tracker.h", + "utils/dl_receiver_utils.cc", + "utils/dl_receiver_utils.h", + ] + + public_configs = [ ":display_list_config" ] + + public_deps = [ + "//flutter/fml", + "//flutter/impeller/runtime_stage", + "//flutter/impeller/typographer", + "//flutter/skia", + ] + + if (!defined(defines)) { + defines = [] + } +} + +test_fixtures("display_list_fixtures") { + fixtures = [ "//flutter/txt/third_party/fonts/Roboto-Regular.ttf" ] +} + +if (enable_unittests) { + executable("display_list_unittests") { + testonly = true + + sources = [ + "benchmarking/dl_complexity_unittests.cc", + "display_list_unittests.cc", + "dl_color_unittests.cc", + "dl_paint_unittests.cc", + "dl_storage_unittests.cc", + "dl_vertices_unittests.cc", + "effects/dl_color_filter_unittests.cc", + "effects/dl_color_source_unittests.cc", + "effects/dl_image_filter_unittests.cc", + "effects/dl_mask_filter_unittests.cc", + "geometry/dl_geometry_types_unittests.cc", + "geometry/dl_path_unittests.cc", + "geometry/dl_region_unittests.cc", + "geometry/dl_rtree_unittests.cc", + "skia/dl_sk_conversions_unittests.cc", + "skia/dl_sk_paint_dispatcher_unittests.cc", + "utils/dl_accumulation_rect_unittests.cc", + "utils/dl_matrix_clip_tracker_unittests.cc", + ] + + deps = [ + ":display_list", + ":display_list_fixtures", + "//flutter/display_list/testing:display_list_testing", + "//flutter/impeller/typographer/backends/skia:typographer_skia_backend", + "//flutter/testing", + "//flutter/testing:skia", + ] + + if (!defined(defines)) { + defines = [] + } + if (is_win) { + # Required for M_PI and others. + defines += [ "_USE_MATH_DEFINES" ] + } + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + if (is_fuchsia) { + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + } + } + + executable("display_list_rendertests") { + testonly = true + + sources = [ "testing/dl_rendering_unittests.cc" ] + + deps = [ + ":display_list", + ":display_list_fixtures", + "//flutter/common/graphics", + "//flutter/display_list/testing:display_list_surface_provider", + "//flutter/display_list/testing:display_list_testing", + "//flutter/impeller/typographer/backends/skia:typographer_skia_backend", + "//flutter/testing", + "//flutter/txt", + ] + + if (!defined(defines)) { + defines = [] + } + if (is_win) { + # Required for M_PI and others. + defines += [ "_USE_MATH_DEFINES" ] + } + + # This is needed for //flutter/third_party/googletest for linking zircon + # symbols. + if (is_fuchsia) { + libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] + } + } + + executable("display_list_builder_benchmarks") { + testonly = true + + sources = [ "benchmarking/dl_builder_benchmarks.cc" ] + + deps = [ + ":display_list", + ":display_list_fixtures", + "//flutter/benchmarking", + "//flutter/display_list/testing:display_list_testing", + "//flutter/testing:testing_lib", + ] + } + + executable("display_list_region_benchmarks") { + testonly = true + + sources = [ "benchmarking/dl_region_benchmarks.cc" ] + + deps = [ + ":display_list_fixtures", + "//flutter/benchmarking", + "//flutter/testing:testing_lib", + ] + } + + executable("display_list_transform_benchmarks") { + testonly = true + + sources = [ "benchmarking/dl_transform_benchmarks.cc" ] + + deps = [ + ":display_list_fixtures", + "//flutter/benchmarking", + "//flutter/testing:testing_lib", + ] + } +} + +source_set("display_list_benchmarks_source") { + testonly = true + + sources = [ + "benchmarking/dl_benchmarks.cc", + "benchmarking/dl_benchmarks.h", + ] + + deps = [ + ":display_list", + ":display_list_fixtures", + "$dart_src/runtime:libdart_jit", # for tracing + "//flutter/benchmarking", + "//flutter/common/graphics", + "//flutter/display_list/testing:display_list_surface_provider", + "//flutter/display_list/testing:display_list_testing", + "//flutter/fml", + "//flutter/skia", + "//flutter/testing:skia", + "//flutter/testing:testing_lib", + ] +} + +executable("display_list_benchmarks") { + testonly = true + + deps = [ ":display_list_benchmarks_source" ] +} + +if (is_ios) { + shared_library("ios_display_list_benchmarks") { + testonly = true + visibility = [ ":*" ] + + configs -= [ + "//build/config/gcc:symbol_visibility_hidden", + "//build/config:symbol_visibility_hidden", + ] + configs += [ "//flutter/benchmarking:benchmark_library_config" ] + cflags = [ + "-fobjc-arc", + "-mios-simulator-version-min=$ios_testing_deployment_target", + ] + ldflags = + [ "-Wl,-install_name,@rpath/libios_display_list_benchmarks.dylib" ] + deps = [ + ":display_list_benchmarks_source", + "//flutter/benchmarking:benchmarking_library", + ] + } +} diff --git a/flutter/engine/src/flutter/display_list/display_list.cc b/flutter/engine/src/flutter/display_list/display_list.cc new file mode 100644 index 0000000000000000000000000000000000000000..3e5505b8f7882bbc7759ed2aeccba861d8a4b8a6 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/display_list.cc @@ -0,0 +1,481 @@ +// 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 + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/dl_op_records.h" +#include "flutter/fml/trace_event.h" + +namespace flutter { + +const SaveLayerOptions SaveLayerOptions::kNoAttributes = SaveLayerOptions(); +const SaveLayerOptions SaveLayerOptions::kWithAttributes = + kNoAttributes.with_renders_with_attributes(); + +DisplayList::DisplayList() + : op_count_(0), + nested_byte_count_(0), + nested_op_count_(0), + total_depth_(0), + unique_id_(0), + can_apply_group_opacity_(true), + is_ui_thread_safe_(true), + modifies_transparent_black_(false), + root_has_backdrop_filter_(false), + root_is_unbounded_(false), + max_root_blend_mode_(DlBlendMode::kClear) { + FML_DCHECK(offsets_.size() == 0u); + FML_DCHECK(storage_.size() == 0u); +} + +DisplayList::DisplayList(DisplayListStorage&& storage, + std::vector&& offsets, + uint32_t op_count, + size_t nested_byte_count, + uint32_t nested_op_count, + uint32_t total_depth, + const DlRect& bounds, + bool can_apply_group_opacity, + bool is_ui_thread_safe, + bool modifies_transparent_black, + DlBlendMode max_root_blend_mode, + bool root_has_backdrop_filter, + bool root_is_unbounded, + sk_sp rtree) + : storage_(std::move(storage)), + offsets_(std::move(offsets)), + op_count_(op_count), + nested_byte_count_(nested_byte_count), + nested_op_count_(nested_op_count), + total_depth_(total_depth), + unique_id_(next_unique_id()), + bounds_(bounds), + can_apply_group_opacity_(can_apply_group_opacity), + is_ui_thread_safe_(is_ui_thread_safe), + modifies_transparent_black_(modifies_transparent_black), + root_has_backdrop_filter_(root_has_backdrop_filter), + root_is_unbounded_(root_is_unbounded), + max_root_blend_mode_(max_root_blend_mode), + rtree_(std::move(rtree)) { + FML_DCHECK(storage_.capacity() == storage_.size()); +} + +DisplayList::~DisplayList() { + DisposeOps(storage_, offsets_); +} + +uint32_t DisplayList::next_unique_id() { + static std::atomic next_id{1}; + uint32_t id; + do { + id = next_id.fetch_add(+1, std::memory_order_relaxed); + } while (id == 0); + return id; +} + +struct SaveInfo { + SaveInfo(DlIndex previous_restore_index, bool save_was_needed) + : previous_restore_index(previous_restore_index), + save_was_needed(save_was_needed) {} + + DlIndex previous_restore_index; + bool save_was_needed; +}; + +void DisplayList::RTreeResultsToIndexVector( + std::vector& indices, + const std::vector& rtree_results) const { + FML_DCHECK(rtree_); + auto cur_rect = rtree_results.begin(); + auto end_rect = rtree_results.end(); + if (cur_rect >= end_rect) { + return; + } + DlIndex next_render_index = rtree_->id(*cur_rect++); + DlIndex next_restore_index = std::numeric_limits::max(); + std::vector save_infos; + for (DlIndex index = 0u; index < offsets_.size(); index++) { + while (index > next_render_index) { + if (cur_rect < end_rect) { + next_render_index = rtree_->id(*cur_rect++); + } else { + // Nothing left to render. + // Nothing left to do, but match our restores from the stack. + while (!save_infos.empty()) { + SaveInfo& info = save_infos.back(); + // stack top boolean tells us whether the local variable + // next_restore_index should be executed. The local variable + // then gets reset to the value stored in the stack top + if (info.save_was_needed) { + FML_DCHECK(next_restore_index < offsets_.size()); + indices.push_back(next_restore_index); + } + next_restore_index = info.previous_restore_index; + save_infos.pop_back(); + } + return; + } + } + const uint8_t* ptr = storage_.base() + offsets_[index]; + const DLOp* op = reinterpret_cast(ptr); + switch (GetOpCategory(op->type)) { + case DisplayListOpCategory::kAttribute: + // Attributes are always needed + indices.push_back(index); + break; + + case DisplayListOpCategory::kTransform: + case DisplayListOpCategory::kClip: + if (next_render_index < next_restore_index) { + indices.push_back(index); + } + break; + + case DisplayListOpCategory::kRendering: + case DisplayListOpCategory::kSubDisplayList: + if (index == next_render_index) { + indices.push_back(index); + } + break; + + case DisplayListOpCategory::kSave: + case DisplayListOpCategory::kSaveLayer: { + bool needed = (next_render_index < next_restore_index); + save_infos.emplace_back(next_restore_index, needed); + switch (op->type) { + case DisplayListOpType::kSave: + case DisplayListOpType::kSaveLayer: + case DisplayListOpType::kSaveLayerBackdrop: + next_restore_index = + static_cast(op)->restore_index; + break; + default: + FML_UNREACHABLE(); + } + if (needed) { + indices.push_back(index); + } + break; + } + + case DisplayListOpCategory::kRestore: { + FML_DCHECK(!save_infos.empty()); + FML_DCHECK(index == next_restore_index); + SaveInfo& info = save_infos.back(); + next_restore_index = info.previous_restore_index; + if (info.save_was_needed) { + indices.push_back(index); + } + save_infos.pop_back(); + break; + } + + case DisplayListOpCategory::kInvalidCategory: + FML_UNREACHABLE(); + } + } +} + +void DisplayList::Dispatch(DlOpReceiver& receiver) const { + const uint8_t* base = storage_.base(); + for (size_t offset : offsets_) { + DispatchOneOp(receiver, base + offset); + } +} + +void DisplayList::Dispatch(DlOpReceiver& receiver, + const DlIRect& cull_rect) const { + Dispatch(receiver, DlRect::Make(cull_rect)); +} + +void DisplayList::Dispatch(DlOpReceiver& receiver, + const DlRect& cull_rect) const { + if (cull_rect.IsEmpty()) { + return; + } + if (!has_rtree() || cull_rect.Contains(GetBounds())) { + Dispatch(receiver); + } else { + auto op_indices = GetCulledIndices(cull_rect); + const uint8_t* base = storage_.base(); + for (DlIndex index : op_indices) { + DispatchOneOp(receiver, base + offsets_[index]); + } + } +} + +void DisplayList::DispatchOneOp(DlOpReceiver& receiver, + const uint8_t* ptr) const { + auto op = reinterpret_cast(ptr); + switch (op->type) { +#define DL_OP_DISPATCH(name) \ + case DisplayListOpType::k##name: \ + static_cast(op)->dispatch(receiver); \ + break; + + FOR_EACH_DISPLAY_LIST_OP(DL_OP_DISPATCH) + +#undef DL_OP_DISPATCH + + case DisplayListOpType::kInvalidOp: + default: + FML_DCHECK(false) << "Unrecognized op type: " + << static_cast(op->type); + } +} + +void DisplayList::DisposeOps(const DisplayListStorage& storage, + const std::vector& offsets) { + const uint8_t* base = storage.base(); + if (!base) { + return; + } + for (size_t offset : offsets) { + auto op = reinterpret_cast(base + offset); + switch (op->type) { +#define DL_OP_DISPOSE(name) \ + case DisplayListOpType::k##name: \ + if (!std::is_trivially_destructible_v) { \ + static_cast(op)->~name##Op(); \ + } \ + break; + + FOR_EACH_DISPLAY_LIST_OP(DL_OP_DISPOSE) + +#undef DL_OP_DISPOSE + + default: + FML_UNREACHABLE(); + } + } +} + +DisplayListOpCategory DisplayList::GetOpCategory(DlIndex index) const { + return GetOpCategory(GetOpType(index)); +} + +DisplayListOpCategory DisplayList::GetOpCategory(DisplayListOpType type) { + switch (type) { + case DisplayListOpType::kSetAntiAlias: + case DisplayListOpType::kSetInvertColors: + case DisplayListOpType::kSetStrokeCap: + case DisplayListOpType::kSetStrokeJoin: + case DisplayListOpType::kSetStyle: + case DisplayListOpType::kSetStrokeWidth: + case DisplayListOpType::kSetStrokeMiter: + case DisplayListOpType::kSetColor: + case DisplayListOpType::kSetBlendMode: + case DisplayListOpType::kClearColorFilter: + case DisplayListOpType::kSetPodColorFilter: + case DisplayListOpType::kClearColorSource: + case DisplayListOpType::kSetPodColorSource: + case DisplayListOpType::kSetImageColorSource: + case DisplayListOpType::kSetRuntimeEffectColorSource: + case DisplayListOpType::kClearImageFilter: + case DisplayListOpType::kSetPodImageFilter: + case DisplayListOpType::kSetSharedImageFilter: + case DisplayListOpType::kClearMaskFilter: + case DisplayListOpType::kSetPodMaskFilter: + return DisplayListOpCategory::kAttribute; + + case DisplayListOpType::kSave: + return DisplayListOpCategory::kSave; + case DisplayListOpType::kSaveLayer: + case DisplayListOpType::kSaveLayerBackdrop: + return DisplayListOpCategory::kSaveLayer; + case DisplayListOpType::kRestore: + return DisplayListOpCategory::kRestore; + + case DisplayListOpType::kTranslate: + case DisplayListOpType::kScale: + case DisplayListOpType::kRotate: + case DisplayListOpType::kSkew: + case DisplayListOpType::kTransform2DAffine: + case DisplayListOpType::kTransformFullPerspective: + case DisplayListOpType::kTransformReset: + return DisplayListOpCategory::kTransform; + + case DisplayListOpType::kClipIntersectRect: + case DisplayListOpType::kClipIntersectOval: + case DisplayListOpType::kClipIntersectRoundRect: + case DisplayListOpType::kClipIntersectRoundSuperellipse: + case DisplayListOpType::kClipIntersectPath: + case DisplayListOpType::kClipDifferenceRect: + case DisplayListOpType::kClipDifferenceOval: + case DisplayListOpType::kClipDifferenceRoundRect: + case DisplayListOpType::kClipDifferenceRoundSuperellipse: + case DisplayListOpType::kClipDifferencePath: + return DisplayListOpCategory::kClip; + + case DisplayListOpType::kDrawPaint: + case DisplayListOpType::kDrawColor: + case DisplayListOpType::kDrawLine: + case DisplayListOpType::kDrawDashedLine: + case DisplayListOpType::kDrawRect: + case DisplayListOpType::kDrawOval: + case DisplayListOpType::kDrawCircle: + case DisplayListOpType::kDrawRoundRect: + case DisplayListOpType::kDrawDiffRoundRect: + case DisplayListOpType::kDrawRoundSuperellipse: + case DisplayListOpType::kDrawArc: + case DisplayListOpType::kDrawPath: + case DisplayListOpType::kDrawPoints: + case DisplayListOpType::kDrawLines: + case DisplayListOpType::kDrawPolygon: + case DisplayListOpType::kDrawVertices: + case DisplayListOpType::kDrawImage: + case DisplayListOpType::kDrawImageWithAttr: + case DisplayListOpType::kDrawImageRect: + case DisplayListOpType::kDrawImageNine: + case DisplayListOpType::kDrawImageNineWithAttr: + case DisplayListOpType::kDrawAtlas: + case DisplayListOpType::kDrawAtlasCulled: + case DisplayListOpType::kDrawTextBlob: + case DisplayListOpType::kDrawTextFrame: + case DisplayListOpType::kDrawShadow: + case DisplayListOpType::kDrawShadowTransparentOccluder: + return DisplayListOpCategory::kRendering; + + case DisplayListOpType::kDrawDisplayList: + return DisplayListOpCategory::kSubDisplayList; + + case DisplayListOpType::kInvalidOp: + return DisplayListOpCategory::kInvalidCategory; + } +} + +DisplayListOpType DisplayList::GetOpType(DlIndex index) const { + // Assert unsigned type so we can eliminate >= 0 comparison + static_assert(std::is_unsigned_v); + if (index >= offsets_.size()) { + return DisplayListOpType::kInvalidOp; + } + + size_t offset = offsets_[index]; + FML_DCHECK(offset < storage_.size()); + auto ptr = storage_.base() + offset; + auto op = reinterpret_cast(ptr); + return op->type; +} + +static void FillAllIndices(std::vector& indices, DlIndex size) { + indices.reserve(size); + for (DlIndex i = 0u; i < size; i++) { + indices.push_back(i); + } +} + +std::vector DisplayList::GetCulledIndices( + const DlRect& cull_rect) const { + std::vector indices; + if (!cull_rect.IsEmpty()) { + if (rtree_) { + std::vector rect_indices; + rtree_->search(cull_rect, &rect_indices); + RTreeResultsToIndexVector(indices, rect_indices); + } else { + FillAllIndices(indices, offsets_.size()); + } + } + return indices; +} + +bool DisplayList::Dispatch(DlOpReceiver& receiver, DlIndex index) const { + // Assert unsigned type so we can eliminate >= 0 comparison + static_assert(std::is_unsigned_v); + if (index >= offsets_.size()) { + return false; + } + + size_t offset = offsets_[index]; + FML_DCHECK(offset < storage_.size()); + auto ptr = storage_.base() + offset; + + DispatchOneOp(receiver, ptr); + + return true; +} + +static bool CompareOps(const DisplayListStorage& storageA, + const std::vector& offsetsA, + const DisplayListStorage& storageB, + const std::vector& offsetsB) { + const uint8_t* base_a = storageA.base(); + const uint8_t* base_b = storageB.base(); + // These conditions are checked by the caller... + FML_DCHECK(offsetsA.size() == offsetsB.size()); + FML_DCHECK(base_a != base_b); + size_t bulk_start = 0u; + for (size_t i = 0; i < offsetsA.size(); i++) { + size_t offset = offsetsA[i]; + FML_DCHECK(offsetsB[i] == offset); + auto opA = reinterpret_cast(base_a + offset); + auto opB = reinterpret_cast(base_b + offset); + if (opA->type != opB->type) { + return false; + } + DisplayListCompare result; + switch (opA->type) { +#define DL_OP_EQUALS(name) \ + case DisplayListOpType::k##name: \ + result = static_cast(opA)->equals( \ + static_cast(opB)); \ + break; + + FOR_EACH_DISPLAY_LIST_OP(DL_OP_EQUALS) + +#undef DL_OP_EQUALS + + default: + FML_DCHECK(false); + return false; + } + switch (result) { + case DisplayListCompare::kNotEqual: + return false; + case DisplayListCompare::kUseBulkCompare: + break; + case DisplayListCompare::kEqual: + // Check if we have a backlog of bytes to bulk compare and then + // reset the bulk compare pointers to the address following this op + if (bulk_start < offset) { + const uint8_t* bulk_start_a = base_a + bulk_start; + const uint8_t* bulk_start_b = base_b + bulk_start; + if (memcmp(bulk_start_a, bulk_start_b, offset - bulk_start) != 0) { + return false; + } + } + bulk_start = + i + 1 < offsetsA.size() ? offsetsA[i + 1] : storageA.size(); + break; + } + } + if (bulk_start < storageA.size()) { + // Perform a final bulk compare if we have remaining bytes waiting + const uint8_t* bulk_start_a = base_a + bulk_start; + const uint8_t* bulk_start_b = base_b + bulk_start; + if (memcmp(bulk_start_a, bulk_start_b, storageA.size() - bulk_start) != 0) { + return false; + } + } + return true; +} + +bool DisplayList::Equals(const DisplayList* other) const { + if (this == other) { + return true; + } + if (offsets_.size() != other->offsets_.size() || + storage_.size() != other->storage_.size() || + op_count_ != other->op_count_) { + return false; + } + if (storage_.base() == other->storage_.base()) { + return true; + } + return CompareOps(storage_, offsets_, other->storage_, other->offsets_); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/display_list.h b/flutter/engine/src/flutter/display_list/display_list.h new file mode 100644 index 0000000000000000000000000000000000000000..afe569a484bb1e4abef9da576da1d9a85947436e --- /dev/null +++ b/flutter/engine/src/flutter/display_list/display_list.h @@ -0,0 +1,566 @@ +// 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_H_ +#define FLUTTER_DISPLAY_LIST_DISPLAY_LIST_H_ + +#include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_storage.h" +#include "flutter/display_list/geometry/dl_geometry_types.h" +#include "flutter/display_list/geometry/dl_rtree.h" + +// The Flutter DisplayList mechanism encapsulates a persistent sequence of +// rendering operations. +// +// This file contains the definitions for: +// DisplayList: the base class that holds the information about the +// sequence of operations and can dispatch them to a DlOpReceiver +// DlOpReceiver: a pure virtual interface which can be implemented to field +// the requests for purposes such as sending them to an SkCanvas +// or detecting various rendering optimization scenarios +// DisplayListBuilder: a class for constructing a DisplayList from DlCanvas +// method calls and which can act as a DlOpReceiver as well +// +// Other files include various class definitions for dealing with display +// lists, such as: +// skia/dl_sk_*.h: classes to interact between SkCanvas and DisplayList +// (SkCanvas->DisplayList adapter and vice versa) +// +// display_list_utils.h: various utility classes to ease implementing +// a DlOpReceiver, including NOP implementations of +// the attribute, clip, and transform methods, +// classes to track attributes, clips, and transforms +// and a class to compute the bounds of a DisplayList +// Any class implementing DlOpReceiver can inherit from +// these utility classes to simplify its creation +// +// The Flutter DisplayList mechanism is used in a similar manner to the Skia +// SkPicture mechanism. +// +// A DisplayList must be created using a DisplayListBuilder using its stateless +// methods inherited from DlCanvas. +// +// A DisplayList can be read back by implementing the DlOpReceiver virtual +// methods (with help from some of the classes in the utils file) and +// passing an instance to the Dispatch() method, or it can be rendered +// to Skia using a DlSkCanvasDispatcher. +// +// The mechanism is inspired by the SkLiteDL class that is not directly +// supported by Skia, but has been recommended as a basis for custom +// display lists for a number of their customers. + +namespace flutter { + +#define FOR_EACH_DISPLAY_LIST_OP(V) \ + V(SetAntiAlias) \ + V(SetInvertColors) \ + \ + V(SetStrokeCap) \ + V(SetStrokeJoin) \ + \ + V(SetStyle) \ + V(SetStrokeWidth) \ + V(SetStrokeMiter) \ + \ + V(SetColor) \ + V(SetBlendMode) \ + \ + V(ClearColorFilter) \ + V(SetPodColorFilter) \ + \ + V(ClearColorSource) \ + V(SetPodColorSource) \ + V(SetImageColorSource) \ + V(SetRuntimeEffectColorSource) \ + \ + V(ClearImageFilter) \ + V(SetPodImageFilter) \ + V(SetSharedImageFilter) \ + \ + V(ClearMaskFilter) \ + V(SetPodMaskFilter) \ + \ + V(Save) \ + V(SaveLayer) \ + V(SaveLayerBackdrop) \ + V(Restore) \ + \ + V(Translate) \ + V(Scale) \ + V(Rotate) \ + V(Skew) \ + V(Transform2DAffine) \ + V(TransformFullPerspective) \ + V(TransformReset) \ + \ + V(ClipIntersectRect) \ + V(ClipIntersectOval) \ + V(ClipIntersectRoundRect) \ + V(ClipIntersectRoundSuperellipse) \ + V(ClipIntersectPath) \ + V(ClipDifferenceRect) \ + V(ClipDifferenceOval) \ + V(ClipDifferenceRoundRect) \ + V(ClipDifferenceRoundSuperellipse) \ + V(ClipDifferencePath) \ + \ + V(DrawPaint) \ + V(DrawColor) \ + \ + V(DrawLine) \ + V(DrawDashedLine) \ + V(DrawRect) \ + V(DrawOval) \ + V(DrawCircle) \ + V(DrawRoundRect) \ + V(DrawDiffRoundRect) \ + V(DrawRoundSuperellipse) \ + V(DrawArc) \ + V(DrawPath) \ + \ + V(DrawPoints) \ + V(DrawLines) \ + V(DrawPolygon) \ + V(DrawVertices) \ + \ + V(DrawImage) \ + V(DrawImageWithAttr) \ + V(DrawImageRect) \ + V(DrawImageNine) \ + V(DrawImageNineWithAttr) \ + V(DrawAtlas) \ + V(DrawAtlasCulled) \ + \ + V(DrawDisplayList) \ + V(DrawTextBlob) \ + V(DrawTextFrame) \ + \ + V(DrawShadow) \ + V(DrawShadowTransparentOccluder) + +#define DL_OP_TO_ENUM_VALUE(name) k##name, +enum class DisplayListOpType { + FOR_EACH_DISPLAY_LIST_OP(DL_OP_TO_ENUM_VALUE) + + // empty comment to make formatter happy + kInvalidOp, + kMaxOp = kInvalidOp, +}; +#undef DL_OP_TO_ENUM_VALUE + +enum class DisplayListOpCategory { + kAttribute, + kTransform, + kClip, + kSave, + kSaveLayer, + kRestore, + kRendering, + kSubDisplayList, + kInvalidCategory, + kMaxCategory = kInvalidCategory, +}; + +class DlOpReceiver; +class DisplayListBuilder; + +class SaveLayerOptions { + public: + static const SaveLayerOptions kWithAttributes; + static const SaveLayerOptions kNoAttributes; + + SaveLayerOptions() : flags_(0) {} + SaveLayerOptions(const SaveLayerOptions& options) : flags_(options.flags_) {} + explicit SaveLayerOptions(const SaveLayerOptions* options) + : flags_(options->flags_) {} + + SaveLayerOptions without_optimizations() const { + SaveLayerOptions options; + options.fRendersWithAttributes = fRendersWithAttributes; + options.fBoundsFromCaller = fBoundsFromCaller; + return options; + } + + bool renders_with_attributes() const { return fRendersWithAttributes; } + SaveLayerOptions with_renders_with_attributes() const { + SaveLayerOptions options(this); + options.fRendersWithAttributes = true; + return options; + } + + bool can_distribute_opacity() const { return fCanDistributeOpacity; } + SaveLayerOptions with_can_distribute_opacity() const { + SaveLayerOptions options(this); + options.fCanDistributeOpacity = true; + return options; + } + + // Returns true iff the bounds for the saveLayer operation were provided + // by the caller, otherwise the bounds will have been computed by the + // DisplayListBuilder and provided for reference. + bool bounds_from_caller() const { return fBoundsFromCaller; } + SaveLayerOptions with_bounds_from_caller() const { + SaveLayerOptions options(this); + options.fBoundsFromCaller = true; + return options; + } + SaveLayerOptions without_bounds_from_caller() const { + SaveLayerOptions options(this); + options.fBoundsFromCaller = false; + return options; + } + bool bounds_were_calculated() const { return !fBoundsFromCaller; } + + // Returns true iff the bounds for the saveLayer do not fully cover the + // contained rendering operations. This will only occur if the original + // caller supplied bounds and those bounds were not a strict superset + // of the content bounds computed by the DisplayListBuilder. + bool content_is_clipped() const { return fContentIsClipped; } + SaveLayerOptions with_content_is_clipped() const { + SaveLayerOptions options(this); + options.fContentIsClipped = true; + return options; + } + + bool contains_backdrop_filter() const { return fHasBackdropFilter; } + SaveLayerOptions with_contains_backdrop_filter() const { + SaveLayerOptions options(this); + options.fHasBackdropFilter = true; + return options; + } + + bool content_is_unbounded() const { return fContentIsUnbounded; } + SaveLayerOptions with_content_is_unbounded() const { + SaveLayerOptions options(this); + options.fContentIsUnbounded = true; + return options; + } + + SaveLayerOptions& operator=(const SaveLayerOptions& other) { + flags_ = other.flags_; + return *this; + } + bool operator==(const SaveLayerOptions& other) const { + return flags_ == other.flags_; + } + bool operator!=(const SaveLayerOptions& other) const { + return flags_ != other.flags_; + } + + private: + union { + struct { + unsigned fRendersWithAttributes : 1; + unsigned fCanDistributeOpacity : 1; + unsigned fBoundsFromCaller : 1; + unsigned fContentIsClipped : 1; + unsigned fHasBackdropFilter : 1; + unsigned fContentIsUnbounded : 1; + }; + uint32_t flags_; + }; +}; + +using DlIndex = uint32_t; + +// The base class that contains a sequence of rendering operations +// for dispatch to a DlOpReceiver. These objects must be instantiated +// through an instance of DisplayListBuilder::build(). +class DisplayList : public SkRefCnt { + public: + DisplayList(); + + ~DisplayList(); + + void Dispatch(DlOpReceiver& ctx) const; + void Dispatch(DlOpReceiver& ctx, const SkRect& cull_rect) const { + Dispatch(ctx, ToDlRect(cull_rect)); + } + void Dispatch(DlOpReceiver& ctx, const SkIRect& cull_rect) const { + Dispatch(ctx, ToDlIRect(cull_rect)); + } + void Dispatch(DlOpReceiver& ctx, const DlRect& cull_rect) const; + void Dispatch(DlOpReceiver& ctx, const DlIRect& cull_rect) const; + + // From historical behavior, SkPicture always included nested bytes, + // 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 { + return sizeof(DisplayList) + storage_.size() + + (nested ? nested_byte_count_ : 0); + } + + uint32_t op_count(bool nested = false) const { + return op_count_ + (nested ? nested_op_count_ : 0); + } + + uint32_t total_depth() const { return total_depth_; } + + uint32_t unique_id() const { return unique_id_; } + + const SkRect& bounds() const { return ToSkRect(bounds_); } + const DlRect& GetBounds() const { return bounds_; } + + bool has_rtree() const { return rtree_ != nullptr; } + sk_sp rtree() const { return rtree_; } + + bool Equals(const DisplayList* other) const; + bool Equals(const DisplayList& other) const { return Equals(&other); } + bool Equals(const sk_sp& other) const { + return Equals(other.get()); + } + + bool can_apply_group_opacity() const { return can_apply_group_opacity_; } + bool isUIThreadSafe() const { return is_ui_thread_safe_; } + + /// @brief Indicates if there are any rendering operations in this + /// DisplayList that will modify a surface of transparent black + /// pixels. + /// + /// This condition can be used to determine whether to create a cleared + /// surface, render a DisplayList into it, and then composite the + /// result into a scene. It is not uncommon for code in the engine to + /// come across such degenerate DisplayList objects when slicing up a + /// frame between platform views. + bool modifies_transparent_black() const { + return modifies_transparent_black_; + } + + const DisplayListStorage& GetStorage() const { return storage_; } + + /// @brief Indicates if there are any saveLayer operations at the root + /// surface level of the DisplayList that use a backdrop filter. + /// + /// This condition can be used to determine what kind of surface to create + /// for the root layer into which to render the DisplayList as some GPUs + /// can support surfaces that do or do not support the readback that would + /// be required for the backdrop filter to do its work. + bool root_has_backdrop_filter() const { return root_has_backdrop_filter_; } + + /// @brief Indicates if a rendering operation at the root level of the + /// DisplayList had an unbounded result, not otherwise limited by + /// a clip operation. + /// + /// This condition can occur in a number of situations. The most common + /// situation is when there is a drawPaint or drawColor rendering + /// operation which fills out the entire drawable surface unless it is + /// bounded by a clip. Other situations include an operation rendered + /// through an ImageFilter that cannot compute the resulting bounds or + /// when an unclipped backdrop filter is applied by a save layer. + bool root_is_unbounded() const { return root_is_unbounded_; } + + /// @brief Indicates the maximum DlBlendMode used on any rendering op + /// in the root surface of the DisplayList. + /// + /// This condition can be used to determine what kind of surface to create + /// for the root layer into which to render the DisplayList as some GPUs + /// can support surfaces that do or do not support the readback that would + /// be required for the indicated blend mode to do its work. + DlBlendMode max_root_blend_mode() const { return max_root_blend_mode_; } + + /// @brief Iterator utility class used for the |DisplayList::begin| + /// and |DisplayList::end| methods. It implements just the + /// basic methods to enable iteration-style for loops. + class Iterator { + public: + DlIndex operator*() const { return value_; } + bool operator!=(const Iterator& other) { return value_ != other.value_; } + Iterator& operator++() { + value_++; + return *this; + } + + private: + explicit Iterator(DlIndex value) : value_(value) {} + + DlIndex value_; + + friend class DisplayList; + }; + + /// @brief Return the number of stored records in the DisplayList. + /// + /// Each stored record represents a dispatchable operation that will be + /// sent to a |DlOpReceiver| by the |Dispatch| method. You can directly + /// simulate the |Dispatch| method using a simple for loop on the indices: + /// + /// { + /// for (DlIndex i = 0u; i < display_list->GetRecordCount(); i++) { + /// display_list->Dispatch(my_receiver, i); + /// } + /// } + /// + /// @see |Dispatch(receiver, index)| + /// @see |begin| + /// @see |end| + /// @see |GetCulledIndices| + DlIndex GetRecordCount() const { return offsets_.size(); } + + /// @brief Return an iterator to the start of the stored records, + /// enabling the iteration form of a for loop. + /// + /// Each stored record represents a dispatchable operation that will be + /// sent to a |DlOpReceiver| by the |Dispatch| method. You can directly + /// simulate the |Dispatch| method using a simple for loop on the indices: + /// + /// { + /// for (DlIndex i : *display_list) { + /// display_list->Dispatch(my_receiver, i); + /// } + /// } + /// + /// @see |end| + /// @see |GetCulledIndices| + Iterator begin() const { return Iterator(0u); } + + /// @brief Return an iterator to the end of the stored records, + /// enabling the iteration form of a for loop. + /// + /// Each stored record represents a dispatchable operation that will be + /// sent to a |DlOpReceiver| by the |Dispatch| method. You can directly + /// simulate the |Dispatch| method using a simple for loop on the indices: + /// + /// { + /// for (DlIndex i : *display_list) { + /// display_list->Dispatch(my_receiver, i); + /// } + /// } + /// + /// @see |begin| + /// @see |GetCulledIndices| + Iterator end() const { return Iterator(offsets_.size()); } + + /// @brief Dispatch a single stored operation by its index. + /// + /// Each stored record represents a dispatchable operation that will be + /// sent to a |DlOpReceiver| by the |Dispatch| method. You can use this + /// method to dispatch a single operation to your receiver with an index + /// between |0u| (inclusive) and |GetRecordCount()| (exclusive), as in: + /// + /// { + /// for (DlIndex i = 0u; i < display_list->GetRecordCount(); i++) { + /// display_list->Dispatch(my_receiver, i); + /// } + /// } + /// + /// If the index is out of the range of the stored records, this method + /// will not call any methods on the receiver and return false. You can + /// check the return value for true if you want to make sure you are + /// using valid indices. + /// + /// @see |GetRecordCount| + /// @see |begin| + /// @see |end| + /// @see |GetCulledIndices| + bool Dispatch(DlOpReceiver& receiver, DlIndex index) const; + + /// @brief Return an enum describing the specific op type stored at + /// the indicated index. + /// + /// The specific types of the records are subject to change without notice + /// as the DisplayList code is developed and optimized. These values are + /// useful mostly for debugging purposes and should not be used in + /// production code. + /// + /// @see |GetOpCategory| for a more stable description of the records + DisplayListOpType GetOpType(DlIndex index) const; + + /// @brief Return an enum describing the general category of the + /// operation record stored at the indicated index. + /// + /// The categories are general and stable and can be used fairly safely + /// in production code to plan how to dispatch or reorder ops during + /// final rendering. + /// + /// @see |GetOpType| for a more detailed description of the records + /// primarily for debugging use + DisplayListOpCategory GetOpCategory(DlIndex index) const; + + /// @brief Return an enum describing the general category of the + /// operation record with the given type. + /// + /// @see |GetOpType| for a more detailed description of the records + /// primarily for debugging use + static DisplayListOpCategory GetOpCategory(DisplayListOpType type); + + /// @brief Return a vector of valid indices for records stored in + /// the DisplayList that must be dispatched if you are + /// restricted to the indicated cull_rect. + /// + /// This method can be used along with indexed dispatching to implement + /// RTree culling while still maintaining control over planning of + /// operations to be rendered, as in: + /// + /// { + /// std::vector indices = + /// display_list->GetCulledIndices(cull-rect); + /// for (DlIndex i : indices) { + /// display_list->Dispatch(my_receiver, i); + /// } + /// } + /// + /// The indices returned in the vector will automatically deal with + /// including or culling related operations such as attributes, clips + /// and transforms that will provide state for any rendering operations + /// selected by the culling checks. + /// + /// @see |GetOpType| for a more detailed description of the records + /// primarily for debugging use + /// + /// @see |Dispatch(receiver, index)| + std::vector GetCulledIndices(const DlRect& cull_rect) const; + + private: + DisplayList(DisplayListStorage&& ptr, + std::vector&& offsets, + uint32_t op_count, + size_t nested_byte_count, + uint32_t nested_op_count, + uint32_t total_depth, + const DlRect& bounds, + bool can_apply_group_opacity, + bool is_ui_thread_safe, + bool modifies_transparent_black, + DlBlendMode max_root_blend_mode, + bool root_has_backdrop_filter, + bool root_is_unbounded, + sk_sp rtree); + + static uint32_t next_unique_id(); + + static void DisposeOps(const DisplayListStorage& storage, + const std::vector& offsets); + + const DisplayListStorage storage_; + const std::vector offsets_; + + const uint32_t op_count_; + const size_t nested_byte_count_; + const uint32_t nested_op_count_; + + const uint32_t total_depth_; + + const uint32_t unique_id_; + const DlRect bounds_; + + const bool can_apply_group_opacity_; + const bool is_ui_thread_safe_; + const bool modifies_transparent_black_; + const bool root_has_backdrop_filter_; + const bool root_is_unbounded_; + const DlBlendMode max_root_blend_mode_; + + const sk_sp rtree_; + + void DispatchOneOp(DlOpReceiver& receiver, const uint8_t* ptr) const; + + void RTreeResultsToIndexVector(std::vector& indices, + const std::vector& rtree_results) const; + + friend class DisplayListBuilder; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DISPLAY_LIST_H_ diff --git a/flutter/engine/src/flutter/display_list/display_list_unittests.cc b/flutter/engine/src/flutter/display_list/display_list_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..2f68ceb2ce77bc0796f9f025ba7f414e74b82573 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/display_list_unittests.cc @@ -0,0 +1,5919 @@ +// 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 +#include +#include +#include +#include + +#include "flutter/display_list/display_list.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/effects/dl_image_filters.h" +#include "flutter/display_list/geometry/dl_rtree.h" +#include "flutter/display_list/skia/dl_sk_dispatcher.h" +#include "flutter/display_list/testing/dl_test_snippets.h" +#include "flutter/display_list/utils/dl_receiver_utils.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/math.h" +#include "flutter/impeller/typographer/backends/skia/text_frame_skia.h" +#include "flutter/testing/assertions_skia.h" +#include "flutter/testing/display_list_testing.h" +#include "flutter/testing/testing.h" + +namespace flutter { + +DlOpReceiver& DisplayListBuilderTestingAccessor(DisplayListBuilder& builder) { + return builder.asReceiver(); +} + +DlPaint DisplayListBuilderTestingAttributes(DisplayListBuilder& builder) { + return builder.CurrentAttributes(); +} + +int DisplayListBuilderTestingLastOpIndex(DisplayListBuilder& builder) { + return builder.LastOpIndex(); +} + +namespace testing { + +static std::vector allGroups = + CreateAllGroups(); + +template +class DisplayListTestBase : public BaseT { + public: + DisplayListTestBase() = default; + + static DlOpReceiver& ToReceiver(DisplayListBuilder& builder) { + return DisplayListBuilderTestingAccessor(builder); + } + + static sk_sp Build(DisplayListInvocation& invocation) { + DisplayListBuilder builder; + invocation.Invoke(ToReceiver(builder)); + return builder.Build(); + } + + static sk_sp Build(size_t g_index, size_t v_index) { + DisplayListBuilder builder; + DlOpReceiver& receiver = + DisplayListTestBase<::testing::Test>::ToReceiver(builder); + uint32_t op_count = 0u; + size_t byte_count = 0u; + uint32_t depth = 0u; + uint32_t render_op_depth_cost = 1u; + for (size_t i = 0; i < allGroups.size(); i++) { + DisplayListInvocationGroup& group = allGroups[i]; + size_t j = (i == g_index ? v_index : 0); + if (j >= group.variants.size()) { + continue; + } + DisplayListInvocation& invocation = group.variants[j]; + op_count += invocation.op_count(); + byte_count += invocation.raw_byte_count(); + depth += invocation.depth_accumulated(render_op_depth_cost); + invocation.Invoke(receiver); + render_op_depth_cost = + invocation.adjust_render_op_depth_cost(render_op_depth_cost); + } + sk_sp dl = builder.Build(); + std::string name; + if (g_index >= allGroups.size()) { + name = "Default"; + } else { + name = allGroups[g_index].op_name; + if (v_index >= allGroups[g_index].variants.size()) { + name += " skipped"; + } else { + name += " variant " + std::to_string(v_index + 1); + } + } + EXPECT_EQ(dl->op_count(false), op_count) << name; + EXPECT_EQ(dl->bytes(false), byte_count + sizeof(DisplayList)) << name; + EXPECT_EQ(dl->total_depth(), depth) << name; + return dl; + } + + static void check_defaults( + DisplayListBuilder& builder, + const DlRect& cull_rect = DisplayListBuilder::kMaxCullRect) { + DlPaint builder_paint = DisplayListBuilderTestingAttributes(builder); + DlPaint defaults; + + EXPECT_EQ(builder_paint.isAntiAlias(), defaults.isAntiAlias()); + EXPECT_EQ(builder_paint.isInvertColors(), defaults.isInvertColors()); + EXPECT_EQ(builder_paint.getColor(), defaults.getColor()); + EXPECT_EQ(builder_paint.getBlendMode(), defaults.getBlendMode()); + EXPECT_EQ(builder_paint.getDrawStyle(), defaults.getDrawStyle()); + EXPECT_EQ(builder_paint.getStrokeWidth(), defaults.getStrokeWidth()); + EXPECT_EQ(builder_paint.getStrokeMiter(), defaults.getStrokeMiter()); + EXPECT_EQ(builder_paint.getStrokeCap(), defaults.getStrokeCap()); + EXPECT_EQ(builder_paint.getStrokeJoin(), defaults.getStrokeJoin()); + EXPECT_EQ(builder_paint.getColorSource(), defaults.getColorSource()); + EXPECT_EQ(builder_paint.getColorFilter(), defaults.getColorFilter()); + EXPECT_EQ(builder_paint.getImageFilter(), defaults.getImageFilter()); + EXPECT_EQ(builder_paint.getMaskFilter(), defaults.getMaskFilter()); + EXPECT_EQ(builder_paint, defaults); + EXPECT_TRUE(builder_paint.isDefault()); + + EXPECT_EQ(builder.GetMatrix(), DlMatrix()); + + EXPECT_EQ(builder.GetLocalClipCoverage(), cull_rect); + EXPECT_EQ(builder.GetDestinationClipCoverage(), cull_rect); + + EXPECT_EQ(builder.GetSaveCount(), 1); + } + + typedef const std::function DlSetup; + typedef const std::function DlRenderer; + + static void verify_inverted_bounds(DlSetup& setup, + DlRenderer& renderer, + DlPaint paint, + DlRect render_rect, + DlRect expected_bounds, + const std::string& desc) { + DisplayListBuilder builder; + setup(builder); + renderer(builder, paint, render_rect); + auto dl = builder.Build(); + EXPECT_EQ(dl->op_count(), 1u) << desc; + EXPECT_EQ(dl->GetBounds(), expected_bounds) << desc; + } + + static void check_inverted_bounds(DlRenderer& renderer, + const std::string& desc) { + DlRect rect = DlRect::MakeLTRB(0.0f, 0.0f, 10.0f, 10.0f); + DlRect invertedLR = DlRect::MakeLTRB(rect.GetRight(), rect.GetTop(), + rect.GetLeft(), rect.GetBottom()); + DlRect invertedTB = DlRect::MakeLTRB(rect.GetLeft(), rect.GetBottom(), + rect.GetRight(), rect.GetTop()); + DlRect invertedLTRB = DlRect::MakeLTRB(rect.GetRight(), rect.GetBottom(), + rect.GetLeft(), rect.GetTop()); + auto empty_setup = [](DlCanvas&) {}; + + ASSERT_TRUE(rect.GetLeft() < rect.GetRight()); + ASSERT_TRUE(rect.GetTop() < rect.GetBottom()); + ASSERT_FALSE(rect.IsEmpty()); + ASSERT_TRUE(invertedLR.GetLeft() > invertedLR.GetRight()); + ASSERT_TRUE(invertedLR.IsEmpty()); + ASSERT_TRUE(invertedTB.GetTop() > invertedTB.GetBottom()); + ASSERT_TRUE(invertedTB.IsEmpty()); + ASSERT_TRUE(invertedLTRB.GetLeft() > invertedLTRB.GetRight()); + ASSERT_TRUE(invertedLTRB.GetTop() > invertedLTRB.GetBottom()); + ASSERT_TRUE(invertedLTRB.IsEmpty()); + + DlPaint ref_paint = DlPaint(); + DlRect ref_bounds = rect; + verify_inverted_bounds(empty_setup, renderer, ref_paint, invertedLR, + ref_bounds, desc + " LR swapped"); + verify_inverted_bounds(empty_setup, renderer, ref_paint, invertedTB, + ref_bounds, desc + " TB swapped"); + verify_inverted_bounds(empty_setup, renderer, ref_paint, invertedLTRB, + ref_bounds, desc + " LR&TB swapped"); + + // Round joins are used because miter joins greatly pad the bounds, + // but only on paths. So we use round joins for consistency there. + // We aren't fully testing all stroke-related bounds computations here, + // those are more fully tested in the render tests. We are simply + // checking that they are applied to the ordered bounds. + DlPaint stroke_paint = DlPaint() // + .setDrawStyle(DlDrawStyle::kStroke) // + .setStrokeJoin(DlStrokeJoin::kRound) // + .setStrokeWidth(2.0f); + DlRect stroke_bounds = rect.Expand(1.0f, 1.0f); + verify_inverted_bounds(empty_setup, renderer, stroke_paint, invertedLR, + stroke_bounds, desc + " LR swapped, sw 2"); + verify_inverted_bounds(empty_setup, renderer, stroke_paint, invertedTB, + stroke_bounds, desc + " TB swapped, sw 2"); + verify_inverted_bounds(empty_setup, renderer, stroke_paint, invertedLTRB, + stroke_bounds, desc + " LR&TB swapped, sw 2"); + + DlBlurMaskFilter mask_filter(DlBlurStyle::kNormal, 2.0f); + DlPaint maskblur_paint = DlPaint() // + .setMaskFilter(&mask_filter); + DlRect maskblur_bounds = rect.Expand(6.0f, 6.0f); + verify_inverted_bounds(empty_setup, renderer, maskblur_paint, invertedLR, + maskblur_bounds, desc + " LR swapped, mask 2"); + verify_inverted_bounds(empty_setup, renderer, maskblur_paint, invertedTB, + maskblur_bounds, desc + " TB swapped, mask 2"); + verify_inverted_bounds(empty_setup, renderer, maskblur_paint, invertedLTRB, + maskblur_bounds, desc + " LR&TB swapped, mask 2"); + + DlErodeImageFilter erode_filter(2.0f, 2.0f); + DlPaint erode_paint = DlPaint() // + .setImageFilter(&erode_filter); + DlRect erode_bounds = rect.Expand(-2.0f, -2.0f); + verify_inverted_bounds(empty_setup, renderer, erode_paint, invertedLR, + erode_bounds, desc + " LR swapped, erode 2"); + verify_inverted_bounds(empty_setup, renderer, erode_paint, invertedTB, + erode_bounds, desc + " TB swapped, erode 2"); + verify_inverted_bounds(empty_setup, renderer, erode_paint, invertedLTRB, + erode_bounds, desc + " LR&TB swapped, erode 2"); + } + + private: + FML_DISALLOW_COPY_AND_ASSIGN(DisplayListTestBase); +}; +using DisplayListTest = DisplayListTestBase<::testing::Test>; + +TEST_F(DisplayListTest, Defaults) { + DisplayListBuilder builder; + check_defaults(builder); +} + +TEST_F(DisplayListTest, EmptyBuild) { + DisplayListBuilder builder; + auto dl = builder.Build(); + EXPECT_EQ(dl->op_count(), 0u); + EXPECT_EQ(dl->bytes(), sizeof(DisplayList)); + EXPECT_EQ(dl->total_depth(), 0u); +} + +TEST_F(DisplayListTest, EmptyRebuild) { + DisplayListBuilder builder; + auto dl1 = builder.Build(); + auto dl2 = builder.Build(); + auto dl3 = builder.Build(); + ASSERT_TRUE(dl1->Equals(dl2)); + ASSERT_TRUE(dl2->Equals(dl3)); +} + +TEST_F(DisplayListTest, NopReusedBuildIsReallyEmpty) { + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(0.0f, 0.0f, 10.0f, 10.0f), DlPaint()); + + { + auto dl1 = builder.Build(); + EXPECT_EQ(dl1->op_count(), 1u); + EXPECT_GT(dl1->bytes(), sizeof(DisplayList)); + EXPECT_EQ(dl1->GetBounds(), DlRect::MakeLTRB(0.0f, 0.0f, 10.0f, 10.0f)); + } + + { + auto dl2 = builder.Build(); + EXPECT_EQ(dl2->op_count(), 0u); + EXPECT_EQ(dl2->bytes(), sizeof(DisplayList)); + EXPECT_EQ(dl2->GetBounds(), DlRect()); + } +} + +TEST_F(DisplayListTest, GeneralReceiverInitialValues) { + DisplayListGeneralReceiver receiver; + + EXPECT_EQ(receiver.GetOpsReceived(), 0u); + + auto max_type = static_cast(DisplayListOpType::kMaxOp); + for (int i = 0; i <= max_type; i++) { + DisplayListOpType type = static_cast(i); + EXPECT_EQ(receiver.GetOpsReceived(type), 0u) << type; + } + + auto max_category = static_cast(DisplayListOpCategory::kMaxCategory); + for (int i = 0; i <= max_category; i++) { + DisplayListOpCategory category = static_cast(i); + EXPECT_EQ(receiver.GetOpsReceived(category), 0u) << category; + } +} + +TEST_F(DisplayListTest, Iteration) { + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + auto dl = builder.Build(); + for (DlIndex i : *dl) { + EXPECT_EQ(dl->GetOpType(i), DisplayListOpType::kDrawRect) // + << "at " << i; + EXPECT_EQ(dl->GetOpCategory(i), DisplayListOpCategory::kRendering) + << "at " << i; + } +} + +TEST_F(DisplayListTest, InvalidIndices) { + DisplayListBuilder builder; + builder.DrawRect(kTestBounds, DlPaint()); + auto dl = builder.Build(); + DisplayListGeneralReceiver receiver; + + EXPECT_FALSE(dl->Dispatch(receiver, -1)); + EXPECT_FALSE(dl->Dispatch(receiver, dl->GetRecordCount())); + EXPECT_EQ(dl->GetOpType(-1), DisplayListOpType::kInvalidOp); + EXPECT_EQ(dl->GetOpType(dl->GetRecordCount()), DisplayListOpType::kInvalidOp); + EXPECT_EQ(dl->GetOpCategory(-1), DisplayListOpCategory::kInvalidCategory); + EXPECT_EQ(dl->GetOpCategory(dl->GetRecordCount()), + DisplayListOpCategory::kInvalidCategory); + EXPECT_EQ(dl->GetOpCategory(-1), DisplayListOpCategory::kInvalidCategory); + EXPECT_EQ(dl->GetOpCategory(DisplayListOpType::kInvalidOp), + DisplayListOpCategory::kInvalidCategory); + EXPECT_EQ(dl->GetOpCategory(DisplayListOpType::kMaxOp), + DisplayListOpCategory::kInvalidCategory); + EXPECT_EQ(receiver.GetOpsReceived(), 0u); +} + +TEST_F(DisplayListTest, ValidIndices) { + DisplayListBuilder builder; + builder.DrawRect(kTestBounds, DlPaint()); + auto dl = builder.Build(); + DisplayListGeneralReceiver receiver; + + EXPECT_EQ(dl->GetRecordCount(), 1u); + EXPECT_TRUE(dl->Dispatch(receiver, 0u)); + EXPECT_EQ(dl->GetOpType(0u), DisplayListOpType::kDrawRect); + EXPECT_EQ(dl->GetOpCategory(0u), DisplayListOpCategory::kRendering); + EXPECT_EQ(receiver.GetOpsReceived(), 1u); +} + +TEST_F(DisplayListTest, BuilderCanBeReused) { + DisplayListBuilder builder(kTestBounds); + builder.DrawRect(kTestBounds, DlPaint()); + auto dl = builder.Build(); + builder.DrawRect(kTestBounds, DlPaint()); + auto dl2 = builder.Build(); + ASSERT_TRUE(dl->Equals(dl2)); +} + +TEST_F(DisplayListTest, SaveRestoreRestoresTransform) { + DlRect cull_rect = DlRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); + DisplayListBuilder builder(cull_rect); + + builder.Save(); + builder.Translate(10.0f, 10.0f); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + builder.Scale(10.0f, 10.0f); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + builder.Skew(0.1f, 0.1f); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + builder.Rotate(45.0f); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + builder.Transform(DlMatrix::MakeScale({10.0f, 10.0f, 1.0f})); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + builder.Transform2DAffine(1.0f, 0.0f, 12.0f, // + 0.0f, 1.0f, 35.0f); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + 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.Restore(); + check_defaults(builder, cull_rect); +} + +TEST_F(DisplayListTest, BuildRestoresTransform) { + DlRect cull_rect = DlRect::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(DlMatrix::MakeScale({10.0f, 10.0f, 1.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.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) { + DlRect cull_rect = DlRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); + DisplayListBuilder builder(cull_rect); + + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0.0f, 0.0f, 10.0f, 10.0f)); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + builder.ClipRoundRect(DlRoundRect::MakeRectXY( + DlRect::MakeLTRB(0.0f, 0.0f, 5.0f, 5.0f), 2.0f, 2.0f)); + builder.Restore(); + check_defaults(builder, cull_rect); + + builder.Save(); + builder.ClipPath(DlPath::MakeOvalLTRB(0.0f, 0.0f, 10.0f, 10.0f)); + builder.Restore(); + check_defaults(builder, cull_rect); +} + +TEST_F(DisplayListTest, BuildRestoresClip) { + DlRect cull_rect = DlRect::MakeLTRB(-10.0f, -10.0f, 500.0f, 500.0f); + DisplayListBuilder builder(cull_rect); + + builder.ClipRect(DlRect::MakeLTRB(0.0f, 0.0f, 10.0f, 10.0f)); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.ClipRoundRect(DlRoundRect::MakeRectXY( + DlRect::MakeLTRB(0.0f, 0.0f, 5.0f, 5.0f), 2.0f, 2.0f)); + builder.Build(); + check_defaults(builder, cull_rect); + + builder.ClipPath(DlPath::MakeOvalLTRB(0.0f, 0.0f, 10.0f, 10.0f)); + builder.Build(); + check_defaults(builder, cull_rect); +} + +TEST_F(DisplayListTest, BuildRestoresAttributes) { + DlRect cull_rect = DlRect::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.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.get()); + builder.Build(); + check_defaults(builder, cull_rect); + + receiver.setColorFilter(kTestMatrixColorFilter1.get()); + 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); +} + +TEST_F(DisplayListTest, BuilderBoundsTransformComparedToSkia) { + const DlRect frame_rect = DlRect::MakeLTRB(10, 10, 100, 100); + DisplayListBuilder builder(frame_rect); + ASSERT_EQ(builder.GetDestinationClipCoverage(), frame_rect); + ASSERT_EQ(builder.GetLocalClipCoverage(), frame_rect); + ASSERT_EQ(builder.GetMatrix(), DlMatrix()); +} + +TEST_F(DisplayListTest, BuilderInitialClipBounds) { + DlRect cull_rect = DlRect::MakeWH(100, 100); + DlRect clip_bounds = DlRect::MakeWH(100, 100); + DisplayListBuilder builder(cull_rect); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); +} + +TEST_F(DisplayListTest, BuilderInitialClipBoundsNaN) { + auto NaN = std::numeric_limits::quiet_NaN(); + DlRect cull_rect = DlRect::MakeWH(NaN, NaN); + DlRect clip_bounds = DlRect(); + DisplayListBuilder builder(cull_rect); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); +} + +TEST_F(DisplayListTest, BuilderClipBoundsAfterClipRect) { + DlRect cull_rect = DlRect::MakeWH(100, 100); + DlRect clip_rect = DlRect::MakeLTRB(10, 10, 20, 20); + DlRect clip_bounds = DlRect::MakeLTRB(10, 10, 20, 20); + DisplayListBuilder builder(cull_rect); + builder.ClipRect(clip_rect, DlClipOp::kIntersect, false); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); +} + +TEST_F(DisplayListTest, BuilderClipBoundsAfterClipRRect) { + DlRect cull_rect = DlRect::MakeWH(100, 100); + DlRect clip_rect = DlRect::MakeLTRB(10, 10, 20, 20); + DlRoundRect clip_rrect = DlRoundRect::MakeRectXY(clip_rect, 2, 2); + DlRect clip_bounds = DlRect::MakeLTRB(10, 10, 20, 20); + DisplayListBuilder builder(cull_rect); + builder.ClipRoundRect(clip_rrect, DlClipOp::kIntersect, false); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); +} + +TEST_F(DisplayListTest, BuilderClipBoundsAfterClipPath) { + DlRect cull_rect = DlRect::MakeWH(100, 100); + DlPath clip_path = DlPath::MakeRectLTRB(10, 10, 15, 15) + + DlPath::MakeRectLTRB(15, 15, 20, 20); + DlRect clip_bounds = DlRect::MakeLTRB(10, 10, 20, 20); + DisplayListBuilder builder(cull_rect); + builder.ClipPath(clip_path, DlClipOp::kIntersect, false); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); +} + +TEST_F(DisplayListTest, BuilderInitialClipBoundsNonZero) { + DlRect cull_rect = DlRect::MakeLTRB(10, 10, 100, 100); + DlRect clip_bounds = DlRect::MakeLTRB(10, 10, 100, 100); + DisplayListBuilder builder(cull_rect); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); +} + +TEST_F(DisplayListTest, UnclippedSaveLayerContentAccountsForFilter) { + DlRect cull_rect = DlRect::MakeLTRB(0.0f, 0.0f, 300.0f, 300.0f); + DlRect clip_rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlRect draw_rect = DlRect::MakeLTRB(50.0f, 140.0f, 101.0f, 160.0f); + auto filter = DlImageFilter::MakeBlur(10.0f, 10.0f, DlTileMode::kDecal); + DlPaint layer_paint = DlPaint().setImageFilter(filter); + + ASSERT_TRUE(clip_rect.IntersectsWithRect(draw_rect)); + ASSERT_TRUE(cull_rect.Contains(clip_rect)); + ASSERT_TRUE(cull_rect.Contains(draw_rect)); + + DisplayListBuilder builder; + builder.Save(); + { + builder.ClipRect(clip_rect, DlClipOp::kIntersect, false); + builder.SaveLayer(cull_rect, &layer_paint); + { // + builder.DrawRect(draw_rect, DlPaint()); + } + builder.Restore(); + } + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->op_count(), 6u); + EXPECT_EQ(display_list->total_depth(), 2u); + + DlRect result_rect = draw_rect.Expand(30.0f, 30.0f); + ASSERT_TRUE(result_rect.IntersectsWithRect(clip_rect)); + result_rect = result_rect.IntersectionOrEmpty(clip_rect); + ASSERT_EQ(result_rect, DlRect::MakeLTRB(100.0f, 110.0f, 131.0f, 190.0f)); + EXPECT_EQ(display_list->GetBounds(), result_rect); +} + +TEST_F(DisplayListTest, ClippedSaveLayerContentAccountsForFilter) { + DlRect cull_rect = DlRect::MakeLTRB(0.0f, 0.0f, 300.0f, 300.0f); + DlRect clip_rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlRect draw_rect = DlRect::MakeLTRB(50.0f, 140.0f, 99.0f, 160.0f); + auto filter = DlImageFilter::MakeBlur(10.0f, 10.0f, DlTileMode::kDecal); + DlPaint layer_paint = DlPaint().setImageFilter(filter); + + ASSERT_FALSE(clip_rect.IntersectsWithRect(draw_rect)); + ASSERT_TRUE(cull_rect.Contains(clip_rect)); + ASSERT_TRUE(cull_rect.Contains(draw_rect)); + + DisplayListBuilder builder; + builder.Save(); + { + builder.ClipRect(clip_rect, DlClipOp::kIntersect, false); + builder.SaveLayer(cull_rect, &layer_paint); + { // + builder.DrawRect(draw_rect, DlPaint()); + } + builder.Restore(); + } + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->op_count(), 6u); + EXPECT_EQ(display_list->total_depth(), 2u); + + DlRect result_rect = draw_rect.Expand(30.0f, 30.0f); + ASSERT_TRUE(result_rect.IntersectsWithRect(clip_rect)); + result_rect = result_rect.IntersectionOrEmpty(clip_rect); + ASSERT_EQ(result_rect, DlRect::MakeLTRB(100.0f, 110.0f, 129.0f, 190.0f)); + EXPECT_EQ(display_list->GetBounds(), result_rect); +} + +TEST_F(DisplayListTest, OOBSaveLayerContentCulledWithBlurFilter) { + DlRect cull_rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlRect draw_rect = DlRect::MakeLTRB(25.0f, 25.0f, 99.0f, 75.0f); + auto filter = DlImageFilter::MakeBlur(10.0f, 10.0f, DlTileMode::kDecal); + DlPaint layer_paint = DlPaint().setImageFilter(filter); + + // We want a draw rect that is outside the layer bounds even though its + // filtered output might be inside. The drawn rect should be culled by + // the expectations of the layer bounds even though it is close enough + // to be visible due to filtering. + ASSERT_FALSE(cull_rect.IntersectsWithRect(draw_rect)); + DlRect mapped_rect; + ASSERT_TRUE(filter->map_local_bounds(draw_rect, mapped_rect)); + ASSERT_TRUE(mapped_rect.IntersectsWithRect(cull_rect)); + + DisplayListBuilder builder; + builder.SaveLayer(cull_rect, &layer_paint); + { // + builder.DrawRect(draw_rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->op_count(), 2u); + EXPECT_EQ(display_list->total_depth(), 1u); + + EXPECT_TRUE(display_list->bounds().isEmpty()) << display_list->bounds(); +} + +TEST_F(DisplayListTest, OOBSaveLayerContentCulledWithMatrixFilter) { + DlRect cull_rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlRect draw_rect = DlRect::MakeLTRB(25.0f, 125.0f, 75.0f, 175.0f); + auto filter = DlImageFilter::MakeMatrix( + DlMatrix::MakeTranslation({100.0f, 0.0f}), DlImageSampling::kLinear); + DlPaint layer_paint = DlPaint().setImageFilter(filter); + + // We want a draw rect that is outside the layer bounds even though its + // filtered output might be inside. The drawn rect should be culled by + // the expectations of the layer bounds even though it is close enough + // to be visible due to filtering. + ASSERT_FALSE(cull_rect.IntersectsWithRect(draw_rect)); + DlRect mapped_rect; + ASSERT_TRUE(filter->map_local_bounds(draw_rect, mapped_rect)); + ASSERT_TRUE(mapped_rect.IntersectsWithRect(cull_rect)); + + DisplayListBuilder builder; + builder.SaveLayer(cull_rect, &layer_paint); + { // + builder.DrawRect(draw_rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->op_count(), 2u); + EXPECT_EQ(display_list->total_depth(), 1u); + + EXPECT_TRUE(display_list->bounds().isEmpty()) << display_list->bounds(); +} + +TEST_F(DisplayListTest, SingleOpSizes) { + for (auto& group : allGroups) { + for (size_t i = 0; i < group.variants.size(); i++) { + 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; + EXPECT_EQ(dl->total_depth(), invocation.depth_accumulated()) << desc; + } + } +} + +TEST_F(DisplayListTest, SingleOpDisplayListsNotEqualEmpty) { + sk_sp empty = DisplayListBuilder().Build(); + for (auto& group : allGroups) { + for (size_t i = 0; i < group.variants.size(); i++) { + sk_sp dl = Build(group.variants[i]); + auto desc = + group.op_name + "(variant " + std::to_string(i + 1) + " != empty)"; + if (group.variants[i].is_empty()) { + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, empty)); + ASSERT_TRUE(empty->Equals(*dl)) << desc; + } else { + ASSERT_TRUE(DisplayListsNE_Verbose(dl, empty)); + ASSERT_FALSE(empty->Equals(*dl)) << desc; + } + } + } +} + +TEST_F(DisplayListTest, SingleOpDisplayListsRecapturedAreEqual) { + for (auto& group : allGroups) { + for (size_t i = 0; i < group.variants.size(); i++) { + sk_sp dl = Build(group.variants[i]); + // Verify recapturing the replay of the display list is Equals() + // when dispatching directly from the DL to another builder + DisplayListBuilder copy_builder; + DlOpReceiver& r = ToReceiver(copy_builder); + dl->Dispatch(r); + sk_sp copy = copy_builder.Build(); + auto desc = + group.op_name + "(variant " + std::to_string(i + 1) + " == copy)"; + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, copy)); + ASSERT_EQ(copy->op_count(false), dl->op_count(false)) << desc; + ASSERT_EQ(copy->GetRecordCount(), dl->GetRecordCount()); + ASSERT_EQ(copy->bytes(false), dl->bytes(false)) << desc; + ASSERT_EQ(copy->op_count(true), dl->op_count(true)) << desc; + ASSERT_EQ(copy->bytes(true), dl->bytes(true)) << desc; + ASSERT_EQ(copy->total_depth(), dl->total_depth()) << desc; + ASSERT_EQ(copy->bounds(), dl->bounds()) << desc; + ASSERT_TRUE(copy->Equals(*dl)) << desc; + ASSERT_TRUE(dl->Equals(*copy)) << desc; + } + } +} + +TEST_F(DisplayListTest, SingleOpDisplayListsRecapturedByIndexAreEqual) { + for (auto& group : allGroups) { + for (size_t i = 0; i < group.variants.size(); i++) { + sk_sp dl = Build(group.variants[i]); + // Verify recapturing the replay of the display list is Equals() + // when dispatching directly from the DL to another builder + DisplayListBuilder copy_builder; + DlOpReceiver& r = ToReceiver(copy_builder); + for (DlIndex i = 0; i < dl->GetRecordCount(); i++) { + EXPECT_NE(dl->GetOpType(i), DisplayListOpType::kInvalidOp); + EXPECT_NE(dl->GetOpCategory(i), + DisplayListOpCategory::kInvalidCategory); + EXPECT_TRUE(dl->Dispatch(r, i)); + } + sk_sp copy = copy_builder.Build(); + auto desc = + group.op_name + "(variant " + std::to_string(i + 1) + " == copy)"; + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, copy)); + ASSERT_EQ(copy->op_count(false), dl->op_count(false)) << desc; + ASSERT_EQ(copy->GetRecordCount(), dl->GetRecordCount()); + ASSERT_EQ(copy->bytes(false), dl->bytes(false)) << desc; + ASSERT_EQ(copy->op_count(true), dl->op_count(true)) << desc; + ASSERT_EQ(copy->bytes(true), dl->bytes(true)) << desc; + ASSERT_EQ(copy->total_depth(), dl->total_depth()) << desc; + ASSERT_EQ(copy->bounds(), dl->bounds()) << desc; + ASSERT_TRUE(copy->Equals(*dl)) << desc; + ASSERT_TRUE(dl->Equals(*copy)) << desc; + } + } +} + +TEST_F(DisplayListTest, SingleOpDisplayListsCompareToEachOther) { + for (auto& group : allGroups) { + std::vector> lists_a; + std::vector> lists_b; + for (size_t i = 0; i < group.variants.size(); i++) { + lists_a.push_back(Build(group.variants[i])); + lists_b.push_back(Build(group.variants[i])); + } + + for (size_t i = 0; i < lists_a.size(); i++) { + sk_sp listA = lists_a[i]; + for (size_t j = 0; j < lists_b.size(); j++) { + sk_sp listB = lists_b[j]; + auto desc = group.op_name + "(variant " + std::to_string(i + 1) + + " ==? variant " + std::to_string(j + 1) + ")"; + if (i == j || + (group.variants[i].is_empty() && group.variants[j].is_empty())) { + // They are the same variant, or both variants are NOPs + ASSERT_EQ(listA->op_count(false), listB->op_count(false)) << desc; + ASSERT_EQ(listA->bytes(false), listB->bytes(false)) << desc; + ASSERT_EQ(listA->op_count(true), listB->op_count(true)) << desc; + ASSERT_EQ(listA->bytes(true), listB->bytes(true)) << desc; + EXPECT_EQ(listA->total_depth(), listB->total_depth()) << desc; + ASSERT_EQ(listA->bounds(), listB->bounds()) << desc; + ASSERT_TRUE(listA->Equals(*listB)) << desc; + ASSERT_TRUE(listB->Equals(*listA)) << desc; + } else { + // No assertion on op/byte counts or bounds + // they may or may not be equal between variants + ASSERT_FALSE(listA->Equals(*listB)) << desc; + ASSERT_FALSE(listB->Equals(*listA)) << desc; + } + } + } + } +} + +TEST_F(DisplayListTest, SingleOpDisplayListsAreEqualWithOrWithoutRtree) { + for (auto& group : allGroups) { + for (size_t i = 0; i < group.variants.size(); i++) { + DisplayListBuilder builder1(/*prepare_rtree=*/false); + DisplayListBuilder builder2(/*prepare_rtree=*/true); + group.variants[i].Invoke(ToReceiver(builder1)); + group.variants[i].Invoke(ToReceiver(builder2)); + sk_sp dl1 = builder1.Build(); + sk_sp dl2 = builder2.Build(); + + auto desc = group.op_name + "(variant " + std::to_string(i + 1) + " )"; + ASSERT_EQ(dl1->op_count(false), dl2->op_count(false)) << desc; + ASSERT_EQ(dl1->bytes(false), dl2->bytes(false)) << desc; + ASSERT_EQ(dl1->op_count(true), dl2->op_count(true)) << desc; + ASSERT_EQ(dl1->bytes(true), dl2->bytes(true)) << desc; + EXPECT_EQ(dl1->total_depth(), dl2->total_depth()) << desc; + ASSERT_EQ(dl1->bounds(), dl2->bounds()) << desc; + ASSERT_EQ(dl1->total_depth(), dl2->total_depth()) << desc; + ASSERT_TRUE(DisplayListsEQ_Verbose(dl1, dl2)) << desc; + ASSERT_TRUE(DisplayListsEQ_Verbose(dl2, dl2)) << desc; + ASSERT_EQ(dl1->rtree().get(), nullptr) << desc; + ASSERT_NE(dl2->rtree().get(), nullptr) << desc; + } + } +} + +TEST_F(DisplayListTest, FullRotationsAreNop) { + DisplayListBuilder builder; + builder.Rotate(0); + builder.Rotate(360); + builder.Rotate(720); + builder.Rotate(1080); + builder.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); + EXPECT_EQ(dl->total_depth(), 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)); + ASSERT_EQ(dl->op_count(false), 0u); + ASSERT_EQ(dl->op_count(true), 0u); + EXPECT_EQ(dl->total_depth(), 0u); +} + +TEST_F(DisplayListTest, DisplayListsWithVaryingOpComparisons) { + sk_sp default_dl = Build(allGroups.size(), 0); + ASSERT_TRUE(default_dl->Equals(*default_dl)) << "Default == itself"; + for (size_t gi = 0; gi < allGroups.size(); gi++) { + DisplayListInvocationGroup& group = allGroups[gi]; + sk_sp missing_dl = Build(gi, group.variants.size()); + auto desc = "[Group " + group.op_name + " omitted]"; + ASSERT_TRUE(missing_dl->Equals(*missing_dl)) << desc << " == itself"; + ASSERT_FALSE(missing_dl->Equals(*default_dl)) << desc << " != Default"; + ASSERT_FALSE(default_dl->Equals(*missing_dl)) << "Default != " << desc; + for (size_t vi = 0; vi < group.variants.size(); vi++) { + auto desc = "[Group " + group.op_name + " variant " + + std::to_string(vi + 1) + "]"; + sk_sp variant_dl = Build(gi, vi); + ASSERT_TRUE(variant_dl->Equals(*variant_dl)) << desc << " == itself"; + if (vi == 0) { + ASSERT_TRUE(variant_dl->Equals(*default_dl)) << desc << " == Default"; + ASSERT_TRUE(default_dl->Equals(*variant_dl)) << "Default == " << desc; + } else { + ASSERT_FALSE(variant_dl->Equals(*default_dl)) << desc << " != Default"; + ASSERT_FALSE(default_dl->Equals(*variant_dl)) << "Default != " << desc; + } + if (group.variants[vi].is_empty()) { + ASSERT_TRUE(variant_dl->Equals(*missing_dl)) << desc << " != omitted"; + ASSERT_TRUE(missing_dl->Equals(*variant_dl)) << "omitted != " << desc; + } else { + ASSERT_FALSE(variant_dl->Equals(*missing_dl)) << desc << " != omitted"; + ASSERT_FALSE(missing_dl->Equals(*variant_dl)) << "omitted != " << desc; + } + } + } +} + +TEST_F(DisplayListTest, DisplayListSaveLayerBoundsWithAlphaFilter) { + DlRect build_bounds = DlRect::MakeLTRB(-100, -100, 200, 200); + DlRect save_bounds = DlRect::MakeWH(100, 100); + DlRect rect = DlRect::MakeLTRB(30, 30, 70, 70); + // clang-format off + const float color_matrix[] = { + 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, + }; + // clang-format on + auto base_color_filter = DlColorFilter::MakeMatrix(color_matrix); + // clang-format off + const float alpha_matrix[] = { + 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 1, + }; + // clang-format on + auto alpha_color_filter = DlColorFilter::MakeMatrix(alpha_matrix); + + { + // No tricky stuff, just verifying drawing a rect produces rect bounds + DisplayListBuilder builder(build_bounds); + builder.SaveLayer(save_bounds, nullptr); + builder.DrawRect(rect, DlPaint()); + builder.Restore(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), rect); + } + + { + // 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(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), rect); + } + + { + // Now checking that DisplayList returns the 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(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), build_bounds); + } + + { + // 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(std::nullopt, &save_paint); + builder.DrawRect(rect, DlPaint()); + builder.Restore(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), build_bounds); + } + + { + // Making sure hiding a ColorFilter as an ImageFilter will + // generate the same behavior as setting it as a ColorFilter + DisplayListBuilder builder(build_bounds); + DlColorFilterImageFilter color_filter_image_filter(base_color_filter); + DlPaint save_paint; + save_paint.setImageFilter(&color_filter_image_filter); + builder.SaveLayer(save_bounds, &save_paint); + builder.DrawRect(rect, DlPaint()); + builder.Restore(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), rect); + } + + { + // Making sure hiding a problematic ColorFilter as an ImageFilter + // will generate the same behavior as setting it as a ColorFilter + DisplayListBuilder builder(build_bounds); + DlColorFilterImageFilter color_filter_image_filter(alpha_color_filter); + DlPaint save_paint; + save_paint.setImageFilter(&color_filter_image_filter); + builder.SaveLayer(save_bounds, &save_paint); + builder.DrawRect(rect, DlPaint()); + builder.Restore(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), build_bounds); + } + + { + // Same as above (ImageFilter hiding ColorFilter) with no save bounds + DisplayListBuilder builder(build_bounds); + DlColorFilterImageFilter color_filter_image_filter(alpha_color_filter); + DlPaint save_paint; + save_paint.setImageFilter(&color_filter_image_filter); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(rect, DlPaint()); + builder.Restore(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), build_bounds); + } + + { + // 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(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), build_bounds); + } + + { + // Same as previous with no save bounds + DisplayListBuilder builder(build_bounds); + DlPaint save_paint; + save_paint.setBlendMode(DlBlendMode::kClear); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(rect, DlPaint()); + builder.Restore(); + sk_sp display_list = builder.Build(); + ASSERT_EQ(display_list->GetBounds(), build_bounds); + } +} + +TEST_F(DisplayListTest, NestedOpCountMetrics) { + DisplayListBuilder builder(DlRect::MakeWH(150, 100)); + DlPaint dl_paint; + for (int y = 10; y <= 60; y += 10) { + for (int x = 10; x <= 60; x += 10) { + dl_paint.setColor(((x + y) % 20) == 10 ? DlColor::kRed() + : DlColor::kBlue()); + builder.DrawRect(DlRect::MakeXYWH(x, y, 80, 80), dl_paint); + } + } + + DisplayListBuilder outer_builder(DlRect::MakeWH(150, 100)); + outer_builder.DrawDisplayList(builder.Build()); + auto display_list = outer_builder.Build(); + + ASSERT_EQ(display_list->op_count(), 1u); + ASSERT_EQ(display_list->op_count(true), 36u); + EXPECT_EQ(display_list->total_depth(), 37u); +} + +TEST_F(DisplayListTest, DisplayListFullPerspectiveTransformHandling) { + auto matrix = DlMatrix::MakeRow( + // clang-format off + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12, + 13, 14, 15, 16 + // clang-format on + ); + + { // First test == + DisplayListBuilder builder; + // builder.TransformFullPerspective takes row-major order + builder.TransformFullPerspective( + // clang-format off + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12, + 13, 14, 15, 16 + // clang-format on + ); + DlMatrix dl_matrix = builder.GetMatrix(); + ASSERT_EQ(dl_matrix, matrix); + } + { // Next test != + DisplayListBuilder builder; + // builder.TransformFullPerspective takes row-major order + builder.TransformFullPerspective( + // clang-format off + 1, 5, 9, 13, + 2, 6, 7, 11, + 3, 7, 11, 15, + 4, 8, 12, 16 + // clang-format on + ); + DlMatrix dl_matrix = builder.GetMatrix(); + ASSERT_NE(dl_matrix, matrix); + } +} + +TEST_F(DisplayListTest, DisplayListTransformResetHandling) { + DisplayListBuilder builder; + builder.Scale(20.0, 20.0); + builder.TransformReset(); + ASSERT_TRUE(builder.GetMatrix().IsIdentity()); +} + +TEST_F(DisplayListTest, SingleOpsMightSupportGroupOpacityBlendMode) { + auto run_tests = [](const std::string& name, + void build(DlCanvas & canvas, const DlPaint& paint), + 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); + auto display_list = builder.Build(); + EXPECT_EQ(display_list->can_apply_group_opacity(), expect_for_op) + << "{" << std::endl + << " " << name << std::endl + << "}"; + } + { + // Second test is the draw op with kSrc, + // (usually fails group opacity) + DisplayListBuilder builder; + DlPaint paint; + paint.setBlendMode(DlBlendMode::kSrc); + build(builder, paint); + auto display_list = builder.Build(); + EXPECT_EQ(display_list->can_apply_group_opacity(), expect_with_kSrc) + << "{" << std::endl + << " receiver.setBlendMode(kSrc);" << std::endl + << " " << name << std::endl + << "}"; + } + }; + +#define RUN_TESTS(body) \ + run_tests( \ + #body, [](DlCanvas& canvas, const DlPaint& paint) { body }, true, false) + +#define RUN_TESTS2(body, expect) \ + run_tests( \ + #body, [](DlCanvas& canvas, const DlPaint& paint) { body }, expect, \ + expect) + + RUN_TESTS(canvas.DrawPaint(paint);); + RUN_TESTS2(canvas.DrawColor(DlColor(SK_ColorRED), DlBlendMode::kSrcOver); + , true); + RUN_TESTS2(canvas.DrawColor(DlColor(SK_ColorRED), DlBlendMode::kSrc);, false); + RUN_TESTS(canvas.DrawLine(DlPoint(0, 0), DlPoint(10, 10), paint);); + RUN_TESTS(canvas.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), paint);); + RUN_TESTS(canvas.DrawOval(DlRect::MakeLTRB(0, 0, 10, 10), paint);); + RUN_TESTS(canvas.DrawCircle(DlPoint(10, 10), 5, paint);); + RUN_TESTS(canvas.DrawRoundRect( + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(0, 0, 10, 10), 2, 2), paint);); + RUN_TESTS(canvas.DrawDiffRoundRect( + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(0, 0, 10, 10), 2, 2), + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(2, 2, 8, 8), 2, 2), paint);); + RUN_TESTS(canvas.DrawPath( + DlPath::MakeOvalLTRB(0, 0, 10, 10) + DlPath::MakeOvalLTRB(5, 5, 15, 15), + paint);); + RUN_TESTS(canvas.DrawArc(DlRect::MakeLTRB(0, 0, 10, 10), 0, math::kPi, true, + paint);); + RUN_TESTS2(canvas.DrawPoints(DlPointMode::kPoints, TestPointCount, + kTestPoints, paint); + , false); + RUN_TESTS2(canvas.DrawVertices(kTestVertices1, DlBlendMode::kSrc, paint); + , false); + RUN_TESTS(canvas.DrawImage(kTestImage1, DlPoint(), kLinearSampling, &paint);); + RUN_TESTS2(canvas.DrawImage(kTestImage1, DlPoint(), kLinearSampling, nullptr); + , true); + RUN_TESTS(canvas.DrawImageRect(kTestImage1, DlIRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(0, 0, 10, 10), + kNearestSampling, &paint, + DlSrcRectConstraint::kFast);); + RUN_TESTS2( + canvas.DrawImageRect(kTestImage1, DlIRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(0, 0, 10, 10), kNearestSampling, + nullptr, DlSrcRectConstraint::kFast); + , true); + RUN_TESTS(canvas.DrawImageNine(kTestImage2, DlIRect::MakeLTRB(20, 20, 30, 30), + DlRect::MakeLTRB(0, 0, 20, 20), + DlFilterMode::kLinear, &paint);); + RUN_TESTS2(canvas.DrawImageNine( + kTestImage2, DlIRect::MakeLTRB(20, 20, 30, 30), + DlRect::MakeLTRB(0, 0, 20, 20), DlFilterMode::kLinear, nullptr); + , true); + static DlRSTransform xforms[] = { + DlRSTransform::Make({0.0f, 0.0f}, 1.0f, DlDegrees(0)), + DlRSTransform::Make({0.0f, 0.0f}, 1.0f, DlDegrees(90)), + }; + static DlRect texs[] = { + DlRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(20, 20, 30, 30), + }; + RUN_TESTS2( + canvas.DrawAtlas(kTestImage1, xforms, texs, nullptr, 2, + DlBlendMode::kSrcIn, kNearestSampling, nullptr, &paint); + , false); + RUN_TESTS2( + canvas.DrawAtlas(kTestImage1, xforms, texs, nullptr, 2, + DlBlendMode::kSrcIn, kNearestSampling, nullptr, nullptr); + , false); + EXPECT_TRUE(TestDisplayList1->can_apply_group_opacity()); + RUN_TESTS2(canvas.DrawDisplayList(TestDisplayList1);, true); + { + static DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), DlPaint()); + builder.DrawRect(DlRect::MakeLTRB(5, 5, 15, 15), DlPaint()); + static auto display_list = builder.Build(); + RUN_TESTS2(canvas.DrawDisplayList(display_list);, false); + } + RUN_TESTS2(canvas.DrawTextBlob(GetTestTextBlob(1), 0, 0, paint);, false); + RUN_TESTS2(canvas.DrawShadow(kTestPath1, DlColor::kBlack(), 1.0, false, 1.0); + , false); + +#undef RUN_TESTS2 +#undef RUN_TESTS +} + +TEST_F(DisplayListTest, OverlappingOpsDoNotSupportGroupOpacity) { + DisplayListBuilder builder; + for (int i = 0; i < 10; i++) { + builder.DrawRect(DlRect::MakeXYWH(i * 10, 0, 30, 30), DlPaint()); + } + auto display_list = builder.Build(); + EXPECT_FALSE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, LineOfNonOverlappingOpsSupportGroupOpacity) { + DisplayListBuilder builder; + for (int i = 0; i < 10; i++) { + builder.DrawRect(DlRect::MakeXYWH(i * 30, 0, 30, 30), DlPaint()); + } + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, CrossOfNonOverlappingOpsSupportGroupOpacity) { + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(200, 200, 300, 300), DlPaint()); // center + builder.DrawRect(DlRect::MakeLTRB(100, 200, 200, 300), DlPaint()); // left + builder.DrawRect(DlRect::MakeLTRB(200, 100, 300, 200), DlPaint()); // above + builder.DrawRect(DlRect::MakeLTRB(300, 200, 400, 300), DlPaint()); // right + builder.DrawRect(DlRect::MakeLTRB(200, 300, 300, 400), DlPaint()); // below + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, SaveLayerFalseSupportsGroupOpacityOverlappingChidren) { + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + for (int i = 0; i < 10; i++) { + builder.DrawRect(DlRect::MakeXYWH(i * 10, 0, 30, 30), DlPaint()); + } + builder.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(std::nullopt, &save_paint); + for (int i = 0; i < 10; i++) { + builder.DrawRect(DlRect::MakeXYWH(i * 10, 0, 30, 30), DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, SaveLayerFalseWithSrcBlendSupportsGroupOpacity) { + DisplayListBuilder builder; + // This empty draw rect will not actually be inserted into the stream, + // but the Src blend mode will be synchronized as an attribute. The + // SaveLayer following it should not use that attribute to base its + // decisions about group opacity and the draw rect after that comes + // with its own compatible blend mode. + builder.DrawRect(DlRect(), DlPaint().setBlendMode(DlBlendMode::kSrc)); + builder.SaveLayer(std::nullopt, nullptr); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), DlPaint()); + builder.Restore(); + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, SaveLayerTrueWithSrcBlendDoesNotSupportGroupOpacity) { + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setBlendMode(DlBlendMode::kSrc); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), DlPaint()); + builder.Restore(); + auto display_list = builder.Build(); + EXPECT_FALSE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, SaveLayerFalseSupportsGroupOpacityWithChildSrcBlend) { + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kSrc)); + builder.Restore(); + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, SaveLayerTrueSupportsGroupOpacityWithChildSrcBlend) { + DisplayListBuilder builder; + DlPaint save_paint; + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kSrc)); + builder.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(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(50, 50, 100, 100), DlPaint()); + // This image filter should be ignored since it was not set before SaveLayer + // And the rect drawn with it will not contribute any more area to the bounds + DlPaint draw_paint; + draw_paint.setImageFilter(&kTestBlurImageFilter1); + builder.DrawRect(DlRect::MakeLTRB(70, 70, 80, 80), draw_paint); + builder.Restore(); + EXPECT_EQ(builder.Build()->GetBounds(), DlRect::MakeLTRB(50, 50, 100, 100)); +} + +#define SAVE_LAYER_EXPECTOR(name) SaveLayerExpector name(__FILE__, __LINE__) + +using SaveLayerOptionsTester = + std::function; + +struct SaveLayerExpectations { + SaveLayerExpectations() {} + + // NOLINTNEXTLINE(google-explicit-constructor) + SaveLayerExpectations(const SaveLayerOptions& o) : options(o) {} + // NOLINTNEXTLINE(google-explicit-constructor) + SaveLayerExpectations(const SaveLayerOptionsTester& t) : tester(t) {} + // NOLINTNEXTLINE(google-explicit-constructor) + SaveLayerExpectations(DlBlendMode mode) : max_blend_mode(mode) {} + + std::optional options; + std::optional tester; + std::optional max_blend_mode; +}; + +::std::ostream& operator<<(::std::ostream& os, + const SaveLayerExpectations& expect) { + os << "SaveLayerExpectation("; + if (expect.options.has_value()) { + os << "options: " << expect.options.value(); + } + if (expect.tester.has_value()) { + os << "option tester: " << &expect.tester.value(); + } + if (expect.max_blend_mode.has_value()) { + os << "max_blend: " << expect.max_blend_mode.value(); + } + os << ")"; + return os; +} + +class SaveLayerExpector : public virtual DlOpReceiver, + public IgnoreAttributeDispatchHelper, + public IgnoreClipDispatchHelper, + public IgnoreTransformDispatchHelper, + public IgnoreDrawDispatchHelper { + public: + SaveLayerExpector(const std::string& file, int line) + : file_(file), line_(line), detail_("") {} + + ~SaveLayerExpector() { // + EXPECT_EQ(save_layer_count_, expected_.size()) << label(); + while (save_layer_count_ < expected_.size()) { + auto expect = expected_[save_layer_count_]; + FML_LOG(ERROR) << "leftover expectation[" << save_layer_count_ + << "] = " << expect; + save_layer_count_++; + } + } + + SaveLayerExpector& addDetail(const std::string& detail) { + detail_ = detail; + return *this; + } + + SaveLayerExpector& addExpectation(const SaveLayerExpectations& expected) { + expected_.push_back(expected); + return *this; + } + + SaveLayerExpector& addExpectation(const SaveLayerOptionsTester& tester) { + expected_.push_back(SaveLayerExpectations(tester)); + return *this; + } + + SaveLayerExpector& addOpenExpectation() { + expected_.push_back(SaveLayerExpectations()); + return *this; + } + + void saveLayer(const DlRect& bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop, + std::optional backdrop_id) override { + FML_UNREACHABLE(); + } + + virtual void saveLayer(const DlRect& bounds, + const SaveLayerOptions& options, + uint32_t total_content_depth, + DlBlendMode max_content_blend_mode, + const DlImageFilter* backdrop = nullptr, + std::optional backdrop_id = std::nullopt) { + ASSERT_LT(save_layer_count_, expected_.size()) << label(); + auto expect = expected_[save_layer_count_]; + if (expect.options.has_value()) { + EXPECT_EQ(options, expect.options.value()) << label(); + } + if (expect.tester.has_value()) { + EXPECT_TRUE(expect.tester.value()(options)) << label(); + } + if (expect.max_blend_mode.has_value()) { + EXPECT_EQ(max_content_blend_mode, expect.max_blend_mode.value()) + << label(); + } + save_layer_count_++; + } + + bool all_expectations_checked() const { + return save_layer_count_ == expected_.size(); + } + + private: + // mutable allows the copy constructor to leave no expectations behind + mutable std::vector expected_; + size_t save_layer_count_ = 0; + + const std::string file_; + const int line_; + std::string detail_; + + std::string label() { + std::string label = "at index " + std::to_string(save_layer_count_) + // + ", from " + file_ + // + ":" + std::to_string(line_); + if (detail_.length() > 0) { + label = label + " (" + detail_ + ")"; + } + return label; + } +}; + +TEST_F(DisplayListTest, SaveLayerOneSimpleOpInheritsOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation( + SaveLayerOptions::kWithAttributes.with_can_distribute_opacity()); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerNoAttributesInheritsOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation( + SaveLayerOptions::kNoAttributes.with_can_distribute_opacity()); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerTwoOverlappingOpsDoesNotInheritOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(SaveLayerOptions::kWithAttributes); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.DrawRect(DlRect::MakeLTRB(15, 15, 25, 25), DlPaint()); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, NestedSaveLayersMightInheritOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector // + .addExpectation( + SaveLayerOptions::kWithAttributes.with_can_distribute_opacity()) + .addExpectation(SaveLayerOptions::kWithAttributes) + .addExpectation( + SaveLayerOptions::kWithAttributes.with_can_distribute_opacity()); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + builder.SaveLayer(std::nullopt, &save_paint); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(15, 15, 25, 25), DlPaint()); + builder.Restore(); + builder.Restore(); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, NestedSaveLayersCanBothSupportOpacityOptimization) { + SAVE_LAYER_EXPECTOR(expector); + expector // + .addExpectation( + SaveLayerOptions::kWithAttributes.with_can_distribute_opacity()) + .addExpectation( + SaveLayerOptions::kNoAttributes.with_can_distribute_opacity()); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + builder.SaveLayer(std::nullopt, &save_paint); + builder.SaveLayer(std::nullopt, nullptr); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Restore(); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerImageFilterDoesNotInheritOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(SaveLayerOptions::kWithAttributes); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + save_paint.setImageFilter(&kTestBlurImageFilter1); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerColorFilterDoesNotInheritOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(SaveLayerOptions::kWithAttributes); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + save_paint.setColorFilter(kTestMatrixColorFilter1); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerSrcBlendDoesNotInheritOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(SaveLayerOptions::kWithAttributes); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + save_paint.setBlendMode(DlBlendMode::kSrc); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerImageFilterOnChildInheritsOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation( + SaveLayerOptions::kWithAttributes.with_can_distribute_opacity()); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + builder.SaveLayer(std::nullopt, &save_paint); + DlPaint draw_paint = save_paint; + draw_paint.setImageFilter(&kTestBlurImageFilter1); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), draw_paint); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerColorFilterOnChildDoesNotInheritOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(SaveLayerOptions::kWithAttributes); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + builder.SaveLayer(std::nullopt, &save_paint); + DlPaint draw_paint = save_paint; + draw_paint.setColorFilter(kTestMatrixColorFilter1); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), draw_paint); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, SaveLayerSrcBlendOnChildDoesNotInheritOpacity) { + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(SaveLayerOptions::kWithAttributes); + + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setColor(DlColor::kWhite().withAlphaF(0.5f)); + builder.SaveLayer(std::nullopt, &save_paint); + DlPaint draw_paint = save_paint; + draw_paint.setBlendMode(DlBlendMode::kSrc); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), draw_paint); + builder.Restore(); + + builder.Build()->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, FlutterSvgIssue661BoundsWereEmpty) { + // See https://github.com/dnfield/flutter_svg/issues/661 + + DlPathBuilder path_builder1; + path_builder1.MoveTo({25.54f, 37.52f}); + path_builder1.CubicCurveTo({20.91f, 37.52f}, // + {16.54f, 33.39f}, // + {13.62f, 30.58f}); + path_builder1.LineTo({13, 30}); + path_builder1.LineTo({12.45f, 29.42f}); + path_builder1.CubicCurveTo({8.39f, 25.15f}, // + {1.61f, 18}, // + {8.37f, 11.27f}); + path_builder1.CubicCurveTo({10.18f, 9.46f}, // + {12.37f, 9.58f}, // + {14.49f, 11.58f}); + path_builder1.CubicCurveTo({15.67f, 12.71f}, // + {17.05f, 14.69f}, // + {17.07f, 16.58f}); + path_builder1.CubicCurveTo({17.0968f, 17.458f}, // + {16.7603f, 18.3081f}, // + {16.14f, 18.93f}); + path_builder1.CubicCurveTo({15.8168f, 19.239f}, // + {15.4653f, 19.5169f}, // + {15.09f, 19.76f}); + path_builder1.CubicCurveTo({14.27f, 20.33f}, // + {14.21f, 20.44f}, // + {14.27f, 20.62f}); + path_builder1.CubicCurveTo({15.1672f, 22.3493f}, // + {16.3239f, 23.9309f}, // + {17.7f, 25.31f}); + path_builder1.CubicCurveTo({19.0791f, 26.6861f}, // + {20.6607f, 27.8428f}, // + {22.39f, 28.74f}); + path_builder1.CubicCurveTo({22.57f, 28.8f}, // + {22.69f, 28.74f}, // + {23.25f, 27.92f}); + path_builder1.CubicCurveTo({23.5f, 27.566f}, // + {23.778f, 27.231f}, // + {24.08f, 26.92f}); + path_builder1.CubicCurveTo({24.7045f, 26.3048f}, // + {25.5538f, 25.9723f}, // + {26.43f, 26}); + path_builder1.CubicCurveTo({28.29f, 26}, // + {30.27f, 27.4f}, // + {31.43f, 28.58f}); + path_builder1.CubicCurveTo({33.43f, 30.67f}, // + {33.55f, 32.9f}, // + {31.74f, 34.7f}); + path_builder1.CubicCurveTo({30.1477f, 36.4508f}, // + {27.906f, 37.4704f}, // + {25.54f, 37.52f}); + path_builder1.Close(); + path_builder1.MoveTo({11.17f, 12.23f}); + path_builder1.CubicCurveTo({10.6946f, 12.2571f}, // + {10.2522f, 12.4819f}, // + {9.95f, 12.85f}); + path_builder1.CubicCurveTo({5.12f, 17.67f}, // + {8.95f, 22.5f}, // + {14.05f, 27.85f}); + path_builder1.LineTo({14.62f, 28.45f}); + path_builder1.LineTo({15.16f, 28.96f}); + path_builder1.CubicCurveTo({20.52f, 34.06f}, // + {25.35f, 37.89f}, // + {30.16f, 33.06f}); + path_builder1.CubicCurveTo({30.83f, 32.39f}, // + {31.25f, 31.56f}, // + {29.81f, 30.06f}); + path_builder1.CubicCurveTo({28.9247f, 29.07f}, // + {27.7359f, 28.4018f}, // + {26.43f, 28.16f}); + path_builder1.CubicCurveTo({26.1476f, 28.1284f}, // + {25.8676f, 28.2367f}, // + {25.68f, 28.45f}); + path_builder1.CubicCurveTo({25.4633f, 28.6774f}, // + {25.269f, 28.9252f}, // + {25.1f, 29.19f}); + path_builder1.CubicCurveTo({24.53f, 30.01f}, // + {23.47f, 31.54f}, // + {21.54f, 30.79f}); + path_builder1.LineTo({21.41f, 30.72f}); + path_builder1.CubicCurveTo({19.4601f, 29.7156f}, // + {17.6787f, 28.4133f}, // + {16.13f, 26.86f}); + path_builder1.CubicCurveTo({14.5748f, 25.3106f}, // + {13.2693f, 23.5295f}, // + {12.26f, 21.58f}); + path_builder1.LineTo({12.2f, 21.44f}); + path_builder1.CubicCurveTo({11.45f, 19.51f}, // + {12.97f, 18.44f}, // + {13.8f, 17.88f}); + path_builder1.CubicCurveTo({14.061f, 17.706f}, // + {14.308f, 17.512f}, // + {14.54f, 17.3f}); + path_builder1.CubicCurveTo({14.7379f, 17.1067f}, // + {14.8404f, 16.8359f}, // + {14.82f, 16.56f}); + path_builder1.CubicCurveTo({14.5978f, 15.268f}, // + {13.9585f, 14.0843f}, // + {13, 13.19f}); + path_builder1.CubicCurveTo({12.5398f, 12.642f}, // + {11.8824f, 12.2971f}, // + {11.17f, 12.23f}); + path_builder1.LineTo({11.17f, 12.23f}); + path_builder1.Close(); + path_builder1.MoveTo({27, 19.34f}); + path_builder1.LineTo({24.74f, 19.34f}); + path_builder1.CubicCurveTo({24.7319f, 18.758f}, // + {24.262f, 18.2881f}, // + {23.68f, 18.28f}); + path_builder1.LineTo({23.68f, 16.05f}); + path_builder1.LineTo({23.7f, 16.05f}); + path_builder1.CubicCurveTo({25.5153f, 16.0582f}, // + {26.9863f, 17.5248f}, // + {27, 19.34f}); + path_builder1.LineTo({27, 19.34f}); + path_builder1.Close(); + path_builder1.MoveTo({32.3f, 19.34f}); + path_builder1.LineTo({30.07f, 19.34f}); + path_builder1.CubicCurveTo({30.037f, 15.859f}, // + {27.171f, 13.011f}, // + {23.69f, 13}); + path_builder1.LineTo({23.69f, 10.72f}); + path_builder1.CubicCurveTo({28.415f, 10.725f}, // + {32.3f, 14.615f}, // + {32.3f, 19.34f}); + path_builder1.Close(); + DlPath dl_path1 = DlPath(path_builder1, DlPathFillType::kNonZero); + + DlPathBuilder path_builder2; + path_builder2.MoveTo({37.5f, 19.33f}); + path_builder2.LineTo({35.27f, 19.33f}); + path_builder2.CubicCurveTo({35.265f, 12.979f}, // + {30.041f, 7.755f}, // + {23.69f, 7.75f}); + path_builder2.LineTo({23.69f, 5.52f}); + path_builder2.CubicCurveTo({31.264f, 5.525f}, // + {37.495f, 11.756f}, // + {37.5f, 19.33f}); + path_builder2.Close(); + DlPath dl_path2 = DlPath(path_builder2, DlPathFillType::kNonZero); + + DisplayListBuilder builder; + DlPaint paint = DlPaint(DlColor::kWhite()).setAntiAlias(true); + { + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 100, 100), DlClipOp::kIntersect, + true); + { + builder.Save(); + builder.Transform2DAffine(2.17391, 0, -2547.83, // + 0, 2.04082, -500); + { + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(1172, 245, 1218, 294), + DlClipOp::kIntersect, true); + { + builder.SaveLayer(std::nullopt, nullptr, nullptr); + { + builder.Save(); + builder.Transform2DAffine(1.4375, 0, 1164.09, // + 0, 1.53125, 236.548); + builder.DrawPath(DlPath(dl_path1), paint); + builder.Restore(); + } + { + builder.Save(); + builder.Transform2DAffine(1.4375, 0, 1164.09, // + 0, 1.53125, 236.548); + builder.DrawPath(DlPath(dl_path2), paint); + builder.Restore(); + } + builder.Restore(); + } + builder.Restore(); + } + builder.Restore(); + } + builder.Restore(); + } + sk_sp display_list = builder.Build(); + // Prior to the fix, the bounds were empty. + EXPECT_FALSE(display_list->bounds().isEmpty()); + // These are just inside and outside of the expected bounds, but + // testing float values can be flaky wrt minor changes in the bounds + // calculations. If these lines have to be revised too often as the DL + // implementation is improved and maintained, then we can eliminate + // this test and just rely on the "rounded out" bounds test that follows. + DlRect min_bounds = DlRect::MakeLTRB(0, 0.00191, 99.983, 100); + DlRect max_bounds = DlRect::MakeLTRB(0, 0.00189, 99.985, 100); + ASSERT_TRUE(max_bounds.Contains(min_bounds)); + EXPECT_TRUE(max_bounds.Contains(display_list->GetBounds())); + EXPECT_TRUE(display_list->GetBounds().Contains(min_bounds)); + + // This is the more practical result. The bounds are "almost" 0,0,100x100 + EXPECT_EQ(DlIRect::RoundOut(display_list->GetBounds()), + DlIRect::MakeWH(100, 100)); + EXPECT_EQ(display_list->op_count(), 19u); + EXPECT_EQ(display_list->bytes(), sizeof(DisplayList) + 392u); + EXPECT_EQ(display_list->total_depth(), 3u); +} + +TEST_F(DisplayListTest, TranslateAffectsCurrentTransform) { + DisplayListBuilder builder; + builder.Translate(12.3f, 14.5f); + DlMatrix matrix = DlMatrix::MakeTranslation({12.3f, 14.5f}); + DlMatrix cur_matrix = builder.GetMatrix(); + ASSERT_EQ(cur_matrix, matrix); + builder.Translate(10, 10); + // CurrentTransform has changed + ASSERT_NE(builder.GetMatrix(), cur_matrix); + // Previous return values have not + ASSERT_EQ(cur_matrix, matrix); +} + +TEST_F(DisplayListTest, ScaleAffectsCurrentTransform) { + DisplayListBuilder builder; + builder.Scale(12.3, 14.5); + DlMatrix matrix = DlMatrix::MakeScale({12.3, 14.5, 1.0f}); + DlMatrix cur_matrix = builder.GetMatrix(); + ASSERT_EQ(cur_matrix, matrix); + builder.Translate(10, 10); + // CurrentTransform has changed + ASSERT_NE(builder.GetMatrix(), cur_matrix); + // Previous return values have not + ASSERT_EQ(cur_matrix, matrix); +} + +TEST_F(DisplayListTest, RotateAffectsCurrentTransform) { + DisplayListBuilder builder; + builder.Rotate(12.3f); + DlMatrix matrix = DlMatrix::MakeRotationZ(DlDegrees(12.3f)); + DlMatrix cur_matrix = builder.GetMatrix(); + ASSERT_EQ(cur_matrix, matrix); + builder.Translate(10, 10); + // CurrentTransform has changed + ASSERT_NE(builder.GetMatrix(), cur_matrix); + // Previous return values have not + ASSERT_EQ(cur_matrix, matrix); +} + +TEST_F(DisplayListTest, SkewAffectsCurrentTransform) { + DisplayListBuilder builder; + builder.Skew(12.3f, 14.5f); + DlMatrix matrix = DlMatrix::MakeSkew(12.3f, 14.5f); + DlMatrix cur_matrix = builder.GetMatrix(); + ASSERT_EQ(cur_matrix, matrix); + builder.Translate(10, 10); + // CurrentTransform has changed + ASSERT_NE(builder.GetMatrix(), cur_matrix); + // Previous return values have not + ASSERT_EQ(cur_matrix, matrix); +} + +TEST_F(DisplayListTest, TransformAffectsCurrentTransform) { + DisplayListBuilder builder; + builder.Transform2DAffine(3.0f, 0.0f, 12.3f, // + 1.0f, 5.0f, 14.5f); + DlMatrix matrix = DlMatrix::MakeRow(3.0f, 0.0f, 0.0f, 12.3, // + 1.0f, 5.0f, 0.0f, 14.5, // + 0.0f, 0.0f, 1.0f, 0.0f, // + 0.0f, 0.0f, 0.0f, 1.0f // + ); + DlMatrix cur_matrix = builder.GetMatrix(); + ASSERT_EQ(cur_matrix, matrix); + builder.Translate(10, 10); + // CurrentTransform has changed + ASSERT_NE(builder.GetMatrix(), cur_matrix); + // Previous return values have not + ASSERT_EQ(cur_matrix, matrix); +} + +TEST_F(DisplayListTest, FullTransformAffectsCurrentTransform) { + DisplayListBuilder builder; + builder.TransformFullPerspective(3.0f, 0.0f, 4.0f, 12.3f, // + 1.0f, 5.0f, 3.0f, 14.5f, // + 0.0f, 0.0f, 7.0f, 16.2f, // + 0.0f, 0.0f, 0.0f, 1.0f); + DlMatrix matrix = DlMatrix::MakeRow(3.0f, 0.0f, 4.0f, 12.3f, // + 1.0f, 5.0f, 3.0f, 14.5f, // + 0.0f, 0.0f, 7.0f, 16.2f, // + 0.0f, 0.0f, 0.0f, 1.0f); + DlMatrix cur_matrix = builder.GetMatrix(); + ASSERT_EQ(cur_matrix, matrix); + builder.Translate(10, 10); + // CurrentTransform has changed + ASSERT_NE(builder.GetMatrix(), cur_matrix); + // Previous return values have not + ASSERT_EQ(cur_matrix, matrix); +} + +TEST_F(DisplayListTest, ClipRectAffectsClipBounds) { + DisplayListBuilder builder; + DlRect clip_bounds = DlRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); + builder.ClipRect(clip_bounds, DlClipOp::kIntersect, false); + + // Save initial return values for testing restored values + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 15, 15), DlClipOp::kIntersect, false); + // Both clip bounds have changed + ASSERT_NE(builder.GetLocalClipCoverage(), clip_bounds); + ASSERT_NE(builder.GetDestinationClipCoverage(), clip_bounds); + // Previous return values have not changed + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); + + builder.Save(); + builder.Scale(2.0f, 2.0f); + DlRect scaled_clip_bounds = DlRect::MakeLTRB(5.1f, 5.65f, 10.2f, 12.85f); + ASSERT_EQ(builder.GetLocalClipCoverage(), scaled_clip_bounds); + // Destination bounds are unaffected by transform + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, ClipRectDoAAAffectsClipBounds) { + DisplayListBuilder builder; + DlRect clip_bounds = DlRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); + DlRect clip_expanded_bounds = DlRect::MakeLTRB(10, 11, 21, 26); + builder.ClipRect(clip_bounds, DlClipOp::kIntersect, true); + + // Save initial return values for testing restored values + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); + ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); + + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 15, 15), DlClipOp::kIntersect, true); + // Both clip bounds have changed + ASSERT_NE(builder.GetLocalClipCoverage(), clip_expanded_bounds); + ASSERT_NE(builder.GetDestinationClipCoverage(), 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(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); + + builder.Save(); + builder.Scale(2, 2); + DlRect scaled_expanded_bounds = DlRect::MakeLTRB(5.0f, 5.5f, 10.5f, 13.0f); + ASSERT_EQ(builder.GetLocalClipCoverage(), scaled_expanded_bounds); + // Destination bounds are unaffected by transform + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_expanded_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, ClipRectAffectsClipBoundsWithMatrix) { + DisplayListBuilder builder; + DlRect clip_bounds_1 = DlRect::MakeLTRB(0, 0, 10, 10); + DlRect clip_bounds_2 = DlRect::MakeLTRB(10, 10, 20, 20); + builder.Save(); + builder.ClipRect(clip_bounds_1, DlClipOp::kIntersect, false); + builder.Translate(10, 0); + builder.ClipRect(clip_bounds_1, DlClipOp::kIntersect, false); + ASSERT_TRUE(builder.GetDestinationClipCoverage().IsEmpty()); + builder.Restore(); + + builder.Save(); + builder.ClipRect(clip_bounds_1, DlClipOp::kIntersect, false); + builder.Translate(-10, -10); + builder.ClipRect(clip_bounds_2, DlClipOp::kIntersect, false); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds_1); + builder.Restore(); +} + +TEST_F(DisplayListTest, ClipRRectAffectsClipBounds) { + DisplayListBuilder builder; + DlRect clip_bounds = DlRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); + DlRoundRect clip = DlRoundRect::MakeRectXY(clip_bounds, 3, 2); + builder.ClipRoundRect(clip, DlClipOp::kIntersect, false); + + // Save initial return values for testing restored values + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 15, 15), DlClipOp::kIntersect, false); + // Both clip bounds have changed + ASSERT_NE(builder.GetLocalClipCoverage(), clip_bounds); + ASSERT_NE(builder.GetDestinationClipCoverage(), clip_bounds); + // Previous return values have not changed + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); + + builder.Save(); + builder.Scale(2, 2); + DlRect scaled_clip_bounds = DlRect::MakeLTRB(5.1f, 5.65f, 10.2f, 12.85f); + ASSERT_EQ(builder.GetLocalClipCoverage(), scaled_clip_bounds); + // Destination bounds are unaffected by transform + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, ClipRRectDoAAAffectsClipBounds) { + DisplayListBuilder builder; + DlRect clip_bounds = DlRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); + DlRect clip_expanded_bounds = DlRect::MakeLTRB(10, 11, 21, 26); + DlRoundRect clip = DlRoundRect::MakeRectXY(clip_bounds, 3, 2); + builder.ClipRoundRect(clip, DlClipOp::kIntersect, true); + + // Save initial return values for testing restored values + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); + ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); + + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 15, 15), DlClipOp::kIntersect, true); + // Both clip bounds have changed + ASSERT_NE(builder.GetLocalClipCoverage(), clip_expanded_bounds); + ASSERT_NE(builder.GetDestinationClipCoverage(), 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(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); + + builder.Save(); + builder.Scale(2, 2); + DlRect scaled_expanded_bounds = DlRect::MakeLTRB(5.0f, 5.5f, 10.5f, 13.0f); + ASSERT_EQ(builder.GetLocalClipCoverage(), scaled_expanded_bounds); + // Destination bounds are unaffected by transform + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_expanded_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, ClipRRectAffectsClipBoundsWithMatrix) { + DisplayListBuilder builder; + DlRect clip_bounds_1 = DlRect::MakeLTRB(0, 0, 10, 10); + DlRect clip_bounds_2 = DlRect::MakeLTRB(10, 10, 20, 20); + DlRoundRect clip1 = DlRoundRect::MakeRectXY(clip_bounds_1, 3, 2); + DlRoundRect clip2 = DlRoundRect::MakeRectXY(clip_bounds_2, 3, 2); + + builder.Save(); + builder.ClipRoundRect(clip1, DlClipOp::kIntersect, false); + builder.Translate(10, 0); + builder.ClipRoundRect(clip1, DlClipOp::kIntersect, false); + ASSERT_TRUE(builder.GetDestinationClipCoverage().IsEmpty()); + builder.Restore(); + + builder.Save(); + builder.ClipRoundRect(clip1, DlClipOp::kIntersect, false); + builder.Translate(-10, -10); + builder.ClipRoundRect(clip2, DlClipOp::kIntersect, false); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds_1); + builder.Restore(); +} + +TEST_F(DisplayListTest, ClipPathAffectsClipBounds) { + DisplayListBuilder builder; + DlPath clip = DlPath::MakeCircle(DlPoint(10.2f, 11.3f), 2.0f) + + DlPath::MakeCircle(DlPoint(20.4f, 25.7f), 2.0f); + DlRect clip_bounds = DlRect::MakeLTRB(8.2, 9.3, 22.4, 27.7); + builder.ClipPath(clip, DlClipOp::kIntersect, false); + + // Save initial return values for testing restored values + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 15, 15), DlClipOp::kIntersect, false); + // Both clip bounds have changed + ASSERT_NE(builder.GetLocalClipCoverage(), clip_bounds); + ASSERT_NE(builder.GetDestinationClipCoverage(), clip_bounds); + // Previous return values have not changed + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); + + builder.Save(); + builder.Scale(2, 2); + DlRect scaled_clip_bounds = DlRect::MakeLTRB(4.1, 4.65, 11.2, 13.85); + ASSERT_EQ(builder.GetLocalClipCoverage(), scaled_clip_bounds); + // Destination bounds are unaffected by transform + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, ClipPathDoAAAffectsClipBounds) { + DisplayListBuilder builder; + DlPath clip = DlPath::MakeCircle(DlPoint(10.2f, 11.3f), 2.0f) + + DlPath::MakeCircle(DlPoint(20.4f, 25.7f), 2.0f); + DlRect clip_expanded_bounds = DlRect::MakeLTRB(8, 9, 23, 28); + builder.ClipPath(clip, DlClipOp::kIntersect, true); + + // Save initial return values for testing restored values + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_expanded_bounds); + ASSERT_EQ(initial_destination_bounds, clip_expanded_bounds); + + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 15, 15), DlClipOp::kIntersect, true); + // Both clip bounds have changed + ASSERT_NE(builder.GetLocalClipCoverage(), clip_expanded_bounds); + ASSERT_NE(builder.GetDestinationClipCoverage(), 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(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); + + builder.Save(); + builder.Scale(2, 2); + DlRect scaled_expanded_bounds = DlRect::MakeLTRB(4.0f, 4.5f, 11.5f, 14.0f); + ASSERT_EQ(builder.GetLocalClipCoverage(), scaled_expanded_bounds); + // Destination bounds are unaffected by transform + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_expanded_bounds); + builder.Restore(); + + // save/restore returned the values to their original values + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, ClipPathAffectsClipBoundsWithMatrix) { + DisplayListBuilder builder; + DlRect clip_bounds = DlRect::MakeLTRB(0, 0, 10, 10); + DlPath clip1 = DlPath::MakeCircle(DlPoint(2.5f, 2.5f), 2.5) + + DlPath::MakeCircle(DlPoint(7.5f, 7.5f), 2.5); + DlPath clip2 = DlPath::MakeCircle(DlPoint(12.5f, 12.5f), 2.5) + + DlPath::MakeCircle(DlPoint(17.5f, 17.5f), 2.5); + + builder.Save(); + builder.ClipPath(clip1, DlClipOp::kIntersect, false); + builder.Translate(10, 0); + builder.ClipPath(clip1, DlClipOp::kIntersect, false); + ASSERT_TRUE(builder.GetDestinationClipCoverage().IsEmpty()); + builder.Restore(); + + builder.Save(); + builder.ClipPath(clip1, DlClipOp::kIntersect, false); + builder.Translate(-10, -10); + builder.ClipPath(clip2, DlClipOp::kIntersect, false); + ASSERT_EQ(builder.GetDestinationClipCoverage(), clip_bounds); + builder.Restore(); +} + +TEST_F(DisplayListTest, DiffClipRectDoesNotAffectClipBounds) { + DisplayListBuilder builder; + DlRect diff_clip = DlRect::MakeLTRB(0, 0, 15, 15); + DlRect clip_bounds = DlRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); + builder.ClipRect(clip_bounds, DlClipOp::kIntersect, false); + + // Save initial return values for testing after kDifference clip + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + + builder.ClipRect(diff_clip, DlClipOp::kDifference, false); + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, DiffClipRRectDoesNotAffectClipBounds) { + DisplayListBuilder builder; + DlRoundRect diff_clip = + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(0, 0, 15, 15), 1, 1); + DlRect clip_bounds = DlRect::MakeLTRB(10.2, 11.3, 20.4, 25.7); + DlRoundRect clip = + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(10.2, 11.3, 20.4, 25.7), 3, 2); + builder.ClipRoundRect(clip, DlClipOp::kIntersect, false); + + // Save initial return values for testing after kDifference clip + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + + builder.ClipRoundRect(diff_clip, DlClipOp::kDifference, false); + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, DiffClipPathDoesNotAffectClipBounds) { + DisplayListBuilder builder; + DlPath diff_clip = DlPath::MakeRectLTRB(0, 0, 15, 15); + DlPath clip = DlPath::MakeCircle(DlPoint(10.2, 11.3), 2) + + DlPath::MakeCircle(DlPoint(20.4, 25.7), 2); + DlRect clip_bounds = DlRect::MakeLTRB(8.2, 9.3, 22.4, 27.7); + builder.ClipPath(clip, DlClipOp::kIntersect, false); + + // Save initial return values for testing after kDifference clip + DlRect initial_local_bounds = builder.GetLocalClipCoverage(); + DlRect initial_destination_bounds = builder.GetDestinationClipCoverage(); + ASSERT_EQ(initial_local_bounds, clip_bounds); + ASSERT_EQ(initial_destination_bounds, clip_bounds); + + builder.ClipPath(diff_clip, DlClipOp::kDifference, false); + ASSERT_EQ(builder.GetLocalClipCoverage(), initial_local_bounds); + ASSERT_EQ(builder.GetDestinationClipCoverage(), initial_destination_bounds); +} + +TEST_F(DisplayListTest, FlatDrawPointsProducesBounds) { + DlPoint horizontal_points[2] = {DlPoint(10, 10), DlPoint(20, 10)}; + DlPoint vertical_points[2] = {DlPoint(10, 10), DlPoint(10, 20)}; + { + DisplayListBuilder builder; + builder.DrawPoints(DlPointMode::kPolygon, 2, horizontal_points, DlPaint()); + DlRect bounds = builder.Build()->GetBounds(); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 10))); + EXPECT_TRUE(bounds.Contains(DlPoint(20, 10))); + EXPECT_GE(bounds.GetWidth(), 10); + } + { + DisplayListBuilder builder; + builder.DrawPoints(DlPointMode::kPolygon, 2, vertical_points, DlPaint()); + DlRect bounds = builder.Build()->GetBounds(); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 10))); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 20))); + EXPECT_GE(bounds.GetHeight(), 10); + } + { + DisplayListBuilder builder; + builder.DrawPoints(DlPointMode::kPoints, 1, horizontal_points, DlPaint()); + DlRect bounds = builder.Build()->GetBounds(); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 10))); + } + { + DisplayListBuilder builder; + DlPaint paint; + paint.setStrokeWidth(2); + builder.DrawPoints(DlPointMode::kPolygon, 2, horizontal_points, paint); + DlRect bounds = builder.Build()->GetBounds(); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 10))); + EXPECT_TRUE(bounds.Contains(DlPoint(20, 10))); + EXPECT_EQ(bounds, DlRect::MakeLTRB(9, 9, 21, 11)); + } + { + DisplayListBuilder builder; + DlPaint paint; + paint.setStrokeWidth(2); + builder.DrawPoints(DlPointMode::kPolygon, 2, vertical_points, paint); + DlRect bounds = builder.Build()->GetBounds(); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 10))); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 20))); + EXPECT_EQ(bounds, DlRect::MakeLTRB(9, 9, 11, 21)); + } + { + DisplayListBuilder builder; + DlPaint paint; + paint.setStrokeWidth(2); + builder.DrawPoints(DlPointMode::kPoints, 1, horizontal_points, paint); + DlRect bounds = builder.Build()->GetBounds(); + EXPECT_TRUE(bounds.Contains(DlPoint(10, 10))); + EXPECT_EQ(bounds, DlRect::MakeLTRB(9, 9, 11, 11)); + } +} + +#define TEST_RTREE(rtree, query, expected_rects, expected_indices) \ + test_rtree(rtree, query, expected_rects, expected_indices, __FILE__, __LINE__) + +static void test_rtree(const sk_sp& rtree, + const DlRect& query, + std::vector expected_rects, + const std::vector& expected_indices, + const std::string& file, + int line) { + std::vector indices; + auto label = "from " + file + ":" + std::to_string(line); + rtree->search(query, &indices); + EXPECT_EQ(indices, expected_indices) << label; + EXPECT_EQ(indices.size(), expected_indices.size()) << label; + std::list rects = rtree->searchAndConsolidateRects(query, false); + // ASSERT_EQ(rects.size(), expected_indices.size()); + auto iterator = rects.cbegin(); + for (int i : expected_indices) { + ASSERT_TRUE(iterator != rects.cend()) << label; + EXPECT_EQ(*iterator++, expected_rects[i]) << label; + } +} + +TEST_F(DisplayListTest, RTreeOfSimpleScene) { + DisplayListBuilder builder(/*prepare_rtree=*/true); + std::vector rects = { + DlRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(50, 50, 60, 60), + }; + builder.DrawRect(rects[0], DlPaint()); + builder.DrawRect(rects[1], DlPaint()); + auto display_list = builder.Build(); + auto rtree = display_list->rtree(); + + // Missing all drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 10, 10), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(20, 20, 25, 25), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 50, 50), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(60, 60, 65, 65), rects, {}); + + // Hitting just 1 of the drawRects + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 11, 11), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 25, 25), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 51, 51), rects, {1}); + TEST_RTREE(rtree, DlRect::MakeLTRB(59, 59, 65, 65), rects, {1}); + + // Hitting both drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 51, 51), rects, + std::vector({0, 1})); +} + +TEST_F(DisplayListTest, RTreeOfSaveRestoreScene) { + DisplayListBuilder builder(/*prepare_rtree=*/true); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Save(); + builder.DrawRect(DlRect::MakeLTRB(50, 50, 60, 60), DlPaint()); + builder.Restore(); + auto display_list = builder.Build(); + auto rtree = display_list->rtree(); + std::vector rects = { + DlRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(50, 50, 60, 60), + }; + + // Missing all drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 10, 10), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(20, 20, 25, 25), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 50, 50), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(60, 60, 65, 65), rects, {}); + + // Hitting just 1 of the drawRects + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 11, 11), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 25, 25), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 51, 51), rects, {1}); + TEST_RTREE(rtree, DlRect::MakeLTRB(59, 59, 65, 65), rects, {1}); + + // Hitting both drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 51, 51), rects, + std::vector({0, 1})); +} + +TEST_F(DisplayListTest, RTreeOfSaveLayerFilterScene) { + DisplayListBuilder builder(/*prepare_rtree=*/true); + // blur filter with sigma=1 expands by 3 on all sides + auto filter = DlBlurImageFilter(1.0, 1.0, DlTileMode::kClamp); + DlPaint default_paint = DlPaint(); + DlPaint filter_paint = DlPaint().setImageFilter(&filter); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), default_paint); + builder.SaveLayer(std::nullopt, &filter_paint); + // the following rectangle will be expanded to 50,50,60,60 + // by the SaveLayer filter during the restore operation + builder.DrawRect(DlRect::MakeLTRB(53, 53, 57, 57), default_paint); + builder.Restore(); + auto display_list = builder.Build(); + auto rtree = display_list->rtree(); + std::vector rects = { + DlRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(50, 50, 60, 60), + }; + + // Missing all drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 10, 10), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(20, 20, 25, 25), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 50, 50), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(60, 60, 65, 65), rects, {}); + + // Hitting just 1 of the drawRects + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 11, 11), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 25, 25), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 51, 51), rects, {1}); + TEST_RTREE(rtree, DlRect::MakeLTRB(59, 59, 65, 65), rects, {1}); + + // Hitting both drawRect calls + auto expected_indices = std::vector{0, 1}; + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 51, 51), rects, expected_indices); +} + +TEST_F(DisplayListTest, NestedDisplayListRTreesAreSparse) { + DisplayListBuilder nested_dl_builder(/**prepare_rtree=*/true); + nested_dl_builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + nested_dl_builder.DrawRect(DlRect::MakeLTRB(50, 50, 60, 60), DlPaint()); + auto nested_display_list = nested_dl_builder.Build(); + + DisplayListBuilder builder(/**prepare_rtree=*/true); + builder.DrawDisplayList(nested_display_list); + auto display_list = builder.Build(); + + auto rtree = display_list->rtree(); + std::vector rects = { + DlRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(50, 50, 60, 60), + }; + + // Hitting both sub-dl drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 51, 51), rects, + std::vector({0, 1})); +} + +TEST_F(DisplayListTest, RemoveUnnecessarySaveRestorePairs) { + { + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Save(); // This save op is unnecessary + builder.DrawRect(DlRect::MakeLTRB(50, 50, 60, 60), DlPaint()); + builder.Restore(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(50, 50, 60, 60), DlPaint()); + ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), builder2.Build())); + } + + { + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Save(); + { + builder.Translate(1.0, 1.0); + builder.Save(); + { // + builder.DrawRect(DlRect::MakeLTRB(50, 50, 60, 60), DlPaint()); + } + builder.Restore(); + } + builder.Restore(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder2.Save(); + { // + builder2.Translate(1.0, 1.0); + { // + builder2.DrawRect(DlRect::MakeLTRB(50, 50, 60, 60), DlPaint()); + } + } + builder2.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(DlRect::MakeLTRB(10, 10, 20, 20), + DlClipOp::kIntersect, false); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + } + builder1.Restore(); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.Translate(10, 10); + builder2.Scale(2, 2); + builder2.ClipRect(DlRect::MakeLTRB(10, 10, 20, 20), DlClipOp::kIntersect, + false); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, CollapseNestedSaveAndSaveLayerRestore) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.SaveLayer(std::nullopt, nullptr); + { + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder1.Scale(2, 2); + } + builder1.Restore(); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.SaveLayer(std::nullopt, nullptr); + { + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.Scale(2, 2); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, RemoveUnnecessarySaveRestorePairsInSetPaint) { + DlRect build_bounds = DlRect::MakeLTRB(-100, -100, 200, 200); + DlRect rect = DlRect::MakeLTRB(30, 30, 70, 70); + // clang-format off + const float alpha_matrix[] = { + 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 1, + }; + // clang-format on + auto alpha_color_filter = DlColorFilter::MakeMatrix(alpha_matrix); + // Making sure hiding a problematic ColorFilter as an ImageFilter + // will generate the same behavior as setting it as a ColorFilter + + DlColorFilterImageFilter color_filter_image_filter(alpha_color_filter); + { + DisplayListBuilder builder(build_bounds); + builder.Save(); + DlPaint paint; + paint.setImageFilter(&color_filter_image_filter); + builder.DrawRect(rect, paint); + builder.Restore(); + sk_sp display_list1 = builder.Build(); + + DisplayListBuilder builder2(build_bounds); + DlPaint paint2; + paint2.setImageFilter(&color_filter_image_filter); + builder2.DrawRect(rect, paint2); + sk_sp display_list2 = builder2.Build(); + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); + } + + { + DisplayListBuilder builder(build_bounds); + builder.Save(); + builder.SaveLayer(build_bounds); + DlPaint paint; + paint.setImageFilter(&color_filter_image_filter); + builder.DrawRect(rect, paint); + builder.Restore(); + builder.Restore(); + sk_sp display_list1 = builder.Build(); + + DisplayListBuilder builder2(build_bounds); + builder2.SaveLayer(build_bounds); + DlPaint paint2; + paint2.setImageFilter(&color_filter_image_filter); + builder2.DrawRect(rect, paint2); + builder2.Restore(); + sk_sp display_list2 = builder2.Build(); + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); + } +} + +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(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.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(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, Transform2DTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Transform2DAffine(0, 1, 12, 1, 0, 33); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.Transform2DAffine(0, 1, 12, 1, 0, 33); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + } + builder1.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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, ResetTransformTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.TransformReset(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.TransformReset(); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, SkewTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Skew(10, 10); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.Skew(10, 10); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, TranslateTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Translate(10, 10); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.Translate(10, 10); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, ScaleTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Scale(0.5, 0.5); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.Scale(0.5, 0.5); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, ClipRectTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.ClipRect(DlRect::MakeLTRB(0, 0, 100, 100), DlClipOp::kIntersect, + true); + builder1.DrawRect(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.ClipRect(DlRect::MakeLTRB(0, 0, 100, 100), DlClipOp::kIntersect, + true); + builder2.DrawRect(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, ClipRRectTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.ClipRoundRect(kTestRRect, DlClipOp::kIntersect, true); + + builder1.DrawRect(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + builder2.ClipRoundRect(kTestRRect, DlClipOp::kIntersect, true); + + builder2.DrawRect(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, ClipPathTriggersDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.ClipPath(kTestPath1, DlClipOp::kIntersect, true); + builder1.DrawRect(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.ClipPath(kTestPath1, DlClipOp::kIntersect, true); + builder2.DrawRect(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, NOPTranslateDoesNotTriggerDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Translate(0, 0); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, NOPScaleDoesNotTriggerDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Scale(1.0, 1.0); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, NOPRotationDoesNotTriggerDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Rotate(360); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, NOPSkewDoesNotTriggerDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Skew(0, 0); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +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(DlRect::MakeLTRB(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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, NOPTransform2DDoesNotTriggerDeferredSave) { + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.Transform2DAffine(1, 0, 0, 0, 1, 0); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); + } + + { + 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(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.Save(); + { + builder2.TransformReset(); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder2.Restore(); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); + } +} + +TEST_F(DisplayListTest, NOPClipDoesNotTriggerDeferredSave) { + DlScalar NaN = std::numeric_limits::quiet_NaN(); + DisplayListBuilder builder1; + builder1.Save(); + { + builder1.Save(); + { + builder1.ClipRect(DlRect::MakeLTRB(0, NaN, NaN, 0), DlClipOp::kIntersect, + true); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + builder1.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + } + builder1.Restore(); + auto display_list1 = builder1.Build(); + + DisplayListBuilder builder2; + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + builder2.DrawRect(DlRect::MakeLTRB(0, 0, 100, 100), DlPaint()); + auto display_list2 = builder2.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(display_list1, display_list2)); +} + +TEST_F(DisplayListTest, RTreeOfClippedSaveLayerFilterScene) { + DisplayListBuilder builder(/*prepare_rtree=*/true); + // blur filter with sigma=1 expands by 30 on all sides + auto filter = DlBlurImageFilter(10.0, 10.0, DlTileMode::kClamp); + DlPaint default_paint = DlPaint(); + DlPaint filter_paint = DlPaint().setImageFilter(&filter); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), default_paint); + builder.ClipRect(DlRect::MakeLTRB(50, 50, 60, 60), DlClipOp::kIntersect, + false); + builder.SaveLayer(std::nullopt, &filter_paint); + // the following rectangle will be expanded to 23,23,87,87 + // by the SaveLayer filter during the restore operation + // but it will then be clipped to 50,50,60,60 + builder.DrawRect(DlRect::MakeLTRB(53, 53, 57, 57), default_paint); + builder.Restore(); + auto display_list = builder.Build(); + auto rtree = display_list->rtree(); + std::vector rects = { + DlRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(50, 50, 60, 60), + }; + + // Missing all drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 10, 10), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(20, 20, 25, 25), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 50, 50), rects, {}); + TEST_RTREE(rtree, DlRect::MakeLTRB(60, 60, 65, 65), rects, {}); + + // Hitting just 1 of the drawRects + TEST_RTREE(rtree, DlRect::MakeLTRB(5, 5, 11, 11), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 25, 25), rects, {0}); + TEST_RTREE(rtree, DlRect::MakeLTRB(45, 45, 51, 51), rects, {1}); + TEST_RTREE(rtree, DlRect::MakeLTRB(59, 59, 65, 65), rects, {1}); + + // Hitting both drawRect calls + TEST_RTREE(rtree, DlRect::MakeLTRB(19, 19, 51, 51), rects, + std::vector({0, 1})); +} + +TEST_F(DisplayListTest, RTreeRenderCulling) { + DlRect rect1 = DlRect::MakeLTRB(0, 0, 10, 10); + DlRect rect2 = DlRect::MakeLTRB(20, 0, 30, 10); + DlRect rect3 = DlRect::MakeLTRB(0, 20, 10, 30); + DlRect rect4 = DlRect::MakeLTRB(20, 20, 30, 30); + DlPaint paint1 = DlPaint().setColor(DlColor::kRed()); + DlPaint paint2 = DlPaint().setColor(DlColor::kGreen()); + DlPaint paint3 = DlPaint().setColor(DlColor::kBlue()); + DlPaint paint4 = DlPaint().setColor(DlColor::kMagenta()); + + DisplayListBuilder main_builder(true); + main_builder.DrawRect(rect1, paint1); + main_builder.DrawRect(rect2, paint2); + main_builder.DrawRect(rect3, paint3); + main_builder.DrawRect(rect4, paint4); + auto main = main_builder.Build(); + + auto test = [main](DlIRect cull_rect, const sk_sp& expected, + const std::string& label) { + DlRect cull_rectf = DlRect::Make(cull_rect); + + { // Test DlIRect culling + DisplayListBuilder culling_builder; + main->Dispatch(ToReceiver(culling_builder), cull_rect); + + EXPECT_TRUE(DisplayListsEQ_Verbose(culling_builder.Build(), expected)) + << "using cull rect " << cull_rect // + << " where " << label; + } + + { // Test DlRect culling + DisplayListBuilder culling_builder; + main->Dispatch(ToReceiver(culling_builder), cull_rectf); + + EXPECT_TRUE(DisplayListsEQ_Verbose(culling_builder.Build(), expected)) + << "using cull rect " << cull_rectf // + << " where " << label; + } + + { // Test using vector of culled indices + DisplayListBuilder culling_builder; + DlOpReceiver& receiver = ToReceiver(culling_builder); + auto indices = main->GetCulledIndices(cull_rectf); + for (DlIndex i : indices) { + EXPECT_TRUE(main->Dispatch(receiver, i)); + } + + EXPECT_TRUE(DisplayListsEQ_Verbose(culling_builder.Build(), expected)) + << "using culled indices on cull rect " << cull_rectf // + << " where " << label; + } + }; + + { // No rects + DlIRect cull_rect = DlIRect::MakeLTRB(11, 11, 19, 19); + + DisplayListBuilder expected_builder; + auto expected = expected_builder.Build(); + + test(cull_rect, expected, "no rects intersect"); + } + + { // Rect 1 + DlIRect cull_rect = DlIRect::MakeLTRB(9, 9, 19, 19); + + DisplayListBuilder expected_builder; + expected_builder.DrawRect(rect1, paint1); + auto expected = expected_builder.Build(); + + test(cull_rect, expected, "rect 1 intersects"); + } + + { // Rect 2 + DlIRect cull_rect = DlIRect::MakeLTRB(11, 9, 21, 19); + + DisplayListBuilder expected_builder; + // Unfortunately we don't cull attribute records (yet?), so we forcibly + // record all attributes for the un-culled operations + ToReceiver(expected_builder).setColor(paint1.getColor()); + expected_builder.DrawRect(rect2, paint2); + auto expected = expected_builder.Build(); + + test(cull_rect, expected, "rect 2 intersects"); + } + + { // Rect 3 + DlIRect cull_rect = DlIRect::MakeLTRB(9, 11, 19, 21); + + DisplayListBuilder expected_builder; + // Unfortunately we don't cull attribute records (yet?), so we forcibly + // record all attributes for the un-culled operations + ToReceiver(expected_builder).setColor(paint1.getColor()); + ToReceiver(expected_builder).setColor(paint2.getColor()); + expected_builder.DrawRect(rect3, paint3); + auto expected = expected_builder.Build(); + + test(cull_rect, expected, "rect 3 intersects"); + } + + { // Rect 4 + DlIRect cull_rect = DlIRect::MakeLTRB(11, 11, 21, 21); + + DisplayListBuilder expected_builder; + // Unfortunately we don't cull attribute records (yet?), so we forcibly + // record all attributes for the un-culled operations + ToReceiver(expected_builder).setColor(paint1.getColor()); + ToReceiver(expected_builder).setColor(paint2.getColor()); + ToReceiver(expected_builder).setColor(paint3.getColor()); + expected_builder.DrawRect(rect4, paint4); + auto expected = expected_builder.Build(); + + test(cull_rect, expected, "rect 4 intersects"); + } + + { // All 4 rects + DlIRect cull_rect = DlIRect::MakeLTRB(9, 9, 21, 21); + + test(cull_rect, main, "all rects intersect"); + } +} + +TEST_F(DisplayListTest, DrawSaveDrawCannotInheritOpacity) { + DisplayListBuilder builder; + builder.DrawCircle(DlPoint(10, 10), 5, DlPaint()); + builder.Save(); + builder.ClipRect(DlRect::MakeLTRB(0, 0, 20, 20), DlClipOp::kIntersect, false); + builder.DrawRect(DlRect::MakeLTRB(5, 5, 15, 15), DlPaint()); + builder.Restore(); + auto display_list = builder.Build(); + + ASSERT_FALSE(display_list->can_apply_group_opacity()); +} + +TEST_F(DisplayListTest, DrawUnorderedRect) { + auto renderer = [](DlCanvas& canvas, DlPaint& paint, DlRect& rect) { + canvas.DrawRect(rect, paint); + }; + check_inverted_bounds(renderer, "DrawRect"); +} + +TEST_F(DisplayListTest, DrawUnorderedRoundRect) { + auto renderer = [](DlCanvas& canvas, DlPaint& paint, DlRect& rect) { + canvas.DrawRoundRect(DlRoundRect::MakeRectXY(rect, 2.0f, 2.0f), paint); + }; + check_inverted_bounds(renderer, "DrawRoundRect"); +} + +TEST_F(DisplayListTest, DrawUnorderedOval) { + auto renderer = [](DlCanvas& canvas, DlPaint& paint, DlRect& rect) { + canvas.DrawOval(rect, paint); + }; + check_inverted_bounds(renderer, "DrawOval"); +} + +TEST_F(DisplayListTest, DrawUnorderedRectangularPath) { + auto renderer = [](DlCanvas& canvas, DlPaint& paint, DlRect& rect) { + canvas.DrawPath(DlPath::MakeRect(rect), paint); + }; + check_inverted_bounds(renderer, "DrawRectangularPath"); +} + +TEST_F(DisplayListTest, DrawUnorderedOvalPath) { + auto renderer = [](DlCanvas& canvas, DlPaint& paint, DlRect& rect) { + canvas.DrawPath(DlPath::MakeOval(rect), paint); + }; + check_inverted_bounds(renderer, "DrawOvalPath"); +} + +TEST_F(DisplayListTest, DrawUnorderedRoundRectPathCW) { + auto renderer = [](DlCanvas& canvas, DlPaint& paint, DlRect& rect) { + DlPath path = DlPath::MakeRoundRectXY(rect, 2.0f, 2.0f, false); + canvas.DrawPath(path, paint); + }; + check_inverted_bounds(renderer, "DrawRoundRectPath Clockwise"); +} + +TEST_F(DisplayListTest, DrawUnorderedRoundRectPathCCW) { + auto renderer = [](DlCanvas& canvas, DlPaint& paint, DlRect& rect) { + DlPath path = DlPath::MakeRoundRectXY(rect, 2.0f, 2.0f, true); + canvas.DrawPath(path, paint); + }; + check_inverted_bounds(renderer, "DrawRoundRectPath Counter-Clockwise"); +} + +TEST_F(DisplayListTest, NopOperationsOmittedFromRecords) { + auto run_tests = [](const std::string& name, + void init(DisplayListBuilder & builder, DlPaint & paint), + uint32_t expected_op_count = 0u, + uint32_t expected_total_depth = 0u) { + auto run_one_test = + [init](const std::string& name, + void build(DisplayListBuilder & builder, DlPaint & paint), + uint32_t expected_op_count = 0u, + uint32_t expected_total_depth = 0u) { + DisplayListBuilder builder; + DlPaint paint; + init(builder, paint); + build(builder, paint); + auto list = builder.Build(); + if (list->op_count() != expected_op_count) { + FML_LOG(ERROR) << *list; + } + ASSERT_EQ(list->op_count(), expected_op_count) << name; + EXPECT_EQ(list->total_depth(), expected_total_depth) << name; + ASSERT_TRUE(list->bounds().isEmpty()) << name; + }; + run_one_test( + name + " DrawColor", + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.DrawColor(paint.getColor(), paint.getBlendMode()); + }, + expected_op_count, expected_total_depth); + run_one_test( + name + " DrawPaint", + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.DrawPaint(paint); + }, + expected_op_count, expected_total_depth); + run_one_test( + name + " DrawRect", + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), paint); + }, + expected_op_count, expected_total_depth); + run_one_test( + name + " Other Draw Ops", + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.DrawLine(DlPoint(10, 10), DlPoint(20, 20), paint); + builder.DrawOval(DlRect::MakeLTRB(10, 10, 20, 20), paint); + builder.DrawCircle(DlPoint(50, 50), 20, paint); + builder.DrawRoundRect( + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(10, 10, 20, 20), 5, 5), + paint); + builder.DrawDiffRoundRect( + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(5, 5, 100, 100), 5, 5), + DlRoundRect::MakeRectXY(DlRect::MakeLTRB(10, 10, 20, 20), 5, 5), + paint); + builder.DrawPath(kTestPath1, paint); + builder.DrawArc(DlRect::MakeLTRB(10, 10, 20, 20), 45, 90, true, + paint); + DlPoint pts[] = {DlPoint(10, 10), DlPoint(20, 20)}; + builder.DrawPoints(DlPointMode::kLines, 2, pts, paint); + builder.DrawVertices(kTestVertices1, DlBlendMode::kSrcOver, paint); + builder.DrawImage(kTestImage1, DlPoint(10, 10), + DlImageSampling::kLinear, &paint); + builder.DrawImageRect(kTestImage1, + DlRect::MakeLTRB(0.0f, 0.0f, 10.0f, 10.0f), + DlRect::MakeLTRB(10.0f, 10.0f, 25.0f, 25.0f), + DlImageSampling::kLinear, &paint); + builder.DrawImageNine(kTestImage1, DlIRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(10, 10, 100, 100), + DlFilterMode::kLinear, &paint); + DlRSTransform xforms[] = { + DlRSTransform::Make({10.0f, 10.0f}, 1.0f, DlDegrees(0)), + DlRSTransform::Make({10.0f, 10.0f}, 1.0f, DlDegrees(90)), + }; + DlRect rects[] = { + DlRect::MakeLTRB(10, 10, 20, 20), + DlRect::MakeLTRB(10, 20, 30, 20), + }; + builder.DrawAtlas(kTestImage1, xforms, rects, nullptr, 2, + DlBlendMode::kSrcOver, DlImageSampling::kLinear, + nullptr, &paint); + builder.DrawTextBlob(GetTestTextBlob(1), 10, 10, paint); + + // Dst mode eliminates most rendering ops except for + // the following two, so we'll prune those manually... + if (paint.getBlendMode() != DlBlendMode::kDst) { + builder.DrawDisplayList(TestDisplayList1, paint.getOpacity()); + builder.DrawShadow(kTestPath1, paint.getColor(), 1, true, 1); + } + }, + expected_op_count, expected_total_depth); + run_one_test( + name + " SaveLayer", + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.SaveLayer(std::nullopt, &paint, nullptr); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + builder.Restore(); + }, + expected_op_count, expected_total_depth); + run_one_test( + name + " inside Save", + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.Save(); + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), paint); + builder.Restore(); + }, + expected_op_count, expected_total_depth); + }; + run_tests("transparent color", // + [](DisplayListBuilder& builder, DlPaint& paint) { + paint.setColor(DlColor::kTransparent()); + }); + run_tests("0 alpha", // + [](DisplayListBuilder& builder, DlPaint& paint) { + // The transparent test above already tested transparent + // black (all 0s), we set White color here so we can test + // the case of all 1s with a 0 alpha + paint.setColor(DlColor::kWhite()); + paint.setAlpha(0); + }); + run_tests("BlendMode::kDst", // + [](DisplayListBuilder& builder, DlPaint& paint) { + paint.setBlendMode(DlBlendMode::kDst); + }); + run_tests("Empty rect clip", // + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.ClipRect(DlRect(), DlClipOp::kIntersect, false); + }); + run_tests("Empty rrect clip", // + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.ClipRoundRect(DlRoundRect(), DlClipOp::kIntersect, false); + }); + run_tests("Empty path clip", // + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.ClipPath(DlPath(), DlClipOp::kIntersect, false); + }); + run_tests("Transparent SaveLayer", // + [](DisplayListBuilder& builder, DlPaint& paint) { + DlPaint save_paint; + save_paint.setColor(DlColor::kTransparent()); + builder.SaveLayer(std::nullopt, &save_paint); + }); + run_tests("0 alpha SaveLayer", // + [](DisplayListBuilder& builder, DlPaint& paint) { + DlPaint save_paint; + // The transparent test above already tested transparent + // black (all 0s), we set White color here so we can test + // the case of all 1s with a 0 alpha + save_paint.setColor(DlColor::kWhite()); + save_paint.setAlpha(0); + builder.SaveLayer(std::nullopt, &save_paint); + }); + run_tests("Dst blended SaveLayer", // + [](DisplayListBuilder& builder, DlPaint& paint) { + DlPaint save_paint; + save_paint.setBlendMode(DlBlendMode::kDst); + builder.SaveLayer(std::nullopt, &save_paint); + }); + run_tests( + "Nop inside SaveLayer", + [](DisplayListBuilder& builder, DlPaint& paint) { + builder.SaveLayer(std::nullopt, nullptr); + paint.setBlendMode(DlBlendMode::kDst); + }, + 2u, 1u); + run_tests("DrawImage inside Culled SaveLayer", // + [](DisplayListBuilder& builder, DlPaint& paint) { + DlPaint save_paint; + save_paint.setColor(DlColor::kTransparent()); + builder.SaveLayer(std::nullopt, &save_paint); + builder.DrawImage(kTestImage1, DlPoint(10, 10), + DlImageSampling::kLinear); + }); +} + +class SaveLayerBoundsExpector : public virtual DlOpReceiver, + public IgnoreAttributeDispatchHelper, + public IgnoreClipDispatchHelper, + public IgnoreTransformDispatchHelper, + public IgnoreDrawDispatchHelper { + public: + explicit SaveLayerBoundsExpector() {} + + SaveLayerBoundsExpector& addComputedExpectation(const DlRect& bounds) { + expected_.emplace_back(BoundsExpectation{ + .bounds = bounds, + .options = SaveLayerOptions(), + }); + return *this; + } + + SaveLayerBoundsExpector& addSuppliedExpectation(const DlRect& bounds, + bool clipped = false) { + SaveLayerOptions options; + options = options.with_bounds_from_caller(); + if (clipped) { + options = options.with_content_is_clipped(); + } + expected_.emplace_back(BoundsExpectation{ + .bounds = bounds, + .options = options, + }); + return *this; + } + + void saveLayer(const DlRect& bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop, + std::optional backdrop_id) override { + ASSERT_LT(save_layer_count_, expected_.size()); + auto expected = expected_[save_layer_count_]; + EXPECT_EQ(options.bounds_from_caller(), + expected.options.bounds_from_caller()) + << "expected bounds index " << save_layer_count_; + EXPECT_EQ(options.content_is_clipped(), + expected.options.content_is_clipped()) + << "expected bounds index " << save_layer_count_; + if (!DlScalarNearlyEqual(bounds.GetLeft(), expected.bounds.GetLeft()) || + !DlScalarNearlyEqual(bounds.GetTop(), expected.bounds.GetTop()) || + !DlScalarNearlyEqual(bounds.GetRight(), expected.bounds.GetRight()) || + !DlScalarNearlyEqual(bounds.GetBottom(), expected.bounds.GetBottom())) { + EXPECT_EQ(bounds, expected.bounds) + << "expected bounds index " << save_layer_count_; + } + save_layer_count_++; + } + + bool all_bounds_checked() const { + return save_layer_count_ == expected_.size(); + } + + private: + struct BoundsExpectation { + const DlRect bounds; + const SaveLayerOptions options; + }; + + std::vector expected_; + size_t save_layer_count_ = 0; +}; + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfMaskBlurredRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlPaint draw_paint; + auto mask_filter = DlBlurMaskFilter::Make(DlBlurStyle::kNormal, 2.0f); + draw_paint.setMaskFilter(mask_filter); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, draw_paint); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect.Expand(6.0f, 6.0f)); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfImageBlurredRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlPaint draw_paint; + auto image_filter = DlImageFilter::MakeBlur(2.0f, 3.0f, DlTileMode::kDecal); + draw_paint.setImageFilter(image_filter); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, draw_paint); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect.Expand(6.0f, 9.0f)); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfStrokedRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlPaint draw_paint; + draw_paint.setStrokeWidth(5.0f); + draw_paint.setDrawStyle(DlDrawStyle::kStroke); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, draw_paint); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect.Expand(2.5f, 2.5f)); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, TranslatedSaveLayerBoundsComputationOfSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.Translate(10.0f, 10.0f); + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, ScaledSaveLayerBoundsComputationOfSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.Scale(10.0f, 10.0f); + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, RotatedSaveLayerBoundsComputationOfSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.Rotate(45.0f); + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, TransformResetSaveLayerBoundsComputationOfSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlRect rect_doubled = DlRect::MakeLTRB(200.0f, 200.0f, 400.0f, 400.0f); + + DisplayListBuilder builder; + builder.Scale(10.0f, 10.0f); + builder.SaveLayer(std::nullopt, nullptr); + builder.TransformReset(); + builder.Scale(20.0f, 20.0f); + // Net local transform for SaveLayer is Scale(2, 2) + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect_doubled); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfTranslatedSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.Translate(10.0f, 10.0f); + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect.Shift(10.0f, 10.0f)); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfScaledSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.Scale(10.0f, 10.0f); + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation( + DlRect::MakeLTRB(1000.0f, 1000.0f, 2000.0f, 2000.0f)); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfRotatedSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.Rotate(45.0f); + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + DlMatrix matrix = DlMatrix::MakeRotationZ(DlDegrees(45.0f)); + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect.TransformAndClipBounds(matrix)); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfNestedSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect); + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, FloodingSaveLayerBoundsComputationOfSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlPaint save_paint; + auto color_filter = + DlColorFilter::MakeBlend(DlColor::kRed(), DlBlendMode::kSrc); + ASSERT_TRUE(color_filter->modifies_transparent_black()); + save_paint.setColorFilter(color_filter); + DlRect clip_rect = rect.Expand(100.0f, 100.0f); + ASSERT_NE(clip_rect, rect); + ASSERT_TRUE(clip_rect.Contains(rect)); + + DisplayListBuilder builder; + builder.ClipRect(clip_rect); + builder.SaveLayer(std::nullopt, &save_paint); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, NestedFloodingSaveLayerBoundsComputationOfSimpleRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlPaint save_paint; + auto color_filter = + DlColorFilter::MakeBlend(DlColor::kRed(), DlBlendMode::kSrc); + ASSERT_TRUE(color_filter->modifies_transparent_black()); + save_paint.setColorFilter(color_filter); + DlRect clip_rect = rect.Expand(100.0f, 100.0f); + ASSERT_NE(clip_rect, rect); + ASSERT_TRUE(clip_rect.Contains(rect)); + + DisplayListBuilder builder; + builder.ClipRect(clip_rect); + builder.SaveLayer(std::nullopt, nullptr); + { + builder.SaveLayer(std::nullopt, &save_paint); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + } + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->GetBounds(), clip_rect); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(clip_rect); + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfFloodingImageFilter) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlPaint draw_paint; + auto color_filter = + DlColorFilter::MakeBlend(DlColor::kRed(), DlBlendMode::kSrc); + ASSERT_TRUE(color_filter->modifies_transparent_black()); + auto image_filter = DlImageFilter::MakeColorFilter(color_filter); + draw_paint.setImageFilter(image_filter); + DlRect clip_rect = rect.Expand(100.0f, 100.0f); + ASSERT_NE(clip_rect, rect); + ASSERT_TRUE(clip_rect.Contains(rect)); + + DisplayListBuilder builder; + builder.ClipRect(clip_rect); + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, draw_paint); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(clip_rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsComputationOfFloodingColorFilter) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlPaint draw_paint; + auto color_filter = + DlColorFilter::MakeBlend(DlColor::kRed(), DlBlendMode::kSrc); + ASSERT_TRUE(color_filter->modifies_transparent_black()); + draw_paint.setColorFilter(color_filter); + DlRect clip_rect = rect.Expand(100.0f, 100.0f); + ASSERT_NE(clip_rect, rect); + ASSERT_TRUE(clip_rect.Contains(rect)); + + DisplayListBuilder builder; + builder.ClipRect(clip_rect); + builder.SaveLayer(std::nullopt, nullptr); + { // + builder.DrawRect(rect, draw_paint); + } + builder.Restore(); + auto display_list = builder.Build(); + + // A color filter is implicitly clipped to the draw bounds so the layer + // bounds will be the same as the draw bounds. + SaveLayerBoundsExpector expector; + expector.addComputedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsClipDetectionSimpleUnclippedRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlRect save_rect = DlRect::MakeLTRB(50.0f, 50.0f, 250.0f, 250.0f); + + DisplayListBuilder builder; + builder.SaveLayer(save_rect, nullptr); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addSuppliedExpectation(rect); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, SaveLayerBoundsClipDetectionSimpleClippedRect) { + DlRect rect = DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + DlRect save_rect = DlRect::MakeLTRB(50.0f, 50.0f, 110.0f, 110.0f); + DlRect content_rect = DlRect::MakeLTRB(100.0f, 100.0f, 110.0f, 110.0f); + + DisplayListBuilder builder; + builder.SaveLayer(save_rect, nullptr); + { // + builder.DrawRect(rect, DlPaint()); + } + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addSuppliedExpectation(content_rect, true); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +TEST_F(DisplayListTest, DisjointSaveLayerBoundsProduceEmptySuppliedBounds) { + // This test was added when we fixed the Builder code to check the + // return value of the Skia Rect intersect method, but it turns out + // that the indicated case never happens in practice due to the + // internal culling during the recording process. It actually passes + // both before and after the fix, but is here to ensure the right + // behavior does not regress. + + DlRect layer_bounds = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRect draw_rect = DlRect::MakeLTRB(50.0f, 50.0f, 100.0f, 100.0f); + ASSERT_FALSE(layer_bounds.IntersectsWithRect(draw_rect)); + ASSERT_FALSE(layer_bounds.IsEmpty()); + ASSERT_FALSE(draw_rect.IsEmpty()); + + DisplayListBuilder builder; + builder.SaveLayer(layer_bounds, nullptr); + builder.DrawRect(draw_rect, DlPaint()); + builder.Restore(); + auto display_list = builder.Build(); + + SaveLayerBoundsExpector expector; + expector.addSuppliedExpectation(DlRect(), false); + display_list->Dispatch(expector); + EXPECT_TRUE(expector.all_bounds_checked()); +} + +class DepthExpector : public virtual DlOpReceiver, + virtual IgnoreAttributeDispatchHelper, + virtual IgnoreTransformDispatchHelper, + virtual IgnoreClipDispatchHelper, + virtual IgnoreDrawDispatchHelper { + public: + explicit DepthExpector(std::vector expectations) + : depth_expectations_(std::move(expectations)) {} + + void save() override { + // This method should not be called since we override the variant with + // the total_content_depth parameter. + FAIL() << "save(no depth parameter) method should not be called"; + } + + void save(uint32_t total_content_depth) override { + ASSERT_LT(index_, depth_expectations_.size()); + EXPECT_EQ(depth_expectations_[index_], total_content_depth) + << "at index " << index_; + index_++; + } + + void saveLayer(const DlRect& bounds, + SaveLayerOptions options, + const DlImageFilter* backdrop, + std::optional backdrop_id) override { + // This method should not be called since we override the variant with + // the total_content_depth parameter. + FAIL() << "saveLayer(no depth parameter) method should not be called"; + } + + void saveLayer(const DlRect& bounds, + const SaveLayerOptions& options, + uint32_t total_content_depth, + DlBlendMode max_content_mode, + const DlImageFilter* backdrop, + std::optional backdrop_id) override { + ASSERT_LT(index_, depth_expectations_.size()); + EXPECT_EQ(depth_expectations_[index_], total_content_depth) + << "at index " << index_; + index_++; + } + + bool all_depths_checked() const { + return index_ == depth_expectations_.size(); + } + + private: + size_t index_ = 0; + std::vector depth_expectations_; +}; + +TEST_F(DisplayListTest, SaveContentDepthTest) { + DisplayListBuilder child_builder; + child_builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), + DlPaint()); // depth 1 + auto child = child_builder.Build(); + + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); // depth 1 + + builder.Save(); // covers depth 1->9 + { + builder.Translate(5, 5); // triggers deferred save at depth 1 + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); // depth 2 + + builder.DrawDisplayList(child, 1.0f); // depth 3 (content) + 4 (self) + + builder.SaveLayer(std::nullopt, nullptr); // covers depth 5->6 + { + builder.DrawRect(DlRect::MakeLTRB(12, 12, 22, 22), DlPaint()); // depth 5 + builder.DrawRect(DlRect::MakeLTRB(14, 14, 24, 24), DlPaint()); // depth 6 + } + builder.Restore(); // layer is restored with depth 6 + + builder.DrawRect(DlRect::MakeLTRB(16, 16, 26, 26), DlPaint()); // depth 8 + builder.DrawRect(DlRect::MakeLTRB(18, 18, 28, 28), DlPaint()); // depth 9 + } + builder.Restore(); // save is restored with depth 9 + + builder.DrawRect(DlRect::MakeLTRB(16, 16, 26, 26), DlPaint()); // depth 10 + builder.DrawRect(DlRect::MakeLTRB(18, 18, 28, 28), DlPaint()); // depth 11 + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->total_depth(), 11u); + + DepthExpector expector({8, 2}); + display_list->Dispatch(expector); +} + +TEST_F(DisplayListTest, FloodingFilteredLayerPushesRestoreOpIndex) { + DisplayListBuilder builder(true); + builder.ClipRect(DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f)); + // ClipRect does not contribute to rtree rects, no id needed + + DlPaint save_paint; + // clang-format off + const float matrix[] = { + 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, + 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, + 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, + 0.5f, 0.0f, 0.0f, 0.0f, 0.5f + }; + // clang-format on + auto color_filter = DlColorFilter::MakeMatrix(matrix); + save_paint.setImageFilter(DlImageFilter::MakeColorFilter(color_filter)); + builder.SaveLayer(std::nullopt, &save_paint); + int save_layer_id = DisplayListBuilderTestingLastOpIndex(builder); + + builder.DrawRect(DlRect::MakeLTRB(120.0f, 120.0f, 125.0f, 125.0f), DlPaint()); + int draw_rect_id = DisplayListBuilderTestingLastOpIndex(builder); + + builder.Restore(); + int restore_id = DisplayListBuilderTestingLastOpIndex(builder); + + auto dl = builder.Build(); + std::vector indices; + dl->rtree()->search(DlRect::MakeLTRB(0.0f, 0.0f, 500.0f, 500.0f), &indices); + ASSERT_EQ(indices.size(), 3u); + EXPECT_EQ(dl->rtree()->id(indices[0]), save_layer_id); + EXPECT_EQ(dl->rtree()->id(indices[1]), draw_rect_id); + EXPECT_EQ(dl->rtree()->id(indices[2]), restore_id); +} + +TEST_F(DisplayListTest, TransformingFilterSaveLayerSimpleContentBounds) { + DisplayListBuilder builder; + builder.ClipRect(DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f)); + + DlPaint save_paint; + auto image_filter = + DlImageFilter::MakeMatrix(DlMatrix::MakeTranslation({100.0f, 100.0f}), + DlImageSampling::kNearestNeighbor); + save_paint.setImageFilter(image_filter); + builder.SaveLayer(std::nullopt, &save_paint); + + builder.DrawRect(DlRect::MakeLTRB(20.0f, 20.0f, 25.0f, 25.0f), DlPaint()); + + builder.Restore(); + + auto dl = builder.Build(); + EXPECT_EQ(dl->GetBounds(), DlRect::MakeLTRB(120.0f, 120.0f, 125.0f, 125.0f)); +} + +TEST_F(DisplayListTest, TransformingFilterSaveLayerFloodedContentBounds) { + DisplayListBuilder builder; + builder.ClipRect(DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f)); + + DlPaint save_paint; + auto image_filter = + DlImageFilter::MakeMatrix(DlMatrix::MakeTranslation({100.0f, 100.0f}), + DlImageSampling::kNearestNeighbor); + save_paint.setImageFilter(image_filter); + builder.SaveLayer(std::nullopt, &save_paint); + + builder.DrawColor(DlColor::kBlue(), DlBlendMode::kSrcOver); + + builder.Restore(); + + auto dl = builder.Build(); + EXPECT_EQ(dl->GetBounds(), DlRect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f)); +} + +TEST_F(DisplayListTest, OpacityIncompatibleRenderOpInsideDeferredSave) { + { + // Without deferred save + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kClear)); + EXPECT_FALSE(builder.Build()->can_apply_group_opacity()); + } + + { + // With deferred save + DisplayListBuilder builder; + builder.Save(); + { + // Nothing to trigger the deferred save... + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kClear)); + } + // Deferred save was not triggered, did it forward the incompatibility + // flags? + builder.Restore(); + EXPECT_FALSE(builder.Build()->can_apply_group_opacity()); + } +} + +TEST_F(DisplayListTest, MaxBlendModeEmptyDisplayList) { + DisplayListBuilder builder; + EXPECT_EQ(builder.Build()->max_root_blend_mode(), DlBlendMode::kClear); +} + +TEST_F(DisplayListTest, MaxBlendModeSimpleRect) { + auto test = [](DlBlendMode mode) { + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setAlpha(0x7f).setBlendMode(mode)); + DlBlendMode expect = + (mode == DlBlendMode::kDst) ? DlBlendMode::kClear : mode; + EXPECT_EQ(builder.Build()->max_root_blend_mode(), expect) // + << "testing " << mode; + }; + + for (int i = 0; i < static_cast(DlBlendMode::kLastMode); i++) { + test(static_cast(i)); + } +} + +TEST_F(DisplayListTest, MaxBlendModeInsideNonDeferredSave) { + DisplayListBuilder builder; + builder.Save(); + { + // Trigger the deferred save + builder.Scale(2.0f, 2.0f); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kModulate)); + } + // Save was triggered, did it forward the max blend mode? + builder.Restore(); + EXPECT_EQ(builder.Build()->max_root_blend_mode(), DlBlendMode::kModulate); +} + +TEST_F(DisplayListTest, MaxBlendModeInsideDeferredSave) { + DisplayListBuilder builder; + builder.Save(); + { + // Nothing to trigger the deferred save... + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kModulate)); + } + // Deferred save was not triggered, did it forward the max blend mode? + builder.Restore(); + EXPECT_EQ(builder.Build()->max_root_blend_mode(), DlBlendMode::kModulate); +} + +TEST_F(DisplayListTest, MaxBlendModeInsideSaveLayer) { + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kModulate)); + } + builder.Restore(); + auto dl = builder.Build(); + EXPECT_EQ(dl->max_root_blend_mode(), DlBlendMode::kSrcOver); + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(DlBlendMode::kModulate); + dl->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, MaxBlendModeInsideNonDefaultBlendedSaveLayer) { + DisplayListBuilder builder; + DlPaint save_paint; + save_paint.setBlendMode(DlBlendMode::kScreen); + builder.SaveLayer(std::nullopt, &save_paint); + { + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kModulate)); + } + builder.Restore(); + auto dl = builder.Build(); + EXPECT_EQ(dl->max_root_blend_mode(), DlBlendMode::kScreen); + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation(DlBlendMode::kModulate); + dl->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, MaxBlendModeInsideComplexDeferredSaves) { + DisplayListBuilder builder; + builder.Save(); + { + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kModulate)); + builder.Save(); + { + // We want to use a blend mode that is greater than modulate here + ASSERT_GT(DlBlendMode::kScreen, DlBlendMode::kModulate); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kScreen)); + } + builder.Restore(); + + // We want to use a blend mode that is smaller than modulate here + ASSERT_LT(DlBlendMode::kSrc, DlBlendMode::kModulate); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kSrc)); + } + builder.Restore(); + + // Double check that kScreen is the max blend mode + auto expect = std::max(DlBlendMode::kModulate, DlBlendMode::kScreen); + expect = std::max(expect, DlBlendMode::kSrc); + ASSERT_EQ(expect, DlBlendMode::kScreen); + + EXPECT_EQ(builder.Build()->max_root_blend_mode(), DlBlendMode::kScreen); +} + +TEST_F(DisplayListTest, MaxBlendModeInsideComplexSaveLayers) { + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { + // outer save layer has Modulate now and Src later - Modulate is larger + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kModulate)); + builder.SaveLayer(std::nullopt, nullptr); + { + // inner save layer only has a Screen blend + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kScreen)); + } + builder.Restore(); + + // We want to use a blend mode that is smaller than modulate here + ASSERT_LT(DlBlendMode::kSrc, DlBlendMode::kModulate); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kSrc)); + } + builder.Restore(); + + // Double check that kModulate is the max blend mode for the first + // SaveLayer operations + auto expect = std::max(DlBlendMode::kModulate, DlBlendMode::kSrc); + ASSERT_EQ(expect, DlBlendMode::kModulate); + + auto dl = builder.Build(); + EXPECT_EQ(dl->max_root_blend_mode(), DlBlendMode::kSrcOver); + SAVE_LAYER_EXPECTOR(expector); + expector // + .addExpectation(DlBlendMode::kModulate) + .addExpectation(DlBlendMode::kScreen); + dl->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, BackdropDetectionEmptyDisplayList) { + DisplayListBuilder builder; + EXPECT_FALSE(builder.Build()->root_has_backdrop_filter()); +} + +TEST_F(DisplayListTest, BackdropDetectionSimpleRect) { + DisplayListBuilder builder; + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), DlPaint()); + EXPECT_FALSE(builder.Build()->root_has_backdrop_filter()); +} + +TEST_F(DisplayListTest, BackdropDetectionSimpleSaveLayer) { + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr, &kTestBlurImageFilter1); + { + // inner content has no backdrop filter + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), DlPaint()); + } + builder.Restore(); + auto dl = builder.Build(); + + EXPECT_TRUE(dl->root_has_backdrop_filter()); + // The SaveLayer itself, though, does not have the contains backdrop + // flag set because its content does not contain a SaveLayer with backdrop + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation( + SaveLayerOptions::kNoAttributes.with_can_distribute_opacity()); + dl->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, BackdropDetectionNestedSaveLayer) { + DisplayListBuilder builder; + builder.SaveLayer(std::nullopt, nullptr); + { + // first inner content does have backdrop filter + builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), DlPaint()); + builder.SaveLayer(std::nullopt, nullptr, &kTestBlurImageFilter1); + { + // second inner content has no backdrop filter + builder.DrawRect(DlRect::MakeLTRB(10, 10, 20, 20), DlPaint()); + } + builder.Restore(); + } + builder.Restore(); + auto dl = builder.Build(); + + EXPECT_FALSE(dl->root_has_backdrop_filter()); + SAVE_LAYER_EXPECTOR(expector); + expector // + .addExpectation(SaveLayerOptions::kNoAttributes // + .with_contains_backdrop_filter() + .with_content_is_unbounded()) + .addExpectation( + SaveLayerOptions::kNoAttributes.with_can_distribute_opacity()); + dl->Dispatch(expector); + EXPECT_TRUE(expector.all_expectations_checked()); +} + +TEST_F(DisplayListTest, DrawDisplayListForwardsMaxBlend) { + DisplayListBuilder child_builder; + child_builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kMultiply)); + auto child_dl = child_builder.Build(); + EXPECT_EQ(child_dl->max_root_blend_mode(), DlBlendMode::kMultiply); + EXPECT_FALSE(child_dl->root_has_backdrop_filter()); + + DisplayListBuilder parent_builder; + parent_builder.DrawDisplayList(child_dl); + auto parent_dl = parent_builder.Build(); + EXPECT_EQ(parent_dl->max_root_blend_mode(), DlBlendMode::kMultiply); + EXPECT_FALSE(parent_dl->root_has_backdrop_filter()); +} + +TEST_F(DisplayListTest, DrawDisplayListForwardsBackdropFlag) { + DisplayListBuilder child_builder; + DlBlurImageFilter backdrop(2.0f, 2.0f, DlTileMode::kDecal); + child_builder.SaveLayer(std::nullopt, nullptr, &backdrop); + child_builder.DrawRect(DlRect::MakeLTRB(0, 0, 10, 10), + DlPaint().setBlendMode(DlBlendMode::kMultiply)); + child_builder.Restore(); + auto child_dl = child_builder.Build(); + EXPECT_EQ(child_dl->max_root_blend_mode(), DlBlendMode::kSrcOver); + EXPECT_TRUE(child_dl->root_has_backdrop_filter()); + + DisplayListBuilder parent_builder; + parent_builder.DrawDisplayList(child_dl); + auto parent_dl = parent_builder.Build(); + EXPECT_EQ(parent_dl->max_root_blend_mode(), DlBlendMode::kSrcOver); + EXPECT_TRUE(parent_dl->root_has_backdrop_filter()); +} + +#define CLIP_EXPECTOR(name) ClipExpector name(__FILE__, __LINE__) + +struct ClipExpectation { + std::variant shape; + bool is_oval; + DlClipOp clip_op; + bool is_aa; + + std::string shape_name() { + switch (shape.index()) { + case 0: + return is_oval ? "Oval" : "Rect"; + case 1: + return "DlRoundRect"; + case 2: + return "DlRoundSuperellipse"; + case 3: + return "DlPath"; + default: + return "Unknown"; + } + } +}; + +::std::ostream& operator<<(::std::ostream& os, const ClipExpectation& expect) { + os << "Expectation("; + switch (expect.shape.index()) { + case 0: + os << std::get(expect.shape); + if (expect.is_oval) { + os << " (oval)"; + } + break; + case 1: + os << std::get(expect.shape); + break; + case 2: + os << std::get(expect.shape).GetSkPath(); + break; + case 3: + os << "Unknown"; + } + os << ", " << expect.clip_op; + os << ", " << expect.is_aa; + os << ")"; + return os; +} + +class ClipExpector : public virtual DlOpReceiver, + virtual IgnoreAttributeDispatchHelper, + virtual IgnoreTransformDispatchHelper, + virtual IgnoreDrawDispatchHelper { + public: + // file and line supplied automatically from CLIP_EXPECTOR macro + explicit ClipExpector(const std::string& file, int line) + : file_(file), line_(line) {} + + ~ClipExpector() { // + EXPECT_EQ(index_, clip_expectations_.size()) << label(); + while (index_ < clip_expectations_.size()) { + auto expect = clip_expectations_[index_]; + FML_LOG(ERROR) << "leftover clip shape[" << index_ << "] = " << expect; + index_++; + } + } + + ClipExpector& addExpectation(const DlRect& rect, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) { + clip_expectations_.push_back({ + .shape = rect, + .is_oval = false, + .clip_op = clip_op, + .is_aa = is_aa, + }); + return *this; + } + + ClipExpector& addOvalExpectation(const DlRect& rect, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) { + clip_expectations_.push_back({ + .shape = rect, + .is_oval = true, + .clip_op = clip_op, + .is_aa = is_aa, + }); + return *this; + } + + ClipExpector& addExpectation(const DlRoundRect& rrect, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) { + clip_expectations_.push_back({ + .shape = rrect, + .is_oval = false, + .clip_op = clip_op, + .is_aa = is_aa, + }); + return *this; + } + + ClipExpector& addExpectation(const DlPath& path, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) { + clip_expectations_.push_back({ + .shape = path, + .is_oval = false, + .clip_op = clip_op, + .is_aa = is_aa, + }); + return *this; + } + + void clipRect(const DlRect& rect, DlClipOp clip_op, bool is_aa) override { + check(rect, clip_op, is_aa); + } + void clipOval(const DlRect& bounds, DlClipOp clip_op, bool is_aa) override { + check(bounds, clip_op, is_aa, true); + } + void clipRoundRect(const DlRoundRect& rrect, + DlClipOp clip_op, + bool is_aa) override { + check(rrect, clip_op, is_aa); + } + void clipRoundSuperellipse(const DlRoundSuperellipse& rse, + DlClipOp clip_op, + bool is_aa) override { + check(rse, clip_op, is_aa); + } + void clipPath(const DlPath& path, DlClipOp clip_op, bool is_aa) override { + check(path, clip_op, is_aa); + } + + private: + size_t index_ = 0; + std::vector clip_expectations_; + + template + void check(T shape, DlClipOp clip_op, bool is_aa, bool is_oval = false) { + ASSERT_LT(index_, clip_expectations_.size()) + << label() << std::endl + << "extra clip shape = " << shape << (is_oval ? " (oval)" : ""); + auto expected = clip_expectations_[index_]; + if (!std::holds_alternative(expected.shape)) { + EXPECT_TRUE(std::holds_alternative(expected.shape)) + << label() << ", expected type: " << expected.shape_name(); + } else { + EXPECT_EQ(std::get(expected.shape), shape) << label(); + } + EXPECT_EQ(expected.is_oval, is_oval) << label(); + EXPECT_EQ(expected.clip_op, clip_op) << label(); + EXPECT_EQ(expected.is_aa, is_aa) << label(); + index_++; + } + + const std::string file_; + const int line_; + + std::string label() { + return "at index " + std::to_string(index_) + // + ", from " + file_ + // + ":" + std::to_string(line_); + } +}; + +TEST_F(DisplayListTest, ClipRectCullingPixel6a) { + // These particular values create bit errors if we use the path that + // tests for inclusion in local space, but work OK if we use a forward + // path that tests for inclusion in device space, due to the fact that + // the extra matrix inversion is just enough math to cause the transform + // to place the local space cull corners just outside the original rect. + // The test in device space only works under a simple scale, such as we + // use for DPR adjustments (and which are not always inversion friendly). + + auto frame = DlRect::MakeLTRB(0.0f, 0.0f, 1080.0f, 2400.0f); + DlScalar DPR = 2.625f; + auto clip = DlRect::MakeLTRB(0.0f, 0.0f, 1080.0f / DPR, 2400.0f / DPR); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(frame, DlClipOp::kIntersect, false); + cull_builder.Scale(DPR, DPR); + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(frame, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRectCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipRect(clip.Expand(1.0f, 1.0f), DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRectNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto smaller_clip = clip.Expand(-1.0f, -1.0f); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipRect(smaller_clip, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + expector.addExpectation(smaller_clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRectNestedCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto larger_clip = clip.Expand(1.0f, 1.0f); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.Save(); + cull_builder.ClipRect(larger_clip, DlClipOp::kIntersect, false); + cull_builder.Restore(); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRectNestedNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto larger_clip = clip.Expand(1.0f, 1.0f); + + DisplayListBuilder cull_builder; + cull_builder.Save(); + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.Restore(); + // Should not be culled because we have restored the prior clip + cull_builder.ClipRect(larger_clip, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + expector.addExpectation(larger_clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRectNestedCullingComplex) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto smaller_clip = clip.Expand(-1.0f, -1.0f); + auto smallest_clip = clip.Expand(-2.0f, -2.0f); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.Save(); + cull_builder.ClipRect(smallest_clip, DlClipOp::kIntersect, false); + cull_builder.ClipRect(smaller_clip, DlClipOp::kIntersect, false); + cull_builder.Restore(); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + expector.addExpectation(smallest_clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRectNestedNonCullingComplex) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto smaller_clip = clip.Expand(-1.0f, -1.0f); + auto smallest_clip = clip.Expand(-2.0f, -2.0f); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.Save(); + cull_builder.ClipRect(smallest_clip, DlClipOp::kIntersect, false); + cull_builder.Restore(); + // Would not be culled if it was inside the clip + cull_builder.ClipRect(smaller_clip, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + expector.addExpectation(smallest_clip, DlClipOp::kIntersect, false); + expector.addExpectation(smaller_clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipOvalCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + // A 10x10 rectangle extends 5x5 from the center to each corner. To have + // an oval that encompasses that rectangle, the radius must be at least + // length(5, 5), or 7.071+ so we expand the radius 5 square clip by 2.072 + // on each side to barely contain the corners of the square. + auto encompassing_oval = clip.Expand(2.072f, 2.072f); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipOval(encompassing_oval, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipOvalNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + // A 10x10 rectangle extends 5x5 from the center to each corner. To have + // an oval that encompasses that rectangle, the radius must be at least + // length(5, 5), or 7.071+ so we expand the radius 5 square clip by 2.072 + // on each side to barely exclude the corners of the square. + auto non_encompassing_oval = clip.Expand(2.071f, 2.071f); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipOval(non_encompassing_oval, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + expector.addOvalExpectation(non_encompassing_oval, DlClipOp::kIntersect, + false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRRectCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto rrect = DlRoundRect::MakeRectXY(clip.Expand(2.0f, 2.0f), 2.0f, 2.0f); + ASSERT_FALSE(rrect.IsOval()); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipRoundRect(rrect, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipRRectNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto rrect = DlRoundRect::MakeRectXY(clip.Expand(1.0f, 1.0f), 4.0f, 4.0f); + ASSERT_FALSE(rrect.IsOval()); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipRoundRect(rrect, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + expector.addExpectation(rrect, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipPathNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlPathBuilder path_builder; + path_builder.MoveTo({0.0f, 0.0f}); + path_builder.LineTo({1000.0f, 0.0f}); + path_builder.LineTo({0.0f, 1000.0f}); + path_builder.Close(); + DlPath path = DlPath(path_builder); + + // Double checking that the path does indeed contain the clip. But, + // sadly, the Builder will not check paths for coverage to this level + // of detail. (In particular, path containment of the corners is not + // authoritative of true containment, but we know in this case that + // a triangle contains a rect if it contains all 4 corners...) + ASSERT_TRUE(path.Contains(clip.GetLeftTop())); + ASSERT_TRUE(path.Contains(clip.GetRightTop())); + ASSERT_TRUE(path.Contains(clip.GetRightBottom())); + ASSERT_TRUE(path.Contains(clip.GetLeftBottom())); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipPath(path, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + expector.addExpectation(path, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipPathRectCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlPath path = DlPath::MakeRect(clip.Expand(1.0f, 1.0f)); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipPath(path, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipPathRectNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto smaller_clip = clip.Expand(-1.0f, -1.0f); + DlPath path = DlPath::MakeRect(smaller_clip); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipPath(path, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + // Builder will not cull this clip, but it will turn it into a ClipRect + expector.addExpectation(smaller_clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipPathOvalCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + // A 10x10 rectangle extends 5x5 from the center to each corner. To have + // an oval that encompasses that rectangle, the radius must be at least + // length(5, 5), or 7.071+ so we expand the radius 5 square clip by 2.072 + // on each side to barely contain the corners of the square. + auto encompassing_oval = clip.Expand(2.072f, 2.072f); + DlPath path = DlPath::MakeOval(encompassing_oval); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipPath(path, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipPathOvalNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + // A 10x10 rectangle extends 5x5 from the center to each corner. To have + // an oval that encompasses that rectangle, the radius must be at least + // length(5, 5), or 7.071+ so we expand the radius 5 square clip by 2.072 + // on each side to barely exclude the corners of the square. + auto non_encompassing_oval = clip.Expand(2.071f, 2.071f); + DlPath path = DlPath::MakeOval(non_encompassing_oval); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipPath(path, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + // Builder will not cull this clip, but it will turn it into a ClipOval + expector.addOvalExpectation(non_encompassing_oval, DlClipOp::kIntersect, + false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipPathRRectCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlPath path = DlPath::MakeRoundRectXY(clip.Expand(2.0f, 2.0f), 2.0f, 2.0f); + ASSERT_FALSE(path.IsOval()); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipPath(path, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, ClipPathRRectNonCulling) { + auto clip = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + auto rrect = DlRoundRect::MakeRectXY(clip.Expand(1.0f, 1.0f), 4.0f, 4.0f); + ASSERT_FALSE(rrect.IsOval()); + DlPath path = DlPath::MakeRoundRect(rrect); + + DisplayListBuilder cull_builder; + cull_builder.ClipRect(clip, DlClipOp::kIntersect, false); + cull_builder.ClipPath(path, DlClipOp::kIntersect, false); + auto cull_dl = cull_builder.Build(); + + CLIP_EXPECTOR(expector); + expector.addExpectation(clip, DlClipOp::kIntersect, false); + // Builder will not cull this clip, but it will turn it into a ClipRRect + expector.addExpectation(rrect, DlClipOp::kIntersect, false); + cull_dl->Dispatch(expector); +} + +TEST_F(DisplayListTest, RecordLargeVertices) { + constexpr size_t vertex_count = 2000000; + auto points = std::vector(); + points.reserve(vertex_count); + auto colors = std::vector(); + colors.reserve(vertex_count); + for (size_t i = 0; i < vertex_count; i++) { + colors.emplace_back(DlColor(-i)); + points.emplace_back(((i & 1) == 0) ? DlPoint(-i, i) : DlPoint(i, i)); + } + ASSERT_EQ(points.size(), vertex_count); + ASSERT_EQ(colors.size(), vertex_count); + auto vertices = DlVertices::Make(DlVertexMode::kTriangleStrip, vertex_count, + points.data(), points.data(), colors.data()); + ASSERT_GT(vertices->size(), 1u << 24); + auto backdrop = DlImageFilter::MakeBlur(5.0f, 5.0f, DlTileMode::kDecal); + + for (int i = 0; i < 1000; i++) { + DisplayListBuilder builder; + for (int j = 0; j < 16; j++) { + builder.SaveLayer(std::nullopt, nullptr, backdrop.get()); + builder.DrawVertices(vertices, DlBlendMode::kSrcOver, DlPaint()); + builder.Restore(); + } + auto dl = builder.Build(); + } +} + +TEST_F(DisplayListTest, DrawRectRRectPromoteToDrawRect) { + DlRect rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + + DisplayListBuilder builder; + builder.DrawRoundRect(DlRoundRect::MakeRect(rect), DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.DrawRect(rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, DrawOvalRRectPromoteToDrawOval) { + DlRect rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + + DisplayListBuilder builder; + builder.DrawRoundRect(DlRoundRect::MakeOval(rect), DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.DrawOval(rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, DrawRectPathPromoteToDrawRect) { + DlRect rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + + DisplayListBuilder builder; + builder.DrawPath(DlPath::MakeRect(rect), DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.DrawRect(rect, DlPaint()); + auto expect_dl = expected.Build(); + + // Support for this will be re-added soon, until then verify that we + // do not promote. + ASSERT_TRUE(DisplayListsNE_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, DrawOvalPathPromoteToDrawOval) { + DlRect rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + + DisplayListBuilder builder; + builder.DrawPath(DlPath::MakeOval(rect), DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.DrawOval(rect, DlPaint()); + auto expect_dl = expected.Build(); + + // Support for this will be re-added soon, until then verify that we + // do not promote. + ASSERT_TRUE(DisplayListsNE_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, DrawRRectPathPromoteToDrawRoundRect) { + DlRect rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRoundRect rrect = DlRoundRect::MakeRectXY(rect, 2.0f, 2.0f); + + DisplayListBuilder builder; + builder.DrawPath(DlPath::MakeRoundRect(rrect), DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.DrawRoundRect(rrect, DlPaint()); + auto expect_dl = expected.Build(); + + // Support for this will be re-added soon, until then verify that we + // do not promote. + ASSERT_TRUE(DisplayListsNE_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, DrawRectRoundRectPathPromoteToDrawRect) { + DlRect rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRoundRect rrect = DlRoundRect::MakeRect(rect); + + DisplayListBuilder builder; + builder.DrawPath(DlPath::MakeRoundRect(rrect), DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.DrawRect(rect, DlPaint()); + auto expect_dl = expected.Build(); + + // Support for this will be re-added soon, until then verify that we + // do not promote. + ASSERT_TRUE(DisplayListsNE_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, DrawOvalRRectPathPromoteToDrawOval) { + DlRect rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRoundRect rrect = DlRoundRect::MakeOval(rect); + + DisplayListBuilder builder; + builder.DrawPath(DlPath::MakeRoundRect(rrect), DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.DrawOval(rect, DlPaint()); + auto expect_dl = expected.Build(); + + // Support for this will be re-added soon, until then verify that we + // do not promote. + ASSERT_TRUE(DisplayListsNE_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, ClipRectRRectPromoteToClipRect) { + DlRect clip_rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRect draw_rect = clip_rect.Expand(2.0f, 2.0f); + + DisplayListBuilder builder; + builder.ClipRoundRect(DlRoundRect::MakeRect(clip_rect), DlClipOp::kIntersect, + false); + // Include a rendering op in case DlBuilder ever removes unneeded clips + builder.DrawRect(draw_rect, DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.ClipRect(clip_rect, DlClipOp::kIntersect, false); + expected.DrawRect(draw_rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, ClipOvalRRectPromoteToClipOval) { + DlRect clip_rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRect draw_rect = clip_rect.Expand(2.0f, 2.0f); + + DisplayListBuilder builder; + builder.ClipRoundRect(DlRoundRect::MakeOval(clip_rect), DlClipOp::kIntersect, + false); + // Include a rendering op in case DlBuilder ever removes unneeded clips + builder.DrawRect(draw_rect, DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.ClipOval(clip_rect, DlClipOp::kIntersect, false); + expected.DrawRect(draw_rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, ClipRectPathPromoteToClipRect) { + DlRect clip_rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRect draw_rect = clip_rect.Expand(2.0f, 2.0f); + DlPath clip_path = DlPath::MakeRect(clip_rect); + ASSERT_TRUE(clip_path.IsRect(nullptr)); + + DisplayListBuilder builder; + builder.ClipPath(clip_path, DlClipOp::kIntersect, false); + // Include a rendering op in case DlBuilder ever removes unneeded clips + builder.DrawRect(draw_rect, DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.ClipRect(clip_rect, DlClipOp::kIntersect, false); + expected.DrawRect(draw_rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, ClipOvalPathPromoteToClipOval) { + DlRect clip_rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRect draw_rect = clip_rect.Expand(2.0f, 2.0f); + DlPath clip_path = DlPath::MakeOval(clip_rect); + ASSERT_TRUE(clip_path.IsOval(nullptr)); + + DisplayListBuilder builder; + builder.ClipPath(clip_path, DlClipOp::kIntersect, false); + // Include a rendering op in case DlBuilder ever removes unneeded clips + builder.DrawRect(draw_rect, DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.ClipOval(clip_rect, DlClipOp::kIntersect, false); + expected.DrawRect(draw_rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, ClipRRectPathPromoteToClipRRect) { + DlRect clip_rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRoundRect clip_rrect = DlRoundRect::MakeRectXY(clip_rect, 2.0f, 2.0f); + DlRect draw_rect = clip_rect.Expand(2.0f, 2.0f); + DlPath clip_path = DlPath::MakeRoundRect(clip_rrect); + ASSERT_TRUE(clip_path.IsRoundRect()); + + DisplayListBuilder builder; + builder.ClipPath(clip_path, DlClipOp::kIntersect, false); + // Include a rendering op in case DlBuilder ever removes unneeded clips + builder.DrawRect(draw_rect, DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.ClipRoundRect(clip_rrect, DlClipOp::kIntersect, false); + expected.DrawRect(draw_rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, ClipRectRRectPathPromoteToClipRect) { + DlRect clip_rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRoundRect clip_rrect = DlRoundRect::MakeRect(clip_rect); + DlRect draw_rect = clip_rect.Expand(2.0f, 2.0f); + DlPath clip_path = DlPath::MakeRoundRect(clip_rrect); + ASSERT_TRUE(clip_path.IsRoundRect()); + + DisplayListBuilder builder; + builder.ClipPath(clip_path, DlClipOp::kIntersect, false); + // Include a rendering op in case DlBuilder ever removes unneeded clips + builder.DrawRect(draw_rect, DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.ClipRect(clip_rect, DlClipOp::kIntersect, false); + expected.DrawRect(draw_rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, ClipOvalRRectPathPromoteToClipOval) { + DlRect clip_rect = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRoundRect clip_rrect = DlRoundRect::MakeOval(clip_rect); + DlRect draw_rect = clip_rect.Expand(2.0f, 2.0f); + DlPath clip_path = DlPath::MakeRoundRect(clip_rrect); + ASSERT_TRUE(clip_path.IsRoundRect()); + + DisplayListBuilder builder; + builder.ClipPath(clip_path, DlClipOp::kIntersect, false); + // Include a rendering op in case DlBuilder ever removes unneeded clips + builder.DrawRect(draw_rect, DlPaint()); + auto dl = builder.Build(); + + DisplayListBuilder expected; + expected.ClipOval(clip_rect, DlClipOp::kIntersect, false); + expected.DrawRect(draw_rect, DlPaint()); + auto expect_dl = expected.Build(); + + ASSERT_TRUE(DisplayListsEQ_Verbose(dl, expect_dl)); +} + +TEST_F(DisplayListTest, BoundedRenderOpsDoNotReportUnbounded) { + static const DlRect root_cull = DlRect::MakeLTRB(100, 100, 200, 200); + static const DlRect draw_rect = DlRect::MakeLTRB(110, 110, 190, 190); + + using Renderer = const std::function; + auto test_bounded = [](const std::string& label, const Renderer& renderer) { + { + DisplayListBuilder builder(root_cull); + renderer(builder); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->GetBounds(), draw_rect) << label; + EXPECT_FALSE(display_list->root_is_unbounded()) << label; + } + + { + DisplayListBuilder builder(root_cull); + builder.SaveLayer(std::nullopt, nullptr); + renderer(builder); + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->GetBounds(), draw_rect) << label; + EXPECT_FALSE(display_list->root_is_unbounded()) << label; + + SAVE_LAYER_EXPECTOR(expector); + expector // + .addDetail(label) + .addExpectation([](const SaveLayerOptions& options) { + return !options.content_is_unbounded(); + }); + display_list->Dispatch(expector); + } + }; + + test_bounded("DrawLine", [](DlCanvas& builder) { + builder.DrawLine( + DlPoint(draw_rect.GetLeft() + 1.0f, draw_rect.GetTop() + 1.0f), + DlPoint(draw_rect.GetRight() - 1.0f, draw_rect.GetTop() + 1.0f), + DlPaint().setStrokeWidth(2.0f).setStrokeCap(DlStrokeCap::kSquare)); + builder.DrawLine( + DlPoint(draw_rect.GetLeft() + 1.0f, draw_rect.GetBottom() - 1.0f), + DlPoint(draw_rect.GetRight() - 1.0f, draw_rect.GetBottom() - 1.0f), + DlPaint().setStrokeWidth(2.0f).setStrokeCap(DlStrokeCap::kSquare)); + }); + + test_bounded("DrawDashedLine", [](DlCanvas& builder) { + builder.DrawDashedLine( + DlPoint(draw_rect.GetLeft() + 1.0f, draw_rect.GetTop() + 1.0f), + DlPoint(draw_rect.GetRight() - 1.0f, draw_rect.GetTop() + 1.0f), + // must fill 80 x 80 square with on dashes at both + // ends - 40 + 25 + 40 == 105 so it will be on + // at both ends + 40.0f, 25.0f, + DlPaint().setStrokeWidth(2.0f).setStrokeCap(DlStrokeCap::kSquare)); + builder.DrawDashedLine( + DlPoint(draw_rect.GetLeft() + 1.0f, draw_rect.GetBottom() - 1.0f), + DlPoint(draw_rect.GetRight() - 1.0f, draw_rect.GetBottom() - 1.0f), + // must fill 80 x 80 square with on dashes at both + // ends - 40 + 25 + 40 == 105 so it will be on + // at both ends + 40.0f, 25.0f, + DlPaint().setStrokeWidth(2.0f).setStrokeCap(DlStrokeCap::kSquare)); + }); + + test_bounded("DrawRect", [](DlCanvas& builder) { + builder.DrawRect(draw_rect, DlPaint()); + }); + + test_bounded("DrawOval", [](DlCanvas& builder) { + builder.DrawOval(draw_rect, DlPaint()); + }); + + test_bounded("DrawCircle", [](DlCanvas& builder) { + builder.DrawCircle(draw_rect.GetCenter(), draw_rect.GetWidth() * 0.5f, + DlPaint()); + }); + + test_bounded("DrawRoundRect", [](DlCanvas& builder) { + builder.DrawRoundRect(DlRoundRect::MakeRectXY(draw_rect, 5.0f, 5.0f), + DlPaint()); + }); + + test_bounded("DrawDiffRoundRect", [](DlCanvas& builder) { + builder.DrawDiffRoundRect( + DlRoundRect::MakeRectXY(draw_rect, 5.0f, 5.0f), + DlRoundRect::MakeRectXY(draw_rect.Expand(-10.0f, -10.0f), 5.0f, 5.0f), + DlPaint()); + }); + + test_bounded("DrawArc", [](DlCanvas& builder) { + builder.DrawArc(draw_rect, 45.0f, 355.0f, false, DlPaint()); + }); + + test_bounded("DrawPathEvenOdd", [](DlCanvas& builder) { + DlPath path = + DlPath::MakeRect(draw_rect).WithFillType(DlPathFillType::kOdd); + builder.DrawPath(path, DlPaint()); + }); + + test_bounded("DrawPathWinding", [](DlCanvas& builder) { + DlPath path = + DlPath::MakeRect(draw_rect).WithFillType(DlPathFillType::kNonZero); + builder.DrawPath(path, DlPaint()); + }); + + auto test_draw_points = [&test_bounded](DlPointMode mode) { + std::stringstream ss; + ss << "DrawPoints(" << mode << ")"; + test_bounded(ss.str(), [mode](DlCanvas& builder) { + DlPoint points[4] = { + DlPoint(draw_rect.GetLeft() + 1.0f, draw_rect.GetTop() + 1.0f), + DlPoint(draw_rect.GetRight() - 1.0f, draw_rect.GetTop() + 1.0f), + DlPoint(draw_rect.GetRight() - 1.0f, draw_rect.GetBottom() - 1.0f), + DlPoint(draw_rect.GetLeft() + 1.0f, draw_rect.GetBottom() - 1.0f), + }; + DlPaint paint; + paint.setStrokeWidth(2.0f); + paint.setDrawStyle(DlDrawStyle::kStroke); + // bounds accumulation doesn't examine the points to see if they + // have diagonals so Square caps may have their corners accumulated + // but Round caps will always pad by only half the stroke width. + paint.setStrokeCap(DlStrokeCap::kRound); + + builder.DrawPoints(mode, 4, points, paint); + }); + }; + + test_draw_points(DlPointMode::kPoints); + test_draw_points(DlPointMode::kLines); + test_draw_points(DlPointMode::kPolygon); + + test_bounded("DrawVerticesTriangles", [](DlCanvas& builder) { + DlPoint points[6] = { + DlPoint(draw_rect.GetLeft(), draw_rect.GetTop()), + DlPoint(draw_rect.GetRight(), draw_rect.GetTop()), + DlPoint(draw_rect.GetRight(), draw_rect.GetBottom()), + DlPoint(draw_rect.GetRight(), draw_rect.GetBottom()), + DlPoint(draw_rect.GetLeft(), draw_rect.GetBottom()), + DlPoint(draw_rect.GetLeft(), draw_rect.GetTop()), + }; + DlVertices::Builder vertices(DlVertexMode::kTriangles, 6, + DlVertices::Builder::kNone, 0); + vertices.store_vertices(points); + builder.DrawVertices(vertices.build(), DlBlendMode::kSrcOver, DlPaint()); + }); + + test_bounded("DrawVerticesTriangleStrip", [](DlCanvas& builder) { + DlPoint points[6] = { + DlPoint(draw_rect.GetLeft(), draw_rect.GetTop()), + DlPoint(draw_rect.GetRight(), draw_rect.GetTop()), + DlPoint(draw_rect.GetRight(), draw_rect.GetBottom()), + DlPoint(draw_rect.GetLeft(), draw_rect.GetBottom()), + DlPoint(draw_rect.GetLeft(), draw_rect.GetTop()), + DlPoint(draw_rect.GetRight(), draw_rect.GetTop()), + }; + DlVertices::Builder vertices(DlVertexMode::kTriangleStrip, 6, + DlVertices::Builder::kNone, 0); + vertices.store_vertices(points); + builder.DrawVertices(vertices.build(), DlBlendMode::kSrcOver, DlPaint()); + }); + + test_bounded("DrawVerticesTriangleFan", [](DlCanvas& builder) { + DlPoint points[6] = { + draw_rect.GetCenter(), + DlPoint(draw_rect.GetLeft(), draw_rect.GetTop()), + DlPoint(draw_rect.GetRight(), draw_rect.GetTop()), + DlPoint(draw_rect.GetRight(), draw_rect.GetBottom()), + DlPoint(draw_rect.GetLeft(), draw_rect.GetBottom()), + }; + DlVertices::Builder vertices(DlVertexMode::kTriangleFan, 5, + DlVertices::Builder::kNone, 0); + vertices.store_vertices(points); + builder.DrawVertices(vertices.build(), DlBlendMode::kSrcOver, DlPaint()); + }); + + test_bounded("DrawImage", [](DlCanvas& builder) { + auto image = MakeTestImage(draw_rect.GetWidth(), draw_rect.GetHeight(), 5); + builder.DrawImage(image, DlPoint(draw_rect.GetLeft(), draw_rect.GetTop()), + DlImageSampling::kLinear); + }); + + test_bounded("DrawImageRect", [](DlCanvas& builder) { + auto image = MakeTestImage(root_cull.GetWidth(), root_cull.GetHeight(), 5); + builder.DrawImageRect(image, draw_rect, DlImageSampling::kLinear); + }); + + test_bounded("DrawImageNine", [](DlCanvas& builder) { + auto image = MakeTestImage(root_cull.GetWidth(), root_cull.GetHeight(), 5); + DlIRect center = image->GetBounds().Expand(-10, -10); + builder.DrawImageNine(image, center, draw_rect, DlFilterMode::kLinear); + }); + + test_bounded("DrawTextBlob", [](DlCanvas& builder) { + auto blob = GetTestTextBlob("Hello"); + + // Make sure the blob fits within the draw_rect bounds. + ASSERT_LT(blob->bounds().width(), draw_rect.GetWidth()); + ASSERT_LT(blob->bounds().height(), draw_rect.GetHeight()); + + // Draw once at upper left and again at lower right to fill the bounds. + builder.DrawTextBlob(blob, draw_rect.GetLeft() - blob->bounds().left(), + draw_rect.GetTop() - blob->bounds().top(), DlPaint()); + builder.DrawTextBlob(blob, draw_rect.GetRight() - blob->bounds().right(), + draw_rect.GetBottom() - blob->bounds().bottom(), + DlPaint()); + }); + + test_bounded("DrawTextFrame", [](DlCanvas& builder) { + auto blob = GetTestTextBlob("Hello"); + auto frame = impeller::MakeTextFrameFromTextBlobSkia(blob); + + // Make sure the blob fits within the draw_rect bounds. + ASSERT_LT(blob->bounds().width(), draw_rect.GetWidth()); + ASSERT_LT(blob->bounds().height(), draw_rect.GetHeight()); + + // Draw once at upper left and again at lower right to fill the bounds. + builder.DrawTextFrame(frame, draw_rect.GetLeft() - blob->bounds().left(), + draw_rect.GetTop() - blob->bounds().top(), DlPaint()); + builder.DrawTextFrame(frame, draw_rect.GetRight() - blob->bounds().right(), + draw_rect.GetBottom() - blob->bounds().bottom(), + DlPaint()); + }); + + test_bounded("DrawBoundedDisplayList", [](DlCanvas& builder) { + DisplayListBuilder nested_builder(root_cull); + nested_builder.DrawRect(draw_rect, DlPaint()); + auto nested_display_list = nested_builder.Build(); + + EXPECT_EQ(nested_display_list->GetBounds(), draw_rect); + ASSERT_FALSE(nested_display_list->root_is_unbounded()); + + builder.DrawDisplayList(nested_display_list); + }); + + test_bounded("DrawShadow", [](DlCanvas& builder) { + DlPath path = DlPath::MakeRect(draw_rect.Expand(-20, -20)); + DlScalar elevation = 2.0f; + DlScalar dpr = 1.0f; + auto shadow_bounds = + DlCanvas::ComputeShadowBounds(path, elevation, dpr, DlMatrix()); + + // Make sure the shadow fits within the draw_rect bounds. + ASSERT_LT(shadow_bounds.GetWidth(), draw_rect.GetWidth()); + ASSERT_LT(shadow_bounds.GetHeight(), draw_rect.GetHeight()); + + // Draw once at upper left and again at lower right to fill the bounds. + DlPath pathUL = + path.WithOffset(draw_rect.GetLeftTop() - shadow_bounds.GetLeftTop()); + builder.DrawShadow(pathUL, DlColor::kMagenta(), elevation, true, dpr); + DlPath pathLR = path.WithOffset(draw_rect.GetRightBottom() - + shadow_bounds.GetRightBottom()); + builder.DrawShadow(pathLR, DlColor::kMagenta(), elevation, true, dpr); + }); + + for (int i = 0; i <= static_cast(DlBlendMode::kLastMode); i++) { + DlBlendMode mode = static_cast(i); + if (mode == DlBlendMode::kDst) { + // No way to make kDst a non-nop + continue; + } + std::stringstream ss; + ss << "DrawRectWith" << mode; + test_bounded(ss.str(), [mode](DlCanvas& builder) { + // alpha of 0x7f prevents kDstIn from being a nop + builder.DrawRect(draw_rect, DlPaint().setBlendMode(mode).setAlpha(0x7f)); + }); + } +} + +TEST_F(DisplayListTest, UnboundedRenderOpsAreReportedUnlessClipped) { + static const DlRect root_cull = DlRect::MakeLTRB(100, 100, 200, 200); + static const DlRect clip_rect = DlRect::MakeLTRB(120, 120, 180, 180); + static const DlRect draw_rect = DlRect::MakeLTRB(110, 110, 190, 190); + + using Renderer = const std::function; + auto test_unbounded = [](const std::string& label, // + const Renderer& renderer, + int extra_save_layers = 0) { + { + DisplayListBuilder builder(root_cull); + renderer(builder); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->GetBounds(), root_cull) << label; + EXPECT_TRUE(display_list->root_is_unbounded()) << label; + } + + { + DisplayListBuilder builder(root_cull); + builder.ClipRect(clip_rect); + renderer(builder); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->GetBounds(), clip_rect) << label; + EXPECT_FALSE(display_list->root_is_unbounded()) << label; + } + + { + DisplayListBuilder builder(root_cull); + builder.SaveLayer(std::nullopt, nullptr); + renderer(builder); + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->GetBounds(), root_cull) << label; + EXPECT_FALSE(display_list->root_is_unbounded()) << label; + + SAVE_LAYER_EXPECTOR(expector); + expector // + .addDetail(label) + .addExpectation([](const SaveLayerOptions& options) { + return options.content_is_unbounded(); + }); + for (int i = 0; i < extra_save_layers; i++) { + expector.addOpenExpectation(); + } + display_list->Dispatch(expector); + } + + { + DisplayListBuilder builder(root_cull); + builder.SaveLayer(std::nullopt, nullptr); + builder.ClipRect(clip_rect); + renderer(builder); + builder.Restore(); + auto display_list = builder.Build(); + + EXPECT_EQ(display_list->GetBounds(), clip_rect) << label; + EXPECT_FALSE(display_list->root_is_unbounded()) << label; + + SAVE_LAYER_EXPECTOR(expector); + expector // + .addDetail(label) + .addExpectation([](const SaveLayerOptions& options) { + return !options.content_is_unbounded(); + }); + for (int i = 0; i < extra_save_layers; i++) { + expector.addOpenExpectation(); + } + display_list->Dispatch(expector); + } + }; + + test_unbounded("DrawPaint", [](DlCanvas& builder) { // + builder.DrawPaint(DlPaint()); + }); + + test_unbounded("DrawColor", [](DlCanvas& builder) { + builder.DrawColor(DlColor::kMagenta(), DlBlendMode::kSrc); + }); + + test_unbounded("Clear", [](DlCanvas& builder) { // + builder.Clear(DlColor::kMagenta()); + }); + + test_unbounded("DrawUnboundedDisplayList", [](DlCanvas& builder) { + DisplayListBuilder nested_builder(root_cull); + nested_builder.DrawPaint(DlPaint()); + auto nested_display_list = nested_builder.Build(); + + EXPECT_EQ(nested_display_list->GetBounds(), root_cull); + ASSERT_TRUE(nested_display_list->root_is_unbounded()); + + builder.DrawDisplayList(nested_display_list); + }); + + test_unbounded("DrawRectWithUnboundedImageFilter", [](DlCanvas& builder) { + // clang-format off + const DlScalar matrix[20] = { + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, + }; + // clang-format on + auto unbounded_cf = DlColorFilter::MakeMatrix(matrix); + // ColorFilter must modify transparent black to be "unbounded" + ASSERT_TRUE(unbounded_cf->modifies_transparent_black()); + auto unbounded_if = DlImageFilter::MakeColorFilter(unbounded_cf); + DlRect output_bounds; + // ImageFilter returns null from bounds queries if it is "unbounded" + ASSERT_EQ(unbounded_if->map_local_bounds(draw_rect, output_bounds), + nullptr); + + builder.DrawRect(draw_rect, DlPaint().setImageFilter(unbounded_if)); + }); + + test_unbounded( + "SaveLayerWithBackdropFilter", + [](DlCanvas& builder) { + auto filter = DlImageFilter::MakeBlur(3.0f, 3.0f, DlTileMode::kMirror); + builder.SaveLayer(std::nullopt, nullptr, filter.get()); + builder.Restore(); + }, + 1); +} + +TEST_F(DisplayListTest, BackdropFilterCulledAlongsideClipAndTransform) { + DlRect frame_bounds = DlRect::MakeWH(100.0f, 100.0f); + DlRect frame_clip = frame_bounds.Expand(-0.5f, -0.5f); + + DlRect clip_rect = DlRect::MakeLTRB(40.0f, 40.0f, 60.0f, 60.0f); + DlRect draw_rect1 = DlRect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f); + DlRect draw_rect2 = DlRect::MakeLTRB(45.0f, 20.0f, 55.0f, 55.0f); + DlRect cull_rect = DlRect::MakeLTRB(1.0f, 1.0f, 99.0f, 30.0f); + auto bdf_filter = DlImageFilter::MakeBlur(5.0f, 5.0f, DlTileMode::kClamp); + + ASSERT_TRUE(frame_bounds.Contains(clip_rect)); + ASSERT_TRUE(frame_bounds.Contains(draw_rect1)); + ASSERT_TRUE(frame_bounds.Contains(draw_rect2)); + ASSERT_TRUE(frame_bounds.Contains(cull_rect)); + + ASSERT_TRUE(frame_clip.Contains(clip_rect)); + ASSERT_TRUE(frame_clip.Contains(draw_rect1)); + ASSERT_TRUE(frame_clip.Contains(draw_rect2)); + ASSERT_TRUE(frame_clip.Contains(cull_rect)); + + ASSERT_FALSE(clip_rect.IntersectsWithRect(draw_rect1)); + ASSERT_TRUE(clip_rect.IntersectsWithRect(draw_rect2)); + + ASSERT_FALSE(cull_rect.IntersectsWithRect(clip_rect)); + ASSERT_TRUE(cull_rect.IntersectsWithRect(draw_rect1)); + ASSERT_TRUE(cull_rect.IntersectsWithRect(draw_rect2)); + + DisplayListBuilder builder(frame_bounds, true); + builder.Save(); + { + builder.Translate(0.1f, 0.1f); + builder.ClipRect(frame_clip); + builder.DrawRect(draw_rect1, DlPaint()); + // Should all be culled below + builder.ClipRect(clip_rect); + builder.Translate(0.1f, 0.1f); + builder.SaveLayer(std::nullopt, nullptr, bdf_filter.get()); + { // + builder.DrawRect(clip_rect, DlPaint()); + } + builder.Restore(); + // End of culling + } + builder.Restore(); + builder.DrawRect(draw_rect2, DlPaint()); + auto display_list = builder.Build(); + + { + DisplayListBuilder unculled(frame_bounds); + display_list->Dispatch(ToReceiver(unculled), frame_bounds); + auto unculled_dl = unculled.Build(); + + EXPECT_TRUE(DisplayListsEQ_Verbose(display_list, unculled_dl)); + } + + { + DisplayListBuilder culled(frame_bounds); + display_list->Dispatch(ToReceiver(culled), cull_rect); + auto culled_dl = culled.Build(); + + EXPECT_TRUE(DisplayListsNE_Verbose(display_list, culled_dl)); + + DisplayListBuilder expected(frame_bounds); + expected.Save(); + { + expected.Translate(0.1f, 0.1f); + expected.ClipRect(frame_clip); + expected.DrawRect(draw_rect1, DlPaint()); + } + expected.Restore(); + expected.DrawRect(draw_rect2, DlPaint()); + auto expected_dl = expected.Build(); + + EXPECT_TRUE(DisplayListsEQ_Verbose(culled_dl, expected_dl)); + } +} + +TEST_F(DisplayListTest, RecordManyLargeDisplayListOperations) { + DisplayListBuilder builder; + + // 2050 points is sizeof(DlPoint) * 2050 = 16400 bytes, this is more + // than the page size of 16384 bytes. + std::vector points(2050); + builder.DrawPoints(DlPointMode::kPoints, points.size(), points.data(), + DlPaint{}); + builder.DrawPoints(DlPointMode::kPoints, points.size(), points.data(), + DlPaint{}); + builder.DrawPoints(DlPointMode::kPoints, points.size(), points.data(), + DlPaint{}); + builder.DrawPoints(DlPointMode::kPoints, points.size(), points.data(), + DlPaint{}); + builder.DrawPoints(DlPointMode::kPoints, points.size(), points.data(), + DlPaint{}); + builder.DrawPoints(DlPointMode::kPoints, points.size(), points.data(), + DlPaint{}); + + EXPECT_TRUE(!!builder.Build()); +} + +TEST_F(DisplayListTest, RecordSingleLargeDisplayListOperation) { + DisplayListBuilder builder; + + std::vector points(40000); + builder.DrawPoints(DlPointMode::kPoints, points.size(), points.data(), + DlPaint{}); + + EXPECT_TRUE(!!builder.Build()); +} + +TEST_F(DisplayListTest, DisplayListDetectsRuntimeEffect) { + auto color_source = DlColorSource::MakeRuntimeEffect( + kTestRuntimeEffect1, {}, std::make_shared>()); + auto image_filter = DlImageFilter::MakeRuntimeEffect( + kTestRuntimeEffect1, {}, std::make_shared>()); + + { + // Default - no runtime effects, supports group opacity + DisplayListBuilder builder; + DlPaint paint; + + builder.DrawRect(DlRect::MakeLTRB(0, 0, 50, 50), paint); + EXPECT_TRUE(builder.Build()->can_apply_group_opacity()); + } + + { + // Draw with RTE color source does not support group opacity + DisplayListBuilder builder; + DlPaint paint; + + paint.setColorSource(color_source); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 50, 50), paint); + + EXPECT_FALSE(builder.Build()->can_apply_group_opacity()); + } + + { + // Draw with RTE image filter does not support group opacity + DisplayListBuilder builder; + DlPaint paint; + + paint.setImageFilter(image_filter); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 50, 50), paint); + + EXPECT_FALSE(builder.Build()->can_apply_group_opacity()); + } + + { + // Draw with RTE color source inside SaveLayer does not support group + // opacity on the SaveLayer, but does support it on the DisplayList + DisplayListBuilder builder; + DlPaint paint; + + builder.SaveLayer(std::nullopt, nullptr); + paint.setColorSource(color_source); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 50, 50), paint); + builder.Restore(); + + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); + + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation([](const SaveLayerOptions& options) { + return !options.can_distribute_opacity(); + }); + display_list->Dispatch(expector); + } + + { + // Draw with RTE image filter inside SaveLayer does not support group + // opacity on the SaveLayer, but does support it on the DisplayList + DisplayListBuilder builder; + DlPaint paint; + + builder.SaveLayer(std::nullopt, nullptr); + paint.setImageFilter(image_filter); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 50, 50), paint); + builder.Restore(); + + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); + + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation([](const SaveLayerOptions& options) { + return !options.can_distribute_opacity(); + }); + display_list->Dispatch(expector); + } + + { + // Draw with RTE color source inside nested saveLayers does not support + // group opacity on the inner SaveLayer, but does support it on the + // outer SaveLayer and the DisplayList + DisplayListBuilder builder; + DlPaint paint; + + builder.SaveLayer(std::nullopt, nullptr); + + builder.SaveLayer(std::nullopt, nullptr); + paint.setColorSource(color_source); + builder.DrawRect(DlRect::MakeLTRB(0, 0, 50, 50), paint); + paint.setColorSource(nullptr); + builder.Restore(); + + builder.SaveLayer(std::nullopt, nullptr); + paint.setImageFilter(image_filter); + // Make sure these DrawRects are non-overlapping otherwise the outer + // SaveLayer and DisplayList will be incompatible due to overlaps + builder.DrawRect(DlRect::MakeLTRB(60, 60, 100, 100), paint); + paint.setImageFilter(nullptr); + builder.Restore(); + + builder.Restore(); + auto display_list = builder.Build(); + EXPECT_TRUE(display_list->can_apply_group_opacity()); + + SAVE_LAYER_EXPECTOR(expector); + expector.addExpectation([](const SaveLayerOptions& options) { + // outer SaveLayer supports group opacity + return options.can_distribute_opacity(); + }); + expector.addExpectation([](const SaveLayerOptions& options) { + // first inner SaveLayer does not support group opacity + return !options.can_distribute_opacity(); + }); + expector.addExpectation([](const SaveLayerOptions& options) { + // second inner SaveLayer does not support group opacity + return !options.can_distribute_opacity(); + }); + display_list->Dispatch(expector); + } +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_attributes.h b/flutter/engine/src/flutter/display_list/dl_attributes.h new file mode 100644 index 0000000000000000000000000000000000000000..294d8573bdfd340fb0c7bdd66e2284302b8b1286 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_attributes.h @@ -0,0 +1,111 @@ +// 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_ATTRIBUTES_H_ +#define FLUTTER_DISPLAY_LIST_DL_ATTRIBUTES_H_ + +#include + +namespace flutter { + +// =========================================================================== + +// The base class for a family of DisplayList attribute classes. +// +// This class is designed to support the following properties for any +// attribute to facilitate the storage of the attribute in a DisplayList +// and for use in code that inspects or creates DisplayList objects: +// +// - Typed: +// Even though most references and pointers are passed around as the +// attribute's base class, a Type property can be queried using the |type| +// method to determine which type of the attribute is being used. For +// example, the Blend type of ColorFilter will return DlColorFilter::kBlend +// from its type method. +// +// - Inspectable: +// Any parameters required to full specify the action of the attribute are +// provided on the type-specific classes. +// +// - Safely Downcast: +// For the subclasses that have specific data to query, methods are +// provided to safely downcast the reference for inspection. The down +// casting method will either return a pointer to the instance with +// its type-specific class type, or nullptr if it is executed on the +// wrong type of instance. +// (eg. DlColorFilter::asBlend() or DlMaskFilter::asBlur()) +// +// - Immutable: +// Neither the base class or any of the subclasses specify any mutation +// methods. Instances are often passed around as const as a reminder, +// but the classes have no mutation methods anyway. +// +// - Flat and Embeddable: +// Bulk freed + bulk compared + zero memory fragmentation. +// +// All of these classes are designed to be stored in the DisplayList +// buffer allocated in-line with the rest of the data to avoid dangling +// pointers that require explicit freeing when the DisplayList goes +// away, or that fragment the memory needed to read the operations in +// the DisplayList. Furthermore, the data in the classes can be bulk +// compared using a |memcmp| when performing a |DisplayList::Equals|. +// +// - Passed by Pointer: +// The data shared via the |DlOpReceiver::set| calls are stored +// in the buffer itself and so their lifetime is controlled by the +// DisplayList. That memory cannot be shared as by a |shared_ptr| +// because the memory may be freed outside the control of the shared +// pointer. Creating a shared version of the object would require a +// new instantiation which we'd like to avoid on every dispatch call, +// so a raw (const) pointer is shared in those dispatch calls instead, +// with all of the responsibilities of non-ownership in the called method. +// +// But, for methods that need to keep a copy of the data... +// +// - Shared_Ptr-able: +// The classes support a method to return a |std::shared_ptr| version of +// themselves, safely instantiating a new copy of the object into a +// shared_ptr using |std::make_shared|. For those receiver objects +// that may want to hold on to the contents of the object (typically +// in a |current_attribute_| field), they can obtain a shared_ptr +// copy safely and easily using the |shared| method. + +// =========================================================================== + +// |D| is the base type for the attribute +// (i.e. DlColorFilter, etc.) +// |T| is the enum that describes the specific subclasses +// (i.e DlColorFilterType, etc.) +template +class DlAttribute { + public: + // Return the recognized specific type of the attribute. + virtual T type() const = 0; + + // Return the size of the instantiated data (typically used to allocate) + // storage in the DisplayList buffer. + virtual size_t size() const = 0; + + // Return a shared version of |this| attribute. The |shared_ptr| returned + // will reference a copy of this object so that the lifetime of the shared + // version is not tied to the storage of this particular instance. + virtual std::shared_ptr shared() const = 0; + + // Perform a content aware |==| comparison of the Attribute. + bool operator==(D const& other) const { + return type() == other.type() && equals_(other); + } + // Perform a content aware |!=| comparison of the Attribute. + bool operator!=(D const& other) const { return !(*this == other); } + + virtual ~DlAttribute() = default; + + protected: + // Virtual comparison method to support |==| and |!=|. + virtual bool equals_(D const& other) const = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_ATTRIBUTES_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_blend_mode.cc b/flutter/engine/src/flutter/display_list/dl_blend_mode.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b3bb91a0fe537361449646fb742ae53fef4755e --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_blend_mode.cc @@ -0,0 +1,7 @@ +// 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_blend_mode.h" + +namespace flutter {} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_blend_mode.h b/flutter/engine/src/flutter/display_list/dl_blend_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..009ef37b1c5a0f3dda8a2d3424361087dcc9b43a --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_blend_mode.h @@ -0,0 +1,16 @@ +// 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_BLEND_MODE_H_ +#define FLUTTER_DISPLAY_LIST_DL_BLEND_MODE_H_ + +#include "flutter/impeller/geometry/color.h" + +namespace flutter { + +using DlBlendMode = impeller::BlendMode; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_BLEND_MODE_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_builder.cc b/flutter/engine/src/flutter/display_list/dl_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..3fd408df414cb013f635934903e0d72487358571 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_builder.cc @@ -0,0 +1,2119 @@ +// 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_filters.h" +#include "flutter/display_list/effects/dl_color_source.h" +#include "flutter/display_list/effects/dl_image_filters.h" +#include "flutter/display_list/utils/dl_accumulation_rect.h" +#include "fml/logging.h" + +namespace flutter { + +// 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)...); +} + +template +void* DisplayListBuilder::Push(size_t pod, Args&&... args) { + // Plan out where and how large a space we need + size_t size = SkAlignPtr(sizeof(T) + pod); + size_t offset = storage_.size(); + + // Allocate the space + auto ptr = storage_.allocate(size); + FML_CHECK(ptr); + + // Initialize the space via the constructor + auto op = reinterpret_cast(ptr); + new (op) T{std::forward(args)...}; + FML_DCHECK(op->type == T::kType); + + // Adjust the counters and offsets (the memory is mostly initialized + // at this point except that the caller might do some pod-based copying + // past the end of the DlOp structure itself when we return) + offsets_.push_back(offset); + render_op_count_ += T::kRenderOpInc; + depth_ += T::kDepthInc * render_op_depth_cost_; + op_index_++; + + return op + 1; +} + +sk_sp DisplayListBuilder::Build() { + while (save_stack_.size() > 1) { + restore(); + } + + int count = render_op_count_; + size_t nested_bytes = nested_bytes_; + int nested_count = nested_op_count_; + uint32_t total_depth = depth_; + bool opacity_compatible = current_layer().is_group_opacity_compatible(); + bool is_safe = is_ui_thread_safe_; + bool affects_transparency = current_layer().affects_transparent_layer; + bool root_has_backdrop_filter = current_layer().contains_backdrop_filter; + bool root_is_unbounded = current_layer().is_unbounded; + DlBlendMode max_root_blend_mode = current_layer().max_blend_mode; + + sk_sp rtree; + DlRect bounds; + if (rtree_data_.has_value()) { + auto& rects = rtree_data_->rects; + auto& indices = rtree_data_->indices; + rtree = sk_make_sp(rects.data(), rects.size(), indices.data(), + [](int id) { return id >= 0; }); + // RTree bounds may be tighter due to applying filter bounds + // adjustments to each op as we restore layers rather than to + // the entire layer bounds. + bounds = rtree->bounds(); + rtree_data_.reset(); + } else { + bounds = current_layer().global_space_accumulator.GetBounds(); + } + + render_op_count_ = op_index_ = 0; + nested_bytes_ = nested_op_count_ = 0; + depth_ = 0; + is_ui_thread_safe_ = true; + current_opacity_compatibility_ = true; + render_op_depth_cost_ = 1u; + current_ = DlPaint(); + + save_stack_.pop_back(); + Init(rtree != nullptr); + + storage_.trim(); + DisplayListStorage storage; + std::vector offsets; + std::swap(offsets, offsets_); + std::swap(storage, storage_); + + return sk_sp(new DisplayList( + std::move(storage), std::move(offsets), count, nested_bytes, nested_count, + total_depth, bounds, opacity_compatible, is_safe, affects_transparency, + max_root_blend_mode, root_has_backdrop_filter, root_is_unbounded, + std::move(rtree))); +} + +static constexpr DlRect kEmpty = DlRect(); + +static const DlRect& ProtectEmpty(const DlRect& rect) { + // isEmpty protects us against NaN while we normalize any empty cull rects + return rect.IsEmpty() ? kEmpty : rect; +} + +DisplayListBuilder::DisplayListBuilder(const DlRect& cull_rect, + bool prepare_rtree) + : original_cull_rect_(ProtectEmpty(cull_rect)) { + Init(prepare_rtree); +} + +void DisplayListBuilder::Init(bool prepare_rtree) { + FML_DCHECK(save_stack_.empty()); + FML_DCHECK(!rtree_data_.has_value()); + + save_stack_.emplace_back(original_cull_rect_); + current_info().is_nop = original_cull_rect_.IsEmpty(); + if (prepare_rtree) { + rtree_data_.emplace(); + } +} + +DisplayListBuilder::~DisplayListBuilder() { + DisplayList::DisposeOps(storage_, offsets_); +} + +DlISize DisplayListBuilder::GetBaseLayerDimensions() const { + return DlIRect::RoundOut(original_cull_rect_).GetSize(); +} + +SkImageInfo DisplayListBuilder::GetImageInfo() const { + DlISize size = GetBaseLayerDimensions(); + return SkImageInfo::MakeUnknown(size.width, size.height); +} + +void DisplayListBuilder::onSetAntiAlias(bool aa) { + current_.setAntiAlias(aa); + Push(0, aa); +} +void DisplayListBuilder::onSetInvertColors(bool invert) { + current_.setInvertColors(invert); + Push(0, invert); + UpdateCurrentOpacityCompatibility(); +} +void DisplayListBuilder::onSetStrokeCap(DlStrokeCap cap) { + current_.setStrokeCap(cap); + Push(0, cap); +} +void DisplayListBuilder::onSetStrokeJoin(DlStrokeJoin join) { + current_.setStrokeJoin(join); + Push(0, join); +} +void DisplayListBuilder::onSetDrawStyle(DlDrawStyle style) { + current_.setDrawStyle(style); + Push(0, style); +} +void DisplayListBuilder::onSetStrokeWidth(float width) { + current_.setStrokeWidth(width); + Push(0, width); +} +void DisplayListBuilder::onSetStrokeMiter(float limit) { + current_.setStrokeMiter(limit); + Push(0, limit); +} +void DisplayListBuilder::onSetColor(DlColor color) { + current_.setColor(color); + Push(0, color); +} +void DisplayListBuilder::onSetBlendMode(DlBlendMode mode) { + current_.setBlendMode(mode); + Push(0, mode); + UpdateCurrentOpacityCompatibility(); +} + +void DisplayListBuilder::onSetColorSource(const DlColorSource* source) { + if (source == nullptr) { + current_.setColorSource(nullptr); + Push(0); + } else { + current_.setColorSource(source->shared()); + is_ui_thread_safe_ = is_ui_thread_safe_ && source->isUIThreadSafe(); + switch (source->type()) { + case DlColorSourceType::kImage: { + const DlImageColorSource* image_source = source->asImage(); + FML_DCHECK(image_source); + Push(0, image_source); + break; + } + case DlColorSourceType::kLinearGradient: { + const DlLinearGradientColorSource* linear = source->asLinearGradient(); + FML_DCHECK(linear); + void* pod = Push(linear->size()); + new (pod) DlLinearGradientColorSource(linear); + break; + } + case DlColorSourceType::kRadialGradient: { + const DlRadialGradientColorSource* radial = source->asRadialGradient(); + FML_DCHECK(radial); + void* pod = Push(radial->size()); + new (pod) DlRadialGradientColorSource(radial); + break; + } + case DlColorSourceType::kConicalGradient: { + const DlConicalGradientColorSource* conical = + source->asConicalGradient(); + FML_DCHECK(conical); + void* pod = Push(conical->size()); + new (pod) DlConicalGradientColorSource(conical); + break; + } + case DlColorSourceType::kSweepGradient: { + const DlSweepGradientColorSource* sweep = source->asSweepGradient(); + FML_DCHECK(sweep); + void* pod = Push(sweep->size()); + new (pod) DlSweepGradientColorSource(sweep); + break; + } + case DlColorSourceType::kRuntimeEffect: { + const DlRuntimeEffectColorSource* effect = source->asRuntimeEffect(); + FML_DCHECK(effect); + Push(0, effect); + break; + } + } + } + UpdateCurrentOpacityCompatibility(); +} +void DisplayListBuilder::onSetImageFilter(const DlImageFilter* filter) { + if (filter == nullptr) { + current_.setImageFilter(nullptr); + Push(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()); + 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()); + 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()); + 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()); + new (pod) DlMatrixImageFilter(matrix_filter); + break; + } + case DlImageFilterType::kCompose: + case DlImageFilterType::kLocalMatrix: + case DlImageFilterType::kColorFilter: + case DlImageFilterType::kRuntimeEffect: { + Push(0, filter); + break; + } + } + } + UpdateCurrentOpacityCompatibility(); +} +void DisplayListBuilder::onSetColorFilter(const DlColorFilter* filter) { + if (filter == nullptr) { + current_.setColorFilter(nullptr); + Push(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()); + 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()); + new (pod) DlMatrixColorFilter(matrix_filter); + break; + } + case DlColorFilterType::kSrgbToLinearGamma: { + void* pod = Push(filter->size()); + new (pod) DlSrgbToLinearGammaColorFilter(); + break; + } + case DlColorFilterType::kLinearToSrgbGamma: { + void* pod = Push(filter->size()); + new (pod) DlLinearToSrgbGammaColorFilter(); + break; + } + } + } + UpdateCurrentOpacityCompatibility(); +} +void DisplayListBuilder::onSetMaskFilter(const DlMaskFilter* filter) { + if (filter == nullptr) { + current_.setMaskFilter(nullptr); + render_op_depth_cost_ = 1u; + Push(0); + } else { + current_.setMaskFilter(filter->shared()); + render_op_depth_cost_ = 2u; + switch (filter->type()) { + case DlMaskFilterType::kBlur: { + const DlBlurMaskFilter* blur_filter = filter->asBlur(); + FML_DCHECK(blur_filter); + void* pod = Push(blur_filter->size()); + 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_alpha_or_color()) { + setColor(paint.getColor()); + } + 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_mask_filter()) { + setMaskFilter(paint.getMaskFilter().get()); + } +} + +void DisplayListBuilder::checkForDeferredSave() { + if (current_info().has_deferred_save_op) { + size_t save_offset = storage_.size(); + Push(0); + current_info().save_offset = save_offset; + current_info().save_depth = depth_; + current_info().has_deferred_save_op = false; + } +} + +void DisplayListBuilder::Save() { + bool was_nop = current_info().is_nop; + save_stack_.emplace_back(¤t_info()); + current_info().is_nop = was_nop; + + FML_DCHECK(save_stack_.size() >= 2u); + FML_DCHECK(current_info().has_deferred_save_op); +} + +void DisplayListBuilder::saveLayer(const DlRect& bounds, + const SaveLayerOptions in_options, + const DlImageFilter* backdrop, + std::optional backdrop_id) { + SaveLayerOptions options = in_options.without_optimizations(); + DisplayListAttributeFlags flags = options.renders_with_attributes() + ? kSaveLayerWithPaintFlags + : kSaveLayerFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + // If we can't render, whether because we were already in a no-render + // state from the parent or because our own attributes make us a nop, + // we can just simplify this whole layer to a regular save that has + // nop state. We need to have a SaveInfo for the eventual restore(), + // but no rendering ops should be accepted between now and then so + // it doesn't need any of the data associated with a layer SaveInfo. + Save(); + current_info().is_nop = true; + return; + } + + if (backdrop != nullptr) { + current_layer().contains_backdrop_filter = true; + } + + // Snapshot these values before we do any work as we need the values + // from before the method was called, but some of the operations below + // might update them. + size_t save_offset = storage_.size(); + uint32_t save_depth = depth_; + + // A backdrop will affect up to the entire surface, bounded by the clip + bool will_be_unbounded = (backdrop != nullptr); + std::shared_ptr filter; + + if (options.renders_with_attributes()) { + if (!paint_nops_on_transparency()) { + // We will fill the clip of the outer layer when we restore. + will_be_unbounded = true; + } + filter = current_.getImageFilter(); + CheckLayerOpacityCompatibility(true); + UpdateLayerResult(result, true); + } else { + CheckLayerOpacityCompatibility(false); + UpdateLayerResult(result, false); + } + + // 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 (will_be_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); + } + + // Accumulate information for the SaveInfo we are about to push onto the + // stack. + { + size_t rtree_index = + rtree_data_.has_value() ? rtree_data_->rects.size() : 0u; + + save_stack_.emplace_back(¤t_info(), filter, rtree_index); + FML_DCHECK(current_info().is_save_layer); + FML_DCHECK(!current_info().is_nop); + FML_DCHECK(!current_info().has_deferred_save_op); + current_info().save_offset = save_offset; + current_info().save_depth = save_depth; + + // If we inherit some culling bounds and we have a filter then we need + // to adjust them so that we cull for the correct input space for the + // output of the filter. + if (filter) { + DlRect outer_cull_rect = + current_info().global_state.GetDeviceCullCoverage(); + DlMatrix matrix = current_info().global_state.matrix(); + + DlIRect output_bounds = DlIRect::RoundOut(outer_cull_rect); + DlIRect input_bounds; + if (filter->get_input_device_bounds(output_bounds, matrix, + input_bounds)) { + current_info().global_state.resetDeviceCullRect( + DlRect::Make(input_bounds)); + } else { + // Filter could not make any promises about the bounds it needs to + // fill the output space, so we use a maximal rect to accumulate + // the layer bounds. + current_info().global_state.resetDeviceCullRect(kMaxCullRect); + } + } + + // We always want to cull based on user provided bounds, though, as + // that is legacy behavior even if it doesn't always work precisely + // in a rotated or skewed coordinate system (but it will work + // conservatively). + if (in_options.bounds_from_caller()) { + current_info().global_state.clipRect(bounds, DlClipOp::kIntersect, false); + } + } + + // Accumulate options to store in the SaveLayer op record. + { + DlRect record_bounds; + if (in_options.bounds_from_caller()) { + options = options.with_bounds_from_caller(); + record_bounds = bounds; + } else { + FML_DCHECK(record_bounds.IsEmpty()); + } + + if (backdrop) { + Push(0, options, record_bounds, backdrop, + backdrop_id); + } else { + Push(0, options, record_bounds); + } + } + + 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_ || filter) { + UpdateLayerOpacityCompatibility(false); + } + } +} +void DisplayListBuilder::SaveLayer(const std::optional& bounds, + const DlPaint* paint, + const DlImageFilter* backdrop, + std::optional backdrop_id) { + SaveLayerOptions options; + DlRect temp_bounds; + if (bounds.has_value()) { + options = options.with_bounds_from_caller(); + temp_bounds = *bounds; + } else { + FML_DCHECK(temp_bounds.IsEmpty()); + } + if (paint != nullptr) { + options = options.with_renders_with_attributes(); + SetAttributesFromPaint(*paint, + DisplayListOpFlags::kSaveLayerWithPaintFlags); + } + saveLayer(temp_bounds, options, backdrop, backdrop_id); +} + +void DisplayListBuilder::Restore() { + if (save_stack_.size() <= 1) { + return; + } + + if (!current_info().has_deferred_save_op) { + SaveOpBase* op = reinterpret_cast(storage_.base() + + current_info().save_offset); + FML_CHECK(op->type == DisplayListOpType::kSave || + op->type == DisplayListOpType::kSaveLayer || + op->type == DisplayListOpType::kSaveLayerBackdrop); + + op->restore_index = op_index_; + op->total_content_depth = depth_ - current_info().save_depth; + + if (current_info().is_save_layer) { + RestoreLayer(); + } + + // Wait until all outgoing bounds information for the saveLayer is + // recorded before pushing the record to the buffer so that any rtree + // bounds will be attributed to the op_index of the restore op. + Push(0); + } else { + FML_DCHECK(!current_info().is_save_layer); + } + + save_stack_.pop_back(); +} + +void DisplayListBuilder::RestoreLayer() { + FML_DCHECK(save_stack_.size() > 1); + FML_DCHECK(current_info().is_save_layer); + FML_DCHECK(!current_info().has_deferred_save_op); + + // A saveLayer will usually do a final copy to the main buffer in + // addition to its content, but that is accounted for outside of + // the total content depth computed above in Restore. + depth_ += render_op_depth_cost_; + + DlRect content_bounds = current_layer().layer_local_accumulator.GetBounds(); + + SaveLayerOpBase* layer_op = reinterpret_cast( + storage_.base() + current_info().save_offset); + FML_CHECK(layer_op->type == DisplayListOpType::kSaveLayer || + layer_op->type == DisplayListOpType::kSaveLayerBackdrop); + + if (layer_op->options.bounds_from_caller()) { + DlRect user_bounds = layer_op->rect; + if (!content_bounds.IsEmpty() && !user_bounds.Contains(content_bounds)) { + layer_op->options = layer_op->options.with_content_is_clipped(); + content_bounds = content_bounds.IntersectionOrEmpty(user_bounds); + } + } + layer_op->rect = content_bounds; + layer_op->max_blend_mode = current_layer().max_blend_mode; + + if (current_layer().contains_backdrop_filter) { + layer_op->options = layer_op->options.with_contains_backdrop_filter(); + } + + if (current_layer().is_group_opacity_compatible()) { + layer_op->options = layer_op->options.with_can_distribute_opacity(); + } + + if (current_layer().is_unbounded) { + layer_op->options = layer_op->options.with_content_is_unbounded(); + } + + // Ensure that the bounds transferred in the following call will be + // attributed to the index of the restore op. + FML_DCHECK(layer_op->restore_index == op_index_); + TransferLayerBounds(content_bounds); +} + +// There are a few different conditions and corresponding operations to +// consider when transferring bounds from one layer to another. The current +// layer will have accumulated its bounds into 2 potential places: +// +// - Its own private layer local bounds, which were potentially clipped by +// the supplied bounds and passed here as the content_bounds. +// +// - Either the rtree rect list, or the global space accumulator, one or +// the other. +// +// If there is no filter then the private layer bounds are complete and +// they simply need to be passed along to the parent into its layer local +// accumulator. Also, if there was no filter then the existing bounds +// recorded in either the rtree rects or the layer's global space accumulator +// (shared with its parent) need no updating so no global space transfer +// has to occur. +// +// If there is a filter then the global content bounds will need to be +// adjusted in one of two ways (rtree vs non-rtree): +// +// - If we are accumulating rtree rects then each of the rects accumulated +// during this current layer will need to be updated by the filter in the +// global coordinate space in which they were accumulated. In this mode +// we should never have a global space accumulator on the layer. +// +// - Otherwise we were accumulating global bounds into our own private +// global space accumulator which need to be adjusted in the global space +// coordinate system by the filter. +// +// Finally, we will have to adjust the layer's content bounds by the filter +// and accumulate those into the parent layer's local bounds. +void DisplayListBuilder::TransferLayerBounds(const DlRect& content_bounds) { + auto& filter = current_layer().filter; + + if (!filter) { + // We either accumulate global bounds into the rtree_data if there + // is one, or into the global_space_accumulator, but not both. + FML_DCHECK(!rtree_data_.has_value() || + current_layer().global_space_accumulator.is_empty()); + + parent_info().AccumulateBoundsLocal(content_bounds); + parent_layer().global_space_accumulator.accumulate( + current_layer().global_space_accumulator); + return; + } + + bool parent_is_flooded = false; + DlRect bounds_for_parent = content_bounds; + + // First, let's adjust or transfer the global/rtree bounds by the filter. + + // Matrix and Clip for the filter adjustment are the global values from + // just before our saveLayer and should still be the current values + // present in the parent layer. + const DlRect clip = parent_info().global_state.GetDeviceCullCoverage(); + const DlMatrix matrix = parent_info().global_state.matrix(); + + if (rtree_data_.has_value()) { + // Neither current or parent layer should have any global bounds in + // their accumulator + FML_DCHECK(current_layer().global_space_accumulator.is_empty()); + FML_DCHECK(parent_layer().global_space_accumulator.is_empty()); + + // The rtree rects were accumulated without the bounds modification of + // the filter applied to the layer so they may fail to trigger on a + // culled dispatch if their filter "fringes" are in the dispatch scope + // but their base rendering bounds are not. (Also, they will not + // contribute fully when we compute the overall bounds of this DL.) + // + // To make sure they are rendered in the culled dispatch situation, we + // revisit all of the RTree rects accumulated during the current layer + // (indicated by rtree_rects_start_index) and expand them by the filter. + + if (AdjustRTreeRects(rtree_data_.value(), *filter, matrix, clip, + current_layer().rtree_rects_start_index)) { + parent_is_flooded = true; + } + } else { + DlRect global_bounds = current_layer().global_space_accumulator.GetBounds(); + if (!global_bounds.IsEmpty()) { + DlIRect global_ibounds = DlIRect::RoundOut(global_bounds); + if (!filter->map_device_bounds(global_ibounds, matrix, global_ibounds)) { + parent_is_flooded = true; + } else { + global_bounds = DlRect::Make(global_ibounds); + std::optional clipped_bounds = global_bounds.Intersection(clip); + if (clipped_bounds.has_value()) { + parent_layer().global_space_accumulator.accumulate( + clipped_bounds.value()); + } + } + } + } + + // Now we visit the layer bounds which are in the layer's local coordinate + // system must be accumulated into the parent layer's bounds while + // adjusting them by the layer's local coordinate system (handled by the + // Accumulate() methods). + + // A filter will happily adjust empty bounds to be non-empty, so we + // specifically avoid that case here. Also, if we are already planning + // to flood the parent due to any of the cases above, we don't need to + // run the filter on the content bounds only to discover the same + // condition. + if (!parent_is_flooded && !bounds_for_parent.IsEmpty()) { + DlRect mappable_bounds = bounds_for_parent; + if (filter->map_local_bounds(mappable_bounds, mappable_bounds)) { + bounds_for_parent = mappable_bounds; + } else { + parent_is_flooded = true; + } + } + + if (parent_is_flooded) { + // All of the above computations deferred the flooded parent status + // to here. We need to mark the parent as flooded in both its layer + // and global accumulators. Note that even though the rtree rects + // were expanded to the size of the clip above, this method will still + // add one more rect to the rtree with the op index of the restore + // command to prevent the saveLayer itself from being elided in the + // rare case that there are no rendering ops in it, or somehow none + // of them were chosen by the rtree search (unlikely). The saveLayer + // must be processed for the parent flood to happen. + AccumulateUnbounded(parent_info()); + } else { + parent_info().AccumulateBoundsLocal(bounds_for_parent); + } +} + +bool DisplayListBuilder::AdjustRTreeRects(RTreeData& data, + const DlImageFilter& filter, + const DlMatrix& matrix, + const DlRect& clip, + size_t rect_start_index) { + auto& rects = data.rects; + auto& indices = data.indices; + FML_DCHECK(rects.size() == indices.size()); + int ret = false; + auto rect_keep = rect_start_index; + for (size_t i = rect_start_index; i < rects.size(); i++) { + DlRect bounds = rects[i]; + DlIRect ibounds = DlIRect::RoundOut(bounds); + if (filter.map_device_bounds(ibounds, matrix, ibounds)) { + bounds = DlRect::Make(ibounds); + } else { + bounds = clip; + ret = true; + } + auto clipped_bounds = bounds.Intersection(clip); + if (clipped_bounds.has_value()) { + indices[rect_keep] = indices[i]; + rects[rect_keep] = clipped_bounds.value(); + rect_keep++; + } + } + indices.resize(rect_keep); + rects.resize(rect_keep); + return ret; +} + +void DisplayListBuilder::RestoreToCount(int restore_count) { + FML_DCHECK(restore_count <= GetSaveCount()); + while (restore_count < GetSaveCount() && GetSaveCount() > 1) { + restore(); + } +} + +void DisplayListBuilder::Translate(DlScalar tx, DlScalar ty) { + if (std::isfinite(tx) && std::isfinite(ty) && (tx != 0.0 || ty != 0.0)) { + checkForDeferredSave(); + Push(0, tx, ty); + global_state().translate(tx, ty); + layer_local_state().translate(tx, ty); + } +} +void DisplayListBuilder::Scale(DlScalar sx, DlScalar sy) { + if (std::isfinite(sx) && std::isfinite(sy) && (sx != 1.0 || sy != 1.0)) { + checkForDeferredSave(); + Push(0, sx, sy); + global_state().scale(sx, sy); + layer_local_state().scale(sx, sy); + } +} +void DisplayListBuilder::Rotate(DlScalar degrees) { + if (SkScalarMod(degrees, 360.0) != 0.0) { + checkForDeferredSave(); + Push(0, degrees); + global_state().rotate(DlDegrees(degrees)); + layer_local_state().rotate(DlDegrees(degrees)); + } +} +void DisplayListBuilder::Skew(DlScalar sx, DlScalar sy) { + if (std::isfinite(sx) && std::isfinite(sy) && (sx != 0.0 || sy != 0.0)) { + checkForDeferredSave(); + Push(0, sx, sy); + global_state().skew(sx, sy); + layer_local_state().skew(sx, sy); + } +} + +// clang-format off + +// 2x3 2D affine subset of a 4x4 transform in row major order +void DisplayListBuilder::Transform2DAffine( + DlScalar mxx, DlScalar mxy, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myt) { + if (std::isfinite(mxx) && std::isfinite(myx) && + std::isfinite(mxy) && std::isfinite(myy) && + std::isfinite(mxt) && std::isfinite(myt)) { + if (mxx == 1 && mxy == 0 && + myx == 0 && myy == 1) { + Translate(mxt, myt); + } else { + checkForDeferredSave(); + Push(0, + mxx, mxy, mxt, + myx, myy, myt); + global_state().transform2DAffine(mxx, mxy, mxt, + myx, myy, myt); + layer_local_state().transform2DAffine(mxx, mxy, mxt, + myx, myy, myt); + } + } +} +// full 4x4 transform in row major order +void DisplayListBuilder::TransformFullPerspective( + DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, + DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, + DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar 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 (std::isfinite(mxx) && std::isfinite(mxy) && + std::isfinite(mxz) && std::isfinite(mxt) && + std::isfinite(myx) && std::isfinite(myy) && + std::isfinite(myz) && std::isfinite(myt) && + std::isfinite(mzx) && std::isfinite(mzy) && + std::isfinite(mzz) && std::isfinite(mzt) && + std::isfinite(mwx) && std::isfinite(mwy) && + std::isfinite(mwz) && std::isfinite(mwt)) { + checkForDeferredSave(); + Push(0, + mxx, mxy, mxz, mxt, + myx, myy, myz, myt, + mzx, mzy, mzz, mzt, + mwx, mwy, mwz, mwt); + global_state().transformFullPerspective(mxx, mxy, mxz, mxt, + myx, myy, myz, myt, + mzx, mzy, mzz, mzt, + mwx, mwy, mwz, mwt); + layer_local_state().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); + + // The matrices in layer_tracker_ and tracker_ are similar, but + // start at a different base transform. The tracker_ potentially + // has some number of transform operations on it that prefix the + // operations accumulated in layer_tracker_. So we can't set them both + // to identity in parallel as they would no longer maintain their + // relationship to each other. + // Instead we reinterpret this operation as transforming by the + // inverse of the current transform. Doing so to tracker_ sets it + // to identity so we can avoid the math there, but we must do the + // math the long way for layer_tracker_. This becomes: + // layer_tracker_.transform(tracker_.inverse()); + if (!layer_local_state().inverseTransform(global_state())) { + // If the inverse operation failed then that means that either + // the matrix above the current layer was singular, or the matrix + // became singular while we were accumulating the current layer. + // In either case, we should no longer be accumulating any + // contents so we set the layer tracking transform to a singular one. + layer_local_state().setTransform(DlMatrix::MakeScale({0.0f, 0.0f, 0.0f})); + } + + global_state().setIdentity(); +} +void DisplayListBuilder::Transform(const DlMatrix& matrix) { + TransformFullPerspective( + matrix.e[0][0], matrix.e[1][0], matrix.e[2][0], matrix.e[3][0], + matrix.e[0][1], matrix.e[1][1], matrix.e[2][1], matrix.e[3][1], + matrix.e[0][2], matrix.e[1][2], matrix.e[2][2], matrix.e[3][2], + matrix.e[0][3], matrix.e[1][3], matrix.e[2][3], matrix.e[3][3]); +} + +void DisplayListBuilder::ClipRect(const DlRect& rect, + DlClipOp clip_op, + bool is_aa) { + if (!rect.IsFinite()) { + return; + } + if (current_info().is_nop) { + return; + } + if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && + layer_local_state().rect_covers_cull(rect)) { + return; + } + global_state().clipRect(rect, clip_op, is_aa); + layer_local_state().clipRect(rect, clip_op, is_aa); + if (global_state().is_cull_rect_empty() || + layer_local_state().is_cull_rect_empty()) { + current_info().is_nop = true; + return; + } + current_info().has_valid_clip = true; + checkForDeferredSave(); + switch (clip_op) { + case DlClipOp::kIntersect: + Push(0, rect, is_aa); + break; + case DlClipOp::kDifference: + Push(0, rect, is_aa); + break; + } +} +void DisplayListBuilder::ClipOval(const DlRect& bounds, + DlClipOp clip_op, + bool is_aa) { + if (!bounds.IsFinite()) { + return; + } + if (current_info().is_nop) { + return; + } + if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && + layer_local_state().oval_covers_cull(bounds)) { + return; + } + global_state().clipOval(bounds, clip_op, is_aa); + layer_local_state().clipOval(bounds, clip_op, is_aa); + if (global_state().is_cull_rect_empty() || + layer_local_state().is_cull_rect_empty()) { + current_info().is_nop = true; + return; + } + current_info().has_valid_clip = true; + checkForDeferredSave(); + switch (clip_op) { + case DlClipOp::kIntersect: + Push(0, bounds, is_aa); + break; + case DlClipOp::kDifference: + Push(0, bounds, is_aa); + break; + } +} +void DisplayListBuilder::ClipRoundRect(const DlRoundRect& rrect, + DlClipOp clip_op, + bool is_aa) { + if (rrect.IsRect()) { + ClipRect(rrect.GetBounds(), clip_op, is_aa); + return; + } + if (rrect.IsOval()) { + ClipOval(rrect.GetBounds(), clip_op, is_aa); + return; + } + if (current_info().is_nop) { + return; + } + if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && + layer_local_state().rrect_covers_cull(rrect)) { + return; + } + global_state().clipRRect(rrect, clip_op, is_aa); + layer_local_state().clipRRect(rrect, clip_op, is_aa); + if (global_state().is_cull_rect_empty() || + layer_local_state().is_cull_rect_empty()) { + current_info().is_nop = true; + return; + } + current_info().has_valid_clip = true; + checkForDeferredSave(); + switch (clip_op) { + case DlClipOp::kIntersect: + Push(0, rrect, is_aa); + break; + case DlClipOp::kDifference: + Push(0, rrect, is_aa); + break; + } +} +void DisplayListBuilder::ClipRoundSuperellipse(const DlRoundSuperellipse& rse, + DlClipOp clip_op, + bool is_aa) { + if (rse.IsRect()) { + ClipRect(rse.GetBounds(), clip_op, is_aa); + return; + } + if (rse.IsOval()) { + ClipOval(rse.GetBounds(), clip_op, is_aa); + return; + } + if (current_info().is_nop) { + return; + } + if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && + layer_local_state().rsuperellipse_covers_cull(rse)) { + return; + } + global_state().clipRSuperellipse(rse, clip_op, is_aa); + layer_local_state().clipRSuperellipse(rse, clip_op, is_aa); + if (global_state().is_cull_rect_empty() || + layer_local_state().is_cull_rect_empty()) { + current_info().is_nop = true; + return; + } + current_info().has_valid_clip = true; + checkForDeferredSave(); + switch (clip_op) { + case DlClipOp::kIntersect: + Push(0, rse, is_aa); + break; + case DlClipOp::kDifference: + Push(0, rse, is_aa); + break; + } +} +void DisplayListBuilder::ClipPath(const DlPath& path, + DlClipOp clip_op, + bool is_aa) { + if (current_info().is_nop) { + return; + } + { + DlRect rect; + if (path.IsRect(&rect)) { + ClipRect(rect, clip_op, is_aa); + return; + } + if (path.IsOval(&rect)) { + ClipOval(rect, clip_op, is_aa); + return; + } + DlRoundRect rrect; + if (path.IsRoundRect(&rrect)) { + ClipRoundRect(rrect, clip_op, is_aa); + return; + } + } + global_state().clipPath(path, clip_op, is_aa); + layer_local_state().clipPath(path, clip_op, is_aa); + if (global_state().is_cull_rect_empty() || + layer_local_state().is_cull_rect_empty()) { + current_info().is_nop = true; + return; + } + current_info().has_valid_clip = true; + checkForDeferredSave(); + switch (clip_op) { + case DlClipOp::kIntersect: + Push(0, path, is_aa); + break; + case DlClipOp::kDifference: + Push(0, path, is_aa); + break; + } +} + +bool DisplayListBuilder::QuickReject(const DlRect& bounds) const { + return global_state().content_culled(bounds); +} + +void DisplayListBuilder::drawPaint() { + OpResult result = PaintResult(current_, kDrawPaintFlags); + if (result != OpResult::kNoEffect && AccumulateUnbounded()) { + Push(0); + 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, color, mode); + CheckLayerOpacityCompatibility(mode); + UpdateLayerResult(result, mode); + } +} +void DisplayListBuilder::drawLine(const DlPoint& p0, const DlPoint& p1) { + DlRect bounds = DlRect::MakeLTRB(p0.x, p0.y, p1.x, p1.y).GetPositive(); + DisplayListAttributeFlags flags = + bounds.IsEmpty() ? kDrawHVLineFlags : kDrawLineFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds, flags)) { + Push(0, p0, p1); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawLine(const DlPoint& p0, + const DlPoint& p1, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawLineFlags); + drawLine(p0, p1); +} +void DisplayListBuilder::drawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length) { + DlRect bounds = DlRect::MakeLTRB(p0.x, p0.y, p1.x, p1.y).GetPositive(); + DisplayListAttributeFlags flags = + bounds.IsEmpty() ? kDrawHVLineFlags : kDrawLineFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds, flags)) { + Push(0, p0, p1, on_length, off_length); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawLineFlags); + drawDashedLine(p0, p1, on_length, off_length); +} +void DisplayListBuilder::drawRect(const DlRect& rect) { + DisplayListAttributeFlags flags = kDrawRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(rect.GetPositive(), flags)) { + Push(0, rect); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawRect(const DlRect& rect, const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRectFlags); + drawRect(rect); +} +void DisplayListBuilder::drawOval(const DlRect& bounds) { + DisplayListAttributeFlags flags = kDrawOvalFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(bounds.GetPositive(), flags)) { + Push(0, bounds); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawOval(const DlRect& bounds, const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawOvalFlags); + drawOval(bounds); +} +void DisplayListBuilder::drawCircle(const DlPoint& center, DlScalar radius) { + DisplayListAttributeFlags flags = kDrawCircleFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect) { + DlRect bounds = DlRect::MakeLTRB(center.x - radius, center.y - radius, + center.x + radius, center.y + radius); + if (AccumulateOpBounds(bounds, flags)) { + Push(0, center, radius); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } + } +} +void DisplayListBuilder::DrawCircle(const DlPoint& center, + DlScalar radius, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawCircleFlags); + drawCircle(center, radius); +} +void DisplayListBuilder::drawRoundRect(const DlRoundRect& rrect) { + if (rrect.IsRect()) { + drawRect(rrect.GetBounds()); + } else if (rrect.IsOval()) { + drawOval(rrect.GetBounds()); + } else { + DisplayListAttributeFlags flags = kDrawRRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(rrect.GetBounds(), flags)) { + Push(0, rrect); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } + } +} +void DisplayListBuilder::DrawRoundRect(const DlRoundRect& rrect, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRRectFlags); + drawRoundRect(rrect); +} +void DisplayListBuilder::drawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner) { + DisplayListAttributeFlags flags = kDrawDRRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(outer.GetBounds(), flags)) { + Push(0, outer, inner); + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawDRRectFlags); + drawDiffRoundRect(outer, inner); +} +void DisplayListBuilder::drawRoundSuperellipse(const DlRoundSuperellipse& rse) { + if (rse.IsRect()) { + drawRect(rse.GetBounds()); + } else if (rse.IsOval()) { + drawOval(rse.GetBounds()); + } else { + DisplayListAttributeFlags flags = kDrawRSuperellipseFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(rse.GetBounds(), flags)) { + // DrawRoundSuperellipseOp only supports filling. Anything related to + // stroking must use path approximation. + if (current_.getDrawStyle() == DlDrawStyle::kFill) { + Push(0, rse); + } else { + DlPathBuilder builder; + builder.SetConvexity(impeller::Convexity::kConvex); + builder.SetBounds(rse.GetBounds()); + builder.AddRoundSuperellipse(DlRoundSuperellipse::MakeRectRadii( + rse.GetBounds(), rse.GetRadii())); + Push(0, DlPath(builder.TakePath())); + } + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); + } + } +} +void DisplayListBuilder::DrawRoundSuperellipse(const DlRoundSuperellipse& rse, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRSuperellipseFlags); + drawRoundSuperellipse(rse); +} +void DisplayListBuilder::drawPath(const DlPath& path) { + DisplayListAttributeFlags flags = kDrawPathFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect) { + bool is_visible = AccumulateOpBounds(path.GetBounds(), flags); + if (is_visible) { + Push(0, path); + CheckLayerOpacityHairlineCompatibility(); + UpdateLayerResult(result); + } + } +} +void DisplayListBuilder::DrawPath(const DlPath& path, const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawPathFlags); + drawPath(path); +} + +void DisplayListBuilder::drawArc(const DlRect& bounds, + DlScalar start, + DlScalar 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, bounds, start, sweep, useCenter); + if (useCenter) { + CheckLayerOpacityHairlineCompatibility(); + } else { + CheckLayerOpacityCompatibility(); + } + UpdateLayerResult(result); + } +} +void DisplayListBuilder::DrawArc(const DlRect& bounds, + DlScalar start, + DlScalar sweep, + bool useCenter, + const DlPaint& paint) { + SetAttributesFromPaint( + paint, useCenter ? kDrawArcWithCenterFlags : kDrawArcNoCenterFlags); + drawArc(bounds, start, sweep, useCenter); +} + +DisplayListAttributeFlags DisplayListBuilder::FlagsForPointMode( + DlPointMode mode) { + switch (mode) { + case DlPointMode::kPoints: + return kDrawPointsAsPointsFlags; + case DlPointMode::kLines: + return kDrawPointsAsLinesFlags; + case DlPointMode::kPolygon: + return kDrawPointsAsPolygonFlags; + } + FML_UNREACHABLE(); +} +void DisplayListBuilder::drawPoints(DlPointMode mode, + uint32_t count, + const DlPoint 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(DlPoint); + AccumulationRect accumulator; + for (size_t i = 0; i < count; i++) { + accumulator.accumulate(pts[i]); + } + if (!AccumulateOpBounds(accumulator.GetBounds(), flags)) { + return; + } + + void* data_ptr; + switch (mode) { + case DlPointMode::kPoints: + data_ptr = Push(bytes, count); + break; + case DlPointMode::kLines: + data_ptr = Push(bytes, count); + break; + case DlPointMode::kPolygon: + data_ptr = Push(bytes, 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 + current_layer().layer_local_accumulator.record_overlapping_bounds(); + // Even though we've eliminated the possibility of opacity peephole + // optimizations above, we still set the appropriate flags based on + // the rendering attributes in case we solve the overlapping points + // problem above. + CheckLayerOpacityCompatibility(); + UpdateLayerResult(result); +} +void DisplayListBuilder::DrawPoints(DlPointMode mode, + uint32_t count, + const DlPoint pts[], + const DlPaint& paint) { + SetAttributesFromPaint(paint, FlagsForPointMode(mode)); + drawPoints(mode, count, pts); +} +void DisplayListBuilder::drawVertices( + const std::shared_ptr& vertices, + DlBlendMode mode) { + DisplayListAttributeFlags flags = kDrawVerticesFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && + AccumulateOpBounds(vertices->GetBounds(), flags)) { + Push(0, 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. + UpdateLayerOpacityCompatibility(false); + UpdateLayerResult(result); + // Even though we already eliminated opacity peephole optimization + // due to the color issues identified above, drawVertices also fails + // based on the fact that the vertices are rendered independently + // so we cannot guarantee the non-overlapping condition. We record + // both conditions in case a solution is found to applying the + // colors above - both conditions must be analyzed sufficiently + // and implemented accordingly before drawVertices is compatible with + // opacity peephole optimizations. + current_layer().layer_local_accumulator.record_overlapping_bounds(); + } +} +void DisplayListBuilder::DrawVertices( + const std::shared_ptr& vertices, + DlBlendMode mode, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawVerticesFlags); + drawVertices(vertices, mode); +} + +void DisplayListBuilder::drawImage(const sk_sp image, + const DlPoint& point, + DlImageSampling sampling, + bool render_with_attributes) { + DisplayListAttributeFlags flags = render_with_attributes // + ? kDrawImageWithPaintFlags + : kDrawImageFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + DlRect bounds = DlRect::MakeXYWH(point.x, point.y, // + image->width(), image->height()); + if (AccumulateOpBounds(bounds, flags)) { + render_with_attributes + ? Push(0, image, point, sampling) + : Push(0, image, point, sampling); + CheckLayerOpacityCompatibility(render_with_attributes); + UpdateLayerResult(result, render_with_attributes); + is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); + } +} +void DisplayListBuilder::DrawImage(const sk_sp& image, + const DlPoint& 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 DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + DlSrcRectConstraint constraint) { + DisplayListAttributeFlags flags = render_with_attributes + ? kDrawImageRectWithPaintFlags + : kDrawImageRectFlags; + OpResult result = PaintResult(current_, flags); + if (result != OpResult::kNoEffect && AccumulateOpBounds(dst, flags)) { + Push(0, image, src, dst, sampling, render_with_attributes, + constraint); + CheckLayerOpacityCompatibility(render_with_attributes); + UpdateLayerResult(result, render_with_attributes); + is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); + } +} +void DisplayListBuilder::DrawImageRect(const sk_sp& image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + const DlPaint* paint, + DlSrcRectConstraint 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 DlIRect& center, + const DlRect& 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, image, center, dst, filter) + : Push(0, image, center, dst, filter); + CheckLayerOpacityCompatibility(render_with_attributes); + UpdateLayerResult(result, render_with_attributes); + is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); + } +} +void DisplayListBuilder::DrawImageNine(const sk_sp& image, + const DlIRect& center, + const DlRect& 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 DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* cull_rect, + bool render_with_attributes) { + DisplayListAttributeFlags flags = render_with_attributes // + ? kDrawAtlasWithPaintFlags + : kDrawAtlasFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + DlQuad quad; + AccumulationRect accumulator; + for (int i = 0; i < count; i++) { + const DlRect& src = tex[i]; + xform[i].GetQuad(src.GetWidth(), src.GetHeight(), quad); + for (int j = 0; j < 4; j++) { + accumulator.accumulate(quad[j]); + } + } + if (accumulator.is_empty() || + !AccumulateOpBounds(accumulator.GetBounds(), flags)) { + return; + } + + // Accumulating the bounds might not trip the overlap condition if the + // whole atlas operation is separated from other rendering calls, but + // since each atlas op is treated as an independent operation, we have + // to pass along our locally computed overlap condition for the individual + // atlas operations to the layer accumulator. + // Note that the above accumulation may falsely trigger the overlapping + // state as it is done quad corner by quad corner and an entire quad may + // be non-overlapping with the layer bounds, but as we add each point + // independently it might expand the bounds on one corner and then flag + // the condition when the next corner is added. + if (accumulator.overlap_detected()) { + current_layer().layer_local_accumulator.record_overlapping_bounds(); + } + + int bytes = count * (sizeof(DlRSTransform) + sizeof(DlRect)); + void* data_ptr; + if (colors != nullptr) { + bytes += count * sizeof(DlColor); + if (cull_rect != nullptr) { + data_ptr = + Push(bytes, atlas, count, mode, sampling, true, + *cull_rect, render_with_attributes); + } else { + data_ptr = Push(bytes, 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, atlas, count, mode, sampling, false, + *cull_rect, render_with_attributes); + } else { + data_ptr = Push(bytes, 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, render_with_attributes); + is_ui_thread_safe_ = is_ui_thread_safe_ && atlas->isUIThreadSafe(); +} +void DisplayListBuilder::DrawAtlas(const sk_sp& atlas, + const DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* 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, + DlScalar opacity) { + if (!std::isfinite(opacity) || opacity <= SK_ScalarNearlyZero || + display_list->op_count() == 0 || display_list->bounds().isEmpty() || + current_info().is_nop) { + return; + } + const DlRect bounds = display_list->GetBounds(); + bool accumulated; + sk_sp rtree; + if (display_list->root_is_unbounded()) { + accumulated = AccumulateUnbounded(); + } else if (!rtree_data_.has_value() || !(rtree = display_list->rtree())) { + accumulated = AccumulateOpBounds(bounds, kDrawDisplayListFlags); + } else { + std::list rects = + rtree->searchAndConsolidateRects(GetLocalClipCoverage(), false); + accumulated = false; + for (const DlRect& rect : rects) { + // TODO (https://github.com/flutter/flutter/issues/114919): Attributes + // are not necessarily `kDrawDisplayListFlags`. + if (AccumulateOpBounds(rect, kDrawDisplayListFlags)) { + accumulated = true; + } + } + } + if (!accumulated) { + return; + } + + DlPaint current_paint = current_; + Push(0, display_list, + opacity < SK_Scalar1 ? opacity : SK_Scalar1); + + // This depth increment accounts for every draw call in the child + // DisplayList and is in addition to the implicit depth increment + // that was performed when we pushed the DrawDisplayListOp. The + // eventual dispatcher can use or ignore the implicit depth increment + // as it sees fit depending on whether it needs to do rendering + // before or after the drawDisplayList op, but it must be accounted + // for if the depth value accounting is to remain consistent between + // the recording and dispatching process. + depth_ += display_list->total_depth(); + + 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, + display_list->max_root_blend_mode()); + if (display_list->root_has_backdrop_filter()) { + current_layer().contains_backdrop_filter = true; + } +} +void DisplayListBuilder::drawTextBlob(const sk_sp blob, + DlScalar x, + DlScalar y) { + DisplayListAttributeFlags flags = kDrawTextBlobFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + DlRect bounds = ToDlRect(blob->bounds().makeOffset(x, y)); + bool unclipped = AccumulateOpBounds(bounds, 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, 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, + DlScalar x, + DlScalar y, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawTextBlobFlags); + drawTextBlob(blob, x, y); +} + +void DisplayListBuilder::drawTextFrame( + const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y) { + DisplayListAttributeFlags flags = kDrawTextBlobFlags; + OpResult result = PaintResult(current_, flags); + if (result == OpResult::kNoEffect) { + return; + } + DlRect bounds = text_frame->GetBounds().Shift(x, y); + bool unclipped = AccumulateOpBounds(bounds, 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, text_frame, 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::DrawTextFrame( + const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y, + const DlPaint& paint) { + SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawTextBlobFlags); + drawTextFrame(text_frame, x, y); +} + +void DisplayListBuilder::DrawShadow(const DlPath& path, + const DlColor color, + const DlScalar elevation, + bool transparent_occluder, + DlScalar dpr) { + OpResult result = PaintResult(DlPaint(color)); + if (result != OpResult::kNoEffect) { + DlRect shadow_bounds = + DlCanvas::ComputeShadowBounds(path, elevation, dpr, GetMatrix()); + if (AccumulateOpBounds(shadow_bounds, kDrawShadowFlags)) { + transparent_occluder // + ? Push(0, path, color, elevation, + dpr) + : Push(0, path, color, elevation, dpr); + UpdateLayerOpacityCompatibility(false); + UpdateLayerResult(result, DlBlendMode::kSrcOver); + } + } +} + +bool DisplayListBuilder::AdjustBoundsForPaint(DlRect& 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.GeometryFlags(is_stroked); + + if (is_stroked) { + // Determine the max multiplier to the stroke width first. + DlScalar 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); + } + DlScalar min_stroke_width = 0.01; + pad *= std::max(current_.getStrokeWidth() * 0.5f, min_stroke_width); + bounds = bounds.Expand(pad, pad); + } + } + + if (flags.applies_mask_filter()) { + auto filter = current_.getMaskFilter(); + if (filter) { + switch (filter->type()) { + case DlMaskFilterType::kBlur: { + FML_DCHECK(filter->asBlur()); + DlScalar mask_sigma_pad = filter->asBlur()->sigma() * 3.0; + bounds = bounds.Expand(mask_sigma_pad, mask_sigma_pad); + } + } + } + } + + // Color filter does not modify bounds even if it affects transparent + // black because it is clipped by the "mask" of the primitive. That + // property only comes into play when it is applied to something like + // a layer. + + if (flags.applies_image_filter()) { + auto filter = current_.getImageFilterPtr(); + if (filter) { + DlRect dl_bounds; + if (!filter->map_local_bounds(bounds, dl_bounds)) { + return false; + } + bounds = dl_bounds; + } + } + + return true; +} + +bool DisplayListBuilder::AccumulateUnbounded(const SaveInfo& save) { + if (!save.has_valid_clip) { + save.layer_info->is_unbounded = true; + } + DlRect global_clip = save.global_state.GetDeviceCullCoverage(); + DlRect layer_clip = save.global_state.GetLocalCullCoverage(); + if (global_clip.IsEmpty() || !save.layer_state.mapAndClipRect(&layer_clip)) { + return false; + } + if (rtree_data_.has_value()) { + FML_DCHECK(save.layer_info->global_space_accumulator.is_empty()); + rtree_data_->rects.push_back(global_clip); + rtree_data_->indices.push_back(op_index_); + } else { + save.layer_info->global_space_accumulator.accumulate(global_clip); + } + save.layer_info->layer_local_accumulator.accumulate(layer_clip); + return true; +} + +bool DisplayListBuilder::AccumulateOpBounds(DlRect& bounds, + DisplayListAttributeFlags flags) { + if (AdjustBoundsForPaint(bounds, flags)) { + return AccumulateBounds(bounds); + } else { + return AccumulateUnbounded(); + } +} + +bool DisplayListBuilder::AccumulateBounds(const DlRect& bounds, + SaveInfo& layer, + int id) { + if (bounds.IsEmpty()) { + return false; + } + DlRect global_bounds; + DlRect layer_bounds; + if (!layer.global_state.mapAndClipRect(bounds, &global_bounds) || + !layer.layer_state.mapAndClipRect(bounds, &layer_bounds)) { + return false; + } + if (rtree_data_.has_value()) { + FML_DCHECK(layer.layer_info->global_space_accumulator.is_empty()); + if (id >= 0) { + rtree_data_->rects.push_back(global_bounds); + rtree_data_->indices.push_back(id); + } + } else { + layer.layer_info->global_space_accumulator.accumulate(global_bounds); + } + layer.layer_info->layer_local_accumulator.accumulate(layer_bounds); + return true; +} + +bool DisplayListBuilder::SaveInfo::AccumulateBoundsLocal(const DlRect& bounds) { + if (bounds.IsEmpty()) { + return false; + } + DlRect local_bounds; + if (!layer_state.mapAndClipRect(bounds, &local_bounds)) { + return false; + } + layer_info->layer_local_accumulator.accumulate(local_bounds); + return true; +} + +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) { + // Suspecting that we need to modulate the ColorSource color by the + // color property, see https://github.com/flutter/flutter/issues/159507 + 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_info().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/flutter/engine/src/flutter/display_list/dl_builder.h b/flutter/engine/src/flutter/display_list/dl_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..84c148a176dd71c51dbd24b9797700698de76786 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_builder.h @@ -0,0 +1,858 @@ +// 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_BUILDER_H_ +#define 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_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/geometry/dl_geometry_types.h" +#include "flutter/display_list/image/dl_image.h" +#include "flutter/display_list/utils/dl_accumulation_rect.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 DlRect kMaxCullRect = + DlRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F); + + explicit DisplayListBuilder(bool prepare_rtree) + : DisplayListBuilder(kMaxCullRect, prepare_rtree) {} + + explicit DisplayListBuilder(const DlRect& cull_rect = kMaxCullRect, + bool prepare_rtree = false); + + DisplayListBuilder(DlScalar width, DlScalar height) + : DisplayListBuilder(DlRect::MakeWH(width, height)) {} + + ~DisplayListBuilder(); + + // |DlCanvas| + DlISize GetBaseLayerDimensions() const override; + // |DlCanvas| + SkImageInfo GetImageInfo() const override; + + // |DlCanvas| + void Save() override; + + // |DlCanvas| + void SaveLayer(const std::optional& bounds, + const DlPaint* paint = nullptr, + const DlImageFilter* backdrop = nullptr, + std::optional backdrop_id = std::nullopt) override; + // |DlCanvas| + void Restore() override; + // |DlCanvas| + int GetSaveCount() const override { return save_stack_.size(); } + // |DlCanvas| + void RestoreToCount(int restore_count) override; + + // |DlCanvas| + void Translate(DlScalar tx, DlScalar ty) override; + // |DlCanvas| + void Scale(DlScalar sx, DlScalar sy) override; + // |DlCanvas| + void Rotate(DlScalar degrees) override; + // |DlCanvas| + void Skew(DlScalar sx, DlScalar sy) override; + + // clang-format off + // 2x3 2D affine subset of a 4x4 transform in row major order + // |DlCanvas| + void Transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myt) override; + // full 4x4 transform in row major order + // |DlCanvas| + void TransformFullPerspective( + DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, + DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, + DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) override; + // clang-format on + // |DlCanvas| + void TransformReset() override; + // |DlCanvas| + void Transform(const DlMatrix& matrix) override; + // |DlCanvas| + void SetTransform(const DlMatrix& matrix) override { + TransformReset(); + Transform(matrix); + } + + /// Returns the 4x4 full perspective transform representing all transform + /// operations executed so far in this DisplayList within the enclosing + /// save stack. + // |DlCanvas| + DlMatrix GetMatrix() const override { return global_state().matrix(); } + + // |DlCanvas| + void ClipRect(const DlRect& rect, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) override; + // |DlCanvas| + void ClipOval(const DlRect& bounds, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) override; + // |DlCanvas| + void ClipRoundRect(const DlRoundRect& rrect, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) override; + // |DlCanvas| + void ClipRoundSuperellipse(const DlRoundSuperellipse& rse, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) override; + // |DlCanvas| + void ClipPath(const DlPath& path, + DlClipOp clip_op = DlClipOp::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| + DlRect GetDestinationClipCoverage() const override { + return global_state().GetDeviceCullCoverage(); + } + /// 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| + DlRect GetLocalClipCoverage() const override { + return global_state().GetLocalCullCoverage(); + } + + /// 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 DlRect& bounds) const override; + + // |DlCanvas| + void DrawPaint(const DlPaint& paint) override; + // |DlCanvas| + void DrawColor(DlColor color, DlBlendMode mode) override; + // |DlCanvas| + void DrawLine(const DlPoint& p0, + const DlPoint& p1, + const DlPaint& paint) override; + // |DlCanvas| + void DrawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length, + const DlPaint& paint) override; + // |DlCanvas| + void DrawRect(const DlRect& rect, const DlPaint& paint) override; + // |DlCanvas| + void DrawOval(const DlRect& bounds, const DlPaint& paint) override; + // |DlCanvas| + void DrawCircle(const DlPoint& center, + DlScalar radius, + const DlPaint& paint) override; + // |DlCanvas| + void DrawRoundRect(const DlRoundRect& rrect, const DlPaint& paint) override; + // |DlCanvas| + void DrawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner, + const DlPaint& paint) override; + // |DlCanvas| + void DrawRoundSuperellipse(const DlRoundSuperellipse& rse, + const DlPaint& paint) override; + // |DlCanvas| + void DrawPath(const DlPath& path, const DlPaint& paint) override; + // |DlCanvas| + void DrawArc(const DlRect& bounds, + DlScalar start, + DlScalar sweep, + bool useCenter, + const DlPaint& paint) override; + // |DlCanvas| + void DrawPoints(DlPointMode mode, + uint32_t count, + const DlPoint pts[], + const DlPaint& paint) override; + // |DlCanvas| + void DrawVertices(const std::shared_ptr& vertices, + DlBlendMode mode, + const DlPaint& paint) override; + // |DlCanvas| + void DrawImage(const sk_sp& image, + const DlPoint& point, + DlImageSampling sampling, + const DlPaint* paint = nullptr) override; + // |DlCanvas| + void DrawImageRect( + const sk_sp& image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + const DlPaint* paint = nullptr, + DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) override; + // include overloads from the virtual base class + using DlCanvas::DrawImageRect; + + // |DlCanvas| + void DrawImageNine(const sk_sp& image, + const DlIRect& center, + const DlRect& dst, + DlFilterMode filter, + const DlPaint* paint = nullptr) override; + // |DlCanvas| + void DrawAtlas(const sk_sp& atlas, + const DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* cullRect, + const DlPaint* paint = nullptr) override; + // |DlCanvas| + void DrawDisplayList(const sk_sp display_list, + DlScalar opacity = SK_Scalar1) override; + // |DlCanvas| + void DrawTextBlob(const sk_sp& blob, + DlScalar x, + DlScalar y, + const DlPaint& paint) override; + + void drawTextFrame(const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y) override; + + void DrawTextFrame(const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y, + const DlPaint& paint) override; + + // |DlCanvas| + void DrawShadow(const DlPath& path, + const DlColor color, + const DlScalar elevation, + bool transparent_occluder, + DlScalar dpr) override; + + // |DlCanvas| + void Flush() override {} + + sk_sp Build(); + + private: + void Init(bool prepare_rtree); + + // 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); + friend int DisplayListBuilderTestingLastOpIndex(DisplayListBuilder& builder); + + void SetAttributesFromPaint(const DlPaint& paint, + const DisplayListAttributeFlags flags); + + // |DlOpReceiver| + void setAntiAlias(bool aa) override { + if (current_.isAntiAlias() != aa) { + onSetAntiAlias(aa); + } + } + // |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 setMaskFilter(const DlMaskFilter* filter) override { + if (NotEquals(current_.getMaskFilter(), filter)) { + onSetMaskFilter(filter); + } + } + + DlPaint CurrentAttributes() const { return current_; } + int LastOpIndex() const { return op_index_ - 1; } + + // |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(DlRect, bool)| method. + // |DlOpReceiver| + void saveLayer(const DlRect& bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop, + std::optional backdrop_id) override; + // |DlOpReceiver| + void restore() override { Restore(); } + + // |DlOpReceiver| + void translate(DlScalar tx, DlScalar ty) override { Translate(tx, ty); } + // |DlOpReceiver| + void scale(DlScalar sx, DlScalar sy) override { Scale(sx, sy); } + // |DlOpReceiver| + void rotate(DlScalar degrees) override { Rotate(degrees); } + // |DlOpReceiver| + void skew(DlScalar sx, DlScalar sy) override { Skew(sx, sy); } + + // clang-format off + // |DlOpReceiver| + void transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myt) override { + Transform2DAffine(mxx, mxy, mxt, myx, myy, myt); + } + // |DlOpReceiver| + void transformFullPerspective( + DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, + DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, + DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar 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 DlRect& rect, DlClipOp clip_op, bool is_aa) override { + ClipRect(rect, clip_op, is_aa); + } + // |DlOpReceiver| + void clipOval(const DlRect& bounds, DlClipOp clip_op, bool is_aa) override { + ClipOval(bounds, clip_op, is_aa); + } + // |DlOpReceiver| + void clipRoundRect(const DlRoundRect& rrect, + DlClipOp clip_op, + bool is_aa) override { + ClipRoundRect(rrect, clip_op, is_aa); + } + // |DlOpReceiver| + void clipRoundSuperellipse(const DlRoundSuperellipse& rse, + DlClipOp clip_op, + bool is_aa) override { + ClipRoundSuperellipse(rse, clip_op, is_aa); + } + // |DlOpReceiver| + void clipPath(const DlPath& path, DlClipOp 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 DlPoint& p0, const DlPoint& p1) override; + // |DlOpReceiver| + void drawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length) override; + // |DlOpReceiver| + void drawRect(const DlRect& rect) override; + // |DlOpReceiver| + void drawOval(const DlRect& bounds) override; + // |DlOpReceiver| + void drawCircle(const DlPoint& center, DlScalar radius) override; + // |DlOpReceiver| + void drawRoundRect(const DlRoundRect& rrect) override; + // |DlOpReceiver| + void drawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner) override; + // |DlOpReceiver| + void drawRoundSuperellipse(const DlRoundSuperellipse& rse) override; + // |DlOpReceiver| + void drawPath(const DlPath& path) override; + // |DlOpReceiver| + void drawArc(const DlRect& bounds, + DlScalar start, + DlScalar sweep, + bool useCenter) override; + // |DlOpReceiver| + void drawPoints(DlPointMode mode, uint32_t count, const DlPoint pts[]) override; + // |DlOpReceiver| + void drawVertices(const std::shared_ptr& vertices, + DlBlendMode mode) override; + + // |DlOpReceiver| + void drawImage(const sk_sp image, + const DlPoint& point, + DlImageSampling sampling, + bool render_with_attributes) override; + // |DlOpReceiver| + void drawImageRect( + const sk_sp image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) override; + // |DlOpReceiver| + void drawImageNine(const sk_sp image, + const DlIRect& center, + const DlRect& dst, + DlFilterMode filter, + bool render_with_attributes) override; + // |DlOpReceiver| + void drawAtlas(const sk_sp atlas, + const DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* cullRect, + bool render_with_attributes) override; + + // |DlOpReceiver| + void drawDisplayList(const sk_sp display_list, + DlScalar opacity) override { + DrawDisplayList(display_list, opacity); + } + // |DlOpReceiver| + void drawTextBlob(const sk_sp blob, + DlScalar x, + DlScalar y) override; + // |DlOpReceiver| + void drawShadow(const DlPath& path, + const DlColor color, + const DlScalar elevation, + bool transparent_occluder, + DlScalar dpr) override { + DrawShadow(path, color, elevation, transparent_occluder, dpr); + } + + void checkForDeferredSave(); + + DisplayListStorage storage_; + std::vector offsets_; + uint32_t render_op_count_ = 0u; + uint32_t depth_ = 0u; + // Most rendering ops will use 1 depth value, but some attributes may + // require an additional depth value (due to implicit saveLayers) + uint32_t render_op_depth_cost_ = 1u; + DlIndex op_index_ = 0; + + // bytes and ops from |drawPicture| and |drawDisplayList| + size_t nested_bytes_ = 0; + uint32_t nested_op_count_ = 0; + + bool is_ui_thread_safe_ = true; + + template + void* Push(size_t extra, Args&&... args); + + struct RTreeData { + std::vector rects; + std::vector indices; + }; + + struct LayerInfo { + LayerInfo(const std::shared_ptr& filter, + size_t rtree_rects_start_index) + : filter(filter), + rtree_rects_start_index(rtree_rects_start_index) {} + + // The filter that will be applied to the contents of the saveLayer + // when it is restored into the parent layer. + const std::shared_ptr filter; + + // The index of the rtree rects when the saveLayer was called, used + // only in the case that the saveLayer has a filter so that the + // accumulated rects can be updated in the corresponding restore call. + const size_t rtree_rects_start_index = 0; + + // The bounds accumulator for the entire DisplayList, relative to its root + // (not used when accumulating rects for an rtree, though) + AccumulationRect global_space_accumulator; + + // The bounds accumulator to set/verify the bounds of the most recently + // invoked saveLayer call, relative to the root of that saveLayer + AccumulationRect layer_local_accumulator; + + DlBlendMode max_blend_mode = DlBlendMode::kClear; + + bool opacity_incompatible_op_detected = false; + bool affects_transparent_layer = false; + bool contains_backdrop_filter = false; + bool is_unbounded = false; + + bool is_group_opacity_compatible() const { + return !opacity_incompatible_op_detected && + !layer_local_accumulator.overlap_detected(); + } + + void update_blend_mode(DlBlendMode mode) { + if (max_blend_mode < mode) { + max_blend_mode = mode; + } + } + }; + + // The SaveInfo class stores internal data common to both Save and + // SaveLayer calls + class SaveInfo { + public: + // For vector reallocation calls to copy vector data + SaveInfo(const SaveInfo& copy) = default; + SaveInfo(SaveInfo&& copy) = default; + + // For constructor (root layer) initialization + explicit SaveInfo(const DlRect& cull_rect) + : is_save_layer(true), + has_valid_clip(false), + global_state(cull_rect), + layer_state(cull_rect), + layer_info(new LayerInfo(nullptr, 0u)) {} + + // For regular save calls: + // Passing a pointer to the parent_info so as to distinguish this + // call from the copy constructors used during vector reallocations + explicit SaveInfo(const SaveInfo* parent_info) + : is_save_layer(false), + has_deferred_save_op(true), + has_valid_clip(parent_info->has_valid_clip), + global_state(parent_info->global_state), + layer_state(parent_info->layer_state), + layer_info(parent_info->layer_info) {} + + // For saveLayer calls: + explicit SaveInfo(const SaveInfo* parent_info, + const std::shared_ptr& filter, + int rtree_rect_index) + : is_save_layer(true), + has_valid_clip(false), + global_state(parent_info->global_state), + layer_state(kMaxCullRect), + layer_info(new LayerInfo(filter, rtree_rect_index)) {} + + const bool is_save_layer; + + bool has_deferred_save_op = false; + bool is_nop = false; + bool has_valid_clip; + + // The depth when the save call is recorded, used to compute the total + // depth of its content when the associated restore is called. + uint32_t save_depth = 0; + + // The offset into the buffer where the associated save op is recorded + // (which is not necessarily the same as when the Save() method is called + // due to deferred saves) + size_t save_offset = 0; + + // The transform and clip accumulated since the root of the DisplayList + DisplayListMatrixClipState global_state; + + // The transform and clip accumulated since the most recent saveLayer, + // used to compute and update its bounds when the restore is called. + DisplayListMatrixClipState layer_state; + + std::shared_ptr layer_info; + + // Records the given bounds after transforming by the global and + // layer matrices. + bool AccumulateBoundsLocal(const DlRect& bounds); + + // Simply transfers the local bounds to the parent + void TransferBoundsToParent(const SaveInfo& parent); + }; + + const DlRect original_cull_rect_; + std::vector save_stack_; + std::optional rtree_data_; + + DlPaint current_; + + // Returns a reference to the SaveInfo structure at the top of the current + // save_stack vector. Note that the clip and matrix state can be accessed + // more directly through global_state() and layer_state(). + SaveInfo& current_info() { return save_stack_.back(); } + const SaveInfo& current_info() const { return save_stack_.back(); } + + // Returns a reference to the SaveInfo structure just below the top + // of the current save_stack state. + SaveInfo& parent_info() { return *std::prev(save_stack_.end(), 2); } + const SaveInfo& parent_info() const { + return *std::prev(save_stack_.end(), 2); + } + + // Returns a reference to the LayerInfo structure at the top of the current + // save_stack vector. Note that the clip and matrix state can be accessed + // more directly through global_state() and layer_state(). + LayerInfo& current_layer() { return *save_stack_.back().layer_info; } + const LayerInfo& current_layer() const { + return *save_stack_.back().layer_info; + } + + // Returns a reference to the LayerInfo structure just below the top + // of the current save_stack state. + LayerInfo& parent_layer() { + return *std::prev(save_stack_.end(), 2)->layer_info; + } + const LayerInfo& parent_layer() const { + return *std::prev(save_stack_.end(), 2)->layer_info; + } + + // Returns a reference to the matrix and clip state for the entire + // DisplayList. The initial transform of this state is identity and + // the initial cull_rect is the root original_cull_rect supplied + // in the constructor. It is a summary of all transform and clip + // calls that have happened since the DisplayList was created + // (and have not yet been removed by a restore() call). + DisplayListMatrixClipState& global_state() { + return current_info().global_state; + } + const DisplayListMatrixClipState& global_state() const { + return current_info().global_state; + } + + // Returns a reference to the matrix and clip state relative to the + // current layer, whether that is defined by the most recent saveLayer + // call, or by the initial root state of the entire DisplayList for + // calls not surrounded by a saveLayer/restore pair. It is a summary + // of only those transform and clip calls that have happened since + // the creation of the DisplayList or since the most recent saveLayer + // (and have not yet been removed by a restore() call). + DisplayListMatrixClipState& layer_local_state() { + return current_info().layer_state; + } + const DisplayListMatrixClipState& layer_local_state() const { + return current_info().layer_state; + } + + void RestoreLayer(); + void TransferLayerBounds(const DlRect& content_bounds); + bool AdjustRTreeRects(RTreeData& data, + const DlImageFilter& filter, + const DlMatrix& matrix, + const DlRect& clip, + size_t rect_index); + + // 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() && // + !current_.usesRuntimeEffect() && // + 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().opacity_incompatible_op_detected = true; + } + } + + // 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 onSetInvertColors(bool invert); + void onSetStrokeCap(DlStrokeCap cap); + void onSetStrokeJoin(DlStrokeJoin join); + void onSetDrawStyle(DlDrawStyle style); + void onSetStrokeWidth(DlScalar width); + void onSetStrokeMiter(DlScalar 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 onSetMaskFilter(const DlMaskFilter* filter); + + static DisplayListAttributeFlags FlagsForPointMode(DlPointMode mode); + + enum class OpResult { + kNoEffect, + kPreservesTransparency, + kAffectsAll, + }; + + bool paint_nops_on_transparency(); + OpResult PaintResult(const DlPaint& paint, + DisplayListAttributeFlags flags = kDrawPaintFlags); + + void UpdateLayerResult(OpResult result, DlBlendMode mode) { + switch (result) { + case OpResult::kNoEffect: + case OpResult::kPreservesTransparency: + break; + case OpResult::kAffectsAll: + current_layer().affects_transparent_layer = true; + break; + } + current_layer().update_blend_mode(mode); + } + void UpdateLayerResult(OpResult result, bool uses_attributes = true) { + UpdateLayerResult(result, uses_attributes ? current_.getBlendMode() + : DlBlendMode::kSrcOver); + } + + // 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().withAlphaF(0.5f); + static_assert(!kAnyColor.isOpaque()); + static_assert(!kAnyColor.isTransparent()); + static DlColor GetEffectiveColor(const DlPaint& paint, + DisplayListAttributeFlags flags); + + // 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(DlRect& 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(const SaveInfo& save); + bool AccumulateUnbounded() { + return AccumulateUnbounded(current_info()); + } + + // Records the bounds for an op after modifying them according to the + // supplied attribute flags and transforming by the current matrix. + bool AccumulateOpBounds(const DlRect& bounds, + DisplayListAttributeFlags flags) { + DlRect 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(DlRect& bounds, DisplayListAttributeFlags flags); + + // Records the given bounds after transforming by the current matrix + // and clipping against the current clip. + bool AccumulateBounds(const DlRect& bounds, SaveInfo& layer, int id); + bool AccumulateBounds(const DlRect& bounds) { + return AccumulateBounds(bounds, current_info(), op_index_); + } +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_BUILDER_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_canvas.cc b/flutter/engine/src/flutter/display_list/dl_canvas.cc new file mode 100644 index 0000000000000000000000000000000000000000..ea51d67f25034784cd6ef4c6ac203a16a8a572c5 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_canvas.cc @@ -0,0 +1,24 @@ +// 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.h" + +#include "third_party/skia/include/core/SkPoint3.h" +#include "third_party/skia/include/utils/SkShadowUtils.h" + +namespace flutter { + +DlRect DlCanvas::ComputeShadowBounds(const DlPath& path, + float elevation, + DlScalar dpr, + const DlMatrix& ctm) { + SkRect shadow_bounds(path.GetSkBounds()); + SkShadowUtils::GetLocalBounds( + ToSkMatrix(ctm), path.GetSkPath(), SkPoint3::Make(0, 0, dpr * elevation), + SkPoint3::Make(0, -1, 1), kShadowLightRadius / kShadowLightHeight, + SkShadowFlags::kDirectionalLight_ShadowFlag, &shadow_bounds); + return ToDlRect(shadow_bounds); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_canvas.h b/flutter/engine/src/flutter/display_list/dl_canvas.h new file mode 100644 index 0000000000000000000000000000000000000000..881af6757ea7413a61ec0462bc175b9bf2f30301 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_canvas.h @@ -0,0 +1,248 @@ +// 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_H_ +#define FLUTTER_DISPLAY_LIST_DL_CANVAS_H_ + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_paint.h" +#include "flutter/display_list/dl_types.h" +#include "flutter/display_list/dl_vertices.h" +#include "flutter/display_list/geometry/dl_geometry_types.h" +#include "flutter/display_list/geometry/dl_path.h" +#include "flutter/display_list/image/dl_image.h" + +#include "third_party/skia/include/core/SkTextBlob.h" + +#include "impeller/typographer/text_frame.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Developer-facing API for rendering anything *within* the engine. +/// +/// |DlCanvas| should be used to render anything in the framework classes (i.e. +/// `lib/ui`), flow and flow layers, embedders, shell, and elsewhere. +/// +/// The only state carried by implementations of this interface are the clip +/// and transform which are saved and restored by the |save|, |saveLayer|, and +/// |restore| calls. +/// +/// @note The interface resembles closely the familiar |SkCanvas| interface +/// used throughout the engine. +class DlCanvas { + public: + virtual ~DlCanvas() = default; + + virtual DlISize GetBaseLayerDimensions() const = 0; + virtual SkImageInfo GetImageInfo() const = 0; + + virtual void Save() = 0; + virtual void SaveLayer(const std::optional& bounds, + const DlPaint* paint = nullptr, + const DlImageFilter* backdrop = nullptr, + std::optional backdrop_id = std::nullopt) = 0; + virtual void Restore() = 0; + virtual int GetSaveCount() const = 0; + virtual void RestoreToCount(int restore_count) = 0; + + virtual void Translate(DlScalar tx, DlScalar ty) = 0; + virtual void Scale(DlScalar sx, DlScalar sy) = 0; + virtual void Rotate(DlScalar degrees) = 0; + virtual void Skew(DlScalar sx, DlScalar sy) = 0; + + // clang-format off + + // 2x3 2D affine subset of a 4x4 transform in row major order + virtual void Transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myt) = 0; + // full 4x4 transform in row major order + virtual void TransformFullPerspective( + DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, + DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, + DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) = 0; + // clang-format on + virtual void TransformReset() = 0; + virtual void Transform(const DlMatrix& matrix) = 0; + virtual void SetTransform(const DlMatrix& matrix) = 0; + + virtual DlMatrix GetMatrix() const = 0; + + virtual void ClipRect(const DlRect& rect, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) = 0; + virtual void ClipOval(const DlRect& bounds, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) = 0; + virtual void ClipRoundRect(const DlRoundRect& rrect, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) = 0; + virtual void ClipRoundSuperellipse(const DlRoundSuperellipse& rse, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) = 0; + virtual void ClipPath(const DlPath& path, + DlClipOp clip_op = DlClipOp::kIntersect, + bool is_aa = false) = 0; + + /// Conservative estimate of the bounds of all outstanding clip operations + /// measured in the coordinate space within which this DisplayList will + /// be rendered. + virtual DlRect GetDestinationClipCoverage() const = 0; + /// Conservative estimate of the bounds of all outstanding clip operations + /// transformed into the local coordinate space in which currently + /// recorded rendering operations are interpreted. + virtual DlRect GetLocalClipCoverage() const = 0; + + /// 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. + virtual bool QuickReject(const DlRect& bounds) const = 0; + + virtual void DrawPaint(const DlPaint& paint) = 0; + virtual void DrawColor(DlColor color, + DlBlendMode mode = DlBlendMode::kSrcOver) = 0; + void Clear(DlColor color) { DrawColor(color, DlBlendMode::kSrc); } + virtual void DrawLine(const DlPoint& p0, + const DlPoint& p1, + const DlPaint& paint) = 0; + virtual void DrawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length, + const DlPaint& paint) = 0; + virtual void DrawRect(const DlRect& rect, const DlPaint& paint) = 0; + virtual void DrawOval(const DlRect& bounds, const DlPaint& paint) = 0; + virtual void DrawCircle(const DlPoint& center, + DlScalar radius, + const DlPaint& paint) = 0; + virtual void DrawRoundRect(const DlRoundRect& rrect, + const DlPaint& paint) = 0; + virtual void DrawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner, + const DlPaint& paint) = 0; + virtual void DrawRoundSuperellipse(const DlRoundSuperellipse& rse, + const DlPaint& paint) = 0; + virtual void DrawPath(const DlPath& path, const DlPaint& paint) = 0; + virtual void DrawArc(const DlRect& bounds, + DlScalar start, + DlScalar sweep, + bool useCenter, + const DlPaint& paint) = 0; + virtual void DrawPoints(DlPointMode mode, + uint32_t count, + const DlPoint pts[], + const DlPaint& paint) = 0; + virtual void DrawVertices(const std::shared_ptr& vertices, + DlBlendMode mode, + const DlPaint& paint) = 0; + virtual void DrawImage(const sk_sp& image, + const DlPoint& point, + DlImageSampling sampling, + const DlPaint* paint = nullptr) = 0; + virtual void DrawImageRect( + const sk_sp& image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + const DlPaint* paint = nullptr, + DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) = 0; + virtual void DrawImageRect( + const sk_sp& image, + const DlIRect& src, + const DlRect& dst, + DlImageSampling sampling, + const DlPaint* paint = nullptr, + DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) { + auto float_src = DlRect::MakeLTRB(src.GetLeft(), src.GetTop(), + src.GetRight(), src.GetBottom()); + DrawImageRect(image, float_src, dst, sampling, paint, constraint); + } + void DrawImageRect( + const sk_sp& image, + const DlRect& dst, + DlImageSampling sampling, + const DlPaint* paint = nullptr, + DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) { + DrawImageRect(image, image->GetBounds(), dst, sampling, paint, constraint); + } + virtual void DrawImageNine(const sk_sp& image, + const DlIRect& center, + const DlRect& dst, + DlFilterMode filter, + const DlPaint* paint = nullptr) = 0; + virtual void DrawAtlas(const sk_sp& atlas, + const DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* cullRect, + const DlPaint* paint = nullptr) = 0; + virtual void DrawDisplayList(const sk_sp display_list, + DlScalar opacity = SK_Scalar1) = 0; + + virtual void DrawTextFrame( + const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y, + const DlPaint& paint) = 0; + + virtual void DrawTextBlob(const sk_sp& blob, + DlScalar x, + DlScalar y, + const DlPaint& paint) = 0; + virtual void DrawShadow(const DlPath& path, + const DlColor color, + const DlScalar elevation, + bool transparent_occluder, + DlScalar dpr) = 0; + + virtual void Flush() = 0; + + static constexpr DlScalar kShadowLightHeight = 600; + static constexpr DlScalar kShadowLightRadius = 800; + + static DlRect ComputeShadowBounds(const DlPath& path, + float elevation, + DlScalar dpr, + const DlMatrix& ctm); +}; + +class DlAutoCanvasRestore { + public: + DlAutoCanvasRestore(DlCanvas* canvas, bool do_save) : canvas_(canvas) { + if (canvas) { + canvas_ = canvas; + restore_count_ = canvas->GetSaveCount(); + if (do_save) { + canvas_->Save(); + } + } else { + canvas_ = nullptr; + restore_count_ = 0; + } + } + + ~DlAutoCanvasRestore() { Restore(); } + + void Restore() { + if (canvas_) { + canvas_->RestoreToCount(restore_count_); + canvas_ = nullptr; + } + } + + private: + DlCanvas* canvas_; + int restore_count_; + + FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlAutoCanvasRestore); +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_CANVAS_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_color.cc b/flutter/engine/src/flutter/display_list/dl_color.cc new file mode 100644 index 0000000000000000000000000000000000000000..24a60f74dd252a2604df183a9836bf4f619626c1 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_color.cc @@ -0,0 +1,75 @@ +// 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_color.h" + +namespace flutter { + +namespace { +const std::array kP3ToSrgb = { + 1.306671048092539, -0.298061942172353, + 0.213228303487995, -0.213580156254466, // + -0.117390025596251, 1.127722006101976, + 0.109727644608938, -0.109450321455370, // + 0.214813187718391, 0.054268702864647, + 1.406898424029350, -0.364892765879631}; + +DlColor transform(const DlColor& color, + const std::array& matrix, + DlColorSpace color_space) { + return DlColor(color.getAlphaF(), + matrix[0] * color.getRedF() + // + matrix[1] * color.getGreenF() + // + matrix[2] * color.getBlueF() + // + matrix[3], // + matrix[4] * color.getRedF() + // + matrix[5] * color.getGreenF() + // + matrix[6] * color.getBlueF() + // + matrix[7], // + matrix[8] * color.getRedF() + // + matrix[9] * color.getGreenF() + // + matrix[10] * color.getBlueF() + // + matrix[11], // + color_space); +} +} // namespace + +DlColor DlColor::withColorSpace(DlColorSpace color_space) const { + switch (color_space_) { + case DlColorSpace::kSRGB: + switch (color_space) { + case DlColorSpace::kSRGB: + return *this; + case DlColorSpace::kExtendedSRGB: + return DlColor(alpha_, red_, green_, blue_, + DlColorSpace::kExtendedSRGB); + case DlColorSpace::kDisplayP3: + FML_CHECK(false) << "not implemented"; + return *this; + } + case DlColorSpace::kExtendedSRGB: + switch (color_space) { + case DlColorSpace::kSRGB: + FML_CHECK(false) << "not implemented"; + return *this; + case DlColorSpace::kExtendedSRGB: + return *this; + case DlColorSpace::kDisplayP3: + FML_CHECK(false) << "not implemented"; + return *this; + } + case DlColorSpace::kDisplayP3: + switch (color_space) { + case DlColorSpace::kSRGB: + FML_CHECK(false) << "not implemented"; + return *this; + case DlColorSpace::kExtendedSRGB: + return transform(*this, kP3ToSrgb, DlColorSpace::kExtendedSRGB); + case DlColorSpace::kDisplayP3: + return *this; + } + } +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_color.h b/flutter/engine/src/flutter/display_list/dl_color.h new file mode 100644 index 0000000000000000000000000000000000000000..51d32bce933173f4fd6102aedb584ff25cea5aa7 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_color.h @@ -0,0 +1,198 @@ +// 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_COLOR_H_ +#define FLUTTER_DISPLAY_LIST_DL_COLOR_H_ + +#include "flutter/display_list/geometry/dl_geometry_types.h" + +namespace flutter { + +// These should match the enumerations defined in //lib/ui/painting.dart. +enum class DlColorSpace { kSRGB = 0, kExtendedSRGB = 1, kDisplayP3 = 2 }; + +/// A representation of a color. +/// +/// The color belongs to a DlColorSpace. Using deprecated integer data accessors +/// on colors not in the kSRGB colorspace can lead to data loss. Using the +/// floating point accessors and constructors that were added for wide-gamut +/// support are preferred. +struct DlColor { + public: + constexpr DlColor() + : alpha_(1.f), + red_(0.f), + green_(0.f), + blue_(0.f), + color_space_(DlColorSpace::kSRGB) {} + constexpr explicit DlColor(uint32_t argb) + : alpha_(toF((argb >> 24) & 0xff)), + red_(toF((argb >> 16) & 0xff)), + green_(toF((argb >> 8) & 0xff)), + blue_(toF((argb >> 0) & 0xff)), + color_space_(DlColorSpace::kSRGB) {} + constexpr DlColor(DlScalar alpha, + DlScalar red, + DlScalar green, + DlScalar blue, + DlColorSpace colorspace) + : alpha_(alpha), + red_(red), + green_(green), + blue_(blue), + color_space_(colorspace) {} + + /// @brief Construct a 32 bit color from floating point R, G, B, and A color + /// channels. + static constexpr DlColor RGBA(DlScalar r, + DlScalar g, + DlScalar b, + DlScalar a) { + return ARGB(a, r, g, b); + } + + /// @brief Construct a 32 bit color from floating point A, R, G, and B color + /// channels. + static constexpr DlColor ARGB(DlScalar a, + DlScalar r, + DlScalar g, + DlScalar b) { + return DlColor(a, r, g, b, DlColorSpace::kSRGB); + } + + static constexpr uint8_t toAlpha(DlScalar opacity) { return toC(opacity); } + static constexpr DlScalar toOpacity(uint8_t alpha) { return toF(alpha); } + + // clang-format off + static constexpr DlColor kTransparent() {return DlColor(0x00000000);}; + static constexpr DlColor kBlack() {return DlColor(0xFF000000);}; + static constexpr DlColor kWhite() {return DlColor(0xFFFFFFFF);}; + static constexpr DlColor kRed() {return DlColor(0xFFFF0000);}; + static constexpr DlColor kGreen() {return DlColor(0xFF00FF00);}; + static constexpr DlColor kBlue() {return DlColor(0xFF0000FF);}; + static constexpr DlColor kCyan() {return DlColor(0xFF00FFFF);}; + static constexpr DlColor kMagenta() {return DlColor(0xFFFF00FF);}; + static constexpr DlColor kYellow() {return DlColor(0xFFFFFF00);}; + static constexpr DlColor kDarkGrey() {return DlColor(0xFF3F3F3F);}; + static constexpr DlColor kMidGrey() {return DlColor(0xFF808080);}; + static constexpr DlColor kLightGrey() {return DlColor(0xFFC0C0C0);}; + static constexpr DlColor kAliceBlue() {return DlColor(0xFFF0F8FF);}; + static constexpr DlColor kFuchsia() {return DlColor(0xFFFF00FF);}; + static constexpr DlColor kMaroon() {return DlColor(0xFF800000);}; + static constexpr DlColor kSkyBlue() {return DlColor(0xFF87CEEB);}; + static constexpr DlColor kCornflowerBlue() {return DlColor(0xFF6495ED);}; + static constexpr DlColor kCrimson() {return DlColor(0xFFFF5733);}; + static constexpr DlColor kAqua() {return DlColor(0xFF00FFFF);}; + static constexpr DlColor kOrange() {return DlColor(0xFFFFA500);}; + static constexpr DlColor kPurple() {return DlColor(0xFF800080);}; + static constexpr DlColor kLimeGreen() {return DlColor(0xFF32CD32);}; + static constexpr DlColor kGreenYellow() {return DlColor(0xFFADFF2F);}; + static constexpr DlColor kDarkMagenta() {return DlColor(0xFF8B008B);}; + static constexpr DlColor kOrangeRed() {return DlColor(0xFFFF4500);}; + static constexpr DlColor kDarkGreen() {return DlColor(0xFF006400);}; + static constexpr DlColor kChartreuse() {return DlColor(0xFF7FFF00);}; + // clang-format on + + constexpr bool isOpaque() const { return alpha_ >= 1.f; } + constexpr bool isTransparent() const { return alpha_ <= 0.f; } + + ///\deprecated Use floating point accessors to avoid data loss when using wide + /// gamut colors. + constexpr int getAlpha() const { return toC(alpha_); } + ///\deprecated Use floating point accessors to avoid data loss when using wide + /// gamut colors. + constexpr int getRed() const { return toC(red_); } + ///\deprecated Use floating point accessors to avoid data loss when using wide + /// gamut colors. + constexpr int getGreen() const { return toC(green_); } + ///\deprecated Use floating point accessors to avoid data loss when using wide + /// gamut colors. + constexpr int getBlue() const { return toC(blue_); } + + constexpr DlScalar getAlphaF() const { return alpha_; } + constexpr DlScalar getRedF() const { return red_; } + constexpr DlScalar getGreenF() const { return green_; } + constexpr DlScalar getBlueF() const { return blue_; } + + constexpr DlColorSpace getColorSpace() const { return color_space_; } + + constexpr DlColor withAlpha(uint8_t alpha) const { // + return DlColor((argb() & 0x00FFFFFF) | (alpha << 24)); + } + constexpr DlColor withRed(uint8_t red) const { // + return DlColor((argb() & 0xFF00FFFF) | (red << 16)); + } + constexpr DlColor withGreen(uint8_t green) const { // + return DlColor((argb() & 0xFFFF00FF) | (green << 8)); + } + constexpr DlColor withBlue(uint8_t blue) const { // + return DlColor((argb() & 0xFFFFFF00) | (blue << 0)); + } + constexpr DlColor withAlphaF(float alpha) const { // + return DlColor(alpha, red_, green_, blue_, color_space_); + } + constexpr DlColor withRedF(float red) const { // + return DlColor(alpha_, red, green_, blue_, color_space_); + } + constexpr DlColor withGreenF(float green) const { // + return DlColor(alpha_, red_, green, blue_, color_space_); + } + constexpr DlColor withBlueF(float blue) const { // + return DlColor(alpha_, red_, green_, blue, color_space_); + } + /// Performs a colorspace transformation. + /// + /// This isn't just a replacement of the color space field, the new color + /// components are calculated. + DlColor withColorSpace(DlColorSpace color_space) const; + + constexpr DlColor modulateOpacity(DlScalar opacity) const { + return opacity <= 0 ? withAlpha(0) + : opacity >= 1 ? *this + : withAlpha(round(getAlpha() * opacity)); + } + + ///\deprecated Use floating point accessors to avoid data loss when using wide + /// gamut colors. + constexpr uint32_t argb() const { + return toC(alpha_) << 24 | // + toC(red_) << 16 | // + toC(green_) << 8 | // + toC(blue_) << 0; + } + + /// Checks that no difference in color components exceeds the delta. + /// + /// This doesn't check against the actual distance between the colors in some + /// space. + bool isClose(DlColor const& other, DlScalar delta = 1.0f / 256.0f) { + return color_space_ == other.color_space_ && + std::abs(alpha_ - other.alpha_) < delta && + std::abs(red_ - other.red_) < delta && + std::abs(green_ - other.green_) < delta && + std::abs(blue_ - other.blue_) < delta; + } + bool operator==(DlColor const& other) const { + return alpha_ == other.alpha_ && red_ == other.red_ && + green_ == other.green_ && blue_ == other.blue_ && + color_space_ == other.color_space_; + } + bool operator!=(DlColor const& other) const { + return !this->operator==(other); + } + + private: + DlScalar alpha_; + DlScalar red_; + DlScalar green_; + DlScalar blue_; + DlColorSpace color_space_; + + static constexpr DlScalar toF(uint8_t comp) { return comp * (1.0f / 255); } + static constexpr uint8_t toC(DlScalar fComp) { return round(fComp * 255); } +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_COLOR_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_color_unittests.cc b/flutter/engine/src/flutter/display_list/dl_color_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e9cbda1f9d142db8c513f91e856f1b980a7aff2d --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_color_unittests.cc @@ -0,0 +1,301 @@ +// 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_color.h" +#include "flutter/testing/display_list_testing.h" +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +static void arraysEqual(const uint32_t* ints, + const DlColor* colors, + int count) { + for (int i = 0; i < count; i++) { + EXPECT_EQ(ints[i], colors[i].argb()) << " index:" << i; + } +} + +TEST(DisplayListColor, DefaultValue) { + DlColor color; + EXPECT_EQ(color.getAlphaF(), 1.f); + EXPECT_EQ(color.getRedF(), 0.f); + EXPECT_EQ(color.getGreenF(), 0.f); + EXPECT_EQ(color.getBlueF(), 0.f); + EXPECT_EQ(color.getColorSpace(), DlColorSpace::kSRGB); +} + +TEST(DisplayListColor, ArrayInterchangeableWithUint32) { + uint32_t ints[5] = { + 0xFF000000, // + 0xFFFF0000, // + 0xFF00FF00, // + 0xFF0000FF, // + 0xF1F2F3F4, + }; + DlColor colors[5] = { + DlColor::kBlack(), // + DlColor::kRed(), // + DlColor::kGreen(), // + DlColor::kBlue(), // + DlColor(0xF1F2F3F4), + }; + arraysEqual(ints, colors, 5); +} + +TEST(DisplayListColor, DlColorFloatConstructor) { + EXPECT_EQ(DlColor::ARGB(1.0f, 1.0f, 1.0f, 1.0f), DlColor(0xFFFFFFFF)); + EXPECT_EQ(DlColor::ARGB(0.0f, 0.0f, 0.0f, 0.0f), DlColor(0x00000000)); + EXPECT_TRUE( + DlColor::ARGB(0.5f, 0.5f, 0.5f, 0.5f).isClose(DlColor(0x80808080))); + EXPECT_TRUE( + DlColor::ARGB(1.0f, 0.0f, 0.5f, 1.0f).isClose(DlColor(0xFF0080FF))); + + EXPECT_EQ(DlColor::RGBA(1.0f, 1.0f, 1.0f, 1.0f), DlColor(0xFFFFFFFF)); + EXPECT_EQ(DlColor::RGBA(0.0f, 0.0f, 0.0f, 0.0f), DlColor(0x00000000)); + EXPECT_TRUE( + DlColor::RGBA(0.5f, 0.5f, 0.5f, 0.5f).isClose(DlColor(0x80808080))); + EXPECT_TRUE( + DlColor::RGBA(1.0f, 0.0f, 0.5f, 1.0f).isClose(DlColor(0xFFFF0080))); +} + +TEST(DisplayListColor, DlColorComponentGetters) { + { + DlColor test(0xFFFFFFFF); + + EXPECT_EQ(test.getAlpha(), 0xFF); + EXPECT_EQ(test.getRed(), 0xFF); + EXPECT_EQ(test.getGreen(), 0xFF); + EXPECT_EQ(test.getBlue(), 0xFF); + + EXPECT_EQ(test.getAlphaF(), 1.0f); + EXPECT_EQ(test.getRedF(), 1.0f); + EXPECT_EQ(test.getGreenF(), 1.0f); + EXPECT_EQ(test.getBlueF(), 1.0f); + } + + { + DlColor test = DlColor::ARGB(1.0f, 1.0f, 1.0f, 1.0f); + + EXPECT_EQ(test.getAlpha(), 0xFF); + EXPECT_EQ(test.getRed(), 0xFF); + EXPECT_EQ(test.getGreen(), 0xFF); + EXPECT_EQ(test.getBlue(), 0xFF); + + EXPECT_EQ(test.getAlphaF(), 1.0f); + EXPECT_EQ(test.getRedF(), 1.0f); + EXPECT_EQ(test.getGreenF(), 1.0f); + EXPECT_EQ(test.getBlueF(), 1.0f); + } + + { + DlColor test(0x00000000); + + EXPECT_EQ(test.getAlpha(), 0x00); + EXPECT_EQ(test.getRed(), 0x00); + EXPECT_EQ(test.getGreen(), 0x00); + EXPECT_EQ(test.getBlue(), 0x00); + + EXPECT_EQ(test.getAlphaF(), 0.0f); + EXPECT_EQ(test.getRedF(), 0.0f); + EXPECT_EQ(test.getGreenF(), 0.0f); + EXPECT_EQ(test.getBlueF(), 0.0f); + } + + { + DlColor test = DlColor::ARGB(0.0f, 0.0f, 0.0f, 0.0f); + + EXPECT_EQ(test.getAlpha(), 0x00); + EXPECT_EQ(test.getRed(), 0x00); + EXPECT_EQ(test.getGreen(), 0x00); + EXPECT_EQ(test.getBlue(), 0x00); + + EXPECT_EQ(test.getAlphaF(), 0.0f); + EXPECT_EQ(test.getRedF(), 0.0f); + EXPECT_EQ(test.getGreenF(), 0.0f); + EXPECT_EQ(test.getBlueF(), 0.0f); + } + + { + DlColor test(0x7F7F7F7F); + + EXPECT_EQ(test.getAlpha(), 0x7F); + EXPECT_EQ(test.getRed(), 0x7F); + EXPECT_EQ(test.getGreen(), 0x7F); + EXPECT_EQ(test.getBlue(), 0x7F); + + const DlScalar half = 127.0f * (1.0f / 255.0f); + + EXPECT_NEAR(test.getAlphaF(), half, 0.00001); + EXPECT_NEAR(test.getRedF(), half, 0.00001); + EXPECT_NEAR(test.getGreenF(), half, 0.00001); + EXPECT_NEAR(test.getBlueF(), half, 0.00001); + } + + { + DlColor test = DlColor::ARGB(0.5f, 0.5f, 0.5f, 0.5f); + + EXPECT_EQ(test.getAlpha(), 0x80); + EXPECT_EQ(test.getRed(), 0x80); + EXPECT_EQ(test.getGreen(), 0x80); + EXPECT_EQ(test.getBlue(), 0x80); + + EXPECT_EQ(test.getAlphaF(), 0.5); + EXPECT_EQ(test.getRedF(), 0.5); + EXPECT_EQ(test.getGreenF(), 0.5); + EXPECT_EQ(test.getBlueF(), 0.5); + } + + { + DlColor test(0x1F2F3F4F); + + EXPECT_EQ(test.getAlpha(), 0x1F); + EXPECT_EQ(test.getRed(), 0x2F); + EXPECT_EQ(test.getGreen(), 0x3F); + EXPECT_EQ(test.getBlue(), 0x4F); + + EXPECT_NEAR(test.getAlphaF(), 0x1f * (1.0f / 255.0f), 0.00001); + EXPECT_NEAR(test.getRedF(), 0x2f * (1.0f / 255.0f), 0.00001); + EXPECT_NEAR(test.getGreenF(), 0x3f * (1.0f / 255.0f), 0.00001); + EXPECT_NEAR(test.getBlueF(), 0x4f * (1.0f / 255.0f), 0.00001); + } + + { + DlColor test = DlColor::ARGB(0.1f, 0.2f, 0.3f, 0.4f); + + EXPECT_EQ(test.getAlpha(), round(0.1f * 255)); + EXPECT_EQ(test.getRed(), round(0.2f * 255)); + EXPECT_EQ(test.getGreen(), round(0.3f * 255)); + EXPECT_EQ(test.getBlue(), round(0.4f * 255)); + + EXPECT_EQ(test.getAlphaF(), 0.1f); + EXPECT_EQ(test.getRedF(), 0.2f); + EXPECT_EQ(test.getGreenF(), 0.3f); + EXPECT_EQ(test.getBlueF(), 0.4f); + } + + { + DlColor test = DlColor::RGBA(0.2f, 0.3f, 0.4f, 0.1f); + + EXPECT_EQ(test.getAlpha(), round(0.1f * 255)); + EXPECT_EQ(test.getRed(), round(0.2f * 255)); + EXPECT_EQ(test.getGreen(), round(0.3f * 255)); + EXPECT_EQ(test.getBlue(), round(0.4f * 255)); + + EXPECT_EQ(test.getAlphaF(), 0.1f); + EXPECT_EQ(test.getRedF(), 0.2f); + EXPECT_EQ(test.getGreenF(), 0.3f); + EXPECT_EQ(test.getBlueF(), 0.4f); + } +} + +TEST(DisplayListColor, DlColorOpaqueTransparent) { + auto test_argb = [](int a, int r, int g, int b) { + ASSERT_TRUE(a >= 0 && a <= 255); + ASSERT_TRUE(r >= 0 && r <= 255); + ASSERT_TRUE(g >= 0 && g <= 255); + ASSERT_TRUE(b >= 0 && b <= 255); + + int argb = ((a << 24) | (r << 16) | (g << 8) | b); + bool is_opaque = (a == 255); + bool is_transprent = (a == 0); + + EXPECT_EQ(DlColor(argb).isOpaque(), is_opaque); + EXPECT_EQ(DlColor(argb).isTransparent(), is_transprent); + + DlScalar aF = a * (1.0f / 255.0f); + DlScalar rF = r * (1.0f / 255.0f); + DlScalar gF = g * (1.0f / 255.0f); + DlScalar bF = b * (1.0f / 255.0f); + + EXPECT_EQ(DlColor::ARGB(aF, rF, gF, bF).isOpaque(), is_opaque); + EXPECT_EQ(DlColor::ARGB(aF, rF, gF, bF).isTransparent(), is_transprent); + + EXPECT_EQ(DlColor::RGBA(rF, gF, bF, aF).isOpaque(), is_opaque); + EXPECT_EQ(DlColor::RGBA(rF, gF, bF, aF).isTransparent(), is_transprent); + }; + + for (int r = 0; r <= 255; r += 15) { + for (int g = 0; g <= 255; g += 15) { + for (int b = 0; b <= 255; b += 15) { + test_argb(0, r, g, b); + for (int a = 15; a < 255; a += 15) { + test_argb(a, r, g, b); + } + test_argb(255, r, g, b); + } + } + } +} + +TEST(DisplayListColor, EqualityWithColorspace) { + EXPECT_TRUE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) == + DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB)); + EXPECT_FALSE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) == + DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB)); + EXPECT_FALSE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) != + DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB)); + EXPECT_TRUE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) != + DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB)); +} + +TEST(DisplayListColor, EqualityWithExtendedSRGB) { + EXPECT_TRUE(DlColor(1.0, 1.1, -0.2, 0.1, DlColorSpace::kExtendedSRGB) == + DlColor(1.0, 1.1, -0.2, 0.1, DlColorSpace::kExtendedSRGB)); + EXPECT_FALSE(DlColor(1.0, 1.1, -0.2, 0.1, DlColorSpace::kExtendedSRGB) == + DlColor(1.0, 1.0, 0.0, 0.0, DlColorSpace::kExtendedSRGB)); +} + +TEST(DisplayListColor, ColorSpaceSRGBtoSRGB) { + DlColor srgb(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB); + EXPECT_EQ(srgb, srgb.withColorSpace(DlColorSpace::kSRGB)); +} + +TEST(DisplayListColor, ColorSpaceSRGBtoExtendedSRGB) { + DlColor srgb(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB); + EXPECT_EQ(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB), + srgb.withColorSpace(DlColorSpace::kExtendedSRGB)); +} + +TEST(DisplayListColor, ColorSpaceExtendedSRGBtoExtendedSRGB) { + DlColor xsrgb(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB); + EXPECT_EQ(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB), + xsrgb.withColorSpace(DlColorSpace::kExtendedSRGB)); +} + +TEST(DisplayListColor, ColorSpaceP3ToP3) { + DlColor p3(0.9, 0.8, 0.7, 0.6, DlColorSpace::kDisplayP3); + EXPECT_EQ(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kDisplayP3), + p3.withColorSpace(DlColorSpace::kDisplayP3)); +} + +TEST(DisplayListColor, ColorSpaceP3ToExtendedSRGB) { + DlColor red(0.9, 1.0, 0.0, 0.0, DlColorSpace::kDisplayP3); + EXPECT_TRUE( + DlColor(0.9, 1.0931, -0.2268, -0.1501, DlColorSpace::kExtendedSRGB) + .isClose(red.withColorSpace(DlColorSpace::kExtendedSRGB))) + << red.withColorSpace(DlColorSpace::kExtendedSRGB); + + DlColor green(0.9, 0.0, 1.0, 0.0, DlColorSpace::kDisplayP3); + EXPECT_TRUE( + DlColor(0.9, -0.5116, 1.0183, -0.3106, DlColorSpace::kExtendedSRGB) + .isClose(green.withColorSpace(DlColorSpace::kExtendedSRGB))) + << green.withColorSpace(DlColorSpace::kExtendedSRGB); + + DlColor blue(0.9, 0.0, 0.0, 1.0, DlColorSpace::kDisplayP3); + EXPECT_TRUE(DlColor(0.9, -0.0004, 0.0003, 1.0420, DlColorSpace::kExtendedSRGB) + .isClose(blue.withColorSpace(DlColorSpace::kExtendedSRGB))) + << blue.withColorSpace(DlColorSpace::kExtendedSRGB); +} + +TEST(DisplayListColor, isClose) { + EXPECT_TRUE(DlColor(0xffaabbcc).isClose(DlColor(0xffaabbcc))); +} + +TEST(DisplayListColor, isNotClose) { + EXPECT_FALSE(DlColor(0xffaabbcc).isClose(DlColor(0xffaabbcd))); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_op_flags.cc b/flutter/engine/src/flutter/display_list/dl_op_flags.cc new file mode 100644 index 0000000000000000000000000000000000000000..6ce407db22b220eeef1d4435163c028c58e9eea2 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_op_flags.cc @@ -0,0 +1,11 @@ +// 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_flags.h" + +namespace flutter { + +// Just exists to ensure that the header can be cleanly imported. + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_op_flags.h b/flutter/engine/src/flutter/display_list/dl_op_flags.h new file mode 100644 index 0000000000000000000000000000000000000000..4cdf089af9486d86a4af8fe6e072668289bade09 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_op_flags.h @@ -0,0 +1,421 @@ +// 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_FLAGS_H_ +#define FLUTTER_DISPLAY_LIST_DL_OP_FLAGS_H_ + +#include "flutter/display_list/dl_paint.h" +#include "flutter/fml/logging.h" + +namespace flutter { + +/// The base class for the classes that maintain a list of +/// attributes that might be important for a number of operations +/// including which rendering attributes need to be set before +/// calling a rendering method (all |drawSomething| calls), +/// or for determining which exceptional conditions may need +/// to be accounted for in bounds calculations. +/// This class contains only protected definitions and helper methods +/// for the public classes |DisplayListAttributeFlags| and +/// |DisplayListSpecialGeometryFlags|. +class DisplayListFlags { + protected: + // A drawing operation that is not geometric in nature (but which + // may still apply a MaskFilter - see |kUsesMaskFilter| below). + static constexpr int kIsNonGeometric = 0; + + // A geometric operation that is defined as a fill operation + // regardless of what the current paint Style is set to. + // This flag will automatically assume |kUsesMaskFilter|. + static constexpr int kIsFilledGeometry = 1 << 0; + + // A geometric operation that is defined as a stroke operation + // regardless of what the current paint Style is set to. + // This flag will automatically assume |kUsesMaskFilter|. + static constexpr int kIsStrokedGeometry = 1 << 1; + + // A geometric operation that may be a stroke or fill operation + // depending on the current state of the paint Style attribute. + // This flag will automatically assume |kUsesMaskFilter|. + static constexpr int kIsDrawnGeometry = 1 << 2; + + static constexpr int kIsAnyGeometryMask = // + kIsFilledGeometry | // + kIsStrokedGeometry | // + kIsDrawnGeometry; + + // A primitive that floods the surface (or clip) with no + // natural bounds, such as |drawColor| or |drawPaint|. + static constexpr int kFloodsSurface = 1 << 3; + + static constexpr int kMayHaveCaps = 1 << 4; + static constexpr int kMayHaveJoins = 1 << 5; + static constexpr int kButtCapIsSquare = 1 << 6; + + // A geometric operation which has a path that might have + // end caps that are not rectilinear which means that square + // end caps might project further than half the stroke width + // from the geometry bounds. + // A rectilinear path such as |drawRect| will not have + // diagonal end caps. |drawLine| might have diagonal end + // caps depending on the angle of the line, and more likely + // |drawPath| will often have such end caps. + static constexpr int kMayHaveDiagonalCaps = 1 << 7; + + // A geometric operation which has joined vertices that are + // not guaranteed to be smooth (angles of incoming and outgoing) + // segments at some joins may not have the same angle) or + // rectilinear (squares have right angles at the corners, but + // those corners will never extend past the bounding box of + // the geometry pre-transform). + // |drawRect|, |drawOval| and |drawRRect| all have well + // behaved joins, but |drawPath| might have joins that cause + // mitered extensions outside the pre-transformed bounding box. + static constexpr int kMayHaveAcuteJoins = 1 << 8; + + static constexpr int kAnySpecialGeometryMask = // + kMayHaveCaps | kMayHaveJoins | kButtCapIsSquare | // + kMayHaveDiagonalCaps | kMayHaveAcuteJoins; + + // clang-format off + static constexpr int kUsesAntiAlias = 1 << 10; + static constexpr int kUsesAlpha = 1 << 11; + static constexpr int kUsesColor = 1 << 12; + static constexpr int kUsesBlend = 1 << 13; + static constexpr int kUsesShader = 1 << 14; + static constexpr int kUsesColorFilter = 1 << 15; + static constexpr int kUsesMaskFilter = 1 << 16; + static constexpr int kUsesImageFilter = 1 << 17; + + // Some ops have an optional paint argument. If the version + // stored in the DisplayList ignores the paint, but there + // is an option to render the same op with a paint then + // both of the following flags are set to indicate that + // a default paint object can be constructed when rendering + // the op to carry information imposed from outside the + // DisplayList (for example, the opacity override). + static constexpr int kIgnoresPaint = 1 << 30; + // clang-format on + + static constexpr int kAnyAttributeMask = // + kUsesAntiAlias | kUsesAlpha | kUsesColor | kUsesBlend | kUsesShader | + kUsesColorFilter | kUsesMaskFilter | kUsesImageFilter; +}; + +class DisplayListFlagsBase : protected DisplayListFlags { + protected: + explicit constexpr DisplayListFlagsBase(int flags) : flags_(flags) {} + + const int flags_; + + constexpr bool has_any(int qFlags) const { return (flags_ & qFlags) != 0; } + constexpr bool has_all(int qFlags) const { + return (flags_ & qFlags) == qFlags; + } + constexpr bool has_none(int qFlags) const { return (flags_ & qFlags) == 0; } +}; + +/// An attribute class for advertising specific properties of +/// a geometric attribute that can affect the computation of +/// the bounds of the primitive. +class DisplayListSpecialGeometryFlags : DisplayListFlagsBase { + public: + /// The geometry may have segments that end without closing the path. + constexpr bool may_have_end_caps() const { return has_any(kMayHaveCaps); } + + /// The geometry may have segments connect non-continuously. + constexpr bool may_have_joins() const { return has_any(kMayHaveJoins); } + + /// Mainly for drawPoints(PointMode) where Butt caps are rendered as squares. + constexpr bool butt_cap_becomes_square() const { + return has_any(kButtCapIsSquare); + } + + /// The geometry may have segments that end on a diagonal + /// such that their end caps extend further than the default + /// |strokeWidth * 0.5| margin around the geometry. + constexpr bool may_have_diagonal_caps() const { + return has_any(kMayHaveDiagonalCaps); + } + + /// The geometry may have segments that meet at vertices at + /// an acute angle such that the miter joins will extend + /// further than the default |strokeWidth * 0.5| margin around + /// the geometry. + constexpr bool may_have_acute_joins() const { + return has_any(kMayHaveAcuteJoins); + } + + private: + explicit constexpr DisplayListSpecialGeometryFlags(int flags) + : DisplayListFlagsBase(flags) { + FML_DCHECK((flags & kAnySpecialGeometryMask) == flags); + } + + const DisplayListSpecialGeometryFlags with(int extra) const { + return extra == 0 ? *this : DisplayListSpecialGeometryFlags(flags_ | extra); + } + + friend class DisplayListAttributeFlags; +}; + +class DisplayListAttributeFlags : DisplayListFlagsBase { + public: + const DisplayListSpecialGeometryFlags GeometryFlags(bool is_stroked) const { + return special_flags_; + } + + constexpr bool ignores_paint() const { return has_any(kIgnoresPaint); } + + constexpr bool applies_anti_alias() const { return has_any(kUsesAntiAlias); } + constexpr bool applies_color() const { return has_any(kUsesColor); } + constexpr bool applies_alpha() const { return has_any(kUsesAlpha); } + constexpr bool applies_alpha_or_color() const { + return has_any(kUsesAlpha | kUsesColor); + } + + /// The primitive dynamically determines whether it is a stroke or fill + /// operation (or both) based on the setting of the |Style| attribute. + constexpr bool applies_style() const { return has_any(kIsDrawnGeometry); } + /// The primitive can use any of the stroke attributes, such as + /// StrokeWidth, StrokeMiter, StrokeCap, or StrokeJoin. This + /// method will return if the primitive is defined as one that + /// strokes its geometry (such as |drawLine|) or if it is defined + /// as one that honors the Style attribute. If the Style attribute + /// is known then a more accurate answer can be returned from + /// the |is_stroked| method by supplying the actual setting of + /// the style. + // bool applies_stroke_attributes() const { return is_stroked(); } + + constexpr bool applies_shader() const { return has_any(kUsesShader); } + /// The primitive honors the current DlColorFilter, including + /// the related attribute InvertColors + constexpr bool applies_color_filter() const { + return has_any(kUsesColorFilter); + } + /// The primitive honors the DlBlendMode + constexpr bool applies_blend() const { return has_any(kUsesBlend); } + /// The primitive honors the DlMaskFilter whether set using the + /// filter object or using the convenience method |setMaskBlurFilter| + constexpr bool applies_mask_filter() const { + return has_any(kUsesMaskFilter); + } + constexpr bool applies_image_filter() const { + return has_any(kUsesImageFilter); + } + + constexpr bool is_geometric() const { return has_any(kIsAnyGeometryMask); } + constexpr bool always_stroked() const { return has_any(kIsStrokedGeometry); } + constexpr bool is_stroked(DlDrawStyle style = DlDrawStyle::kStroke) const { + return (has_any(kIsStrokedGeometry) || + (style != DlDrawStyle::kFill && has_any(kIsDrawnGeometry))); + } + + constexpr bool is_flood() const { return has_any(kFloodsSurface); } + + constexpr bool operator==(DisplayListAttributeFlags const& other) const { + return flags_ == other.flags_; + } + + private: + explicit constexpr DisplayListAttributeFlags(int flags) + : DisplayListFlagsBase(flags), + special_flags_(flags & kAnySpecialGeometryMask) { + FML_DCHECK((flags & kIsAnyGeometryMask) == kIsNonGeometric || + (flags & kIsAnyGeometryMask) == kIsFilledGeometry || + (flags & kIsAnyGeometryMask) == kIsStrokedGeometry || + (flags & kIsAnyGeometryMask) == kIsDrawnGeometry); + FML_DCHECK(((flags & kAnyAttributeMask) == 0) != + ((flags & kIgnoresPaint) == 0)); + FML_DCHECK((flags & kIsAnyGeometryMask) != 0 || + (flags & kAnySpecialGeometryMask) == 0); + } + + constexpr DisplayListAttributeFlags operator+(int extra) const { + return extra == 0 ? *this : DisplayListAttributeFlags(flags_ | extra); + } + + constexpr DisplayListAttributeFlags operator-(int remove) const { + FML_DCHECK(has_all(remove)); + return DisplayListAttributeFlags(flags_ & ~remove); + } + + const DisplayListSpecialGeometryFlags special_flags_; + + friend class DisplayListOpFlags; +}; + +class DisplayListOpFlags : DisplayListFlags { + private: + // Flags common to all primitives that apply colors + static constexpr int kBasePaintFlags = (kUsesColor | // + kUsesAlpha | // + kUsesBlend | // + kUsesShader | // + kUsesColorFilter | // + kUsesImageFilter); + + // Flags common to all primitives that stroke or fill + static constexpr int kBaseStrokeOrFillFlags = (kIsDrawnGeometry | // + kUsesAntiAlias | // + kUsesMaskFilter); + + // Flags common to primitives that stroke geometry + static constexpr int kBaseStrokeFlags = (kIsStrokedGeometry | // + kUsesAntiAlias | // + kUsesMaskFilter); + + // Flags common to primitives that render an image with paint attributes + static constexpr int kBaseImageFlags = (kIsNonGeometric | // + kUsesAlpha | // + kUsesBlend | // + kUsesColorFilter | // + kUsesImageFilter); + + public: + static constexpr DisplayListAttributeFlags kSaveLayerFlags{ + kIgnoresPaint // + }; + static constexpr DisplayListAttributeFlags kSaveLayerWithPaintFlags{ + kIsNonGeometric | // + kUsesAlpha | // + kUsesBlend | // + kUsesColorFilter | // + kUsesImageFilter // + }; + static constexpr DisplayListAttributeFlags kDrawColorFlags{ + kFloodsSurface | // + kIgnoresPaint // + }; + static constexpr DisplayListAttributeFlags kDrawPaintFlags{ + kBasePaintFlags | // + kFloodsSurface // + }; + // Special case flags for horizonal and vertical lines + static constexpr DisplayListAttributeFlags kDrawHVLineFlags{ + kBasePaintFlags | // + kBaseStrokeFlags | // + kMayHaveCaps // + }; + static constexpr DisplayListAttributeFlags kDrawLineFlags{ + kDrawHVLineFlags // + + kMayHaveDiagonalCaps // + }; + static constexpr DisplayListAttributeFlags kDrawRectFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags | // + kMayHaveJoins // + }; + static constexpr DisplayListAttributeFlags kDrawOvalFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags // + }; + static constexpr DisplayListAttributeFlags kDrawCircleFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags // + }; + static constexpr DisplayListAttributeFlags kDrawRRectFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags // + }; + static constexpr DisplayListAttributeFlags kDrawDRRectFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags // + }; + static constexpr DisplayListAttributeFlags kDrawRSuperellipseFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags // + }; + static constexpr DisplayListAttributeFlags kDrawPathFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags | // + kMayHaveCaps | // + kMayHaveDiagonalCaps | // + kMayHaveJoins | // + kMayHaveAcuteJoins // + }; + static constexpr DisplayListAttributeFlags kDrawArcNoCenterFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags | // + kMayHaveCaps | // + kMayHaveDiagonalCaps // + }; + static constexpr DisplayListAttributeFlags kDrawArcWithCenterFlags{ + kBasePaintFlags | // + kBaseStrokeOrFillFlags | // + kMayHaveJoins | // + kMayHaveAcuteJoins // + }; + static constexpr DisplayListAttributeFlags kDrawPointsAsPointsFlags{ + kBasePaintFlags | // + kBaseStrokeFlags | // + kMayHaveCaps | // + kButtCapIsSquare // + }; + static constexpr DisplayListAttributeFlags kDrawPointsAsLinesFlags{ + kBasePaintFlags | // + kBaseStrokeFlags | // + kMayHaveCaps | // + kMayHaveDiagonalCaps // + }; + // Polygon mode just draws (count-1) separate lines, no joins + static constexpr DisplayListAttributeFlags kDrawPointsAsPolygonFlags{ + kBasePaintFlags | // + kBaseStrokeFlags | // + kMayHaveCaps | // + kMayHaveDiagonalCaps // + }; + static constexpr DisplayListAttributeFlags kDrawVerticesFlags{ + kIsNonGeometric | // + kUsesAlpha | // + kUsesShader | // + kUsesBlend | // + kUsesColorFilter | // + kUsesImageFilter // + }; + static constexpr DisplayListAttributeFlags kDrawImageFlags{ + kIgnoresPaint // + }; + static constexpr DisplayListAttributeFlags kDrawImageWithPaintFlags{ + kBaseImageFlags | // + kUsesAntiAlias | // + kUsesMaskFilter // + }; + static constexpr DisplayListAttributeFlags kDrawImageRectFlags{ + kIgnoresPaint // + }; + static constexpr DisplayListAttributeFlags kDrawImageRectWithPaintFlags{ + kBaseImageFlags | // + kUsesAntiAlias | // + kUsesMaskFilter // + }; + static constexpr DisplayListAttributeFlags kDrawImageNineFlags{ + kIgnoresPaint // + }; + static constexpr DisplayListAttributeFlags kDrawImageNineWithPaintFlags{ + kBaseImageFlags // + }; + static constexpr DisplayListAttributeFlags kDrawAtlasFlags{ + kIgnoresPaint // + }; + static constexpr DisplayListAttributeFlags kDrawAtlasWithPaintFlags{ + kBaseImageFlags // + }; + static constexpr DisplayListAttributeFlags kDrawDisplayListFlags{ + kIgnoresPaint // + }; + static constexpr DisplayListAttributeFlags kDrawTextBlobFlags{ + DisplayListAttributeFlags(kBasePaintFlags | // + kBaseStrokeOrFillFlags | // + kMayHaveJoins) // + - kUsesAntiAlias // + }; + static constexpr DisplayListAttributeFlags kDrawShadowFlags{ + kIgnoresPaint // + }; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_OP_FLAGS_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_op_receiver.cc b/flutter/engine/src/flutter/display_list/dl_op_receiver.cc new file mode 100644 index 0000000000000000000000000000000000000000..b1b6c01967e56cc0bc8c34475d3a2ecd66317caa --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_op_receiver.cc @@ -0,0 +1,11 @@ +// 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_receiver.h" + +namespace flutter { + +// Just exists to ensure that the header can be cleanly imported. + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_op_receiver.h b/flutter/engine/src/flutter/display_list/dl_op_receiver.h new file mode 100644 index 0000000000000000000000000000000000000000..0d65bad7e0c80066edb7cebadeb635492b52bc3a --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_op_receiver.h @@ -0,0 +1,373 @@ +// 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_RECEIVER_H_ +#define FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_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_paint.h" +#include "flutter/display_list/dl_sampling_options.h" +#include "flutter/display_list/dl_vertices.h" +#include "flutter/display_list/effects/dl_color_filter.h" +#include "flutter/display_list/effects/dl_color_source.h" +#include "flutter/display_list/effects/dl_image_filter.h" +#include "flutter/display_list/effects/dl_mask_filter.h" +#include "flutter/display_list/image/dl_image.h" + +namespace flutter { + +class DisplayList; + +//------------------------------------------------------------------------------ +/// @brief Internal API for rendering recorded display lists to backends. +/// +/// The |DisplayList| object will play back recorded operations in this format. +/// Most developers should not need to deal with this interface unless they are +/// writing a utility that needs to examine the contents of a display list. +/// +/// Similar to |DlCanvas|, this interface carries clip and transform state +/// which are saved and restored by the |save|, |saveLayer|, and |restore| +/// calls. +/// +/// Unlike DlCanvas, this interface has attribute state which is global across +/// an entire DisplayList (not affected by save/restore). +/// +/// DISPLAYLIST DEPTH TRACKING +/// +/// Each rendering call in the DisplayList stream is assumed to have a "depth" +/// value relative to the beginning of its DisplayList. The depth value is +/// implicitly allocated during recording and only reported in 2 places so +/// it is important for a dispatcher to perform the same internal allocations +/// if it is to make sense of the information reported by the save/saveLayer +/// calls. This depth value is maintained as follows: +/// +/// - The absolute depth value is never reported, only the total depth +/// size of the entire DisplayList or one of its save/restore pairs +/// is reported. Since the DisplayList might be dispatched recursively +/// due to embedded drawDisplayList calls, these depth size values +/// will often be relative to things like: +/// - the start of a given save/saveLayer group +/// - the start of a DisplayList dispatch or recursion +/// as such, only totals for groups of DisplayList dispatched calls +/// will be reported. These totals will be reported in: +/// - the `DisplayList::total_depth()` method reporting the total +/// depth accumulated for every operation in the DisplayList +/// - the save/saveLayer dispatch calls will report the total +/// depth accumulated for every call until their corresponding +/// restore call. +/// - The depth value is incremented for every drawing operation, including: +/// - all draw* calls (including drawDisplayList) +/// - drawDisplayList will also accumulate the total_depth() of the +/// DisplayList object it is drawing (in other words it will skip enough +/// depth values for each drawing call in the child). +/// This bump is in addition to the depth value it records for being +/// a rendering operation. Some implementations may need to surround +/// the actual drawDisplayList with a protective saveLayer, but others +/// may not - so the implicit depth value assigned to the drawDisplayList +/// call itself may go unused, but must be accounted for. +/// - a saveLayer call will also increment the depth value just like a +/// rendering call. This is in addition to the depth of its content. +/// It is doing so to reserve a depth for the drawing operation that +/// copies its layer back to the parent. +/// - Each save() or saveLayer() call will report the total depth of all +/// rendering calls within its content (recorded before the corresponding +/// restore) and report this total during dispatch. This information might +/// be needed to assign depths to the clip operations that occur within +/// its content. As there is no enclosing saveLayer/restore pair around +/// the root of a DisplayList, the total depth of the DisplayList can +/// be used to determine the appropriate clip depths for any clip ops +/// appearing before the first save/saveLayer or after the last restore. +/// +/// @see DlSkCanvasDispatcher +/// @see impeller::DlDispatcher +/// @see DlOpSpy +class DlOpReceiver { + public: + // MaxDrawPointsCount * sizeof(DlPoint) must be less than 1 << 32 + static constexpr int kMaxDrawPointsCount = ((1 << 29) - 1); + + // 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 + // another method that changes the same attribute. The current set of + // attributes is not affected by |save| and |restore|. + virtual void setAntiAlias(bool aa) = 0; + virtual void setDrawStyle(DlDrawStyle style) = 0; + virtual void setColor(DlColor color) = 0; + virtual void setStrokeWidth(float width) = 0; + virtual void setStrokeMiter(float limit) = 0; + virtual void setStrokeCap(DlStrokeCap cap) = 0; + virtual void setStrokeJoin(DlStrokeJoin join) = 0; + virtual void setColorSource(const DlColorSource* source) = 0; + virtual void setColorFilter(const DlColorFilter* filter) = 0; + // setInvertColors is a quick way to set a ColorFilter that inverts the + // rgb values of all rendered colors. + // It is not reset by |setColorFilter|, but instead composed with that + // filter so that the color inversion happens after the ColorFilter. + virtual void setInvertColors(bool invert) = 0; + virtual void setBlendMode(DlBlendMode mode) = 0; + virtual void setMaskFilter(const DlMaskFilter* filter) = 0; + virtual void setImageFilter(const DlImageFilter* filter) = 0; + + // All of the following methods are nearly 1:1 with their counterparts + // in |SkCanvas| and have the same behavior and output. + virtual void save() = 0; + // Optional variant of save() that passes the total depth count of + // all rendering operations that occur until the next restore() call. + virtual void save(uint32_t total_content_depth) { save(); } + // The |options| parameter can specify whether the existing rendering + // attributes will be applied to the save layer surface while rendering + // it back to the current surface. If the flag is false then this method + // is equivalent to |SkCanvas::saveLayer| with a null paint object. + // + // The |options| parameter can also specify whether the bounds came from + // the caller who recorded the operation, or whether they were calculated + // by the DisplayListBuilder. + // + // The |options| parameter may contain other options that indicate some + // specific optimizations may be made by the underlying implementation + // to avoid creating a temporary layer, these optimization options will + // be determined as the |DisplayList| is constructed and should not be + // specified in calling a |DisplayListBuilder| as they will be ignored. + // The |backdrop| filter, if not null, is used to initialize the new + // layer before further rendering happens. + virtual void saveLayer(const DlRect& bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop = nullptr, + std::optional backdrop_id = std::nullopt) = 0; + // Optional variant of saveLayer() that passes the total depth count of + // all rendering operations that occur until the next restore() call. + virtual void saveLayer(const DlRect& bounds, + const SaveLayerOptions& options, + uint32_t total_content_depth, + DlBlendMode max_content_blend_mode, + const DlImageFilter* backdrop = nullptr, + std::optional backdrop_id = std::nullopt) { + saveLayer(bounds, options, backdrop, backdrop_id); + } + virtual void restore() = 0; + + // --------------------------------------------------------------------- + // Legacy helper method for older callers that use the null-ness of + // the bounds to indicate if they should be recorded or computed. + // This method will not be called on a |DlOpReceiver| that is passed + // to the |DisplayList::Dispatch()| method, so client receivers should + // ignore it for their implementation purposes. + // + // DlOpReceiver methods are generally meant to ONLY be output from a + // previously recorded DisplayList so this method is really only used + // from testing methods that bypass the public builder APIs for legacy + // convenience or for internal white-box testing of the DisplayList + // internals. Such methods should eventually be converted to using the + // public DisplayListBuilder/DlCanvas public interfaces where possible, + // as tracked in: + // https://github.com/flutter/flutter/issues/144070 + virtual void saveLayer( + const DlRect* bounds, + const SaveLayerOptions options, + const DlImageFilter* backdrop = nullptr, + std::optional backdrop_id = std::nullopt) final { + if (bounds) { + saveLayer(*bounds, options.with_bounds_from_caller(), backdrop, + backdrop_id); + } else { + saveLayer(DlRect(), options.without_bounds_from_caller(), backdrop, + backdrop_id); + } + } + // --------------------------------------------------------------------- + + virtual void translate(DlScalar tx, DlScalar ty) = 0; + virtual void scale(DlScalar sx, DlScalar sy) = 0; + virtual void rotate(DlScalar degrees) = 0; + virtual void skew(DlScalar sx, DlScalar sy) = 0; + + // The transform methods all assume the following math for transforming + // an arbitrary 3D homogenous point (x, y, z, w). + // All coordinates in the rendering methods (and DlPoint and DlRect objects) + // represent a simplified coordinate (x, y, 0, 1). + // x' = x * mxx + y * mxy + z * mxz + w * mxt + // y' = x * myx + y * myy + z * myz + w * myt + // z' = x * mzx + y * mzy + z * mzz + w * mzt + // w' = x * mwx + y * mwy + z * mwz + w * mwt + // Note that for non-homogenous 2D coordinates, the last column in those + // equations is multiplied by 1 and is simply adding a translation and + // so is referred to with the final letter "t" here instead of "w". + // + // In 2D coordinates, z=0 and so the 3rd column always evaluates to 0. + // + // In non-perspective transforms, the 4th row has identity values + // and so w` = w. (i.e. w'=1 for 2d points transformed by a matrix + // with identity values in the last row). + // + // In affine 2D transforms, the 3rd and 4th row and 3rd column are all + // identity values and so z` = z (which is 0 for 2D coordinates) and + // the x` and y` equations don't see a contribution from a z coordinate + // and the w' ends up being the same as the w from the source coordinate + // (which is 1 for a 2D coordinate). + // + // Here is the math for transforming a 2D source coordinate and + // looking for the destination 2D coordinate (for a surface that + // does not have a Z buffer or track the Z coordinates in any way) + // Source coordinate = (x, y, 0, 1) + // x' = x * mxx + y * mxy + 0 * mxz + 1 * mxt + // y' = x * myx + y * myy + 0 * myz + 1 * myt + // z' = x * mzx + y * mzy + 0 * mzz + 1 * mzt + // w' = x * mwx + y * mwy + 0 * mwz + 1 * mwt + // Destination coordinate does not need z', so this reduces to: + // x' = x * mxx + y * mxy + mxt + // y' = x * myx + y * myy + myt + // w' = x * mwx + y * mwy + mwt + // Destination coordinate is (x' / w', y' / w', 0, 1) + // Note that these are the matrix values in SkMatrix which means that + // an SkMatrix contains enough data to transform a 2D source coordinate + // and place it on a 2D surface, but is otherwise not enough to continue + // concatenating with further matrices as its missing elements will not + // be able to model the interplay between the rows and columns that + // happens during a full 4x4 by 4x4 matrix multiplication. + // + // If the transform doesn't have any perspective parts (the last + // row is identity - 0, 0, 0, 1), then this further simplifies to: + // x' = x * mxx + y * mxy + mxt + // y' = x * myx + y * myy + myt + // w' = x * 0 + y * 0 + 1 = 1 + // + // In short, while the full 4x4 set of matrix entries needs to be + // maintained for accumulating transform mutations accurately, the + // actual end work of transforming a single 2D coordinate (or, in + // the case of bounds transformations, 4 of them) can be accomplished + // with the 9 values from transform3x3 or SkMatrix. + // + // The only need for the w value here is for homogenous coordinates + // which only come up if the perspective elements (the 4th row) of + // a transform are non-identity. Otherwise the w always ends up + // being 1 in all calculations. If the matrix has perspecitve elements + // then the final transformed coordinates will have a w that is not 1 + // and the actual coordinates are determined by dividing out that w + // factor resulting in a real-world point expressed as (x, y, z, 1). + // + // Because of the predominance of 2D affine transforms the + // 2x3 subset of the 4x4 transform matrix is special cased with + // its own dispatch method that omits the last 2 rows and the 3rd + // column. Even though a 3x3 subset is enough for transforming + // leaf coordinates as shown above, no method is provided for + // representing a 3x3 transform in the DisplayList since if there + // is perspective involved then a full 4x4 matrix should be provided + // for accurate concatenations. Providing a 3x3 method or record + // in the stream would encourage developers to prematurely subset + // a full perspective matrix. + + // clang-format off + + // |transform2DAffine| is equivalent to concatenating the internal + // 4x4 transform with the following row major transform matrix: + // [ mxx mxy 0 mxt ] + // [ myx myy 0 myt ] + // [ 0 0 1 0 ] + // [ 0 0 0 1 ] + virtual void transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myt) = 0; + // |transformFullPerspective| is equivalent to concatenating the internal + // 4x4 transform with the following row major transform matrix: + // [ mxx mxy mxz mxt ] + // [ myx myy myz myt ] + // [ mzx mzy mzz mzt ] + // [ mwx mwy mwz mwt ] + virtual void transformFullPerspective( + DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, + DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, + DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) = 0; + // clang-format on + + // Clears the transformation stack. + virtual void transformReset() = 0; + + virtual void clipRect(const DlRect& rect, DlClipOp clip_op, bool is_aa) = 0; + virtual void clipOval(const DlRect& bounds, DlClipOp clip_op, bool is_aa) = 0; + virtual void clipRoundRect(const DlRoundRect& rrect, + DlClipOp clip_op, + bool is_aa) = 0; + virtual void clipRoundSuperellipse(const DlRoundSuperellipse& rse, + DlClipOp clip_op, + bool is_aa) = 0; + virtual void clipPath(const DlPath& path, DlClipOp clip_op, bool is_aa) = 0; + + // The following rendering methods all take their rendering attributes + // from the last value set by the attribute methods above (regardless + // of any |save| or |restore| operations which do not affect attributes). + // In cases where a paint object may have been optional in the SkCanvas + // method, the methods here will generally offer a boolean parameter + // which specifies whether to honor the attributes of the display list + // stream, or assume default attributes. + virtual void drawColor(DlColor color, DlBlendMode mode) = 0; + virtual void drawPaint() = 0; + virtual void drawLine(const DlPoint& p0, const DlPoint& p1) = 0; + virtual void drawDashedLine(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length) = 0; + virtual void drawRect(const DlRect& rect) = 0; + virtual void drawOval(const DlRect& bounds) = 0; + virtual void drawCircle(const DlPoint& center, DlScalar radius) = 0; + virtual void drawRoundRect(const DlRoundRect& rrect) = 0; + virtual void drawDiffRoundRect(const DlRoundRect& outer, + const DlRoundRect& inner) = 0; + virtual void drawRoundSuperellipse(const DlRoundSuperellipse& rse) = 0; + virtual void drawPath(const DlPath& path) = 0; + virtual void drawArc(const DlRect& oval_bounds, + DlScalar start_degrees, + DlScalar sweep_degrees, + bool use_center) = 0; + virtual void drawPoints(DlPointMode mode, + uint32_t count, + const DlPoint points[]) = 0; + virtual void drawVertices(const std::shared_ptr& vertices, + DlBlendMode mode) = 0; + virtual void drawImage(const sk_sp image, + const DlPoint& point, + DlImageSampling sampling, + bool render_with_attributes) = 0; + virtual void drawImageRect( + const sk_sp image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) = 0; + virtual void drawImageNine(const sk_sp image, + const DlIRect& center, + const DlRect& dst, + DlFilterMode filter, + bool render_with_attributes) = 0; + virtual void drawAtlas(const sk_sp atlas, + const DlRSTransform xform[], + const DlRect tex[], + const DlColor colors[], + int count, + DlBlendMode mode, + DlImageSampling sampling, + const DlRect* cull_rect, + bool render_with_attributes) = 0; + virtual void drawDisplayList(const sk_sp display_list, + DlScalar opacity = SK_Scalar1) = 0; + virtual void drawTextBlob(const sk_sp blob, + DlScalar x, + DlScalar y) = 0; + virtual void drawTextFrame( + const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y) = 0; + virtual void drawShadow(const DlPath& path, + const DlColor color, + const DlScalar elevation, + bool transparent_occluder, + DlScalar dpr) = 0; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_op_records.cc b/flutter/engine/src/flutter/display_list/dl_op_records.cc new file mode 100644 index 0000000000000000000000000000000000000000..e93e65afb4d6d5fa11d2ae278d95078deab4c35a --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_op_records.cc @@ -0,0 +1,11 @@ +// 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_records.h" + +namespace flutter { + +// Just exists to ensure that the header can be cleanly imported. + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_op_records.h b/flutter/engine/src/flutter/display_list/dl_op_records.h new file mode 100644 index 0000000000000000000000000000000000000000..8ce8db76ba41ade8cb10aef4ccc77019d7ab0119 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_op_records.h @@ -0,0 +1,1075 @@ +// 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_RECORDS_H_ +#define FLUTTER_DISPLAY_LIST_DL_OP_RECORDS_H_ + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_op_receiver.h" +#include "flutter/display_list/dl_sampling_options.h" +#include "flutter/display_list/effects/dl_color_sources.h" +#include "flutter/display_list/utils/dl_comparable.h" +#include "flutter/fml/macros.h" + +#include "flutter/impeller/geometry/path.h" +#include "flutter/impeller/typographer/text_frame.h" + +namespace flutter { + +// Most Ops can be bulk compared using memcmp because they contain +// only numeric values or constructs that are constructed from numeric +// values. +// +// Some contain sk_sp<> references which can also be bulk compared +// to see if they are pointing to the same reference. (Note that +// two sk_sp<> that refer to the same object are themselves ==.) +// +// Only a DLOp that wants to do a deep compare needs to override the +// DLOp::equals() method and return a value of kEqual or kNotEqual. +enum class DisplayListCompare { + // The Op is deferring comparisons to a bulk memcmp performed lazily + // across all bulk-comparable ops. + kUseBulkCompare, + + // The Op provided a specific equals method that spotted a difference + kNotEqual, + + // The Op provided a specific equals method that saw no differences + kEqual, +}; + +// "DLOpPackLabel" is just a label for the pack pragma so it can be popped +// later. +#pragma pack(push, DLOpPackLabel, 8) + +// Assuming a 64-bit platform (most of our platforms at this time?) +// the following comments are a "worst case" assessment of how well +// these structures pack into memory. They may be packed more tightly +// on some of the 32-bit platforms that we see in older phones. +// +// Struct allocation in the DL memory is aligned to a void* boundary +// which means that the minimum (aligned) struct size will be 8 bytes. +// The DLOp base uses 4 bytes so each Op-specific struct gets 4 bytes +// of data for "free" and works best when it packs well into an 8-byte +// aligned size. +struct DLOp { + static constexpr uint32_t kDepthInc = 0; + static constexpr uint32_t kRenderOpInc = 0; + + explicit DLOp(DisplayListOpType type) : type(type) {} + + const DisplayListOpType type; + + DisplayListCompare equals(const DLOp* other) const { + return DisplayListCompare::kUseBulkCompare; + } +}; + +// 4 byte header + 4 byte payload packs into minimum 8 bytes +#define DEFINE_SET_BOOL_OP(name) \ + struct Set##name##Op final : DLOp { \ + static constexpr auto kType = DisplayListOpType::kSet##name; \ + \ + explicit Set##name##Op(bool value) : DLOp(kType), value(value) {} \ + \ + const bool value; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.set##name(value); \ + } \ + }; +DEFINE_SET_BOOL_OP(AntiAlias) +DEFINE_SET_BOOL_OP(InvertColors) +#undef DEFINE_SET_BOOL_OP + +// 4 byte header + 4 byte payload packs into minimum 8 bytes +#define DEFINE_SET_ENUM_OP(name) \ + struct SetStroke##name##Op final : DLOp { \ + static constexpr auto kType = DisplayListOpType::kSetStroke##name; \ + \ + explicit SetStroke##name##Op(DlStroke##name value) \ + : DLOp(kType), value(value) {} \ + \ + const DlStroke##name value; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.setStroke##name(value); \ + } \ + }; +DEFINE_SET_ENUM_OP(Cap) +DEFINE_SET_ENUM_OP(Join) +#undef DEFINE_SET_ENUM_OP + +// 4 byte header + 4 byte payload packs into minimum 8 bytes +struct SetStyleOp final : DLOp { + static constexpr auto kType = DisplayListOpType::kSetStyle; + + explicit SetStyleOp(DlDrawStyle style) : DLOp(kType), style(style) {} + + const DlDrawStyle style; + + void dispatch(DlOpReceiver& receiver) const { // + receiver.setDrawStyle(style); + } +}; +// 4 byte header + 4 byte payload packs into minimum 8 bytes +struct SetStrokeWidthOp final : DLOp { + static constexpr auto kType = DisplayListOpType::kSetStrokeWidth; + + explicit SetStrokeWidthOp(float width) : DLOp(kType), width(width) {} + + const float width; + + void dispatch(DlOpReceiver& receiver) const { + receiver.setStrokeWidth(width); + } +}; +// 4 byte header + 4 byte payload packs into minimum 8 bytes +struct SetStrokeMiterOp final : DLOp { + static constexpr auto kType = DisplayListOpType::kSetStrokeMiter; + + explicit SetStrokeMiterOp(float limit) : DLOp(kType), limit(limit) {} + + const float limit; + + void dispatch(DlOpReceiver& receiver) const { + receiver.setStrokeMiter(limit); + } +}; + +// 4 byte header + 20 byte payload packs into minimum 24 bytes +struct SetColorOp final : DLOp { + static constexpr auto kType = DisplayListOpType::kSetColor; + + explicit SetColorOp(DlColor color) : DLOp(kType), color(color) {} + + const DlColor color; + + void dispatch(DlOpReceiver& receiver) const { receiver.setColor(color); } +}; +// 4 byte header + 4 byte payload packs into minimum 8 bytes +struct SetBlendModeOp final : DLOp { + static constexpr auto kType = DisplayListOpType::kSetBlendMode; + + explicit SetBlendModeOp(DlBlendMode mode) : DLOp(kType), mode(mode) {} + + const DlBlendMode mode; + + void dispatch(DlOpReceiver& receiver) const { // + receiver.setBlendMode(mode); + } +}; + +// Clear: 4 byte header + unused 4 byte payload uses 8 bytes +// (4 bytes unused) +// Set: 4 byte header + unused 4 byte struct padding + Dl +// instance copied to the memory following the record +// yields a size and efficiency that has somewhere between +// 4 and 8 bytes unused +#define DEFINE_SET_CLEAR_DLATTR_OP(name, field) \ + struct Clear##name##Op final : DLOp { \ + static constexpr auto kType = DisplayListOpType::kClear##name; \ + \ + Clear##name##Op() : DLOp(kType) {} \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.set##name(nullptr); \ + } \ + }; \ + struct SetPod##name##Op final : DLOp { \ + static constexpr auto kType = DisplayListOpType::kSetPod##name; \ + \ + SetPod##name##Op() : DLOp(kType) {} \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + const Dl##name* filter = reinterpret_cast(this + 1); \ + receiver.set##name(filter); \ + } \ + }; +DEFINE_SET_CLEAR_DLATTR_OP(ColorFilter, filter) +DEFINE_SET_CLEAR_DLATTR_OP(ImageFilter, filter) +DEFINE_SET_CLEAR_DLATTR_OP(MaskFilter, filter) +DEFINE_SET_CLEAR_DLATTR_OP(ColorSource, source) +#undef DEFINE_SET_CLEAR_DLATTR_OP + +// 4 byte header + 96 bytes for the embedded DlImageColorSource +// uses 104 total bytes (4 bytes unused) +struct SetImageColorSourceOp : DLOp { + static constexpr auto kType = DisplayListOpType::kSetImageColorSource; + + explicit SetImageColorSourceOp(const DlImageColorSource* source) + : DLOp(kType), + source(source->image(), + source->horizontal_tile_mode(), + source->vertical_tile_mode(), + source->sampling(), + source->matrix_ptr()) {} + + const DlImageColorSource source; + + void dispatch(DlOpReceiver& receiver) const { + receiver.setColorSource(&source); + } +}; + +// 56 bytes: 4 byte header, 4 byte padding, 8 for vtable, 8 * 2 for sk_sps, 24 +// for the std::vector. +struct SetRuntimeEffectColorSourceOp : DLOp { + static constexpr auto kType = DisplayListOpType::kSetRuntimeEffectColorSource; + + explicit SetRuntimeEffectColorSourceOp( + const DlRuntimeEffectColorSource* source) + : DLOp(kType), + source(source->runtime_effect(), + source->samplers(), + source->uniform_data()) {} + + const DlRuntimeEffectColorSource source; + + void dispatch(DlOpReceiver& receiver) const { + receiver.setColorSource(&source); + } + + DisplayListCompare equals(const SetRuntimeEffectColorSourceOp* other) const { + return (source == other->source) ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; + +// 4 byte header + 16 byte payload uses 24 total bytes (4 bytes unused) +struct SetSharedImageFilterOp : DLOp { + static constexpr auto kType = DisplayListOpType::kSetSharedImageFilter; + + explicit SetSharedImageFilterOp(const DlImageFilter* filter) + : DLOp(kType), filter(filter->shared()) {} + + const std::shared_ptr filter; + + void dispatch(DlOpReceiver& receiver) const { + receiver.setImageFilter(filter.get()); + } + + DisplayListCompare equals(const SetSharedImageFilterOp* other) const { + return Equals(filter, other->filter) ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; + +// The base struct for all save() and saveLayer() ops +// 4 byte header + 12 byte payload packs exactly into 16 bytes +struct SaveOpBase : DLOp { + static constexpr uint32_t kDepthInc = 0; + static constexpr uint32_t kRenderOpInc = 1; + + explicit SaveOpBase(DisplayListOpType type) + : DLOp(type), options(), restore_index(0), total_content_depth(0) {} + + SaveOpBase(DisplayListOpType type, const SaveLayerOptions& options) + : DLOp(type), + options(options), + restore_index(0), + total_content_depth(0) {} + + // options parameter is only used by saveLayer operations, but since + // it packs neatly into the empty space created by laying out the rest + // of the data here, it can be stored for free and defaulted to 0 for + // save operations. + SaveLayerOptions options; + DlIndex restore_index; + uint32_t total_content_depth; +}; +// 16 byte SaveOpBase with no additional data (options is unsed here) +struct SaveOp final : SaveOpBase { + static constexpr auto kType = DisplayListOpType::kSave; + + SaveOp() : SaveOpBase(kType) {} + + void dispatch(DlOpReceiver& receiver) const { + receiver.save(total_content_depth); + } +}; +// The base struct for all saveLayer() ops +// 16 byte SaveOpBase + 20 byte payload packs into 36 bytes +struct SaveLayerOpBase : SaveOpBase { + SaveLayerOpBase(DisplayListOpType type, + const SaveLayerOptions& options, + const DlRect& rect) + : SaveOpBase(type, options), rect(rect) {} + + DlRect rect; + DlBlendMode max_blend_mode = DlBlendMode::kClear; +}; +// 36 byte SaveLayerOpBase with no additional data packs into 40 bytes +// of buffer storage with 4 bytes unused. +struct SaveLayerOp final : SaveLayerOpBase { + static constexpr auto kType = DisplayListOpType::kSaveLayer; + + SaveLayerOp(const SaveLayerOptions& options, const DlRect& rect) + : SaveLayerOpBase(kType, options, rect) {} + + void dispatch(DlOpReceiver& receiver) const { + receiver.saveLayer(rect, options, total_content_depth, max_blend_mode); + } +}; +// 36 byte SaveLayerOpBase + 4 bytes for alignment + 16 byte payload packs +// into minimum 56 bytes +struct SaveLayerBackdropOp final : SaveLayerOpBase { + static constexpr auto kType = DisplayListOpType::kSaveLayerBackdrop; + + SaveLayerBackdropOp(const SaveLayerOptions& options, + const DlRect& rect, + const DlImageFilter* backdrop, + std::optional backdrop_id) + : SaveLayerOpBase(kType, options, rect), + backdrop(backdrop->shared()), + backdrop_id_(backdrop_id) {} + + const std::shared_ptr backdrop; + std::optional backdrop_id_; + + void dispatch(DlOpReceiver& receiver) const { + receiver.saveLayer(rect, options, total_content_depth, max_blend_mode, + backdrop.get(), backdrop_id_); + } + + DisplayListCompare equals(const SaveLayerBackdropOp* other) const { + return (options == other->options && rect == other->rect && + Equals(backdrop, other->backdrop) && + backdrop_id_ == other->backdrop_id_) + ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; +// 4 byte header + no payload uses minimum 8 bytes (4 bytes unused) +struct RestoreOp final : DLOp { + static constexpr auto kType = DisplayListOpType::kRestore; + static constexpr uint32_t kDepthInc = 0; + static constexpr uint32_t kRenderOpInc = 1; + + RestoreOp() : DLOp(kType) {} + + void dispatch(DlOpReceiver& receiver) const { // + receiver.restore(); + } +}; + +struct TransformClipOpBase : DLOp { + static constexpr uint32_t kDepthInc = 0; + static constexpr uint32_t kRenderOpInc = 1; + + explicit TransformClipOpBase(DisplayListOpType type) : DLOp(type) {} +}; +// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes +// (4 bytes unused) +struct TranslateOp final : TransformClipOpBase { + static constexpr auto kType = DisplayListOpType::kTranslate; + + TranslateOp(DlScalar tx, DlScalar ty) + : TransformClipOpBase(kType), tx(tx), ty(ty) {} + + const DlScalar tx; + const DlScalar ty; + + void dispatch(DlOpReceiver& receiver) const { // + receiver.translate(tx, ty); + } +}; +// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes +// (4 bytes unused) +struct ScaleOp final : TransformClipOpBase { + static constexpr auto kType = DisplayListOpType::kScale; + + ScaleOp(DlScalar sx, DlScalar sy) + : TransformClipOpBase(kType), sx(sx), sy(sy) {} + + const DlScalar sx; + const DlScalar sy; + + void dispatch(DlOpReceiver& receiver) const { // + receiver.scale(sx, sy); + } +}; +// 4 byte header + 4 byte payload packs into minimum 8 bytes +struct RotateOp final : TransformClipOpBase { + static constexpr auto kType = DisplayListOpType::kRotate; + + explicit RotateOp(DlScalar degrees) + : TransformClipOpBase(kType), degrees(degrees) {} + + const DlScalar degrees; + + void dispatch(DlOpReceiver& receiver) const { // + receiver.rotate(degrees); + } +}; +// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes +// (4 bytes unused) +struct SkewOp final : TransformClipOpBase { + static constexpr auto kType = DisplayListOpType::kSkew; + + SkewOp(DlScalar sx, DlScalar sy) + : TransformClipOpBase(kType), sx(sx), sy(sy) {} + + const DlScalar sx; + const DlScalar sy; + + void dispatch(DlOpReceiver& receiver) const { // + receiver.skew(sx, sy); + } +}; +// 4 byte header + 24 byte payload uses 28 bytes but is rounded up to 32 bytes +// (4 bytes unused) +struct Transform2DAffineOp final : TransformClipOpBase { + static constexpr auto kType = DisplayListOpType::kTransform2DAffine; + + // clang-format off + Transform2DAffineOp(DlScalar mxx, DlScalar mxy, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myt) + : TransformClipOpBase(kType), + mxx(mxx), mxy(mxy), mxt(mxt), + myx(myx), myy(myy), myt(myt) {} + // clang-format on + + const DlScalar mxx, mxy, mxt; + const DlScalar myx, myy, myt; + + void dispatch(DlOpReceiver& receiver) const { + receiver.transform2DAffine(mxx, mxy, mxt, // + myx, myy, myt); + } +}; +// 4 byte header + 64 byte payload uses 68 bytes which is rounded up to 72 bytes +// (4 bytes unused) +struct TransformFullPerspectiveOp final : TransformClipOpBase { + static constexpr auto kType = DisplayListOpType::kTransformFullPerspective; + + // clang-format off + TransformFullPerspectiveOp( + DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, + DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, + DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, + DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) + : TransformClipOpBase(kType), + mxx(mxx), mxy(mxy), mxz(mxz), mxt(mxt), + myx(myx), myy(myy), myz(myz), myt(myt), + mzx(mzx), mzy(mzy), mzz(mzz), mzt(mzt), + mwx(mwx), mwy(mwy), mwz(mwz), mwt(mwt) {} + // clang-format on + + const DlScalar mxx, mxy, mxz, mxt; + const DlScalar myx, myy, myz, myt; + const DlScalar mzx, mzy, mzz, mzt; + const DlScalar mwx, mwy, mwz, mwt; + + void dispatch(DlOpReceiver& receiver) const { + receiver.transformFullPerspective(mxx, mxy, mxz, mxt, // + myx, myy, myz, myt, // + mzx, mzy, mzz, mzt, // + mwx, mwy, mwz, mwt); + } +}; + +// 4 byte header with no payload. +struct TransformResetOp final : TransformClipOpBase { + static constexpr auto kType = DisplayListOpType::kTransformReset; + + TransformResetOp() : TransformClipOpBase(kType) {} + + void dispatch(DlOpReceiver& receiver) const { // + receiver.transformReset(); + } +}; + +// 4 byte header + 4 byte common payload packs into minimum 8 bytes +// DlRect is 16 more bytes, which packs efficiently into 24 bytes total +// DlRoundRect is 48 more bytes, which rounds up to 48 bytes +// which packs into 56 bytes total +// DlRoundSuperellipse is the same as DlRoundRect +// CacheablePath is 128 more bytes, which packs efficiently into 136 bytes total +// +// We could pack the clip_op and the bool both into the free 4 bytes after +// the header, but the Windows compiler keeps wanting to expand that +// packing into more bytes than needed (even when they are declared as +// packed bit fields!) +#define DEFINE_CLIP_SHAPE_OP(shapename, shapetype, clipop) \ + struct Clip##clipop##shapename##Op final : TransformClipOpBase { \ + static constexpr auto kType = DisplayListOpType::kClip##clipop##shapename; \ + \ + Clip##clipop##shapename##Op(shapetype shape, bool is_aa) \ + : TransformClipOpBase(kType), is_aa(is_aa), shape(shape) {} \ + \ + const bool is_aa; \ + const shapetype shape; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.clip##shapename(shape, DlClipOp::k##clipop, is_aa); \ + } \ + }; +DEFINE_CLIP_SHAPE_OP(Rect, DlRect, Intersect) +DEFINE_CLIP_SHAPE_OP(Oval, DlRect, Intersect) +DEFINE_CLIP_SHAPE_OP(RoundRect, DlRoundRect, Intersect) +DEFINE_CLIP_SHAPE_OP(RoundSuperellipse, DlRoundSuperellipse, Intersect) +DEFINE_CLIP_SHAPE_OP(Rect, DlRect, Difference) +DEFINE_CLIP_SHAPE_OP(Oval, DlRect, Difference) +DEFINE_CLIP_SHAPE_OP(RoundRect, DlRoundRect, Difference) +DEFINE_CLIP_SHAPE_OP(RoundSuperellipse, DlRoundSuperellipse, Difference) +#undef DEFINE_CLIP_SHAPE_OP + +// 4 byte header + 20 byte payload packs evenly into 24 bytes +#define DEFINE_CLIP_PATH_OP(clipop) \ + struct Clip##clipop##PathOp final : TransformClipOpBase { \ + static constexpr auto kType = DisplayListOpType::kClip##clipop##Path; \ + \ + Clip##clipop##PathOp(const DlPath& path, bool is_aa) \ + : TransformClipOpBase(kType), is_aa(is_aa), path(path) {} \ + \ + const bool is_aa; \ + const DlPath path; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.clipPath(path, DlClipOp::k##clipop, is_aa); \ + } \ + \ + DisplayListCompare equals(const Clip##clipop##PathOp* other) const { \ + return is_aa == other->is_aa && path == other->path \ + ? DisplayListCompare::kEqual \ + : DisplayListCompare::kNotEqual; \ + } \ + }; +DEFINE_CLIP_PATH_OP(Intersect) +DEFINE_CLIP_PATH_OP(Difference) +#undef DEFINE_CLIP_PATH_OP + +struct DrawOpBase : DLOp { + static constexpr uint32_t kDepthInc = 1; + static constexpr uint32_t kRenderOpInc = 1; + + explicit DrawOpBase(DisplayListOpType type) : DLOp(type) {} +}; + +// 4 byte header + no payload uses minimum 8 bytes (4 bytes unused) +struct DrawPaintOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawPaint; + + DrawPaintOp() : DrawOpBase(kType) {} + + void dispatch(DlOpReceiver& receiver) const { // + receiver.drawPaint(); + } +}; +// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes +// (4 bytes unused) +struct DrawColorOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawColor; + + DrawColorOp(DlColor color, DlBlendMode mode) + : DrawOpBase(kType), color(color), mode(mode) {} + + const DlColor color; + const DlBlendMode mode; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawColor(color, mode); + } +}; + +// The common data is a 4 byte header with an unused 4 bytes +// DlRect is 16 more bytes, using 20 bytes which rounds up to 24 bytes total +// (4 bytes unused) +// SkOval is same as DlRect +// DlRoundRect is 48 more bytes, using 52 bytes which rounds up to 56 bytes +// total (4 bytes unused) +// DlRoundSuperellipse is the same as DlRoundRect +#define DEFINE_DRAW_1ARG_OP(op_name, arg_type, arg_name) \ + struct Draw##op_name##Op final : DrawOpBase { \ + static constexpr auto kType = DisplayListOpType::kDraw##op_name; \ + \ + explicit Draw##op_name##Op(arg_type arg_name) \ + : DrawOpBase(kType), arg_name(arg_name) {} \ + \ + const arg_type arg_name; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.draw##op_name(arg_name); \ + } \ + }; +DEFINE_DRAW_1ARG_OP(Rect, DlRect, rect) +DEFINE_DRAW_1ARG_OP(Oval, DlRect, oval) +DEFINE_DRAW_1ARG_OP(RoundRect, DlRoundRect, rrect) +DEFINE_DRAW_1ARG_OP(RoundSuperellipse, DlRoundSuperellipse, rse) +#undef DEFINE_DRAW_1ARG_OP + +// 4 byte header + 16 byte payload uses 20 bytes but is rounded +// up to 24 bytes (4 bytes unused) +struct DrawPathOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawPath; + + explicit DrawPathOp(const DlPath& path) : DrawOpBase(kType), path(path) {} + + const DlPath path; + + void dispatch(DlOpReceiver& receiver) const { // + receiver.drawPath(path); + } + + DisplayListCompare equals(const DrawPathOp* other) const { + return path == other->path ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; + +// The common data is a 4 byte header with an unused 4 bytes +// 2 x DlPoint is 16 more bytes, using 20 bytes rounding up to 24 bytes total +// (4 bytes unused) +// DlPoint + DlScalar is 12 more bytes, packing efficiently into 16 bytes total +// 2 x DlRoundRect is 96 more bytes, using 100 and rounding up to 104 bytes +// total (4 bytes unused) +#define DEFINE_DRAW_2ARG_OP(op_name, type1, name1, type2, name2) \ + struct Draw##op_name##Op final : DrawOpBase { \ + static constexpr auto kType = DisplayListOpType::kDraw##op_name; \ + \ + Draw##op_name##Op(type1 name1, type2 name2) \ + : DrawOpBase(kType), name1(name1), name2(name2) {} \ + \ + const type1 name1; \ + const type2 name2; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.draw##op_name(name1, name2); \ + } \ + }; +DEFINE_DRAW_2ARG_OP(Line, DlPoint, p0, DlPoint, p1) +DEFINE_DRAW_2ARG_OP(Circle, DlPoint, center, DlScalar, radius) +DEFINE_DRAW_2ARG_OP(DiffRoundRect, DlRoundRect, outer, DlRoundRect, inner) +#undef DEFINE_DRAW_2ARG_OP + +// 4 byte header + 24 byte payload packs into 32 bytes (4 bytes unused) +struct DrawDashedLineOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawDashedLine; + + DrawDashedLineOp(const DlPoint& p0, + const DlPoint& p1, + DlScalar on_length, + DlScalar off_length) + : DrawOpBase(kType), + p0(p0), + p1(p1), + on_length(on_length), + off_length(off_length) {} + + const DlPoint p0; + const DlPoint p1; + const DlScalar on_length; + const DlScalar off_length; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawDashedLine(p0, p1, on_length, off_length); + } +}; + +// 4 byte header + 28 byte payload packs efficiently into 32 bytes +struct DrawArcOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawArc; + + DrawArcOp(DlRect bounds, DlScalar start, DlScalar sweep, bool center) + : DrawOpBase(kType), + bounds(bounds), + start(start), + sweep(sweep), + center(center) {} + + const DlRect bounds; + const DlScalar start; + const DlScalar sweep; + const bool center; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawArc(bounds, start, sweep, center); + } +}; + +// 4 byte header + 4 byte fixed payload packs efficiently into 8 bytes +// But then there is a list of points following the structure which +// is guaranteed to be a multiple of 8 bytes (DlPoint is 8 bytes) +// so this op will always pack efficiently +// The point type is packed into 3 different OpTypes to avoid expanding +// the fixed payload beyond the 8 bytes +#define DEFINE_DRAW_POINTS_OP(name, mode) \ + struct Draw##name##Op final : DrawOpBase { \ + static constexpr auto kType = DisplayListOpType::kDraw##name; \ + \ + explicit Draw##name##Op(uint32_t count) \ + : DrawOpBase(kType), count(count) {} \ + \ + const uint32_t count; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + const DlPoint* pts = reinterpret_cast(this + 1); \ + receiver.drawPoints(DlPointMode::mode, count, pts); \ + } \ + }; +DEFINE_DRAW_POINTS_OP(Points, kPoints); +DEFINE_DRAW_POINTS_OP(Lines, kLines); +DEFINE_DRAW_POINTS_OP(Polygon, kPolygon); +#undef DEFINE_DRAW_POINTS_OP + +// 4 byte header + 20 byte payload packs efficiently into 24 bytes +struct DrawVerticesOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawVertices; + + explicit DrawVerticesOp(const std::shared_ptr& vertices, + DlBlendMode mode) + : DrawOpBase(kType), mode(mode), vertices(vertices) {} + + const DlBlendMode mode; + const std::shared_ptr vertices; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawVertices(vertices, mode); + } +}; + +// 4 byte header + 40 byte payload uses 44 bytes but is rounded up to 48 bytes +// (4 bytes unused) +#define DEFINE_DRAW_IMAGE_OP(name, with_attributes) \ + struct name##Op final : DrawOpBase { \ + static constexpr auto kType = DisplayListOpType::k##name; \ + \ + name##Op(const sk_sp& image, \ + const DlPoint& point, \ + DlImageSampling sampling) \ + : DrawOpBase(kType), \ + point(point), \ + sampling(sampling), \ + image(std::move(image)) {} \ + \ + const DlPoint point; \ + const DlImageSampling sampling; \ + const sk_sp image; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.drawImage(image, point, sampling, with_attributes); \ + } \ + \ + DisplayListCompare equals(const name##Op* other) const { \ + return (point == other->point && sampling == other->sampling && \ + image->Equals(other->image)) \ + ? DisplayListCompare::kEqual \ + : DisplayListCompare::kNotEqual; \ + } \ + }; +DEFINE_DRAW_IMAGE_OP(DrawImage, false) +DEFINE_DRAW_IMAGE_OP(DrawImageWithAttr, true) +#undef DEFINE_DRAW_IMAGE_OP + +// 4 byte header + 72 byte payload uses 76 bytes but is rounded up to 80 bytes +// (4 bytes unused) +struct DrawImageRectOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawImageRect; + + DrawImageRectOp(const sk_sp& image, + const DlRect& src, + const DlRect& dst, + DlImageSampling sampling, + bool render_with_attributes, + DlSrcRectConstraint constraint) + : DrawOpBase(kType), + src(src), + dst(dst), + sampling(sampling), + render_with_attributes(render_with_attributes), + constraint(constraint), + image(image) {} + + const DlRect src; + const DlRect dst; + const DlImageSampling sampling; + const bool render_with_attributes; + const DlSrcRectConstraint constraint; + const sk_sp image; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawImageRect(image, src, dst, sampling, render_with_attributes, + constraint); + } + + DisplayListCompare equals(const DrawImageRectOp* other) const { + return (src == other->src && dst == other->dst && + sampling == other->sampling && + render_with_attributes == other->render_with_attributes && + constraint == other->constraint && image->Equals(other->image)) + ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; + +// 4 byte header + 44 byte payload packs efficiently into 48 bytes +#define DEFINE_DRAW_IMAGE_NINE_OP(name, render_with_attributes) \ + struct name##Op final : DrawOpBase { \ + static constexpr auto kType = DisplayListOpType::k##name; \ + static constexpr uint32_t kDepthInc = 9; \ + \ + name##Op(const sk_sp& image, \ + const DlIRect& center, \ + const DlRect& dst, \ + DlFilterMode mode) \ + : DrawOpBase(kType), \ + center(center), \ + dst(dst), \ + mode(mode), \ + image(std::move(image)) {} \ + \ + const DlIRect center; \ + const DlRect dst; \ + const DlFilterMode mode; \ + const sk_sp image; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.drawImageNine(image, center, dst, mode, \ + render_with_attributes); \ + } \ + \ + DisplayListCompare equals(const name##Op* other) const { \ + return (center == other->center && dst == other->dst && \ + mode == other->mode && image->Equals(other->image)) \ + ? DisplayListCompare::kEqual \ + : DisplayListCompare::kNotEqual; \ + } \ + }; +DEFINE_DRAW_IMAGE_NINE_OP(DrawImageNine, false) +DEFINE_DRAW_IMAGE_NINE_OP(DrawImageNineWithAttr, true) +#undef DEFINE_DRAW_IMAGE_NINE_OP + +// 4 byte header + 40 byte payload uses 44 bytes but is rounded up to 48 bytes +// (4 bytes unused) +// Each of these is then followed by a number of lists. +// DlRSTransform list is a multiple of 16 bytes so it is always packed well +// DlRect list is also a multiple of 16 bytes so it also packs well +// DlColor list only packs well if the count is even, otherwise there +// can be 4 unusued bytes at the end. +struct DrawAtlasBaseOp : DrawOpBase { + DrawAtlasBaseOp(DisplayListOpType type, + const sk_sp& atlas, + int count, + DlBlendMode mode, + DlImageSampling sampling, + bool has_colors, + bool render_with_attributes) + : DrawOpBase(type), + count(count), + mode_index(static_cast(mode)), + has_colors(has_colors), + render_with_attributes(render_with_attributes), + sampling(sampling), + atlas(atlas) {} + + const int count; + const uint16_t mode_index; + const uint8_t has_colors; + const uint8_t render_with_attributes; + const DlImageSampling sampling; + const sk_sp atlas; + + bool equals(const DrawAtlasBaseOp* other, + const void* pod_this, + const void* pod_other) const { + bool ret = (count == other->count && mode_index == other->mode_index && + has_colors == other->has_colors && + render_with_attributes == other->render_with_attributes && + sampling == other->sampling && atlas->Equals(other->atlas)); + if (ret) { + size_t bytes = count * (sizeof(DlRSTransform) + sizeof(DlRect)); + if (has_colors) { + bytes += count * sizeof(DlColor); + } + ret = (memcmp(pod_this, pod_other, bytes) == 0); + } + return ret; + } +}; + +// Packs into 48 bytes as per DrawAtlasBaseOp +// with array data following the struct also as per DrawAtlasBaseOp +struct DrawAtlasOp final : DrawAtlasBaseOp { + static constexpr auto kType = DisplayListOpType::kDrawAtlas; + + DrawAtlasOp(const sk_sp& atlas, + int count, + DlBlendMode mode, + DlImageSampling sampling, + bool has_colors, + bool render_with_attributes) + : DrawAtlasBaseOp(kType, + atlas, + count, + mode, + sampling, + has_colors, + render_with_attributes) {} + + void dispatch(DlOpReceiver& receiver) const { + const DlRSTransform* xform = + reinterpret_cast(this + 1); + const DlRect* tex = reinterpret_cast(xform + count); + const DlColor* colors = + has_colors ? reinterpret_cast(tex + count) : nullptr; + const DlBlendMode mode = static_cast(mode_index); + receiver.drawAtlas(atlas, xform, tex, colors, count, mode, sampling, + nullptr, render_with_attributes); + } + + DisplayListCompare equals(const DrawAtlasOp* other) const { + const void* pod_this = reinterpret_cast(this + 1); + const void* pod_other = reinterpret_cast(other + 1); + return (DrawAtlasBaseOp::equals(other, pod_this, pod_other)) + ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; + +// Packs into 48 bytes as per DrawAtlasBaseOp plus +// an additional 16 bytes for the cull rect resulting in a total +// of 56 bytes for the Culled drawAtlas. +// Also with array data following the struct as per DrawAtlasBaseOp +struct DrawAtlasCulledOp final : DrawAtlasBaseOp { + static constexpr auto kType = DisplayListOpType::kDrawAtlasCulled; + + DrawAtlasCulledOp(const sk_sp& atlas, + int count, + DlBlendMode mode, + DlImageSampling sampling, + bool has_colors, + const DlRect& cull_rect, + bool render_with_attributes) + : DrawAtlasBaseOp(kType, + atlas, + count, + mode, + sampling, + has_colors, + render_with_attributes), + cull_rect(cull_rect) {} + + const DlRect cull_rect; + + void dispatch(DlOpReceiver& receiver) const { + const DlRSTransform* xform = + reinterpret_cast(this + 1); + const DlRect* tex = reinterpret_cast(xform + count); + const DlColor* colors = + has_colors ? reinterpret_cast(tex + count) : nullptr; + const DlBlendMode mode = static_cast(mode_index); + receiver.drawAtlas(atlas, xform, tex, colors, count, mode, sampling, + &cull_rect, render_with_attributes); + } + + DisplayListCompare equals(const DrawAtlasCulledOp* other) const { + const void* pod_this = reinterpret_cast(this + 1); + const void* pod_other = reinterpret_cast(other + 1); + return (cull_rect == other->cull_rect && + DrawAtlasBaseOp::equals(other, pod_this, pod_other)) + ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; + +// 4 byte header + ptr aligned payload uses 12 bytes round up to 16 +// (4 bytes unused) +struct DrawDisplayListOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawDisplayList; + + explicit DrawDisplayListOp(const sk_sp& display_list, + DlScalar opacity) + : DrawOpBase(kType), opacity(opacity), display_list(display_list) {} + + DlScalar opacity; + const sk_sp display_list; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawDisplayList(display_list, opacity); + } + + DisplayListCompare equals(const DrawDisplayListOp* other) const { + return (opacity == other->opacity && + display_list->Equals(other->display_list)) + ? DisplayListCompare::kEqual + : DisplayListCompare::kNotEqual; + } +}; + +// 4 byte header + 8 payload bytes + an aligned pointer take 24 bytes +// (4 unused to align the pointer) +struct DrawTextBlobOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawTextBlob; + + DrawTextBlobOp(const sk_sp& blob, DlScalar x, DlScalar y) + : DrawOpBase(kType), x(x), y(y), blob(blob) {} + + const DlScalar x; + const DlScalar y; + const sk_sp blob; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawTextBlob(blob, x, y); + } +}; + +struct DrawTextFrameOp final : DrawOpBase { + static constexpr auto kType = DisplayListOpType::kDrawTextFrame; + + DrawTextFrameOp(const std::shared_ptr& text_frame, + DlScalar x, + DlScalar y) + : DrawOpBase(kType), x(x), y(y), text_frame(text_frame) {} + + const DlScalar x; + const DlScalar y; + const std::shared_ptr text_frame; + + void dispatch(DlOpReceiver& receiver) const { + receiver.drawTextFrame(text_frame, x, y); + } +}; + +// 4 byte header + 44 byte payload packs evenly into 48 bytes +#define DEFINE_DRAW_SHADOW_OP(name, transparent_occluder) \ + struct Draw##name##Op final : DrawOpBase { \ + static constexpr auto kType = DisplayListOpType::kDraw##name; \ + \ + Draw##name##Op(const DlPath& path, \ + DlColor color, \ + DlScalar elevation, \ + DlScalar dpr) \ + : DrawOpBase(kType), \ + color(color), \ + elevation(elevation), \ + dpr(dpr), \ + path(path) {} \ + \ + const DlColor color; \ + const DlScalar elevation; \ + const DlScalar dpr; \ + const DlPath path; \ + \ + void dispatch(DlOpReceiver& receiver) const { \ + receiver.drawShadow(path, color, elevation, transparent_occluder, dpr); \ + } \ + \ + DisplayListCompare equals(const Draw##name##Op* other) const { \ + return color == other->color && elevation == other->elevation && \ + dpr == other->dpr && path == other->path \ + ? DisplayListCompare::kEqual \ + : DisplayListCompare::kNotEqual; \ + } \ + }; +DEFINE_DRAW_SHADOW_OP(Shadow, false) +DEFINE_DRAW_SHADOW_OP(ShadowTransparentOccluder, true) +#undef DEFINE_DRAW_SHADOW_OP + +#pragma pack(pop, DLOpPackLabel) + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_OP_RECORDS_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_paint.cc b/flutter/engine/src/flutter/display_list/dl_paint.cc new file mode 100644 index 0000000000000000000000000000000000000000..76a682eab99673edc9403a73c1f9b1b4cd52e2a8 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_paint.cc @@ -0,0 +1,40 @@ +// 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_paint.h" + +#include "flutter/display_list/utils/dl_comparable.h" + +namespace flutter { + +DlPaint::DlPaint(DlColor color) + : blend_mode_(static_cast(DlBlendMode::kDefaultMode)), + draw_style_(static_cast(DlDrawStyle::kDefaultStyle)), + stroke_cap_(static_cast(DlStrokeCap::kDefaultCap)), + stroke_join_(static_cast(DlStrokeJoin::kDefaultJoin)), + is_anti_alias_(false), + is_invert_colors_(false), + color_(color), + stroke_width_(kDefaultWidth), + stroke_miter_(kDefaultMiter) {} + +bool DlPaint::operator==(DlPaint const& other) const { + return blend_mode_ == other.blend_mode_ && // + draw_style_ == other.draw_style_ && // + stroke_cap_ == other.stroke_cap_ && // + stroke_join_ == other.stroke_join_ && // + is_anti_alias_ == other.is_anti_alias_ && // + is_invert_colors_ == other.is_invert_colors_ && // + color_ == other.color_ && // + stroke_width_ == other.stroke_width_ && // + stroke_miter_ == other.stroke_miter_ && // + Equals(color_source_, other.color_source_) && // + Equals(color_filter_, other.color_filter_) && // + Equals(image_filter_, other.image_filter_) && // + Equals(mask_filter_, other.mask_filter_); +} + +const DlPaint DlPaint::kDefault; + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_paint.h b/flutter/engine/src/flutter/display_list/dl_paint.h new file mode 100644 index 0000000000000000000000000000000000000000..57876283766f7934f76c6b9f48b139c3eacb6136 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_paint.h @@ -0,0 +1,225 @@ +// 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_PAINT_H_ +#define FLUTTER_DISPLAY_LIST_DL_PAINT_H_ + +#include +#include +#include "flutter/display_list/dl_blend_mode.h" +#include "flutter/display_list/dl_color.h" +#include "flutter/display_list/effects/dl_color_filter.h" +#include "flutter/display_list/effects/dl_color_source.h" +#include "flutter/display_list/effects/dl_image_filter.h" +#include "flutter/display_list/effects/dl_mask_filter.h" + +namespace flutter { + +enum class DlDrawStyle { + kFill, //!< fills interior of shapes + kStroke, //!< strokes boundary of shapes + kStrokeAndFill, //!< both strokes and fills shapes + + kLastStyle = kStrokeAndFill, + kDefaultStyle = kFill, +}; + +enum class DlStrokeCap { + kButt, //!< no stroke extension + kRound, //!< adds circle + kSquare, //!< adds square + + kLastCap = kSquare, + kDefaultCap = kButt, +}; + +enum class DlStrokeJoin { + kMiter, //!< extends to miter limit + kRound, //!< adds circle + kBevel, //!< connects outside edges + + kLastJoin = kBevel, + kDefaultJoin = kMiter, +}; + +class DlPaint { + public: + static constexpr DlColor kDefaultColor = DlColor::kBlack(); + static constexpr float kDefaultWidth = 0.0; + static constexpr float kDefaultMiter = 4.0; + + static const DlPaint kDefault; + + DlPaint() : DlPaint(DlColor::kBlack()) {} + explicit DlPaint(DlColor color); + + bool isAntiAlias() const { return is_anti_alias_; } + DlPaint& setAntiAlias(bool isAntiAlias) { + is_anti_alias_ = isAntiAlias; + return *this; + } + + bool isInvertColors() const { return is_invert_colors_; } + DlPaint& setInvertColors(bool isInvertColors) { + is_invert_colors_ = isInvertColors; + return *this; + } + + DlColor getColor() const { return color_; } + DlPaint& setColor(DlColor color) { + color_ = color; + return *this; + } + + uint8_t getAlpha() const { return color_.argb() >> 24; } + DlPaint& setAlpha(uint8_t alpha) { return setColor(color_.withAlpha(alpha)); } + DlScalar getOpacity() const { return color_.getAlphaF(); } + DlPaint& setOpacity(DlScalar opacity) { + return setAlpha(DlColor::toAlpha(opacity)); + } + + DlBlendMode getBlendMode() const { + return static_cast(blend_mode_); + } + DlPaint& setBlendMode(DlBlendMode mode) { + blend_mode_ = static_cast(mode); + return *this; + } + + DlDrawStyle getDrawStyle() const { + return static_cast(draw_style_); + } + DlPaint& setDrawStyle(DlDrawStyle style) { + draw_style_ = static_cast(style); + return *this; + } + + DlStrokeCap getStrokeCap() const { + return static_cast(stroke_cap_); + } + DlPaint& setStrokeCap(DlStrokeCap cap) { + stroke_cap_ = static_cast(cap); + return *this; + } + + DlStrokeJoin getStrokeJoin() const { + return static_cast(stroke_join_); + } + DlPaint& setStrokeJoin(DlStrokeJoin join) { + stroke_join_ = static_cast(join); + return *this; + } + + float getStrokeWidth() const { return stroke_width_; } + DlPaint& setStrokeWidth(float width) { + stroke_width_ = width; + return *this; + } + + float getStrokeMiter() const { return stroke_miter_; } + DlPaint& setStrokeMiter(float miter) { + stroke_miter_ = miter; + return *this; + } + + std::shared_ptr getColorSource() const { + return color_source_; + } + const DlColorSource* getColorSourcePtr() const { return color_source_.get(); } + DlPaint& setColorSource(std::shared_ptr source) { + color_source_ = std::move(source); + return *this; + } + DlPaint& setColorSource(const DlColorSource* source) { + color_source_ = source ? source->shared() : nullptr; + return *this; + } + + std::shared_ptr getColorFilter() const { + return color_filter_; + } + const DlColorFilter* getColorFilterPtr() const { return color_filter_.get(); } + DlPaint& setColorFilter(const std::shared_ptr& filter) { + color_filter_ = filter; + return *this; + } + DlPaint& setColorFilter(const DlColorFilter* filter) { + color_filter_ = filter ? filter->shared() : nullptr; + return *this; + } + + std::shared_ptr getImageFilter() const { + return image_filter_; + } + const DlImageFilter* getImageFilterPtr() const { return image_filter_.get(); } + DlPaint& setImageFilter(const std::shared_ptr& filter) { + image_filter_ = filter; + return *this; + } + DlPaint& setImageFilter(const DlImageFilter* filter) { + image_filter_ = filter ? filter->shared() : nullptr; + return *this; + } + + std::shared_ptr getMaskFilter() const { + return mask_filter_; + } + const DlMaskFilter* getMaskFilterPtr() const { return mask_filter_.get(); } + DlPaint& setMaskFilter(const std::shared_ptr& filter) { + mask_filter_ = filter; + return *this; + } + DlPaint& setMaskFilter(const DlMaskFilter* filter) { + mask_filter_ = filter ? filter->shared() : nullptr; + return *this; + } + + bool isDefault() const { return *this == kDefault; } + + bool usesRuntimeEffect() const { + return ((color_source_ && color_source_->asRuntimeEffect()) || + (image_filter_ && image_filter_->asRuntimeEffectFilter())); + } + + bool operator==(DlPaint const& other) const; + bool operator!=(DlPaint const& other) const { return !(*this == other); } + + private: +#define ASSERT_ENUM_FITS(last_enum, num_bits) \ + static_assert(static_cast(last_enum) < (1 << num_bits) && \ + static_cast(last_enum) * 2 >= (1 << num_bits)) + + static constexpr int kBlendModeBits = 5; + static constexpr int kDrawStyleBits = 2; + static constexpr int kStrokeCapBits = 2; + static constexpr int kStrokeJoinBits = 2; + ASSERT_ENUM_FITS(DlBlendMode::kLastMode, kBlendModeBits); + ASSERT_ENUM_FITS(DlDrawStyle::kLastStyle, kDrawStyleBits); + ASSERT_ENUM_FITS(DlStrokeCap::kLastCap, kStrokeCapBits); + ASSERT_ENUM_FITS(DlStrokeJoin::kLastJoin, kStrokeJoinBits); + + union { + struct { + unsigned blend_mode_ : kBlendModeBits; + unsigned draw_style_ : kDrawStyleBits; + unsigned stroke_cap_ : kStrokeCapBits; + unsigned stroke_join_ : kStrokeJoinBits; + unsigned is_anti_alias_ : 1; + unsigned is_invert_colors_ : 1; + }; + }; + + DlColor color_; + float stroke_width_; + float stroke_miter_; + + std::shared_ptr color_source_; + std::shared_ptr color_filter_; + std::shared_ptr image_filter_; + std::shared_ptr mask_filter_; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_PAINT_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_paint_unittests.cc b/flutter/engine/src/flutter/display_list/dl_paint_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..02465892a11699cf1b183bdf375b12c5bfd345be --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_paint_unittests.cc @@ -0,0 +1,199 @@ +// 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_paint.h" + +#include "flutter/display_list/testing/dl_test_equality.h" +#include "flutter/display_list/testing/dl_test_snippets.h" +#include "flutter/display_list/utils/dl_comparable.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(DisplayListPaint, ConstructorDefaults) { + DlPaint paint; + EXPECT_FALSE(paint.isAntiAlias()); + EXPECT_FALSE(paint.isInvertColors()); + EXPECT_EQ(paint.getColor(), DlPaint::kDefaultColor); + EXPECT_EQ(paint.getAlpha(), 0xFF); + EXPECT_EQ(paint.getBlendMode(), DlBlendMode::kDefaultMode); + EXPECT_EQ(paint.getDrawStyle(), DlDrawStyle::kDefaultStyle); + EXPECT_EQ(paint.getStrokeCap(), DlStrokeCap::kDefaultCap); + EXPECT_EQ(paint.getStrokeJoin(), DlStrokeJoin::kDefaultJoin); + EXPECT_EQ(paint.getStrokeWidth(), DlPaint::kDefaultWidth); + EXPECT_EQ(paint.getStrokeMiter(), DlPaint::kDefaultMiter); + EXPECT_EQ(paint.getColorSource(), nullptr); + EXPECT_EQ(paint.getColorFilter(), nullptr); + EXPECT_EQ(paint.getImageFilter(), nullptr); + EXPECT_EQ(paint.getMaskFilter(), nullptr); + EXPECT_TRUE(paint.isDefault()); + EXPECT_EQ(paint, DlPaint::kDefault); + + EXPECT_EQ(DlBlendMode::kDefaultMode, DlBlendMode::kSrcOver); + EXPECT_EQ(DlDrawStyle::kDefaultStyle, DlDrawStyle::kFill); + EXPECT_EQ(DlStrokeCap::kDefaultCap, DlStrokeCap::kButt); + EXPECT_EQ(DlStrokeJoin::kDefaultJoin, DlStrokeJoin::kMiter); + + EXPECT_EQ(DlPaint::kDefaultColor, DlColor::kBlack()); + EXPECT_EQ(DlPaint::kDefaultWidth, 0.0); + EXPECT_EQ(DlPaint::kDefaultMiter, 4.0); + + EXPECT_EQ(paint, DlPaint()); + EXPECT_EQ(paint, DlPaint(DlColor::kBlack())); + EXPECT_EQ(paint, DlPaint(DlColor(0xFF000000))); + + EXPECT_NE(paint, DlPaint().setAntiAlias(true)); + EXPECT_NE(paint, DlPaint().setInvertColors(true)); + EXPECT_NE(paint, DlPaint().setColor(DlColor::kGreen())); + EXPECT_NE(paint, DlPaint(DlColor::kGreen())); + EXPECT_NE(paint, DlPaint(DlColor(0xFF00FF00))); + EXPECT_NE(paint, DlPaint().setAlpha(0x7f)); + EXPECT_NE(paint, DlPaint().setBlendMode(DlBlendMode::kDstIn)); + EXPECT_NE(paint, DlPaint().setDrawStyle(DlDrawStyle::kStrokeAndFill)); + EXPECT_NE(paint, DlPaint().setStrokeCap(DlStrokeCap::kRound)); + EXPECT_NE(paint, DlPaint().setStrokeJoin(DlStrokeJoin::kRound)); + EXPECT_NE(paint, DlPaint().setStrokeWidth(6)); + EXPECT_NE(paint, DlPaint().setStrokeMiter(7)); + + DlColor colors[2] = { + DlColor::kGreen(), + DlColor::kBlue(), + }; + float stops[2] = { + 0.0f, + 1.0f, + }; + auto color_source = DlColorSource::MakeLinear({0, 0}, {10, 10}, 2, colors, + stops, DlTileMode::kClamp); + EXPECT_NE(paint, DlPaint().setColorSource(color_source)); + + auto color_filter = + DlColorFilter::MakeBlend(DlColor::kYellow(), DlBlendMode::kDstATop); + EXPECT_NE(paint, DlPaint().setColorFilter(color_filter)); + + auto image_filter = DlImageFilter::MakeBlur(1.3, 4.7, DlTileMode::kClamp); + EXPECT_NE(paint, DlPaint().setImageFilter(image_filter)); + + DlBlurMaskFilter mask_filter(DlBlurStyle::kInner, 3.14); + EXPECT_NE(paint, DlPaint().setMaskFilter(mask_filter.shared())); +} + +TEST(DisplayListPaint, NullPointerSetGet) { + DlColorSource* null_color_source = nullptr; + DlColorFilter* null_color_filter = nullptr; + DlImageFilter* null_image_filter = nullptr; + DlMaskFilter* null_mask_filter = nullptr; + DlPaint paint; + EXPECT_EQ(paint.setColorSource(null_color_source).getColorSource(), nullptr); + EXPECT_EQ(paint.setColorFilter(null_color_filter).getColorFilter(), nullptr); + EXPECT_EQ(paint.setImageFilter(null_image_filter).getImageFilter(), nullptr); + EXPECT_EQ(paint.setMaskFilter(null_mask_filter).getMaskFilter(), nullptr); +} + +TEST(DisplayListPaint, NullSharedPointerSetGet) { + std::shared_ptr null_color_source; + std::shared_ptr null_color_filter; + std::shared_ptr null_image_filter; + std::shared_ptr null_mask_filter; + DlPaint paint; + EXPECT_EQ(paint.setColorSource(null_color_source).getColorSource(), nullptr); + EXPECT_EQ(paint.setColorFilter(null_color_filter).getColorFilter(), nullptr); + EXPECT_EQ(paint.setImageFilter(null_image_filter).getImageFilter(), nullptr); + EXPECT_EQ(paint.setMaskFilter(null_mask_filter).getMaskFilter(), nullptr); +} + +TEST(DisplayListPaint, ChainingConstructor) { + DlColor colors[2] = { + DlColor::kGreen(), + DlColor::kBlue(), + }; + float stops[2] = { + 0.0f, + 1.0f, + }; + DlPaint paint = + DlPaint() // + .setAntiAlias(true) // + .setInvertColors(true) // + .setColor(DlColor::kGreen()) // + .setAlpha(0x7F) // + .setBlendMode(DlBlendMode::kLuminosity) // + .setDrawStyle(DlDrawStyle::kStrokeAndFill) // + .setStrokeCap(DlStrokeCap::kSquare) // + .setStrokeJoin(DlStrokeJoin::kBevel) // + .setStrokeWidth(42) // + .setStrokeMiter(1.5) // + .setColorSource(DlColorSource::MakeLinear( // + {0, 0}, {10, 10}, 2, colors, stops, DlTileMode::kClamp)) // + .setColorFilter( + DlColorFilter::MakeBlend(DlColor::kYellow(), DlBlendMode::kDstIn)) + .setImageFilter(DlImageFilter::MakeBlur(1.3, 4.7, DlTileMode::kClamp)) + .setMaskFilter(DlBlurMaskFilter(DlBlurStyle::kInner, 3.14).shared()); + EXPECT_TRUE(paint.isAntiAlias()); + EXPECT_TRUE(paint.isInvertColors()); + EXPECT_EQ(paint.getColor(), DlColor::kGreen().withAlpha(0x7F)); + EXPECT_EQ(paint.getAlpha(), 0x7F); + EXPECT_EQ(paint.getBlendMode(), DlBlendMode::kLuminosity); + EXPECT_EQ(paint.getDrawStyle(), DlDrawStyle::kStrokeAndFill); + EXPECT_EQ(paint.getStrokeCap(), DlStrokeCap::kSquare); + EXPECT_EQ(paint.getStrokeJoin(), DlStrokeJoin::kBevel); + EXPECT_EQ(paint.getStrokeWidth(), 42); + EXPECT_EQ(paint.getStrokeMiter(), 1.5); + EXPECT_TRUE(Equals(paint.getColorSource(), + DlColorSource::MakeLinear({0, 0}, {10, 10}, 2, colors, + stops, DlTileMode::kClamp))); + EXPECT_TRUE(Equals( + paint.getColorFilter(), + DlColorFilter::MakeBlend(DlColor::kYellow(), DlBlendMode::kDstIn))); + EXPECT_TRUE(Equals(paint.getImageFilter(), + DlImageFilter::MakeBlur(1.3, 4.7, DlTileMode::kClamp))); + EXPECT_EQ(*paint.getMaskFilter(), + DlBlurMaskFilter(DlBlurStyle::kInner, 3.14)); + + EXPECT_NE(paint, DlPaint()); +} + +TEST(DisplayListPaint, PaintDetectsRuntimeEffects) { + auto color_source = DlColorSource::MakeRuntimeEffect( + kTestRuntimeEffect1, {}, std::make_shared>()); + auto image_filter = DlImageFilter::MakeRuntimeEffect( + kTestRuntimeEffect1, {}, std::make_shared>()); + DlPaint paint; + + EXPECT_FALSE(paint.usesRuntimeEffect()); + paint.setColorSource(color_source); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setColorSource(nullptr); + EXPECT_FALSE(paint.usesRuntimeEffect()); + + EXPECT_FALSE(paint.usesRuntimeEffect()); + paint.setImageFilter(image_filter); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setImageFilter(nullptr); + EXPECT_FALSE(paint.usesRuntimeEffect()); + + EXPECT_FALSE(paint.usesRuntimeEffect()); + paint.setColorSource(color_source); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setImageFilter(image_filter); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setImageFilter(nullptr); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setColorSource(nullptr); + EXPECT_FALSE(paint.usesRuntimeEffect()); + + EXPECT_FALSE(paint.usesRuntimeEffect()); + paint.setColorSource(color_source); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setImageFilter(image_filter); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setColorSource(nullptr); + EXPECT_TRUE(paint.usesRuntimeEffect()); + paint.setImageFilter(nullptr); + EXPECT_FALSE(paint.usesRuntimeEffect()); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_sampling_options.h b/flutter/engine/src/flutter/display_list/dl_sampling_options.h new file mode 100644 index 0000000000000000000000000000000000000000..3563cf000ae3b6cd885bc0dd080fc860af55872b --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_sampling_options.h @@ -0,0 +1,26 @@ +// 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_SAMPLING_OPTIONS_H_ +#define FLUTTER_DISPLAY_LIST_DL_SAMPLING_OPTIONS_H_ + +namespace flutter { + +enum class DlFilterMode { + kNearest, // single sample point (nearest neighbor) + kLinear, // interporate between 2x2 sample points (bilinear interpolation) + + kLast = kLinear, +}; + +enum class DlImageSampling { + kNearestNeighbor, + kLinear, + kMipmapLinear, + kCubic, +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_SAMPLING_OPTIONS_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_storage.cc b/flutter/engine/src/flutter/display_list/dl_storage.cc new file mode 100644 index 0000000000000000000000000000000000000000..9a36d461980f0e3bf23fa91e4f8380f7c8546479 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_storage.cc @@ -0,0 +1,62 @@ +// 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_storage.h" + +namespace flutter { + +static constexpr inline bool is_power_of_two(int value) { + return (value & (value - 1)) == 0; +} + +void DisplayListStorage::realloc(size_t count) { + ptr_.reset(static_cast(std::realloc(ptr_.release(), count))); + FML_CHECK(ptr_); + allocated_ = count; +} + +uint8_t* DisplayListStorage::allocate(size_t needed) { + if (used_ + needed > allocated_) { + static_assert(is_power_of_two(kDLPageSize), + "This math needs updating for non-pow2."); + // Next greater multiple of DL_BUILDER_PAGE. + size_t new_size = (used_ + needed + kDLPageSize) & ~(kDLPageSize - 1); + size_t old_size = allocated_; + realloc(new_size); + FML_CHECK(ptr_.get()); + FML_CHECK(allocated_ == new_size); + FML_CHECK(allocated_ >= old_size); + FML_CHECK(used_ + needed <= allocated_); + memset(ptr_.get() + used_, 0, allocated_ - old_size); + } + uint8_t* ret = ptr_.get() + used_; + used_ += needed; + FML_CHECK(used_ <= allocated_); + return ret; +} + +DisplayListStorage::DisplayListStorage(DisplayListStorage&& source) { + ptr_ = std::move(source.ptr_); + used_ = source.used_; + allocated_ = source.allocated_; + source.used_ = 0u; + source.allocated_ = 0u; +} + +void DisplayListStorage::reset() { + ptr_.reset(); + used_ = 0u; + allocated_ = 0u; +} + +DisplayListStorage& DisplayListStorage::operator=(DisplayListStorage&& source) { + ptr_ = std::move(source.ptr_); + used_ = source.used_; + allocated_ = source.allocated_; + source.used_ = 0u; + source.allocated_ = 0u; + return *this; +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_storage.h b/flutter/engine/src/flutter/display_list/dl_storage.h new file mode 100644 index 0000000000000000000000000000000000000000..89108d75b5fa2c5cc76722c14a11e149012811c3 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_storage.h @@ -0,0 +1,60 @@ +// 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_STORAGE_H_ +#define FLUTTER_DISPLAY_LIST_DL_STORAGE_H_ + +#include + +#include "flutter/fml/logging.h" + +namespace flutter { + +// Manages a buffer allocated with malloc. +class DisplayListStorage { + public: + static const constexpr size_t kDLPageSize = 4096u; + + DisplayListStorage() = default; + DisplayListStorage(DisplayListStorage&&); + + /// Returns a pointer to the base of the storage. + uint8_t* base() { return ptr_.get(); } + const uint8_t* base() const { return ptr_.get(); } + + /// Returns the currently allocated size + size_t size() const { return used_; } + + /// Returns the maximum currently allocated space + size_t capacity() const { return allocated_; } + + /// Ensures the indicated number of bytes are available and returns + /// a pointer to that memory within the storage while also invalidating + /// any other outstanding pointers into the storage. + uint8_t* allocate(size_t needed); + + /// Trims the storage to the currently allocated size and invalidates + /// any outstanding pointers into the storage. + void trim() { realloc(used_); } + + /// Resets the storage and allocation of the object to an empty state + void reset(); + + DisplayListStorage& operator=(DisplayListStorage&& other); + + private: + void realloc(size_t count); + + struct FreeDeleter { + void operator()(uint8_t* p) { std::free(p); } + }; + std::unique_ptr ptr_; + + size_t used_ = 0u; + size_t allocated_ = 0u; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_STORAGE_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_storage_unittests.cc b/flutter/engine/src/flutter/display_list/dl_storage_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..78d6dcef0cbc4b916bce21674d5cd31789e6c6ff --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_storage_unittests.cc @@ -0,0 +1,47 @@ +// 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_storage.h" + +#include "flutter/testing/testing.h" + +namespace flutter { +namespace testing { + +TEST(DisplayListStorage, DefaultConstructed) { + DisplayListStorage storage; + EXPECT_EQ(storage.base(), nullptr); + EXPECT_EQ(storage.size(), 0u); + EXPECT_EQ(storage.capacity(), 0u); +} + +TEST(DisplayListStorage, Allocation) { + DisplayListStorage storage; + EXPECT_NE(storage.allocate(10u), nullptr); + EXPECT_NE(storage.base(), nullptr); + EXPECT_EQ(storage.size(), 10u); + EXPECT_EQ(storage.capacity(), DisplayListStorage::kDLPageSize); +} + +TEST(DisplayListStorage, PostMove) { + DisplayListStorage original; + EXPECT_NE(original.allocate(10u), nullptr); + + DisplayListStorage moved = std::move(original); + + // NOLINTBEGIN(bugprone-use-after-move) + // NOLINTBEGIN(clang-analyzer-cplusplus.Move) + EXPECT_EQ(original.base(), nullptr); + EXPECT_EQ(original.size(), 0u); + EXPECT_EQ(original.capacity(), 0u); + // NOLINTEND(clang-analyzer-cplusplus.Move) + // NOLINTEND(bugprone-use-after-move) + + EXPECT_NE(moved.base(), nullptr); + EXPECT_EQ(moved.size(), 10u); + EXPECT_EQ(moved.capacity(), DisplayListStorage::kDLPageSize); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_tile_mode.h b/flutter/engine/src/flutter/display_list/dl_tile_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..60132e8b317ae9ddb1a530f188bc2ac1a68f2f0d --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_tile_mode.h @@ -0,0 +1,33 @@ +// 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_TILE_MODE_H_ +#define FLUTTER_DISPLAY_LIST_DL_TILE_MODE_H_ + +namespace flutter { + +// An enum to define how to repeat, fold, or omit colors outside of the +// typically defined range of the source of the colors (such as the +// bounds of an image or the defining geoetry of a gradient). +enum class DlTileMode { + // Replicate the edge color if the |DlColorSource| draws outside of the + // defined bounds. + kClamp, + + // Repeat the |DlColorSource|'s defined colors both horizontally and + // vertically (or both along and perpendicular to a gradient's geometry). + kRepeat, + + // Repeat the |DlColorSource|'s colors horizontally and vertically, + // alternating mirror images so that adjacent images always seam. + kMirror, + + // Only draw within the original domain, return transparent-black everywhere + // else. + kDecal, +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_TILE_MODE_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_types.cc b/flutter/engine/src/flutter/display_list/dl_types.cc new file mode 100644 index 0000000000000000000000000000000000000000..b15e264017c4f21790ae14f7b0ed53236c634d9f --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_types.cc @@ -0,0 +1,11 @@ +// 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_types.h" + +namespace flutter { + +// Only exists to verify that the types can be cleanly included. + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_types.h b/flutter/engine/src/flutter/display_list/dl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..3298c30ac314b08cef1bf20a68195256783babe1 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_types.h @@ -0,0 +1,28 @@ +// 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_TYPES_H_ +#define FLUTTER_DISPLAY_LIST_DL_TYPES_H_ + +namespace flutter { + +enum class DlClipOp { + kDifference, + kIntersect, +}; + +enum class DlPointMode { + kPoints, //!< draw each point separately + kLines, //!< draw each separate pair of points as a line segment + kPolygon, //!< draw each pair of overlapping points as a line segment +}; + +enum class DlSrcRectConstraint { + kStrict, + kFast, +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_TYPES_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_vertices.cc b/flutter/engine/src/flutter/display_list/dl_vertices.cc new file mode 100644 index 0000000000000000000000000000000000000000..a55c9f7d9965f3c22b62860aafddb7ff2dbc44c3 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_vertices.cc @@ -0,0 +1,322 @@ +// 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_vertices.h" + +#include "flutter/display_list/utils/dl_accumulation_rect.h" +#include "flutter/fml/logging.h" + +namespace flutter { + +using Flags = DlVertices::Builder::Flags; + +static void DlVerticesDeleter(void* p) { + // Some of our target environments would prefer a sized delete, + // but other target environments do not have that operator. + // Use an unsized delete until we get better agreement in the + // environments. + // See https://github.com/flutter/flutter/issues/100327 + ::operator delete(p); +} + +static size_t bytes_needed(int vertex_count, Flags flags, int index_count) { + int needed = sizeof(DlVertices); + // We always have vertices + needed += vertex_count * sizeof(DlPoint); + if (flags.has_texture_coordinates) { + needed += vertex_count * sizeof(DlPoint); + } + if (flags.has_colors) { + needed += vertex_count * sizeof(DlColor); + } + if (index_count > 0) { + needed += index_count * sizeof(uint16_t); + } + return needed; +} + +std::shared_ptr DlVertices::Make( + DlVertexMode mode, + int vertex_count, + const DlPoint vertices[], + const DlPoint texture_coordinates[], + const DlColor colors[], + int index_count, + const uint16_t indices[], + const DlRect* bounds) { + if (!vertices || vertex_count <= 0) { + vertex_count = 0; + texture_coordinates = nullptr; + colors = nullptr; + } + if (!indices || index_count <= 0) { + index_count = 0; + indices = nullptr; + } + + Flags flags; + FML_DCHECK(!flags.has_texture_coordinates); + FML_DCHECK(!flags.has_colors); + if (texture_coordinates) { + flags |= Builder::kHasTextureCoordinates; + } + if (colors) { + flags |= Builder::kHasColors; + } + Builder builder(mode, vertex_count, flags, index_count); + + builder.store_vertices(vertices); + if (texture_coordinates) { + builder.store_texture_coordinates(texture_coordinates); + } + if (colors) { + builder.store_colors(colors); + } + if (indices) { + builder.store_indices(indices); + } + if (bounds != nullptr) { + builder.store_bounds(*bounds); + } + + return builder.build(); +} + +size_t DlVertices::size() const { + return bytes_needed(vertex_count_, + {{texture_coordinates_offset_ > 0, colors_offset_ > 0}}, + index_count_); +} + +static DlRect compute_bounds(const DlPoint* points, int count) { + AccumulationRect accumulator; + for (int i = 0; i < count; i++) { + accumulator.accumulate(points[i]); + } + return accumulator.GetBounds(); +} + +DlVertices::DlVertices(DlVertexMode mode, + int unchecked_vertex_count, + const DlPoint* vertices, + const DlPoint* texture_coordinates, + const DlColor* colors, + int unchecked_index_count, + const uint16_t* indices, + const DlRect* bounds) + : mode_(mode), + vertex_count_(std::max(unchecked_vertex_count, 0)), + index_count_(indices ? std::max(unchecked_index_count, 0) : 0) { + bounds_ = bounds ? *bounds : compute_bounds(vertices, vertex_count_); + + char* pod = reinterpret_cast(this); + size_t offset = sizeof(DlVertices); + + auto advance = [pod, &offset](auto* src, int count) { + if (src != nullptr && count > 0) { + size_t bytes = count * sizeof(*src); + memcpy(pod + offset, src, bytes); + size_t ret = offset; + offset += bytes; + return ret; + } else { + return static_cast(0); + } + }; + + vertices_offset_ = advance(vertices, vertex_count_); + texture_coordinates_offset_ = advance(texture_coordinates, vertex_count_); + colors_offset_ = advance(colors, vertex_count_); + indices_offset_ = advance(indices, index_count_); + FML_DCHECK(offset == bytes_needed(vertex_count_, + {{!!texture_coordinates, !!colors}}, + index_count_)); +} + +DlVertices::DlVertices(const DlVertices* other) + : DlVertices(other->mode_, + other->vertex_count_, + other->vertex_data(), + other->texture_coordinate_data(), + other->colors(), + other->index_count_, + other->indices(), + &other->bounds_) {} + +DlVertices::DlVertices(DlVertexMode mode, + int unchecked_vertex_count, + Flags flags, + int unchecked_index_count) + : mode_(mode), + vertex_count_(std::max(unchecked_vertex_count, 0)), + index_count_(std::max(unchecked_index_count, 0)) { + char* pod = reinterpret_cast(this); + size_t offset = sizeof(DlVertices); + + auto advance = [pod, &offset](size_t size, int count) { + if (count > 0) { + size_t bytes = count * size; + memset(pod + offset, 0, bytes); + size_t ret = offset; + offset += bytes; + return ret; + } else { + return static_cast(0); + } + }; + + vertices_offset_ = advance(sizeof(DlPoint), vertex_count_); + texture_coordinates_offset_ = advance( + sizeof(DlPoint), flags.has_texture_coordinates ? vertex_count_ : 0); + colors_offset_ = + advance(sizeof(DlColor), flags.has_colors ? vertex_count_ : 0); + indices_offset_ = advance(sizeof(uint16_t), index_count_); + FML_DCHECK(offset == bytes_needed(vertex_count_, flags, index_count_)); + FML_DCHECK((vertex_count_ != 0) == (vertex_data() != nullptr)); + FML_DCHECK((vertex_count_ != 0 && flags.has_texture_coordinates) == + (texture_coordinate_data() != nullptr)); + FML_DCHECK((vertex_count_ != 0 && flags.has_colors) == (colors() != nullptr)); + FML_DCHECK((index_count_ != 0) == (indices() != nullptr)); +} + +bool DlVertices::operator==(DlVertices const& other) const { + auto lists_equal = [](auto* a, auto* b, int count) { + if (a == nullptr || b == nullptr) { + return a == b; + } + for (int i = 0; i < count; i++) { + if (a[i] != b[i]) { + return false; + } + } + return true; + }; + return // + mode_ == other.mode_ && // + vertex_count_ == other.vertex_count_ && // + lists_equal(vertex_data(), other.vertex_data(), vertex_count_) && // + lists_equal(texture_coordinate_data(), // + other.texture_coordinate_data(), // + vertex_count_) && // + lists_equal(colors(), other.colors(), vertex_count_) && // + index_count_ == other.index_count_ && // + lists_equal(indices(), other.indices(), index_count_); +} + +DlVertices::Builder::Builder(DlVertexMode mode, + int vertex_count, + Flags flags, + int index_count) + : needs_texture_coords_(flags.has_texture_coordinates), + needs_colors_(flags.has_colors), + needs_indices_(index_count > 0) { + vertex_count = std::max(vertex_count, 0); + index_count = std::max(index_count, 0); + void* storage = + ::operator new(bytes_needed(vertex_count, flags, index_count)); + vertices_.reset(new (storage) + DlVertices(mode, vertex_count, flags, index_count), + DlVerticesDeleter); +} + +static void store_points(char* dst, int offset, const float* src, int count) { + DlPoint* points = reinterpret_cast(dst + offset); + for (int i = 0; i < count; i++) { + points[i] = DlPoint(src[i * 2], src[i * 2 + 1]); + } +} + +void DlVertices::Builder::store_vertices(const DlPoint vertices[]) { + FML_DCHECK(is_valid()); + FML_DCHECK(needs_vertices_); + char* pod = reinterpret_cast(vertices_.get()); + size_t bytes = vertices_->vertex_count_ * sizeof(vertices[0]); + memcpy(pod + vertices_->vertices_offset_, vertices, bytes); + needs_vertices_ = false; +} + +void DlVertices::Builder::store_vertices(const float vertices[]) { + FML_DCHECK(is_valid()); + FML_DCHECK(needs_vertices_); + char* pod = reinterpret_cast(vertices_.get()); + store_points(pod, vertices_->vertices_offset_, vertices, + vertices_->vertex_count_); + needs_vertices_ = false; +} + +void DlVertices::Builder::store_texture_coordinates(const DlPoint coords[]) { + FML_DCHECK(is_valid()); + FML_DCHECK(needs_texture_coords_); + char* pod = reinterpret_cast(vertices_.get()); + size_t bytes = vertices_->vertex_count_ * sizeof(coords[0]); + memcpy(pod + vertices_->texture_coordinates_offset_, coords, bytes); + needs_texture_coords_ = false; +} + +void DlVertices::Builder::store_texture_coordinates(const float coords[]) { + FML_DCHECK(is_valid()); + FML_DCHECK(needs_texture_coords_); + char* pod = reinterpret_cast(vertices_.get()); + store_points(pod, vertices_->texture_coordinates_offset_, coords, + vertices_->vertex_count_); + needs_texture_coords_ = false; +} + +void DlVertices::Builder::store_colors(const DlColor colors[]) { + FML_DCHECK(is_valid()); + FML_DCHECK(needs_colors_); + char* pod = reinterpret_cast(vertices_.get()); + size_t bytes = vertices_->vertex_count_ * sizeof(colors[0]); + memcpy(pod + vertices_->colors_offset_, colors, bytes); + needs_colors_ = false; +} + +void DlVertices::Builder::store_colors(const uint32_t colors[]) { + FML_DCHECK(is_valid()); + FML_DCHECK(needs_colors_); + char* pod = reinterpret_cast(vertices_.get()); + DlColor* dlcolors_ptr = + reinterpret_cast(pod + vertices_->colors_offset_); + for (int i = 0; i < vertices_->vertex_count_; ++i) { + *dlcolors_ptr++ = DlColor(colors[i]); + } + needs_colors_ = false; +} + +void DlVertices::Builder::store_indices(const uint16_t indices[]) { + FML_DCHECK(is_valid()); + FML_DCHECK(needs_indices_); + char* pod = reinterpret_cast(vertices_.get()); + size_t bytes = vertices_->index_count_ * sizeof(indices[0]); + memcpy(pod + vertices_->indices_offset_, indices, bytes); + needs_indices_ = false; +} + +void DlVertices::Builder::store_bounds(DlRect bounds) { + vertices_->bounds_ = bounds; + needs_bounds_ = false; +} + +std::shared_ptr DlVertices::Builder::build() { + FML_DCHECK(is_valid()); + if (vertices_->vertex_count() <= 0) { + // We set this to true in the constructor to make sure that they + // call store_vertices() only once, but if there are no vertices + // then we will not object to them never having stored any vertices + needs_vertices_ = false; + } + FML_DCHECK(!needs_vertices_); + FML_DCHECK(!needs_texture_coords_); + FML_DCHECK(!needs_colors_); + FML_DCHECK(!needs_indices_); + + if (needs_bounds_) { + vertices_->bounds_ = + compute_bounds(vertices_->vertex_data(), vertices_->vertex_count_); + } + + return std::move(vertices_); +} + +} // namespace flutter diff --git a/flutter/engine/src/flutter/display_list/dl_vertices.h b/flutter/engine/src/flutter/display_list/dl_vertices.h new file mode 100644 index 0000000000000000000000000000000000000000..653fa9202be91114fced801db072e5f1b88f62a8 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_vertices.h @@ -0,0 +1,288 @@ +// 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_VERTICES_H_ +#define FLUTTER_DISPLAY_LIST_DL_VERTICES_H_ + +#include + +#include "flutter/display_list/dl_color.h" + +namespace flutter { + +//------------------------------------------------------------------------------ +/// @brief Defines the way in which the vertices of a DlVertices object +/// are separated into triangles into which to render. +/// +enum class DlVertexMode { + /// The vertices are taken 3 at a time to form a triangle. + kTriangles, + + /// The vertices are taken in overlapping triplets to form triangles, with + /// each triplet sharing 2 of its vertices with the preceding and following + /// triplets. + /// vertices [ABCDE] yield 3 triangles ABC,BCD,CDE + kTriangleStrip, + + /// The vertices are taken in overlapping pairs and combined with the first + /// vertex to form triangles that radiate outward from the initial point. + /// vertices [ABCDE] yield 3 triangles ABC,ACD,ADE + kTriangleFan, +}; + +//------------------------------------------------------------------------------ +/// @brief Holds all of the data (both required and optional) for a +/// DisplayList drawVertices call. +/// +/// There are 4 main pices of data: +/// - vertices(): +/// the points on the rendering surface that define the pixels +/// being rendered to in a series of triangles. These points +/// can map to triangles in various ways depending on the +/// supplied |DlVertexMode|. +/// - texture_coordinates(): +/// the points in the DlColorSource to map to the coordinates +/// of the triangles in the vertices(). If missing, the +/// vertex coordinates themselves will be used to map the +/// source colors to the vertices. +/// - colors(): +/// colors to map to each triangle vertex. Note that each +/// vertex is mapped to exactly 1 color even if the DlVertex +/// - indices(): +/// An indirection based on indices into the array of vertices +/// (and by extension, their associated texture_coordinates and +/// colors). Note that the DLVertexMode will still apply to the +/// indices in the same way (and instead of the way) that it +/// would normally be applied to the vertices themselves. The +/// indices are useful, for example, to fill the vertices with +/// a grid of points and then use the indices to define a +/// triangular mesh that covers that grid without having to +/// repeat the vertex (and texture coordinate and color) +/// information for the times when a given grid coordinate +/// gets reused in up to 4 mesh triangles. +/// +/// Note that each vertex is mapped to exactly 1 texture_coordinate and +/// color even if the DlVertexMode or indices specify that it contributes +/// to more than one output triangle. +/// +class DlVertices { + public: + /// @brief A utility class to build up a |DlVertices| object + /// one set of data at a time. + class Builder { + public: + /// @brief flags to indicate/promise which of the optional + /// texture coordinates or colors will be supplied + /// during the build phase. + union Flags { + struct { + unsigned has_texture_coordinates : 1; + unsigned has_colors : 1; + }; + uint32_t mask = 0; + + inline Flags operator|(const Flags& rhs) const { + return {.mask = (mask | rhs.mask)}; + } + + inline Flags& operator|=(const Flags& rhs) { + mask = mask | rhs.mask; + return *this; + } + }; + static constexpr Flags kNone = {{false, false}}; + static constexpr Flags kHasTextureCoordinates = {{true, false}}; + static constexpr Flags kHasColors = {{false, true}}; + + //-------------------------------------------------------------------------- + /// @brief Constructs a Builder and prepares room for the + /// required and optional data. + /// + /// Vertices are always required. Optional texture coordinates + /// and optional colors are reserved depending on the |Flags|. + /// Optional indices will be reserved if the index_count is + /// positive (>0). + /// + /// The caller must provide all data that is promised by the + /// supplied |flags| and |index_count| parameters before + /// calling the |build()| method. + Builder(DlVertexMode mode, int vertex_count, Flags flags, int index_count); + + /// Returns true iff the underlying object was successfully allocated. + bool is_valid() const { return vertices_ != nullptr; } + + /// @brief Copies the indicated list of points as vertices. + /// + /// fails if vertices have already been supplied. + void store_vertices(const DlPoint vertices[]); + + /// @brief Copies the indicated list of float pairs as vertices. + /// + /// fails if vertices have already been supplied. + void store_vertices(const float coordinates[]); + + /// @brief Copies the indicated list of points as texture coordinates. + /// + /// fails if texture coordinates have already been supplied or if they + /// were not promised by the flags.has_texture_coordinates. + void store_texture_coordinates(const DlPoint points[]); + + /// @brief Copies the indicated list of float pairs as texture coordinates. + /// + /// fails if texture coordinates have already been supplied or if they + /// were not promised by the flags.has_texture_coordinates. + void store_texture_coordinates(const float coordinates[]); + + /// @brief Copies the indicated list of colors as vertex colors. + /// + /// fails if colors have already been supplied or if they were not + /// promised by the flags.has_colors. + void store_colors(const DlColor colors[]); + + /// @brief Copies the indicated list of unsigned ints as vertex colors + /// in the 32-bit RGBA format. + /// + /// fails if colors have already been supplied or if they were not + /// promised by the flags.has_colors. + void store_colors(const uint32_t colors[]); + + /// @brief Copies the indicated list of 16-bit indices as vertex indices. + /// + /// fails if indices have already been supplied or if they were not + /// promised by (index_count > 0). + void store_indices(const uint16_t indices[]); + + /// @brief Overwrite the internal bounds with a precomputed bounding rect. + void store_bounds(DlRect bounds); + + /// @brief Finalizes and the constructed DlVertices object. + /// + /// fails if any of the optional data promised in the constructor is + /// missing. + std::shared_ptr build(); + + private: + std::shared_ptr vertices_; + bool needs_vertices_ = true; + bool needs_texture_coords_; + bool needs_colors_; + bool needs_indices_; + bool needs_bounds_ = true; + }; + + //-------------------------------------------------------------------------- + /// @brief Constructs a DlVector with compact inline storage for all + /// of its required and optional lists of data. + /// + /// Vertices are always required. Optional texture coordinates + /// and optional colors are stored if the arguments are non-null. + /// Optional indices will be stored iff the array argument is + /// non-null and the index_count is positive (>0). + static std::shared_ptr Make(DlVertexMode mode, + int vertex_count, + const DlPoint vertices[], + const DlPoint texture_coordinates[], + const DlColor colors[], + int index_count = 0, + const uint16_t indices[] = nullptr, + const DlRect* bounds = nullptr); + + /// Returns the size of the object including all of the inlined data. + size_t size() const; + + /// Returns the bounds of the vertices. + DlRect GetBounds() const { return bounds_; } + + /// Returns the vertex mode that defines how the vertices (or the indices) + /// are turned into triangles. + DlVertexMode mode() const { return mode_; } + + /// Returns the number of vertices, which also applies to the number of + /// texture coordinate and colors if they are provided. + int vertex_count() const { return vertex_count_; } + + /// Returns a pointer to the vertex information. Should be non-null. + const DlPoint* vertex_data() const { + return static_cast(pod(vertices_offset_)); + } + + /// Returns a pointer to the vertex texture coordinate + /// or null if none were provided. + const DlPoint* texture_coordinate_data() const { + return static_cast(pod(texture_coordinates_offset_)); + } + + /// Returns a pointer to the vertex colors + /// or null if none were provided. + const DlColor* colors() const { + return static_cast(pod(colors_offset_)); + } + + /// Returns a pointer to the count of vertex indices + /// or 0 if none were provided. + int index_count() const { return index_count_; } + + /// Returns a pointer to the vertex indices + /// or null if none were provided. + const uint16_t* indices() const { + return static_cast(pod(indices_offset_)); + } + + bool operator==(DlVertices const& other) const; + + bool operator!=(DlVertices const& other) const { return !(*this == other); } + + private: + // Constructors are designed to encapsulate arrays sequentially in memory + // which means they can only be called by intantiations that use the + // new (ptr) paradigm which precomputes and preallocates the memory for + // the class body and all of its arrays, such as in Builder. + DlVertices(DlVertexMode mode, + int vertex_count, + const DlPoint vertices[], + const DlPoint texture_coordinates[], + const DlColor colors[], + int index_count, + const uint16_t indices[], + const DlRect* bounds = nullptr); + + // This constructor is specifically used by the DlVertices::Builder to + // establish the object before the copying of data is requested. + DlVertices(DlVertexMode mode, + int vertex_count, + Builder::Flags flags, + int index_count); + + // The copy constructor has the same memory pre-allocation requirements + // as this other constructors. This particular version is used by the + // DisplaylistBuilder to copy the instance into pre-allocated pod memory + // in the display list buffer. + explicit DlVertices(const DlVertices* other); + + DlVertexMode mode_; + + int vertex_count_; + size_t vertices_offset_; + size_t texture_coordinates_offset_; + size_t colors_offset_; + + int index_count_; + size_t indices_offset_; + + DlRect bounds_; + + const void* pod(int offset) const { + if (offset <= 0) { + return nullptr; + } + const void* base = static_cast(this); + return static_cast(base) + offset; + } + + friend class DisplayListBuilder; +}; + +} // namespace flutter + +#endif // FLUTTER_DISPLAY_LIST_DL_VERTICES_H_ diff --git a/flutter/engine/src/flutter/display_list/dl_vertices_unittests.cc b/flutter/engine/src/flutter/display_list/dl_vertices_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d43d02e2e545cea72008fc96ef49f108a724b584 --- /dev/null +++ b/flutter/engine/src/flutter/display_list/dl_vertices_unittests.cc @@ -0,0 +1,983 @@ +// 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/dl_vertices.h" +#include "flutter/display_list/testing/dl_test_equality.h" +#include "flutter/display_list/utils/dl_comparable.h" +#include "gtest/gtest.h" + +namespace flutter { +namespace testing { + +TEST(DisplayListVertices, MakeWithZeroAndNegativeVerticesAndIndices) { + std::shared_ptr vertices1 = DlVertices::Make( + DlVertexMode::kTriangles, 0, nullptr, nullptr, nullptr, 0, nullptr); + EXPECT_NE(vertices1, nullptr); + EXPECT_EQ(vertices1->vertex_count(), 0); + EXPECT_EQ(vertices1->vertex_data(), nullptr); + EXPECT_EQ(vertices1->texture_coordinate_data(), nullptr); + EXPECT_EQ(vertices1->colors(), nullptr); + EXPECT_EQ(vertices1->index_count(), 0); + EXPECT_EQ(vertices1->indices(), nullptr); + + std::shared_ptr vertices2 = DlVertices::Make( + DlVertexMode::kTriangles, -1, nullptr, nullptr, nullptr, -1, nullptr); + EXPECT_NE(vertices2, nullptr); + EXPECT_EQ(vertices2->vertex_count(), 0); + EXPECT_EQ(vertices2->vertex_data(), nullptr); + EXPECT_EQ(vertices2->texture_coordinate_data(), nullptr); + EXPECT_EQ(vertices2->colors(), nullptr); + EXPECT_EQ(vertices2->index_count(), 0); + EXPECT_EQ(vertices2->indices(), nullptr); + + TestEquals(*vertices1, *vertices2); +} + +TEST(DisplayListVertices, MakeWithTexAndColorAndIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + DlColor colors[3] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + ASSERT_EQ(vertices->colors()[i], colors[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } +} + +TEST(DisplayListVertices, MakeWithTexAndColor) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + DlColor colors[3] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, nullptr); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + ASSERT_EQ(vertices->colors()[i], colors[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, MakeWithTexAndIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, texture_coords, nullptr, 6, indices); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } +} + +TEST(DisplayListVertices, MakeWithColorAndIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlColor colors[3] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, nullptr, colors, 6, indices); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->colors()[i], colors[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } +} + +TEST(DisplayListVertices, MakeWithTex) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, texture_coords, nullptr, 6, nullptr); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, MakeWithColor) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlColor colors[3] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, nullptr, colors, 6, nullptr); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->colors()[i], colors[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, MakeWithIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 6, indices); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } +} + +TEST(DisplayListVertices, MakeWithNoOptionalData) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 6, nullptr); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, MakeWithIndicesButZeroIndexCount) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 0, indices); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, MakeWithIndicesButNegativeIndexCount) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + std::shared_ptr vertices = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, -5, indices); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +using Builder = DlVertices::Builder; + +TEST(DisplayListVertices, BuilderFlags) { + Builder::Flags flags; + EXPECT_FALSE(flags.has_texture_coordinates); + EXPECT_FALSE(flags.has_colors); + + flags |= Builder::kHasTextureCoordinates; + EXPECT_TRUE(flags.has_texture_coordinates); + EXPECT_FALSE(flags.has_colors); + + flags |= Builder::kHasColors; + EXPECT_TRUE(flags.has_texture_coordinates); + EXPECT_TRUE(flags.has_colors); + + flags = Builder::Flags(); + EXPECT_FALSE(flags.has_texture_coordinates); + EXPECT_FALSE(flags.has_colors); + + flags |= Builder::kHasColors; + EXPECT_FALSE(flags.has_texture_coordinates); + EXPECT_TRUE(flags.has_colors); + + flags |= Builder::kHasTextureCoordinates; + EXPECT_TRUE(flags.has_texture_coordinates); + EXPECT_TRUE(flags.has_colors); + + EXPECT_FALSE(Builder::kNone.has_texture_coordinates); + EXPECT_FALSE(Builder::kNone.has_colors); + + EXPECT_TRUE(Builder::kHasTextureCoordinates.has_texture_coordinates); + EXPECT_FALSE(Builder::kHasTextureCoordinates.has_colors); + + EXPECT_FALSE(Builder::kHasColors.has_texture_coordinates); + EXPECT_TRUE(Builder::kHasColors.has_colors); + + EXPECT_TRUE((Builder::kHasTextureCoordinates | Builder::kHasColors) // + .has_texture_coordinates); + EXPECT_TRUE((Builder::kHasTextureCoordinates | Builder::kHasColors) // + .has_colors); +} + +TEST(DisplayListVertices, BuildWithZeroAndNegativeVerticesAndIndices) { + Builder builder1(DlVertexMode::kTriangles, 0, Builder::kNone, 0); + EXPECT_TRUE(builder1.is_valid()); + std::shared_ptr vertices1 = builder1.build(); + EXPECT_NE(vertices1, nullptr); + EXPECT_EQ(vertices1->vertex_count(), 0); + EXPECT_EQ(vertices1->vertex_data(), nullptr); + EXPECT_EQ(vertices1->texture_coordinate_data(), nullptr); + EXPECT_EQ(vertices1->colors(), nullptr); + EXPECT_EQ(vertices1->index_count(), 0); + EXPECT_EQ(vertices1->indices(), nullptr); + + Builder builder2(DlVertexMode::kTriangles, -1, Builder::kNone, -1); + EXPECT_TRUE(builder2.is_valid()); + std::shared_ptr vertices2 = builder2.build(); + EXPECT_NE(vertices2, nullptr); + EXPECT_EQ(vertices2->vertex_count(), 0); + EXPECT_EQ(vertices2->vertex_data(), nullptr); + EXPECT_EQ(vertices2->texture_coordinate_data(), nullptr); + EXPECT_EQ(vertices2->colors(), nullptr); + EXPECT_EQ(vertices2->index_count(), 0); + EXPECT_EQ(vertices2->indices(), nullptr); + + TestEquals(*vertices1, *vertices2); +} + +TEST(DisplayListVertices, BuildWithTexAndColorAndIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + DlColor colors[3] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + Builder builder(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates | Builder::kHasColors, 6); + builder.store_vertices(coords); + builder.store_texture_coordinates(texture_coords); + builder.store_colors(colors); + builder.store_indices(indices); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + ASSERT_EQ(vertices->colors()[i], colors[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } + + Builder builder2(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates | Builder::kHasColors, 6); + builder2.store_vertices(coords); + builder2.store_texture_coordinates(texture_coords); + builder2.store_colors(colors); + builder2.store_indices(indices); + std::shared_ptr vertices2 = builder2.build(); + + TestEquals(*vertices, *vertices2); + + std::shared_ptr vertices3 = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices); + + TestEquals(*vertices, *vertices3); +} + +TEST(DisplayListVertices, BuildWithTexAndColor) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + DlColor colors[3] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + }; + + Builder builder(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates | Builder::kHasColors, 0); + builder.store_vertices(coords); + builder.store_texture_coordinates(texture_coords); + builder.store_colors(colors); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + ASSERT_EQ(vertices->colors()[i], colors[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, BuildWithTexAndIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + Builder builder(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates, 6); + builder.store_vertices(coords); + builder.store_texture_coordinates(texture_coords); + builder.store_indices(indices); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } +} + +TEST(DisplayListVertices, BuildWithColorAndIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + uint32_t colors[3] = { + 0xffff0000, + 0xff00ffff, + 0xff00ff00, + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + Builder builder(DlVertexMode::kTriangles, 3, // + Builder::kHasColors, 6); + builder.store_vertices(coords); + builder.store_colors(colors); + builder.store_indices(indices); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->colors()[i].argb(), colors[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } +} + +TEST(DisplayListVertices, BuildWithTexUsingPoints) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + + Builder builder(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates, 0); + builder.store_vertices(coords); + builder.store_texture_coordinates(texture_coords); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, BuildWithTexUsingFloats) { + float coords[6] = { + 2, 3, // + 5, 6, // + 15, 20, + }; + float texture_coords[6] = { + 102, 103, // + 105, 106, // + 115, 120, + }; + + Builder builder(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates, 0); + builder.store_vertices(coords); + builder.store_texture_coordinates(texture_coords); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_NE(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i].x, coords[i * 2 + 0]); + ASSERT_EQ(vertices->vertex_data()[i].y, coords[i * 2 + 1]); + ASSERT_EQ(vertices->texture_coordinate_data()[i].x, + texture_coords[i * 2 + 0]); + ASSERT_EQ(vertices->texture_coordinate_data()[i].y, + texture_coords[i * 2 + 1]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, BuildUsingFloatsSameAsPoints) { + DlPoint coord_points[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coord_points[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + + float coord_floats[6] = { + 2, 3, // + 5, 6, // + 15, 20, + }; + float texture_coord_floats[6] = { + 102, 103, // + 105, 106, // + 115, 120, + }; + + Builder builder_points(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates, 0); + builder_points.store_vertices(coord_points); + builder_points.store_texture_coordinates(texture_coord_points); + std::shared_ptr vertices_points = builder_points.build(); + + Builder builder_floats(DlVertexMode::kTriangles, 3, // + Builder::kHasTextureCoordinates, 0); + builder_floats.store_vertices(coord_floats); + builder_floats.store_texture_coordinates(texture_coord_floats); + std::shared_ptr vertices_floats = builder_floats.build(); + + TestEquals(*vertices_points, *vertices_floats); +} + +TEST(DisplayListVertices, BuildWithColor) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + uint32_t colors[3] = { + 0xffff0000, + 0xff00ffff, + 0xff00ff00, + }; + + Builder builder(DlVertexMode::kTriangles, 3, // + Builder::kHasColors, 0); + builder.store_vertices(coords); + builder.store_colors(colors); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_NE(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + ASSERT_EQ(vertices->colors()[i].argb(), colors[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, BuildWithIndices) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, 6); + builder.store_vertices(coords); + builder.store_indices(indices); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_NE(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + } + ASSERT_EQ(vertices->index_count(), 6); + for (int i = 0; i < 6; i++) { + ASSERT_EQ(vertices->indices()[i], indices[i]); + } +} + +TEST(DisplayListVertices, BuildWithNoOptionalData) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + + Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, 0); + builder.store_vertices(coords); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, BuildWithNegativeIndexCount) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + + Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, -5); + builder.store_vertices(coords); + std::shared_ptr vertices = builder.build(); + + ASSERT_NE(vertices, nullptr); + ASSERT_NE(vertices->vertex_data(), nullptr); + ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); + ASSERT_EQ(vertices->colors(), nullptr); + ASSERT_EQ(vertices->indices(), nullptr); + + ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); + ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); + ASSERT_EQ(vertices->vertex_count(), 3); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(vertices->vertex_data()[i], coords[i]); + } + ASSERT_EQ(vertices->index_count(), 0); +} + +TEST(DisplayListVertices, TestEquals) { + DlPoint coords[3] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + }; + DlPoint texture_coords[3] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + }; + DlColor colors[3] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + }; + uint16_t indices[6] = { + 2, 1, 0, // + 1, 2, 0, + }; + + std::shared_ptr vertices1 = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices); + std::shared_ptr vertices2 = DlVertices::Make( + DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices); + TestEquals(*vertices1, *vertices2); +} + +TEST(DisplayListVertices, TestNotEquals) { + DlPoint coords[4] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + DlPoint(53, 62), + }; + DlPoint wrong_coords[4] = { + DlPoint(2, 3), + DlPoint(5, 6), + DlPoint(15, 20), + DlPoint(57, 62), + }; + DlPoint texture_coords[4] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 120), + DlPoint(153, 162), + }; + DlPoint wrong_texture_coords[4] = { + DlPoint(102, 103), + DlPoint(105, 106), + DlPoint(115, 121), + DlPoint(153, 162), + }; + DlColor colors[4] = { + DlColor::kRed(), + DlColor::kCyan(), + DlColor::kGreen(), + DlColor::kMagenta(), + }; + DlColor wrong_colors[4] = { + DlColor::kRed(), + DlColor::kBlue(), + DlColor::kGreen(), + DlColor::kMagenta(), + }; + uint16_t indices[9] = { + 2, 1, 0, // + 1, 2, 0, // + 1, 2, 3, + }; + uint16_t wrong_indices[9] = { + 2, 1, 0, // + 1, 2, 0, // + 2, 3, 1, + }; + + std::shared_ptr vertices1 = DlVertices::Make( + DlVertexMode::kTriangles, 4, coords, texture_coords, colors, 9, indices); + + { + std::shared_ptr vertices2 = + DlVertices::Make(DlVertexMode::kTriangleFan, 4, coords, // + texture_coords, colors, 9, indices); + TestNotEquals(*vertices1, *vertices2, "vertex mode differs"); + } + { + std::shared_ptr vertices2 = + DlVertices::Make(DlVertexMode::kTriangles, 3, coords, // + texture_coords, colors, 9, indices); + TestNotEquals(*vertices1, *vertices2, "vertex count differs"); + } + { + std::shared_ptr vertices2 = + DlVertices::Make(DlVertexMode::kTriangles, 4, wrong_coords, // + texture_coords, colors, 9, indices); + TestNotEquals(*vertices1, *vertices2, "vertex coordinates differ"); + } + { + std::shared_ptr vertices2 = + DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // + wrong_texture_coords, colors, 9, indices); + TestNotEquals(*vertices1, *vertices2, "texture coordinates differ"); + } + { + std::shared_ptr vertices2 = + DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // + texture_coords, wrong_colors, 9, indices); + TestNotEquals(*vertices1, *vertices2, "colors differ"); + } + { + std::shared_ptr vertices2 = + DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // + texture_coords, colors, 6, indices); + TestNotEquals(*vertices1, *vertices2, "index count differs"); + } + { + std::shared_ptr vertices2 = + DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // + texture_coords, colors, 9, wrong_indices); + TestNotEquals(*vertices1, *vertices2, "indices differ"); + } +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/docs/Crashes.md b/flutter/engine/src/flutter/docs/Crashes.md new file mode 100644 index 0000000000000000000000000000000000000000..3fcd3e80649538d7f03509d776f2be72ca4d7576 --- /dev/null +++ b/flutter/engine/src/flutter/docs/Crashes.md @@ -0,0 +1,172 @@ +# Symbolicating stack traces for engine crashes + +iOS app archives produced using Flutter 3.24 or later embed engine debugging symbols and thus crashes are symbolicated by default. + +The easiest way to symbolicate stack traces for Android and older iOS apps is to run the [dart_ci symbolizer locally](https://github.com/dart-lang/dart_ci/blob/main/github-label-notifier/symbolizer/README.md#using-this-locally). If that is not an option, the steps below explain how to do it manually. + +## Android + +### Get the symbols + +1. Get the Flutter Framework or Flutter Engine revision from the report. If you have the Engine revision, skip to step 3. + +2. Get the Engine revision from the Framework (this could be automated). `flutter/blob/main/bin/cache/engine.stamp` is the file which contains the information. Substitute the framework hash for `main` in that url. + +3. With the full engine revision (e.g. cea5ed2b9be42a981eac762af3664e4a17d0a53f), you can now get the proper symbol files: + + To view the available artifacts for a build, visit this URL in a browser (replacing the engine hash with your hash): `https://console.cloud.google.com/storage/browser/flutter_infra_release/flutter/cea5ed2b9be42a981eac762af3664e4a17d0a53f` + + To download the symbols for android-arm, download this URL _using your browser_ (replacing the hash again, and noting that this URL is on a different host, "storage", compared to the one above, which uses "console"): `https://storage.cloud.google.com/flutter_infra_release/flutter/cea5ed2b9be42a981eac762af3664e4a17d0a53f/android-arm/symbols.zip`. + + Please be aware that the type of the symbol must match your Apps release type. In above example, this refers to a android-arm **debug** build. If you work with a **release** or **profile** build, the URLs would look like this: + + * + * + + You have to use your browser because it does authentication. + +### Symbolicate with ndk-stack + +Once you have the symbols unzipped, you can use ndk-stack from your Android NDK. Suppose `stack.txt` contains the stack (including the leading `*** *** ***` line from the crash): + +```bash +.../ndk/prebuilt/linux-x86_64/bin/ndk-stack -sym .../path/to/downloaded/symbols < stack.txt +``` + +Or on macOS: +```bash +.../ndk/prebuilt/darwin-x86_64/bin/ndk-stack -sym .../path/to/downloaded/symbols < stack.txt +``` + +Some debugging tools, like _pidcat_ may not show the full tombstone logs. In that case, please use `adb logcat` directly and copy the full output. + +### Symbolicate with addr2line + +A alternative way to symbolicate is by using the addr2line tool. It is bundled with the NDK. +To use it, simply call it with a path to the .so file downloaded above and feed the stack addresses to it manually. For example, on macOS: + +``` +% $ANDROID_HOME/ndk/20.0.5594570/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android-addr2line -e ~/Downloads/libflutter.so +``` +_The tool is now awaiting your input, so let's feed it a memory address_: +``` +0x00000000006a26ec +/b/s/w/ir/cache/builder/src/out/android_release_arm64/../../third_party/dart/runtime/vm/dart_api_impl.cc:1366 +``` +This revealed address `0x00000000006a26ec` to correspond with `dart_api_impl.cc:1366`. + +### Making sure you got the right libflutter.so + +The build system sets a build id for each `libflutter.so` file. In the tombstones, you would see the ID like so: + +``` +#00 pc 000000000062d6e0 /data/app/com.app-tARy3eLH2Y-QN8J0d0WFog==/lib/arm64/libflutter.so!libflutter.so (offset 0x270000) (BuildId: 34ad5bdf0830d77a) +``` + +This equals to a build id of **34ad5bdf0830d77a**. The `libflutter.so` debug files downloaded as shown above could be verified using the `file` command: + +```sh +% file ~/Downloads/libflutter.so +/Users/user/Downloads/libflutter.so: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, BuildID[xxHash]=34ad5bdf0830d77a, with debug_info, not stripped +``` + +Ensure the build IDs match, else you will not be able to symbolicate. + +### Expanding Git Revisions + +Go to a commit page with the short commit as the last fragment of the URL: +(e.g. https://github.com/flutter/flutter/commit/9cb914df1 or https://github.com/flutter/engine/commit/2a13567) and then find the full revision on the page. + +### Symbolicating local builds (Android) + +If you have made your own builds, you can use ndk-stack directly: + +```sh +# dev/engine is where your engine's .gclient file is +# android_debug_unopt is whatever build of your engine you are using +adb logcat | ~/dev/engine/src/third_party/android_tools/ndk/prebuilt/linux-x86_64/bin/ndk-stack -sym ~/dev/engine/src/out/android_debug_unopt +``` + +### iOS + +Since Flutter 3.24, symbols can be found in the Flutter framework's artifact +cache, within the xcframework bundle at +`bin/cache/artifacts/engine/ios-release/Flutter.xcframework`. + +* Symbols for device builds are in the `ios-arm64/dSYMs/Flutter.framework.dSYM` bundle. +* Symbols for simulator builds are in the `ios-arm64_x86_64-simulator/dSYMs/Flutter.framework.dSYM` bundle. + +For versions prior to Flutter 3.24, the dSYM bundle can downloaded from Google +Cloud Storage. Follow the steps from the Android section in this guide, but in +the last step use a download url following this schema: +`https://storage.cloud.google.com/flutter_infra_release/flutter/38a646e14cc25f5a56a989c6a5787bf74e0ea386/ios-release/Flutter.dSYM.zip` +(replace the engine hash with your hash). + +For release since Flutter 3.24, these symbols are no longer uploaded as a +separate archive and should be obtained from the artifact cache as described +above. The artifact cache can be downloaded direcly using a URL following this +schema: +`https://storage.googleapis.com/flutter_infra_release/flutter/c11fe483947c95553610ab59210af643f031f5f4/ios-release/artifacts.zip` +(replace the engine hash with your hash). + +### macOS + +Since Flutter 3.27, symbols can be found in the Flutter framework's artifact +cache, within the xcframework bundle at +`bin/cache/artifacts/engine/darwin-x64-release/Flutter.xcframework`. + +* Symbols for device builds are in the `macos-arm64_x86_64/dSYMs/FlutterMacOS.framework.dSYM` bundle. + +For versions prior to Flutter 3.27, the dSYM bundle can downloaded from Google +Cloud Storage. Follow the steps from the Android section in this guide, but in +the last step use a download url following this schema: +`https://storage.cloud.google.com/flutter_infra_release/flutter/cf4507ae1008c11c6155d31e852999d75670afcf/darwin-x64-release/FlutterMacOS.dSYM.zip` +(replace the engine hash with your hash). + +For release since Flutter 3.27, these symbols are no longer uploaded as a +separate archive and should be obtained from the artifact cache as described +above. The artifact cache can be downloaded direcly using a URL following this +schema: +`https://storage.googleapis.com/flutter_infra_release/flutter/cf4507ae1008c11c6155d31e852999d75670afcf/darwin-x64-release/framework.zip` +(replace the engine hash with your hash). + +### Symbolicating local builds (macOS) + +If you built your local engine in debug or profile Dart modes, the framework's dylib's symbols aren't stripped and are available by default. + +### Crashes in Dart AOT code + +If the crash is in AOT Dart code (in `--release` or `--profile` builds) on iOS, and you can build your own engine, these steps will be helpful for the VM team to fix the bug: + +* Prepare a reduced test case. +* Compile the engine in profile mode and disable optimizations for symbolicated traces. + * `sky/tools/gn --ios --unopt --runtime-mode profile; ninja -C out/ios_profile_unopt -j800`. +* Launch the application via the Xcode project and make it crash in the debugger. +* File a bug on [dart-lang/sdk](https://github.com/dart-lang/sdk/issues/new). +* Dump the register state and paste it into the bug. + * In `lldb`, `register read`. +* Copy the backtrace and paste it into the bug. + * In `lldb`, `thread backtrace`. Assumes you are on the thread that crashed. If not, `thread select n`. +* Disassemble the last frame and paste it into the bug. + * In `lldb`, `frame select 0` then `disassemble --frame`. +* Disassemble using the `gen_snapshot` and paste the function into the bug for more detailed information. + * In the backtrace, look for the name of the precompiled function that caused the crash. + * Open `SnapshotterInvoke` from Xcode and to the `RunCommand ... Snapshotter` call, add the `--disassemble` flags. + * Modify the `RunCommand` function to dump to a file. + * Build again. The results should end up in the file. + * Look for the function name (by substring match) in this file and copy out that information to the bug. +* Ping someone on dart-lang/sdk. + +## Android Local Engine Builds + +When running with a local engine build, the symbolization workflow can be cumbersome and unecessary. Instead, it is possible to build the engine itself with symbols and disable Gradle's automatic symbol stripping. This is also required to see symbol names in Android Studio CPU profiles. + +1. In the android engine configuration, provide a --no-stripped argument to gn. For example: `gn --android --android-cpu=arm64 --unopt --no-stripped` + +2. In the flutter project file `android/app/build.gradle`, add the following line under the `android` block: + +```gradle +packagingOptions{ + doNotStrip "**/*.so" +} +``` diff --git a/flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedders.md b/flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedders.md new file mode 100644 index 0000000000000000000000000000000000000000..021b51c7f772d671cfb5365875b26e23dc493c40 --- /dev/null +++ b/flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedders.md @@ -0,0 +1,22 @@ +The Flutter Engine is window toolkit agnostic. If you want to build Flutter embedders on one of the platforms not supported out of the box (i.e, iOS & Android), this page is for you. + +This is a very low level API and is not suitable for beginners. + +* The window toolkit agnostic component of the Flutter engine is available as a dynamic library in the `flutter_engine` GN target in [`//shell/platform/embedder:flutter_engine`](https://github.com/flutter/flutter/blob/5517cc9b3b3bcf12431b47f495e342a30b738835/engine/src/flutter/shell/platform/embedder/BUILD.gn#L558). +* That target must be built as part of the host GN build. Such builds are already available for desktop Linux & Mac. If you want to target another platform, you will have to configure a GN toolchain for the same. +* You may build this target yourself or download the same artifacts uploaded by the buildbots on each commit. + * The Mac buildbot uploads the artifacts to a known location. Access it here [`https://storage.googleapis.com/flutter_infra_release/flutter/FLUTTER_HASH/darwin-x64/FlutterEmbedder.framework.zip`](https://storage.googleapis.com/flutter_infra_release/flutter/e672b006cb34c921db85b8e2f482ed3144a4574b/darwin-x64/FlutterEmbedder.framework.zip). + * Replace `FLUTTER_HASH` with the SHA of the Flutter commit you wish to use. + * The Linux buildbot uploads the artifacts to a known location. Access it here [`https://storage.googleapis.com/flutter_infra_release/flutter/FLUTTER_HASH/linux-x64/linux-x64-embedder.zip`](https://storage.googleapis.com/flutter_infra_release/flutter/e672b006cb34c921db85b8e2f482ed3144a4574b/linux-x64/linux-x64-embedder.zip) + * Replace `FLUTTER_HASH` with the SHA of the Flutter commit you wish to use. + * The binary is not stripped and contains debug information. Embedders are advised to strip the binary before deployment. + * The Windows buildbot uploads the artifacts to a known location. Access it here [`https://storage.googleapis.com/flutter_infra_release/flutter/FLUTTER_HASH/windows-x64/windows-x64-embedder.zip`](https://storage.googleapis.com/flutter_infra_release/flutter/e672b006cb34c921db85b8e2f482ed3144a4574b/windows-x64/windows-x64-embedder.zip) + * Replace `FLUTTER_HASH` with the SHA of the Flutter commit you wish to use. +* The Flutter engine API has no platform specific dependencies, has a stable ABI and is available in its entirety in a [single C header file available here](https://github.com/flutter/engine/blob/master/engine/src/flutter/shell/platform/embedder/embedder.h). +* To use as a guide, you may use [this example embedder that uses GLFW](https://github.com/flutter/engine/blob/master/engine/src/flutter/examples/glfw/FlutterEmbedderGLFW.cc) for window management and rendering. + +While we do not object to teams creating custom builds of the Flutter engine for their purposes, we do not support this configuration. Not supporting it means that we do not commit to any timelines for fixing bugs that may come up in such a configuration, even for customers for which we would usually be willing to make commitments (see the [Issue Hygiene](../contributing/issue_hygiene/README.md) page). It also means that we encourage teams to view such configurations as short-term solutions only and encourage teams to transition away from such configurations at the earliest possible opportunity. + +We do not expect custom engine builds to be long-term sustainable. They are not supported on any platform where we plan to be the publisher of a Flutter runtime distinct from the applications that run on the runtime, and they require significant effort to port to our new target platforms such as Web and desktop. There is also an expensive maintenance burden (for example, if we add new features, a custom engine build would need to be updated to support that feature). + +We would generally recommend using custom engine builds only when porting Flutter to platforms that are not supported out of the box, for example in embedded hardware. diff --git a/flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedding-in-AOT-Mode.md b/flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedding-in-AOT-Mode.md new file mode 100644 index 0000000000000000000000000000000000000000..64f181c9a9cc14a97070b4b4725f3d4cba31f952 --- /dev/null +++ b/flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedding-in-AOT-Mode.md @@ -0,0 +1,132 @@ +This document is intended for developers of third party embedders who wish to package and ship their Flutter applications for AOT mode operation. A third party embedder uses [the stable C embedder API](https://github.com/flutter/engine/blob/869d9f528503778be1e5ab27ba53502f0cb20de2/shell/platform/embedder/embedder.h) to embed Flutter applications on their platform. + +## Building an AOT Flutter Engine + +By default, the Flutter engine packaged for embedders assumes that the mode of operation is JIT. An engine configured for JIT packages a VM that is incompatible with AOT snapshots. Build an AOT engine using the following invocation. This is also the invocation where custom target, sysroot and toolchain selection flags can be specified. + +``` +./flutter/tools/gn --runtime-mode release +``` + +**Note:** Throughout this document, the `gn` flags mentioned work fine with other non-runtime mode or configuration selection options (stuff like `--no-lto`,` --unoptimized`, etc..). Such options are particularly useful during development and their use is highly encouraged. + +This will produce a Flutter engine configured for AOT mode targeting the host. Note that we are repurposing Flutter’s “release” mode policy to prepare an AOT engine. The application of this policy to third party embedders is optional and a decision the authors of such embedders need to make themselves. + +## Building the Architecture Specific `gen_snapshot` + +The binary that converts Dart code to architecture specific AOT instructions is called `gen_snapshot`. A successful invocation of `gen_snapshot` should produce four binary blobs. These are the Dart VM heap and instructions snapshots as well as the isolate heap and instruction snapshots. Refer to the [wiki article on engine operation in AOT mode](Flutter-engine-operation-in-AOT-Mode.md) for the purpose of these snapshots. + +A specific `gen_snapshot` can only produce AOT instructions for one target architecture. To verify that the `gen_snapshot` you have is producing instructions for the architecture you care about, invoke the same with the `--version` flag. It should produce something like the following. + +``` +Dart VM version: 2.1.1-dev.2.0.flutter-ac1bf656c4 (Thu Jan 17 16:55:19 2019 +0000) on "macos_x64" +``` + +The final string denotes the host/target pair. In the case of the example above, the host is `macos` and the target `x64`. An example of a `gen_snapshot` that produces instructions for `aarch64` would read “macos_simarm64” (the author is on MacOS X). + +It is easiest to just pick the supported Flutter target whose architecture is closest to the one of the embedder. For example, if the target is `armv7`, the following invocation will generate a `gen_snapshot` that is suitably configured for that target. + +``` +./flutter/tools/gn --android --runtime-mode release +``` + +Another useful invocation for aarch64 AOT targeted `gen_snapshot` is: + +``` +./flutter/tools/gn --android --runtime-mode release --android-cpu arm64 +``` + +**Important:** Calling convention and alignment must be the same (in addition to just the target architecture) for the AOT instructions generated by `gen_snapshot` and the target. Repurposing Flutter’s build targets makes sure that all those subtleties are taken care of. But it is still up to the embedder to pick and match the AOT instructions. For example, the `--android` --android-cpu arm64`configured`gen_snapshot`will not generate completely compatible instructions for iOS on`aarch64` (even though the target architectures are the same). A mismatch between the snapshot's architecture/ABI and the device's architecture/ABI will be detected when the snapshot is loaded and clearly reported. + +## Building the AOT Snapshot + +There are two separate steps involved in the generation of AOT instructions for the target architecture. First, a target architecture agnostic kernel snapshot (~AST) of the Flutter Dart application needs to be generated. Then, this snapshot is given to `gen_snaphost` which generates the AOT snapshot in the form of the four blobs (~machine code) listed above (and detailed on the wiki page). + +### The Short and Easy Way + +Both iOS and Android AOT modes need to do this step when they build their artifacts. So, if the embedder targets are similar, the workflow supported by the Flutter tooling can be repurposed for custom AOT embedders. For example, in the case of `aarch64` AOT instructions for Android like targets, the following instructions will generated the four AOT blobs in the intermediates. + +```bash +flutter --local-engine --local-engine-host build aot --target-platform android-arm64 --release +``` + +**Note:** The `--local-engine` (and `--local-engine-host`) flag is technically optional. However, not specifying the flag will make the tools pick the released version on of the Flutter engine. This version may contain subtle version mismatches with the engine you are using to prepare the `gen_snapshot` binary. So it is safer to just make sure the version are the same. +See [running with a local engine](Debugging-the-engine.md#running-a-flutter-app-with-a-local-engine) for more details. + +The result of the invocation will be the generation of the following binary blobs in the `build/aot directory`: + +- `vm_snapshot_data`: The VM snapshot data. +- `vm_snapshot_instr`: The VM snapshot instructions. +- `isolate_snapshot_data`: The Isolate snapshot data. +- `isolate_snapshot_instr`: The isolate snapshot instructions. + +### The Hard Way + +To generate the four AOT snapshot blobs directly, you will have to generate the kernel snapshot and then prepare the AOT snapshot manually. The exact flags to use are rather esoteric but self explanatory. And, when necessary, the `-v` flag can be passed to the `flutter build aot` instruction to dump the exact flags used by Flutter. These can then be modified as necessary for the target architecture. + +#### Generating the Kernel Snapshot + +The following invocation will generate a file called `kernel_snapshot.dill` in the build directory. Make sure you run `flutter packages get` in your project first to fetch all package dependencies. + +``` +$FLUTTER_ENGINE_OUT_DIR/dart \ + $FLUTTER_ENGINE_OUT_DIR/frontend_server.dart.snapshot \ + --sdk-root $FLUTTER_ENGINE_OUT_DIR/flutter_patched_sdk/ \ + --strong \ + --target=flutter \ + --aot \ + --tfa \ + -Ddart.vm.product=true \ + --packages .packages \ + --output-dill build/kernel_snapshot.dill \ + package:flutter_gallery/main.dart +``` + +#### Generating the AOT Snapshot + +Once the `kernel_snapshot.dill` file has been obtained, `gen_snapshot` can be invoked with the following arguments to generate the four blobs that form the AOT snapshot. + +``` +$FLUTTER_ENGINE_OUT_DIR/gen_snapshot \ + --causal_async_stacks \ + --packages=.packages \ + --deterministic \ + --snapshot_kind=app-aot-blobs \ + --vm_snapshot_data=build/vm_snapshot_data \ + --isolate_snapshot_data=build/isolate_snapshot_data \ + --vm_snapshot_instructions=build/vm_snapshot_instr \ + --isolate_snapshot_instructions=build/isolate_snapshot_instr \ + --no-sim-use-hardfp \ + --no-use-integer-division \ + build/kernel_snapshot.dill +``` + +**Note:** The `-no*` flags in the invocation above may not be necessary for all targets and can be skipped. As always, when in doubt, call `flutter build aot -v` after selecting the most similar target and see the flags used by Flutter. + +## Packaging the AOT Blobs + +The four AOT blobs need to be shipped with the application and are necessary for the `FlutterEngineRun` call. Embedders have to make a decision about how best to package and ship these blobs to the target. + +On the target at runtime, these blobs need to be mapped into the address space with the following restrictions: + +- `vm_snapshot_data`: Read-Only. +- `vm_snapshot_instr`: Read-Execute. +- `isolate_snapshot_data`: Read-Only. +- `isolate_snapshot_instr`: Read-Execute. + +The responsibility of keeping the mappings alive is upto the embedder. The mappings must be maintained as long as the `FlutterEngine` is running and alive. + +## Configuring the Engine for AOT Operation + +In the `FlutterProjectArgs` struct given the `FlutterEngineRun` call, provide the following options: + +- `vm_snapshot_data`: Pointer to the read-only VM snapshot mapping. +- `vm_snapshot_data_size`: Size of the VM snapshot mapping. +- `vm_snapshot_instructions`: Pointer to the read-execute VM instructions mapping. +- `vm_snapshot_instructions_size`: Size of the VM instructions mapping. +- `isolate_snapshot_data`: Pointer to the read-only isolate snapshot mapping. +- `isolate_snapshot_data_size`: Size of the isolate snapshot mapping. +- `isolate_snapshot_instructions`: Pointer to the read-execute isolate instructions mapping. +- `isolate_snapshot_instructions_size`: Size of the isolate instructions mapping. + +Flutter Engine is now running in AOT mode! diff --git a/flutter/engine/src/flutter/docs/Debugging-the-engine.md b/flutter/engine/src/flutter/docs/Debugging-the-engine.md new file mode 100644 index 0000000000000000000000000000000000000000..6d358de97edd8a684e48128660ba7a21df57e6d9 --- /dev/null +++ b/flutter/engine/src/flutter/docs/Debugging-the-engine.md @@ -0,0 +1,168 @@ +This page has some hints about debugging the engine. + +See also [Crashes](Crashes.md) for advice on handling engine crashes (specifically around obtaining stack traces, and reporting crashes in AOT Dart code). + +## Running a Flutter app with a local engine + +First, make sure the appropriate version of the engine is built (see [Compiling the engine](./contributing/Compiling-the-engine.md)). + +### Using the Flutter tool + +Run your Flutter app with: + +```bash +flutter run --local-engine=XXXX --local-engine-host=YYYY +``` + +to run an app with the local engine where `XXXX` should be replaced with the version you wish to use. For example, use `--local-engine=android_debug_unopt --local-engine-host=host_debug_unopt` to run a debug android engine or `--local-engine=ios_debug_sim_unopt --local-engine-host=host_debug_unopt` to run a debug iOS simulator engine. + +> 💡 **TIP**: When developing on a Mac with ARM (M CPU), use `--local-engine-host=host_debug_unopt_arm64`. +> +> You can continue to use `host_debug_unopt` (required for Intel Macs), but the engine will be run under Rosetta +> which may be slower. See [Developing with Flutter on Apple Silicon](../platforms/desktop/macos/Developing-with-Flutter-on-Apple-Silicon.md) +> for more information. + + +It is important to always have a `host_XXXX` version of the engine built when using a local engine since Flutter uses the host build's version of Dart. + +### Using Visual Studio Code + +You will need to add a new [launch configuration](https://code.visualstudio.com/docs/editor/debugging#_launch-configurations) in the `launch.json` file: + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch (local engine)", + "request": "launch", + "type": "dart", + "args": ["--local-engine", "XXX", "--local-engine-host", "YYY"] + } + + // Other profiles below.. + ] +} +``` + +## Bisecting a roll failure + +If the engine roll is failing (see [Autorollers](../infra/Autorollers.md)), you can use `git bisect` on the engine repo to track down the offending commit, using the `--local-engine` and `--local-engine-host` arguments as described above to run the failing framework test with each version of the engine. + +## Tracing OpenGL calls in Skia + +All OpenGL calls in Skia are guarded by either the `GR_GL_CALL_NOERRCHECK` or `GR_GL_CALL_RET_NOERRCHECK` macros. Trace events may be added in these macros to trace all GL calls made by Skia, for example [in a patch like this](https://gist.github.com/chinmaygarde/607eb86d5447615b9cf2804a4f8fb1ce). + +Due to the number of events traced to the timeline, the trace buffer may be filled up very quickly. Unless you want to see only the traces for the past few frames, use an endless trace buffer (`flutter run --endless-trace-buffer` turns on an endless trace buffer). + +Also, make sure to run your application with the `--trace-skia` flag. + +## Googlers using RBE + +You need to tell your IDE where your Flutter Engine sources are located. You can do this using an LLDB Init file. Place one in your home directory named `~/.lldbinit`. The contents of the file should be (fixup the path as necessary): + +``` +settings set target.source-map "flutter/" "/path/to/engine/src/flutter/" +``` + +## Debugging iOS builds with Xcode + +Building with `flutter --local-engine` will set a `LOCAL_ENGINE` Xcode build setting in your Flutter application's `ios/Flutter/Generated.xcconfig` file. This will be set until you run `flutter run` again with either a different `--local-engine` option, or with none at all (which will unset it). + +You can speed up your workflow by adding the `--config-only` flag to set up the Xcode build settings and plugins, but not compile the app. For example: + +```bash +flutter build ios --local-engine ios_debug_unopt --local-engine-host host_debug_unopt --config-only +``` + +If you are a Googler using RBE, [update `~/.lldbinit`](#googlers-using-rbe) to tell Xcode where the engine sources are located. + +To start debugging, open your Flutter app `ios/Runner.xcworkspace` file in Xcode. Ensure **Product > Scheme > Edit Scheme > Run > Build Configuration** matches your engine runtime mode (defaults to `Debug`). + +Product > Scheme > Edit Scheme > Run > Build Configuration + +Add an engine symbol breakpoint via **Debug > Breakpoints > Create Symbolic Breakpoint...**. The **Symbol** field should be the engine symbol you're interested in, like `-[FlutterEngine runWithEntrypoint:]` (note the `-[` prefix has no space). + +You can also set a breakpoint directly with [lldb](https://lldb.llvm.org/tutorial.html) by expanding **Flutter > Runner** in the Runner Project Navigator. Put a breakpoint in `AppDelegate.swift`'s `application(didFinishLaunchingWithOptions:)` (Swift project) or `main.m`'s `main()` (Objective-C project) and start the application by clicking the Run button (CMD + R). Then, set your desired breakpoint in the engine in `lldb` via `breakpoint set -...`. + +## Debugging Android builds with gdb + +See https://github.com/flutter/flutter/blob/master/engine/src/flutter/sky/tools/flutter_gdb + +## Debugging native engine code on Android with Android Studio + +1. Build an unoptimized local engine. i.e. `et build -c host_debug_unopt_arm64 && et build -c android_debug_unopt_arm64`. +2. Decide on a Flutter app that you with to debug and run it with `flutter build apk` and the local engine flags. i.e.: `--debug --local-engine-src-path path/to/my/engine/src --local-engine=android_debug_unopt_arm64`. +3. Open Android Studio and use `File > Profile or Debug APK`. The location of the debug build APK should be `build/app/outputs/apk/debug/app-debug.apk` under the Flutter app project. + + + +4. You may see the warning "One or more debug symbols point to paths not found on this machine". Add "Debuggable Library" path `out/android_debug_unopt_arm64/lib/libflutter.so`. + + + +5. If you are a Googler using RBE, [update `~/.lldbinit`](#googlers-using-rbe) to tell Android Studio where the engine sources are located. + +6. To attach the debugger, use `Run > Attach Debugger to Android Process`. For "Use Android Debugger Settings from" choose `[Use default settings]`, and for "Debug Type" choose `Native Only`. + + +7. Once attached, you can use Android Studio to open local engine C++ source files and set breakpoints. You can set Symbolic Breakpoints, i.e. Symbol name `impeller::ContextVK::ContectVK`. + +## Debugging Windows builds with Visual Studio + +Compiling the engine creates a Visual Studio solution file. You can use it to debug the engine: + +1. Launch your Flutter app using a locally built engine `flutter run -d windows --local-engine host_debug_unopt --local-engine-host host_debug_unopt` +2. Using Visual Studio, open the engine's solution file `.\out\host_debug_unopt\all.sln` +3. Open `Debug` > `Attach to Process...` (or press `CTRL+ALT+P`) +4. Choose your Flutter app using either `Select Window`, or, the list of available processes. +5. Press the `Attach` button + +Building a Flutter app also creates a Visual Studio solution file. You can use it to debug the +engine, your app's runner, and your app's plugins: + +1. Build your Flutter app using a locally built engine using `flutter build windows --debug --local-engine host_debug_unopt --local-engine-host host_debug_unopt` +2. Using Visual Studio, open the Flutter app's `.\build\windows\.sln` +3. In the `Solution Explorer` pane, right click the project whose name matches your app, and select `Set as Startup Project` + + ![Set as Startup Project example](https://user-images.githubusercontent.com/737941/215009513-d31c59fd-1f54-44d9-a702-6dd3fdf71492.png) + +4. Now run your app by pressing `F5` or `DEBUG` > `Start Debugging`. This will launch your app with Visual Studio's debugger attached. + +Read this guide to [learn how to debug C++ using Visual Studio](https://learn.microsoft.com/visualstudio/debugger/getting-started-with-the-debugger-cpp?view=vs-2022). + +## Debugging with gdb on Linux + +Once you have built the engine, you'll find the unstripped libraries in `out/host_debug_unopt/lib.unstripped`, and the executables in `out/host_debug_unopt/exe.unstripped`. + +So, for instance, to run the unit tests under the debugger you would execute: + +```shell +flutter/tools/gn --runtime-mode=debug --unoptimized +ninja -C out/host_debug_unopt +gdb out/host_debug_unopt/exe.unstripped/flutter_linux_unittests +``` + +And then debug the test normally using GDB commands. + +To debug a Flutter app using GDB, the stripped flutter engine GTK library in the built application needs to be replaced with the unstripped one in the engine build output directory. + +First, in your Flutter project, build your Flutter app using the local engine: + +```shell +flutter build linux --debug --local-engine=host_debug_unopt --local-engine-host=host_debug_unopt lib/main.dart +``` + +Then, replace the library in your Flutter application's build directory: `build/linux/x64/debug/bundle/lib/libflutter_linux_gtk.so` with a copy or symbolic link to the engine build's output file `out/host_debug_unopt/lib.unstripped/libflutter_linux_gtk.so`. + +Then you can open it in the debugger with: + +```shell +gdb build/linux/x64/debug/bundle/your_app_name +``` + +Note that this won't help you debug the Dart portion of the app: this is just for debugging the engine code. If you need to simultaneously debug the Dart portion, you can connect to the observatory port given when you run the app in `gdb`. + +## Logging in the engine + +Flutter tool will by default parse out any non-error output from the engine. Error logs will be displayed. Logging is handled though the FML library's `logging.h`. diff --git a/flutter/engine/src/flutter/docs/Doxyfile.template b/flutter/engine/src/flutter/docs/Doxyfile.template new file mode 100644 index 0000000000000000000000000000000000000000..129cff8b2b5dfe4efb8c2dbd63e4bff5676fd772 --- /dev/null +++ b/flutter/engine/src/flutter/docs/Doxyfile.template @@ -0,0 +1,2747 @@ +# Doxyfile 1.9.4 + +# This file is a template for the Doxyfile used to generate Flutter +# documentation for the Engine code using Doxygen. Fields with +# @@FIELD_NAME@@ as the value will be substituted by the +# tools/gen_docs.sh script to contain the appropriate values for a +# specific documentation section configured in the script. + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). +# +# Note: +# +# Use doxygen to compare the used configuration file with the template +# configuration file: +# doxygen -x [configFile] +# Use doxygen to compare the used configuration file with the template +# configuration file without replacing the environment variables or CMake type +# replacement variables: +# doxygen -x_noenv [configFile] + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the configuration +# file that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# https://www.gnu.org/software/libiconv/ for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "@@PROJECT_NAME@@" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = ./docs/flutter_logo.png + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = "@@OUTPUT_DIRECTORY@@" + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create up to 4096 +# sub-directories (in 2 levels) under the output directory of each output format +# and will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. Adapt CREATE_SUBDIRS_LEVEL to +# control the number of sub-directories. +# The default value is: NO. + +# For Flutter, this should be NO, so that URLs remain stable across versions. +CREATE_SUBDIRS = NO + +# Controls the number of sub-directories that will be created when +# CREATE_SUBDIRS tag is set to YES. Level 0 represents 16 directories, and every +# level increment doubles the number of directories, resulting in 4096 +# directories at level 8 which is the default and also the maximum value. The +# sub-directories are organized in 2 levels, the first level always has a fixed +# number of 16 directories. +# Minimum value: 0, maximum value: 8, default value: 8. +# This tag requires that the tag CREATE_SUBDIRS is set to YES. + +CREATE_SUBDIRS_LEVEL = 8 + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Bulgarian, +# Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, English +# (United States), Esperanto, Farsi (Persian), Finnish, French, German, Greek, +# Hindi, Hungarian, Indonesian, Italian, Japanese, Japanese-en (Japanese with +# English messages), Korean, Korean-en (Korean with English messages), Latvian, +# Lithuanian, Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, +# Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, +# Swedish, Turkish, Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = NO + +# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line +# such as +# /*************** +# as being the beginning of a Javadoc-style comment "banner". If set to NO, the +# Javadoc-style will behave just like regular comments and it will not be +# interpreted by doxygen. +# The default value is: NO. + +JAVADOC_BANNER = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# By default Python docstrings are displayed as preformatted text and doxygen's +# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the +# doxygen's special commands can be used and the contents of the docstring +# documentation blocks is shown as doxygen documentation. +# The default value is: YES. + +PYTHON_DOCSTRING = YES + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:^^" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". Note that you cannot put \n's in the value part of an alias +# to insert newlines (in the resulting output). You can put ^^ in the value part +# of an alias to insert a newline as if a physical newline was in the original +# file. When you need a literal { or } or , in the value part of an alias you +# have to escape them by means of a backslash (\), this can lead to conflicts +# with the commands \{ and \} for these it is advised to use the version @{ and +# @} or use a double escape (\\{ and \\}) + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice +# sources only. Doxygen will then generate output that is more tailored for that +# language. For instance, namespaces will be presented as modules, types will be +# separated into more groups, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_SLICE = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, JavaScript, +# Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice, +# VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: +# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser +# tries to guess whether the code is fixed or free formatted code, this is the +# default for Fortran type files). For instance to make doxygen treat .inc files +# as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. When specifying no_extension you should add +# * to the FILE_PATTERNS. +# +# Note see also the list of default file extension mappings. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See https://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 5. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 0 + +# The MARKDOWN_ID_STYLE tag can be used to specify the algorithm used to +# generate identifiers for the Markdown headings. Note: Every identifier is +# unique. +# Possible values are: DOXYGEN Use a fixed 'autotoc_md' string followed by a +# sequence number starting at 0. and GITHUB Use the lower case version of title +# with any whitespace replaced by '-' and punctations characters removed.. +# The default value is: DOXYGEN. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +MARKDOWN_ID_STYLE = DOXYGEN + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +# The NUM_PROC_THREADS specifies the number of threads doxygen is allowed to use +# during processing. When set to 0 doxygen will based this on the number of +# cores available in the system. You can set it explicitly to a value larger +# than 0 to get more control over the balance between CPU load and processing +# speed. At this moment only the input processing can be done using multiple +# threads. Since this is still an experimental feature the default is set to 1, +# which effectively disables parallel processing. Please report any issues you +# encounter. Generating dot graphs in parallel is controlled by the +# DOT_NUM_THREADS setting. +# Minimum value: 0, maximum value: 32, default value: 1. + +NUM_PROC_THREADS = 1 + +# If the TIMESTAMP tag is set different from NO then each generated page will +# contain the date or date and time when the page was generated. Setting this to +# NO can help when comparing the output of multiple runs. +# Possible values are: YES, NO, DATETIME and DATE. +# The default value is: NO. + +TIMESTAMP = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual +# methods of a class will be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIV_VIRTUAL = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If this flag is set to YES, the name of an unnamed parameter in a declaration +# will be determined by the corresponding definition. By default unnamed +# parameters remain unnamed in the output. +# The default value is: YES. + +RESOLVE_UNNAMED_PARAMS = YES + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# will also hide undocumented C++ concepts if enabled. This option has no effect +# if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# declarations. If set to NO, these declarations will be included in the +# documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# With the correct setting of option CASE_SENSE_NAMES doxygen will better be +# able to match the capabilities of the underlying filesystem. In case the +# filesystem is case sensitive (i.e. it supports files in the same directory +# whose names only differ in casing), the option must be set to YES to properly +# deal with such files in case they appear in the input. For filesystems that +# are not case sensitive the option should be set to NO to properly deal with +# output files written for symbols that only differ in casing, such as for two +# classes, one named CLASS and the other named Class, and to also support +# references to files without having to specify the exact matching casing. On +# Windows (including Cygwin) and MacOS, users should typically set this option +# to NO, whereas on Linux or other Unix flavors it should typically be set to +# YES. +# Possible values are: SYSTEM, NO and YES. +# The default value is: SYSTEM. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_HEADERFILE tag is set to YES then the documentation for a class +# will show which file needs to be included to use the class. +# The default value is: YES. + +SHOW_HEADERFILE = YES + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = NO + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = NO + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = NO + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= NO + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. See also section "Changing the +# layout of pages" for information. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as documenting some parameters in +# a documented function twice, or documenting parameters that don't exist or +# using markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# If WARN_IF_INCOMPLETE_DOC is set to YES, doxygen will warn about incomplete +# function parameter documentation. If set to NO, doxygen will accept that some +# parameters have no documentation without warning. +# The default value is: YES. + +WARN_IF_INCOMPLETE_DOC = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong parameter +# documentation, but not about the absence of documentation. If EXTRACT_ALL is +# set to YES then this flag will automatically be disabled. See also +# WARN_IF_INCOMPLETE_DOC +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# If WARN_IF_UNDOC_ENUM_VAL option is set to YES, doxygen will warn about +# undocumented enumeration values. If set to NO, doxygen will accept +# undocumented enumeration values. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: NO. + +WARN_IF_UNDOC_ENUM_VAL = NO + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS +# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but +# at the end of the doxygen process doxygen will return with a non-zero status. +# If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS_PRINT then doxygen behaves +# like FAIL_ON_WARNINGS but in case no WARN_LOGFILE is defined doxygen will not +# write the warning messages in between other messages but write them at the end +# of a run, in case a WARN_LOGFILE is defined the warning messages will be +# besides being in the defined file also be shown at the end of a run, unless +# the WARN_LOGFILE is defined as - i.e. standard output (stdout) in that case +# the behavior will remain as with the setting FAIL_ON_WARNINGS. +# Possible values are: NO, YES, FAIL_ON_WARNINGS and FAIL_ON_WARNINGS_PRINT. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# See also: WARN_LINE_FORMAT +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# In the $text part of the WARN_FORMAT command it is possible that a reference +# to a more specific place is given. To make it easier to jump to this place +# (outside of doxygen) the user can define a custom "cut" / "paste" string. +# Example: +# WARN_LINE_FORMAT = "'vi $file +$line'" +# See also: WARN_FORMAT +# The default value is: at line $line of file $file. + +WARN_LINE_FORMAT = "at line $line of file $file" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). In case the file specified cannot be opened for writing the +# warning and error messages are written to standard error. When as file - is +# specified the warning and error messages are written to standard output +# (stdout). + +WARN_LOGFILE = "@@LOG_FILE@@" + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = @@INPUT_DIRECTORIES@@ + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: +# https://www.gnu.org/software/libiconv/) for the list of possible encodings. +# See also: INPUT_FILE_ENCODING +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses The INPUT_FILE_ENCODING tag can be used to specify +# character encoding on a per file pattern basis. Doxygen will compare the file +# name with each pattern and apply the encoding instead of the default +# INPUT_ENCODING) if there is a match. The character encodings are a list of the +# form: pattern=encoding (like *.php=ISO-8859-1). See cfg_input_encoding +# "INPUT_ENCODING" for further information on supported encodings. + +INPUT_FILE_ENCODING = + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# Note the list of default checked file patterns might differ from the list of +# default file extension mappings. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, +# *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C +# comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd, +# *.vhdl, *.ucf, *.qsf and *.ice. + +FILE_PATTERNS = *.h \ + *.c \ + *.cc \ + *.m \ + *.mm \ + *.cpp \ + *.cxx \ + *.hh \ + *.hxx \ + *.hpp \ + *.c++ \ + *.h++ + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = */tests/* \ + */testing/* \ + */test/* \ + */test_utils/* + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# ANamespace::AClass, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that doxygen will use the data processed and written to standard output +# for further processing, therefore nothing else, like debug statements or used +# commands (so in case of a Windows batch file always use @echo OFF), should be +# written to standard output. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = ./README.md + +# The Fortran standard specifies that for fixed formatted Fortran code all +# characters from position 72 are to be considered as comment. A common +# extension is to allow longer lines before the automatic comment starts. The +# setting FORTRAN_COMMENT_AFTER will also make it possible that longer lines can +# be processed before the automatic comment starts. +# Minimum value: 7, maximum value: 10000, default value: 72. + +FORTRAN_COMMENT_AFTER = 72 + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = YES + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = NO + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# entity all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see https://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The IGNORE_PREFIX tag can be used to specify a prefix (or a list of prefixes) +# that should be ignored while generating the index headers. The IGNORE_PREFIX +# tag works for classes, function and member names. The entity will be placed in +# the alphabetical list under the first letter of the entity name that remains +# after removing the prefix. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). +# Note: Since the styling of scrollbars can currently not be overruled in +# Webkit/Chromium, the styling will be left out of the default doxygen.css if +# one or more extra stylesheets have been specified. So if scrollbar +# customization is desired it has to be added explicitly. For an example see the +# documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE tag can be used to specify if the generated HTML output +# should be rendered with a dark or light theme. +# Possible values are: LIGHT always generate light mode output, DARK always +# generate dark mode output, AUTO_LIGHT automatically set the mode according to +# the user preference, use light mode if no preference is set (the default), +# AUTO_DARK automatically set the mode according to the user preference, use +# dark mode if no preference is set and TOGGLE allow to user to switch between +# light and dark mode via a button. +# The default value is: AUTO_LIGHT. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE = AUTO_LIGHT + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a color-wheel, see +# https://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 212 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use gray-scales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 183 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 100 + +# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML +# documentation will contain a main index with vertical navigation menus that +# are dynamically created via JavaScript. If disabled, the navigation index will +# consists of multiple levels of tabs that are statically embedded in every HTML +# page. Disable this option to support browsers that do not have JavaScript, +# like the Qt help browser. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_MENUS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: +# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To +# create a documentation set, doxygen will generate a Makefile in the HTML +# output directory. Running make will produce the docset in that directory and +# running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy +# genXcode/_index.html for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = YES + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "@@DOCSET_FEEDNAME@@" + +# This tag determines the URL of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDURL = + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = io.flutter.engine + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = io.flutter.engine + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Flutter + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# on Windows. In the beginning of 2021 Microsoft took the original page, with +# a.o. the download links, offline the HTML help workshop was already many years +# in maintenance mode). You can download the HTML help workshop from the web +# archives at Installation executable (see: +# http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo +# ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe). +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the main .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# The SITEMAP_URL tag is used to specify the full URL of the place where the +# generated documentation will be placed on the server by the user during the +# deployment of the documentation. The generated sitemap is called sitemap.xml +# and placed on the directory specified by HTML_OUTPUT. In case no SITEMAP_URL +# is specified no sitemap is generated. For information about the sitemap +# protocol see https://www.sitemaps.org +# This tag requires that the tag GENERATE_HTML is set to YES. + +SITEMAP_URL = + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = io.flutter.engine + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location (absolute path +# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to +# run qhelpgenerator on the generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = io.flutter.engine + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = YES + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine tune the look of the index (see "Fine-tuning the output"). As an +# example, the default style sheet generated by doxygen has an example that +# shows how to put an image at the root of the tree instead of the PROJECT_NAME. +# Since the tree basically has the same information as the tab index, you could +# consider setting DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = YES + +# When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the +# FULL_SIDEBAR option determines if the side bar is limited to only the treeview +# area (value NO) or if it should extend to the full height of the window (value +# YES). Setting this to YES gives a layout similar to +# https://docs.readthedocs.io with more room for contents, but less room for the +# project logo, title, and description. If either GENERATE_TREEVIEW or +# DISABLE_INDEX is set to NO, this option has no effect. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FULL_SIDEBAR = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 1 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# If the OBFUSCATE_EMAILS tag is set to YES, doxygen will obfuscate email +# addresses. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +OBFUSCATE_EMAILS = YES + +# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg +# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see +# https://inkscape.org) to generate formulas as SVG images instead of PNGs for +# the HTML output. These images will generally look nicer at scaled resolutions. +# Possible values are: png (the default) and svg (looks nicer but requires the +# pdf2svg or inkscape tool). +# The default value is: png. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FORMULA_FORMAT = png + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands +# to create new LaTeX commands to be used in formulas as building blocks. See +# the section "Including formulas" for details. + +FORMULA_MACROFILE = + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# https://www.mathjax.org) which uses client side JavaScript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# With MATHJAX_VERSION it is possible to specify the MathJax version to be used. +# Note that the different versions of MathJax have different requirements with +# regards to the different settings, so it is possible that also other MathJax +# settings have to be changed when switching between the different MathJax +# versions. +# Possible values are: MathJax_2 and MathJax_3. +# The default value is: MathJax_2. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_VERSION = MathJax_2 + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. For more details about the output format see MathJax +# version 2 (see: +# http://docs.mathjax.org/en/v2.7-latest/output.html) and MathJax version 3 +# (see: +# http://docs.mathjax.org/en/latest/web/components/output.html). +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility. This is the name for Mathjax version 2, for MathJax version 3 +# this will be translated into chtml), NativeMML (i.e. MathML. Only supported +# for NathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This +# is the name for Mathjax version 3, for MathJax version 2 this will be +# translated into HTML-CSS) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from https://www.mathjax.org before deployment. The default value is: +# - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2 +# - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3 +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/ + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# for MathJax version 2 (see +# https://docs.mathjax.org/en/v2.7-latest/tex.html#tex-and-latex-extensions): +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# For example for MathJax version 3 (see +# http://docs.mathjax.org/en/latest/input/tex/extensions/index.html): +# MATHJAX_EXTENSIONS = ams +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: +# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /