text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_VK_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_VK_H_ #include <memory> #include "impeller/geometry/size.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/context.h" #include "impeller/renderer/surface.h" namespace impeller { class KHRSwapchainImplVK; //------------------------------------------------------------------------------ /// @brief A swapchain that adapts to the underlying surface going out of /// date. If the caller cannot acquire the next drawable, it is due /// to an unrecoverable error and the swapchain must be recreated /// with a new surface. /// class KHRSwapchainVK { public: static std::shared_ptr<KHRSwapchainVK> Create( const std::shared_ptr<Context>& context, vk::UniqueSurfaceKHR surface, const ISize& size, bool enable_msaa = true); ~KHRSwapchainVK(); bool IsValid() const; std::unique_ptr<Surface> AcquireNextDrawable(); vk::Format GetSurfaceFormat() const; /// @brief Mark the current swapchain configuration as dirty, forcing it to be /// recreated on the next frame. void UpdateSurfaceSize(const ISize& size); private: std::shared_ptr<KHRSwapchainImplVK> impl_; ISize size_; const bool enable_msaa_; KHRSwapchainVK(std::shared_ptr<KHRSwapchainImplVK> impl, const ISize& size, bool enable_msaa); KHRSwapchainVK(const KHRSwapchainVK&) = delete; KHRSwapchainVK& operator=(const KHRSwapchainVK&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_VK_H_
engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h", "repo_id": "engine", "token_count": 737 }
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_IMPELLER_RENDERER_BACKEND_VULKAN_VMA_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VMA_H_ #include "flutter/flutter_vma/flutter_vma.h" #include "flutter/fml/trace_event.h" #include "flutter/fml/unique_object.h" #include "impeller/renderer/backend/vulkan/vk.h" namespace impeller { // ----------------------------------------------------------------------------- // Unique handles to VMA allocators. // ----------------------------------------------------------------------------- struct AllocatorVMATraits { static VmaAllocator InvalidValue() { return {}; } static bool IsValid(const VmaAllocator& value) { return value != InvalidValue(); } static void Free(VmaAllocator allocator) { TRACE_EVENT0("impeller", "DestroyAllocator"); ::vmaDestroyAllocator(allocator); } }; using UniqueAllocatorVMA = fml::UniqueObject<VmaAllocator, AllocatorVMATraits>; // ----------------------------------------------------------------------------- // Unique handles to VMA pools. // ----------------------------------------------------------------------------- struct PoolVMA { VmaAllocator allocator = {}; VmaPool pool = {}; constexpr bool operator==(const PoolVMA& other) const { return allocator == other.allocator && pool == other.pool; } constexpr bool operator!=(const PoolVMA& other) const { return !(*this == other); } }; struct PoolVMATraits { static PoolVMA InvalidValue() { return {}; } static bool IsValid(const PoolVMA& value) { return value.allocator != VmaAllocator{}; } static void Free(const PoolVMA& pool) { TRACE_EVENT0("impeller", "DestroyPool"); ::vmaDestroyPool(pool.allocator, pool.pool); } }; using UniquePoolVMA = fml::UniqueObject<PoolVMA, PoolVMATraits>; // ----------------------------------------------------------------------------- // Unique handles to VMA buffers. // ----------------------------------------------------------------------------- struct BufferVMA { VmaAllocator allocator = {}; VmaAllocation allocation = {}; vk::Buffer buffer = {}; constexpr bool operator==(const BufferVMA& other) const { return allocator == other.allocator && allocation == other.allocation && buffer == other.buffer; } constexpr bool operator!=(const BufferVMA& other) const { return !(*this == other); } }; struct BufferVMATraits { static BufferVMA InvalidValue() { return {}; } static bool IsValid(const BufferVMA& value) { return value.allocator != VmaAllocator{}; } static void Free(const BufferVMA& buffer) { TRACE_EVENT0("impeller", "DestroyBuffer"); ::vmaDestroyBuffer(buffer.allocator, static_cast<VkBuffer>(buffer.buffer), buffer.allocation); } }; using UniqueBufferVMA = fml::UniqueObject<BufferVMA, BufferVMATraits>; // ----------------------------------------------------------------------------- // Unique handles to VMA images. // ----------------------------------------------------------------------------- struct ImageVMA { VmaAllocator allocator = {}; VmaAllocation allocation = {}; vk::Image image = {}; constexpr bool operator==(const ImageVMA& other) const { return allocator == other.allocator && allocation == other.allocation && image == other.image; } constexpr bool operator!=(const ImageVMA& other) const { return !(*this == other); } }; struct ImageVMATraits { static ImageVMA InvalidValue() { return {}; } static bool IsValid(const ImageVMA& value) { return value.allocator != VmaAllocator{}; } static void Free(const ImageVMA& image) { TRACE_EVENT0("impeller", "DestroyImage"); ::vmaDestroyImage(image.allocator, static_cast<VkImage>(image.image), image.allocation); } }; using UniqueImageVMA = fml::UniqueObject<ImageVMA, ImageVMATraits>; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VMA_H_
engine/impeller/renderer/backend/vulkan/vma.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/vma.h", "repo_id": "engine", "token_count": 1283 }
226
// 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_IMPELLER_RENDERER_COMMAND_BUFFER_H_ #define FLUTTER_IMPELLER_RENDERER_COMMAND_BUFFER_H_ #include <functional> #include <memory> #include "impeller/renderer/blit_pass.h" #include "impeller/renderer/compute_pass.h" namespace impeller { class ComputePass; class Context; class RenderPass; class RenderTarget; class CommandQueue; namespace testing { class CommandBufferMock; } //------------------------------------------------------------------------------ /// @brief A collection of encoded commands to be submitted to the GPU for /// execution. A command buffer is obtained from a graphics /// `Context`. /// /// To submit commands to the GPU, acquire a `RenderPass` from the /// command buffer and record `Command`s into that pass. A /// `RenderPass` describes the configuration of the various /// attachments when the command is submitted. /// /// A command buffer is only meant to be used on a single thread. If /// a frame workload needs to be encoded from multiple threads, /// set up and record into multiple command buffers. The order of /// submission of commands encoded in multiple command buffers can /// be controlled via either the order in which the command buffers /// were created, or, using the `ReserveSpotInQueue` command which /// allows for encoding commands for submission in an order that is /// different from the encoding order. /// class CommandBuffer { friend class testing::CommandBufferMock; public: enum class Status { kPending, kError, kCompleted, }; using CompletionCallback = std::function<void(Status)>; virtual ~CommandBuffer(); virtual bool IsValid() const = 0; virtual void SetLabel(const std::string& label) const = 0; //---------------------------------------------------------------------------- /// @brief Force execution of pending GPU commands. /// void WaitUntilScheduled(); //---------------------------------------------------------------------------- /// @brief Create a render pass to record render commands into. /// /// @param[in] render_target The description of the render target this pass /// will target. /// /// @return A valid render pass or null. /// std::shared_ptr<RenderPass> CreateRenderPass( const RenderTarget& render_target); //---------------------------------------------------------------------------- /// @brief Create a blit pass to record blit commands into. /// /// @return A valid blit pass or null. /// std::shared_ptr<BlitPass> CreateBlitPass(); //---------------------------------------------------------------------------- /// @brief Create a compute pass to record compute commands into. /// /// @return A valid compute pass or null. /// std::shared_ptr<ComputePass> CreateComputePass(); protected: std::weak_ptr<const Context> context_; explicit CommandBuffer(std::weak_ptr<const Context> context); virtual std::shared_ptr<RenderPass> OnCreateRenderPass( RenderTarget render_target) = 0; virtual std::shared_ptr<BlitPass> OnCreateBlitPass() = 0; [[nodiscard]] virtual bool OnSubmitCommands(CompletionCallback callback) = 0; virtual void OnWaitUntilScheduled() = 0; virtual std::shared_ptr<ComputePass> OnCreateComputePass() = 0; private: friend class CommandQueue; //---------------------------------------------------------------------------- /// @brief Schedule the command encoded by render passes within this /// command buffer on the GPU. The encoding of these commnands is /// performed immediately on the calling thread. /// /// A command buffer may only be committed once. /// /// @param[in] callback The completion callback. /// [[nodiscard]] bool SubmitCommands(const CompletionCallback& callback); [[nodiscard]] bool SubmitCommands(); CommandBuffer(const CommandBuffer&) = delete; CommandBuffer& operator=(const CommandBuffer&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_COMMAND_BUFFER_H_
engine/impeller/renderer/command_buffer.h/0
{ "file_path": "engine/impeller/renderer/command_buffer.h", "repo_id": "engine", "token_count": 1358 }
227
// 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. #extension GL_KHR_shader_subgroup_arithmetic : enable layout(local_size_x = 256, local_size_y = 1) in; layout(std430) buffer; #include <impeller/path.glsl> layout(binding = 0) readonly buffer Cubics { uint count; CubicData data[]; } cubics; layout(binding = 1) buffer Quads { uint count; QuadData data[]; } quads; layout(binding = 2) buffer Lines { uint count; LineData data[]; } lines; layout(binding = 3) buffer Components { uint count; PathComponent data[]; } components; layout(binding = 4) buffer Polyline { uint count; vec2 data[]; } polyline; uniform Config { float cubic_accuracy; float quad_tolerance; } config; shared uvec2 cubic_ranges[512]; shared uvec2 quad_ranges[512]; shared uint scratch_count[512]; shared uint scratch_sum[512]; uint ComputePosition(uint index) { uint sum = scratch_sum[index]; for (uint position = gl_SubgroupSize - 1; position < index; position += gl_SubgroupSize) { sum += scratch_sum[position] + scratch_count[position]; } return sum; } void ProcessCubic(uint ident) { CubicData cubic; uint quad_count = 0; if (ident < cubics.count) { cubic = cubics.data[ident]; quad_count = EstimateQuadraticCount(cubic, config.cubic_accuracy); scratch_count[ident] = quad_count; } barrier(); uint offset = 0; if (quad_count > 0) { scratch_sum[ident] = subgroupExclusiveAdd(scratch_count[ident]); offset = ComputePosition(ident) + quads.count; } barrier(); if (quad_count > 0) { atomicAdd(quads.count, quad_count); cubic_ranges[ident] = uvec2(offset, quad_count); for (uint i = 0; i < quad_count; i++) { quads.data[offset + i] = GenerateQuadraticFromCubic(cubic, i, quad_count); } } } void ProcessQuad(uint ident) { QuadData quad; QuadDecomposition decomposition; if (ident < quads.count) { quad = quads.data[ident]; decomposition = DecomposeQuad(quad, config.quad_tolerance); scratch_count[ident] = decomposition.line_count; } barrier(); uint offset = 0; if (decomposition.line_count > 0) { scratch_sum[ident] = subgroupExclusiveAdd(scratch_count[ident]); offset = ComputePosition(ident) + lines.count; } barrier(); if (decomposition.line_count > 0) { atomicAdd(lines.count, decomposition.line_count); quad_ranges[ident] = uvec2(offset, decomposition.line_count); vec2 last_point = quad.p1; for (uint i = 1; i < decomposition.line_count; i++) { LineData line = LineData(last_point, GenerateLineFromQuad(quad, i, decomposition)); last_point = line.p2; lines.data[offset + i - 1] = line; } lines.data[offset + decomposition.line_count - 1] = LineData(last_point, quad.p2); } } void ProcessLine(uint ident) { if (ident == 0) { polyline.count = lines.count + 1; } PathComponent component; uvec2 range = uvec2(0, 0); if (ident < components.count) { component = components.data[ident]; if (component.count == 4) { // Determine location in quads uvec2 quad_range = cubic_ranges[component.index]; uvec2 end_range = quad_ranges[quad_range.x + quad_range.y - 1]; range.x = quad_ranges[quad_range.x].x; range.y = end_range.x + end_range.y - range.x; } else if (component.count == 3) { range = quad_ranges[component.index]; } else if (component.count == 2) { range = uvec2(component.index, 1); } scratch_count[ident] = range.y; } barrier(); if (ident < components.count) { scratch_sum[ident] = subgroupExclusiveAdd(scratch_count[ident]); uint offset = ComputePosition(ident); polyline.data[offset] = lines.data[range.x].p1; for (uint i = 0; i < range.y; i++) { polyline.data[offset + i + 1] = lines.data[range.x + i].p2; } } } void main() { uint ident = gl_GlobalInvocationID.x; // Turn each cubic into quads. ProcessCubic(ident); barrier(); // Turn each quad into lines. ProcessQuad(ident); barrier(); // Copy lines to the output buffer. ProcessLine(ident); }
engine/impeller/renderer/path_polyline.comp/0
{ "file_path": "engine/impeller/renderer/path_polyline.comp", "repo_id": "engine", "token_count": 1599 }
228
// 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_IMPELLER_RENDERER_RENDER_TARGET_H_ #define FLUTTER_IMPELLER_RENDERER_RENDER_TARGET_H_ #include <functional> #include <map> #include <optional> #include "flutter/fml/hash_combine.h" #include "impeller/core/allocator.h" #include "impeller/core/formats.h" #include "impeller/geometry/size.h" namespace impeller { class Context; struct RenderTargetConfig { ISize size = ISize{0, 0}; size_t mip_count = 0; bool has_msaa = false; bool has_depth_stencil = false; constexpr bool operator==(const RenderTargetConfig& o) const { return size == o.size && mip_count == o.mip_count && has_msaa == o.has_msaa && has_depth_stencil == o.has_depth_stencil; } constexpr size_t Hash() const { return fml::HashCombine(size.width, size.height, mip_count, has_msaa, has_depth_stencil); } }; class RenderTarget final { public: struct AttachmentConfig { StorageMode storage_mode; LoadAction load_action; StoreAction store_action; Color clear_color; }; struct AttachmentConfigMSAA { StorageMode storage_mode; StorageMode resolve_storage_mode; LoadAction load_action; StoreAction store_action; Color clear_color; }; static constexpr AttachmentConfig kDefaultColorAttachmentConfig = { .storage_mode = StorageMode::kDevicePrivate, .load_action = LoadAction::kClear, .store_action = StoreAction::kStore, .clear_color = Color::BlackTransparent()}; static constexpr AttachmentConfigMSAA kDefaultColorAttachmentConfigMSAA = { .storage_mode = StorageMode::kDeviceTransient, .resolve_storage_mode = StorageMode::kDevicePrivate, .load_action = LoadAction::kClear, .store_action = StoreAction::kMultisampleResolve, .clear_color = Color::BlackTransparent()}; static constexpr AttachmentConfig kDefaultStencilAttachmentConfig = { .storage_mode = StorageMode::kDeviceTransient, .load_action = LoadAction::kClear, .store_action = StoreAction::kDontCare, .clear_color = Color::BlackTransparent()}; RenderTarget(); ~RenderTarget(); bool IsValid() const; void SetupDepthStencilAttachments( const Context& context, Allocator& allocator, ISize size, bool msaa, const std::string& label = "Offscreen", RenderTarget::AttachmentConfig stencil_attachment_config = RenderTarget::kDefaultStencilAttachmentConfig, const std::shared_ptr<Texture>& depth_stencil_texture = nullptr); SampleCount GetSampleCount() const; bool HasColorAttachment(size_t index) const; ISize GetRenderTargetSize() const; std::shared_ptr<Texture> GetRenderTargetTexture() const; PixelFormat GetRenderTargetPixelFormat() const; std::optional<ISize> GetColorAttachmentSize(size_t index) const; RenderTarget& SetColorAttachment(const ColorAttachment& attachment, size_t index); RenderTarget& SetDepthAttachment(std::optional<DepthAttachment> attachment); RenderTarget& SetStencilAttachment( std::optional<StencilAttachment> attachment); size_t GetMaxColorAttacmentBindIndex() const; const std::map<size_t, ColorAttachment>& GetColorAttachments() const; const std::optional<DepthAttachment>& GetDepthAttachment() const; const std::optional<StencilAttachment>& GetStencilAttachment() const; size_t GetTotalAttachmentCount() const; void IterateAllAttachments( const std::function<bool(const Attachment& attachment)>& iterator) const; std::string ToString() const; RenderTargetConfig ToConfig() const { auto& color_attachment = GetColorAttachments().find(0)->second; return RenderTargetConfig{ .size = color_attachment.texture->GetSize(), .mip_count = color_attachment.texture->GetMipCount(), .has_msaa = color_attachment.resolve_texture != nullptr, .has_depth_stencil = depth_.has_value() && stencil_.has_value()}; } private: std::map<size_t, ColorAttachment> colors_; std::optional<DepthAttachment> depth_; std::optional<StencilAttachment> stencil_; }; /// @brief a wrapper around the impeller [Allocator] instance that can be used /// to provide caching of allocated render target textures. class RenderTargetAllocator { public: explicit RenderTargetAllocator(std::shared_ptr<Allocator> allocator); virtual ~RenderTargetAllocator() = default; virtual RenderTarget CreateOffscreen( const Context& context, ISize size, int mip_count, const std::string& label = "Offscreen", RenderTarget::AttachmentConfig color_attachment_config = RenderTarget::kDefaultColorAttachmentConfig, std::optional<RenderTarget::AttachmentConfig> stencil_attachment_config = RenderTarget::kDefaultStencilAttachmentConfig, const std::shared_ptr<Texture>& existing_color_texture = nullptr, const std::shared_ptr<Texture>& existing_depth_stencil_texture = nullptr); virtual RenderTarget CreateOffscreenMSAA( const Context& context, ISize size, int mip_count, const std::string& label = "Offscreen MSAA", RenderTarget::AttachmentConfigMSAA color_attachment_config = RenderTarget::kDefaultColorAttachmentConfigMSAA, std::optional<RenderTarget::AttachmentConfig> stencil_attachment_config = RenderTarget::kDefaultStencilAttachmentConfig, const std::shared_ptr<Texture>& existing_color_msaa_texture = nullptr, const std::shared_ptr<Texture>& existing_color_resolve_texture = nullptr, const std::shared_ptr<Texture>& existing_depth_stencil_texture = nullptr); /// @brief Mark the beginning of a frame workload. /// /// This may be used to reset any tracking state on whether or not a /// particular texture instance is still in use. virtual void Start(); /// @brief Mark the end of a frame workload. /// /// This may be used to deallocate any unused textures. virtual void End(); private: std::shared_ptr<Allocator> allocator_; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_RENDER_TARGET_H_
engine/impeller/renderer/render_target.h/0
{ "file_path": "engine/impeller/renderer/render_target.h", "repo_id": "engine", "token_count": 2200 }
229
// 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 "impeller/renderer/surface.h" #include "flutter/fml/logging.h" namespace impeller { Surface::Surface() : Surface(RenderTarget{}) {} Surface::Surface(const RenderTarget& target_desc) : desc_(target_desc) { if (auto size = desc_.GetColorAttachmentSize(0u); size.has_value()) { size_ = size.value(); } else { return; } is_valid_ = true; } Surface::~Surface() = default; const ISize& Surface::GetSize() const { return size_; } bool Surface::IsValid() const { return is_valid_; } const RenderTarget& Surface::GetTargetRenderPassDescriptor() const { return desc_; } bool Surface::Present() const { return false; }; } // namespace impeller
engine/impeller/renderer/surface.cc/0
{ "file_path": "engine/impeller/renderer/surface.cc", "repo_id": "engine", "token_count": 283 }
230
// 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. namespace impeller.fb; enum Stage:byte { kVertex, kFragment, kCompute, } // The subset of impeller::ShaderType that may be used for uniform bindings. // kStruct is only supported for Impeller Vulkan. // kFloat encompases multiple float-based types e.g. vec2. enum UniformDataType:uint32 { kFloat, kSampledImage, kStruct, } // A struct is made up solely of 4 byte floats and 4-byte paddings between // them. // This enum describes whether a particular byte is a float or padding. enum StructByteType:uint8 { kPadding = 0, kFloat = 1, } table UniformDescription { name: string; location: uint64; type: UniformDataType; bit_width: uint64; rows: uint64; columns: uint64; array_elements: uint64; struct_layout: [StructByteType]; struct_float_count: uint64; } // The subset of impeller::ShaderType that may be used for vertex attributes. enum InputDataType:uint32 { kBoolean, kSignedByte, kUnsignedByte, kSignedShort, kUnsignedShort, kSignedInt, kUnsignedInt, kSignedInt64, kUnsignedInt64, kFloat, kDouble, } // This contains the same attribute reflection data as // impeller::ShaderStageIOSlot. table StageInput { name: string; location: uint64; set: uint64; binding: uint64; type: InputDataType; bit_width: uint64; vec_size: uint64; columns: uint64; offset: uint64; } table RuntimeStage { stage: Stage; entrypoint: string; inputs: [StageInput]; uniforms: [UniformDescription]; shader: [ubyte]; struct_byte_length: uint64; float_count: uint64; } table RuntimeStages { sksl: RuntimeStage; metal: RuntimeStage; opengles: RuntimeStage; vulkan: RuntimeStage; }
engine/impeller/runtime_stage/runtime_stage_types.fbs/0
{ "file_path": "engine/impeller/runtime_stage/runtime_stage_types.fbs", "repo_id": "engine", "token_count": 616 }
231
// 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_IMPELLER_SCENE_GEOMETRY_H_ #define FLUTTER_IMPELLER_SCENE_GEOMETRY_H_ #include <memory> #include "flutter/fml/macros.h" #include "impeller/core/allocator.h" #include "impeller/core/device_buffer.h" #include "impeller/core/host_buffer.h" #include "impeller/core/vertex_buffer.h" #include "impeller/geometry/matrix.h" #include "impeller/geometry/vector.h" #include "impeller/renderer/command.h" #include "impeller/renderer/render_pass.h" #include "impeller/scene/importer/scene_flatbuffers.h" #include "impeller/scene/pipeline_key.h" #include "impeller/scene/scene_context.h" namespace impeller { namespace scene { class CuboidGeometry; class UnskinnedVertexBufferGeometry; class Geometry { public: virtual ~Geometry(); static std::shared_ptr<CuboidGeometry> MakeCuboid(Vector3 size); static std::shared_ptr<Geometry> MakeVertexBuffer(VertexBuffer vertex_buffer, bool is_skinned); static std::shared_ptr<Geometry> MakeFromFlatbuffer( const fb::MeshPrimitive& mesh, Allocator& allocator); virtual GeometryType GetGeometryType() const = 0; virtual VertexBuffer GetVertexBuffer(Allocator& allocator) const = 0; virtual void BindToCommand(const SceneContext& scene_context, HostBuffer& buffer, const Matrix& transform, RenderPass& pass) const = 0; virtual void SetJointsTexture(const std::shared_ptr<Texture>& texture); }; class CuboidGeometry final : public Geometry { public: CuboidGeometry(); ~CuboidGeometry() override; void SetSize(Vector3 size); // |Geometry| GeometryType GetGeometryType() const override; // |Geometry| VertexBuffer GetVertexBuffer(Allocator& allocator) const override; // |Geometry| void BindToCommand(const SceneContext& scene_context, HostBuffer& buffer, const Matrix& transform, RenderPass& pass) const override; private: Vector3 size_; CuboidGeometry(const CuboidGeometry&) = delete; CuboidGeometry& operator=(const CuboidGeometry&) = delete; }; class UnskinnedVertexBufferGeometry final : public Geometry { public: UnskinnedVertexBufferGeometry(); ~UnskinnedVertexBufferGeometry() override; void SetVertexBuffer(VertexBuffer vertex_buffer); // |Geometry| GeometryType GetGeometryType() const override; // |Geometry| VertexBuffer GetVertexBuffer(Allocator& allocator) const override; // |Geometry| void BindToCommand(const SceneContext& scene_context, HostBuffer& buffer, const Matrix& transform, RenderPass& pass) const override; private: VertexBuffer vertex_buffer_; UnskinnedVertexBufferGeometry(const UnskinnedVertexBufferGeometry&) = delete; UnskinnedVertexBufferGeometry& operator=( const UnskinnedVertexBufferGeometry&) = delete; }; class SkinnedVertexBufferGeometry final : public Geometry { public: SkinnedVertexBufferGeometry(); ~SkinnedVertexBufferGeometry() override; void SetVertexBuffer(VertexBuffer vertex_buffer); // |Geometry| GeometryType GetGeometryType() const override; // |Geometry| VertexBuffer GetVertexBuffer(Allocator& allocator) const override; // |Geometry| void BindToCommand(const SceneContext& scene_context, HostBuffer& buffer, const Matrix& transform, RenderPass& pass) const override; // |Geometry| void SetJointsTexture(const std::shared_ptr<Texture>& texture) override; private: VertexBuffer vertex_buffer_; std::shared_ptr<Texture> joints_texture_; SkinnedVertexBufferGeometry(const SkinnedVertexBufferGeometry&) = delete; SkinnedVertexBufferGeometry& operator=(const SkinnedVertexBufferGeometry&) = delete; }; } // namespace scene } // namespace impeller #endif // FLUTTER_IMPELLER_SCENE_GEOMETRY_H_
engine/impeller/scene/geometry.h/0
{ "file_path": "engine/impeller/scene/geometry.h", "repo_id": "engine", "token_count": 1548 }
232
// 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 "impeller/scene/mesh.h" #include <memory> #include <optional> #include "impeller/base/validation.h" #include "impeller/scene/material.h" #include "impeller/scene/pipeline_key.h" #include "impeller/scene/scene_encoder.h" namespace impeller { namespace scene { Mesh::Mesh() = default; Mesh::~Mesh() = default; void Mesh::AddPrimitive(Primitive mesh) { if (mesh.geometry == nullptr) { VALIDATION_LOG << "Mesh geometry cannot be null."; } if (mesh.material == nullptr) { VALIDATION_LOG << "Mesh material cannot be null."; } primitives_.push_back(std::move(mesh)); } std::vector<Mesh::Primitive>& Mesh::GetPrimitives() { return primitives_; } bool Mesh::Render(SceneEncoder& encoder, const Matrix& transform, const std::shared_ptr<Texture>& joints) const { for (const auto& mesh : primitives_) { mesh.geometry->SetJointsTexture(joints); SceneCommand command = { .label = "Mesh Primitive", .transform = transform, .geometry = mesh.geometry.get(), .material = mesh.material.get(), }; encoder.Add(command); } return true; } } // namespace scene } // namespace impeller
engine/impeller/scene/mesh.cc/0
{ "file_path": "engine/impeller/scene/mesh.cc", "repo_id": "engine", "token_count": 510 }
233
// 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 "impeller/scene/skin.h" #include <cmath> #include <memory> #include <vector> #include "flutter/fml/logging.h" #include "impeller/base/allocation.h" #include "impeller/core/allocator.h" #include "impeller/scene/importer/conversions.h" namespace impeller { namespace scene { std::unique_ptr<Skin> Skin::MakeFromFlatbuffer( const fb::Skin& skin, const std::vector<std::shared_ptr<Node>>& scene_nodes) { if (!skin.joints() || !skin.inverse_bind_matrices() || skin.joints()->size() != skin.inverse_bind_matrices()->size()) { VALIDATION_LOG << "Skin data is missing joints or bind matrices."; return nullptr; } Skin result; result.joints_.reserve(skin.joints()->size()); for (auto joint : *skin.joints()) { if (joint < 0 || static_cast<size_t>(joint) > scene_nodes.size()) { VALIDATION_LOG << "Skin joint index out of range."; result.joints_.push_back(nullptr); continue; } if (scene_nodes[joint]) { scene_nodes[joint]->SetIsJoint(true); } result.joints_.push_back(scene_nodes[joint]); } result.inverse_bind_matrices_.reserve(skin.inverse_bind_matrices()->size()); for (size_t matrix_i = 0; matrix_i < skin.inverse_bind_matrices()->size(); matrix_i++) { const auto* ip_matrix = skin.inverse_bind_matrices()->Get(matrix_i); Matrix matrix = ip_matrix ? importer::ToMatrix(*ip_matrix) : Matrix(); result.inverse_bind_matrices_.push_back(matrix); // Overwrite the joint transforms with the inverse bind pose. result.joints_[matrix_i]->SetGlobalTransform(matrix.Invert()); } return std::make_unique<Skin>(std::move(result)); } Skin::Skin() = default; Skin::~Skin() = default; Skin::Skin(Skin&&) = default; Skin& Skin::operator=(Skin&&) = default; std::shared_ptr<Texture> Skin::GetJointsTexture(Allocator& allocator) { // Each joint has a matrix. 1 matrix = 16 floats. 1 pixel = 4 floats. // Therefore, each joint needs 4 pixels. auto required_pixels = joints_.size() * 4; auto dimension_size = std::max( 2u, Allocation::NextPowerOfTwoSize(std::ceil(std::sqrt(required_pixels)))); impeller::TextureDescriptor texture_descriptor; texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible; texture_descriptor.format = PixelFormat::kR32G32B32A32Float; texture_descriptor.size = {dimension_size, dimension_size}; texture_descriptor.mip_count = 1u; auto result = allocator.CreateTexture(texture_descriptor); result->SetLabel("Joints Texture"); if (!result) { FML_LOG(ERROR) << "Could not create joint texture."; return nullptr; } std::vector<Matrix> joints; joints.resize(result->GetSize().Area() / 4, Matrix()); FML_DCHECK(joints.size() >= joints_.size()); for (size_t joint_i = 0; joint_i < joints_.size(); joint_i++) { const Node* joint = joints_[joint_i].get(); if (!joint) { // When a joint is missing, just let it remain as an identity matrix. continue; } // Compute a model space matrix for the joint by walking up the bones to the // skeleton root. while (joint && joint->IsJoint()) { joints[joint_i] = joint->GetLocalTransform() * joints[joint_i]; joint = joint->GetParent(); } // Get the joint transform relative to the default pose of the bone by // incorporating the joint's inverse bind matrix. The inverse bind matrix // transforms from model space to the default pose space of the joint. The // result is a model space matrix that only captures the difference between // the joint's default pose and the joint's current pose in the scene. This // is necessary because the skinned model's vertex positions (which _define_ // the default pose) are all in model space. joints[joint_i] = joints[joint_i] * inverse_bind_matrices_[joint_i]; } if (!result->SetContents(reinterpret_cast<uint8_t*>(joints.data()), joints.size() * sizeof(Matrix))) { FML_LOG(ERROR) << "Could not set contents of joint texture."; return nullptr; } return result; } } // namespace scene } // namespace impeller
engine/impeller/scene/skin.cc/0
{ "file_path": "engine/impeller/scene/skin.cc", "repo_id": "engine", "token_count": 1534 }
234
// 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 "impeller/toolkit/android/native_window.h" namespace impeller::android { NativeWindow::NativeWindow(ANativeWindow* window) : window_(window) { if (window_.get()) { GetProcTable().ANativeWindow_acquire(window_.get()); } } NativeWindow::~NativeWindow() = default; bool NativeWindow::IsValid() const { return window_.is_valid(); } ISize NativeWindow::GetSize() const { if (!IsValid()) { return {}; } const int32_t width = ANativeWindow_getWidth(window_.get()); const int32_t height = ANativeWindow_getHeight(window_.get()); return ISize::MakeWH(std::max(width, 0), std::max(height, 0)); } ANativeWindow* NativeWindow::GetHandle() const { return window_.get(); } } // namespace impeller::android
engine/impeller/toolkit/android/native_window.cc/0
{ "file_path": "engine/impeller/toolkit/android/native_window.cc", "repo_id": "engine", "token_count": 288 }
235
// 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 "impeller/toolkit/egl/egl.h" #include "flutter/fml/logging.h" namespace impeller { namespace egl { std::function<void*(const char*)> CreateProcAddressResolver() { return [](const char* name) -> void* { return reinterpret_cast<void*>(::eglGetProcAddress(name)); }; } static const char* EGLErrorToString(EGLint error) { switch (error) { case EGL_SUCCESS: return "Success"; case EGL_NOT_INITIALIZED: return "Not Initialized"; case EGL_BAD_ACCESS: return "Bad Access"; case EGL_BAD_ALLOC: return "Bad Alloc"; case EGL_BAD_ATTRIBUTE: return "Bad Attribute"; case EGL_BAD_CONTEXT: return "Bad Context"; case EGL_BAD_CONFIG: return "Bad Config"; case EGL_BAD_CURRENT_SURFACE: return "Bad Current Surface"; case EGL_BAD_DISPLAY: return "Bad Display"; case EGL_BAD_SURFACE: return "Bad Surface"; case EGL_BAD_MATCH: return "Bad Match"; case EGL_BAD_PARAMETER: return "Bad Parameter"; case EGL_BAD_NATIVE_PIXMAP: return "Bad Native Pixmap"; case EGL_BAD_NATIVE_WINDOW: return "Bad Native Window"; case EGL_CONTEXT_LOST: return "Context Lost"; } return "Unknown"; } void LogEGLError(const char* file, int line) { const auto error = ::eglGetError(); FML_LOG(ERROR) << "EGL Error: " << EGLErrorToString(error) << " (" << error << ") in " << file << ":" << line; } } // namespace egl } // namespace impeller
engine/impeller/toolkit/egl/egl.cc/0
{ "file_path": "engine/impeller/toolkit/egl/egl.cc", "repo_id": "engine", "token_count": 694 }
236
#!/usr/bin/env vpython3 # 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 argparse import json import os import subprocess import sys # This script parses the JSON output produced by malioc about GPU cores, # and outputs it in a form that can be consumed by GN def parse_args(argv): parser = argparse.ArgumentParser( description='This script sanitizes GPU core info output from malioc', ) parser.add_argument( '--malioc', '-m', type=str, help='The path to malioc.', ) parser.add_argument( '--output', '-o', type=str, help='The output path.', ) return parser.parse_args(argv) def validate_args(args): if not args.malioc or not os.path.isfile(args.malioc): print('The --malioc argument must refer to the malioc binary.') return False return True def malioc_core_list(malioc): malioc_cores = subprocess.check_output( [malioc, '--list', '--format', 'json'], stderr=subprocess.STDOUT, ) cores_json = json.loads(malioc_cores) cores = [] for core in cores_json['cores']: cores.append(core['core']) return cores def malioc_core_info(malioc, core): malioc_info = subprocess.check_output( [malioc, '--info', '--core', core, '--format', 'json'], stderr=subprocess.STDOUT, ) info_json = json.loads(malioc_info) apis = info_json['apis'] opengles_max_version = 0 if 'opengles' in apis: opengles = apis['opengles'] if opengles['max_version'] is not None: opengles_max_version = opengles['max_version'] vulkan_max_version = 0 if 'vulkan' in apis: vulkan = apis['vulkan'] if vulkan['max_version'] is not None: vulkan_max_version = int(vulkan['max_version'] * 100) info = { 'core': core, 'opengles_max_version': opengles_max_version, 'vulkan_max_version': vulkan_max_version, } return info def main(argv): args = parse_args(argv[1:]) if not validate_args(args): return 1 infos = [] for core in malioc_core_list(args.malioc): infos.append(malioc_core_info(args.malioc, core)) if args.output: with open(args.output, 'w') as file: json.dump(infos, file, sort_keys=True) else: print(infos) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
engine/impeller/tools/malioc_cores.py/0
{ "file_path": "engine/impeller/tools/malioc_cores.py", "repo_id": "engine", "token_count": 964 }
237
// 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 "impeller/typographer/backends/stb/text_frame_stb.h" #include "impeller/typographer/font.h" namespace impeller { std::shared_ptr<TextFrame> MakeTextFrameSTB( const std::shared_ptr<TypefaceSTB>& typeface_stb, Font::Metrics metrics, const std::string& text) { TextRun run(Font(typeface_stb, metrics)); // Shape the text run using STB. The glyph positions could also be resolved // using a more advanced text shaper such as harfbuzz. float scale = stbtt_ScaleForPixelHeight( typeface_stb->GetFontInfo(), metrics.point_size * TypefaceSTB::kPointsToPixels); int ascent, descent, line_gap; stbtt_GetFontVMetrics(typeface_stb->GetFontInfo(), &ascent, &descent, &line_gap); ascent = std::round(ascent * scale); descent = std::round(descent * scale); float x = 0; for (size_t i = 0; i < text.size(); i++) { int glyph_index = stbtt_FindGlyphIndex(typeface_stb->GetFontInfo(), text[i]); int x0, y0, x1, y1; stbtt_GetGlyphBitmapBox(typeface_stb->GetFontInfo(), glyph_index, scale, scale, &x0, &y0, &x1, &y1); float y = y0; int advance_width; int left_side_bearing; stbtt_GetGlyphHMetrics(typeface_stb->GetFontInfo(), glyph_index, &advance_width, &left_side_bearing); Glyph glyph(glyph_index, Glyph::Type::kPath, Rect::MakeXYWH(0, 0, x1 - x0, y1 - y0)); run.AddGlyph(glyph, {x + (left_side_bearing * scale), y}); if (i + 1 < text.size()) { int kerning = stbtt_GetCodepointKernAdvance(typeface_stb->GetFontInfo(), text[i], text[i + 1]); x += std::round((advance_width + kerning) * scale); } } std::optional<Rect> result; for (const auto& glyph_position : run.GetGlyphPositions()) { Rect glyph_rect = Rect::MakeOriginSize( glyph_position.position + glyph_position.glyph.bounds.GetOrigin(), glyph_position.glyph.bounds.GetSize()); result = result.has_value() ? result->Union(glyph_rect) : glyph_rect; } std::vector<TextRun> runs = {run}; return std::make_shared<TextFrame>( runs, result.value_or(Rect::MakeLTRB(0, 0, 0, 0)), false); } } // namespace impeller
engine/impeller/typographer/backends/stb/text_frame_stb.cc/0
{ "file_path": "engine/impeller/typographer/backends/stb/text_frame_stb.cc", "repo_id": "engine", "token_count": 1032 }
238
// 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 "impeller/typographer/rectangle_packer.h" #include <algorithm> #include <vector> namespace impeller { // Pack rectangles and track the current silhouette // Based, in part, on Jukka Jylanki's work at http://clb.demon.fi // and ported from Skia's implementation // https://github.com/google/skia/blob/b5de4b8ae95c877a9ecfad5eab0765bc22550301/src/gpu/RectanizerSkyline.cpp class SkylineRectanglePacker final : public RectanglePacker { public: SkylineRectanglePacker(int w, int h) : RectanglePacker(w, h) { this->reset(); } ~SkylineRectanglePacker() final {} void reset() final { area_so_far_ = 0; skyline_.clear(); skyline_.push_back(SkylineSegment{0, 0, this->width()}); } bool addRect(int w, int h, IPoint16* loc) final; float percentFull() const final { return area_so_far_ / ((float)this->width() * this->height()); } private: struct SkylineSegment { int x_; int y_; int width_; }; std::vector<SkylineSegment> skyline_; int32_t area_so_far_; // Can a width x height rectangle fit in the free space represented by // the skyline segments >= 'skylineIndex'? If so, return true and fill in // 'y' with the y-location at which it fits (the x location is pulled from // 'skylineIndex's segment. bool rectangleFits(int skylineIndex, int width, int height, int* y) const; // Update the skyline structure to include a width x height rect located // at x,y. void addSkylineLevel(int skylineIndex, int x, int y, int width, int height); }; bool SkylineRectanglePacker::addRect(int width, int height, IPoint16* loc) { if ((unsigned)width > (unsigned)this->width() || (unsigned)height > (unsigned)this->height()) { return false; } // find position for new rectangle int bestWidth = this->width() + 1; int bestX = 0; int bestY = this->height() + 1; int bestIndex = -1; for (int i = 0; i < (int)skyline_.size(); ++i) { int y; if (this->rectangleFits(i, width, height, &y)) { // minimize y position first, then width of skyline if (y < bestY || (y == bestY && skyline_[i].width_ < bestWidth)) { bestIndex = i; bestWidth = skyline_[i].width_; bestX = skyline_[i].x_; bestY = y; } } } // add rectangle to skyline if (-1 != bestIndex) { this->addSkylineLevel(bestIndex, bestX, bestY, width, height); loc->x_ = bestX; loc->y_ = bestY; area_so_far_ += width * height; return true; } loc->x_ = 0; loc->y_ = 0; return false; } bool SkylineRectanglePacker::rectangleFits(int skylineIndex, int width, int height, int* ypos) const { int x = skyline_[skylineIndex].x_; if (x + width > this->width()) { return false; } int widthLeft = width; int i = skylineIndex; int y = skyline_[skylineIndex].y_; while (widthLeft > 0 && i < (int)skyline_.size()) { y = std::max(y, skyline_[i].y_); if (y + height > this->height()) { return false; } widthLeft -= skyline_[i].width_; ++i; } *ypos = y; return true; } void SkylineRectanglePacker::addSkylineLevel(int skylineIndex, int x, int y, int width, int height) { SkylineSegment newSegment; newSegment.x_ = x; newSegment.y_ = y + height; newSegment.width_ = width; skyline_.insert(std::next(skyline_.begin(), skylineIndex), newSegment); FML_DCHECK(newSegment.x_ + newSegment.width_ <= this->width()); FML_DCHECK(newSegment.y_ <= this->height()); // delete width of the new skyline segment from following ones for (int i = skylineIndex + 1; i < (int)skyline_.size(); ++i) { // The new segment subsumes all or part of skyline_[i] FML_DCHECK(skyline_[i - 1].x_ <= skyline_[i].x_); if (skyline_[i].x_ < skyline_[i - 1].x_ + skyline_[i - 1].width_) { int shrink = skyline_[i - 1].x_ + skyline_[i - 1].width_ - skyline_[i].x_; skyline_[i].x_ += shrink; skyline_[i].width_ -= shrink; if (skyline_[i].width_ <= 0) { // fully consumed, remove item at index i skyline_.erase(std::next(skyline_.begin(), i)); --i; } else { // only partially consumed break; } } else { break; } } // merge skyline_s for (int i = 0; i < ((int)skyline_.size()) - 1; ++i) { if (skyline_[i].y_ == skyline_[i + 1].y_) { skyline_[i].width_ += skyline_[i + 1].width_; skyline_.erase(std::next(skyline_.begin(), i)); --i; } } } std::unique_ptr<RectanglePacker> RectanglePacker::Factory(int width, int height) { return std::make_unique<SkylineRectanglePacker>(width, height); } } // namespace impeller
engine/impeller/typographer/rectangle_packer.cc/0
{ "file_path": "engine/impeller/typographer/rectangle_packer.cc", "repo_id": "engine", "token_count": 2204 }
239
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_GPU_CONTEXT_H_ #define FLUTTER_LIB_GPU_CONTEXT_H_ #include "dart_api.h" #include "flutter/lib/gpu/export.h" #include "flutter/lib/ui/dart_wrapper.h" #include "impeller/renderer/context.h" namespace flutter { namespace gpu { class Context : public RefCountedDartWrappable<Context> { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(Context); public: static void SetOverrideContext(std::shared_ptr<impeller::Context> context); static std::shared_ptr<impeller::Context> GetOverrideContext(); static std::shared_ptr<impeller::Context> GetDefaultContext( std::optional<std::string>& out_error); explicit Context(std::shared_ptr<impeller::Context> context); ~Context() override; std::shared_ptr<impeller::Context> GetContext(); private: /// An Impeller context that takes precedent over the IO state context when /// set. This is used to inject the context when running with the Impeller /// playground, which doesn't instantiate an Engine instance. static std::shared_ptr<impeller::Context> default_context_; std::shared_ptr<impeller::Context> context_; FML_DISALLOW_COPY_AND_ASSIGN(Context); }; } // namespace gpu } // namespace flutter //---------------------------------------------------------------------------- /// Exports /// extern "C" { FLUTTER_GPU_EXPORT extern Dart_Handle InternalFlutterGpu_Context_InitializeDefault( Dart_Handle wrapper); FLUTTER_GPU_EXPORT extern int InternalFlutterGpu_Context_GetBackendType( flutter::gpu::Context* wrapper); FLUTTER_GPU_EXPORT extern int InternalFlutterGpu_Context_GetDefaultColorFormat( flutter::gpu::Context* wrapper); FLUTTER_GPU_EXPORT extern int InternalFlutterGpu_Context_GetDefaultStencilFormat( flutter::gpu::Context* wrapper); FLUTTER_GPU_EXPORT extern int InternalFlutterGpu_Context_GetDefaultDepthStencilFormat( flutter::gpu::Context* wrapper); } // extern "C" #endif // FLUTTER_LIB_GPU_CONTEXT_H_
engine/lib/gpu/context.h/0
{ "file_path": "engine/lib/gpu/context.h", "repo_id": "engine", "token_count": 698 }
240
// 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. // ignore_for_file: public_member_api_docs part of flutter_gpu; base class ColorAttachment { ColorAttachment({ this.loadAction = LoadAction.clear, this.storeAction = StoreAction.store, this.clearValue = const ui.Color(0x00000000), required this.texture, this.resolveTexture = null, }); LoadAction loadAction; StoreAction storeAction; ui.Color clearValue; Texture texture; Texture? resolveTexture; } base class DepthStencilAttachment { DepthStencilAttachment({ this.depthLoadAction = LoadAction.clear, this.depthStoreAction = StoreAction.dontCare, this.depthClearValue = 0.0, this.stencilLoadAction = LoadAction.clear, this.stencilStoreAction = StoreAction.dontCare, this.stencilClearValue = 0, required this.texture, }); LoadAction depthLoadAction; StoreAction depthStoreAction; double depthClearValue; LoadAction stencilLoadAction; StoreAction stencilStoreAction; int stencilClearValue; Texture texture; } base class ColorBlendEquation { ColorBlendEquation({ this.colorBlendOperation = BlendOperation.add, this.sourceColorBlendFactor = BlendFactor.one, this.destinationColorBlendFactor = BlendFactor.oneMinusSourceAlpha, this.alphaBlendOperation = BlendOperation.add, this.sourceAlphaBlendFactor = BlendFactor.one, this.destinationAlphaBlendFactor = BlendFactor.oneMinusSourceAlpha, }); BlendOperation colorBlendOperation; BlendFactor sourceColorBlendFactor; BlendFactor destinationColorBlendFactor; BlendOperation alphaBlendOperation; BlendFactor sourceAlphaBlendFactor; BlendFactor destinationAlphaBlendFactor; } base class SamplerOptions { SamplerOptions({ this.minFilter = MinMagFilter.nearest, this.magFilter = MinMagFilter.nearest, this.mipFilter = MipFilter.nearest, this.widthAddressMode = SamplerAddressMode.clampToEdge, this.heightAddressMode = SamplerAddressMode.clampToEdge, }); MinMagFilter minFilter; MinMagFilter magFilter; MipFilter mipFilter; SamplerAddressMode widthAddressMode; SamplerAddressMode heightAddressMode; } base class RenderTarget { const RenderTarget( {this.colorAttachments = const <ColorAttachment>[], this.depthStencilAttachment}); RenderTarget.singleColor(ColorAttachment colorAttachment, {DepthStencilAttachment? depthStencilAttachment}) : this( colorAttachments: [colorAttachment], depthStencilAttachment: depthStencilAttachment); final List<ColorAttachment> colorAttachments; final DepthStencilAttachment? depthStencilAttachment; } base class RenderPass extends NativeFieldWrapperClass1 { /// Creates a new RenderPass. RenderPass._(CommandBuffer commandBuffer, RenderTarget renderTarget) { _initialize(); String? error; for (final (index, color) in renderTarget.colorAttachments.indexed) { error = _setColorAttachment( index, color.loadAction.index, color.storeAction.index, color.clearValue.value, color.texture, color.resolveTexture); if (error != null) { throw Exception(error); } } if (renderTarget.depthStencilAttachment != null) { final ds = renderTarget.depthStencilAttachment!; error = _setDepthStencilAttachment( ds.depthLoadAction.index, ds.depthStoreAction.index, ds.depthClearValue, ds.stencilLoadAction.index, ds.stencilStoreAction.index, ds.stencilClearValue, ds.texture); if (error != null) { throw Exception(error); } } error = _begin(commandBuffer); if (error != null) { throw Exception(error); } } void bindPipeline(RenderPipeline pipeline) { _bindPipeline(pipeline); } void bindVertexBuffer(BufferView bufferView, int vertexCount) { bufferView.buffer._bindAsVertexBuffer( this, bufferView.offsetInBytes, bufferView.lengthInBytes, vertexCount); } void bindIndexBuffer( BufferView bufferView, IndexType indexType, int indexCount) { bufferView.buffer._bindAsIndexBuffer(this, bufferView.offsetInBytes, bufferView.lengthInBytes, indexType, indexCount); } void bindUniform(UniformSlot slot, BufferView bufferView) { bool success = bufferView.buffer._bindAsUniform( this, slot, bufferView.offsetInBytes, bufferView.lengthInBytes); if (!success) { throw Exception("Failed to bind uniform"); } } void bindTexture(UniformSlot slot, Texture texture, {SamplerOptions? sampler}) { if (sampler == null) { sampler = SamplerOptions(); } bool success = _bindTexture( slot.shader, slot.uniformName, texture, sampler.minFilter.index, sampler.magFilter.index, sampler.mipFilter.index, sampler.widthAddressMode.index, sampler.heightAddressMode.index); if (!success) { throw Exception("Failed to bind texture"); } } void clearBindings() { _clearBindings(); } void setColorBlendEnable(bool enable, {int colorAttachmentIndex = 0}) { _setColorBlendEnable(colorAttachmentIndex, enable); } void setColorBlendEquation(ColorBlendEquation equation, {int colorAttachmentIndex = 0}) { _setColorBlendEquation( colorAttachmentIndex, equation.colorBlendOperation.index, equation.sourceColorBlendFactor.index, equation.destinationColorBlendFactor.index, equation.alphaBlendOperation.index, equation.sourceAlphaBlendFactor.index, equation.destinationAlphaBlendFactor.index); } void setDepthWriteEnable(bool enable) { _setDepthWriteEnable(enable); } void setDepthCompareOperation(CompareFunction compareFunction) { _setDepthCompareOperation(compareFunction.index); } void draw() { if (!_draw()) { throw Exception("Failed to append draw"); } } /// Wrap with native counterpart. @Native<Void Function(Handle)>( symbol: 'InternalFlutterGpu_RenderPass_Initialize') external void _initialize(); @Native< Handle Function(Pointer<Void>, Int, Int, Int, Int, Pointer<Void>, Handle)>(symbol: 'InternalFlutterGpu_RenderPass_SetColorAttachment') external String? _setColorAttachment( int colorAttachmentIndex, int loadAction, int storeAction, int clearColor, Texture texture, Texture? resolveTexture); @Native< Handle Function( Pointer<Void>, Int, Int, Float, Int, Int, Int, Pointer<Void>)>( symbol: 'InternalFlutterGpu_RenderPass_SetDepthStencilAttachment') external String? _setDepthStencilAttachment( int depthLoadAction, int depthStoreAction, double depthClearValue, int stencilLoadAction, int stencilStoreAction, int stencilClearValue, Texture texture); @Native<Handle Function(Pointer<Void>, Pointer<Void>)>( symbol: 'InternalFlutterGpu_RenderPass_Begin') external String? _begin(CommandBuffer commandBuffer); @Native<Void Function(Pointer<Void>, Pointer<Void>)>( symbol: 'InternalFlutterGpu_RenderPass_BindPipeline') external void _bindPipeline(RenderPipeline pipeline); @Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int)>( symbol: 'InternalFlutterGpu_RenderPass_BindVertexBufferDevice') external void _bindVertexBufferDevice(DeviceBuffer buffer, int offsetInBytes, int lengthInBytes, int vertexCount); @Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int)>( symbol: 'InternalFlutterGpu_RenderPass_BindVertexBufferHost') external void _bindVertexBufferHost( HostBuffer buffer, int offsetInBytes, int lengthInBytes, int vertexCount); @Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int, Int)>( symbol: 'InternalFlutterGpu_RenderPass_BindIndexBufferDevice') external void _bindIndexBufferDevice(DeviceBuffer buffer, int offsetInBytes, int lengthInBytes, int indexType, int indexCount); @Native<Void Function(Pointer<Void>, Pointer<Void>, Int, Int, Int, Int)>( symbol: 'InternalFlutterGpu_RenderPass_BindIndexBufferHost') external void _bindIndexBufferHost(HostBuffer buffer, int offsetInBytes, int lengthInBytes, int indexType, int indexCount); @Native< Bool Function(Pointer<Void>, Pointer<Void>, Handle, Pointer<Void>, Int, Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindUniformDevice') external bool _bindUniformDevice(Shader shader, String uniformName, DeviceBuffer buffer, int offsetInBytes, int lengthInBytes); @Native< Bool Function(Pointer<Void>, Pointer<Void>, Handle, Pointer<Void>, Int, Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindUniformHost') external bool _bindUniformHost(Shader shader, String uniformName, HostBuffer buffer, int offsetInBytes, int lengthInBytes); @Native< Bool Function( Pointer<Void>, Pointer<Void>, Handle, Pointer<Void>, Int, Int, Int, Int, Int)>(symbol: 'InternalFlutterGpu_RenderPass_BindTexture') external bool _bindTexture( Shader shader, String uniformName, Texture texture, int minFilter, int magFilter, int mipFilter, int widthAddressMode, int heightAddressMode); @Native<Void Function(Pointer<Void>)>( symbol: 'InternalFlutterGpu_RenderPass_ClearBindings') external void _clearBindings(); @Native<Void Function(Pointer<Void>, Int, Bool)>( symbol: 'InternalFlutterGpu_RenderPass_SetColorBlendEnable') external void _setColorBlendEnable(int colorAttachmentIndex, bool enable); @Native<Void Function(Pointer<Void>, Int, Int, Int, Int, Int, Int, Int)>( symbol: 'InternalFlutterGpu_RenderPass_SetColorBlendEquation') external void _setColorBlendEquation( int colorAttachmentIndex, int colorBlendOperation, int sourceColorBlendFactor, int destinationColorBlendFactor, int alphaBlendOperation, int sourceAlphaBlendFactor, int destinationAlphaBlendFactor); @Native<Void Function(Pointer<Void>, Bool)>( symbol: 'InternalFlutterGpu_RenderPass_SetDepthWriteEnable') external void _setDepthWriteEnable(bool enable); @Native<Void Function(Pointer<Void>, Int)>( symbol: 'InternalFlutterGpu_RenderPass_SetDepthCompareOperation') external void _setDepthCompareOperation(int compareOperation); @Native<Bool Function(Pointer<Void>)>( symbol: 'InternalFlutterGpu_RenderPass_Draw') external bool _draw(); }
engine/lib/gpu/lib/src/render_pass.dart/0
{ "file_path": "engine/lib/gpu/lib/src/render_pass.dart", "repo_id": "engine", "token_count": 3901 }
241
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_GPU_SMOKETEST_H_ #define FLUTTER_LIB_GPU_SMOKETEST_H_ #include <cstdint> #include "flutter/lib/gpu/export.h" #include "flutter/lib/ui/dart_wrapper.h" #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/tonic/dart_state.h" #include "third_party/tonic/dart_wrapper_info.h" namespace flutter { // TODO(131346): Remove this once we migrate the Dart GPU API into this space. class FlutterGpuTestClass : public RefCountedDartWrappable<FlutterGpuTestClass> { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(FlutterGpuTestClass); public: ~FlutterGpuTestClass() override; }; } // namespace flutter //---------------------------------------------------------------------------- /// Exports /// extern "C" { // TODO(131346): Remove this once we migrate the Dart GPU API into this space. FLUTTER_GPU_EXPORT extern uint32_t InternalFlutterGpuTestProc(); // TODO(131346): Remove this once we migrate the Dart GPU API into this space. FLUTTER_GPU_EXPORT extern Dart_Handle InternalFlutterGpuTestProcWithCallback(Dart_Handle callback); // TODO(131346): Remove this once we migrate the Dart GPU API into this space. FLUTTER_GPU_EXPORT extern void InternalFlutterGpuTestClass_Create(Dart_Handle wrapper); // TODO(131346): Remove this once we migrate the Dart GPU API into this space. FLUTTER_GPU_EXPORT extern void InternalFlutterGpuTestClass_Method( flutter::FlutterGpuTestClass* self, int something); } // extern "C" #endif // FLUTTER_LIB_GPU_SMOKETEST_H_
engine/lib/gpu/smoketest.h/0
{ "file_path": "engine/lib/gpu/smoketest.h", "repo_id": "engine", "token_count": 578 }
242
// 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. part of dart.ui; /// An opaque object representing a composited scene. /// /// To create a Scene object, use a [SceneBuilder]. /// /// Scene objects can be displayed on the screen using the [FlutterView.render] /// method. abstract class Scene { /// Synchronously creates a handle to an image from this scene. /// /// {@macro dart.ui.painting.Picture.toImageSync} Image toImageSync(int width, int height); /// Creates a raster image representation of the current state of the scene. /// /// This is a slow operation that is performed on a background thread. /// /// Callers must dispose the [Image] when they are done with it. If the result /// will be shared with other methods or classes, [Image.clone] should be used /// and each handle created must be disposed. Future<Image> toImage(int width, int height); /// Releases the resources used by this scene. /// /// After calling this function, the scene is cannot be used further. /// /// This can't be a leaf call because the native function calls Dart API /// (Dart_SetNativeInstanceField). void dispose(); } @pragma('vm:entry-point') base class _NativeScene extends NativeFieldWrapperClass1 implements Scene { /// This class is created by the engine, and should not be instantiated /// or extended directly. /// /// To create a Scene object, use a [SceneBuilder]. @pragma('vm:entry-point') _NativeScene._(); @override Image toImageSync(int width, int height) { if (width <= 0 || height <= 0) { throw Exception('Invalid image dimensions.'); } final _Image image = _Image._(); final String? result = _toImageSync(width, height, image); if (result != null) { throw PictureRasterizationException._(result); } return Image._(image, image.width, image.height); } @Native<Handle Function(Pointer<Void>, Uint32, Uint32, Handle)>(symbol: 'Scene::toImageSync') external String? _toImageSync(int width, int height, _Image outImage); @override Future<Image> toImage(int width, int height) { if (width <= 0 || height <= 0) { throw Exception('Invalid image dimensions.'); } return _futurize((_Callback<Image?> callback) => _toImage(width, height, (_Image? image) { if (image == null) { callback(null); } else { callback(Image._(image, image.width, image.height)); } }), ); } @Native<Handle Function(Pointer<Void>, Uint32, Uint32, Handle)>(symbol: 'Scene::toImage') external String? _toImage(int width, int height, _Callback<_Image?> callback); @override @Native<Void Function(Pointer<Void>)>(symbol: 'Scene::dispose') external void dispose(); @override String toString() => 'Scene'; } // Lightweight wrapper of a native layer object. // // This is used to provide a typed API for engine layers to prevent // incompatible layers from being passed to [SceneBuilder]'s push methods. // For example, this prevents a layer returned from `pushOpacity` from being // passed as `oldLayer` to `pushTransform`. This is achieved by having one // concrete subclass of this class per push method. abstract class _EngineLayerWrapper implements EngineLayer { _EngineLayerWrapper._(EngineLayer nativeLayer) : _nativeLayer = nativeLayer; EngineLayer? _nativeLayer; @override void dispose() { assert(_nativeLayer != null, 'Object disposed'); _nativeLayer!.dispose(); assert(() { _nativeLayer = null; return true; }()); } // Children of this layer. // // Null if this layer has no children. This field is populated only in debug // mode. List<_EngineLayerWrapper>? _debugChildren; // Whether this layer was used as `oldLayer` in a past frame. // // It is illegal to use a layer object again after it is passed as an // `oldLayer` argument. bool _debugWasUsedAsOldLayer = false; bool _debugCheckNotUsedAsOldLayer() { // The hashCode formatting should match shortHash in the framework assert( !_debugWasUsedAsOldLayer, 'Layer $runtimeType#${hashCode.toUnsigned(20).toRadixString(16).padLeft(5, '0')} was previously used as oldLayer.\n' 'Once a layer is used as oldLayer, it may not be used again. Instead, ' 'after calling one of the SceneBuilder.push* methods and passing an oldLayer ' 'to it, use the layer returned by the method as oldLayer in subsequent ' 'frames.'); return true; } } /// An opaque handle to a transform engine layer. /// /// Instances of this class are created by [SceneBuilder.pushTransform]. /// /// {@template dart.ui.sceneBuilder.oldLayerCompatibility} /// `oldLayer` parameter in [SceneBuilder] methods only accepts objects created /// by the engine. [SceneBuilder] will throw an [AssertionError] if you pass it /// a custom implementation of this class. /// {@endtemplate} class TransformEngineLayer extends _EngineLayerWrapper { TransformEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to an offset engine layer. /// /// Instances of this class are created by [SceneBuilder.pushOffset]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class OffsetEngineLayer extends _EngineLayerWrapper { OffsetEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to a clip rect engine layer. /// /// Instances of this class are created by [SceneBuilder.pushClipRect]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class ClipRectEngineLayer extends _EngineLayerWrapper { ClipRectEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to a clip rounded rect engine layer. /// /// Instances of this class are created by [SceneBuilder.pushClipRRect]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class ClipRRectEngineLayer extends _EngineLayerWrapper { ClipRRectEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to a clip path engine layer. /// /// Instances of this class are created by [SceneBuilder.pushClipPath]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class ClipPathEngineLayer extends _EngineLayerWrapper { ClipPathEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to an opacity engine layer. /// /// Instances of this class are created by [SceneBuilder.pushOpacity]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class OpacityEngineLayer extends _EngineLayerWrapper { OpacityEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to a color filter engine layer. /// /// Instances of this class are created by [SceneBuilder.pushColorFilter]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class ColorFilterEngineLayer extends _EngineLayerWrapper { ColorFilterEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to an image filter engine layer. /// /// Instances of this class are created by [SceneBuilder.pushImageFilter]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class ImageFilterEngineLayer extends _EngineLayerWrapper { ImageFilterEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to a backdrop filter engine layer. /// /// Instances of this class are created by [SceneBuilder.pushBackdropFilter]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class BackdropFilterEngineLayer extends _EngineLayerWrapper { BackdropFilterEngineLayer._(super.nativeLayer) : super._(); } /// An opaque handle to a shader mask engine layer. /// /// Instances of this class are created by [SceneBuilder.pushShaderMask]. /// /// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} class ShaderMaskEngineLayer extends _EngineLayerWrapper { ShaderMaskEngineLayer._(super.nativeLayer) : super._(); } /// Builds a [Scene] containing the given visuals. /// /// A [Scene] can then be rendered using [FlutterView.render]. /// /// To draw graphical operations onto a [Scene], first create a /// [Picture] using a [PictureRecorder] and a [Canvas], and then add /// it to the scene using [addPicture]. abstract class SceneBuilder { factory SceneBuilder() = _NativeSceneBuilder; /// Pushes a transform operation onto the operation stack. /// /// The objects are transformed by the given matrix before rasterization. /// /// {@template dart.ui.sceneBuilder.oldLayer} /// If `oldLayer` is not null the engine will attempt to reuse the resources /// allocated for the old layer when rendering the new layer. This is purely /// an optimization. It has no effect on the correctness of rendering. /// {@endtemplate} /// /// {@template dart.ui.sceneBuilder.oldLayerVsRetained} /// Passing a layer to [addRetained] or as `oldLayer` argument to a push /// method counts as _usage_. A layer can be used no more than once in a scene. /// For example, it may not be passed simultaneously to two push methods, or /// to a push method and to `addRetained`. /// /// When a layer is passed to [addRetained] all descendant layers are also /// considered as used in this scene. The same single-usage restriction /// applies to descendants. /// /// When a layer is passed as an `oldLayer` argument to a push method, it may /// no longer be used in subsequent frames. If you would like to continue /// reusing the resources associated with the layer, store the layer object /// returned by the push method and use that in the next frame instead of the /// original object. /// {@endtemplate} /// /// See [pop] for details about the operation stack. TransformEngineLayer pushTransform( Float64List matrix4, { TransformEngineLayer? oldLayer, }); /// Pushes an offset operation onto the operation stack. /// /// This is equivalent to [pushTransform] with a matrix with only translation. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack. OffsetEngineLayer pushOffset( double dx, double dy, { OffsetEngineLayer? oldLayer, }); /// Pushes a rectangular clip operation onto the operation stack. /// /// Rasterization outside the given rectangle is discarded. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack, and [Clip] for different clip modes. /// By default, the clip will be anti-aliased (clip = [Clip.antiAlias]). ClipRectEngineLayer pushClipRect( Rect rect, { Clip clipBehavior = Clip.antiAlias, ClipRectEngineLayer? oldLayer, }); /// Pushes a rounded-rectangular clip operation onto the operation stack. /// /// Rasterization outside the given rounded rectangle is discarded. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack, and [Clip] for different clip modes. /// By default, the clip will be anti-aliased (clip = [Clip.antiAlias]). ClipRRectEngineLayer pushClipRRect( RRect rrect, { Clip clipBehavior = Clip.antiAlias, ClipRRectEngineLayer? oldLayer, }); /// Pushes a path clip operation onto the operation stack. /// /// Rasterization outside the given path is discarded. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack. See [Clip] for different clip modes. /// By default, the clip will be anti-aliased (clip = [Clip.antiAlias]). ClipPathEngineLayer pushClipPath( Path path, { Clip clipBehavior = Clip.antiAlias, ClipPathEngineLayer? oldLayer, }); /// Pushes an opacity operation onto the operation stack. /// /// The given alpha value is blended into the alpha value of the objects' /// rasterization. An alpha value of 0 makes the objects entirely invisible. /// An alpha value of 255 has no effect (i.e., the objects retain the current /// opacity). /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack. OpacityEngineLayer pushOpacity( int alpha, { Offset? offset = Offset.zero, OpacityEngineLayer? oldLayer, }); /// Pushes a color filter operation onto the operation stack. /// /// The given color is applied to the objects' rasterization using the given /// blend mode. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack. ColorFilterEngineLayer pushColorFilter( ColorFilter filter, { ColorFilterEngineLayer? oldLayer, }); /// Pushes an image filter operation onto the operation stack. /// /// The given filter is applied to the children's rasterization before compositing them into /// the scene. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack. ImageFilterEngineLayer pushImageFilter( ImageFilter filter, { Offset offset = Offset.zero, ImageFilterEngineLayer? oldLayer, }); /// Pushes a backdrop filter operation onto the operation stack. /// /// The given filter is applied to the current contents of the scene as far back as /// the most recent save layer and rendered back to the scene using the indicated /// [blendMode] prior to rasterizing the child layers. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack. BackdropFilterEngineLayer pushBackdropFilter( ImageFilter filter, { BlendMode blendMode = BlendMode.srcOver, BackdropFilterEngineLayer? oldLayer, }); /// Pushes a shader mask operation onto the operation stack. /// /// The given shader is applied to the object's rasterization in the given /// rectangle using the given blend mode. /// /// {@macro dart.ui.sceneBuilder.oldLayer} /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} /// /// See [pop] for details about the operation stack. ShaderMaskEngineLayer pushShaderMask( Shader shader, Rect maskRect, BlendMode blendMode, { ShaderMaskEngineLayer? oldLayer, FilterQuality filterQuality = FilterQuality.low, }); /// Ends the effect of the most recently pushed operation. /// /// Internally the scene builder maintains a stack of operations. Each of the /// operations in the stack applies to each of the objects added to the scene. /// Calling this function removes the most recently added operation from the /// stack. void pop(); /// Add a retained engine layer subtree from previous frames. /// /// All the engine layers that are in the subtree of the retained layer will /// be automatically appended to the current engine layer tree. /// /// Therefore, when implementing a subclass of the [Layer] concept defined in /// the rendering layer of Flutter's framework, once this is called, there's /// no need to call [Layer.addToScene] for its children layers. /// /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} void addRetained(EngineLayer retainedLayer); /// Adds an object to the scene that displays performance statistics. /// /// Useful during development to assess the performance of the application. /// The enabledOptions controls which statistics are displayed. The bounds /// controls where the statistics are displayed. /// /// enabledOptions is a bit field with the following bits defined: /// - 0x01: displayRasterizerStatistics - show raster thread frame time /// - 0x02: visualizeRasterizerStatistics - graph raster thread frame times /// - 0x04: displayEngineStatistics - show UI thread frame time /// - 0x08: visualizeEngineStatistics - graph UI thread frame times /// Set enabledOptions to 0x0F to enable all the currently defined features. /// /// The "UI thread" is the thread that includes all the execution of the main /// Dart isolate (the isolate that can call [FlutterView.render]). The UI /// thread frame time is the total time spent executing the /// [PlatformDispatcher.onBeginFrame] callback. The "raster thread" is the /// thread (running on the CPU) that subsequently processes the [Scene] /// provided by the Dart code to turn it into GPU commands and send it to the /// GPU. /// /// See also the [PerformanceOverlayOption] enum in the rendering library. /// for more details. // Values above must match constants in //engine/src/sky/compositor/performance_overlay_layer.h void addPerformanceOverlay(int enabledOptions, Rect bounds); /// Adds a [Picture] to the scene. /// /// The picture is rasterized at the given `offset`. /// /// The rendering _may_ be cached to reduce the cost of painting the picture /// if it is reused in subsequent frames. Whether a picture is cached or not /// depends on the backend implementation. When caching is considered, the /// choice to cache or not cache is a heuristic based on how often the picture /// is being painted and the cost of painting the picture. To disable this /// caching, set `willChangeHint` to true. To force the caching to happen (in /// backends that do caching), set `isComplexHint` to true. When both are set, /// `willChangeHint` prevails. /// /// In general, setting these hints is not very useful. Backends that cache /// pictures only do so for pictures that have been rendered three times /// already; setting `willChangeHint` to true to avoid caching an animating /// picture that changes every frame is therefore redundant, the picture /// wouldn't have been cached anyway. Similarly, backends that cache pictures /// are relatively aggressive about doing so, such that any image complicated /// enough to warrant caching is probably already being cached even without /// `isComplexHint` being set to true. void addPicture( Offset offset, Picture picture, { bool isComplexHint = false, bool willChangeHint = false, }); /// Adds a backend texture to the scene. /// /// The texture is scaled to the given size and rasterized at the given offset. /// /// If `freeze` is true the texture that is added to the scene will not /// be updated with new frames. `freeze` is used when resizing an embedded /// Android view: When resizing an Android view there is a short period during /// which the framework cannot tell if the newest texture frame has the /// previous or new size, to workaround this the framework "freezes" the /// texture just before resizing the Android view and un-freezes it when it is /// certain that a frame with the new size is ready. void addTexture( int textureId, { Offset offset = Offset.zero, double width = 0.0, double height = 0.0, bool freeze = false, FilterQuality filterQuality = FilterQuality.low, }); /// Adds a platform view (e.g an iOS UIView) to the scene. /// /// On iOS this layer splits the current output surface into two surfaces, one for the scene nodes /// preceding the platform view, and one for the scene nodes following the platform view. /// /// ## Performance impact /// /// Adding an additional surface doubles the amount of graphics memory directly used by Flutter /// for output buffers. Quartz might allocated extra buffers for compositing the Flutter surfaces /// and the platform view. /// /// With a platform view in the scene, Quartz has to composite the two Flutter surfaces and the /// embedded UIView. In addition to that, on iOS versions greater than 9, the Flutter frames are /// synchronized with the UIView frames adding additional performance overhead. /// /// The `offset` argument is not used for iOS and Android. void addPlatformView( int viewId, { Offset offset = Offset.zero, double width = 0.0, double height = 0.0, }); /// Sets a threshold after which additional debugging information should be recorded. /// /// Currently this interface is difficult to use by end-developers. If you're /// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev). /// We'll hopefully be able to figure out how to make this feature more useful /// to you. void setRasterizerTracingThreshold(int frameInterval); /// Sets whether the raster cache should checkerboard cached entries. This is /// only useful for debugging purposes. /// /// The compositor can sometimes decide to cache certain portions of the /// widget hierarchy. Such portions typically don't change often from frame to /// frame and are expensive to render. This can speed up overall rendering. However, /// there is certain upfront cost to constructing these cache entries. And, if /// the cache entries are not used very often, this cost may not be worth the /// speedup in rendering of subsequent frames. If the developer wants to be certain /// that populating the raster cache is not causing stutters, this option can be /// set. Depending on the observations made, hints can be provided to the compositor /// that aid it in making better decisions about caching. /// /// Currently this interface is difficult to use by end-developers. If you're /// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev). void setCheckerboardRasterCacheImages(bool checkerboard); /// Sets whether the compositor should checkerboard layers that are rendered /// to offscreen bitmaps. /// /// This is only useful for debugging purposes. void setCheckerboardOffscreenLayers(bool checkerboard); /// Finishes building the scene. /// /// Returns a [Scene] containing the objects that have been added to /// this scene builder. The [Scene] can then be displayed on the /// screen with [FlutterView.render]. /// /// After calling this function, the scene builder object is invalid and /// cannot be used further. Scene build(); } base class _NativeSceneBuilder extends NativeFieldWrapperClass1 implements SceneBuilder { /// Creates an empty [SceneBuilder] object. _NativeSceneBuilder() { _constructor(); } @Native<Void Function(Handle)>(symbol: 'SceneBuilder::Create') external void _constructor(); // Layers used in this scene. // // The key is the layer used. The value is the description of what the layer // is used for, e.g. "pushOpacity" or "addRetained". final Map<EngineLayer, String> _usedLayers = <EngineLayer, String>{}; // In debug mode checks that the `layer` is only used once in a given scene. bool _debugCheckUsedOnce(EngineLayer layer, String usage) { assert(() { assert( !_usedLayers.containsKey(layer), 'Layer ${layer.runtimeType} already used.\n' 'The layer is already being used as ${_usedLayers[layer]} in this scene.\n' 'A layer may only be used once in a given scene.'); _usedLayers[layer] = usage; return true; }()); return true; } bool _debugCheckCanBeUsedAsOldLayer(_EngineLayerWrapper? layer, String methodName) { assert(() { if (layer == null) { return true; } assert(layer._nativeLayer != null, 'Object disposed'); layer._debugCheckNotUsedAsOldLayer(); assert(_debugCheckUsedOnce(layer, 'oldLayer in $methodName')); layer._debugWasUsedAsOldLayer = true; return true; }()); return true; } final List<_EngineLayerWrapper> _layerStack = <_EngineLayerWrapper>[]; // Pushes the `newLayer` onto the `_layerStack` and adds it to the // `_debugChildren` of the current layer in the stack, if any. bool _debugPushLayer(_EngineLayerWrapper newLayer) { assert(() { if (_layerStack.isNotEmpty) { final _EngineLayerWrapper currentLayer = _layerStack.last; currentLayer._debugChildren ??= <_EngineLayerWrapper>[]; currentLayer._debugChildren!.add(newLayer); } _layerStack.add(newLayer); return true; }()); return true; } @override TransformEngineLayer pushTransform( Float64List matrix4, { TransformEngineLayer? oldLayer, }) { assert(_matrix4IsValid(matrix4)); assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushTransform')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushTransform(engineLayer, matrix4, oldLayer?._nativeLayer); final TransformEngineLayer layer = TransformEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Handle, Handle)>(symbol: 'SceneBuilder::pushTransformHandle') external void _pushTransform(EngineLayer layer, Float64List matrix4, EngineLayer? oldLayer); @override OffsetEngineLayer pushOffset( double dx, double dy, { OffsetEngineLayer? oldLayer, }) { assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushOffset')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushOffset(engineLayer, dx, dy, oldLayer?._nativeLayer); final OffsetEngineLayer layer = OffsetEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Double, Double, Handle)>(symbol: 'SceneBuilder::pushOffset') external void _pushOffset(EngineLayer layer, double dx, double dy, EngineLayer? oldLayer); @override ClipRectEngineLayer pushClipRect( Rect rect, { Clip clipBehavior = Clip.antiAlias, ClipRectEngineLayer? oldLayer, }) { assert(clipBehavior != Clip.none); assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushClipRect')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushClipRect(engineLayer, rect.left, rect.right, rect.top, rect.bottom, clipBehavior.index, oldLayer?._nativeLayer); final ClipRectEngineLayer layer = ClipRectEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Double, Double, Double, Double, Int32, Handle)>(symbol: 'SceneBuilder::pushClipRect') external void _pushClipRect( EngineLayer outEngineLayer, double left, double right, double top, double bottom, int clipBehavior, EngineLayer? oldLayer); @override ClipRRectEngineLayer pushClipRRect( RRect rrect, { Clip clipBehavior = Clip.antiAlias, ClipRRectEngineLayer? oldLayer, }) { assert(clipBehavior != Clip.none); assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushClipRRect')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushClipRRect(engineLayer, rrect._getValue32(), clipBehavior.index, oldLayer?._nativeLayer); final ClipRRectEngineLayer layer = ClipRRectEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Handle, Int32, Handle)>(symbol: 'SceneBuilder::pushClipRRect') external void _pushClipRRect(EngineLayer layer, Float32List rrect, int clipBehavior, EngineLayer? oldLayer); @override ClipPathEngineLayer pushClipPath( Path path, { Clip clipBehavior = Clip.antiAlias, ClipPathEngineLayer? oldLayer, }) { assert(clipBehavior != Clip.none); assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushClipPath')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushClipPath(engineLayer, path as _NativePath, clipBehavior.index, oldLayer?._nativeLayer); final ClipPathEngineLayer layer = ClipPathEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Pointer<Void>, Int32, Handle)>(symbol: 'SceneBuilder::pushClipPath') external void _pushClipPath(EngineLayer layer, _NativePath path, int clipBehavior, EngineLayer? oldLayer); @override OpacityEngineLayer pushOpacity( int alpha, { Offset? offset = Offset.zero, OpacityEngineLayer? oldLayer, }) { assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushOpacity')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushOpacity(engineLayer, alpha, offset!.dx, offset.dy, oldLayer?._nativeLayer); final OpacityEngineLayer layer = OpacityEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Int32, Double, Double, Handle)>(symbol: 'SceneBuilder::pushOpacity') external void _pushOpacity(EngineLayer layer, int alpha, double dx, double dy, EngineLayer? oldLayer); @override ColorFilterEngineLayer pushColorFilter( ColorFilter filter, { ColorFilterEngineLayer? oldLayer, }) { assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushColorFilter')); final _ColorFilter nativeFilter = filter._toNativeColorFilter()!; final EngineLayer engineLayer = _NativeEngineLayer._(); _pushColorFilter(engineLayer, nativeFilter, oldLayer?._nativeLayer); final ColorFilterEngineLayer layer = ColorFilterEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Pointer<Void>, Handle)>(symbol: 'SceneBuilder::pushColorFilter') external void _pushColorFilter(EngineLayer layer, _ColorFilter filter, EngineLayer? oldLayer); @override ImageFilterEngineLayer pushImageFilter( ImageFilter filter, { Offset offset = Offset.zero, ImageFilterEngineLayer? oldLayer, }) { assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushImageFilter')); final _ImageFilter nativeFilter = filter._toNativeImageFilter(); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushImageFilter(engineLayer, nativeFilter, offset.dx, offset.dy, oldLayer?._nativeLayer); final ImageFilterEngineLayer layer = ImageFilterEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Pointer<Void>, Double, Double, Handle)>(symbol: 'SceneBuilder::pushImageFilter') external void _pushImageFilter(EngineLayer outEngineLayer, _ImageFilter filter, double dx, double dy, EngineLayer? oldLayer); @override BackdropFilterEngineLayer pushBackdropFilter( ImageFilter filter, { BlendMode blendMode = BlendMode.srcOver, BackdropFilterEngineLayer? oldLayer, }) { assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushBackdropFilter')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushBackdropFilter(engineLayer, filter._toNativeImageFilter(), blendMode.index, oldLayer?._nativeLayer); final BackdropFilterEngineLayer layer = BackdropFilterEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Pointer<Void>, Int32, Handle)>(symbol: 'SceneBuilder::pushBackdropFilter') external void _pushBackdropFilter(EngineLayer outEngineLayer, _ImageFilter filter, int blendMode, EngineLayer? oldLayer); @override ShaderMaskEngineLayer pushShaderMask( Shader shader, Rect maskRect, BlendMode blendMode, { ShaderMaskEngineLayer? oldLayer, FilterQuality filterQuality = FilterQuality.low, }) { assert(_debugCheckCanBeUsedAsOldLayer(oldLayer, 'pushShaderMask')); final EngineLayer engineLayer = _NativeEngineLayer._(); _pushShaderMask( engineLayer, shader, maskRect.left, maskRect.right, maskRect.top, maskRect.bottom, blendMode.index, filterQuality.index, oldLayer?._nativeLayer, ); final ShaderMaskEngineLayer layer = ShaderMaskEngineLayer._(engineLayer); assert(_debugPushLayer(layer)); return layer; } @Native<Void Function(Pointer<Void>, Handle, Pointer<Void>, Double, Double, Double, Double, Int32, Int32, Handle)>(symbol: 'SceneBuilder::pushShaderMask') external void _pushShaderMask( EngineLayer engineLayer, Shader shader, double maskRectLeft, double maskRectRight, double maskRectTop, double maskRectBottom, int blendMode, int filterQualityIndex, EngineLayer? oldLayer); @override void pop() { if (_layerStack.isNotEmpty) { _layerStack.removeLast(); } _pop(); } @Native<Void Function(Pointer<Void>)>(symbol: 'SceneBuilder::pop', isLeaf: true) external void _pop(); @override void addRetained(EngineLayer retainedLayer) { assert(retainedLayer is _EngineLayerWrapper); assert(() { final _EngineLayerWrapper layer = retainedLayer as _EngineLayerWrapper; assert(layer._nativeLayer != null); void recursivelyCheckChildrenUsedOnce(_EngineLayerWrapper parentLayer) { _debugCheckUsedOnce(parentLayer, 'retained layer'); parentLayer._debugCheckNotUsedAsOldLayer(); final List<_EngineLayerWrapper>? children = parentLayer._debugChildren; if (children == null || children.isEmpty) { return; } children.forEach(recursivelyCheckChildrenUsedOnce); } recursivelyCheckChildrenUsedOnce(layer); return true; }()); final _EngineLayerWrapper wrapper = retainedLayer as _EngineLayerWrapper; _addRetained(wrapper._nativeLayer!); } @Native<Void Function(Pointer<Void>, Handle)>(symbol: 'SceneBuilder::addRetained') external void _addRetained(EngineLayer retainedLayer); @override void addPerformanceOverlay(int enabledOptions, Rect bounds) { _addPerformanceOverlay(enabledOptions, bounds.left, bounds.right, bounds.top, bounds.bottom); } @Native<Void Function(Pointer<Void>, Uint64, Double, Double, Double, Double)>(symbol: 'SceneBuilder::addPerformanceOverlay', isLeaf: true) external void _addPerformanceOverlay(int enabledOptions, double left, double right, double top, double bottom); @override void addPicture( Offset offset, Picture picture, { bool isComplexHint = false, bool willChangeHint = false, }) { assert(!picture.debugDisposed); final int hints = (isComplexHint ? 1 : 0) | (willChangeHint ? 2 : 0); _addPicture(offset.dx, offset.dy, picture as _NativePicture, hints); } @Native<Void Function(Pointer<Void>, Double, Double, Pointer<Void>, Int32)>(symbol: 'SceneBuilder::addPicture') external void _addPicture(double dx, double dy, _NativePicture picture, int hints); @override void addTexture( int textureId, { Offset offset = Offset.zero, double width = 0.0, double height = 0.0, bool freeze = false, FilterQuality filterQuality = FilterQuality.low, }) { _addTexture(offset.dx, offset.dy, width, height, textureId, freeze, filterQuality.index); } @Native<Void Function(Pointer<Void>, Double, Double, Double, Double, Int64, Bool, Int32)>(symbol: 'SceneBuilder::addTexture', isLeaf: true) external void _addTexture(double dx, double dy, double width, double height, int textureId, bool freeze, int filterQuality); @override void addPlatformView( int viewId, { Offset offset = Offset.zero, double width = 0.0, double height = 0.0, }) { _addPlatformView(offset.dx, offset.dy, width, height, viewId); } @Native<Void Function(Pointer<Void>, Double, Double, Double, Double, Int64)>(symbol: 'SceneBuilder::addPlatformView', isLeaf: true) external void _addPlatformView(double dx, double dy, double width, double height, int viewId); @override @Native<Void Function(Pointer<Void>, Uint32)>(symbol: 'SceneBuilder::setRasterizerTracingThreshold', isLeaf: true) external void setRasterizerTracingThreshold(int frameInterval); @override @Native<Void Function(Pointer<Void>, Bool)>(symbol: 'SceneBuilder::setCheckerboardRasterCacheImages', isLeaf: true) external void setCheckerboardRasterCacheImages(bool checkerboard); @override @Native<Void Function(Pointer<Void>, Bool)>(symbol: 'SceneBuilder::setCheckerboardOffscreenLayers', isLeaf: true) external void setCheckerboardOffscreenLayers(bool checkerboard); @override Scene build() { final Scene scene = _NativeScene._(); _build(scene); return scene; } @Native<Void Function(Pointer<Void>, Handle)>(symbol: 'SceneBuilder::build') external void _build(Scene outScene); @override String toString() => 'SceneBuilder'; }
engine/lib/ui/compositing.dart/0
{ "file_path": "engine/lib/ui/compositing.dart", "repo_id": "engine", "token_count": 11063 }
243
#version 320 es // 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. precision highp float; layout(location = 0) out vec4 fragColor; layout(location = 0) uniform float a; void main() { mat2 zeros = mat2(0.0); mat3 ones = mat3(a); mat4 identity = mat4(a, 0.0, 0.0, 0.0, 0.0, a, 0.0, 0.0, 0.0, 0.0, a, 0.0, 0.0, 0.0, 0.0, a); fragColor = vec4(zeros[1][1], ones[2][2], identity[3][1], identity[3][3]); }
engine/lib/ui/fixtures/shaders/supported_op_shaders/24_OpTypeMatrix.frag/0
{ "file_path": "engine/lib/ui/fixtures/shaders/supported_op_shaders/24_OpTypeMatrix.frag", "repo_id": "engine", "token_count": 235 }
244
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_ISOLATE_NAME_SERVER_ISOLATE_NAME_SERVER_NATIVES_H_ #define FLUTTER_LIB_UI_ISOLATE_NAME_SERVER_ISOLATE_NAME_SERVER_NATIVES_H_ #include <string> #include "third_party/dart/runtime/include/dart_api.h" namespace flutter { class IsolateNameServerNatives { public: static Dart_Handle LookupPortByName(const std::string& name); static bool RegisterPortWithName(Dart_Handle port_handle, const std::string& name); static bool RemovePortNameMapping(const std::string& name); }; } // namespace flutter #endif // FLUTTER_LIB_UI_ISOLATE_NAME_SERVER_ISOLATE_NAME_SERVER_NATIVES_H_
engine/lib/ui/isolate_name_server/isolate_name_server_natives.h/0
{ "file_path": "engine/lib/ui/isolate_name_server/isolate_name_server_natives.h", "repo_id": "engine", "token_count": 304 }
245
// 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/lib/ui/painting/display_list_image_gpu.h" namespace flutter { sk_sp<DlImageGPU> DlImageGPU::Make(SkiaGPUObject<SkImage> image) { if (!image.skia_object()) { return nullptr; } return sk_sp<DlImageGPU>(new DlImageGPU(std::move(image))); } DlImageGPU::DlImageGPU(SkiaGPUObject<SkImage> image) : image_(std::move(image)) {} // |DlImage| DlImageGPU::~DlImageGPU() {} // |DlImage| sk_sp<SkImage> DlImageGPU::skia_image() const { return image_.skia_object(); }; // |DlImage| std::shared_ptr<impeller::Texture> DlImageGPU::impeller_texture() const { return nullptr; } // |DlImage| bool DlImageGPU::isOpaque() const { if (auto image = skia_image()) { return image->isOpaque(); } return false; } // |DlImage| bool DlImageGPU::isTextureBacked() const { if (auto image = skia_image()) { return image->isTextureBacked(); } return false; } // |DlImage| bool DlImageGPU::isUIThreadSafe() const { return true; } // |DlImage| SkISize DlImageGPU::dimensions() const { const auto image = skia_image(); return image ? image->dimensions() : SkISize::MakeEmpty(); } // |DlImage| size_t DlImageGPU::GetApproximateByteSize() const { auto size = sizeof(*this); if (auto image = skia_image()) { const auto& info = image->imageInfo(); const auto kMipmapOverhead = image->hasMipmaps() ? 4.0 / 3.0 : 1.0; const size_t image_byte_size = info.computeMinByteSize() * kMipmapOverhead; size += image_byte_size; } return size; } } // namespace flutter
engine/lib/ui/painting/display_list_image_gpu.cc/0
{ "file_path": "engine/lib/ui/painting/display_list_image_gpu.cc", "repo_id": "engine", "token_count": 642 }
246
// 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/lib/ui/painting/image_decoder_no_gl_unittests.h" #include "flutter/fml/endianness.h" namespace flutter { namespace testing { // Tests are disabled for fuchsia. #if defined(OS_FUCHSIA) #pragma GCC diagnostic ignored "-Wunreachable-code" #endif namespace { bool IsPngWithPLTE(const uint8_t* bytes, size_t size) { constexpr std::string_view kPngMagic = "\x89PNG\x0d\x0a\x1a\x0a"; constexpr std::string_view kPngPlte = "PLTE"; constexpr uint32_t kLengthBytes = 4; constexpr uint32_t kTypeBytes = 4; constexpr uint32_t kCrcBytes = 4; if (size < kPngMagic.size()) { return false; } if (memcmp(bytes, kPngMagic.data(), kPngMagic.size()) != 0) { return false; } const uint8_t* end = bytes + size; const uint8_t* loc = bytes + kPngMagic.size(); while (loc + kLengthBytes + kTypeBytes <= end) { uint32_t chunk_length = fml::BigEndianToArch(*reinterpret_cast<const uint32_t*>(loc)); if (memcmp(loc + kLengthBytes, kPngPlte.data(), kPngPlte.size()) == 0) { return true; } loc += kLengthBytes + kTypeBytes + chunk_length + kCrcBytes; } return false; } } // namespace float HalfToFloat(uint16_t half) { switch (half) { case 0x7c00: return std::numeric_limits<float>::infinity(); case 0xfc00: return -std::numeric_limits<float>::infinity(); } bool negative = half >> 15; uint16_t exponent = (half >> 10) & 0x1f; uint16_t fraction = half & 0x3ff; float fExponent = exponent - 15.0f; float fFraction = static_cast<float>(fraction) / 1024.f; float pow_value = powf(2.0f, fExponent); return (negative ? -1.f : 1.f) * pow_value * (1.0f + fFraction); } float DecodeBGR10(uint32_t x) { const float max = 1.25098f; const float min = -0.752941f; const float intercept = min; const float slope = (max - min) / 1024.0f; return (x * slope) + intercept; } TEST(ImageDecoderNoGLTest, ImpellerWideGamutDisplayP3) { #if defined(OS_FUCHSIA) GTEST_SKIP() << "Fuchsia can't load the test fixtures."; #endif auto data = flutter::testing::OpenFixtureAsSkData("DisplayP3Logo.png"); auto image = SkImages::DeferredFromEncodedData(data); ASSERT_TRUE(image != nullptr); ASSERT_EQ(SkISize::Make(100, 100), image->dimensions()); ImageGeneratorRegistry registry; std::shared_ptr<ImageGenerator> generator = registry.CreateCompatibleGenerator(data); ASSERT_TRUE(generator); auto descriptor = fml::MakeRefCounted<ImageDescriptor>(std::move(data), std::move(generator)); ASSERT_FALSE( IsPngWithPLTE(descriptor->data()->bytes(), descriptor->data()->size())); #if IMPELLER_SUPPORTS_RENDERING std::shared_ptr<impeller::Allocator> allocator = std::make_shared<impeller::TestImpellerAllocator>(); std::optional<DecompressResult> wide_result = ImageDecoderImpeller::DecompressTexture( descriptor.get(), SkISize::Make(100, 100), {100, 100}, /*supports_wide_gamut=*/true, allocator); ASSERT_TRUE(wide_result.has_value()); ASSERT_EQ(wide_result->image_info.colorType(), kRGBA_F16_SkColorType); ASSERT_TRUE(wide_result->image_info.colorSpace()->isSRGB()); const SkPixmap& wide_pixmap = wide_result->sk_bitmap->pixmap(); const uint16_t* half_ptr = static_cast<const uint16_t*>(wide_pixmap.addr()); bool found_deep_red = false; for (int i = 0; i < wide_pixmap.width() * wide_pixmap.height(); ++i) { float red = HalfToFloat(*half_ptr++); float green = HalfToFloat(*half_ptr++); float blue = HalfToFloat(*half_ptr++); half_ptr++; // alpha if (fabsf(red - 1.0931f) < 0.01f && fabsf(green - -0.2268f) < 0.01f && fabsf(blue - -0.1501f) < 0.01f) { found_deep_red = true; break; } } ASSERT_TRUE(found_deep_red); std::optional<DecompressResult> narrow_result = ImageDecoderImpeller::DecompressTexture( descriptor.get(), SkISize::Make(100, 100), {100, 100}, /*supports_wide_gamut=*/false, allocator); ASSERT_TRUE(narrow_result.has_value()); ASSERT_EQ(narrow_result->image_info.colorType(), kRGBA_8888_SkColorType); #endif // IMPELLER_SUPPORTS_RENDERING } TEST(ImageDecoderNoGLTest, ImpellerWideGamutIndexedPng) { #if defined(OS_FUCHSIA) GTEST_SKIP() << "Fuchsia can't load the test fixtures."; #endif auto data = flutter::testing::OpenFixtureAsSkData("WideGamutIndexed.png"); auto image = SkImages::DeferredFromEncodedData(data); ASSERT_TRUE(image != nullptr); ASSERT_EQ(SkISize::Make(100, 100), image->dimensions()); ImageGeneratorRegistry registry; std::shared_ptr<ImageGenerator> generator = registry.CreateCompatibleGenerator(data); ASSERT_TRUE(generator); auto descriptor = fml::MakeRefCounted<ImageDescriptor>(std::move(data), std::move(generator)); ASSERT_TRUE( IsPngWithPLTE(descriptor->data()->bytes(), descriptor->data()->size())); #if IMPELLER_SUPPORTS_RENDERING std::shared_ptr<impeller::Allocator> allocator = std::make_shared<impeller::TestImpellerAllocator>(); std::optional<DecompressResult> wide_result = ImageDecoderImpeller::DecompressTexture( descriptor.get(), SkISize::Make(100, 100), {100, 100}, /*supports_wide_gamut=*/true, allocator); ASSERT_EQ(wide_result->image_info.colorType(), kBGR_101010x_XR_SkColorType); ASSERT_TRUE(wide_result->image_info.colorSpace()->isSRGB()); const SkPixmap& wide_pixmap = wide_result->sk_bitmap->pixmap(); const uint32_t* pixel_ptr = static_cast<const uint32_t*>(wide_pixmap.addr()); bool found_deep_red = false; for (int i = 0; i < wide_pixmap.width() * wide_pixmap.height(); ++i) { uint32_t pixel = *pixel_ptr++; float blue = DecodeBGR10((pixel >> 0) & 0x3ff); float green = DecodeBGR10((pixel >> 10) & 0x3ff); float red = DecodeBGR10((pixel >> 20) & 0x3ff); if (fabsf(red - 1.0931f) < 0.01f && fabsf(green - -0.2268f) < 0.01f && fabsf(blue - -0.1501f) < 0.01f) { found_deep_red = true; break; } } ASSERT_TRUE(found_deep_red); std::optional<DecompressResult> narrow_result = ImageDecoderImpeller::DecompressTexture( descriptor.get(), SkISize::Make(100, 100), {100, 100}, /*supports_wide_gamut=*/false, allocator); ASSERT_TRUE(narrow_result.has_value()); ASSERT_EQ(narrow_result->image_info.colorType(), kRGBA_8888_SkColorType); #endif // IMPELLER_SUPPORTS_RENDERING } } // namespace testing } // namespace flutter
engine/lib/ui/painting/image_decoder_no_gl_unittests.cc/0
{ "file_path": "engine/lib/ui/painting/image_decoder_no_gl_unittests.cc", "repo_id": "engine", "token_count": 2747 }
247
// 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/lib/ui/painting/image_filter.h" #include "flutter/lib/ui/floating_point.h" #include "flutter/lib/ui/painting/matrix.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, ImageFilter); void ImageFilter::Create(Dart_Handle wrapper) { UIDartState::ThrowIfUIOperationsProhibited(); auto res = fml::MakeRefCounted<ImageFilter>(); res->AssociateWithDartWrapper(wrapper); } static const std::array<DlImageSampling, 4> kFilterQualities = { DlImageSampling::kNearestNeighbor, DlImageSampling::kLinear, DlImageSampling::kMipmapLinear, DlImageSampling::kCubic, }; DlImageSampling ImageFilter::SamplingFromIndex(int filterQualityIndex) { if (filterQualityIndex < 0) { return kFilterQualities.front(); } else if (static_cast<size_t>(filterQualityIndex) >= kFilterQualities.size()) { return kFilterQualities.back(); } else { return kFilterQualities[filterQualityIndex]; } } DlFilterMode ImageFilter::FilterModeFromIndex(int filterQualityIndex) { if (filterQualityIndex <= 0) { return DlFilterMode::kNearest; } return DlFilterMode::kLinear; } ImageFilter::ImageFilter() {} ImageFilter::~ImageFilter() {} void ImageFilter::initBlur(double sigma_x, double sigma_y, DlTileMode tile_mode) { filter_ = DlBlurImageFilter::Make(SafeNarrow(sigma_x), SafeNarrow(sigma_y), tile_mode); } void ImageFilter::initDilate(double radius_x, double radius_y) { filter_ = DlDilateImageFilter::Make(SafeNarrow(radius_x), SafeNarrow(radius_y)); } void ImageFilter::initErode(double radius_x, double radius_y) { filter_ = DlErodeImageFilter::Make(SafeNarrow(radius_x), SafeNarrow(radius_y)); } void ImageFilter::initMatrix(const tonic::Float64List& matrix4, int filterQualityIndex) { auto sampling = ImageFilter::SamplingFromIndex(filterQualityIndex); filter_ = DlMatrixImageFilter::Make(ToSkMatrix(matrix4), sampling); } void ImageFilter::initColorFilter(ColorFilter* colorFilter) { FML_DCHECK(colorFilter); filter_ = DlColorFilterImageFilter::Make(colorFilter->filter()); } void ImageFilter::initComposeFilter(ImageFilter* outer, ImageFilter* inner) { FML_DCHECK(outer && inner); filter_ = DlComposeImageFilter::Make(outer->filter(), inner->filter()); } } // namespace flutter
engine/lib/ui/painting/image_filter.cc/0
{ "file_path": "engine/lib/ui/painting/image_filter.cc", "repo_id": "engine", "token_count": 1068 }
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_LIB_UI_PAINTING_MULTI_FRAME_CODEC_H_ #define FLUTTER_LIB_UI_PAINTING_MULTI_FRAME_CODEC_H_ #include "flutter/fml/macros.h" #include "flutter/lib/ui/painting/codec.h" #include "flutter/lib/ui/painting/image_generator.h" #include <utility> namespace flutter { class MultiFrameCodec : public Codec { public: explicit MultiFrameCodec(std::shared_ptr<ImageGenerator> generator); ~MultiFrameCodec() override; // |Codec| int frameCount() const override; // |Codec| int repetitionCount() const override; // |Codec| Dart_Handle getNextFrame(Dart_Handle args) override; private: // Captures the state shared between the IO and UI task runners. // // The state is initialized on the UI task runner when the Dart object is // created. Decoding occurs on the IO task runner. Since it is possible for // the UI object to be collected independently of the IO task runner work, // it is not safe for this state to live directly on the MultiFrameCodec. // Instead, the MultiFrameCodec creates this object when it is constructed, // shares it with the IO task runner's decoding work, and sets the live_ // member to false when it is destructed. struct State { explicit State(std::shared_ptr<ImageGenerator> generator); const std::shared_ptr<ImageGenerator> generator_; const int frameCount_; const int repetitionCount_; bool is_impeller_enabled_ = false; // The non-const members and functions below here are only read or written // to on the IO thread. They are not safe to access or write on the UI // thread. int nextFrameIndex_ = 0; // The last decoded frame that's required to decode any subsequent frames. std::optional<SkBitmap> lastRequiredFrame_; // The index of the last decoded required frame. int lastRequiredFrameIndex_ = -1; // The rectangle that should be cleared if the previous frame's disposal // method was kRestoreBGColor. std::optional<SkIRect> restoreBGColorRect_; std::pair<sk_sp<DlImage>, std::string> GetNextFrameImage( fml::WeakPtr<GrDirectContext> resourceContext, const std::shared_ptr<const fml::SyncSwitch>& gpu_disable_sync_switch, const std::shared_ptr<impeller::Context>& impeller_context, fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue); void GetNextFrameAndInvokeCallback( std::unique_ptr<tonic::DartPersistentValue> callback, const fml::RefPtr<fml::TaskRunner>& ui_task_runner, fml::WeakPtr<GrDirectContext> resourceContext, fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue, const std::shared_ptr<const fml::SyncSwitch>& gpu_disable_sync_switch, size_t trace_id, const std::shared_ptr<impeller::Context>& impeller_context); }; // Shared across the UI and IO task runners. std::shared_ptr<State> state_; FML_FRIEND_MAKE_REF_COUNTED(MultiFrameCodec); FML_FRIEND_REF_COUNTED_THREAD_SAFE(MultiFrameCodec); }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_MULTI_FRAME_CODEC_H_
engine/lib/ui/painting/multi_frame_codec.h/0
{ "file_path": "engine/lib/ui/painting/multi_frame_codec.h", "repo_id": "engine", "token_count": 1103 }
249
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_PAINTING_SCENE_SCENE_NODE_H_ #define FLUTTER_LIB_UI_PAINTING_SCENE_SCENE_NODE_H_ #include <memory> #include <string> #include <vector> #include "flutter/fml/memory/ref_ptr.h" #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/painting/shader.h" #include "third_party/tonic/dart_library_natives.h" namespace flutter { class SceneShader; /// @brief A scene node, which may be a deserialized ipscene asset. This node /// can be safely added as a child to multiple scene nodes, whether /// they're in the same scene or a different scene. The deserialized /// node itself is treated as immutable on the IO thread. /// /// Internally, nodes may have an animation player, which is controlled /// via the mutation log in the `DlSceneColorSource`, which is built by /// `SceneShader`. class SceneNode : public RefCountedDartWrappable<SceneNode> { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(SceneShader); public: SceneNode(); ~SceneNode() override; static void Create(Dart_Handle wrapper); std::string initFromAsset(const std::string& asset_name, Dart_Handle completion_callback_handle); void initFromTransform(const tonic::Float64List& matrix4); void AddChild(Dart_Handle scene_node_handle); void SetTransform(const tonic::Float64List& matrix4); void SetAnimationState(const std::string& animation_name, bool playing, bool loop, double weight, double time_scale); void SeekAnimation(const std::string& animation_name, double time); fml::RefPtr<SceneNode> node(Dart_Handle shader); private: std::shared_ptr<impeller::scene::Node> node_; std::vector<fml::RefPtr<SceneNode>> children_; friend SceneShader; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_SCENE_SCENE_NODE_H_
engine/lib/ui/painting/scene/scene_node.h/0
{ "file_path": "engine/lib/ui/painting/scene/scene_node.h", "repo_id": "engine", "token_count": 803 }
250
// 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. part of dart.ui; /// The possible actions that can be conveyed from the operating system /// accessibility APIs to a semantics node. /// /// \warning When changes are made to this class, the equivalent APIs in /// `lib/ui/semantics/semantics_node.h` and in each of the embedders /// *must* be updated. /// See also: /// - file://./../../lib/ui/semantics/semantics_node.h class SemanticsAction { const SemanticsAction._(this.index, this.name); /// The numerical value for this action. /// /// Each action has one bit set in this bit field. final int index; /// A human-readable name for this flag, used for debugging purposes. final String name; static const int _kTapIndex = 1 << 0; static const int _kLongPressIndex = 1 << 1; static const int _kScrollLeftIndex = 1 << 2; static const int _kScrollRightIndex = 1 << 3; static const int _kScrollUpIndex = 1 << 4; static const int _kScrollDownIndex = 1 << 5; static const int _kIncreaseIndex = 1 << 6; static const int _kDecreaseIndex = 1 << 7; static const int _kShowOnScreenIndex = 1 << 8; static const int _kMoveCursorForwardByCharacterIndex = 1 << 9; static const int _kMoveCursorBackwardByCharacterIndex = 1 << 10; static const int _kSetSelectionIndex = 1 << 11; static const int _kCopyIndex = 1 << 12; static const int _kCutIndex = 1 << 13; static const int _kPasteIndex = 1 << 14; static const int _kDidGainAccessibilityFocusIndex = 1 << 15; static const int _kDidLoseAccessibilityFocusIndex = 1 << 16; static const int _kCustomActionIndex = 1 << 17; static const int _kDismissIndex = 1 << 18; static const int _kMoveCursorForwardByWordIndex = 1 << 19; static const int _kMoveCursorBackwardByWordIndex = 1 << 20; static const int _kSetTextIndex = 1 << 21; // READ THIS: if you add an action here, you MUST update the // numSemanticsActions value in testing/dart/semantics_test.dart, or tests // will fail. /// The equivalent of a user briefly tapping the screen with the finger /// without moving it. static const SemanticsAction tap = SemanticsAction._(_kTapIndex, 'tap'); /// The equivalent of a user pressing and holding the screen with the finger /// for a few seconds without moving it. static const SemanticsAction longPress = SemanticsAction._(_kLongPressIndex, 'longPress'); /// The equivalent of a user moving their finger across the screen from right /// to left. /// /// This action should be recognized by controls that are horizontally /// scrollable. static const SemanticsAction scrollLeft = SemanticsAction._(_kScrollLeftIndex, 'scrollLeft'); /// The equivalent of a user moving their finger across the screen from left /// to right. /// /// This action should be recognized by controls that are horizontally /// scrollable. static const SemanticsAction scrollRight = SemanticsAction._(_kScrollRightIndex, 'scrollRight'); /// The equivalent of a user moving their finger across the screen from /// bottom to top. /// /// This action should be recognized by controls that are vertically /// scrollable. static const SemanticsAction scrollUp = SemanticsAction._(_kScrollUpIndex, 'scrollUp'); /// The equivalent of a user moving their finger across the screen from top /// to bottom. /// /// This action should be recognized by controls that are vertically /// scrollable. static const SemanticsAction scrollDown = SemanticsAction._(_kScrollDownIndex, 'scrollDown'); /// A request to increase the value represented by the semantics node. /// /// For example, this action might be recognized by a slider control. static const SemanticsAction increase = SemanticsAction._(_kIncreaseIndex, 'increase'); /// A request to decrease the value represented by the semantics node. /// /// For example, this action might be recognized by a slider control. static const SemanticsAction decrease = SemanticsAction._(_kDecreaseIndex, 'decrease'); /// A request to fully show the semantics node on screen. /// /// For example, this action might be send to a node in a scrollable list that /// is partially off screen to bring it on screen. static const SemanticsAction showOnScreen = SemanticsAction._(_kShowOnScreenIndex, 'showOnScreen'); /// Move the cursor forward by one character. /// /// This is for example used by the cursor control in text fields. /// /// The action includes a boolean argument, which indicates whether the cursor /// movement should extend (or start) a selection. static const SemanticsAction moveCursorForwardByCharacter = SemanticsAction._(_kMoveCursorForwardByCharacterIndex, 'moveCursorForwardByCharacter'); /// Move the cursor backward by one character. /// /// This is for example used by the cursor control in text fields. /// /// The action includes a boolean argument, which indicates whether the cursor /// movement should extend (or start) a selection. static const SemanticsAction moveCursorBackwardByCharacter = SemanticsAction._(_kMoveCursorBackwardByCharacterIndex, 'moveCursorBackwardByCharacter'); /// Replaces the current text in the text field. /// /// This is for example used by the text editing in voice access. /// /// The action includes a string argument, which is the new text to /// replace. static const SemanticsAction setText = SemanticsAction._(_kSetTextIndex, 'setText'); /// Set the text selection to the given range. /// /// The provided argument is a Map<String, int> which includes the keys `base` /// and `extent` indicating where the selection within the `value` of the /// semantics node should start and where it should end. Values for both /// keys can range from 0 to length of `value` (inclusive). /// /// Setting `base` and `extent` to the same value will move the cursor to /// that position (without selecting anything). static const SemanticsAction setSelection = SemanticsAction._(_kSetSelectionIndex, 'setSelection'); /// Copy the current selection to the clipboard. static const SemanticsAction copy = SemanticsAction._(_kCopyIndex, 'copy'); /// Cut the current selection and place it in the clipboard. static const SemanticsAction cut = SemanticsAction._(_kCutIndex, 'cut'); /// Paste the current content of the clipboard. static const SemanticsAction paste = SemanticsAction._(_kPasteIndex, 'paste'); /// Indicates that the node has gained accessibility focus. /// /// This handler is invoked when the node annotated with this handler gains /// the accessibility focus. The accessibility focus is the /// green (on Android with TalkBack) or black (on iOS with VoiceOver) /// rectangle shown on screen to indicate what element an accessibility /// user is currently interacting with. /// /// The accessibility focus is different from the input focus. The input focus /// is usually held by the element that currently responds to keyboard inputs. /// Accessibility focus and input focus can be held by two different nodes! static const SemanticsAction didGainAccessibilityFocus = SemanticsAction._(_kDidGainAccessibilityFocusIndex, 'didGainAccessibilityFocus'); /// Indicates that the node has lost accessibility focus. /// /// This handler is invoked when the node annotated with this handler /// loses the accessibility focus. The accessibility focus is /// the green (on Android with TalkBack) or black (on iOS with VoiceOver) /// rectangle shown on screen to indicate what element an accessibility /// user is currently interacting with. /// /// The accessibility focus is different from the input focus. The input focus /// is usually held by the element that currently responds to keyboard inputs. /// Accessibility focus and input focus can be held by two different nodes! static const SemanticsAction didLoseAccessibilityFocus = SemanticsAction._(_kDidLoseAccessibilityFocusIndex, 'didLoseAccessibilityFocus'); /// Indicates that the user has invoked a custom accessibility action. /// /// This handler is added automatically whenever a custom accessibility /// action is added to a semantics node. static const SemanticsAction customAction = SemanticsAction._(_kCustomActionIndex, 'customAction'); /// A request that the node should be dismissed. /// /// A [SnackBar], for example, may have a dismiss action to indicate to the /// user that it can be removed after it is no longer relevant. On Android, /// (with TalkBack) special hint text is spoken when focusing the node and /// a custom action is available in the local context menu. On iOS, /// (with VoiceOver) users can perform a standard gesture to dismiss it. static const SemanticsAction dismiss = SemanticsAction._(_kDismissIndex, 'dismiss'); /// Move the cursor forward by one word. /// /// This is for example used by the cursor control in text fields. /// /// The action includes a boolean argument, which indicates whether the cursor /// movement should extend (or start) a selection. static const SemanticsAction moveCursorForwardByWord = SemanticsAction._(_kMoveCursorForwardByWordIndex, 'moveCursorForwardByWord'); /// Move the cursor backward by one word. /// /// This is for example used by the cursor control in text fields. /// /// The action includes a boolean argument, which indicates whether the cursor /// movement should extend (or start) a selection. static const SemanticsAction moveCursorBackwardByWord = SemanticsAction._(_kMoveCursorBackwardByWordIndex, 'moveCursorBackwardByWord'); /// The possible semantics actions. /// /// The map's key is the [index] of the action and the value is the action /// itself. static const Map<int, SemanticsAction> _kActionById = <int, SemanticsAction>{ _kTapIndex: tap, _kLongPressIndex: longPress, _kScrollLeftIndex: scrollLeft, _kScrollRightIndex: scrollRight, _kScrollUpIndex: scrollUp, _kScrollDownIndex: scrollDown, _kIncreaseIndex: increase, _kDecreaseIndex: decrease, _kShowOnScreenIndex: showOnScreen, _kMoveCursorForwardByCharacterIndex: moveCursorForwardByCharacter, _kMoveCursorBackwardByCharacterIndex: moveCursorBackwardByCharacter, _kSetSelectionIndex: setSelection, _kCopyIndex: copy, _kCutIndex: cut, _kPasteIndex: paste, _kDidGainAccessibilityFocusIndex: didGainAccessibilityFocus, _kDidLoseAccessibilityFocusIndex: didLoseAccessibilityFocus, _kCustomActionIndex: customAction, _kDismissIndex: dismiss, _kMoveCursorForwardByWordIndex: moveCursorForwardByWord, _kMoveCursorBackwardByWordIndex: moveCursorBackwardByWord, _kSetTextIndex: setText, }; static List<SemanticsAction> get values => _kActionById.values.toList(growable: false); static SemanticsAction? fromIndex(int index) => _kActionById[index]; @override String toString() => 'SemanticsAction.$name'; } /// A Boolean value that can be associated with a semantics node. // // When changes are made to this class, the equivalent APIs in // `lib/ui/semantics/semantics_node.h` and in each of the embedders *must* be // updated. If the change affects the visibility of a [SemanticsNode] to // accessibility services, `flutter_test/controller.dart#SemanticsController._importantFlags` // must be updated as well. class SemanticsFlag { const SemanticsFlag._(this.index, this.name); /// The numerical value for this flag. /// /// Each flag has one bit set in this bit field. final int index; /// A human-readable name for this flag, used for debugging purposes. final String name; static const int _kHasCheckedStateIndex = 1 << 0; static const int _kIsCheckedIndex = 1 << 1; static const int _kIsSelectedIndex = 1 << 2; static const int _kIsButtonIndex = 1 << 3; static const int _kIsTextFieldIndex = 1 << 4; static const int _kIsFocusedIndex = 1 << 5; static const int _kHasEnabledStateIndex = 1 << 6; static const int _kIsEnabledIndex = 1 << 7; static const int _kIsInMutuallyExclusiveGroupIndex = 1 << 8; static const int _kIsHeaderIndex = 1 << 9; static const int _kIsObscuredIndex = 1 << 10; static const int _kScopesRouteIndex = 1 << 11; static const int _kNamesRouteIndex = 1 << 12; static const int _kIsHiddenIndex = 1 << 13; static const int _kIsImageIndex = 1 << 14; static const int _kIsLiveRegionIndex = 1 << 15; static const int _kHasToggledStateIndex = 1 << 16; static const int _kIsToggledIndex = 1 << 17; static const int _kHasImplicitScrollingIndex = 1 << 18; static const int _kIsMultilineIndex = 1 << 19; static const int _kIsReadOnlyIndex = 1 << 20; static const int _kIsFocusableIndex = 1 << 21; static const int _kIsLinkIndex = 1 << 22; static const int _kIsSliderIndex = 1 << 23; static const int _kIsKeyboardKeyIndex = 1 << 24; static const int _kIsCheckStateMixedIndex = 1 << 25; static const int _kHasExpandedStateIndex = 1 << 26; static const int _kIsExpandedIndex = 1 << 27; // READ THIS: if you add a flag here, you MUST update the numSemanticsFlags // value in testing/dart/semantics_test.dart, or tests will fail. Also, // please update the Flag enum in // flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java, // and the SemanticsFlag class in lib/web_ui/lib/semantics.dart. If the new flag // affects the visibility of a [SemanticsNode] to accessibility services, // `flutter_test/controller.dart#SemanticsController._importantFlags` // must be updated as well. /// The semantics node has the quality of either being "checked" or "unchecked". /// /// This flag is mutually exclusive with [hasToggledState]. /// /// For example, a checkbox or a radio button widget has checked state. /// /// See also: /// /// * [SemanticsFlag.isChecked], which controls whether the node is "checked" or "unchecked". static const SemanticsFlag hasCheckedState = SemanticsFlag._(_kHasCheckedStateIndex, 'hasCheckedState'); /// Whether a semantics node that [hasCheckedState] is checked. /// /// If true, the semantics node is "checked". If false, the semantics node is /// "unchecked". /// /// For example, if a checkbox has a visible checkmark, [isChecked] is true. /// /// See also: /// /// * [SemanticsFlag.hasCheckedState], which enables a checked state. static const SemanticsFlag isChecked = SemanticsFlag._(_kIsCheckedIndex, 'isChecked'); /// Whether a tristate checkbox is in its mixed state. /// /// If this is true, the check box this semantics node represents /// is in a mixed state. /// /// For example, a [Checkbox] with [Checkbox.tristate] set to true /// can have checked, unchecked, or mixed state. /// /// Must be false when the checkbox is either checked or unchecked. static const SemanticsFlag isCheckStateMixed = SemanticsFlag._(_kIsCheckStateMixedIndex, 'isCheckStateMixed'); /// Whether a semantics node is selected. /// /// If true, the semantics node is "selected". If false, the semantics node is /// "unselected". /// /// For example, the active tab in a tab bar has [isSelected] set to true. static const SemanticsFlag isSelected = SemanticsFlag._(_kIsSelectedIndex, 'isSelected'); /// Whether the semantic node represents a button. /// /// Platforms have special handling for buttons, for example Android's TalkBack /// and iOS's VoiceOver provides an additional hint when the focused object is /// a button. static const SemanticsFlag isButton = SemanticsFlag._(_kIsButtonIndex, 'isButton'); /// Whether the semantic node represents a text field. /// /// Text fields are announced as such and allow text input via accessibility /// affordances. static const SemanticsFlag isTextField = SemanticsFlag._(_kIsTextFieldIndex, 'isTextField'); /// Whether the semantic node represents a slider. static const SemanticsFlag isSlider = SemanticsFlag._(_kIsSliderIndex, 'isSlider'); /// Whether the semantic node represents a keyboard key. static const SemanticsFlag isKeyboardKey = SemanticsFlag._(_kIsKeyboardKeyIndex, 'isKeyboardKey'); /// Whether the semantic node is read only. /// /// Only applicable when [isTextField] is true. static const SemanticsFlag isReadOnly = SemanticsFlag._(_kIsReadOnlyIndex, 'isReadOnly'); /// Whether the semantic node is an interactive link. /// /// Platforms have special handling for links, for example iOS's VoiceOver /// provides an additional hint when the focused object is a link, as well as /// the ability to parse the links through another navigation menu. static const SemanticsFlag isLink = SemanticsFlag._(_kIsLinkIndex, 'isLink'); /// Whether the semantic node is able to hold the user's focus. /// /// The focused element is usually the current receiver of keyboard inputs. static const SemanticsFlag isFocusable = SemanticsFlag._(_kIsFocusableIndex, 'isFocusable'); /// Whether the semantic node currently holds the user's focus. /// /// The focused element is usually the current receiver of keyboard inputs. static const SemanticsFlag isFocused = SemanticsFlag._(_kIsFocusedIndex, 'isFocused'); /// The semantics node has the quality of either being "enabled" or /// "disabled". /// /// For example, a button can be enabled or disabled and therefore has an /// "enabled" state. Static text is usually neither enabled nor disabled and /// therefore does not have an "enabled" state. static const SemanticsFlag hasEnabledState = SemanticsFlag._(_kHasEnabledStateIndex, 'hasEnabledState'); /// Whether a semantic node that [hasEnabledState] is currently enabled. /// /// A disabled element does not respond to user interaction. For example, a /// button that currently does not respond to user interaction should be /// marked as disabled. static const SemanticsFlag isEnabled = SemanticsFlag._(_kIsEnabledIndex, 'isEnabled'); /// Whether a semantic node is in a mutually exclusive group. /// /// For example, a radio button is in a mutually exclusive group because /// only one radio button in that group can be marked as [isChecked]. static const SemanticsFlag isInMutuallyExclusiveGroup = SemanticsFlag._(_kIsInMutuallyExclusiveGroupIndex, 'isInMutuallyExclusiveGroup'); /// Whether a semantic node is a header that divides content into sections. /// /// For example, headers can be used to divide a list of alphabetically /// sorted words into the sections A, B, C, etc. as can be found in many /// address book applications. static const SemanticsFlag isHeader = SemanticsFlag._(_kIsHeaderIndex, 'isHeader'); /// Whether the value of the semantics node is obscured. /// /// This is usually used for text fields to indicate that its content /// is a password or contains other sensitive information. static const SemanticsFlag isObscured = SemanticsFlag._(_kIsObscuredIndex, 'isObscured'); /// Whether the value of the semantics node is coming from a multi-line text /// field. /// /// This is used for text fields to distinguish single-line text fields from /// multi-line ones. static const SemanticsFlag isMultiline = SemanticsFlag._(_kIsMultilineIndex, 'isMultiline'); /// Whether the semantics node is the root of a subtree for which a route name /// should be announced. /// /// When a node with this flag is removed from the semantics tree, the /// framework will select the last in depth-first, paint order node with this /// flag. When a node with this flag is added to the semantics tree, it is /// selected automatically, unless there were multiple nodes with this flag /// added. In this case, the last added node in depth-first, paint order /// will be selected. /// /// From this selected node, the framework will search in depth-first, paint /// order for the first node with a [namesRoute] flag and a non-null, /// non-empty label. The [namesRoute] and [scopesRoute] flags may be on the /// same node. The label of the found node will be announced as an edge /// transition. If no non-empty, non-null label is found then: /// /// * VoiceOver will make a chime announcement. /// * TalkBack will make no announcement /// /// Semantic nodes annotated with this flag are generally not a11y focusable. /// /// This is used in widgets such as Routes, Drawers, and Dialogs to /// communicate significant changes in the visible screen. static const SemanticsFlag scopesRoute = SemanticsFlag._(_kScopesRouteIndex, 'scopesRoute'); /// Whether the semantics node label is the name of a visually distinct /// route. /// /// This is used by certain widgets like Drawers and Dialogs, to indicate /// that the node's semantic label can be used to announce an edge triggered /// semantics update. /// /// Semantic nodes annotated with this flag will still receive a11y focus. /// /// Updating this label within the same active route subtree will not cause /// additional announcements. static const SemanticsFlag namesRoute = SemanticsFlag._(_kNamesRouteIndex, 'namesRoute'); /// Whether the semantics node is considered hidden. /// /// Hidden elements are currently not visible on screen. They may be covered /// by other elements or positioned outside of the visible area of a viewport. /// /// Hidden elements cannot gain accessibility focus though regular touch. The /// only way they can be focused is by moving the focus to them via linear /// navigation. /// /// Platforms are free to completely ignore hidden elements and new platforms /// are encouraged to do so. /// /// Instead of marking an element as hidden it should usually be excluded from /// the semantics tree altogether. Hidden elements are only included in the /// semantics tree to work around platform limitations and they are mainly /// used to implement accessibility scrolling on iOS. /// /// See also: /// /// * [RenderObject.describeSemanticsClip] static const SemanticsFlag isHidden = SemanticsFlag._(_kIsHiddenIndex, 'isHidden'); /// Whether the semantics node represents an image. /// /// Both TalkBack and VoiceOver will inform the user the semantics node /// represents an image. static const SemanticsFlag isImage = SemanticsFlag._(_kIsImageIndex, 'isImage'); /// Whether the semantics node is a live region. /// /// A live region indicates that updates to semantics node are important. /// Platforms may use this information to make polite announcements to the /// user to inform them of updates to this node. /// /// An example of a live region is a [SnackBar] widget. On Android and iOS, /// live region causes a polite announcement to be generated automatically, /// even if the widget does not have accessibility focus. This announcement /// may not be spoken if the OS accessibility services are already /// announcing something else, such as reading the label of a focused /// widget or providing a system announcement. static const SemanticsFlag isLiveRegion = SemanticsFlag._(_kIsLiveRegionIndex, 'isLiveRegion'); /// The semantics node has the quality of either being "on" or "off". /// /// This flag is mutually exclusive with [hasCheckedState]. /// /// For example, a switch has toggled state. /// /// See also: /// /// * [SemanticsFlag.isToggled], which controls whether the node is "on" or "off". static const SemanticsFlag hasToggledState = SemanticsFlag._(_kHasToggledStateIndex, 'hasToggledState'); /// If true, the semantics node is "on". If false, the semantics node is /// "off". /// /// For example, if a switch is in the on position, [isToggled] is true. /// /// See also: /// /// * [SemanticsFlag.hasToggledState], which enables a toggled state. static const SemanticsFlag isToggled = SemanticsFlag._(_kIsToggledIndex, 'isToggled'); /// Whether the platform can scroll the semantics node when the user attempts /// to move focus to an offscreen child. /// /// For example, a [ListView] widget has implicit scrolling so that users can /// easily move the accessibility focus to the next set of children. A /// [PageView] widget does not have implicit scrolling, so that users don't /// navigate to the next page when reaching the end of the current one. static const SemanticsFlag hasImplicitScrolling = SemanticsFlag._(_kHasImplicitScrollingIndex, 'hasImplicitScrolling'); /// The semantics node has the quality of either being "expanded" or "collapsed". /// /// For example, a [SubmenuButton] widget has expanded state. /// /// See also: /// /// * [SemanticsFlag.isExpanded], which controls whether the node is "expanded" or "collapsed". static const SemanticsFlag hasExpandedState = SemanticsFlag._(_kHasExpandedStateIndex, 'hasExpandedState'); /// Whether a semantics node is expanded. /// /// If true, the semantics node is "expanded". If false, the semantics node is /// "collapsed". /// /// For example, if a [SubmenuButton] shows its children, [isExpanded] is true. /// /// See also: /// /// * [SemanticsFlag.hasExpandedState], which enables an expanded/collapsed state. static const SemanticsFlag isExpanded = SemanticsFlag._(_kIsExpandedIndex, 'isExpanded'); /// The possible semantics flags. /// /// The map's key is the [index] of the flag and the value is the flag itself. static const Map<int, SemanticsFlag> _kFlagById = <int, SemanticsFlag>{ _kHasCheckedStateIndex: hasCheckedState, _kIsCheckedIndex: isChecked, _kIsSelectedIndex: isSelected, _kIsButtonIndex: isButton, _kIsTextFieldIndex: isTextField, _kIsFocusedIndex: isFocused, _kHasEnabledStateIndex: hasEnabledState, _kIsEnabledIndex: isEnabled, _kIsInMutuallyExclusiveGroupIndex: isInMutuallyExclusiveGroup, _kIsHeaderIndex: isHeader, _kIsObscuredIndex: isObscured, _kScopesRouteIndex: scopesRoute, _kNamesRouteIndex: namesRoute, _kIsHiddenIndex: isHidden, _kIsImageIndex: isImage, _kIsLiveRegionIndex: isLiveRegion, _kHasToggledStateIndex: hasToggledState, _kIsToggledIndex: isToggled, _kHasImplicitScrollingIndex: hasImplicitScrolling, _kIsMultilineIndex: isMultiline, _kIsReadOnlyIndex: isReadOnly, _kIsFocusableIndex: isFocusable, _kIsLinkIndex: isLink, _kIsSliderIndex: isSlider, _kIsKeyboardKeyIndex: isKeyboardKey, _kIsCheckStateMixedIndex: isCheckStateMixed, _kHasExpandedStateIndex: hasExpandedState, _kIsExpandedIndex: isExpanded, }; static List<SemanticsFlag> get values => _kFlagById.values.toList(growable: false); static SemanticsFlag? fromIndex(int index) => _kFlagById[index]; @override String toString() => 'SemanticsFlag.$name'; } // When adding a new StringAttribute, the classes in these files must be // updated as well. // * engine/src/flutter/lib/web_ui/lib/semantics.dart // * engine/src/flutter/lib/ui/semantics/string_attribute.h // * engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java // * engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_api_test.dart // * engine/src/flutter/testing/dart/semantics_test.dart /// An abstract interface for string attributes that affects how assistive /// technologies, e.g. VoiceOver or TalkBack, treat the text. /// /// See also: /// /// * [AttributedString], where the string attributes are used. /// * [SpellOutStringAttribute], which causes the assistive technologies to /// spell out the string character by character when announcing the string. /// * [LocaleStringAttribute], which causes the assistive technologies to /// treat the string in the specific language. abstract base class StringAttribute extends NativeFieldWrapperClass1 { StringAttribute._({ required this.range, }); /// The range of the text to which this attribute applies. final TextRange range; /// Creates a new attribute with all properties copied except for range, which /// is updated to the specified value. /// /// For example, the [LocaleStringAttribute] specifies a [Locale] for its /// range of characters. Copying it will result in a new /// [LocaleStringAttribute] that has the same locale but an updated /// [TextRange]. StringAttribute copy({required TextRange range}); } /// A string attribute that causes the assistive technologies, e.g. VoiceOver, /// to spell out the string character by character. /// /// See also: /// /// * [AttributedString], where the string attributes are used. /// * [LocaleStringAttribute], which causes the assistive technologies to /// treat the string in the specific language. base class SpellOutStringAttribute extends StringAttribute { /// Creates a string attribute that denotes the text in [range] must be /// spell out when the assistive technologies announce the string. SpellOutStringAttribute({ required TextRange range, }) : super._(range: range) { _initSpellOutStringAttribute(this, range.start, range.end); } @Native<Void Function(Handle, Int32, Int32)>(symbol: 'NativeStringAttribute::initSpellOutStringAttribute') external static void _initSpellOutStringAttribute(SpellOutStringAttribute instance, int start, int end); @override StringAttribute copy({required TextRange range}) { return SpellOutStringAttribute(range: range); } @override String toString() { return 'SpellOutStringAttribute($range)'; } } /// A string attribute that causes the assistive technologies, e.g. VoiceOver, /// to treat string as a certain language. /// /// See also: /// /// * [AttributedString], where the string attributes are used. /// * [SpellOutStringAttribute], which causes the assistive technologies to /// spell out the string character by character when announcing the string. base class LocaleStringAttribute extends StringAttribute { /// Creates a string attribute that denotes the text in [range] must be /// treated as the language specified by the [locale] when the assistive /// technologies announce the string. LocaleStringAttribute({ required TextRange range, required this.locale, }) : super._(range: range) { _initLocaleStringAttribute(this, range.start, range.end, locale.toLanguageTag()); } /// The lanuage of this attribute. final Locale locale; @Native<Void Function(Handle, Int32, Int32, Handle)>(symbol: 'NativeStringAttribute::initLocaleStringAttribute') external static void _initLocaleStringAttribute(LocaleStringAttribute instance, int start, int end, String locale); @override StringAttribute copy({required TextRange range}) { return LocaleStringAttribute(range: range, locale: locale); } @override String toString() { return 'LocaleStringAttribute($range, ${locale.toLanguageTag()})'; } } /// An object that creates [SemanticsUpdate] objects. /// /// Once created, the [SemanticsUpdate] objects can be passed to /// [PlatformDispatcher.updateSemantics] to update the semantics conveyed to the /// user. abstract class SemanticsUpdateBuilder { /// Creates an empty [SemanticsUpdateBuilder] object. factory SemanticsUpdateBuilder() = _NativeSemanticsUpdateBuilder; /// Update the information associated with the node with the given `id`. /// /// The semantics nodes form a tree, with the root of the tree always having /// an id of zero. The `childrenInTraversalOrder` and `childrenInHitTestOrder` /// are the ids of the nodes that are immediate children of this node. The /// former enumerates children in traversal order, and the latter enumerates /// the same children in the hit test order. The two lists must have the same /// length and contain the same ids. They may only differ in the order the /// ids are listed in. For more information about different child orders, see /// [DebugSemanticsDumpOrder]. /// /// The system retains the nodes that are currently reachable from the root. /// A given update need not contain information for nodes that do not change /// in the update. If a node is not reachable from the root after an update, /// the node will be discarded from the tree. /// /// The `flags` are a bit field of [SemanticsFlag]s that apply to this node. /// /// The `actions` are a bit field of [SemanticsAction]s that can be undertaken /// by this node. If the user wishes to undertake one of these actions on this /// node, the [PlatformDispatcher.onSemanticsActionEvent] will be called with /// a [SemanticsActionEvent] specifying the action to be performed. Because /// the semantics tree is maintained asynchronously, the /// [PlatformDispatcher.onSemanticsActionEvent] callback might be called with /// an action that is no longer possible. /// /// The `identifier` is a string that describes the node for UI automation /// tools that work by querying the accessibility hierarchy, such as Android /// UI Automator, iOS XCUITest, or Appium. It's not exposed to users. /// /// The `label` is a string that describes this node. The `value` property /// describes the current value of the node as a string. The `increasedValue` /// string will become the `value` string after a [SemanticsAction.increase] /// action is performed. The `decreasedValue` string will become the `value` /// string after a [SemanticsAction.decrease] action is performed. The `hint` /// string describes what result an action performed on this node has. The /// reading direction of all these strings is given by `textDirection`. /// /// The `labelAttributes`, `valueAttributes`, `hintAttributes`, /// `increasedValueAttributes`, and `decreasedValueAttributes` are the lists of /// [StringAttribute] carried by the `label`, `value`, `hint`, `increasedValue`, /// and `decreasedValue` respectively. Their contents must not be changed during /// the semantics update. /// /// The `tooltip` is a string that describe additional information when user /// hover or long press on the backing widget of this semantics node. /// /// The fields `textSelectionBase` and `textSelectionExtent` describe the /// currently selected text within `value`. A value of -1 indicates no /// current text selection base or extent. /// /// The field `maxValueLength` is used to indicate that an editable text /// field has a limit on the number of characters entered. If it is -1 there /// is no limit on the number of characters entered. The field /// `currentValueLength` indicates how much of that limit has already been /// used up. When `maxValueLength` is >= 0, `currentValueLength` must also be /// >= 0, otherwise it should be specified to be -1. /// /// The field `platformViewId` references the platform view, whose semantics /// nodes will be added as children to this node. If a platform view is /// specified, `childrenInHitTestOrder` and `childrenInTraversalOrder` must /// be empty. A value of -1 indicates that this node is not associated with a /// platform view. /// /// For scrollable nodes `scrollPosition` describes the current scroll /// position in logical pixel. `scrollExtentMax` and `scrollExtentMin` /// describe the maximum and minimum in-rage values that `scrollPosition` can /// be. Both or either may be infinity to indicate unbound scrolling. The /// value for `scrollPosition` can (temporarily) be outside this range, for /// example during an overscroll. `scrollChildren` is the count of the /// total number of child nodes that contribute semantics and `scrollIndex` /// is the index of the first visible child node that contributes semantics. /// /// The `rect` is the region occupied by this node in its own coordinate /// system. /// /// The `transform` is a matrix that maps this node's coordinate system into /// its parent's coordinate system. /// /// The `elevation` describes the distance in z-direction between this node /// and the `elevation` of the parent. /// /// The `thickness` describes how much space this node occupies in the /// z-direction starting at `elevation`. Basically, in the z-direction the /// node starts at `elevation` above the parent and ends at `elevation` + /// `thickness` above the parent. void updateNode({ required int id, required int flags, required int actions, required int maxValueLength, required int currentValueLength, required int textSelectionBase, required int textSelectionExtent, required int platformViewId, required int scrollChildren, required int scrollIndex, required double scrollPosition, required double scrollExtentMax, required double scrollExtentMin, required double elevation, required double thickness, required Rect rect, required String identifier, required String label, required List<StringAttribute> labelAttributes, required String value, required List<StringAttribute> valueAttributes, required String increasedValue, required List<StringAttribute> increasedValueAttributes, required String decreasedValue, required List<StringAttribute> decreasedValueAttributes, required String hint, required List<StringAttribute> hintAttributes, required String tooltip, required TextDirection? textDirection, required Float64List transform, required Int32List childrenInTraversalOrder, required Int32List childrenInHitTestOrder, required Int32List additionalActions, }); /// Update the custom semantics action associated with the given `id`. /// /// The name of the action exposed to the user is the `label`. For overridden /// standard actions this value is ignored. /// /// The `hint` should describe what happens when an action occurs, not the /// manner in which a tap is accomplished. For example, use "delete" instead /// of "double tap to delete". /// /// The text direction of the `hint` and `label` is the same as the global /// window. /// /// For overridden standard actions, `overrideId` corresponds with a /// [SemanticsAction.index] value. For custom actions this argument should not be /// provided. void updateCustomAction({required int id, String? label, String? hint, int overrideId = -1}); /// Creates a [SemanticsUpdate] object that encapsulates the updates recorded /// by this object. /// /// The returned object can be passed to [PlatformDispatcher.updateSemantics] /// to actually update the semantics retained by the system. /// /// This object is unusable after calling build. SemanticsUpdate build(); } base class _NativeSemanticsUpdateBuilder extends NativeFieldWrapperClass1 implements SemanticsUpdateBuilder { _NativeSemanticsUpdateBuilder() { _constructor(); } @Native<Void Function(Handle)>(symbol: 'SemanticsUpdateBuilder::Create') external void _constructor(); @override void updateNode({ required int id, required int flags, required int actions, required int maxValueLength, required int currentValueLength, required int textSelectionBase, required int textSelectionExtent, required int platformViewId, required int scrollChildren, required int scrollIndex, required double scrollPosition, required double scrollExtentMax, required double scrollExtentMin, required double elevation, required double thickness, required Rect rect, required String identifier, required String label, required List<StringAttribute> labelAttributes, required String value, required List<StringAttribute> valueAttributes, required String increasedValue, required List<StringAttribute> increasedValueAttributes, required String decreasedValue, required List<StringAttribute> decreasedValueAttributes, required String hint, required List<StringAttribute> hintAttributes, required String tooltip, required TextDirection? textDirection, required Float64List transform, required Int32List childrenInTraversalOrder, required Int32List childrenInHitTestOrder, required Int32List additionalActions, }) { assert(_matrix4IsValid(transform)); _updateNode( id, flags, actions, maxValueLength, currentValueLength, textSelectionBase, textSelectionExtent, platformViewId, scrollChildren, scrollIndex, scrollPosition, scrollExtentMax, scrollExtentMin, rect.left, rect.top, rect.right, rect.bottom, elevation, thickness, identifier, label, labelAttributes, value, valueAttributes, increasedValue, increasedValueAttributes, decreasedValue, decreasedValueAttributes, hint, hintAttributes, tooltip, textDirection != null ? textDirection.index + 1 : 0, transform, childrenInTraversalOrder, childrenInHitTestOrder, additionalActions, ); } @Native< Void Function( Pointer<Void>, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Double, Double, Double, Double, Double, Double, Double, Double, Double, Handle, Handle, Handle, Handle, Handle, Handle, Handle, Handle, Handle, Handle, Handle, Handle, Int32, Handle, Handle, Handle, Handle)>(symbol: 'SemanticsUpdateBuilder::updateNode') external void _updateNode( int id, int flags, int actions, int maxValueLength, int currentValueLength, int textSelectionBase, int textSelectionExtent, int platformViewId, int scrollChildren, int scrollIndex, double scrollPosition, double scrollExtentMax, double scrollExtentMin, double left, double top, double right, double bottom, double elevation, double thickness, String? identifier, String label, List<StringAttribute> labelAttributes, String value, List<StringAttribute> valueAttributes, String increasedValue, List<StringAttribute> increasedValueAttributes, String decreasedValue, List<StringAttribute> decreasedValueAttributes, String hint, List<StringAttribute> hintAttributes, String tooltip, int textDirection, Float64List transform, Int32List childrenInTraversalOrder, Int32List childrenInHitTestOrder, Int32List additionalActions); @override void updateCustomAction({required int id, String? label, String? hint, int overrideId = -1}) { _updateCustomAction(id, label ?? '', hint ?? '', overrideId); } @Native<Void Function(Pointer<Void>, Int32, Handle, Handle, Int32)>(symbol: 'SemanticsUpdateBuilder::updateCustomAction') external void _updateCustomAction(int id, String label, String hint, int overrideId); @override SemanticsUpdate build() { final _NativeSemanticsUpdate semanticsUpdate = _NativeSemanticsUpdate._(); _build(semanticsUpdate); return semanticsUpdate; } @Native<Void Function(Pointer<Void>, Handle)>(symbol: 'SemanticsUpdateBuilder::build') external void _build(_NativeSemanticsUpdate outSemanticsUpdate); @override String toString() => 'SemanticsUpdateBuilder'; } /// An opaque object representing a batch of semantics updates. /// /// To create a SemanticsUpdate object, use a [SemanticsUpdateBuilder]. /// /// Semantics updates can be applied to the system's retained semantics tree /// using the [PlatformDispatcher.updateSemantics] method. abstract class SemanticsUpdate { /// Releases the resources used by this semantics update. /// /// After calling this function, the semantics update is cannot be used /// further. /// /// This can't be a leaf call because the native function calls Dart API /// (Dart_SetNativeInstanceField). void dispose(); } base class _NativeSemanticsUpdate extends NativeFieldWrapperClass1 implements SemanticsUpdate { /// This class is created by the engine, and should not be instantiated /// or extended directly. /// /// To create a SemanticsUpdate object, use a [SemanticsUpdateBuilder]. _NativeSemanticsUpdate._(); @override @Native<Void Function(Pointer<Void>)>(symbol: 'SemanticsUpdate::dispose') external void dispose(); @override String toString() => 'SemanticsUpdate'; }
engine/lib/ui/semantics.dart/0
{ "file_path": "engine/lib/ui/semantics.dart", "repo_id": "engine", "token_count": 12708 }
251
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_TEXT_ASSET_MANAGER_FONT_PROVIDER_H_ #define FLUTTER_LIB_UI_TEXT_ASSET_MANAGER_FONT_PROVIDER_H_ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "flutter/assets/asset_manager.h" #include "flutter/fml/macros.h" #include "third_party/skia/include/core/SkFontMgr.h" #include "third_party/skia/include/core/SkTypeface.h" #include "txt/font_asset_provider.h" namespace flutter { class AssetManagerFontStyleSet : public SkFontStyleSet { public: AssetManagerFontStyleSet(std::shared_ptr<AssetManager> asset_manager, std::string family_name); ~AssetManagerFontStyleSet() override; void registerAsset(const std::string& asset); // |SkFontStyleSet| int count() override; // |SkFontStyleSet| void getStyle(int index, SkFontStyle*, SkString* style) override; // |SkFontStyleSet| using CreateTypefaceRet = decltype(std::declval<SkFontStyleSet>().createTypeface(0)); CreateTypefaceRet createTypeface(int index) override; // |SkFontStyleSet| using MatchStyleRet = decltype(std::declval<SkFontStyleSet>().matchStyle( std::declval<SkFontStyle>())); MatchStyleRet matchStyle(const SkFontStyle& pattern) override; private: std::shared_ptr<AssetManager> asset_manager_; std::string family_name_; struct TypefaceAsset { explicit TypefaceAsset(std::string a); TypefaceAsset(const TypefaceAsset& other); ~TypefaceAsset(); std::string asset; sk_sp<SkTypeface> typeface; }; std::vector<TypefaceAsset> assets_; FML_DISALLOW_COPY_AND_ASSIGN(AssetManagerFontStyleSet); }; class AssetManagerFontProvider : public txt::FontAssetProvider { public: explicit AssetManagerFontProvider( std::shared_ptr<AssetManager> asset_manager); ~AssetManagerFontProvider() override; void RegisterAsset(const std::string& family_name, const std::string& asset); // |FontAssetProvider| size_t GetFamilyCount() const override; // |FontAssetProvider| std::string GetFamilyName(int index) const override; // |FontAssetProvider| sk_sp<SkFontStyleSet> MatchFamily(const std::string& family_name) override; private: std::shared_ptr<AssetManager> asset_manager_; std::unordered_map<std::string, sk_sp<AssetManagerFontStyleSet>> registered_families_; std::vector<std::string> family_names_; FML_DISALLOW_COPY_AND_ASSIGN(AssetManagerFontProvider); }; } // namespace flutter #endif // FLUTTER_LIB_UI_TEXT_ASSET_MANAGER_FONT_PROVIDER_H_
engine/lib/ui/text/asset_manager_font_provider.h/0
{ "file_path": "engine/lib/ui/text/asset_manager_font_provider.h", "repo_id": "engine", "token_count": 917 }
252
// 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/lib/ui/window/key_data_packet.h" #include <cstring> #include <iostream> #include "flutter/fml/logging.h" namespace flutter { KeyDataPacket::KeyDataPacket(const KeyData& event, const char* character) { size_t char_size = character == nullptr ? 0 : strlen(character); uint64_t char_size_64 = char_size; data_.resize(sizeof(char_size_64) + sizeof(KeyData) + char_size); memcpy(CharacterSizeStart(), &char_size_64, sizeof(char_size_64)); memcpy(KeyDataStart(), &event, sizeof(KeyData)); if (character != nullptr) { memcpy(CharacterStart(), character, char_size); } } KeyDataPacket::~KeyDataPacket() = default; } // namespace flutter
engine/lib/ui/window/key_data_packet.cc/0
{ "file_path": "engine/lib/ui/window/key_data_packet.cc", "repo_id": "engine", "token_count": 289 }
253
// 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 "flutter/fml/mapping.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/lib/ui/window/platform_message_response_dart.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/common/shell_test.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { TEST_F(ShellTest, PlatformMessageResponseDart) { bool did_pass = false; auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform CreateNewThread(), // raster CreateNewThread(), // ui CreateNewThread() // io ); auto nativeCallPlatformMessageResponseDart = [ui_task_runner = task_runners.GetUITaskRunner()](Dart_NativeArguments args) { auto dart_state = std::make_shared<tonic::DartState>(); auto response = fml::MakeRefCounted<PlatformMessageResponseDart>( tonic::DartPersistentValue(tonic::DartState::Current(), Dart_GetNativeArgument(args, 0)), ui_task_runner, "foobar"); uint8_t* data = static_cast<uint8_t*>(malloc(100)); auto mapping = std::make_unique<fml::MallocMapping>(data, 100); response->Complete(std::move(mapping)); }; AddNativeCallback("CallPlatformMessageResponseDart", CREATE_NATIVE_ENTRY(nativeCallPlatformMessageResponseDart)); auto nativeFinishCallResponse = [message_latch, &did_pass](Dart_NativeArguments args) { did_pass = tonic::DartConverter<bool>::FromDart(Dart_GetNativeArgument(args, 0)); message_latch->Signal(); }; AddNativeCallback("FinishCallResponse", CREATE_NATIVE_ENTRY(nativeFinishCallResponse)); Settings settings = CreateSettingsForFixture(); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("platformMessageResponseTest"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); ASSERT_TRUE(did_pass); DestroyShell(std::move(shell), task_runners); } } // namespace testing } // namespace flutter
engine/lib/ui/window/platform_message_response_dart_unittests.cc/0
{ "file_path": "engine/lib/ui/window/platform_message_response_dart_unittests.cc", "repo_id": "engine", "token_count": 1105 }
254
# For more information on test and runner configurations: # # * https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md#platforms platforms: - ie - vm
engine/lib/web_ui/dart_test_edge.yaml/0
{ "file_path": "engine/lib/web_ui/dart_test_edge.yaml", "repo_id": "engine", "token_count": 61 }
255
#!/bin/bash set -e # felt: a command-line utility for building and testing Flutter web engine. # It stands for Flutter Engine Local Tester. # TODO: Add git fetch --tags step. Tags are critical for the correct Dart # version. FELT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" KERNEL_NAME=`uname` CPU_NAME=`uname -m` ENGINE_SRC_DIR="$(dirname $(dirname $(dirname $(dirname ${FELT_DIR}))))" FLUTTER_DIR="${ENGINE_SRC_DIR}/flutter" SDK_PREBUILTS_DIR="${FLUTTER_DIR}/prebuilts" # If set to 0 (the default) will run felt non-incrementally. For example, it will # run pub get. # If set to 1 (via the -i option) will run felt incrementally. INCREMENTAL=0 # All arguments passed to felt, except -i, if any. ARGS="" for arg in "$@" ; do case "$arg" in -i) INCREMENTAL=1 shift ;; *) ARGS="${ARGS} ${arg}" ;; esac done if [ -z "${DART_SDK_DIR}" ] then if [[ $KERNEL_NAME == *"Darwin"* ]] then TARGET_OS="macos" elif [[ $KERNEL_NAME == *"Linux"* ]] then TARGET_OS="linux" else echo "Unrecognized kernel name: ${KERNEL_NAME}" exit 1 fi if [[ $CPU_NAME == *"x86_64"* ]] then TARGET_ARCH="x64" elif [[ $CPU_NAME == *"arm64"* ]] then TARGET_ARCH="arm64" else echo "Unrecognized architecture: ${CPU_NAME}" exit 1 fi PREBUILT_TARGET="${TARGET_OS}-${TARGET_ARCH}" DART_SDK_DIR="${SDK_PREBUILTS_DIR}/${PREBUILT_TARGET}/dart-sdk" if [ ! -d "$DART_SDK_DIR" ] then echo "Prebuilt dart sdk for ${PREBUILT_TARGET} not found." echo "Note: You can specify your own path to a built dart sdk with the DART_SDK_DIR environment variable." exit 1 fi else if [ ! -d "$DART_SDK_DIR" ] then echo "Explicitly specified dart SDK not found at ${DART_SDK_DIR}." exit 1 fi fi WEB_UI_DIR="${FLUTTER_DIR}/lib/web_ui" DART_PATH="$DART_SDK_DIR/bin/dart" if [[ "$FELT_DEBUG" == "true" || "$FELT_DEBUG" == "1" ]] then FELT_DEBUG_FLAGS="--enable-vm-service --pause-isolates-on-start" fi SILENT_LOG=/tmp/felt_pub_get_silent_log.txt trap "rm -f $SILENT_LOG" EXIT verbose_on_failure() { echo "FAILED with the following output:" cat $SILENT_LOG exit 1 } silent_on_success() { COMMAND=${1+"$@"} $COMMAND > $SILENT_LOG 2>&1 || verbose_on_failure } install_deps() { # We need to run pub get here before we actually invoke felt. echo "Running \`dart pub get\` in 'engine/src/flutter/lib/web_ui'" (cd "$WEB_UI_DIR"; silent_on_success $DART_PATH pub get) } cd $WEB_UI_DIR if [[ "$INCREMENTAL" == "0" ]] then install_deps fi (cd $WEB_UI_DIR && $DART_SDK_DIR/bin/dart run $FELT_DEBUG_FLAGS dev/felt.dart ${ARGS})
engine/lib/web_ui/dev/felt/0
{ "file_path": "engine/lib/web_ui/dev/felt", "repo_id": "engine", "token_count": 1171 }
256
// 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 'dart:convert'; import 'dart:io' as io; import 'package:path/path.dart' as pathlib; // TODO(yjbanov): remove hacks when this is fixed: // https://github.com/dart-lang/test/issues/1521 import 'package:skia_gold_client/skia_gold_client.dart'; import 'package:test_api/backend.dart' as hack; // TODO(ditman): Fix ignores when https://github.com/flutter/flutter/issues/143599 is resolved. import 'package:test_core/src/executable.dart' as test; // ignore: implementation_imports import 'package:test_core/src/runner/hack_register_platform.dart' as hack; // ignore: implementation_imports import '../browser.dart'; import '../common.dart'; import '../environment.dart'; import '../exceptions.dart'; import '../felt_config.dart'; import '../pipeline.dart'; import '../test_platform.dart'; import '../utils.dart'; /// Runs a test suite. /// /// Assumes the artifacts from previous steps are available, either from /// running them prior to this step locally, or by having the build graph copy /// them from another bot. class RunSuiteStep implements PipelineStep { RunSuiteStep(this.suite, { required this.startPaused, required this.isVerbose, required this.doUpdateScreenshotGoldens, required this.requireSkiaGold, required this.overridePathToCanvasKit, required this.useDwarf, this.testFiles, }); final TestSuite suite; final Set<FilePath>? testFiles; final bool startPaused; final bool isVerbose; final bool doUpdateScreenshotGoldens; final String? overridePathToCanvasKit; final bool useDwarf; /// Require Skia Gold to be available and reachable. final bool requireSkiaGold; @override String get description => 'run_suite'; @override bool get isSafeToInterrupt => true; @override Future<void> interrupt() async {} @override Future<void> run() async { _prepareTestResultsDirectory(); final BrowserEnvironment browserEnvironment = getBrowserEnvironment( suite.runConfig.browser, useDwarf: useDwarf, ); await browserEnvironment.prepare(); final SkiaGoldClient? skiaClient = await _createSkiaClient(); final String configurationFilePath = pathlib.join( environment.webUiRootDir.path, browserEnvironment.packageTestConfigurationYamlFile, ); final String bundleBuildPath = getBundleBuildDirectory(suite.testBundle).path; final List<String> testArgs = <String>[ ...<String>['-r', 'compact'], // Disable concurrency. Running with concurrency proved to be flaky. '--concurrency=1', if (startPaused) '--pause-after-load', '--platform=${browserEnvironment.packageTestRuntime.identifier}', '--precompiled=$bundleBuildPath', '--configuration=$configurationFilePath', if (AnsiColors.shouldEscape) '--color' else '--no-color', // TODO(jacksongardner): Set the default timeout to five minutes when // https://github.com/dart-lang/test/issues/2006 is fixed. '--', ..._collectTestPaths(), ]; hack.registerPlatformPlugin(<hack.Runtime>[ browserEnvironment.packageTestRuntime, ], () { return BrowserPlatform.start( suite, browserEnvironment: browserEnvironment, doUpdateScreenshotGoldens: doUpdateScreenshotGoldens, skiaClient: skiaClient, overridePathToCanvasKit: overridePathToCanvasKit, isVerbose: isVerbose, ); }); print('[${suite.name.ansiCyan}] Running...'); // We want to run tests with the test set's directory as a working directory. final io.Directory testSetDirectory = io.Directory(pathlib.join( environment.webUiTestDir.path, suite.testBundle.testSet.directory, )); final dynamic originalCwd = io.Directory.current; io.Directory.current = testSetDirectory; try { await test.main(testArgs); } finally { io.Directory.current = originalCwd; } await browserEnvironment.cleanup(); // Since we are just calling `main()` on the test executable, it will modify // the exit code. We use this as a signal that there were some tests that failed. if (io.exitCode != 0) { print('[${suite.name.ansiCyan}] ${'Some tests failed.'.ansiRed}'); // Change the exit code back to 0 when we're done. Failures will be bubbled up // at the end of the pipeline and we'll exit abnormally if there were any // failures in the pipeline. io.exitCode = 0; throw ToolExit('Some unit tests failed in suite ${suite.name.ansiCyan}.'); } else { print('[${suite.name.ansiCyan}] ${'All tests passed!'.ansiGreen}'); } } io.Directory _prepareTestResultsDirectory() { final io.Directory resultsDirectory = io.Directory(pathlib.join( environment.webUiTestResultsDirectory.path, suite.name, )); if (resultsDirectory.existsSync()) { resultsDirectory.deleteSync(recursive: true); } resultsDirectory.createSync(recursive: true); return resultsDirectory; } List<String> _collectTestPaths() { final io.Directory bundleBuild = getBundleBuildDirectory(suite.testBundle); final io.File resultsJsonFile = io.File(pathlib.join( bundleBuild.path, 'results.json', )); if (!resultsJsonFile.existsSync()) { throw ToolExit('Could not find built bundle ${suite.testBundle.name.ansiMagenta} for suite ${suite.name.ansiCyan}.'); } final String jsonString = resultsJsonFile.readAsStringSync(); final dynamic jsonContents = const JsonDecoder().convert(jsonString); final dynamic results = jsonContents['results']; final List<String> testPaths = <String>[]; results.forEach((dynamic k, dynamic v) { final String result = v as String; final String testPath = k as String; if (testFiles != null) { if (!testFiles!.contains(FilePath.fromTestSet(suite.testBundle.testSet, testPath))) { return; } } if (result == 'success') { testPaths.add(testPath); } }); return testPaths; } Future<SkiaGoldClient?> _createSkiaClient() async { if (suite.testBundle.compileConfigs.length > 1) { // Multiple compile configs are only used for our fallback tests, which // do not collect goldens. return null; } if (suite.runConfig.browser == BrowserName.safari) { // Goldens from Safari produce too many diffs, disabled for now. // See https://github.com/flutter/flutter/issues/143591 return null; } final Renderer renderer = suite.testBundle.compileConfigs.first.renderer; final CanvasKitVariant? variant = suite.runConfig.variant; final io.Directory workDirectory = getSkiaGoldDirectoryForSuite(suite); if (workDirectory.existsSync()) { workDirectory.deleteSync(recursive: true); } final bool isWasm = suite.testBundle.compileConfigs.first.compiler == Compiler.dart2wasm; final SkiaGoldClient skiaClient = SkiaGoldClient( workDirectory, dimensions: <String, String> { 'Browser': suite.runConfig.browser.name, if (isWasm) 'Wasm': 'true', 'Renderer': renderer.name, if (variant != null) 'CanvasKitVariant': variant.name, }, ); if (await _checkSkiaClient(skiaClient)) { return skiaClient; } if (requireSkiaGold) { throw ToolExit('Skia Gold is required but is unavailable.'); } return null; } /// Checks whether the Skia Client is usable in this environment. Future<bool> _checkSkiaClient(SkiaGoldClient skiaClient) async { // Now let's check whether Skia Gold is reachable or not. if (isLuci) { if (SkiaGoldClient.isAvailable()) { try { await skiaClient.auth(); return true; } catch (e) { print(e); } } } else { try { // Check if we can reach Gold. await skiaClient.getExpectationForTest(''); return true; } on io.OSError catch (_) { print('OSError occurred, could not reach Gold.'); } on io.SocketException catch (_) { print('SocketException occurred, could not reach Gold.'); } } return false; } }
engine/lib/web_ui/dev/steps/run_suite_step.dart/0
{ "file_path": "engine/lib/web_ui/dev/steps/run_suite_step.dart", "repo_id": "engine", "token_count": 3052 }
257
// 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 { baseUri } from "./base_uri.js"; /** * Wraps `promise` in a timeout of the given `duration` in ms. * * Resolves/rejects with whatever the original `promises` does, or rejects * if `promise` takes longer to complete than `duration`. In that case, * `debugName` is used to compose a legible error message. * * If `duration` is < 0, the original `promise` is returned unchanged. * @param {Promise} promise * @param {number} duration * @param {string} debugName * @returns {Promise} a wrapped promise. */ async function timeout(promise, duration, debugName) { if (duration < 0) { return promise; } let timeoutId; const _clock = new Promise((_, reject) => { timeoutId = setTimeout(() => { reject( new Error( `${debugName} took more than ${duration}ms to resolve. Moving on.`, { cause: timeout, } ) ); }, duration); }); return Promise.race([promise, _clock]).finally(() => { clearTimeout(timeoutId); }); } /** * Handles loading/reloading Flutter's service worker, if configured. * * @see: https://developers.google.com/web/fundamentals/primers/service-workers */ export class FlutterServiceWorkerLoader { /** * Injects a TrustedTypesPolicy (or undefined if the feature is not supported). * @param {TrustedTypesPolicy | undefined} policy */ setTrustedTypesPolicy(policy) { this._ttPolicy = policy; } /** * Returns a Promise that resolves when the latest Flutter service worker, * configured by `settings` has been loaded and activated. * * Otherwise, the promise is rejected with an error message. * @param {import("./types").ServiceWorkerSettings} settings Service worker settings * @returns {Promise} that resolves when the latest serviceWorker is ready. */ loadServiceWorker(settings) { if (!settings) { // In the future, settings = null -> uninstall service worker? console.debug("Null serviceWorker configuration. Skipping."); return Promise.resolve(); } if (!("serviceWorker" in navigator)) { let errorMessage = "Service Worker API unavailable."; if (!window.isSecureContext) { errorMessage += "\nThe current context is NOT secure." errorMessage += "\nRead more: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"; } return Promise.reject( new Error(errorMessage) ); } const { serviceWorkerVersion, serviceWorkerUrl = `${baseUri}flutter_service_worker.js?v=${serviceWorkerVersion}`, timeoutMillis = 4000, } = settings; // Apply the TrustedTypes policy, if present. let url = serviceWorkerUrl; if (this._ttPolicy != null) { url = this._ttPolicy.createScriptURL(url); } const serviceWorkerActivation = navigator.serviceWorker .register(url) .then((serviceWorkerRegistration) => this._getNewServiceWorker(serviceWorkerRegistration, serviceWorkerVersion)) .then(this._waitForServiceWorkerActivation); // Timeout race promise return timeout( serviceWorkerActivation, timeoutMillis, "prepareServiceWorker" ); } /** * Returns the latest service worker for the given `serviceWorkerRegistration`. * * This might return the current service worker, if there's no new service worker * awaiting to be installed/updated. * * @param {ServiceWorkerRegistration} serviceWorkerRegistration * @param {string} serviceWorkerVersion * @returns {Promise<ServiceWorker>} */ async _getNewServiceWorker(serviceWorkerRegistration, serviceWorkerVersion) { if (!serviceWorkerRegistration.active && (serviceWorkerRegistration.installing || serviceWorkerRegistration.waiting)) { // No active web worker and we have installed or are installing // one for the first time. Simply wait for it to activate. console.debug("Installing/Activating first service worker."); return serviceWorkerRegistration.installing || serviceWorkerRegistration.waiting; } else if (!serviceWorkerRegistration.active.scriptURL.endsWith(serviceWorkerVersion)) { // When the app updates the serviceWorkerVersion changes, so we // need to ask the service worker to update. const newRegistration = await serviceWorkerRegistration.update(); console.debug("Updating service worker."); return newRegistration.installing || newRegistration.waiting || newRegistration.active; } else { console.debug("Loading from existing service worker."); return serviceWorkerRegistration.active; } } /** * Returns a Promise that resolves when the `serviceWorker` changes its * state to "activated". * * @param {ServiceWorker} serviceWorker * @returns {Promise<void>} */ async _waitForServiceWorkerActivation(serviceWorker) { if (!serviceWorker || serviceWorker.state === "activated") { if (!serviceWorker) { throw new Error("Cannot activate a null service worker!"); } else { console.debug("Service worker already active."); return; } } return new Promise((resolve, _) => { serviceWorker.addEventListener("statechange", () => { if (serviceWorker.state === "activated") { console.debug("Activated new service worker."); resolve(); } }); }); } }
engine/lib/web_ui/flutter_js/src/service_worker_loader.js/0
{ "file_path": "engine/lib/web_ui/flutter_js/src/service_worker_loader.js", "repo_id": "engine", "token_count": 1859 }
258
// 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. part of ui; // For documentation see https://github.com/flutter/engine/blob/main/lib/ui/painting.dart abstract class Path { factory Path() => engine.renderer.createPath(); factory Path.from(Path source) => engine.renderer.copyPath(source); PathFillType get fillType; set fillType(PathFillType value); void moveTo(double x, double y); void relativeMoveTo(double dx, double dy); void lineTo(double x, double y); void relativeLineTo(double dx, double dy); void quadraticBezierTo(double x1, double y1, double x2, double y2); void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2); void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3); void relativeCubicTo(double x1, double y1, double x2, double y2, double x3, double y3); void conicTo(double x1, double y1, double x2, double y2, double w); void relativeConicTo(double x1, double y1, double x2, double y2, double w); void arcTo(Rect rect, double startAngle, double sweepAngle, bool forceMoveTo); void arcToPoint( Offset arcEnd, { Radius radius = Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true, }); void relativeArcToPoint( Offset arcEndDelta, { Radius radius = Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true, }); void addRect(Rect rect); void addOval(Rect oval); void addArc(Rect oval, double startAngle, double sweepAngle); void addPolygon(List<Offset> points, bool close); void addRRect(RRect rrect); void addPath(Path path, Offset offset, {Float64List? matrix4}); void extendWithPath(Path path, Offset offset, {Float64List? matrix4}); void close(); void reset(); bool contains(Offset point); Path shift(Offset offset); Path transform(Float64List matrix4); // see https://skia.org/user/api/SkPath_Reference#SkPath_getBounds Rect getBounds(); static Path combine(PathOperation operation, Path path1, Path path2) => engine.renderer.combinePaths(operation, path1, path2); PathMetrics computeMetrics({bool forceClosed = false}); }
engine/lib/web_ui/lib/path.dart/0
{ "file_path": "engine/lib/web_ui/lib/path.dart", "repo_id": "engine", "token_count": 749 }
259
// 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 'dart:math' as math; import 'package:ui/ui.dart' as ui; import '../../engine.dart' show PlatformViewManager, longestIncreasingSubsequence; import '../display.dart'; import '../dom.dart'; import '../html/path_to_svg_clip.dart'; import '../platform_views/slots.dart'; import '../svg.dart'; import '../util.dart'; import '../vector_math.dart'; import 'canvas.dart'; import 'overlay_scene_optimizer.dart'; import 'painting.dart'; import 'path.dart'; import 'picture.dart'; import 'picture_recorder.dart'; import 'rasterizer.dart'; /// This composites HTML views into the [ui.Scene]. class HtmlViewEmbedder { HtmlViewEmbedder(this.sceneHost, this.rasterizer); final DomElement sceneHost; final ViewRasterizer rasterizer; /// The context for the current frame. EmbedderFrameContext _context = EmbedderFrameContext(); /// The most recent composition parameters for a given view id. /// /// If we receive a request to composite a view, but the composition /// parameters haven't changed, we can avoid having to recompute the /// element stack that correctly composites the view into the scene. final Map<int, EmbeddedViewParams> _currentCompositionParams = <int, EmbeddedViewParams>{}; /// The clip chain for a view Id. /// /// This contains: /// * The root view in the stack of mutator elements for the view id. /// * The slot view in the stack (what shows the actual platform view contents). /// * The number of clipping elements used last time the view was composited. final Map<int, ViewClipChain> _viewClipChains = <int, ViewClipChain>{}; /// The maximum number of render canvases to create. Too many canvases can /// cause a performance burden. static const int maximumCanvases = 8; /// The views that need to be recomposited into the scene on the next frame. final Set<int> _viewsToRecomposite = <int>{}; /// The list of view ids that should be composited, in order. final List<int> _compositionOrder = <int>[]; /// The most recent composition order. final List<int> _activeCompositionOrder = <int>[]; /// The most recent rendering. Rendering _activeRendering = Rendering(); DisplayCanvas? debugBoundsCanvas; /// The size of the frame, in physical pixels. late ui.Size _frameSize; set frameSize(ui.Size size) { _frameSize = size; } /// Returns a list of canvases which will be overlaid on top of the "base" /// canvas after a platform view is composited into the scene. /// /// The engine asks for the overlay canvases immediately before the paint /// phase, after the preroll phase. In the preroll phase we must be /// conservative and assume that every platform view which is prerolled is /// also composited, and therefore requires an overlay canvas. However, not /// every platform view which is prerolled ends up being composited (it may be /// clipped out and not actually drawn). This means that we may end up /// overallocating canvases. This isn't a problem in practice, however, as /// unused recording canvases are simply deleted at the end of the frame. Iterable<CkCanvas> getOverlayCanvases() { return _context.pictureRecordersCreatedDuringPreroll .map((CkPictureRecorder r) => r.recordingCanvas!); } void prerollCompositeEmbeddedView(int viewId, EmbeddedViewParams params) { final CkPictureRecorder pictureRecorder = CkPictureRecorder(); pictureRecorder.beginRecording(ui.Offset.zero & _frameSize); _context.pictureRecordersCreatedDuringPreroll.add(pictureRecorder); // Do nothing if the params didn't change. if (_currentCompositionParams[viewId] == params) { // If the view was prerolled but not composited, then it needs to be // recomposited. if (!_activeCompositionOrder.contains(viewId)) { _viewsToRecomposite.add(viewId); } return; } _currentCompositionParams[viewId] = params; _viewsToRecomposite.add(viewId); } /// Prepares to composite [viewId]. /// /// If this returns a [CkCanvas], then that canvas should be the new leaf /// node. Otherwise, keep the same leaf node. CkCanvas? compositeEmbeddedView(int viewId) { // Ensure platform view with `viewId` is injected into the `rasterizer.view`. rasterizer.view.dom.injectPlatformView(viewId); final int overlayIndex = _context.viewCount; _compositionOrder.add(viewId); _context.viewCount++; CkPictureRecorder? recorderToUseForRendering; if (overlayIndex < _context.pictureRecordersCreatedDuringPreroll.length) { recorderToUseForRendering = _context.pictureRecordersCreatedDuringPreroll[overlayIndex]; _context.pictureRecorders.add(recorderToUseForRendering); } if (_viewsToRecomposite.contains(viewId)) { _compositeWithParams(viewId, _currentCompositionParams[viewId]!); _viewsToRecomposite.remove(viewId); } return recorderToUseForRendering?.recordingCanvas; } void _compositeWithParams(int platformViewId, EmbeddedViewParams params) { // If we haven't seen this viewId yet, cache it for clips/transforms. final ViewClipChain clipChain = _viewClipChains.putIfAbsent(platformViewId, () { return ViewClipChain(view: createPlatformViewSlot(platformViewId)); }); final DomElement slot = clipChain.slot; // See `apply()` in the PersistedPlatformView class for the HTML version // of this code. slot.style ..width = '${params.size.width}px' ..height = '${params.size.height}px' ..position = 'absolute'; // Recompute the position in the DOM of the `slot` element... final int currentClippingCount = _countClips(params.mutators); final int previousClippingCount = clipChain.clipCount; if (currentClippingCount != previousClippingCount) { final DomElement oldPlatformViewRoot = clipChain.root; final DomElement newPlatformViewRoot = _reconstructClipViewsChain( currentClippingCount, slot, oldPlatformViewRoot, ); // Store the updated root element, and clip count clipChain.updateClipChain( root: newPlatformViewRoot, clipCount: currentClippingCount, ); } // Apply mutators to the slot _applyMutators(params, slot, platformViewId); } int _countClips(MutatorsStack mutators) { int clipCount = 0; for (final Mutator mutator in mutators) { if (mutator.isClipType) { clipCount++; } } return clipCount; } DomElement _reconstructClipViewsChain( int numClips, DomElement platformView, DomElement headClipView, ) { DomNode? headClipViewNextSibling; bool headClipViewWasAttached = false; if (headClipView.parentNode != null) { headClipViewWasAttached = true; headClipViewNextSibling = headClipView.nextSibling; headClipView.remove(); } DomElement head = platformView; int clipIndex = 0; // Re-use as much existing clip views as needed. while (head != headClipView && clipIndex < numClips) { head = head.parent!; clipIndex++; } // If there weren't enough existing clip views, add more. while (clipIndex < numClips) { final DomElement clippingView = createDomElement('flt-clip'); clippingView.append(head); head = clippingView; clipIndex++; } head.remove(); // If the chain was previously attached, attach it to the same position. if (headClipViewWasAttached) { sceneHost.insertBefore(head, headClipViewNextSibling); } return head; } /// Clean up the old SVG clip definitions, as this platform view is about to /// be recomposited. void _cleanUpClipDefs(int viewId) { if (_svgClipDefs.containsKey(viewId)) { final DomElement clipDefs = _svgPathDefs!.querySelector('#sk_path_defs')!; final List<DomElement> nodesToRemove = <DomElement>[]; final Set<String> oldDefs = _svgClipDefs[viewId]!; for (final DomElement child in clipDefs.children) { if (oldDefs.contains(child.id)) { nodesToRemove.add(child); } } for (final DomElement node in nodesToRemove) { node.remove(); } _svgClipDefs[viewId]!.clear(); } } void _applyMutators( EmbeddedViewParams params, DomElement embeddedView, int viewId) { final MutatorsStack mutators = params.mutators; DomElement head = embeddedView; Matrix4 headTransform = params.offset == ui.Offset.zero ? Matrix4.identity() : Matrix4.translationValues(params.offset.dx, params.offset.dy, 0); double embeddedOpacity = 1.0; _resetAnchor(head); _cleanUpClipDefs(viewId); for (final Mutator mutator in mutators) { switch (mutator.type) { case MutatorType.transform: headTransform = mutator.matrix!.multiplied(headTransform); head.style.transform = float64ListToCssTransform(headTransform.storage); case MutatorType.clipRect: case MutatorType.clipRRect: case MutatorType.clipPath: final DomElement clipView = head.parent!; clipView.style.clip = ''; clipView.style.clipPath = ''; headTransform = Matrix4.identity(); clipView.style.transform = ''; // We need to set width and height for the clipView to cover the // bounds of the path since Safari seem to incorrectly intersect // the element bounding rect with the clip path. clipView.style.width = '100%'; clipView.style.height = '100%'; if (mutator.rect != null) { final ui.Rect rect = mutator.rect!; clipView.style.clip = 'rect(${rect.top}px, ${rect.right}px, ' '${rect.bottom}px, ${rect.left}px)'; } else if (mutator.rrect != null) { final CkPath path = CkPath(); path.addRRect(mutator.rrect!); _ensureSvgPathDefs(); final DomElement pathDefs = _svgPathDefs!.querySelector('#sk_path_defs')!; _clipPathCount += 1; final String clipId = 'svgClip$_clipPathCount'; final SVGClipPathElement newClipPath = createSVGClipPathElement(); newClipPath.id = clipId; newClipPath.append( createSVGPathElement()..setAttribute('d', path.toSvgString()!)); pathDefs.append(newClipPath); // Store the id of the node instead of [newClipPath] directly. For // some reason, calling `newClipPath.remove()` doesn't remove it // from the DOM. _svgClipDefs.putIfAbsent(viewId, () => <String>{}).add(clipId); clipView.style.clipPath = 'url(#$clipId)'; } else if (mutator.path != null) { final CkPath path = mutator.path! as CkPath; _ensureSvgPathDefs(); final DomElement pathDefs = _svgPathDefs!.querySelector('#sk_path_defs')!; _clipPathCount += 1; final String clipId = 'svgClip$_clipPathCount'; final SVGClipPathElement newClipPath = createSVGClipPathElement(); newClipPath.id = clipId; newClipPath.append( createSVGPathElement()..setAttribute('d', path.toSvgString()!)); pathDefs.append(newClipPath); // Store the id of the node instead of [newClipPath] directly. For // some reason, calling `newClipPath.remove()` doesn't remove it // from the DOM. _svgClipDefs.putIfAbsent(viewId, () => <String>{}).add(clipId); clipView.style.clipPath = 'url(#$clipId)'; } _resetAnchor(clipView); head = clipView; case MutatorType.opacity: embeddedOpacity *= mutator.alphaFloat; } } embeddedView.style.opacity = embeddedOpacity.toString(); // Reverse scale based on screen scale. // // HTML elements use logical (CSS) pixels, but we have been using physical // pixels, so scale down the head element to match the logical resolution. final double scale = EngineFlutterDisplay.instance.devicePixelRatio; final double inverseScale = 1 / scale; final Matrix4 scaleMatrix = Matrix4.diagonal3Values(inverseScale, inverseScale, 1); headTransform = scaleMatrix.multiplied(headTransform); head.style.transform = float64ListToCssTransform(headTransform.storage); } /// Sets the transform origin to the top-left corner of the element. /// /// By default, the transform origin is the center of the element, but /// Flutter assumes the transform origin is the top-left point. void _resetAnchor(DomElement element) { element.style.transformOrigin = '0 0 0'; element.style.position = 'absolute'; } int _clipPathCount = 0; DomElement? _svgPathDefs; /// The nodes containing the SVG clip definitions needed to clip this view. final Map<int, Set<String>> _svgClipDefs = <int, Set<String>>{}; /// Ensures we add a container of SVG path defs to the DOM so they can /// be referred to in clip-path: url(#blah). void _ensureSvgPathDefs() { if (_svgPathDefs != null) { return; } _svgPathDefs = kSvgResourceHeader.cloneNode(false) as SVGElement; _svgPathDefs!.append(createSVGDefsElement()..id = 'sk_path_defs'); sceneHost.append(_svgPathDefs!); } Future<void> submitFrame(CkPicture basePicture) async { final List<CkPicture> pictures = <CkPicture>[basePicture]; for (final CkPictureRecorder recorder in _context.pictureRecorders) { pictures.add(recorder.endRecording()); } Rendering rendering = createOptimizedRendering( pictures, _compositionOrder, _currentCompositionParams); rendering = _modifyRenderingForMaxCanvases(rendering); _updateDomForNewRendering(rendering); if (rendering.equalsForRendering(_activeRendering)) { // Copy the display canvases to the new rendering. for (int i = 0; i < rendering.canvases.length; i++) { rendering.canvases[i].displayCanvas = _activeRendering.canvases[i].displayCanvas; _activeRendering.canvases[i].displayCanvas = null; } } _activeRendering = rendering; final List<RenderingRenderCanvas> renderCanvases = rendering.canvases; for (final RenderingRenderCanvas renderCanvas in renderCanvases) { await rasterizer.rasterizeToCanvas( renderCanvas.displayCanvas!, renderCanvas.pictures); } for (final CkPictureRecorder recorder in _context.pictureRecordersCreatedDuringPreroll) { if (recorder.isRecording) { recorder.endRecording(); } } // Draw the computed bounds for pictures and platform views if overlay // optimization debugging is enabled. if (debugOverlayOptimizationBounds) { debugBoundsCanvas ??= rasterizer.displayFactory.getCanvas(); final CkPictureRecorder boundsRecorder = CkPictureRecorder(); final CkCanvas boundsCanvas = boundsRecorder.beginRecording( ui.Rect.fromLTWH(0, 0, _frameSize.width, _frameSize.height)); final CkPaint platformViewBoundsPaint = CkPaint() ..color = const ui.Color.fromARGB(100, 0, 255, 0); final CkPaint pictureBoundsPaint = CkPaint() ..color = const ui.Color.fromARGB(100, 0, 0, 255); for (final RenderingEntity entity in _activeRendering.entities) { if (entity is RenderingPlatformView) { if (entity.debugComputedBounds != null) { boundsCanvas.drawRect( entity.debugComputedBounds!, platformViewBoundsPaint); } } else if (entity is RenderingRenderCanvas) { for (final CkPicture picture in entity.pictures) { boundsCanvas.drawRect(picture.cullRect, pictureBoundsPaint); } } } await rasterizer.rasterizeToCanvas( debugBoundsCanvas!, <CkPicture>[boundsRecorder.endRecording()]); sceneHost.append(debugBoundsCanvas!.hostElement); } // Reset the context. _context = EmbedderFrameContext(); if (listEquals(_compositionOrder, _activeCompositionOrder)) { _compositionOrder.clear(); return; } final Set<int> unusedViews = Set<int>.from(_activeCompositionOrder); _activeCompositionOrder.clear(); List<int>? debugInvalidViewIds; for (int i = 0; i < _compositionOrder.length; i++) { final int viewId = _compositionOrder[i]; bool isViewInvalid = false; assert(() { isViewInvalid = !PlatformViewManager.instance.knowsViewId(viewId); if (isViewInvalid) { debugInvalidViewIds ??= <int>[]; debugInvalidViewIds!.add(viewId); } return true; }()); if (isViewInvalid) { continue; } _activeCompositionOrder.add(viewId); unusedViews.remove(viewId); } _compositionOrder.clear(); unusedViews.forEach(disposeView); assert( debugInvalidViewIds == null || debugInvalidViewIds!.isEmpty, 'Cannot render platform views: ${debugInvalidViewIds!.join(', ')}. ' 'These views have not been created, or they have been deleted.', ); } void disposeView(int viewId) { final ViewClipChain? clipChain = _viewClipChains.remove(viewId); clipChain?.root.remove(); // More cleanup _currentCompositionParams.remove(viewId); _viewsToRecomposite.remove(viewId); _cleanUpClipDefs(viewId); _svgClipDefs.remove(viewId); } /// Modify the given rendering by removing canvases until the number of /// canvases is less than or equal to the maximum number of canvases. Rendering _modifyRenderingForMaxCanvases(Rendering rendering) { final Rendering result = Rendering(); final int numCanvases = rendering.canvases.length; if (numCanvases <= maximumCanvases) { return rendering; } int numCanvasesToDelete = numCanvases - maximumCanvases; final List<CkPicture> picturesForLastCanvas = <CkPicture>[]; final List<RenderingEntity> modifiedEntities = List<RenderingEntity>.from(rendering.entities); bool sawLastCanvas = false; for (int i = rendering.entities.length - 1; i > 0; i--) { final RenderingEntity entity = modifiedEntities[i]; if (entity is RenderingRenderCanvas) { if (!sawLastCanvas) { sawLastCanvas = true; picturesForLastCanvas.insertAll(0, entity.pictures); continue; } modifiedEntities.removeAt(i); picturesForLastCanvas.insertAll(0, entity.pictures); numCanvasesToDelete--; if (numCanvasesToDelete == 0) { break; } } } // Replace the pictures in the last canvas with all the pictures from the // deleted canvases. for (int i = modifiedEntities.length - 1; i > 0; i--) { final RenderingEntity entity = modifiedEntities[i]; if (entity is RenderingRenderCanvas) { entity.pictures.clear(); entity.pictures.addAll(picturesForLastCanvas); break; } } result.entities.addAll(modifiedEntities); return result; } void _updateDomForNewRendering(Rendering rendering) { if (rendering.equalsForRendering(_activeRendering)) { // The rendering has not changed, so no DOM manipulation is needed. return; } final List<int> indexMap = _getIndexMapFromPreviousRendering(_activeRendering, rendering); final List<int> existingIndexMap = indexMap.where((int index) => index != -1).toList(); final List<int> staticElements = longestIncreasingSubsequence(existingIndexMap); // Convert longest increasing subsequence from subsequence of indices of // `existingIndexMap` to a subsequence of indices in previous rendering. for (int i = 0; i < staticElements.length; i++) { staticElements[i] = existingIndexMap[staticElements[i]]; } // Remove elements which are in the active rendering, but not in the new // rendering. for (int i = 0; i < _activeRendering.entities.length; i++) { if (indexMap.contains(i)) { continue; } final RenderingEntity entity = _activeRendering.entities[i]; if (entity is RenderingPlatformView) { disposeView(entity.viewId); } else if (entity is RenderingRenderCanvas) { assert( entity.displayCanvas != null, 'RenderCanvas in previous rendering was ' 'not assigned a DisplayCanvas'); rasterizer.releaseOverlay(entity.displayCanvas!); entity.displayCanvas = null; } } // Updates [renderCanvas] (located in [index] in the next rendering) to have // a display canvas, either taken from the associated render canvas in the // previous rendering, or newly created. void updateRenderCanvasWithDisplay( RenderingRenderCanvas renderCanvas, int index) { // Does [nextEntity] correspond with a render canvas in the previous // rendering? If so, then the render canvas in the previous rendering // had an associated display canvas. Use this display canvas for // [nextEntity]. if (indexMap[index] != -1) { final RenderingEntity previousEntity = _activeRendering.entities[indexMap[index]]; assert(previousEntity is RenderingRenderCanvas && previousEntity.displayCanvas != null); renderCanvas.displayCanvas = (previousEntity as RenderingRenderCanvas).displayCanvas; previousEntity.displayCanvas = null; } else { // There is no corresponding render canvas in the previous // rendering. So this render canvas needs a display canvas. renderCanvas.displayCanvas = rasterizer.getOverlay(); } } // At this point, the DOM contains the static elements and the elements from // the previous rendering which need to move. We iterate over the static // elements and insert the elements which come before them into the DOM. int staticElementIndex = 0; int nextRenderingIndex = 0; while (staticElementIndex < staticElements.length) { final int staticElementIndexInActiveRendering = staticElements[staticElementIndex]; final DomElement staticDomElement = _getElement( _activeRendering.entities[staticElementIndexInActiveRendering]); // Go through next rendering elements until we reach the static element. while ( indexMap[nextRenderingIndex] != staticElementIndexInActiveRendering) { final RenderingEntity nextEntity = rendering.entities[nextRenderingIndex]; if (nextEntity is RenderingRenderCanvas) { updateRenderCanvasWithDisplay(nextEntity, nextRenderingIndex); } sceneHost.insertBefore(_getElement(nextEntity), staticDomElement); nextRenderingIndex++; } if (rendering.entities[nextRenderingIndex] is RenderingRenderCanvas) { updateRenderCanvasWithDisplay( rendering.entities[nextRenderingIndex] as RenderingRenderCanvas, nextRenderingIndex); } // Also increment the next rendering index because this is the static // element. nextRenderingIndex++; staticElementIndex++; } // Add the leftover entities. while (nextRenderingIndex < rendering.entities.length) { final RenderingEntity nextEntity = rendering.entities[nextRenderingIndex]; if (nextEntity is RenderingRenderCanvas) { updateRenderCanvasWithDisplay(nextEntity, nextRenderingIndex); } sceneHost.append(_getElement(nextEntity)); nextRenderingIndex++; } } DomElement _getElement(RenderingEntity entity) { switch (entity) { case RenderingRenderCanvas(): return entity.displayCanvas!.hostElement; case RenderingPlatformView(): return _viewClipChains[entity.viewId]!.root; } } /// Returns a [List] of ints mapping elements from the [next] rendering to /// elements of the [previous] rendering. If there is no matching element in /// the previous rendering, then the index map for that element is `-1`. List<int> _getIndexMapFromPreviousRendering( Rendering previous, Rendering next) { assert(!previous.equalsForRendering(next), 'Should not be in this method if the Renderings are equal'); final List<int> result = <int>[]; int index = 0; final int maxUnchangedLength = math.min(previous.entities.length, next.entities.length); // A canvas in the previous rendering can only be used once in the next // rendering. So if it is matched with one in the next rendering, mark it // here so it is only matched once. final Set<int> alreadyClaimedCanvases = <int>{}; // Add the unchanged elements from the beginning of the list. while (index < maxUnchangedLength && previous.entities[index].equalsForRendering(next.entities[index])) { result.add(index); if (previous.entities[index] is RenderingRenderCanvas) { alreadyClaimedCanvases.add(index); } index += 1; } while (index < next.entities.length) { bool foundForIndex = false; for (int oldIndex = 0; oldIndex < previous.entities.length; oldIndex += 1) { if (previous.entities[oldIndex] .equalsForRendering(next.entities[index]) && !alreadyClaimedCanvases.contains(oldIndex)) { result.add(oldIndex); if (previous.entities[oldIndex] is RenderingRenderCanvas) { alreadyClaimedCanvases.add(oldIndex); } foundForIndex = true; break; } } if (!foundForIndex) { result.add(-1); } index += 1; } assert(result.length == next.entities.length); return result; } /// Deletes SVG clip paths, useful for tests. void debugCleanupSvgClipPaths() { final DomElement? parent = _svgPathDefs?.children.single; if (parent != null) { for (DomNode? child = parent.lastChild; child != null; child = parent.lastChild) { parent.removeChild(child); } } _svgClipDefs.clear(); } static void removeElement(DomElement element) { element.remove(); } /// Disposes the state of this view embedder. void dispose() { _viewClipChains.keys.toList().forEach(disposeView); _context = EmbedderFrameContext(); _currentCompositionParams.clear(); debugCleanupSvgClipPaths(); _currentCompositionParams.clear(); _viewClipChains.clear(); _viewsToRecomposite.clear(); _activeCompositionOrder.clear(); _compositionOrder.clear(); _activeRendering = Rendering(); } /// Clears the state. Used in tests. void debugClear() { dispose(); rasterizer.removeOverlaysFromDom(); } } /// Represents a Clip Chain (for a view). /// /// Objects of this class contain: /// * The root view in the stack of mutator elements for the view id. /// * The slot view in the stack (the actual contents of the platform view). /// * The number of clipping elements used last time the view was composited. class ViewClipChain { ViewClipChain({required DomElement view}) : _root = view, _slot = view; DomElement _root; final DomElement _slot; int _clipCount = -1; DomElement get root => _root; DomElement get slot => _slot; int get clipCount => _clipCount; void updateClipChain({required DomElement root, required int clipCount}) { _root = root; _clipCount = clipCount; } } /// The parameters passed to the view embedder. class EmbeddedViewParams { EmbeddedViewParams(this.offset, this.size, MutatorsStack mutators) : mutators = MutatorsStack._copy(mutators); final ui.Offset offset; final ui.Size size; final MutatorsStack mutators; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is EmbeddedViewParams && other.offset == offset && other.size == size && other.mutators == mutators; } @override int get hashCode => Object.hash(offset, size, mutators); } enum MutatorType { clipRect, clipRRect, clipPath, transform, opacity, } /// Stores mutation information like clipping or transform. class Mutator { const Mutator.clipRect(ui.Rect rect) : this._(MutatorType.clipRect, rect, null, null, null, null); const Mutator.clipRRect(ui.RRect rrect) : this._(MutatorType.clipRRect, null, rrect, null, null, null); const Mutator.clipPath(ui.Path path) : this._(MutatorType.clipPath, null, null, path, null, null); const Mutator.transform(Matrix4 matrix) : this._(MutatorType.transform, null, null, null, matrix, null); const Mutator.opacity(int alpha) : this._(MutatorType.opacity, null, null, null, null, alpha); const Mutator._( this.type, this.rect, this.rrect, this.path, this.matrix, this.alpha, ); final MutatorType type; final ui.Rect? rect; final ui.RRect? rrect; final ui.Path? path; final Matrix4? matrix; final int? alpha; bool get isClipType => type == MutatorType.clipRect || type == MutatorType.clipRRect || type == MutatorType.clipPath; double get alphaFloat => alpha! / 255.0; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other is! Mutator) { return false; } final Mutator typedOther = other; if (type != typedOther.type) { return false; } switch (type) { case MutatorType.clipRect: return rect == typedOther.rect; case MutatorType.clipRRect: return rrect == typedOther.rrect; case MutatorType.clipPath: return path == typedOther.path; case MutatorType.transform: return matrix == typedOther.matrix; case MutatorType.opacity: return alpha == typedOther.alpha; default: return false; } } @override int get hashCode => Object.hash(type, rect, rrect, path, matrix, alpha); } /// A stack of mutators that can be applied to an embedded view. class MutatorsStack extends Iterable<Mutator> { MutatorsStack() : _mutators = <Mutator>[]; MutatorsStack._copy(MutatorsStack original) : _mutators = List<Mutator>.from(original._mutators); final List<Mutator> _mutators; void pushClipRect(ui.Rect rect) { _mutators.add(Mutator.clipRect(rect)); } void pushClipRRect(ui.RRect rrect) { _mutators.add(Mutator.clipRRect(rrect)); } void pushClipPath(ui.Path path) { _mutators.add(Mutator.clipPath(path)); } void pushTransform(Matrix4 matrix) { _mutators.add(Mutator.transform(matrix)); } void pushOpacity(int alpha) { _mutators.add(Mutator.opacity(alpha)); } void pop() { _mutators.removeLast(); } @override bool operator ==(Object other) { if (identical(other, this)) { return true; } return other is MutatorsStack && listEquals<Mutator>(other._mutators, _mutators); } @override int get hashCode => Object.hashAll(_mutators); @override Iterator<Mutator> get iterator => _mutators.reversed.iterator; /// Iterate over the mutators in reverse. Iterable<Mutator> get reversed => _mutators; } /// The state for the current frame. class EmbedderFrameContext { /// Picture recorders which were created during the preroll phase. /// /// These picture recorders will be "claimed" in the paint phase by platform /// views being composited into the scene. final List<CkPictureRecorder> pictureRecordersCreatedDuringPreroll = <CkPictureRecorder>[]; /// Picture recorders which were actually used in the paint phase. /// /// This is a subset of [_pictureRecordersCreatedDuringPreroll]. final List<CkPictureRecorder> pictureRecorders = <CkPictureRecorder>[]; /// The number of platform views in this frame. int viewCount = 0; }
engine/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/embedded_views.dart", "repo_id": "engine", "token_count": 11995 }
260
// 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 'dart:math' as math; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../vector_math.dart'; import 'canvaskit_api.dart'; import 'native_memory.dart'; import 'path_metrics.dart'; /// An implementation of [ui.Path] which is backed by an `SkPath`. /// /// The `SkPath` is required for `CkCanvas` methods which take a path. class CkPath implements ui.Path { factory CkPath() { final SkPath skPath = SkPath(); skPath.setFillType(toSkFillType(ui.PathFillType.nonZero)); return CkPath._(skPath, ui.PathFillType.nonZero); } factory CkPath.from(CkPath other) { final SkPath skPath = other.skiaObject.copy(); skPath.setFillType(toSkFillType(other._fillType)); return CkPath._(skPath, other._fillType); } factory CkPath.fromSkPath(SkPath skPath, ui.PathFillType fillType) { skPath.setFillType(toSkFillType(fillType)); return CkPath._(skPath, fillType); } CkPath._(SkPath nativeObject, this._fillType) { _ref = UniqueRef<SkPath>(this, nativeObject, 'Path'); } late final UniqueRef<SkPath> _ref; SkPath get skiaObject => _ref.nativeObject; ui.PathFillType _fillType; @override ui.PathFillType get fillType => _fillType; @override set fillType(ui.PathFillType newFillType) { if (_fillType == newFillType) { return; } _fillType = newFillType; skiaObject.setFillType(toSkFillType(newFillType)); } @override void addArc(ui.Rect oval, double startAngle, double sweepAngle) { const double toDegrees = 180.0 / math.pi; skiaObject.addArc( toSkRect(oval), startAngle * toDegrees, sweepAngle * toDegrees, ); } @override void addOval(ui.Rect oval) { skiaObject.addOval(toSkRect(oval), false, 1); } @override void addPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { List<double> skMatrix; if (matrix4 == null) { skMatrix = toSkMatrixFromFloat32( Matrix4.translationValues(offset.dx, offset.dy, 0.0).storage); } else { skMatrix = toSkMatrixFromFloat64(matrix4); skMatrix[2] += offset.dx; skMatrix[5] += offset.dy; } final CkPath otherPath = path as CkPath; skiaObject.addPath( otherPath.skiaObject, skMatrix[0], skMatrix[1], skMatrix[2], skMatrix[3], skMatrix[4], skMatrix[5], skMatrix[6], skMatrix[7], skMatrix[8], false, ); } @override void addPolygon(List<ui.Offset> points, bool close) { final SkFloat32List encodedPoints = toMallocedSkPoints(points); skiaObject.addPoly(encodedPoints.toTypedArray(), close); free(encodedPoints); } @override void addRRect(ui.RRect rrect) { skiaObject.addRRect( toSkRRect(rrect), false, ); } @override void addRect(ui.Rect rect) { skiaObject.addRect(toSkRect(rect)); } @override void arcTo( ui.Rect rect, double startAngle, double sweepAngle, bool forceMoveTo) { const double toDegrees = 180.0 / math.pi; skiaObject.arcToOval( toSkRect(rect), startAngle * toDegrees, sweepAngle * toDegrees, forceMoveTo, ); } @override void arcToPoint(ui.Offset arcEnd, {ui.Radius radius = ui.Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true}) { skiaObject.arcToRotated( radius.x, radius.y, rotation, !largeArc, !clockwise, arcEnd.dx, arcEnd.dy, ); } @override void close() { skiaObject.close(); } @override ui.PathMetrics computeMetrics({bool forceClosed = false}) { return CkPathMetrics(this, forceClosed); } @override void conicTo(double x1, double y1, double x2, double y2, double w) { skiaObject.conicTo(x1, y1, x2, y2, w); } @override bool contains(ui.Offset point) { return skiaObject.contains(point.dx, point.dy); } @override void cubicTo( double x1, double y1, double x2, double y2, double x3, double y3) { skiaObject.cubicTo(x1, y1, x2, y2, x3, y3); } @override void extendWithPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { List<double> skMatrix; if (matrix4 == null) { skMatrix = toSkMatrixFromFloat32( Matrix4.translationValues(offset.dx, offset.dy, 0.0).storage); } else { skMatrix = toSkMatrixFromFloat64(matrix4); skMatrix[2] += offset.dx; skMatrix[5] += offset.dy; } final CkPath otherPath = path as CkPath; skiaObject.addPath( otherPath.skiaObject, skMatrix[0], skMatrix[1], skMatrix[2], skMatrix[3], skMatrix[4], skMatrix[5], skMatrix[6], skMatrix[7], skMatrix[8], true, ); } @override ui.Rect getBounds() => fromSkRect(skiaObject.getBounds()); @override void lineTo(double x, double y) { skiaObject.lineTo(x, y); } @override void moveTo(double x, double y) { skiaObject.moveTo(x, y); } @override void quadraticBezierTo(double x1, double y1, double x2, double y2) { skiaObject.quadTo(x1, y1, x2, y2); } @override void relativeArcToPoint(ui.Offset arcEndDelta, {ui.Radius radius = ui.Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true}) { skiaObject.rArcTo( radius.x, radius.y, rotation, !largeArc, !clockwise, arcEndDelta.dx, arcEndDelta.dy, ); } @override void relativeConicTo(double x1, double y1, double x2, double y2, double w) { skiaObject.rConicTo(x1, y1, x2, y2, w); } @override void relativeCubicTo( double x1, double y1, double x2, double y2, double x3, double y3) { skiaObject.rCubicTo(x1, y1, x2, y2, x3, y3); } @override void relativeLineTo(double dx, double dy) { skiaObject.rLineTo(dx, dy); } @override void relativeMoveTo(double dx, double dy) { skiaObject.rMoveTo(dx, dy); } @override void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2) { skiaObject.rQuadTo(x1, y1, x2, y2); } @override void reset() { // Only reset the local field. Skia will reset its internal state via // SkPath.reset() below. _fillType = ui.PathFillType.nonZero; skiaObject.reset(); } @override CkPath shift(ui.Offset offset) { // `SkPath.transform` mutates the existing path, so create a copy and call // `transform` on the copy. final SkPath shiftedPath = skiaObject.copy(); shiftedPath.transform( 1.0, 0.0, offset.dx, 0.0, 1.0, offset.dy, 0.0, 0.0, 1.0, ); return CkPath.fromSkPath(shiftedPath, _fillType); } static CkPath combine( ui.PathOperation operation, ui.Path uiPath1, ui.Path uiPath2, ) { final CkPath path1 = uiPath1 as CkPath; final CkPath path2 = uiPath2 as CkPath; final SkPath newPath = canvasKit.Path.MakeFromOp( path1.skiaObject, path2.skiaObject, toSkPathOp(operation), ); return CkPath.fromSkPath(newPath, path1._fillType); } @override ui.Path transform(Float64List matrix4) { final SkPath newPath = skiaObject.copy(); final Float32List m = toSkMatrixFromFloat64(matrix4); newPath.transform( m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], ); return CkPath.fromSkPath(newPath, _fillType); } String? toSvgString() { return skiaObject.toSVGString(); } /// Return `true` if this path contains no segments. bool get isEmpty { return skiaObject.isEmpty(); } }
engine/lib/web_ui/lib/src/engine/canvaskit/path.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/path.dart", "repo_id": "engine", "token_count": 3365 }
261
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; enum ColorFilterType { mode, matrix, linearToSrgbGamma, srgbToLinearGamma, } /// A description of a color filter to apply when drawing a shape or compositing /// a layer with a particular [Paint]. A color filter is a function that takes /// two colors, and outputs one color. When applied during compositing, it is /// independently applied to each pixel of the layer being drawn before the /// entire layer is merged with the destination. /// /// Instances of this class are used with [Paint.colorFilter] on [Paint] /// objects. class EngineColorFilter implements SceneImageFilter, ui.ColorFilter { /// Creates a color filter that applies the blend mode given as the second /// argument. The source color is the one given as the first argument, and the /// destination color is the one from the layer being composited. /// /// The output of this filter is then composited into the background according /// to the [Paint.blendMode], using the output of this filter as the source /// and the background as the destination. const EngineColorFilter.mode(ui.Color this.color, ui.BlendMode this.blendMode) : matrix = null, type = ColorFilterType.mode; /// Construct a color filter that transforms a color by a 5x5 matrix, where /// the fifth row is implicitly added in an identity configuration. /// /// Every pixel's color value, represented as an `[R, G, B, A]`, is matrix /// multiplied to create a new color: /// /// ```text /// | R' | | a00 a01 a02 a03 a04 | | R | /// | G' | | a10 a11 a12 a13 a14 | | G | /// | B' | = | a20 a21 a22 a23 a24 | * | B | /// | A' | | a30 a31 a32 a33 a34 | | A | /// | 1 | | 0 0 0 0 1 | | 1 | /// ``` /// /// The matrix is in row-major order and the translation column is specified /// in unnormalized, 0...255, space. For example, the identity matrix is: /// /// ``` /// const ColorMatrix identity = ColorFilter.matrix(<double>[ /// 1, 0, 0, 0, 0, /// 0, 1, 0, 0, 0, /// 0, 0, 1, 0, 0, /// 0, 0, 0, 1, 0, /// ]); /// ``` /// /// ## Examples /// /// An inversion color matrix: /// /// ``` /// const ColorFilter invert = ColorFilter.matrix(<double>[ /// -1, 0, 0, 0, 255, /// 0, -1, 0, 0, 255, /// 0, 0, -1, 0, 255, /// 0, 0, 0, 1, 0, /// ]); /// ``` /// /// A sepia-toned color matrix (values based on the [Filter Effects Spec](https://www.w3.org/TR/filter-effects-1/#sepiaEquivalent)): /// /// ``` /// const ColorFilter sepia = ColorFilter.matrix(<double>[ /// 0.393, 0.769, 0.189, 0, 0, /// 0.349, 0.686, 0.168, 0, 0, /// 0.272, 0.534, 0.131, 0, 0, /// 0, 0, 0, 1, 0, /// ]); /// ``` /// /// A greyscale color filter (values based on the [Filter Effects Spec](https://www.w3.org/TR/filter-effects-1/#grayscaleEquivalent)): /// /// ``` /// const ColorFilter greyscale = ColorFilter.matrix(<double>[ /// 0.2126, 0.7152, 0.0722, 0, 0, /// 0.2126, 0.7152, 0.0722, 0, 0, /// 0.2126, 0.7152, 0.0722, 0, 0, /// 0, 0, 0, 1, 0, /// ]); /// ``` const EngineColorFilter.matrix(List<double> this.matrix) : color = null, blendMode = null, type = ColorFilterType.matrix; /// Construct a color filter that applies the sRGB gamma curve to the RGB /// channels. const EngineColorFilter.linearToSrgbGamma() : color = null, blendMode = null, matrix = null, type = ColorFilterType.linearToSrgbGamma; /// Creates a color filter that applies the inverse of the sRGB gamma curve /// to the RGB channels. const EngineColorFilter.srgbToLinearGamma() : color = null, blendMode = null, matrix = null, type = ColorFilterType.srgbToLinearGamma; final ui.Color? color; final ui.BlendMode? blendMode; final List<double>? matrix; final ColorFilterType type; /// Color filters don't affect the image bounds @override ui.Rect filterBounds(ui.Rect inputBounds) => inputBounds; @override String toString() { switch (type) { case ColorFilterType.mode: return 'ColorFilter.mode($color, $blendMode)'; case ColorFilterType.matrix: return 'ColorFilter.matrix($matrix)'; case ColorFilterType.linearToSrgbGamma: return 'ColorFilter.linearToSrgbGamma()'; case ColorFilterType.srgbToLinearGamma: return 'ColorFilter.srgbToLinearGamma()'; } } }
engine/lib/web_ui/lib/src/engine/color_filter.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/color_filter.dart", "repo_id": "engine", "token_count": 1747 }
262
// 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 '../dom.dart'; DomHTMLElement _createContainer() { final DomHTMLElement container = createDomHTMLDivElement(); container.style ..position = 'fixed' ..top = '0' ..right = '0' ..padding = '6px' ..color = '#fff' ..backgroundColor = '#000' ..opacity = '0.8'; return container; } /// An overlay in the top right corner of the page that shows statistics /// regarding canvas reuse. /// /// This should only be used for development purposes and never included in /// release builds. class DebugCanvasReuseOverlay { DebugCanvasReuseOverlay._() { final DomHTMLElement container = _createContainer(); final DomHTMLElement title = createDomHTMLDivElement(); title.style ..fontWeight = 'bold' ..textDecoration = 'underline'; title.text = 'Canvas Reuse'; domDocument.body!.append( container ..append(title) ..append( createDomHTMLDivElement() ..appendText('Created: ') ..append(_created), ) ..append( createDomHTMLDivElement() ..appendText('Kept: ') ..append(_kept), ) ..append( createDomHTMLDivElement() ..appendText('Reused: ') ..append(_reused), ) ..append( createDomHTMLDivElement() ..appendText('Disposed: ') ..append(_disposed), ) ..append( createDomHTMLDivElement() ..appendText('In Recycle List: ') ..append(_inRecycle), ) ..append( createDomHTMLDivElement() ..append( createDomHTMLButtonElement() ..text = 'Reset' ..addEventListener('click', createDomEventListener((_) => _reset())), ), ), ); } static DebugCanvasReuseOverlay? _instance; static DebugCanvasReuseOverlay get instance { if (_instance == null) { // Only call the constructor when assertions are enabled to guard against // mistakingly including this class in a release build. assert(() { _instance = DebugCanvasReuseOverlay._(); return true; }()); } return _instance!; } final DomText _created = createDomText('0'); final DomText _kept = createDomText('0'); final DomText _reused = createDomText('0'); final DomText _disposed = createDomText('0'); final DomText _inRecycle = createDomText('0'); int _createdCount = 0; int get createdCount => _createdCount; set createdCount(int createdCount) { _createdCount = createdCount; _update(); } int _keptCount = 0; int get keptCount => _keptCount; set keptCount(int keptCount) { _keptCount = keptCount; _update(); } int _reusedCount = 0; int get reusedCount => _reusedCount; set reusedCount(int reusedCount) { _reusedCount = reusedCount; _update(); } int _disposedCount = 0; int get disposedCount => _disposedCount; set disposedCount(int disposedCount) { _disposedCount = disposedCount; _update(); } int _inRecycleCount = 0; int get inRecycleCount => _inRecycleCount; set inRecycleCount(int inRecycleCount) { _inRecycleCount = inRecycleCount; _update(); } void _update() { _created.text = '$_createdCount'; _kept.text = '$_keptCount'; _reused.text = '$_reusedCount'; _disposed.text = '$_disposedCount'; _inRecycle.text = '$_inRecycleCount'; } void _reset() { _createdCount = _keptCount = _reusedCount = _disposedCount = _inRecycleCount = 0; _update(); } }
engine/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart", "repo_id": "engine", "token_count": 1536 }
263
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:ui/ui.dart' as ui; import '../browser_detection.dart'; import '../dom.dart'; import '../svg.dart'; import 'path/path.dart'; import 'path/path_to_svg.dart'; /// Counter used for generating clip path id inside an svg <defs> tag. int _clipIdCounter = 0; /// Used for clipping and filter svg resources. /// /// Position needs to be absolute since these svgs are sandwiched between /// canvas elements and can cause layout shifts otherwise. final SVGSVGElement kSvgResourceHeader = createSVGSVGElement() ..setAttribute('width', 0) ..setAttribute('height', 0) ..style.position = 'absolute'; /// Converts Path to svg element that contains a clip-path definition. /// /// Calling this method updates [_clipIdCounter]. The HTML id of the generated /// clip is set to "svgClip${_clipIdCounter}", e.g. "svgClip123". SVGSVGElement pathToSvgClipPath(ui.Path path, {double offsetX = 0, double offsetY = 0, double scaleX = 1.0, double scaleY = 1.0}) { _clipIdCounter += 1; final SVGSVGElement root = kSvgResourceHeader.cloneNode(false) as SVGSVGElement; final SVGDefsElement defs = createSVGDefsElement(); root.append(defs); final String clipId = 'svgClip$_clipIdCounter'; final SVGClipPathElement clipPath = createSVGClipPathElement(); defs.append(clipPath); clipPath.id = clipId; final SVGPathElement svgPath = createSVGPathElement(); clipPath.append(svgPath); svgPath.setAttribute('fill', '#FFFFFF'); // Firefox objectBoundingBox fails to scale to 1x1 units, instead use // no clipPathUnits but write the path in target units. if (browserEngine != BrowserEngine.firefox) { clipPath.setAttribute('clipPathUnits', 'objectBoundingBox'); svgPath.setAttribute('transform', 'scale($scaleX, $scaleY)'); } if (path.fillType == ui.PathFillType.evenOdd) { svgPath.setAttribute('clip-rule', 'evenodd'); } else { svgPath.setAttribute('clip-rule', 'nonzero'); } svgPath.setAttribute('d', pathToSvg((path as SurfacePath).pathRef, offsetX: offsetX, offsetY: offsetY)); return root; } String createSvgClipUrl() => 'url(#svgClip$_clipIdCounter)'; /// Resets clip ids. Used for testing by [debugForgetFrameScene] API. void resetSvgClipIds() { _clipIdCounter = 0; }
engine/lib/web_ui/lib/src/engine/html/path_to_svg_clip.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/path_to_svg_clip.dart", "repo_id": "engine", "token_count": 808 }
264
// 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 'dart:async'; import '../display.dart'; import '../dom.dart'; import 'bitmap_canvas.dart'; import 'dom_canvas.dart'; import 'picture.dart'; import 'scene.dart'; import 'surface.dart'; /// Surfaces that were retained this frame. /// /// Surfaces should be added to this list directly. Instead, if a surface needs /// to be retained call [_retainSurface]. List<PersistedSurface> retainedSurfaces = <PersistedSurface>[]; /// Maps every surface currently active on the screen to debug statistics. Map<PersistedSurface, DebugSurfaceStats> surfaceStats = <PersistedSurface, DebugSurfaceStats>{}; List<Map<PersistedSurface, DebugSurfaceStats>> _surfaceStatsTimeline = <Map<PersistedSurface, DebugSurfaceStats>>[]; /// Returns debug statistics for the given [surface]. DebugSurfaceStats surfaceStatsFor(PersistedSurface surface) { if (!debugExplainSurfaceStats) { throw Exception( 'surfaceStatsFor is only available when debugExplainSurfaceStats is set to true.'); } return surfaceStats.putIfAbsent(surface, () => DebugSurfaceStats(surface)); } /// Compositor information collected for one frame useful for assessing the /// efficiency of constructing the frame. /// /// This information is only available in debug mode. /// /// For stats pertaining to a single surface the numeric counter fields are /// typically either 0 or 1. For aggregated stats, the numbers can be >1. class DebugSurfaceStats { DebugSurfaceStats(this.surface); /// The surface these stats are for, or `null` if these are aggregated stats. final PersistedSurface? surface; /// How many times a surface was retained from a previously rendered frame. int retainSurfaceCount = 0; /// How many times a surface reused an HTML element from a previously rendered /// surface. int reuseElementCount = 0; /// If a surface is a [PersistedPicture], how many times it painted. int paintCount = 0; /// If a surface is a [PersistedPicture], how many pixels it painted. int paintPixelCount = 0; /// If a surface is a [PersistedPicture], how many times it reused a /// previously allocated `<canvas>` element when it painted. int reuseCanvasCount = 0; /// If a surface is a [PersistedPicture], how many times it allocated a new /// bitmap canvas. int allocateBitmapCanvasCount = 0; /// If a surface is a [PersistedPicture], how many pixels it allocated for /// the bitmap. /// /// For aggregated stats, this is the total sum of all pixels across all /// canvases. int allocatedBitmapSizeInPixels = 0; /// The number of HTML DOM nodes a surface allocated. /// /// For aggregated stats, this is the total sum of all DOM nodes across all /// surfaces. int allocatedDomNodeCount = 0; /// Adds all counters of [oneSurfaceStats] into this object. void aggregate(DebugSurfaceStats oneSurfaceStats) { retainSurfaceCount += oneSurfaceStats.retainSurfaceCount; reuseElementCount += oneSurfaceStats.reuseElementCount; paintCount += oneSurfaceStats.paintCount; paintPixelCount += oneSurfaceStats.paintPixelCount; reuseCanvasCount += oneSurfaceStats.reuseCanvasCount; allocateBitmapCanvasCount += oneSurfaceStats.allocateBitmapCanvasCount; allocatedBitmapSizeInPixels += oneSurfaceStats.allocatedBitmapSizeInPixels; allocatedDomNodeCount += oneSurfaceStats.allocatedDomNodeCount; } } DomCanvasRenderingContext2D? _debugSurfaceStatsOverlayCtx; void debugRepaintSurfaceStatsOverlay(PersistedScene scene) { final int overlayWidth = domWindow.innerWidth!.toInt(); const int rowHeight = 30; const int rowCount = 4; const int overlayHeight = rowHeight * rowCount; const int strokeWidth = 2; _surfaceStatsTimeline.add(surfaceStats); while (_surfaceStatsTimeline.length > (overlayWidth / strokeWidth)) { _surfaceStatsTimeline.removeAt(0); } if (_debugSurfaceStatsOverlayCtx == null) { final DomCanvasElement debugSurfaceStatsOverlay = createDomCanvasElement( width: overlayWidth, height: overlayHeight, ); debugSurfaceStatsOverlay.style ..position = 'fixed' ..left = '0' ..top = '0' ..zIndex = '1000' ..opacity = '0.8'; _debugSurfaceStatsOverlayCtx = debugSurfaceStatsOverlay.context2D; domDocument.body!.append(debugSurfaceStatsOverlay); } _debugSurfaceStatsOverlayCtx! ..fillStyle = 'black' ..beginPath() ..rect(0, 0, overlayWidth, overlayHeight) ..fill(); final double physicalScreenWidth = domWindow.innerWidth! * EngineFlutterDisplay.instance.browserDevicePixelRatio; final double physicalScreenHeight = domWindow.innerHeight! * EngineFlutterDisplay.instance.browserDevicePixelRatio; final double physicsScreenPixelCount = physicalScreenWidth * physicalScreenHeight; final int totalDomNodeCount = scene.rootElement!.querySelectorAll('*').length; for (int i = 0; i < _surfaceStatsTimeline.length; i++) { final Map<PersistedSurface, DebugSurfaceStats> statsMap = _surfaceStatsTimeline[i]; final DebugSurfaceStats totals = DebugSurfaceStats(null); int pixelCount = 0; for (final DebugSurfaceStats oneSurfaceStats in statsMap.values) { totals.aggregate(oneSurfaceStats); if (oneSurfaceStats.surface is PersistedPicture) { final PersistedPicture picture = oneSurfaceStats.surface! as PersistedPicture; pixelCount += picture.bitmapPixelCount; } } final double repaintRate = totals.paintPixelCount / pixelCount; final double domAllocationRate = totals.allocatedDomNodeCount / totalDomNodeCount; final double bitmapAllocationRate = totals.allocatedBitmapSizeInPixels / physicsScreenPixelCount; final double surfaceRetainRate = totals.retainSurfaceCount / _surfaceStatsTimeline[i].length; // Repaints _debugSurfaceStatsOverlayCtx! ..lineWidth = strokeWidth ..strokeStyle = 'red' ..beginPath() ..moveTo(strokeWidth * i, rowHeight) ..lineTo(strokeWidth * i, rowHeight * (1 - repaintRate)) ..stroke(); // DOM allocations _debugSurfaceStatsOverlayCtx! ..lineWidth = strokeWidth ..strokeStyle = 'red' ..beginPath() ..moveTo(strokeWidth * i, 2 * rowHeight) ..lineTo(strokeWidth * i, rowHeight * (2 - domAllocationRate)) ..stroke(); // Bitmap allocations _debugSurfaceStatsOverlayCtx! ..lineWidth = strokeWidth ..strokeStyle = 'red' ..beginPath() ..moveTo(strokeWidth * i, 3 * rowHeight) ..lineTo(strokeWidth * i, rowHeight * (3 - bitmapAllocationRate)) ..stroke(); // Surface retentions _debugSurfaceStatsOverlayCtx! ..lineWidth = strokeWidth ..strokeStyle = 'green' ..beginPath() ..moveTo(strokeWidth * i, 4 * rowHeight) ..lineTo(strokeWidth * i, rowHeight * (4 - surfaceRetainRate)) ..stroke(); } _debugSurfaceStatsOverlayCtx! ..font = 'normal normal 14px sans-serif' ..fillStyle = 'white' ..fillText('Repaint rate', 5, rowHeight - 5) ..fillText('DOM alloc rate', 5, 2 * rowHeight - 5) ..fillText('Bitmap alloc rate', 5, 3 * rowHeight - 5) ..fillText('Retain rate', 5, 4 * rowHeight - 5); for (int i = 1; i <= rowCount; i++) { _debugSurfaceStatsOverlayCtx! ..lineWidth = 1 ..strokeStyle = 'blue' ..beginPath() ..moveTo(0, overlayHeight - rowHeight * i) ..lineTo(overlayWidth, overlayHeight - rowHeight * i) ..stroke(); } } /// Prints debug statistics for the current frame to the console. void debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { int pictureCount = 0; int paintCount = 0; int bitmapCanvasCount = 0; int bitmapReuseCount = 0; int bitmapAllocationCount = 0; int bitmapPaintCount = 0; int bitmapPixelsAllocated = 0; int domCanvasCount = 0; int domPaintCount = 0; int surfaceRetainCount = 0; int elementReuseCount = 0; int totalAllocatedDomNodeCount = 0; void countReusesRecursively(PersistedSurface surface) { final DebugSurfaceStats stats = surfaceStatsFor(surface); surfaceRetainCount += stats.retainSurfaceCount; elementReuseCount += stats.reuseElementCount; totalAllocatedDomNodeCount += stats.allocatedDomNodeCount; if (surface is PersistedPicture) { pictureCount += 1; paintCount += stats.paintCount; if (surface.canvas is DomCanvas) { domCanvasCount++; domPaintCount += stats.paintCount; } if (surface.canvas is BitmapCanvas) { bitmapCanvasCount++; bitmapPaintCount += stats.paintCount; } bitmapReuseCount += stats.reuseCanvasCount; bitmapAllocationCount += stats.allocateBitmapCanvasCount; bitmapPixelsAllocated += stats.allocatedBitmapSizeInPixels; } surface.visitChildren(countReusesRecursively); } scene.visitChildren(countReusesRecursively); final StringBuffer buf = StringBuffer(); buf ..writeln( '---------------------- FRAME #$frameNumber -------------------------') ..writeln('Surfaces retained: $surfaceRetainCount') ..writeln('Elements reused: $elementReuseCount') ..writeln('Elements allocated: $totalAllocatedDomNodeCount') ..writeln('Pictures: $pictureCount') ..writeln(' Painted: $paintCount') ..writeln(' Skipped painting: ${pictureCount - paintCount}') ..writeln('DOM canvases:') ..writeln(' Painted: $domPaintCount') ..writeln(' Skipped painting: ${domCanvasCount - domPaintCount}') ..writeln('Bitmap canvases: $bitmapCanvasCount') ..writeln(' Painted: $bitmapPaintCount') ..writeln(' Skipped painting: ${bitmapCanvasCount - bitmapPaintCount}') ..writeln(' Reused: $bitmapReuseCount') ..writeln(' Allocated: $bitmapAllocationCount') ..writeln(' Allocated pixels: $bitmapPixelsAllocated') ..writeln(' Available for reuse: ${recycledCanvases.length}'); // A microtask will fire after the DOM is flushed, letting us probe into // actual <canvas> tags. scheduleMicrotask(() { final Iterable<DomElement> canvasElements = domDocument.querySelectorAll('canvas'); final StringBuffer canvasInfo = StringBuffer(); final int pixelCount = canvasElements .cast<DomCanvasElement>() .map<int>((DomCanvasElement e) { final int pixels = (e.width! * e.height!).toInt(); canvasInfo.writeln(' - ${e.width!} x ${e.height!} = $pixels pixels'); return pixels; }).fold(0, (int total, int pixels) => total + pixels); final double physicalScreenWidth = domWindow.innerWidth! * EngineFlutterDisplay.instance.browserDevicePixelRatio; final double physicalScreenHeight = domWindow.innerHeight! * EngineFlutterDisplay.instance.browserDevicePixelRatio; final double physicsScreenPixelCount = physicalScreenWidth * physicalScreenHeight; final double screenPixelRatio = pixelCount / physicsScreenPixelCount; final String screenDescription = '1 screen is $physicalScreenWidth x $physicalScreenHeight = $physicsScreenPixelCount pixels'; final String canvasPixelDescription = '$pixelCount (${screenPixelRatio.toStringAsFixed(2)} x screens'; buf ..writeln(' Elements: ${canvasElements.length}') ..writeln(canvasInfo) ..writeln(' Pixels: $canvasPixelDescription; $screenDescription)') ..writeln('-----------------------------------------------------------'); final bool screenPixelRatioTooHigh = screenPixelRatio > kScreenPixelRatioWarningThreshold; if (screenPixelRatioTooHigh) { print( 'WARNING: pixel/screen ratio too high (${screenPixelRatio.toStringAsFixed(2)}x)'); } print(buf); }); }
engine/lib/web_ui/lib/src/engine/html/surface_stats.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/surface_stats.dart", "repo_id": "engine", "token_count": 3986 }
265
// 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. class NotoFont { NotoFont(this.name, this.url, {this.enabled = true}); final String name; final String url; /// `true` if this font is to be considered as a fallback font. Almost all /// fonts are enabled, but [enabled] may be `false` to exclude a font. This is /// used to choose between color and monochrome emoji fonts - only one of them /// is enabled. final bool enabled; final int index = _index++; static int _index = 0; /// During fallback font selection this is the number of missing code points /// that are covered by (i.e. in) this font. int coverCount = 0; /// During fallback font selection this is a list of [FallbackFontComponent]s /// from this font that are required to cover some of the missing code /// points. The cover count for the font is the sum of the cover counts for /// the components that make up the font. final List<FallbackFontComponent> coverComponents = <FallbackFontComponent>[]; } /// A component is a set of code points common to some fonts. Each code point is /// in a single component. Each font can be represented as a disjoint union of /// components. We store the inverse of this relationship, the fonts that use /// this component. The font fallback selection algorithm does not need the code /// points in a component or a font, so this is not stored, but can be recovered /// via the map from code-point to component. class FallbackFontComponent { FallbackFontComponent(this._allFonts); final List<NotoFont> _allFonts; late final List<NotoFont> _activeFonts = List<NotoFont>.unmodifiable( _allFonts.where((NotoFont font) => font.enabled)); List<NotoFont> get fonts => _activeFonts; /// During fallback font selection this is the number of missing code points /// that are covered by this component. int coverCount = 0; }
engine/lib/web_ui/lib/src/engine/noto_font.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/noto_font.dart", "repo_id": "engine", "token_count": 541 }
266
// 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 'dart:async'; import 'dart:typed_data'; import '../engine.dart' show registerHotRestartListener; import 'browser_detection.dart'; import 'dom.dart'; import 'keyboard_binding.dart'; import 'platform_dispatcher.dart'; import 'services.dart'; /// Provides keyboard bindings, such as the `flutter/keyevent` channel. class RawKeyboard { RawKeyboard._(this._onMacOs) { registerHotRestartListener(() { dispose(); }); } /// Initializes the [RawKeyboard] singleton. /// /// Use the [instance] getter to get the singleton after calling this method. static void initialize({bool onMacOs = false}) { _instance ??= RawKeyboard._(onMacOs); // KeyboardBinding is responsible for forwarding the keyboard // events to the RawKeyboard handler. KeyboardBinding.initInstance(); } /// The [RawKeyboard] singleton. static RawKeyboard? get instance => _instance; static RawKeyboard? _instance; /// A mapping of [KeyboardEvent.code] to [Timer]. /// /// The timer is for when to synthesize a keyup for the [KeyboardEvent.code] /// if no repeat events were received. final Map<String, Timer> _keydownTimers = <String, Timer>{}; /// Uninitializes the [RawKeyboard] singleton. /// /// After calling this method this object becomes unusable and [instance] /// becomes `null`. Call [initialize] again to initialize a new singleton. void dispose() { for (final String key in _keydownTimers.keys) { _keydownTimers[key]!.cancel(); } _keydownTimers.clear(); _instance = null; } static const JSONMessageCodec _messageCodec = JSONMessageCodec(); /// Contains meta state from the latest event. /// /// Initializing with `0x0` which means no meta keys are pressed. int _lastMetaState = 0x0; final bool _onMacOs; // When the user enters a browser/system shortcut (e.g. `cmd+alt+i`) on macOS, // the browser doesn't send a keyup for it. This puts the framework in a // corrupt state because it thinks the key was never released. // // To avoid this, we rely on the fact that browsers send repeat events // while the key is held down by the user. If we don't receive a repeat // event within a specific duration ([_kKeydownCancelDurationMac]) we assume // the user has released the key and we synthesize a keyup event. bool _shouldDoKeyGuard() { return _onMacOs; } bool _shouldIgnore(FlutterHtmlKeyboardEvent event) { // During IME composition, Tab fires twice (once for composition and once // for regular tabbing behavior), which causes issues. Intercepting the // tab keydown event during composition prevents these issues from occurring. // https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event#ignoring_keydown_during_ime_composition return event.type == 'keydown' && event.key == 'Tab' && event.isComposing; } void handleHtmlEvent(DomEvent domEvent) { if (!domInstanceOfString(domEvent, 'KeyboardEvent')) { return; } final FlutterHtmlKeyboardEvent event = FlutterHtmlKeyboardEvent(domEvent as DomKeyboardEvent); final String timerKey = event.code!; if (_shouldIgnore(event)) { return; } // Don't handle synthesizing a keyup event for modifier keys if (!_isModifierKey(event) && _shouldDoKeyGuard()) { _keydownTimers[timerKey]?.cancel(); // Only keys affected by modifiers, require synthesizing // because the browser always sends a keyup event otherwise if (event.type == 'keydown' && _isAffectedByModifiers(event)) { _keydownTimers[timerKey] = Timer(_kKeydownCancelDurationMac, () { _keydownTimers.remove(timerKey); _synthesizeKeyup(event); }); } else { _keydownTimers.remove(timerKey); } } _lastMetaState = _getMetaState(event); if (event.type == 'keydown') { // For lock modifiers _getMetaState won't report a metaState at keydown. // See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState. if (event.key == 'CapsLock') { _lastMetaState |= modifierCapsLock; } else if (event.code == 'NumLock') { _lastMetaState |= modifierNumLock; } else if (event.key == 'ScrollLock') { _lastMetaState |= modifierScrollLock; } else if (event.key == 'Meta' && operatingSystem == OperatingSystem.linux) { // On Chrome Linux, metaState can be wrong when a Meta key is pressed. _lastMetaState |= _modifierMeta; } else if (event.code == 'MetaLeft' && event.key == 'Process') { // When Meta key is pressed, browsers can emit an event whose key is 'Process'. // See https://github.com/flutter/flutter/issues/141186. _lastMetaState |= _modifierMeta; } } final Map<String, dynamic> eventData = <String, dynamic>{ 'type': event.type, 'keymap': 'web', 'code': event.code, 'key': event.key, 'location': event.location, 'metaState': _lastMetaState, 'keyCode': event.keyCode, }; EnginePlatformDispatcher.instance.invokeOnPlatformMessage('flutter/keyevent', _messageCodec.encodeMessage(eventData), (ByteData? data) { if (data == null) { return; } final Map<String, dynamic> jsonResponse = _messageCodec.decodeMessage(data) as Map<String, dynamic>; if (jsonResponse['handled'] as bool) { // If the framework handled it, then don't propagate it any further. event.preventDefault(); event.stopPropagation(); } }, ); } void _synthesizeKeyup(FlutterHtmlKeyboardEvent event) { final Map<String, dynamic> eventData = <String, dynamic>{ 'type': 'keyup', 'keymap': 'web', 'code': event.code, 'key': event.key, 'location': event.location, 'metaState': _lastMetaState, 'keyCode': event.keyCode, }; EnginePlatformDispatcher.instance.invokeOnPlatformMessage('flutter/keyevent', _messageCodec.encodeMessage(eventData), _noopCallback); } /// After a keydown is received, this is the duration we wait for a repeat event /// before we decide to synthesize a keyup event. /// /// This value is only for macOS, where the keyboard repeat delay goes up to /// 2000ms. static const Duration _kKeydownCancelDurationMac = Duration(milliseconds: 2000); } const int _modifierNone = 0x00; const int _modifierShift = 0x01; const int _modifierAlt = 0x02; const int _modifierControl = 0x04; const int _modifierMeta = 0x08; const int modifierNumLock = 0x10; const int modifierCapsLock = 0x20; const int modifierScrollLock = 0x40; /// Creates a bitmask representing the meta state of the [event]. int _getMetaState(FlutterHtmlKeyboardEvent event) { int metaState = _modifierNone; if (event.getModifierState('Shift')) { metaState |= _modifierShift; } if (event.getModifierState('Alt') || event.getModifierState('AltGraph')) { metaState |= _modifierAlt; } if (event.getModifierState('Control')) { metaState |= _modifierControl; } if (event.getModifierState('Meta')) { metaState |= _modifierMeta; } // See https://github.com/flutter/flutter/issues/66601 for why we don't // set the ones below based on persistent state. // if (event.getModifierState("CapsLock")) { // metaState |= modifierCapsLock; // } // if (event.getModifierState("NumLock")) { // metaState |= modifierNumLock; // } // if (event.getModifierState("ScrollLock")) { // metaState |= modifierScrollLock; // } return metaState; } /// Returns true if the [event] was caused by a modifier key. /// /// Modifier keys are shift, alt, ctrl and meta/cmd/win. These are the keys used /// to perform keyboard shortcuts (e.g. `cmd+c`, `cmd+l`). bool _isModifierKey(FlutterHtmlKeyboardEvent event) { final String key = event.key!; return key == 'Meta' || key == 'Shift' || key == 'Alt' || key == 'Control'; } /// Returns true if the [event] is been affects by any of the modifiers key /// /// This is a strong indication that this key is been used for a shortcut bool _isAffectedByModifiers(FlutterHtmlKeyboardEvent event) { return event.ctrlKey || event.shiftKey || event.altKey || event.metaKey; } void _noopCallback(ByteData? data) {}
engine/lib/web_ui/lib/src/engine/raw_keyboard.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/raw_keyboard.dart", "repo_id": "engine", "token_count": 2931 }
267
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:meta/meta.dart'; import '../platform_dispatcher.dart'; import 'accessibility.dart'; import 'label_and_value.dart'; import 'semantics.dart'; /// Manages semantics configurations that represent live regions. /// /// Assistive technologies treat "aria-live" attribute differently. To keep /// the behavior consistent, [AccessibilityAnnouncements.announce] is used. /// /// When there is an update to [LiveRegion], assistive technologies read the /// label of the element. See [LabelAndValue]. If there is no label provided /// no content will be read. class LiveRegion extends RoleManager { LiveRegion(SemanticsObject semanticsObject, PrimaryRoleManager owner) : super(Role.liveRegion, semanticsObject, owner); String? _lastAnnouncement; static AccessibilityAnnouncements? _accessibilityAnnouncementsOverride; @visibleForTesting static void debugOverrideAccessibilityAnnouncements(AccessibilityAnnouncements? value) { _accessibilityAnnouncementsOverride = value; } AccessibilityAnnouncements get _accessibilityAnnouncements => _accessibilityAnnouncementsOverride ?? EnginePlatformDispatcher.instance.implicitView!.accessibilityAnnouncements; @override void update() { if (!semanticsObject.isLiveRegion) { return; } // Avoid announcing the same message over and over. if (_lastAnnouncement != semanticsObject.label) { _lastAnnouncement = semanticsObject.label; if (semanticsObject.hasLabel) { _accessibilityAnnouncements.announce( _lastAnnouncement!, Assertiveness.polite, ); } } } }
engine/lib/web_ui/lib/src/engine/semantics/live_region.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/semantics/live_region.dart", "repo_id": "engine", "token_count": 540 }
268
// 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 'dart:js_interop'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; class SkwasmImageDecoder extends BrowserImageDecoder { SkwasmImageDecoder({ required super.contentType, required super.dataSource, required super.debugSource, }); @override ui.Image generateImageFromVideoFrame(VideoFrame frame) { final int width = frame.codedWidth.toInt(); final int height = frame.codedHeight.toInt(); final SkwasmSurface surface = (renderer as SkwasmRenderer).surface; return SkwasmImage(imageCreateFromTextureSource( frame as JSObject, width, height, surface.handle, )); } }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/codecs.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/codecs.dart", "repo_id": "engine", "token_count": 307 }
269
// 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. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:convert'; import 'dart:ffi'; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; final class Stack extends Opaque {} typedef StackPointer = Pointer<Stack>; /// Generic linear memory allocation @Native<StackPointer Function(Size)>(symbol: 'stackAlloc', isLeaf: true) external StackPointer stackAlloc(int length); @Native<StackPointer Function()>(symbol: 'stackSave', isLeaf: true) external StackPointer stackSave(); @Native<Void Function(StackPointer)>(symbol: 'stackRestore', isLeaf: true) external void stackRestore(StackPointer pointer); class StackScope { Pointer<Int8> convertStringToNative(String string) { final Uint8List encoded = utf8.encode(string); final Pointer<Int8> pointer = allocInt8Array(encoded.length + 1); for (int i = 0; i < encoded.length; i++) { pointer[i] = encoded[i]; } pointer[encoded.length] = 0; return pointer; } Pointer<Float> convertMatrix4toSkMatrix(List<double> matrix4) { final Pointer<Float> pointer = allocFloatArray(9); final int matrixLength = matrix4.length; double getVal(int index) { return (index < matrixLength) ? matrix4[index] : 0.0; } pointer[0] = getVal(0); pointer[1] = getVal(4); pointer[2] = getVal(12); pointer[3] = getVal(1); pointer[4] = getVal(5); pointer[5] = getVal(13); pointer[6] = getVal(3); pointer[7] = getVal(7); pointer[8] = getVal(15); return pointer; } Pointer<Float> convertMatrix44toNative(Float64List matrix4) { assert(matrix4.length == 16); final Pointer<Float> pointer = allocFloatArray(16); for (int i = 0; i < 16; i++) { pointer[i] = matrix4[i]; } return pointer; } Float64List convertMatrix44FromNative(Pointer<Float> buffer) { final Float64List matrix = Float64List(16); for (int i = 0; i < 16; i++) { matrix[i] = buffer[i]; } return matrix; } Pointer<Float> convertRectToNative(ui.Rect rect) { final Pointer<Float> pointer = allocFloatArray(4); pointer[0] = rect.left; pointer[1] = rect.top; pointer[2] = rect.right; pointer[3] = rect.bottom; return pointer; } Pointer<Float> convertRectsToNative(List<ui.Rect> rects) { final Pointer<Float> pointer = allocFloatArray(rects.length * 4); for (int i = 0; i < rects.length; i++) { final ui.Rect rect = rects[i]; pointer[i * 4] = rect.left; pointer[i * 4 + 1] = rect.top; pointer[i * 4 + 2] = rect.right; pointer[i * 4 + 3] = rect.bottom; } return pointer; } ui.Rect convertRectFromNative(Pointer<Float> buffer) { return ui.Rect.fromLTRB( buffer[0], buffer[1], buffer[2], buffer[3], ); } Pointer<Int32> convertIRectToNative(ui.Rect rect) { final Pointer<Int32> pointer = allocInt32Array(4); pointer[0] = rect.left.floor(); pointer[1] = rect.top.floor(); pointer[2] = rect.right.ceil(); pointer[3] = rect.bottom.ceil(); return pointer; } ui.Rect convertIRectFromNative(Pointer<Int32> buffer) { return ui.Rect.fromLTRB( buffer[0].toDouble(), buffer[1].toDouble(), buffer[2].toDouble(), buffer[3].toDouble(), ); } Pointer<Float> convertRRectToNative(ui.RRect rect) { final Pointer<Float> pointer = allocFloatArray(12); pointer[0] = rect.left; pointer[1] = rect.top; pointer[2] = rect.right; pointer[3] = rect.bottom; pointer[4] = rect.tlRadiusX; pointer[5] = rect.tlRadiusY; pointer[6] = rect.trRadiusX; pointer[7] = rect.trRadiusY; pointer[8] = rect.brRadiusX; pointer[9] = rect.brRadiusY; pointer[10] = rect.blRadiusX; pointer[11] = rect.blRadiusY; return pointer; } Pointer<Float> convertRSTransformsToNative(List<ui.RSTransform> transforms) { final Pointer<Float> pointer = allocFloatArray(transforms.length * 4); for (int i = 0; i < transforms.length; i++) { final ui.RSTransform transform = transforms[i]; pointer[i * 4] = transform.scos; pointer[i * 4 + 1] = transform.ssin; pointer[i * 4 + 2] = transform.tx; pointer[i * 4 + 3] = transform.ty; } return pointer; } Pointer<Float> convertDoublesToNative(List<double> values) { final Pointer<Float> pointer = allocFloatArray(values.length); for (int i = 0; i < values.length; i++) { pointer[i] = values[i]; } return pointer; } Pointer<Uint16> convertIntsToUint16Native(List<int> values) { final Pointer<Uint16> pointer = allocUint16Array(values.length); for (int i = 0; i < values.length; i++) { pointer[i] = values[i]; } return pointer; } Pointer<Uint32> convertIntsToUint32Native(List<int> values) { final Pointer<Uint32> pointer = allocUint32Array(values.length); for (int i = 0; i < values.length; i++) { pointer[i] = values[i]; } return pointer; } Pointer<Float> convertPointArrayToNative(List<ui.Offset> points) { final Pointer<Float> pointer = allocFloatArray(points.length * 2); for (int i = 0; i < points.length; i++) { pointer[i * 2] = points[i].dx; pointer[i * 2 + 1] = points[i].dy; } return pointer; } Pointer<Uint32> convertColorArrayToNative(List<ui.Color> colors) { final Pointer<Uint32> pointer = allocUint32Array(colors.length); for (int i = 0; i < colors.length; i++) { pointer[i] = colors[i].value; } return pointer; } Pointer<Bool> allocBoolArray(int count) { final int length = count * sizeOf<Bool>(); return stackAlloc(length).cast<Bool>(); } Pointer<Int8> allocInt8Array(int count) { final int length = count * sizeOf<Int8>(); return stackAlloc(length).cast<Int8>(); } Pointer<Uint16> allocUint16Array(int count) { final int length = count * sizeOf<Uint16>(); return stackAlloc(length).cast<Uint16>(); } Pointer<Int32> allocInt32Array(int count) { final int length = count * sizeOf<Int32>(); return stackAlloc(length).cast<Int32>(); } Pointer<Uint32> allocUint32Array(int count) { final int length = count * sizeOf<Uint32>(); return stackAlloc(length).cast<Uint32>(); } Pointer<Float> allocFloatArray(int count) { final int length = count * sizeOf<Float>(); return stackAlloc(length).cast<Float>(); } Pointer<Pointer<Void>> allocPointerArray(int count) { final int length = count * sizeOf<Pointer<Void>>(); return stackAlloc(length).cast<Pointer<Void>>(); } } T withStackScope<T>(T Function(StackScope scope) f) { final StackPointer stack = stackSave(); final T result = f(StackScope()); stackRestore(stack); return result; }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_memory.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_memory.dart", "repo_id": "engine", "token_count": 2721 }
270
// 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. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:ffi'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; final class RawTextStyle extends Opaque {} typedef TextStyleHandle = Pointer<RawTextStyle>; @Native<TextStyleHandle Function()>(symbol: 'textStyle_create', isLeaf: true) external TextStyleHandle textStyleCreate(); @Native<TextStyleHandle Function(TextStyleHandle)>(symbol: 'textStyle_copy', isLeaf: true) external TextStyleHandle textStyleCopy(TextStyleHandle handle); @Native<Void Function(TextStyleHandle)>(symbol: 'textStyle_dispose', isLeaf: true) external void textStyleDispose(TextStyleHandle handle); @Native<Void Function(TextStyleHandle, Int32)>(symbol: 'textStyle_setColor', isLeaf: true) external void textStyleSetColor(TextStyleHandle handle, int color); @Native<Void Function(TextStyleHandle, Int)>(symbol: 'textStyle_setDecoration', isLeaf: true) external void textStyleSetDecoration(TextStyleHandle handle, int decoration); @Native<Void Function(TextStyleHandle, Int32)>(symbol: 'textStyle_setDecorationColor', isLeaf: true) external void textStyleSetDecorationColor(TextStyleHandle handle, int decorationColor); @Native<Void Function(TextStyleHandle, Int)>(symbol: 'textStyle_setDecorationStyle', isLeaf: true) external void textStyleSetDecorationStyle(TextStyleHandle handle, int decorationStyle); @Native<Void Function(TextStyleHandle, Float)>(symbol: 'textStyle_setDecorationThickness', isLeaf: true) external void textStyleSetDecorationThickness(TextStyleHandle handle, double decorationThickness); @Native<Void Function( TextStyleHandle, Int, Int )>(symbol: 'textStyle_setFontStyle', isLeaf: true) external void textStyleSetFontStyle( TextStyleHandle handle, int weight, int slant ); @Native<Void Function(TextStyleHandle, Int)>(symbol: 'textStyle_setTextBaseline', isLeaf: true) external void textStyleSetTextBaseline(TextStyleHandle handle, int baseline); @Native<Void Function(TextStyleHandle)>(symbol: 'textStyle_clearFontFamilies', isLeaf: true) external void textStyleClearFontFamilies(TextStyleHandle handle); @Native<Void Function( TextStyleHandle, Pointer<SkStringHandle>, Int count )>(symbol: 'textStyle_addFontFamilies', isLeaf: true) external void textStyleAddFontFamilies( TextStyleHandle handle, Pointer<SkStringHandle> families, int count ); @Native<Void Function(TextStyleHandle, Float)>(symbol: 'textStyle_setFontSize', isLeaf: true) external void textStyleSetFontSize(TextStyleHandle handle, double size); @Native<Void Function(TextStyleHandle, Float)>(symbol: 'textStyle_setLetterSpacing', isLeaf: true) external void textStyleSetLetterSpacing(TextStyleHandle handle, double spacing); @Native<Void Function(TextStyleHandle, Float)>(symbol: 'textStyle_setWordSpacing', isLeaf: true) external void textStyleSetWordSpacing(TextStyleHandle handle, double spacing); @Native<Void Function(TextStyleHandle, Float)>(symbol: 'textStyle_setHeight', isLeaf: true) external void textStyleSetHeight(TextStyleHandle handle, double height); @Native<Void Function(TextStyleHandle, Bool)>(symbol: 'textStyle_setHalfLeading', isLeaf: true) external void textStyleSetHalfLeading(TextStyleHandle handle, bool halfLeading); @Native<Void Function(TextStyleHandle, SkStringHandle)>(symbol: 'textStyle_setLocale', isLeaf: true) external void textStyleSetLocale(TextStyleHandle handle, SkStringHandle locale); @Native<Void Function(TextStyleHandle, PaintHandle)>(symbol: 'textStyle_setBackground', isLeaf: true) external void textStyleSetBackground(TextStyleHandle handle, PaintHandle paint); @Native<Void Function(TextStyleHandle, PaintHandle)>(symbol: 'textStyle_setForeground', isLeaf: true) external void textStyleSetForeground(TextStyleHandle handle, PaintHandle paint); @Native<Void Function( TextStyleHandle, Int32, Float, Float, Float, )>(symbol: 'textStyle_addShadow', isLeaf: true) external void textStyleAddShadow( TextStyleHandle handle, int color, double offsetX, double offsetY, double blurSigma, ); @Native<Void Function( TextStyleHandle, SkStringHandle, Int )>(symbol: 'textStyle_addFontFeature', isLeaf: true) external void textStyleAddFontFeature( TextStyleHandle handle, SkStringHandle featureName, int value, ); @Native<Void Function( TextStyleHandle, Pointer<Uint32>, Pointer<Float>, Int )>(symbol: 'textStyle_setFontVariations', isLeaf: true) external void textStyleSetFontVariations( TextStyleHandle handle, Pointer<Uint32> axes, Pointer<Float> values, int count, );
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/text/raw_text_style.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/text/raw_text_style.dart", "repo_id": "engine", "token_count": 1442 }
271
// 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 'dart:js_interop'; import '../dom.dart'; import 'fragmenter.dart'; import 'line_break_properties.dart'; import 'unicode_range.dart'; const Set<int> _kNewlines = <int>{ 0x000A, // LF 0x000B, // BK 0x000C, // BK 0x000D, // CR 0x0085, // NL 0x2028, // BK 0x2029, // BK }; const Set<int> _kSpaces = <int>{ 0x0020, // SP 0x200B, // ZW }; /// Various types of line breaks as defined by the Unicode spec. enum LineBreakType { /// Indicates that a line break is possible but not mandatory. opportunity, /// Indicates that a line break isn't possible. prohibited, /// Indicates that this is a hard line break that can't be skipped. mandatory, /// Indicates the end of the text (which is also considered a line break in /// the Unicode spec). This is the same as [mandatory] but it's needed in our /// implementation to distinguish between the universal [endOfText] and the /// line break caused by "\n" at the end of the text. endOfText, } /// Splits [text] into fragments based on line breaks. abstract class LineBreakFragmenter extends TextFragmenter { factory LineBreakFragmenter(String text) { if (domIntl.v8BreakIterator != null) { return V8LineBreakFragmenter(text); } return FWLineBreakFragmenter(text); } @override List<LineBreakFragment> fragment(); } /// Flutter web's custom implementation of [LineBreakFragmenter]. class FWLineBreakFragmenter extends TextFragmenter implements LineBreakFragmenter { FWLineBreakFragmenter(super.text); @override List<LineBreakFragment> fragment() { return _computeLineBreakFragments(text); } } /// An implementation of [LineBreakFragmenter] that uses V8's /// `v8BreakIterator` API to find line breaks in the given [text]. class V8LineBreakFragmenter extends TextFragmenter implements LineBreakFragmenter { V8LineBreakFragmenter(super.text) : assert(domIntl.v8BreakIterator != null); final DomV8BreakIterator _v8BreakIterator = createV8BreakIterator(); @override List<LineBreakFragment> fragment() { return breakLinesUsingV8BreakIterator(text, text.toJS, _v8BreakIterator); } } List<LineBreakFragment> breakLinesUsingV8BreakIterator(String text, JSString jsText, DomV8BreakIterator iterator) { final List<LineBreakFragment> breaks = <LineBreakFragment>[]; int fragmentStart = 0; iterator.adoptText(jsText); iterator.first(); while (iterator.next() != -1) { final int fragmentEnd = iterator.current().toInt(); int trailingNewlines = 0; int trailingSpaces = 0; // Calculate trailing newlines and spaces. for (int i = fragmentStart; i < fragmentEnd; i++) { final int codeUnit = text.codeUnitAt(i); if (_kNewlines.contains(codeUnit)) { trailingNewlines++; trailingSpaces++; } else if (_kSpaces.contains(codeUnit)) { trailingSpaces++; } else { // Always break after a sequence of spaces. if (trailingSpaces > 0) { breaks.add(LineBreakFragment( fragmentStart, i, LineBreakType.opportunity, trailingNewlines: trailingNewlines, trailingSpaces: trailingSpaces, )); fragmentStart = i; trailingNewlines = 0; trailingSpaces = 0; } } } final LineBreakType type; if (trailingNewlines > 0) { type = LineBreakType.mandatory; } else if (fragmentEnd == text.length) { type = LineBreakType.endOfText; } else { type = LineBreakType.opportunity; } breaks.add(LineBreakFragment( fragmentStart, fragmentEnd, type, trailingNewlines: trailingNewlines, trailingSpaces: trailingSpaces, )); fragmentStart = fragmentEnd; } if (breaks.isEmpty || breaks.last.type == LineBreakType.mandatory) { breaks.add(LineBreakFragment(text.length, text.length, LineBreakType.endOfText, trailingNewlines: 0, trailingSpaces: 0)); } return breaks; } class LineBreakFragment extends TextFragment { const LineBreakFragment(super.start, super.end, this.type, { required this.trailingNewlines, required this.trailingSpaces, }); final LineBreakType type; final int trailingNewlines; final int trailingSpaces; @override int get hashCode => Object.hash(start, end, type, trailingNewlines, trailingSpaces); @override bool operator ==(Object other) { return other is LineBreakFragment && other.start == start && other.end == end && other.type == type && other.trailingNewlines == trailingNewlines && other.trailingSpaces == trailingSpaces; } @override String toString() { return 'LineBreakFragment($start, $end, $type)'; } } bool _isHardBreak(LineCharProperty? prop) { // No need to check for NL because it's already normalized to BK. return prop == LineCharProperty.LF || prop == LineCharProperty.BK; } bool _isALorHL(LineCharProperty? prop) { return prop == LineCharProperty.AL || prop == LineCharProperty.HL; } /// Whether the given property is part of a Korean Syllable block. /// /// See: /// - https://unicode.org/reports/tr14/tr14-45.html#LB27 bool _isKoreanSyllable(LineCharProperty? prop) { return prop == LineCharProperty.JL || prop == LineCharProperty.JV || prop == LineCharProperty.JT || prop == LineCharProperty.H2 || prop == LineCharProperty.H3; } /// Whether the given char code has an Eastern Asian width property of F, W or H. /// /// See: /// - https://www.unicode.org/reports/tr14/tr14-45.html#LB30 /// - https://www.unicode.org/Public/13.0.0/ucd/EastAsianWidth.txt bool _hasEastAsianWidthFWH(int charCode) { return charCode == 0x2329 || (charCode >= 0x3008 && charCode <= 0x301D) || (charCode >= 0xFE17 && charCode <= 0xFF62); } bool _isSurrogatePair(int? codePoint) { return codePoint != null && codePoint > 0xFFFF; } /// Finds the next line break in the given [text] starting from [index]. /// /// We think about indices as pointing between characters, and they go all the /// way from 0 to the string length. For example, here are the indices for the /// string "foo bar": /// /// ``` /// f o o b a r /// ^ ^ ^ ^ ^ ^ ^ ^ /// 0 1 2 3 4 5 6 7 /// ``` /// /// This way the indices work well with [String.substring]. /// /// Useful resources: /// /// * https://www.unicode.org/reports/tr14/tr14-45.html#Algorithm /// * https://www.unicode.org/Public/11.0.0/ucd/LineBreak.txt List<LineBreakFragment> _computeLineBreakFragments(String text) { final List<LineBreakFragment> fragments = <LineBreakFragment>[]; // Keeps track of the character two positions behind. LineCharProperty? prev2; LineCharProperty? prev1; int? codePoint = getCodePoint(text, 0); LineCharProperty? curr = lineLookup.findForChar(codePoint); // When there's a sequence of combining marks, this variable contains the base // property i.e. the property of the character preceding the sequence. LineCharProperty baseOfCombiningMarks = LineCharProperty.AL; int index = 0; int trailingNewlines = 0; int trailingSpaces = 0; int fragmentStart = 0; void setBreak(LineBreakType type, int debugRuleNumber) { final int fragmentEnd = type == LineBreakType.endOfText ? text.length : index; assert(fragmentEnd >= fragmentStart); // Uncomment the following line to help debug line breaking. // print('{$fragmentStart:$fragmentEnd} [$debugRuleNumber] -- $type'); if (prev1 == LineCharProperty.SP) { trailingSpaces++; } else if (_isHardBreak(prev1) || prev1 == LineCharProperty.CR) { trailingNewlines++; trailingSpaces++; } if (type == LineBreakType.prohibited) { // Don't create a fragment. return; } fragments.add(LineBreakFragment( fragmentStart, fragmentEnd, type, trailingNewlines: trailingNewlines, trailingSpaces: trailingSpaces, )); fragmentStart = index; // Reset trailing spaces/newlines counter after a new fragment. trailingNewlines = 0; trailingSpaces = 0; prev1 = prev2 = null; } // Never break at the start of text. // LB2: sot × setBreak(LineBreakType.prohibited, 2); // Never break at the start of text. // LB2: sot × // // Skip index 0 because a line break can't exist at the start of text. index++; int regionalIndicatorCount = 0; // We need to go until `text.length` in order to handle the case where the // paragraph ends with a hard break. In this case, there will be an empty line // at the end. for (; index <= text.length; index++) { prev2 = prev1; prev1 = curr; if (_isSurrogatePair(codePoint)) { // Can't break in the middle of a surrogate pair. setBreak(LineBreakType.prohibited, -1); // Advance `index` one extra step to skip the tail of the surrogate pair. index++; } codePoint = getCodePoint(text, index); curr = lineLookup.findForChar(codePoint); // Keep count of the RI (regional indicator) sequence. if (prev1 == LineCharProperty.RI) { regionalIndicatorCount++; } else { regionalIndicatorCount = 0; } // Always break after hard line breaks. // LB4: BK ! // // Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks. // LB5: LF ! // NL ! if (_isHardBreak(prev1)) { setBreak(LineBreakType.mandatory, 5); continue; } if (prev1 == LineCharProperty.CR) { if (curr == LineCharProperty.LF) { // LB5: CR × LF setBreak(LineBreakType.prohibited, 5); } else { // LB5: CR ! setBreak(LineBreakType.mandatory, 5); } continue; } // Do not break before hard line breaks. // LB6: × ( BK | CR | LF | NL ) if (_isHardBreak(curr) || curr == LineCharProperty.CR) { setBreak(LineBreakType.prohibited, 6); continue; } if (index >= text.length) { break; } // Do not break before spaces or zero width space. // LB7: × SP // × ZW if (curr == LineCharProperty.SP || curr == LineCharProperty.ZW) { setBreak(LineBreakType.prohibited, 7); continue; } // Break after spaces. // LB18: SP ÷ if (prev1 == LineCharProperty.SP) { setBreak(LineBreakType.opportunity, 18); continue; } // Break before any character following a zero-width space, even if one or // more spaces intervene. // LB8: ZW SP* ÷ if (prev1 == LineCharProperty.ZW) { setBreak(LineBreakType.opportunity, 8); continue; } // Do not break after a zero width joiner. // LB8a: ZWJ × if (prev1 == LineCharProperty.ZWJ) { setBreak(LineBreakType.prohibited, 8); continue; } // Establish the base for the sequences of combining marks. if (prev1 != LineCharProperty.CM && prev1 != LineCharProperty.ZWJ) { baseOfCombiningMarks = prev1 ?? LineCharProperty.AL; } // Do not break a combining character sequence; treat it as if it has the // line breaking class of the base character in all of the following rules. // Treat ZWJ as if it were CM. if (curr == LineCharProperty.CM || curr == LineCharProperty.ZWJ) { if (baseOfCombiningMarks == LineCharProperty.SP) { // LB10: Treat any remaining combining mark or ZWJ as AL. curr = LineCharProperty.AL; } else { // LB9: Treat X (CM | ZWJ)* as if it were X // where X is any line break class except BK, NL, LF, CR, SP, or ZW. curr = baseOfCombiningMarks; if (curr == LineCharProperty.RI) { // Prevent the previous RI from being double-counted. regionalIndicatorCount--; } setBreak(LineBreakType.prohibited, 9); continue; } } // In certain situations (e.g. CM immediately following a hard break), we // need to also check if the previous character was CM/ZWJ. That's because // hard breaks caused the previous iteration to short-circuit, which leads // to `baseOfCombiningMarks` not being updated properly. if (prev1 == LineCharProperty.CM || prev1 == LineCharProperty.ZWJ) { prev1 = baseOfCombiningMarks; } // Do not break before or after Word joiner and related characters. // LB11: × WJ // WJ × if (curr == LineCharProperty.WJ || prev1 == LineCharProperty.WJ) { setBreak(LineBreakType.prohibited, 11); continue; } // Do not break after NBSP and related characters. // LB12: GL × if (prev1 == LineCharProperty.GL) { setBreak(LineBreakType.prohibited, 12); continue; } // Do not break before NBSP and related characters, except after spaces and // hyphens. // LB12a: [^SP BA HY] × GL if (!(prev1 == LineCharProperty.SP || prev1 == LineCharProperty.BA || prev1 == LineCharProperty.HY) && curr == LineCharProperty.GL) { setBreak(LineBreakType.prohibited, 12); continue; } // Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces. // LB13: × CL // × CP // × EX // × IS // × SY // // The above is a quote from unicode.org. In our implementation, we did the // following modification: When there are spaces present, we consider it a // line break opportunity. // // We made this modification to match the browser behavior. if (prev1 != LineCharProperty.SP && (curr == LineCharProperty.CL || curr == LineCharProperty.CP || curr == LineCharProperty.EX || curr == LineCharProperty.IS || curr == LineCharProperty.SY)) { setBreak(LineBreakType.prohibited, 13); continue; } // Do not break after ‘[’, even after spaces. // LB14: OP SP* × // // The above is a quote from unicode.org. In our implementation, we did the // following modification: Allow breaks when there are spaces. // // We made this modification to match the browser behavior. if (prev1 == LineCharProperty.OP) { setBreak(LineBreakType.prohibited, 14); continue; } // Do not break within ‘”[’, even with intervening spaces. // LB15: QU SP* × OP // // The above is a quote from unicode.org. In our implementation, we did the // following modification: Allow breaks when there are spaces. // // We made this modification to match the browser behavior. if (prev1 == LineCharProperty.QU && curr == LineCharProperty.OP) { setBreak(LineBreakType.prohibited, 15); continue; } // Do not break between closing punctuation and a nonstarter, even with // intervening spaces. // LB16: (CL | CP) SP* × NS // // The above is a quote from unicode.org. In our implementation, we did the // following modification: Allow breaks when there are spaces. // // We made this modification to match the browser behavior. if ((prev1 == LineCharProperty.CL || prev1 == LineCharProperty.CP) && curr == LineCharProperty.NS) { setBreak(LineBreakType.prohibited, 16); continue; } // Do not break within ‘——’, even with intervening spaces. // LB17: B2 SP* × B2 // // The above is a quote from unicode.org. In our implementation, we did the // following modification: Allow breaks when there are spaces. // // We made this modification to match the browser behavior. if (prev1 == LineCharProperty.B2 && curr == LineCharProperty.B2) { setBreak(LineBreakType.prohibited, 17); continue; } // Do not break before or after quotation marks, such as ‘”’. // LB19: × QU // QU × if (prev1 == LineCharProperty.QU || curr == LineCharProperty.QU) { setBreak(LineBreakType.prohibited, 19); continue; } // Break before and after unresolved CB. // LB20: ÷ CB // CB ÷ // // In flutter web, we use this as an object-replacement character for // placeholders. if (prev1 == LineCharProperty.CB || curr == LineCharProperty.CB) { setBreak(LineBreakType.opportunity, 20); continue; } // Do not break before hyphen-minus, other hyphens, fixed-width spaces, // small kana, and other non-starters, or after acute accents. // LB21: × BA // × HY // × NS // BB × if (curr == LineCharProperty.BA || curr == LineCharProperty.HY || curr == LineCharProperty.NS || prev1 == LineCharProperty.BB) { setBreak(LineBreakType.prohibited, 21); continue; } // Don't break after Hebrew + Hyphen. // LB21a: HL (HY | BA) × if (prev2 == LineCharProperty.HL && (prev1 == LineCharProperty.HY || prev1 == LineCharProperty.BA)) { setBreak(LineBreakType.prohibited, 21); continue; } // Don’t break between Solidus and Hebrew letters. // LB21b: SY × HL if (prev1 == LineCharProperty.SY && curr == LineCharProperty.HL) { setBreak(LineBreakType.prohibited, 21); continue; } // Do not break before ellipses. // LB22: × IN if (curr == LineCharProperty.IN) { setBreak(LineBreakType.prohibited, 22); continue; } // Do not break between digits and letters. // LB23: (AL | HL) × NU // NU × (AL | HL) if ((_isALorHL(prev1) && curr == LineCharProperty.NU) || (prev1 == LineCharProperty.NU && _isALorHL(curr))) { setBreak(LineBreakType.prohibited, 23); continue; } // Do not break between numeric prefixes and ideographs, or between // ideographs and numeric postfixes. // LB23a: PR × (ID | EB | EM) if (prev1 == LineCharProperty.PR && (curr == LineCharProperty.ID || curr == LineCharProperty.EB || curr == LineCharProperty.EM)) { setBreak(LineBreakType.prohibited, 23); continue; } // LB23a: (ID | EB | EM) × PO if ((prev1 == LineCharProperty.ID || prev1 == LineCharProperty.EB || prev1 == LineCharProperty.EM) && curr == LineCharProperty.PO) { setBreak(LineBreakType.prohibited, 23); continue; } // Do not break between numeric prefix/postfix and letters, or between // letters and prefix/postfix. // LB24: (PR | PO) × (AL | HL) if ((prev1 == LineCharProperty.PR || prev1 == LineCharProperty.PO) && _isALorHL(curr)) { setBreak(LineBreakType.prohibited, 24); continue; } // LB24: (AL | HL) × (PR | PO) if (_isALorHL(prev1) && (curr == LineCharProperty.PR || curr == LineCharProperty.PO)) { setBreak(LineBreakType.prohibited, 24); continue; } // Do not break between the following pairs of classes relevant to numbers. // LB25: (CL | CP | NU) × (PO | PR) if ((prev1 == LineCharProperty.CL || prev1 == LineCharProperty.CP || prev1 == LineCharProperty.NU) && (curr == LineCharProperty.PO || curr == LineCharProperty.PR)) { setBreak(LineBreakType.prohibited, 25); continue; } // LB25: (PO | PR) × OP if ((prev1 == LineCharProperty.PO || prev1 == LineCharProperty.PR) && curr == LineCharProperty.OP) { setBreak(LineBreakType.prohibited, 25); continue; } // LB25: (PO | PR | HY | IS | NU | SY) × NU if ((prev1 == LineCharProperty.PO || prev1 == LineCharProperty.PR || prev1 == LineCharProperty.HY || prev1 == LineCharProperty.IS || prev1 == LineCharProperty.NU || prev1 == LineCharProperty.SY) && curr == LineCharProperty.NU) { setBreak(LineBreakType.prohibited, 25); continue; } // Do not break a Korean syllable. // LB26: JL × (JL | JV | H2 | H3) if (prev1 == LineCharProperty.JL && (curr == LineCharProperty.JL || curr == LineCharProperty.JV || curr == LineCharProperty.H2 || curr == LineCharProperty.H3)) { setBreak(LineBreakType.prohibited, 26); continue; } // LB26: (JV | H2) × (JV | JT) if ((prev1 == LineCharProperty.JV || prev1 == LineCharProperty.H2) && (curr == LineCharProperty.JV || curr == LineCharProperty.JT)) { setBreak(LineBreakType.prohibited, 26); continue; } // LB26: (JT | H3) × JT if ((prev1 == LineCharProperty.JT || prev1 == LineCharProperty.H3) && curr == LineCharProperty.JT) { setBreak(LineBreakType.prohibited, 26); continue; } // Treat a Korean Syllable Block the same as ID. // LB27: (JL | JV | JT | H2 | H3) × PO if (_isKoreanSyllable(prev1) && curr == LineCharProperty.PO) { setBreak(LineBreakType.prohibited, 27); continue; } // LB27: PR × (JL | JV | JT | H2 | H3) if (prev1 == LineCharProperty.PR && _isKoreanSyllable(curr)) { setBreak(LineBreakType.prohibited, 27); continue; } // Do not break between alphabetics. // LB28: (AL | HL) × (AL | HL) if (_isALorHL(prev1) && _isALorHL(curr)) { setBreak(LineBreakType.prohibited, 28); continue; } // Do not break between numeric punctuation and alphabetics (“e.g.”). // LB29: IS × (AL | HL) if (prev1 == LineCharProperty.IS && _isALorHL(curr)) { setBreak(LineBreakType.prohibited, 29); continue; } // Do not break between letters, numbers, or ordinary symbols and opening or // closing parentheses. // LB30: (AL | HL | NU) × OP // // LB30 requires that we exclude characters that have an Eastern Asian width // property of value F, W or H classes. if ((_isALorHL(prev1) || prev1 == LineCharProperty.NU) && curr == LineCharProperty.OP && !_hasEastAsianWidthFWH(text.codeUnitAt(index))) { setBreak(LineBreakType.prohibited, 30); continue; } // LB30: CP × (AL | HL | NU) if (prev1 == LineCharProperty.CP && !_hasEastAsianWidthFWH(text.codeUnitAt(index - 1)) && (_isALorHL(curr) || curr == LineCharProperty.NU)) { setBreak(LineBreakType.prohibited, 30); continue; } // Break between two regional indicator symbols if and only if there are an // even number of regional indicators preceding the position of the break. // LB30a: sot (RI RI)* RI × RI // [^RI] (RI RI)* RI × RI if (curr == LineCharProperty.RI) { if (regionalIndicatorCount.isOdd) { setBreak(LineBreakType.prohibited, 30); } else { setBreak(LineBreakType.opportunity, 30); } continue; } // Do not break between an emoji base and an emoji modifier. // LB30b: EB × EM if (prev1 == LineCharProperty.EB && curr == LineCharProperty.EM) { setBreak(LineBreakType.prohibited, 30); continue; } // Break everywhere else. // LB31: ALL ÷ // ÷ ALL setBreak(LineBreakType.opportunity, 31); } // Always break at the end of text. // LB3: ! eot setBreak(LineBreakType.endOfText, 3); return fragments; }
engine/lib/web_ui/lib/src/engine/text/line_breaker.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/text/line_breaker.dart", "repo_id": "engine", "token_count": 8992 }
272
// 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 'dart:typed_data'; import 'package:ui/ui.dart' as ui; bool rectIsValid(ui.Rect rect) { assert( !(rect.left.isNaN || rect.right.isNaN || rect.top.isNaN || rect.bottom.isNaN), 'Rect argument contained a NaN value.'); return true; } bool rrectIsValid(ui.RRect rrect) { assert( !(rrect.left.isNaN || rrect.right.isNaN || rrect.top.isNaN || rrect.bottom.isNaN), 'RRect argument contained a NaN value.'); return true; } bool offsetIsValid(ui.Offset offset) { assert(!offset.dx.isNaN && !offset.dy.isNaN, 'Offset argument contained a NaN value.'); return true; } bool matrix4IsValid(Float32List matrix4) { assert(matrix4.length == 16, 'Matrix4 must have 16 entries.'); return true; } bool radiusIsValid(ui.Radius radius) { assert(!radius.x.isNaN && !radius.y.isNaN, 'Radius argument contained a NaN value.'); return true; } /// Validates color and color stops used for a gradient. void validateColorStops(List<ui.Color> colors, List<double>? colorStops) { if (colorStops == null) { if (colors.length != 2) { throw ArgumentError( '"colors" must have length 2 if "colorStops" is omitted.'); } } else { if (colors.length != colorStops.length) { throw ArgumentError( '"colors" and "colorStops" arguments must have equal length.'); } } }
engine/lib/web_ui/lib/src/engine/validators.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/validators.dart", "repo_id": "engine", "token_count": 638 }
273
// 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. part of ui; // These enum values must be kept in sync with SkShader::TileMode. enum TileMode { clamp, repeated, mirror, decal, }
engine/lib/web_ui/lib/tile_mode.dart/0
{ "file_path": "engine/lib/web_ui/lib/tile_mode.dart", "repo_id": "engine", "token_count": 91 }
274
// 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 "export.h" #include "helpers.h" #include "wrappers.h" #include "third_party/skia/include/core/SkPoint3.h" #include "third_party/skia/include/core/SkVertices.h" #include "third_party/skia/include/utils/SkShadowUtils.h" #include "third_party/skia/modules/skparagraph/include/Paragraph.h" using namespace skia::textlayout; using namespace Skwasm; namespace { // These numbers have been chosen empirically to give a result closest to the // material spec. // These values are also used by the CanvasKit renderer and the native engine. // See: // flutter/display_list/skia/dl_sk_dispatcher.cc // flutter/lib/web_ui/lib/src/engine/canvaskit/util.dart constexpr SkScalar kShadowAmbientAlpha = 0.039; constexpr SkScalar kShadowSpotAlpha = 0.25; constexpr SkScalar kShadowLightRadius = 1.1; constexpr SkScalar kShadowLightHeight = 600.0; constexpr SkScalar kShadowLightXOffset = 0; constexpr SkScalar kShadowLightYOffset = -450; } // namespace SKWASM_EXPORT void canvas_saveLayer(SkCanvas* canvas, SkRect* rect, SkPaint* paint, SkImageFilter* backdrop) { canvas->saveLayer(SkCanvas::SaveLayerRec(rect, paint, backdrop, 0)); } SKWASM_EXPORT void canvas_save(SkCanvas* canvas) { canvas->save(); } SKWASM_EXPORT void canvas_restore(SkCanvas* canvas) { canvas->restore(); } SKWASM_EXPORT void canvas_restoreToCount(SkCanvas* canvas, int count) { canvas->restoreToCount(count); } SKWASM_EXPORT int canvas_getSaveCount(SkCanvas* canvas) { return canvas->getSaveCount(); } SKWASM_EXPORT void canvas_translate(SkCanvas* canvas, SkScalar dx, SkScalar dy) { canvas->translate(dx, dy); } SKWASM_EXPORT void canvas_scale(SkCanvas* canvas, SkScalar sx, SkScalar sy) { canvas->scale(sx, sy); } SKWASM_EXPORT void canvas_rotate(SkCanvas* canvas, SkScalar degrees) { canvas->rotate(degrees); } SKWASM_EXPORT void canvas_skew(SkCanvas* canvas, SkScalar sx, SkScalar sy) { canvas->skew(sx, sy); } SKWASM_EXPORT void canvas_transform(SkCanvas* canvas, const SkM44* matrix44) { canvas->concat(*matrix44); } SKWASM_EXPORT void canvas_clipRect(SkCanvas* canvas, const SkRect* rect, SkClipOp op, bool antialias) { canvas->clipRect(*rect, op, antialias); } SKWASM_EXPORT void canvas_clipRRect(SkCanvas* canvas, const SkScalar* rrectValues, bool antialias) { canvas->clipRRect(createRRect(rrectValues), antialias); } SKWASM_EXPORT void canvas_clipPath(SkCanvas* canvas, SkPath* path, bool antialias) { canvas->clipPath(*path, antialias); } SKWASM_EXPORT void canvas_drawColor(SkCanvas* canvas, SkColor color, SkBlendMode blendMode) { canvas->drawColor(color, blendMode); } SKWASM_EXPORT void canvas_drawLine(SkCanvas* canvas, SkScalar x1, SkScalar y1, SkScalar x2, SkScalar y2, SkPaint* paint) { canvas->drawLine(x1, y1, x2, y2, *paint); } SKWASM_EXPORT void canvas_drawPaint(SkCanvas* canvas, SkPaint* paint) { canvas->drawPaint(*paint); } SKWASM_EXPORT void canvas_drawRect(SkCanvas* canvas, SkRect* rect, SkPaint* paint) { canvas->drawRect(*rect, *paint); } SKWASM_EXPORT void canvas_drawRRect(SkCanvas* canvas, const SkScalar* rrectValues, SkPaint* paint) { canvas->drawRRect(createRRect(rrectValues), *paint); } SKWASM_EXPORT void canvas_drawDRRect(SkCanvas* canvas, const SkScalar* outerRrectValues, const SkScalar* innerRrectValues, SkPaint* paint) { canvas->drawDRRect(createRRect(outerRrectValues), createRRect(innerRrectValues), *paint); } SKWASM_EXPORT void canvas_drawOval(SkCanvas* canvas, const SkRect* rect, SkPaint* paint) { canvas->drawOval(*rect, *paint); } SKWASM_EXPORT void canvas_drawCircle(SkCanvas* canvas, SkScalar x, SkScalar y, SkScalar radius, SkPaint* paint) { canvas->drawCircle(x, y, radius, *paint); } SKWASM_EXPORT void canvas_drawArc(SkCanvas* canvas, const SkRect* rect, SkScalar startAngleDegrees, SkScalar sweepAngleDegrees, bool useCenter, SkPaint* paint) { canvas->drawArc(*rect, startAngleDegrees, sweepAngleDegrees, useCenter, *paint); } SKWASM_EXPORT void canvas_drawPath(SkCanvas* canvas, SkPath* path, SkPaint* paint) { canvas->drawPath(*path, *paint); } SKWASM_EXPORT void canvas_drawShadow(SkCanvas* canvas, SkPath* path, SkScalar elevation, SkScalar devicePixelRatio, SkColor color, bool transparentOccluder) { SkColor inAmbient = SkColorSetA(color, kShadowAmbientAlpha * SkColorGetA(color)); SkColor inSpot = SkColorSetA(color, kShadowSpotAlpha * SkColorGetA(color)); SkColor outAmbient; SkColor outSpot; SkShadowUtils::ComputeTonalColors(inAmbient, inSpot, &outAmbient, &outSpot); uint32_t flags = transparentOccluder ? SkShadowFlags::kTransparentOccluder_ShadowFlag : SkShadowFlags::kNone_ShadowFlag; flags |= SkShadowFlags::kDirectionalLight_ShadowFlag; SkShadowUtils::DrawShadow( canvas, *path, SkPoint3::Make(0.0f, 0.0f, elevation * devicePixelRatio), SkPoint3::Make(kShadowLightXOffset, kShadowLightYOffset, kShadowLightHeight * devicePixelRatio), devicePixelRatio * kShadowLightRadius, outAmbient, outSpot, flags); } SKWASM_EXPORT void canvas_drawParagraph(SkCanvas* canvas, Paragraph* paragraph, SkScalar x, SkScalar y) { paragraph->paint(canvas, x, y); } SKWASM_EXPORT void canvas_drawPicture(SkCanvas* canvas, SkPicture* picture) { canvas->drawPicture(picture); } SKWASM_EXPORT void canvas_drawImage(SkCanvas* canvas, SkImage* image, SkScalar offsetX, SkScalar offsetY, SkPaint* paint, FilterQuality quality) { canvas->drawImage(image, offsetX, offsetY, samplingOptionsForQuality(quality), paint); } SKWASM_EXPORT void canvas_drawImageRect(SkCanvas* canvas, SkImage* image, SkRect* sourceRect, SkRect* destRect, SkPaint* paint, FilterQuality quality) { canvas->drawImageRect(image, *sourceRect, *destRect, samplingOptionsForQuality(quality), paint, SkCanvas::kStrict_SrcRectConstraint); } SKWASM_EXPORT void canvas_drawImageNine(SkCanvas* canvas, SkImage* image, SkIRect* centerRect, SkRect* destinationRect, SkPaint* paint, FilterQuality quality) { canvas->drawImageNine(image, *centerRect, *destinationRect, filterModeForQuality(quality), paint); } SKWASM_EXPORT void canvas_drawVertices(SkCanvas* canvas, SkVertices* vertices, SkBlendMode mode, SkPaint* paint) { canvas->drawVertices(sk_ref_sp<SkVertices>(vertices), mode, *paint); } SKWASM_EXPORT void canvas_drawPoints(SkCanvas* canvas, SkCanvas::PointMode mode, SkPoint* points, int pointCount, SkPaint* paint) { canvas->drawPoints(mode, pointCount, points, *paint); } SKWASM_EXPORT void canvas_drawAtlas(SkCanvas* canvas, SkImage* atlas, SkRSXform* transforms, SkRect* rects, SkColor* colors, int spriteCount, SkBlendMode mode, SkRect* cullRect, SkPaint* paint) { canvas->drawAtlas( atlas, transforms, rects, colors, spriteCount, mode, SkSamplingOptions{SkFilterMode::kLinear, SkMipmapMode::kNone}, cullRect, paint); } SKWASM_EXPORT void canvas_getTransform(SkCanvas* canvas, SkM44* outTransform) { *outTransform = canvas->getLocalToDevice(); } SKWASM_EXPORT void canvas_getLocalClipBounds(SkCanvas* canvas, SkRect* outRect) { *outRect = canvas->getLocalClipBounds(); } SKWASM_EXPORT void canvas_getDeviceClipBounds(SkCanvas* canvas, SkIRect* outRect) { *outRect = canvas->getDeviceClipBounds(); }
engine/lib/web_ui/skwasm/canvas.cpp/0
{ "file_path": "engine/lib/web_ui/skwasm/canvas.cpp", "repo_id": "engine", "token_count": 5779 }
275
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_WEB_UI_SKWASM_SURFACE_H_ #define FLUTTER_LIB_WEB_UI_SKWASM_SURFACE_H_ #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <emscripten.h> #include <emscripten/html5_webgl.h> #include <emscripten/threading.h> #include <webgl/webgl1.h> #include <cassert> #include "export.h" #include "skwasm_support.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkPicture.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/encode/SkPngEncoder.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" #include "wrappers.h" namespace Skwasm { // This must be kept in sync with the `ImageByteFormat` enum in dart:ui. enum class ImageByteFormat { rawRgba, rawStraightRgba, rawUnmodified, png, }; class TextureSourceWrapper { public: TextureSourceWrapper(unsigned long threadId, SkwasmObject textureSource) : _rasterThreadId(threadId) { skwasm_setAssociatedObjectOnThread(_rasterThreadId, this, textureSource); } ~TextureSourceWrapper() { skwasm_disposeAssociatedObjectOnThread(_rasterThreadId, this); } SkwasmObject getTextureSource() { return skwasm_getAssociatedObject(this); } private: unsigned long _rasterThreadId; }; class Surface { public: using CallbackHandler = void(uint32_t, void*, SkwasmObject); // Main thread only Surface(); unsigned long getThreadId() { return _thread; } // Main thread only void dispose(); uint32_t renderPictures(SkPicture** picture, int count); uint32_t rasterizeImage(SkImage* image, ImageByteFormat format); void setCallbackHandler(CallbackHandler* callbackHandler); void onRenderComplete(uint32_t callbackId, SkwasmObject imageBitmap); // Any thread std::unique_ptr<TextureSourceWrapper> createTextureSourceWrapper( SkwasmObject textureSource); // Worker thread void renderPicturesOnWorker(sk_sp<SkPicture>* picture, int pictureCount, uint32_t callbackId, double rasterStart); private: void _runWorker(); void _init(); void _dispose(); void _resizeCanvasToFit(int width, int height); void _recreateSurface(); void _rasterizeImage(SkImage* image, ImageByteFormat format, uint32_t callbackId); void _onRasterizeComplete(SkData* data, uint32_t callbackId); std::string _canvasID; CallbackHandler* _callbackHandler = nullptr; uint32_t _currentCallbackId = 0; int _canvasWidth = 0; int _canvasHeight = 0; EMSCRIPTEN_WEBGL_CONTEXT_HANDLE _glContext = 0; sk_sp<GrDirectContext> _grContext = nullptr; sk_sp<SkSurface> _surface = nullptr; GrGLFramebufferInfo _fbInfo; GrGLint _sampleCount; GrGLint _stencil; pthread_t _thread; static void fDispose(Surface* surface); static void fOnRenderComplete(Surface* surface, uint32_t callbackId, SkwasmObject imageBitmap); static void fRasterizeImage(Surface* surface, SkImage* image, ImageByteFormat format, uint32_t callbackId); static void fOnRasterizeComplete(Surface* surface, SkData* imageData, uint32_t callbackId); }; } // namespace Skwasm #endif // FLUTTER_LIB_WEB_UI_SKWASM_SURFACE_H_
engine/lib/web_ui/skwasm/surface.h/0
{ "file_path": "engine/lib/web_ui/skwasm/surface.h", "repo_id": "engine", "token_count": 1587 }
276
// 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 'dart:js_interop'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } // This test exists to make sure we don't accidentally run the CanvasKit test suite // in "auto" mode. The CanvasKit variant should always be deterministic. void testMain() { setUpCanvasKitTest(); test('CanvasKit tests always run with a specific variant', () { expect( configuration.canvasKitVariant, anyOf(CanvasKitVariant.chromium, CanvasKitVariant.full), reason: 'canvasKitVariant must be set to "chromium" or "full" in canvaskit tests!', ); }); test('debugOverrideJsConfiguration can bypass (and restore) variant', () { // Set-up in the test_platform.dart file. See `_testBootstrapHandler`. final CanvasKitVariant originalValue = configuration.canvasKitVariant; expect(configuration.canvasKitVariant, isNot(CanvasKitVariant.auto)); debugOverrideJsConfiguration( <String, Object?>{ 'canvasKitVariant': 'auto', }.jsify() as JsFlutterConfiguration? ); expect(configuration.canvasKitVariant, CanvasKitVariant.auto); debugOverrideJsConfiguration(null); expect(configuration.canvasKitVariant, originalValue); }); }
engine/lib/web_ui/test/canvaskit/configuration_canvaskit_variant_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/configuration_canvaskit_variant_test.dart", "repo_id": "engine", "token_count": 494 }
277
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 250); /// Test that we can render even if `createImageBitmap` is not supported. void testMain() { group('CanvasKit', () { setUpCanvasKitTest(withImplicitView: true); setUp(() async { EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(1.0); }); tearDown(() { debugDisableCreateImageBitmapSupport = false; debugIsChrome110OrOlder = null; }); test('can render without createImageBitmap', () async { debugDisableCreateImageBitmapSupport = true; expect(browserSupportsCreateImageBitmap, isFalse); final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); final CkGradientLinear gradient = CkGradientLinear( ui.Offset(region.left + region.width / 4, region.height / 2), ui.Offset(region.right - region.width / 8, region.height / 2), const <ui.Color>[ ui.Color(0xFF4285F4), ui.Color(0xFF34A853), ui.Color(0xFFFBBC05), ui.Color(0xFFEA4335), ui.Color(0xFF4285F4), ], const <double>[ 0.0, 0.25, 0.5, 0.75, 1.0, ], ui.TileMode.clamp, null); final CkPaint paint = CkPaint()..shader = gradient; canvas.drawRect(region, paint); await matchPictureGolden( 'canvaskit_linear_gradient_no_create_image_bitmap.png', recorder.endRecording(), region: region, ); }); test( 'createImageBitmap support is disabled on ' 'Windows on Chrome version 110 or older', () async { debugIsChrome110OrOlder = true; debugDisableCreateImageBitmapSupport = false; expect(browserSupportsCreateImageBitmap, isFalse); }); }); }
engine/lib/web_ui/test/canvaskit/no_create_image_bitmap_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/no_create_image_bitmap_test.dart", "repo_id": "engine", "token_count": 981 }
278
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('CanvasKit text', () { setUpCanvasKitTest(); test("doesn't crash when using shadows", () { final ui.TextStyle textStyleWithShadows = ui.TextStyle( fontSize: 16, shadows: <ui.Shadow>[ const ui.Shadow( blurRadius: 3.0, offset: ui.Offset(3.0, 3.0), ), const ui.Shadow( blurRadius: 3.0, offset: ui.Offset(-3.0, 3.0), ), const ui.Shadow( blurRadius: 3.0, offset: ui.Offset(3.0, -3.0), ), const ui.Shadow( blurRadius: 3.0, offset: ui.Offset(-3.0, -3.0), ), ], fontFamily: 'Roboto', ); for (int i = 0; i < 10; i++) { final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle(fontSize: 16)); builder.pushStyle(textStyleWithShadows); builder.addText('test'); final ui.Paragraph paragraph = builder.build(); expect(paragraph, isNotNull); } }); // Regression test for https://github.com/flutter/flutter/issues/78550 test('getBoxesForRange works for LTR text in an RTL paragraph', () { // Create builder for an RTL paragraph. final ui.ParagraphBuilder builder = ui.ParagraphBuilder( ui.ParagraphStyle(fontSize: 16, textDirection: ui.TextDirection.rtl)); builder.addText('hello'); final ui.Paragraph paragraph = builder.build(); paragraph.layout(const ui.ParagraphConstraints(width: 100)); expect(paragraph, isNotNull); final List<ui.TextBox> boxes = paragraph.getBoxesForRange(0, 1); expect(boxes, hasLength(1)); // The direction for this span is LTR even though the paragraph is RTL // because the directionality of the 'h' is LTR. expect(boxes.single.direction, equals(ui.TextDirection.ltr)); }); test('Renders tab as space instead of tofu', () async { // CanvasKit renders a tofu if the font does not have a glyph for a // character. However, Flutter opts-in to a CanvasKit feature to render // tabs as a single space. // See: https://github.com/flutter/flutter/issues/79153 Future<ui.Image> drawText(String text) { const ui.Rect bounds = ui.Rect.fromLTRB(0, 0, 100, 100); final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(bounds); final CkParagraph paragraph = makeSimpleText(text); canvas.drawParagraph(paragraph, ui.Offset.zero); final ui.Picture picture = recorder.endRecording(); return picture.toImage(100, 100); } // The backspace character, \b, does not have a corresponding glyph and // is rendered as a tofu. final ui.Image tabImage = await drawText('>\t<'); final ui.Image spaceImage = await drawText('> <'); final ui.Image tofuImage = await drawText('>\b<'); expect(await matchImage(tabImage, spaceImage), isTrue); expect(await matchImage(tabImage, tofuImage), isFalse); }); group('test fonts in flutterTester environment', () { final bool resetValue = ui_web.debugEmulateFlutterTesterEnvironment; ui_web.debugEmulateFlutterTesterEnvironment = true; tearDownAll(() { ui_web.debugEmulateFlutterTesterEnvironment = resetValue; }); const List<String> testFonts = <String>['FlutterTest', 'Ahem']; test('The default test font is used when a non-test fontFamily is specified', () { final String defaultTestFontFamily = testFonts.first; expect(CkTextStyle(fontFamily: 'BogusFontFamily').effectiveFontFamily, defaultTestFontFamily); expect(CkParagraphStyle(fontFamily: 'BogusFontFamily').getTextStyle().effectiveFontFamily, defaultTestFontFamily); expect(CkStrutStyle(fontFamily: 'BogusFontFamily'), CkStrutStyle(fontFamily: defaultTestFontFamily)); }); test('The default test font is used when fontFamily is unspecified', () { final String defaultTestFontFamily = testFonts.first; expect(CkTextStyle().effectiveFontFamily, defaultTestFontFamily); expect(CkParagraphStyle().getTextStyle().effectiveFontFamily, defaultTestFontFamily); expect(CkStrutStyle(), CkStrutStyle(fontFamily: defaultTestFontFamily)); }); test('Can specify test fontFamily to use', () { for (final String testFont in testFonts) { expect(CkTextStyle(fontFamily: testFont).effectiveFontFamily, testFont); expect(CkParagraphStyle(fontFamily: testFont).getTextStyle().effectiveFontFamily, testFont); } }); }); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520 }, skip: isSafari || isFirefox); }
engine/lib/web_ui/test/canvaskit/text_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/text_test.dart", "repo_id": "engine", "token_count": 2084 }
279
// 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. @TestOn('browser') library; import 'package:js/js_util.dart' as js_util; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../common/matchers.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('FlutterConfiguration', () { test('initializes with null', () async { final FlutterConfiguration config = FlutterConfiguration.legacy(null); expect(config.canvasKitBaseUrl, 'canvaskit/'); // _defaultCanvasKitBaseUrl }); test('legacy constructor initializes with a Js Object', () async { final FlutterConfiguration config = FlutterConfiguration.legacy( js_util.jsify(<String, Object?>{ 'canvasKitBaseUrl': 'some_other_url/', }) as JsFlutterConfiguration); expect(config.canvasKitBaseUrl, 'some_other_url/'); }); }); group('setUserConfiguration', () { test('throws assertion error if already initialized from JS', () async { final FlutterConfiguration config = FlutterConfiguration.legacy( js_util.jsify(<String, Object?>{ 'canvasKitBaseUrl': 'some_other_url/', }) as JsFlutterConfiguration); expect(() { config.setUserConfiguration( js_util.jsify(<String, Object?>{ 'canvasKitBaseUrl': 'yet_another_url/', }) as JsFlutterConfiguration); }, throwsAssertionError); }); test('stores config if JS configuration was null', () async { final FlutterConfiguration config = FlutterConfiguration.legacy(null); config.setUserConfiguration( js_util.jsify(<String, Object?>{ 'canvasKitBaseUrl': 'one_more_url/', }) as JsFlutterConfiguration); expect(config.canvasKitBaseUrl, 'one_more_url/'); }); test('can receive non-existing properties without crashing', () async { final FlutterConfiguration config = FlutterConfiguration.legacy(null); expect(() { config.setUserConfiguration( js_util.jsify(<String, Object?>{ 'canvasKitMaximumSurfaces': 32.0, }) as JsFlutterConfiguration); }, returnsNormally); }); }); group('Default configuration values', () { late FlutterConfiguration defaultConfig; setUp(() { defaultConfig = FlutterConfiguration(); defaultConfig.setUserConfiguration( js_util.jsify(<String, Object?>{}) as JsFlutterConfiguration, ); }); test('canvasKitVariant', () { expect(defaultConfig.canvasKitVariant, CanvasKitVariant.auto); }); test('useColorEmoji', () { expect(defaultConfig.useColorEmoji, isFalse); }); test('multiViewEnabled', () { expect(defaultConfig.multiViewEnabled, isFalse); }); }); group('setUserConfiguration (values)', () { group('canvasKitVariant', () { test('value undefined - defaults to "auto"', () { final FlutterConfiguration config = FlutterConfiguration(); config.setUserConfiguration( // With an empty map, the canvasKitVariant is undefined in JS. js_util.jsify(<String, Object?>{}) as JsFlutterConfiguration, ); expect(config.canvasKitVariant, CanvasKitVariant.auto); }); test('value - converts to CanvasKitVariant enum (or throw)', () { final FlutterConfiguration config = FlutterConfiguration(); config.setUserConfiguration( js_util.jsify(<String, Object?>{'canvasKitVariant': 'foo'}) as JsFlutterConfiguration, ); expect(() => config.canvasKitVariant, throwsArgumentError); config.setUserConfiguration( js_util.jsify(<String, Object?>{'canvasKitVariant': 'auto'}) as JsFlutterConfiguration, ); expect(config.canvasKitVariant, CanvasKitVariant.auto); config.setUserConfiguration( js_util.jsify(<String, Object?>{'canvasKitVariant': 'full'}) as JsFlutterConfiguration, ); expect(config.canvasKitVariant, CanvasKitVariant.full); config.setUserConfiguration( js_util.jsify(<String, Object?>{'canvasKitVariant': 'chromium'}) as JsFlutterConfiguration, ); expect(config.canvasKitVariant, CanvasKitVariant.chromium); }); }); test('useColorEmoji', () { final FlutterConfiguration config = FlutterConfiguration(); config.setUserConfiguration( js_util.jsify(<String, Object?>{'useColorEmoji': true}) as JsFlutterConfiguration, ); expect(config.useColorEmoji, isTrue); }); test('multiViewEnabled', () { final FlutterConfiguration config = FlutterConfiguration(); config.setUserConfiguration( js_util.jsify(<String, Object?>{'multiViewEnabled': true}) as JsFlutterConfiguration, ); expect(config.multiViewEnabled, isTrue); }); }); }
engine/lib/web_ui/test/engine/configuration_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/configuration_test.dart", "repo_id": "engine", "token_count": 1919 }
280
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { test('Locale', () { expect(const Locale('en').toString(), 'en'); expect(const Locale('en'), const Locale('en')); expect(const Locale('en').hashCode, const Locale('en').hashCode); expect(const Locale('en'), isNot(const Locale('en', ''))); // TODO(het): This fails on web because "".hashCode == null.hashCode == 0 //expect(const Locale('en').hashCode, isNot(const Locale('en', '').hashCode)); expect(const Locale('en', 'US').toString(), 'en_US'); expect(const Locale('iw').toString(), 'he'); expect(const Locale('iw', 'DD').toString(), 'he_DE'); expect(const Locale('iw', 'DD'), const Locale('he', 'DE')); }); test('Locale.fromSubtags', () { expect(const Locale.fromSubtags().languageCode, 'und'); expect(const Locale.fromSubtags().scriptCode, null); expect(const Locale.fromSubtags().countryCode, null); expect(const Locale.fromSubtags(languageCode: 'en').toString(), 'en'); expect(const Locale.fromSubtags(languageCode: 'en').languageCode, 'en'); expect(const Locale.fromSubtags(scriptCode: 'Latn').toString(), 'und_Latn'); expect(const Locale.fromSubtags(scriptCode: 'Latn').scriptCode, 'Latn'); expect(const Locale.fromSubtags(countryCode: 'US').toString(), 'und_US'); expect(const Locale.fromSubtags(countryCode: 'US').countryCode, 'US'); expect( const Locale.fromSubtags(languageCode: 'es', countryCode: '419') .toString(), 'es_419'); expect( const Locale.fromSubtags(languageCode: 'es', countryCode: '419') .languageCode, 'es'); expect( const Locale.fromSubtags(languageCode: 'es', countryCode: '419') .countryCode, '419'); expect( const Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN') .toString(), 'zh_Hans_CN'); }); test('Locale equality', () { expect( const Locale.fromSubtags(languageCode: 'en'), isNot( const Locale.fromSubtags(languageCode: 'en', scriptCode: 'Latn'))); expect( const Locale.fromSubtags(languageCode: 'en').hashCode, isNot(const Locale.fromSubtags(languageCode: 'en', scriptCode: 'Latn') .hashCode)); }); }
engine/lib/web_ui/test/engine/locale_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/locale_test.dart", "repo_id": "engine", "token_count": 1032 }
281
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import '../common/mock_engine_canvas.dart'; import '../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { setUpUnitTests( withImplicitView: true, setUpTestViewDimensions: false, ); late RecordingCanvas underTest; late MockEngineCanvas mockCanvas; const Rect screenRect = Rect.largest; setUp(() { underTest = RecordingCanvas(screenRect); mockCanvas = MockEngineCanvas(); }); group('paragraph bounds', () { Paragraph paragraphForBoundsTest(TextAlign alignment) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontFamily: 'Ahem', fontSize: 20, textAlign: alignment, )); builder.addText('A AAAAA AAA'); return builder.build(); } test('not laid out', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.start); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(underTest.pictureBounds, Rect.zero); }); test('finite width', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.start); paragraph.layout(const ParagraphConstraints(width: 110)); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(paragraph.width, 110); expect(paragraph.height, 60); expect(underTest.pictureBounds, const Rect.fromLTRB(0, 0, 100, 60)); }); test('finite width center-aligned', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.center); paragraph.layout(const ParagraphConstraints(width: 110)); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(paragraph.width, 110); expect(paragraph.height, 60); expect(underTest.pictureBounds, const Rect.fromLTRB(5, 0, 105, 60)); }); test('infinite width', () { final Paragraph paragraph = paragraphForBoundsTest(TextAlign.start); paragraph.layout(const ParagraphConstraints(width: double.infinity)); underTest.drawParagraph(paragraph, Offset.zero); underTest.endRecording(); expect(paragraph.width, double.infinity); expect(paragraph.height, 20); expect(underTest.pictureBounds, const Rect.fromLTRB(0, 0, 220, 20)); }); }); group('drawDRRect', () { final RRect rrect = RRect.fromLTRBR(10, 10, 50, 50, const Radius.circular(3)); final SurfacePaint somePaint = SurfacePaint() ..color = const Color(0xFFFF0000); test('Happy case', () { underTest.drawDRRect(rrect, rrect.deflate(1), somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); _expectDrawDRRectCall(mockCanvas, <String, dynamic>{ 'path': 'Path(' 'MoveTo(${10.0}, ${47.0}) ' 'LineTo(${10.0}, ${13.0}) ' 'Conic(${10.0}, ${10.0}, ${10.0}, ${13.0}, w = ${0.7071067690849304}) ' 'LineTo(${47.0}, ${10.0}) ' 'Conic(${50.0}, ${10.0}, ${10.0}, ${50.0}, w = ${0.7071067690849304}) ' 'LineTo(${50.0}, ${47.0}) ' 'Conic(${50.0}, ${50.0}, ${50.0}, ${47.0}, w = ${0.7071067690849304}) ' 'LineTo(${13.0}, ${50.0}) ' 'Conic(${10.0}, ${50.0}, ${50.0}, ${10.0}, w = ${0.7071067690849304}) ' 'Close() ' 'MoveTo(${11.0}, ${47.0}) ' 'LineTo(${11.0}, ${13.0}) ' 'Conic(${11.0}, ${11.0}, ${11.0}, ${13.0}, w = ${0.7071067690849304}) ' 'LineTo(${47.0}, ${11.0}) ' 'Conic(${49.0}, ${11.0}, ${11.0}, ${49.0}, w = ${0.7071067690849304}) ' 'LineTo(${49.0}, ${47.0}) ' 'Conic(${49.0}, ${49.0}, ${49.0}, ${47.0}, w = ${0.7071067690849304}) ' 'LineTo(${13.0}, ${49.0}) ' 'Conic(${11.0}, ${49.0}, ${49.0}, ${11.0}, w = ${0.7071067690849304}) ' 'Close()' ')', 'paint': somePaint.paintData, }); }); test('Inner RRect > Outer RRect', () { underTest.drawDRRect(rrect, rrect.inflate(1), somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect nothing to be called expect(mockCanvas.methodCallLog.length, equals(1)); expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint'); }); test('Inner RRect not completely inside Outer RRect', () { underTest.drawDRRect( rrect, rrect.deflate(1).shift(const Offset(0.0, 10)), somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect nothing to be called expect(mockCanvas.methodCallLog.length, equals(1)); expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint'); }); test('Inner RRect same as Outer RRect', () { underTest.drawDRRect(rrect, rrect, somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect nothing to be called expect(mockCanvas.methodCallLog.length, equals(1)); expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint'); }); test('deflated corners in inner RRect get passed through to draw', () { // This comes from github issue #40728 final RRect outer = RRect.fromRectAndCorners( const Rect.fromLTWH(0, 0, 88, 48), topLeft: const Radius.circular(6), bottomLeft: const Radius.circular(6)); final RRect inner = outer.deflate(1); expect(inner.brRadius, equals(Radius.zero)); expect(inner.trRadius, equals(Radius.zero)); underTest.drawDRRect(outer, inner, somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); // Expect to draw, even when inner has negative radii (which get ignored by canvas) _expectDrawDRRectCall(mockCanvas, <String, dynamic>{ 'path': 'Path(' 'MoveTo(${0.0}, ${42.0}) ' 'LineTo(${0.0}, ${6.0}) ' 'Conic(${0.0}, ${0.0}, ${0.0}, ${6.0}, w = ${0.7071067690849304}) ' 'LineTo(${88.0}, ${0.0}) ' 'Conic(${88.0}, ${0.0}, ${0.0}, ${88.0}, w = ${0.7071067690849304}) ' 'LineTo(${88.0}, ${48.0}) ' 'Conic(${88.0}, ${48.0}, ${48.0}, ${88.0}, w = ${0.7071067690849304}) ' 'LineTo(${6.0}, ${48.0}) ' 'Conic(${0.0}, ${48.0}, ${48.0}, ${0.0}, w = ${0.7071067690849304}) ' 'Close() ' 'MoveTo(${1.0}, ${42.0}) ' 'LineTo(${1.0}, ${6.0}) ' 'Conic(${1.0}, ${1.0}, ${1.0}, ${6.0}, w = ${0.7071067690849304}) ' 'LineTo(${87.0}, ${1.0}) ' 'Conic(${87.0}, ${1.0}, ${1.0}, ${87.0}, w = ${0.7071067690849304}) ' 'LineTo(${87.0}, ${47.0}) ' 'Conic(${87.0}, ${47.0}, ${47.0}, ${87.0}, w = ${0.7071067690849304}) ' 'LineTo(${6.0}, ${47.0}) ' 'Conic(${1.0}, ${47.0}, ${47.0}, ${1.0}, w = ${0.7071067690849304}) ' 'Close()' ')', 'paint': somePaint.paintData, }); }); test('preserve old golden test behavior', () { final RRect outer = RRect.fromRectAndCorners(const Rect.fromLTRB(10, 20, 30, 40)); final RRect inner = RRect.fromRectAndCorners(const Rect.fromLTRB(12, 22, 28, 38)); underTest.drawDRRect(outer, inner, somePaint); underTest.endRecording(); underTest.apply(mockCanvas, screenRect); _expectDrawDRRectCall(mockCanvas, <String, dynamic>{ 'path': 'Path(' 'MoveTo(${10.0}, ${20.0}) ' 'LineTo(${30.0}, ${20.0}) ' 'LineTo(${30.0}, ${40.0}) ' 'LineTo(${10.0}, ${40.0}) ' 'Close() ' 'MoveTo(${12.0}, ${22.0}) ' 'LineTo(${28.0}, ${22.0}) ' 'LineTo(${28.0}, ${38.0}) ' 'LineTo(${12.0}, ${38.0}) ' 'Close()' ')', 'paint': somePaint.paintData, }); }); }); test('Filters out paint commands outside the clip rect', () { // Outside to the left underTest.drawRect(const Rect.fromLTWH(0.0, 20.0, 10.0, 10.0), SurfacePaint()); // Outside above underTest.drawRect(const Rect.fromLTWH(20.0, 0.0, 10.0, 10.0), SurfacePaint()); // Visible underTest.drawRect(const Rect.fromLTWH(20.0, 20.0, 10.0, 10.0), SurfacePaint()); // Inside the layer clip rect but zero-size underTest.drawRect(const Rect.fromLTRB(20.0, 20.0, 30.0, 20.0), SurfacePaint()); // Inside the layer clip but clipped out by a canvas clip underTest.save(); underTest.clipRect(const Rect.fromLTWH(0, 0, 10, 10), ClipOp.intersect); underTest.drawRect(const Rect.fromLTWH(20.0, 20.0, 10.0, 10.0), SurfacePaint()); underTest.restore(); // Outside to the right underTest.drawRect(const Rect.fromLTWH(40.0, 20.0, 10.0, 10.0), SurfacePaint()); // Outside below underTest.drawRect(const Rect.fromLTWH(20.0, 40.0, 10.0, 10.0), SurfacePaint()); underTest.endRecording(); expect(underTest.debugPaintCommands, hasLength(10)); final PaintDrawRect outsideLeft = underTest.debugPaintCommands[0] as PaintDrawRect; expect(outsideLeft.isClippedOut, isFalse); expect(outsideLeft.leftBound, 0); expect(outsideLeft.topBound, 20); expect(outsideLeft.rightBound, 10); expect(outsideLeft.bottomBound, 30); final PaintDrawRect outsideAbove = underTest.debugPaintCommands[1] as PaintDrawRect; expect(outsideAbove.isClippedOut, isFalse); final PaintDrawRect visible = underTest.debugPaintCommands[2] as PaintDrawRect; expect(visible.isClippedOut, isFalse); final PaintDrawRect zeroSize = underTest.debugPaintCommands[3] as PaintDrawRect; expect(zeroSize.isClippedOut, isTrue); expect(underTest.debugPaintCommands[4], isA<PaintSave>()); final PaintClipRect clip = underTest.debugPaintCommands[5] as PaintClipRect; expect(clip.isClippedOut, isFalse); final PaintDrawRect clippedOut = underTest.debugPaintCommands[6] as PaintDrawRect; expect(clippedOut.isClippedOut, isTrue); expect(underTest.debugPaintCommands[7], isA<PaintRestore>()); final PaintDrawRect outsideRight = underTest.debugPaintCommands[8] as PaintDrawRect; expect(outsideRight.isClippedOut, isFalse); final PaintDrawRect outsideBelow = underTest.debugPaintCommands[9] as PaintDrawRect; expect(outsideBelow.isClippedOut, isFalse); // Give it the entire screen so everything paints. underTest.apply(mockCanvas, screenRect); expect(mockCanvas.methodCallLog, hasLength(11)); expect(mockCanvas.methodCallLog[0].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[1].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[2].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[3].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[4].methodName, 'save'); expect(mockCanvas.methodCallLog[5].methodName, 'clipRect'); expect(mockCanvas.methodCallLog[6].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[7].methodName, 'restore'); expect(mockCanvas.methodCallLog[8].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[9].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[10].methodName, 'endOfPaint'); // Clip out a middle region that only contains 'drawRect' mockCanvas.methodCallLog.clear(); underTest.apply(mockCanvas, const Rect.fromLTRB(15, 15, 35, 35)); expect(mockCanvas.methodCallLog, hasLength(4)); expect(mockCanvas.methodCallLog[0].methodName, 'drawRect'); expect(mockCanvas.methodCallLog[1].methodName, 'save'); expect(mockCanvas.methodCallLog[2].methodName, 'restore'); expect(mockCanvas.methodCallLog[3].methodName, 'endOfPaint'); }); // Regression test for https://github.com/flutter/flutter/issues/61697. test('Allows restore calls after recording has ended', () { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 200, 400)); rc.endRecording(); // Should not throw exception on restore. expect(() => rc.restore(), returnsNormally); }); // Regression test for https://github.com/flutter/flutter/issues/61697. test('Allows restore calls even if recording is not ended', () { final RecordingCanvas rc = RecordingCanvas(const Rect.fromLTRB(0, 0, 200, 400)); // Should not throw exception on restore. expect(() => rc.restore(), returnsNormally); }); } // Expect a drawDRRect call to be registered in the mock call log, with the expectedArguments void _expectDrawDRRectCall( MockEngineCanvas mock, Map<String, dynamic> expectedArguments) { expect(mock.methodCallLog.length, equals(2)); final MockCanvasCall mockCall = mock.methodCallLog[0]; expect(mockCall.methodName, equals('drawPath')); final Map<String, dynamic> argMap = mockCall.arguments as Map<String, dynamic>; final Map<String, dynamic> argContents = <String, dynamic>{}; argMap.forEach((String key, dynamic value) { argContents[key] = value is SurfacePath ? value.toString() : value; }); expect(argContents, equals(expectedArguments)); }
engine/lib/web_ui/test/engine/recording_canvas_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/recording_canvas_test.dart", "repo_id": "engine", "token_count": 5694 }
282
// 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 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('ImageFilter constructors', () { test('matrix is copied', () { final Matrix4 matrix = Matrix4.identity(); final Float64List storage = matrix.toFloat64(); final ImageFilter filter1 = ImageFilter.matrix(storage); storage[0] = 2.0; final ImageFilter filter2 = ImageFilter.matrix(storage); expect(filter1, filter1); expect(filter2, filter2); expect(filter1, isNot(equals(filter2))); expect(filter2, isNot(equals(filter1))); }); test('matrix tests all values on ==', () { final Matrix4 matrix = Matrix4.identity(); final Float64List storage = matrix.toFloat64(); final ImageFilter filter1a = ImageFilter.matrix(storage, filterQuality: FilterQuality.none); final ImageFilter filter1b = ImageFilter.matrix(storage, filterQuality: FilterQuality.high); storage[0] = 2.0; final ImageFilter filter2a = ImageFilter.matrix(storage, filterQuality: FilterQuality.none); final ImageFilter filter2b = ImageFilter.matrix(storage, filterQuality: FilterQuality.high); expect(filter1a, filter1a); expect(filter1a, isNot(equals(filter1b))); expect(filter1a, isNot(equals(filter2a))); expect(filter1a, isNot(equals(filter2b))); expect(filter1b, isNot(equals(filter1a))); expect(filter1b, filter1b); expect(filter1b, isNot(equals(filter2a))); expect(filter1b, isNot(equals(filter2b))); expect(filter2a, isNot(equals(filter1a))); expect(filter2a, isNot(equals(filter1b))); expect(filter2a, filter2a); expect(filter2a, isNot(equals(filter2b))); expect(filter2b, isNot(equals(filter1a))); expect(filter2b, isNot(equals(filter1b))); expect(filter2b, isNot(equals(filter2a))); expect(filter2b, filter2b); }); test('blur tests all values on ==', () { final ImageFilter filter1 = ImageFilter.blur(sigmaX: 2.0, sigmaY: 2.0, tileMode: TileMode.decal); final ImageFilter filter2 = ImageFilter.blur(sigmaX: 2.0, sigmaY: 3.0, tileMode: TileMode.decal); final ImageFilter filter3 = ImageFilter.blur(sigmaX: 2.0, sigmaY: 2.0, tileMode: TileMode.mirror); expect(filter1, filter1); expect(filter1, isNot(equals(filter2))); expect(filter1, isNot(equals(filter3))); expect(filter2, isNot(equals(filter1))); expect(filter2, filter2); expect(filter2, isNot(equals(filter3))); expect(filter3, isNot(equals(filter1))); expect(filter3, isNot(equals(filter2))); expect(filter3, filter3); }); }); }
engine/lib/web_ui/test/engine/surface/filters/image_filter_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/surface/filters/image_filter_test.dart", "repo_id": "engine", "token_count": 1174 }
283
// 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. @JS() library dom_manager_test; // We need this to mess with the ShadowDOM. import 'dart:js_interop'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../../common/matchers.dart'; void main() { internalBootstrapBrowserTest(() => doTests); } void doTests() { group('DomManager', () { test('DOM tree looks right', () { final DomManager domManager = DomManager(devicePixelRatio: 3.0); // Check tag names. expect(domManager.rootElement.tagName, equalsIgnoringCase(DomManager.flutterViewTagName)); expect(domManager.platformViewsHost.tagName, equalsIgnoringCase(DomManager.glassPaneTagName)); expect(domManager.textEditingHost.tagName, equalsIgnoringCase(DomManager.textEditingHostTagName)); expect(domManager.semanticsHost.tagName, equalsIgnoringCase(DomManager.semanticsHostTagName)); expect(domManager.announcementsHost.tagName, equalsIgnoringCase(DomManager.announcementsHostTagName)); // Check parent-child relationships. final List<DomElement> rootChildren = domManager.rootElement.children.toList(); expect(rootChildren.length, 4); expect(rootChildren[0], domManager.platformViewsHost); expect(rootChildren[1], domManager.textEditingHost); expect(rootChildren[2], domManager.semanticsHost); expect(rootChildren[3].tagName, equalsIgnoringCase('style')); final List<DomElement> shadowChildren = domManager.renderingHost.childNodes.cast<DomElement>().toList(); expect(shadowChildren.length, 3); expect(shadowChildren[0], domManager.sceneHost); expect(shadowChildren[1], domManager.announcementsHost); expect(shadowChildren[2].tagName, equalsIgnoringCase('style')); }); test('hide placeholder text for textfield', () { final DomManager domManager = DomManager(devicePixelRatio: 3.0); domDocument.body!.append(domManager.rootElement); final DomHTMLInputElement regularTextField = createDomHTMLInputElement(); regularTextField.placeholder = 'Now you see me'; domManager.rootElement.appendChild(regularTextField); regularTextField.focus(); DomCSSStyleDeclaration? style = domWindow.getComputedStyle( domManager.rootElement.querySelector('input')!, '::placeholder'); expect(style, isNotNull); expect(style.opacity, isNot('0')); final DomHTMLInputElement textField = createDomHTMLInputElement(); textField.placeholder = 'Now you dont'; textField.classList.add('flt-text-editing'); domManager.rootElement.appendChild(textField); textField.focus(); style = domWindow.getComputedStyle( domManager.rootElement.querySelector('input.flt-text-editing')!, '::placeholder'); expect(style, isNotNull); expect(style.opacity, '0'); domManager.rootElement.remove(); // For some reason, only Firefox is able to correctly compute styles for // the `::placeholder` pseudo-element. }, skip: browserEngine != BrowserEngine.firefox); }); group('Shadow root', () { test('throws when shadowDom is not available', () { final dynamic oldAttachShadow = attachShadow; expect(oldAttachShadow, isNotNull); attachShadow = null; // Break ShadowDOM expect(() => DomManager(devicePixelRatio: 3.0), throwsAssertionError); attachShadow = oldAttachShadow; // Restore ShadowDOM }); test('Initializes and attaches a shadow root', () { final DomManager domManager = DomManager(devicePixelRatio: 3.0); expect(domInstanceOfString(domManager.renderingHost, 'ShadowRoot'), isTrue); expect(domManager.renderingHost.host, domManager.platformViewsHost); expect(domManager.renderingHost, domManager.platformViewsHost.shadowRoot); // The shadow root should be initialized with correct parameters. expect(domManager.renderingHost.mode, 'open'); if (browserEngine != BrowserEngine.firefox && browserEngine != BrowserEngine.webkit) { // Older versions of Safari and Firefox don't support this flag yet. // See: https://caniuse.com/mdn-api_shadowroot_delegatesfocus expect(domManager.renderingHost.delegatesFocus, isFalse); } }); test('Attaches a stylesheet to the shadow root', () { final DomManager domManager = DomManager(devicePixelRatio: 3.0); final DomElement? style = domManager.renderingHost.querySelector('#flt-internals-stylesheet'); expect(style, isNotNull); expect(style!.tagName, equalsIgnoringCase('style')); expect(style.parentNode, domManager.renderingHost); }); test('setScene', () { final DomManager domManager = DomManager(devicePixelRatio: 3.0); final DomElement sceneHost = domManager.renderingHost.querySelector('flt-scene-host')!; final DomElement scene1 = createDomElement('flt-scene'); domManager.setScene(scene1); expect(sceneHost.children, <DomElement>[scene1]); // Insert the same scene again. domManager.setScene(scene1); expect(sceneHost.children, <DomElement>[scene1]); // Insert a different scene. final DomElement scene2 = createDomElement('flt-scene'); domManager.setScene(scene2); expect(sceneHost.children, <DomElement>[scene2]); expect(scene1.parent, isNull); }); }); } @JS('Element.prototype.attachShadow') external JSAny? get _attachShadow; dynamic get attachShadow => _attachShadow?.toObjectShallow; @JS('Element.prototype.attachShadow') external set _attachShadow(JSAny? x); set attachShadow(Object? x) => _attachShadow = x?.toJSAnyShallow;
engine/lib/web_ui/test/engine/view_embedder/dom_manager_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/view_embedder/dom_manager_test.dart", "repo_id": "engine", "token_count": 2021 }
284
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const Rect region = Rect.fromLTWH(0, 0, 500, 500); late BitmapCanvas canvas; setUp(() { canvas = BitmapCanvas(region, RenderStrategy()); }); tearDown(() { canvas.rootElement.remove(); }); test('draws paths using nonzero and evenodd winding rules', () async { paintPaths(canvas); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_path_winding.png', region: region); }); } void paintPaths(BitmapCanvas canvas) { canvas.drawRect(const Rect.fromLTRB(0, 0, 500, 500), SurfacePaintData() ..color = 0xFFFFFFFF ..style = PaintingStyle.fill); // white final SurfacePaint paintFill = SurfacePaint() ..style = PaintingStyle.fill ..color = const Color(0xFF00B0FF); final SurfacePaint paintStroke = SurfacePaint() ..style = PaintingStyle.stroke ..strokeWidth = 2 ..color = const Color(0xFFE00000); final Path path1 = Path() ..fillType = PathFillType.evenOdd ..moveTo(50, 0) ..lineTo(21, 90) ..lineTo(98, 35) ..lineTo(2, 35) ..lineTo(79, 90) ..close() ..addRect(const Rect.fromLTWH(20, 100, 200, 50)) ..addRect(const Rect.fromLTWH(40, 120, 160, 10)); final Path path2 = Path() ..fillType = PathFillType.nonZero ..moveTo(50, 200) ..lineTo(21, 290) ..lineTo(98, 235) ..lineTo(2, 235) ..lineTo(79, 290) ..close() ..addRect(const Rect.fromLTWH(20, 300, 200, 50)) ..addRect(const Rect.fromLTWH(40, 320, 160, 10)); canvas.drawPath(path1, paintFill.paintData); canvas.drawPath(path2, paintFill.paintData); canvas.drawPath(path1, paintStroke.paintData); canvas.drawPath(path2, paintStroke.paintData); }
engine/lib/web_ui/test/html/canvas_winding_rule_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/canvas_winding_rule_golden_test.dart", "repo_id": "engine", "token_count": 823 }
285
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const Rect region = Rect.fromLTWH(0, 0, 150, 420); late BitmapCanvas canvas; setUp(() { canvas = BitmapCanvas(region, RenderStrategy()); }); tearDown(() { canvas.rootElement.remove(); }); test('draws rect with flipped coordinates L > R, T > B', () async { paintRects(canvas); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_rect_flipped.png', region: region); }); } void paintRects(BitmapCanvas canvas) { canvas.drawRect(const Rect.fromLTRB(30, 40, 100, 50), SurfacePaintData() ..color = 0xFF4CAF50 //Colors.green ..strokeWidth = 1.0 ..style = PaintingStyle.stroke); // swap left and right. canvas.drawRect(const Rect.fromLTRB(100, 150, 30, 140), SurfacePaintData() ..color = 0xFFF44336 //Colors.red ..strokeWidth = 1.0 ..style = PaintingStyle.stroke); // Repeat above for fill canvas.drawRect(const Rect.fromLTRB(30, 240, 100, 250), SurfacePaintData() ..color = 0xFF4CAF50 //Colors.green ..style = PaintingStyle.fill); // swap left and right. canvas.drawRect(const Rect.fromLTRB(100, 350, 30, 340), SurfacePaintData() ..color = 0xFFF44336 //Colors.red ..style = PaintingStyle.fill); }
engine/lib/web_ui/test/html/drawing/canvas_rect_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/drawing/canvas_rect_golden_test.dart", "repo_id": "engine", "token_count": 676 }
286
// 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 'dart:math' as math; import 'package:test/bootstrap/browser.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import '../../common/test_initialization.dart'; import 'text_goldens.dart'; typedef PaintTest = void Function(RecordingCanvas recordingCanvas); void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { final EngineGoldenTester goldenTester = await EngineGoldenTester.initialize( viewportSize: const Size(600, 600), ); setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); void paintTest(EngineCanvas canvas, PaintTest painter) { const Rect screenRect = Rect.fromLTWH(0, 0, 600, 600); final RecordingCanvas recordingCanvas = RecordingCanvas(screenRect); painter(recordingCanvas); recordingCanvas.endRecording(); recordingCanvas.apply(canvas, screenRect); } testEachCanvas( 'clips multiline text against rectangle', (EngineCanvas canvas) { // [DomCanvas] doesn't support clip commands. if (canvas is! DomCanvas) { paintTest(canvas, paintTextWithClipRect); return goldenTester.diffCanvasScreenshot( canvas, 'multiline_text_clipping_rect'); } return null; }, ); testEachCanvas( 'clips multiline text against rectangle with transform', (EngineCanvas canvas) { // [DomCanvas] doesn't support clip commands. if (canvas is! DomCanvas) { paintTest(canvas, paintTextWithClipRectTranslated); return goldenTester.diffCanvasScreenshot( canvas, 'multiline_text_clipping_rect_translate'); } return null; }, ); testEachCanvas( 'clips multiline text against round rectangle', (EngineCanvas canvas) { // [DomCanvas] doesn't support clip commands. if (canvas is! DomCanvas) { paintTest(canvas, paintTextWithClipRoundRect); return goldenTester.diffCanvasScreenshot( canvas, 'multiline_text_clipping_roundrect'); } return null; }, ); testEachCanvas( 'clips multiline text against path', (EngineCanvas canvas) { // [DomCanvas] doesn't support clip commands. if (canvas is! DomCanvas) { paintTest(canvas, paintTextWithClipPath); return goldenTester.diffCanvasScreenshot( canvas, 'multiline_text_clipping_path'); } return null; }, ); testEachCanvas( 'clips multiline text against stack of rects', (EngineCanvas canvas) { // [DomCanvas] doesn't support clip commands. if (canvas is! DomCanvas) { paintTest(canvas, paintTextWithClipStack); return goldenTester.diffCanvasScreenshot( canvas, 'multiline_text_clipping_stack1'); } return null; }, ); } const Rect testBounds = Rect.fromLTRB(50, 50, 230, 220); void drawBackground(RecordingCanvas canvas) { canvas.drawRect( testBounds, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color(0xFF9E9E9E)); canvas.drawRect( testBounds.inflate(-40), SurfacePaint() ..strokeWidth = 1 ..style = PaintingStyle.stroke ..color = const Color(0xFF009688)); } void drawQuickBrownFox(RecordingCanvas canvas) { canvas.drawParagraph( paragraph( 'The quick brown fox jumps over the lazy dog', textStyle: TextStyle( color: const Color(0xFF000000), decoration: TextDecoration.none, fontFamily: 'Roboto', fontSize: 30, background: Paint()..color = const Color.fromRGBO(50, 255, 50, 1.0), ), maxWidth: 180, ), Offset(testBounds.left, testBounds.top)); } void paintTextWithClipRect(RecordingCanvas canvas) { drawBackground(canvas); canvas.clipRect(testBounds.inflate(-40), ClipOp.intersect); drawQuickBrownFox(canvas); } void paintTextWithClipRectTranslated(RecordingCanvas canvas) { drawBackground(canvas); canvas.clipRect(testBounds.inflate(-40), ClipOp.intersect); canvas.translate(30, 10); drawQuickBrownFox(canvas); } const Color deepOrange = Color(0xFFFF5722); void paintTextWithClipRoundRect(RecordingCanvas canvas) { final RRect roundRect = RRect.fromRectAndCorners(testBounds.inflate(-40), topRight: const Radius.elliptical(45, 40), bottomLeft: const Radius.elliptical(50, 40), bottomRight: const Radius.circular(30)); drawBackground(canvas); canvas.drawRRect( roundRect, SurfacePaint() ..color = deepOrange ..style = PaintingStyle.fill); canvas.clipRRect(roundRect); drawQuickBrownFox(canvas); } void paintTextWithClipPath(RecordingCanvas canvas) { drawBackground(canvas); final Path path = Path(); const double delta = 40.0; final Rect clipBounds = testBounds.inflate(-delta); final double midX = (clipBounds.left + clipBounds.right) / 2.0; final double midY = (clipBounds.top + clipBounds.bottom) / 2.0; path.moveTo(clipBounds.left - delta, midY); path.quadraticBezierTo(midX, midY, midX, clipBounds.top - delta); path.quadraticBezierTo(midX, midY, clipBounds.right + delta, midY); path.quadraticBezierTo(midX, midY, midX, clipBounds.bottom + delta); path.quadraticBezierTo(midX, midY, clipBounds.left - delta, midY); path.close(); canvas.drawPath( path, SurfacePaint() ..color = deepOrange ..style = PaintingStyle.fill); canvas.clipPath(path); drawQuickBrownFox(canvas); } void paintTextWithClipStack(RecordingCanvas canvas) { drawBackground(canvas); final Rect inflatedRect = testBounds.inflate(-40); canvas.clipRect(inflatedRect, ClipOp.intersect); canvas.rotate(math.pi / 8.0); canvas.translate(40, -40); canvas.clipRect(inflatedRect, ClipOp.intersect); canvas.drawRect( inflatedRect, SurfacePaint() ..color = deepOrange ..style = PaintingStyle.fill); drawQuickBrownFox(canvas); }
engine/lib/web_ui/test/html/paragraph/text_multiline_clipping_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/paragraph/text_multiline_clipping_golden_test.dart", "repo_id": "engine", "token_count": 2389 }
287
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart' hide BackdropFilterEngineLayer, ClipRectEngineLayer; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; import '../../common/test_initialization.dart'; /// To debug compositing failures on browsers, set this flag to true and run /// flutter run -d chrome --web-renderer=html /// test/golden_tests/engine/shader_mask_golden_test.dart --profile const bool debugTest = false; DomElement get sceneHost => EnginePlatformDispatcher.instance.implicitView!.dom.renderingHost .querySelector(DomManager.sceneHostTagName)!; Future<void> main() async { if (!debugTest) { internalBootstrapBrowserTest(() => testMain); } else { _renderCirclesScene(BlendMode.color); } } // TODO(ferhat): unskip webkit tests once flakiness is resolved. See // https://github.com/flutter/flutter/issues/76713 // TODO(yjbanov): unskip Firefox tests when Firefox implements WebGL in headless mode. // https://github.com/flutter/flutter/issues/86623 Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); setUpAll(() async { debugShowClipLayers = true; }); setUp(() async { SurfaceSceneBuilder.debugForgetFrameScene(); for (final DomNode scene in sceneHost.querySelectorAll('flt-scene').cast<DomNode>()) { scene.remove(); } initWebGl(); }); /// Should render the picture unmodified. test('Renders shader mask with linear gradient BlendMode dst', () async { _renderCirclesScene(BlendMode.dst); await matchGoldenFile('shadermask_linear_dst.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); /// Should render the gradient only where circles have alpha channel. test('Renders shader mask with linear gradient BlendMode srcIn', () async { _renderCirclesScene(BlendMode.srcIn); await matchGoldenFile('shadermask_linear_srcin.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); test('Renders shader mask with linear gradient BlendMode color', () async { _renderCirclesScene(BlendMode.color); await matchGoldenFile('shadermask_linear_color.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); test('Renders shader mask with linear gradient BlendMode xor', () async { _renderCirclesScene(BlendMode.xor); await matchGoldenFile('shadermask_linear_xor.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); test('Renders shader mask with linear gradient BlendMode plus', () async { _renderCirclesScene(BlendMode.plus); await matchGoldenFile('shadermask_linear_plus.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); test('Renders shader mask with linear gradient BlendMode modulate', () async { _renderCirclesScene(BlendMode.modulate); await matchGoldenFile('shadermask_linear_modulate.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); test('Renders shader mask with linear gradient BlendMode overlay', () async { _renderCirclesScene(BlendMode.overlay); await matchGoldenFile('shadermask_linear_overlay.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); /// Should render the gradient opaque on top of content. test('Renders shader mask with linear gradient BlendMode src', () async { _renderCirclesScene(BlendMode.src); await matchGoldenFile('shadermask_linear_src.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); /// Should render text with gradient. test('Renders text with linear gradient shader mask', () async { _renderTextScene(BlendMode.srcIn); await matchGoldenFile('shadermask_linear_text.png', region: const Rect.fromLTWH(0, 0, 360, 200)); }, skip: isSafari || isFirefox); } Picture _drawTestPictureWithCircles( Rect region, double offsetX, double offsetY) { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(region); canvas.drawCircle(Offset(offsetX + 30, offsetY + 30), 30, SurfacePaint()..style = PaintingStyle.fill); canvas.drawCircle( Offset(offsetX + 110, offsetY + 30), 30, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color(0xFFFF0000)); canvas.drawCircle( Offset(offsetX + 30, offsetY + 110), 30, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color(0xFF00FF00)); canvas.drawCircle( Offset(offsetX + 110, offsetY + 110), 30, SurfacePaint() ..style = PaintingStyle.fill ..color = const Color(0xFF0000FF)); return recorder.endRecording(); } void _renderCirclesScene(BlendMode blendMode) { const Rect region = Rect.fromLTWH(0, 0, 400, 400); final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); final Picture circles1 = _drawTestPictureWithCircles(region, 10, 10); builder.addPicture(Offset.zero, circles1); const List<Color> colors = <Color>[ Color(0xFF000000), Color(0xFFFF3C38), Color(0xFFFF8C42), Color(0xFFFFF275), Color(0xFF6699CC), Color(0xFF656D78), ]; const List<double> stops = <double>[0.0, 0.05, 0.4, 0.6, 0.9, 1.0]; const Rect shaderBounds = Rect.fromLTWH(180, 10, 140, 140); final EngineGradient shader = GradientLinear( Offset(200 - shaderBounds.left, 30 - shaderBounds.top), Offset(320 - shaderBounds.left, 150 - shaderBounds.top), colors, stops, TileMode.clamp, Matrix4.identity().storage); builder.pushShaderMask(shader, shaderBounds, blendMode); final Picture circles2 = _drawTestPictureWithCircles(region, 180, 10); builder.addPicture(Offset.zero, circles2); builder.pop(); sceneHost.append(builder.build().webOnlyRootElement!); } Picture _drawTestPictureWithText( Rect region, double offsetX, double offsetY) { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(region); const String text = 'Shader test'; final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 40.0, ); final CanvasParagraphBuilder builder = CanvasParagraphBuilder(paragraphStyle); builder.pushStyle(EngineTextStyle.only(color: const Color(0xFFFF0000))); builder.addText(text); final CanvasParagraph paragraph = builder.build(); const double maxWidth = 200 - 10; paragraph.layout(const ParagraphConstraints(width: maxWidth)); canvas.drawParagraph(paragraph, Offset(offsetX, offsetY)); return recorder.endRecording(); } void _renderTextScene(BlendMode blendMode) { const Rect region = Rect.fromLTWH(0, 0, 600, 400); final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); final Picture textPicture = _drawTestPictureWithText(region, 10, 10); builder.addPicture(Offset.zero, textPicture); const List<Color> colors = <Color>[ Color(0xFF000000), Color(0xFFFF3C38), Color(0xFFFF8C42), Color(0xFFFFF275), Color(0xFF6699CC), Color(0xFF656D78), ]; const List<double> stops = <double>[0.0, 0.05, 0.4, 0.6, 0.9, 1.0]; const Rect shaderBounds = Rect.fromLTWH(180, 10, 140, 140); final EngineGradient shader = GradientLinear( Offset(200 - shaderBounds.left, 30 - shaderBounds.top), Offset(320 - shaderBounds.left, 150 - shaderBounds.top), colors, stops, TileMode.clamp, Matrix4.identity().storage); builder.pushShaderMask(shader, shaderBounds, blendMode); final Picture textPicture2 = _drawTestPictureWithText(region, 180, 10); builder.addPicture(Offset.zero, textPicture2); builder.pop(); sceneHost.append(builder.build().webOnlyRootElement!); }
engine/lib/web_ui/test/html/shaders/shader_mask_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/shaders/shader_mask_golden_test.dart", "repo_id": "engine", "token_count": 2849 }
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. // This is testing some of the named constants. // ignore_for_file: use_named_constants import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../common/matchers.dart'; import '../common/test_initialization.dart'; import 'paragraph/helper.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const double baselineRatio = 1.1662499904632568; setUpUnitTests(withImplicitView: true); late String fallback; setUp(() { if (operatingSystem == OperatingSystem.macOs || operatingSystem == OperatingSystem.iOs) { if (isIOS15) { fallback = 'BlinkMacSystemFont'; } else { fallback = '-apple-system, BlinkMacSystemFont'; } } else { fallback = 'Arial'; } }); test('predictably lays out a single-line paragraph', () { for (final double fontSize in <double>[10.0, 20.0, 30.0, 40.0]) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontFamily: 'Ahem', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: fontSize, )); builder.addText('Test'); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 400.0)); expect(paragraph.height, fontSize); expect(paragraph.width, 400.0); expect(paragraph.minIntrinsicWidth, fontSize * 4.0); expect(paragraph.maxIntrinsicWidth, fontSize * 4.0); expect(paragraph.alphabeticBaseline, fontSize * .8); expect( paragraph.ideographicBaseline, within( distance: 0.001, from: paragraph.alphabeticBaseline * baselineRatio), ); } }); test('predictably lays out a multi-line paragraph', () { for (final double fontSize in <double>[10.0, 20.0, 30.0, 40.0]) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontFamily: 'Ahem', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: fontSize, )); builder.addText('Test Ahem'); final Paragraph paragraph = builder.build(); paragraph.layout(ParagraphConstraints(width: fontSize * 5.0)); expect(paragraph.height, fontSize * 2.0); // because it wraps expect(paragraph.width, fontSize * 5.0); expect(paragraph.minIntrinsicWidth, fontSize * 4.0); expect(paragraph.maxIntrinsicWidth, fontSize * 9.0); expect(paragraph.alphabeticBaseline, fontSize * .8); expect( paragraph.ideographicBaseline, within( distance: 0.001, from: paragraph.alphabeticBaseline * baselineRatio), ); } }); test('Basic line related metrics', () { const double fontSize = 10; final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: fontSize, maxLines: 1, ellipsis: 'BBB', ))..addText('A' * 100); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 100.0)); expect(paragraph.numberOfLines, 1); expect(paragraph.getLineMetricsAt(-1), isNull); expect(paragraph.getLineMetricsAt(0)?.lineNumber, 0); expect(paragraph.getLineMetricsAt(1), isNull); expect(paragraph.getLineNumberAt(-1), isNull); expect(paragraph.getLineNumberAt(0), 0); expect(paragraph.getLineNumberAt(6), 0); // The last 3 characters on the first line are ellipsized with BBB. expect(paragraph.getLineNumberAt(7), isNull); }); test('Basic glyph metrics', () { const double fontSize = 10; final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: fontSize, maxLines: 1, ellipsis: 'BBB', ))..addText('A' * 100); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 100.0)); expect(paragraph.getGlyphInfoAt(-1), isNull); // The last 3 characters on the first line are ellipsized with BBB. expect(paragraph.getGlyphInfoAt(0)?.graphemeClusterCodeUnitRange, const TextRange(start: 0, end: 1)); expect(paragraph.getGlyphInfoAt(6)?.graphemeClusterCodeUnitRange, const TextRange(start: 6, end: 7)); expect(paragraph.getGlyphInfoAt(7), isNull); expect(paragraph.getGlyphInfoAt(200), isNull); }); test('Basic glyph metrics - hit test', () { const double fontSize = 10.0; final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontSize: fontSize, fontFamily: 'FlutterTest', ))..addText('Test\nTest'); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: double.infinity)); final GlyphInfo? bottomRight = paragraph.getClosestGlyphInfoForOffset(const Offset(99.0, 99.0)); final GlyphInfo? last = paragraph.getGlyphInfoAt(8); expect(bottomRight, equals(last)); expect(bottomRight, isNot(paragraph.getGlyphInfoAt(0))); expect(bottomRight?.graphemeClusterLayoutBounds, const Rect.fromLTWH(30, 10, 10, 10)); expect(bottomRight?.graphemeClusterCodeUnitRange, const TextRange(start: 8, end: 9)); expect(bottomRight?.writingDirection, TextDirection.ltr); }); test('Basic glyph metrics - hit test - center aligned text in separate fragments', () { const double fontSize = 10.0; final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontSize: fontSize, textAlign: TextAlign.center, fontFamily: 'FlutterTest', ))..addText('12345\n') ..addText('1') ..addText('2') ..addText('3'); final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: 50)); final GlyphInfo? bottomCenter = paragraph.getClosestGlyphInfoForOffset(const Offset(25.0, 99.0)); final GlyphInfo? expected = paragraph.getGlyphInfoAt(7); expect(bottomCenter, equals(expected)); expect(bottomCenter, isNot(paragraph.getGlyphInfoAt(8))); expect(bottomCenter?.graphemeClusterLayoutBounds, const Rect.fromLTWH(20, 10, 10, 10)); expect(bottomCenter?.graphemeClusterCodeUnitRange, const TextRange(start: 7, end: 8)); expect(bottomCenter?.writingDirection, TextDirection.ltr); }); test('Glyph metrics with grapheme split into different runs', () { const double fontSize = 10; final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: fontSize, maxLines: 1, ))..addText('A') // The base charater A. ..addText('̀'); // The diacritical grave accent, which should combine with the base character to form a single grapheme. final Paragraph paragraph = builder.build(); paragraph.layout(const ParagraphConstraints(width: double.infinity)); expect(paragraph.getGlyphInfoAt(0)?.graphemeClusterCodeUnitRange, const TextRange(start: 0, end: 2)); expect(paragraph.getGlyphInfoAt(0)?.graphemeClusterLayoutBounds, const Rect.fromLTWH(0.0, 0.0, 10.0, 10.0)); expect(paragraph.getGlyphInfoAt(1)?.graphemeClusterCodeUnitRange, const TextRange(start: 0, end: 2)); expect(paragraph.getGlyphInfoAt(1)?.graphemeClusterLayoutBounds, const Rect.fromLTWH(0.0, 0.0, 10.0, 10.0)); final GlyphInfo? bottomRight = paragraph.getClosestGlyphInfoForOffset(const Offset(99.0, 99.0)); expect(bottomRight?.graphemeClusterCodeUnitRange, const TextRange(start: 0, end: 2)); expect(bottomRight?.graphemeClusterLayoutBounds, const Rect.fromLTWH(0.0, 0.0, 10.0, 10.0)); }, skip: domIntl.v8BreakIterator == null); // Intended: Intl.v8breakiterator is needed for correctly breaking grapheme clusters. test('disable rounding hack', () { const double fontSize = 1; const String text = '12345'; const double letterSpacing = 0.25; const double expectedIntrinsicWidth = text.length * (fontSize + letterSpacing); assert(expectedIntrinsicWidth.truncate() != expectedIntrinsicWidth); final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(fontSize: fontSize, fontFamily: 'FlutterTest')); builder.pushStyle(TextStyle(letterSpacing: letterSpacing)); builder.addText(text); final Paragraph paragraph = builder.build() ..layout(const ParagraphConstraints(width: expectedIntrinsicWidth)); expect(paragraph.maxIntrinsicWidth, expectedIntrinsicWidth); switch (paragraph.computeLineMetrics()) { case [LineMetrics(width: final double width)]: expect(width, expectedIntrinsicWidth); case final List<LineMetrics> metrics: expect(metrics, hasLength(1)); } }); test('lay out unattached paragraph', () { final CanvasParagraph paragraph = plain(EngineParagraphStyle( fontFamily: 'sans-serif', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 14.0, ), 'How do you do this fine morning?'); expect(paragraph.height, 0.0); expect(paragraph.width, -1.0); expect(paragraph.minIntrinsicWidth, 0.0); expect(paragraph.maxIntrinsicWidth, 0.0); expect(paragraph.alphabeticBaseline, -1.0); expect(paragraph.ideographicBaseline, -1.0); paragraph.layout(const ParagraphConstraints(width: 60.0)); expect(paragraph.height, greaterThan(0.0)); expect(paragraph.width, greaterThan(0.0)); expect(paragraph.minIntrinsicWidth, greaterThan(0.0)); expect(paragraph.maxIntrinsicWidth, greaterThan(0.0)); expect(paragraph.minIntrinsicWidth, lessThan(paragraph.maxIntrinsicWidth)); expect(paragraph.alphabeticBaseline, greaterThan(0.0)); expect(paragraph.ideographicBaseline, greaterThan(0.0)); }); Paragraph measure( {String text = 'Hello', double fontSize = 14.0, double width = 50.0}) { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle( fontFamily: 'sans-serif', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: fontSize, )); builder.addText(text); final Paragraph paragraph = builder.build(); paragraph.layout(ParagraphConstraints(width: width)); return paragraph; } test('baseline increases with font size', () { Paragraph previousParagraph = measure(fontSize: 10.0); for (int i = 0; i < 6; i++) { final double fontSize = 20.0 + 10.0 * i; final Paragraph paragraph = measure(fontSize: fontSize); expect(paragraph.alphabeticBaseline, greaterThan(previousParagraph.alphabeticBaseline)); expect(paragraph.ideographicBaseline, greaterThan(previousParagraph.ideographicBaseline)); previousParagraph = paragraph; } }); test('baseline does not depend on text', () { final Paragraph golden = measure(fontSize: 30.0); for (int i = 1; i < 30; i++) { final Paragraph paragraph = measure(text: 'hello ' * i, fontSize: 30.0); expect(paragraph.alphabeticBaseline, golden.alphabeticBaseline); expect(paragraph.ideographicBaseline, golden.ideographicBaseline); } }); test('$ParagraphBuilder detects plain text', () { ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle( fontFamily: 'sans-serif', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 15.0, )); builder.addText('hi'); CanvasParagraph paragraph = builder.build() as CanvasParagraph; expect(paragraph.plainText, isNotNull); expect(paragraph.paragraphStyle.fontWeight, FontWeight.normal); builder = ParagraphBuilder(EngineParagraphStyle( fontFamily: 'sans-serif', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 15.0, )); builder.pushStyle(TextStyle(fontWeight: FontWeight.bold)); builder.addText('hi'); paragraph = builder.build() as CanvasParagraph; expect(paragraph.plainText, isNotNull); }); test('$ParagraphBuilder detects rich text', () { final ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle( fontFamily: 'sans-serif', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 15.0, )); builder.addText('h'); builder.pushStyle(TextStyle(fontWeight: FontWeight.bold)); builder.addText('i'); final CanvasParagraph paragraph = builder.build() as CanvasParagraph; expect(paragraph.plainText, 'hi'); }); test('$ParagraphBuilder treats empty text as plain', () { final ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle( fontFamily: 'sans-serif', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 15.0, )); builder.pushStyle(TextStyle(fontWeight: FontWeight.bold)); final CanvasParagraph paragraph = builder.build() as CanvasParagraph; expect(paragraph.plainText, ''); }); // Regression test for https://github.com/flutter/flutter/issues/38972 test( 'should not set fontFamily to effectiveFontFamily for spans in rich text', () { final ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle( fontFamily: 'Roboto', fontStyle: FontStyle.normal, fontWeight: FontWeight.normal, fontSize: 15.0, )); builder .pushStyle(TextStyle(fontFamily: 'Menlo', fontWeight: FontWeight.bold)); const String firstSpanText = 'abc'; builder.addText(firstSpanText); builder.pushStyle(TextStyle(fontSize: 30.0, fontWeight: FontWeight.normal)); const String secondSpanText = 'def'; builder.addText(secondSpanText); final CanvasParagraph paragraph = builder.build() as CanvasParagraph; paragraph.layout(const ParagraphConstraints(width: 800.0)); expect(paragraph.plainText, 'abcdef'); final List<DomElement> spans = paragraph.toDomElement().querySelectorAll('flt-span').toList(); expect(spans[0].style.fontFamily, 'FlutterTest, $fallback, sans-serif'); // The nested span here should not set it's family to default sans-serif. expect(spans[1].style.fontFamily, 'FlutterTest, $fallback, sans-serif'); }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/46638 skip: browserEngine == BrowserEngine.firefox); test('adds Arial and sans-serif as fallback fonts', () { // Set this to false so it doesn't default to the test font. ui_web.debugEmulateFlutterTesterEnvironment = false; final CanvasParagraph paragraph = plain(EngineParagraphStyle( fontFamily: 'SomeFont', fontSize: 12.0, ), 'Hello'); paragraph.layout(constrain(double.infinity)); expect(paragraph.toDomElement().children.single.style.fontFamily, 'SomeFont, $fallback, sans-serif'); ui_web.debugEmulateFlutterTesterEnvironment = true; }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/46638 skip: browserEngine == BrowserEngine.firefox); test('does not add fallback fonts to generic families', () { // Set this to false so it doesn't default to the default test font. ui_web.debugEmulateFlutterTesterEnvironment = false; final CanvasParagraph paragraph = plain(EngineParagraphStyle( fontFamily: 'serif', fontSize: 12.0, ), 'Hello'); paragraph.layout(constrain(double.infinity)); expect(paragraph.toDomElement().children.single.style.fontFamily, 'serif'); ui_web.debugEmulateFlutterTesterEnvironment = true; }); test('can set font families that need to be quoted', () { // Set this to false so it doesn't default to the default test font. ui_web.debugEmulateFlutterTesterEnvironment = false; final CanvasParagraph paragraph = plain(EngineParagraphStyle( fontFamily: 'MyFont 2000', fontSize: 12.0, ), 'Hello'); paragraph.layout(constrain(double.infinity)); expect(paragraph.toDomElement().children.single.style.fontFamily, '"MyFont 2000", $fallback, sans-serif'); ui_web.debugEmulateFlutterTesterEnvironment = true; }); group('TextRange', () { test('empty ranges are correct', () { const TextRange range = TextRange(start: -1, end: -1); expect(range, equals(TextRange.collapsed(-1))); // ignore: prefer_const_constructors expect(range, equals(TextRange.empty)); }); test('isValid works', () { expect(TextRange.empty.isValid, isFalse); expect(const TextRange(start: 0, end: 0).isValid, isTrue); expect(const TextRange(start: 0, end: 10).isValid, isTrue); expect(const TextRange(start: 10, end: 10).isValid, isTrue); expect(const TextRange(start: -1, end: 10).isValid, isFalse); expect(const TextRange(start: 10, end: 0).isValid, isTrue); expect(const TextRange(start: 10, end: -1).isValid, isFalse); }); test('isCollapsed works', () { expect(TextRange.empty.isCollapsed, isTrue); expect(const TextRange(start: 0, end: 0).isCollapsed, isTrue); expect(const TextRange(start: 0, end: 10).isCollapsed, isFalse); expect(const TextRange(start: 10, end: 10).isCollapsed, isTrue); expect(const TextRange(start: -1, end: 10).isCollapsed, isFalse); expect(const TextRange(start: 10, end: 0).isCollapsed, isFalse); expect(const TextRange(start: 10, end: -1).isCollapsed, isFalse); }); test('isNormalized works', () { expect(TextRange.empty.isNormalized, isTrue); expect(const TextRange(start: 0, end: 0).isNormalized, isTrue); expect(const TextRange(start: 0, end: 10).isNormalized, isTrue); expect(const TextRange(start: 10, end: 10).isNormalized, isTrue); expect(const TextRange(start: -1, end: 10).isNormalized, isTrue); expect(const TextRange(start: 10, end: 0).isNormalized, isFalse); expect(const TextRange(start: 10, end: -1).isNormalized, isFalse); }); test('textBefore works', () { expect(const TextRange(start: 0, end: 0).textBefore('hello'), isEmpty); expect( const TextRange(start: 1, end: 1).textBefore('hello'), equals('h')); expect( const TextRange(start: 1, end: 2).textBefore('hello'), equals('h')); expect(const TextRange(start: 5, end: 5).textBefore('hello'), equals('hello')); expect(const TextRange(start: 0, end: 5).textBefore('hello'), isEmpty); }); test('textAfter works', () { expect(const TextRange(start: 0, end: 0).textAfter('hello'), equals('hello')); expect( const TextRange(start: 1, end: 1).textAfter('hello'), equals('ello')); expect( const TextRange(start: 1, end: 2).textAfter('hello'), equals('llo')); expect(const TextRange(start: 5, end: 5).textAfter('hello'), isEmpty); expect(const TextRange(start: 0, end: 5).textAfter('hello'), isEmpty); }); test('textInside works', () { expect(const TextRange(start: 0, end: 0).textInside('hello'), isEmpty); expect(const TextRange(start: 1, end: 1).textInside('hello'), isEmpty); expect( const TextRange(start: 1, end: 2).textInside('hello'), equals('e')); expect(const TextRange(start: 5, end: 5).textInside('hello'), isEmpty); expect(const TextRange(start: 0, end: 5).textInside('hello'), equals('hello')); }); }); test('FontWeights have the correct value', () { expect(FontWeight.w100.value, 100); expect(FontWeight.w200.value, 200); expect(FontWeight.w300.value, 300); expect(FontWeight.w400.value, 400); expect(FontWeight.w500.value, 500); expect(FontWeight.w600.value, 600); expect(FontWeight.w700.value, 700); expect(FontWeight.w800.value, 800); expect(FontWeight.w900.value, 900); }); group('test fonts in flutterTester environment', () { final bool resetValue = ui_web.debugEmulateFlutterTesterEnvironment; ui_web.debugEmulateFlutterTesterEnvironment = true; tearDownAll(() { ui_web.debugEmulateFlutterTesterEnvironment = resetValue; }); const List<String> testFonts = <String>['FlutterTest', 'Ahem']; test('The default test font is used when a non-test fontFamily is specified, or fontFamily is not specified', () { final String defaultTestFontFamily = testFonts.first; expect(EngineTextStyle.only().effectiveFontFamily, defaultTestFontFamily); expect(EngineTextStyle.only(fontFamily: 'BogusFontFamily').effectiveFontFamily, defaultTestFontFamily); }); test('Can specify test fontFamily to use', () { for (final String testFont in testFonts) { expect(EngineTextStyle.only(fontFamily: testFont).effectiveFontFamily, testFont); } }); }); }
engine/lib/web_ui/test/html/text_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/text_test.dart", "repo_id": "engine", "token_count": 7633 }
289
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart' as ui; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, setUpTestViewDimensions: false, ); test('empty paragraph', () { const double fontSize = 10.0; final ui.Paragraph paragraph = ui.ParagraphBuilder(ui.ParagraphStyle( fontSize: fontSize, )).build(); paragraph.layout(const ui.ParagraphConstraints(width: double.infinity)); expect(paragraph.getLineMetricsAt(0), isNull); expect(paragraph.numberOfLines, 0); expect(paragraph.getLineNumberAt(0), isNull); }, skip: isHtml); // https://github.com/flutter/flutter/issues/144412 test('Basic line related metrics', () { const double fontSize = 10; final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle( fontStyle: ui.FontStyle.normal, fontWeight: ui.FontWeight.normal, fontSize: fontSize, maxLines: 1, ellipsis: 'BBB', ))..addText('A' * 100); final ui.Paragraph paragraph = builder.build(); paragraph.layout(const ui.ParagraphConstraints(width: 100.0)); expect(paragraph.numberOfLines, 1); expect(paragraph.getLineMetricsAt(-1), isNull); expect(paragraph.getLineMetricsAt(0)?.lineNumber, 0); expect(paragraph.getLineMetricsAt(1), isNull); expect(paragraph.getLineNumberAt(-1), isNull); expect(paragraph.getLineNumberAt(0), 0); expect(paragraph.getLineNumberAt(6), 0); // The last 3 characters on the first line are ellipsized with BBB. expect(paragraph.getLineMetricsAt(7), isNull); }); test('Basic glyph metrics', () { const double fontSize = 10; final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle( fontStyle: ui.FontStyle.normal, fontWeight: ui.FontWeight.normal, fontFamily: 'FlutterTest', fontSize: fontSize, maxLines: 1, ellipsis: 'BBB', ))..addText('A' * 100); final ui.Paragraph paragraph = builder.build(); paragraph.layout(const ui.ParagraphConstraints(width: 100.0)); expect(paragraph.getGlyphInfoAt(-1), isNull); // The last 3 characters on the first line are ellipsized with BBB. expect(paragraph.getGlyphInfoAt(0)?.graphemeClusterCodeUnitRange, const ui.TextRange(start: 0, end: 1)); expect(paragraph.getGlyphInfoAt(6)?.graphemeClusterCodeUnitRange, const ui.TextRange(start: 6, end: 7)); expect(paragraph.getGlyphInfoAt(7), isNull); expect(paragraph.getGlyphInfoAt(200), isNull); }); test('Basic glyph metrics - hit test', () { const double fontSize = 10.0; final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle( fontSize: fontSize, fontFamily: 'FlutterTest', ))..addText('Test\nTest'); final ui.Paragraph paragraph = builder.build(); paragraph.layout(const ui.ParagraphConstraints(width: double.infinity)); final ui.GlyphInfo? bottomRight = paragraph.getClosestGlyphInfoForOffset(const ui.Offset(99.0, 99.0)); final ui.GlyphInfo? last = paragraph.getGlyphInfoAt(8); expect(bottomRight, equals(last)); expect(bottomRight, isNot(paragraph.getGlyphInfoAt(0))); expect(bottomRight?.graphemeClusterLayoutBounds, const ui.Rect.fromLTWH(30, 10, 10, 10)); expect(bottomRight?.graphemeClusterCodeUnitRange, const ui.TextRange(start: 8, end: 9)); expect(bottomRight?.writingDirection, ui.TextDirection.ltr); }); test('rounding hack is always disabled', () { const double fontSize = 1.25; const String text = '12345'; assert((fontSize * text.length).truncate() != fontSize * text.length); final ui.ParagraphBuilder builder = ui.ParagraphBuilder( ui.ParagraphStyle(fontSize: fontSize, fontFamily: 'FlutterTest'), ); builder.addText(text); final ui.Paragraph paragraph = builder.build() ..layout(const ui.ParagraphConstraints(width: text.length * fontSize)); expect(paragraph.maxIntrinsicWidth, text.length * fontSize); switch (paragraph.computeLineMetrics()) { case [ui.LineMetrics(width: final double width)]: expect(width, text.length * fontSize); case final List<ui.LineMetrics> metrics: expect(metrics, hasLength(1)); } }, skip: isHtml); // The rounding hack doesn't apply to the html renderer }
engine/lib/web_ui/test/ui/line_metrics_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/line_metrics_test.dart", "repo_id": "engine", "token_count": 1697 }
290
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; import 'package:ui/src/engine.dart'; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../common/matchers.dart'; import '../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests(); setUp(() { ui_web.debugResetCustomUrlStrategy(); }); tearDown(() { ui_web.debugResetCustomUrlStrategy(); }); test('uses the default if no custom URL strategy is set', () { final ui_web.UrlStrategy defaultUrlStrategy = TestUrlStrategy(); ui_web.debugDefaultUrlStrategyOverride = defaultUrlStrategy; expect(ui_web.urlStrategy, defaultUrlStrategy); expect(ui_web.isCustomUrlStrategySet, isFalse); }); test('can set a custom URL strategy', () { final TestUrlStrategy customUrlStrategy = TestUrlStrategy(); ui_web.urlStrategy = customUrlStrategy; expect(ui_web.urlStrategy, customUrlStrategy); expect(ui_web.isCustomUrlStrategySet, isTrue); // Does not allow custom URL strategy to be set again. expect( () { ui_web.urlStrategy = customUrlStrategy; }, throwsAssertionError, ); }); test('custom URL strategy can be prevented manually', () { ui_web.preventCustomUrlStrategy(); expect(ui_web.isCustomUrlStrategySet, isFalse); expect( () { ui_web.urlStrategy = TestUrlStrategy(); }, throwsAssertionError, ); }); }
engine/lib/web_ui/test/ui/url_strategy_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/url_strategy_test.dart", "repo_id": "engine", "token_count": 625 }
291
// 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/runtime/dart_snapshot.h" #include <sstream> #include "flutter/fml/native_library.h" #include "flutter/fml/paths.h" #include "flutter/fml/trace_event.h" #include "flutter/lib/snapshot/snapshot.h" #include "flutter/runtime/dart_vm.h" #include "third_party/dart/runtime/include/dart_api.h" namespace flutter { const char* DartSnapshot::kVMDataSymbol = "kDartVmSnapshotData"; const char* DartSnapshot::kVMInstructionsSymbol = "kDartVmSnapshotInstructions"; const char* DartSnapshot::kIsolateDataSymbol = "kDartIsolateSnapshotData"; const char* DartSnapshot::kIsolateInstructionsSymbol = "kDartIsolateSnapshotInstructions"; // On Windows and Android (in debug mode) the engine finds the Dart snapshot // data through symbols that are statically linked into the executable. // On other platforms this data is obtained by a dynamic symbol lookup. #define DART_SNAPSHOT_STATIC_LINK \ ((FML_OS_WIN || FML_OS_ANDROID) && FLUTTER_JIT_RUNTIME) #if !DART_SNAPSHOT_STATIC_LINK static std::unique_ptr<const fml::Mapping> GetFileMapping( const std::string& path, bool executable) { if (executable) { return fml::FileMapping::CreateReadExecute(path); } else { return fml::FileMapping::CreateReadOnly(path); } } // The first party embedders don't yet use the stable embedder API and depend on // the engine figuring out the locations of the various heap and instructions // buffers. Consequently, the engine had baked in opinions about where these // buffers would reside and how they would be packaged (examples, in an external // dylib, in the same dylib, at a path, at a path relative to and FD, etc..). As // the needs of the platforms changed, the lack of an API meant that the engine // had to be patched to look for new fields in the settings object. This grew // untenable and with the addition of the new Fuchsia embedder and the generic C // embedder API, embedders could specify the mapping directly. Once everyone // moves to the embedder API, this method can effectively be reduced to just // invoking the embedder_mapping_callback directly. static std::shared_ptr<const fml::Mapping> SearchMapping( const MappingCallback& embedder_mapping_callback, const std::string& file_path, const std::vector<std::string>& native_library_path, const char* native_library_symbol_name, bool is_executable) { // Ask the embedder. There is no fallback as we expect the embedders (via // their embedding APIs) to just specify the mappings directly. if (embedder_mapping_callback) { // Note that mapping will be nullptr if the mapping callback returns an // invalid mapping. If all the other methods for resolving the data also // fail, the engine will stop with accompanying error logs. if (auto mapping = embedder_mapping_callback()) { return mapping; } } // Attempt to open file at path specified. if (!file_path.empty()) { if (auto file_mapping = GetFileMapping(file_path, is_executable)) { return file_mapping; } } // Look in application specified native library if specified. for (const std::string& path : native_library_path) { auto native_library = fml::NativeLibrary::Create(path.c_str()); auto symbol_mapping = std::make_unique<const fml::SymbolMapping>( native_library, native_library_symbol_name); if (symbol_mapping->GetMapping() != nullptr) { return symbol_mapping; } } // Look inside the currently loaded process. { auto loaded_process = fml::NativeLibrary::CreateForCurrentProcess(); auto symbol_mapping = std::make_unique<const fml::SymbolMapping>( loaded_process, native_library_symbol_name); if (symbol_mapping->GetMapping() != nullptr) { return symbol_mapping; } } return nullptr; } #endif // !DART_SNAPSHOT_STATIC_LINK static std::shared_ptr<const fml::Mapping> ResolveVMData( const Settings& settings) { #if DART_SNAPSHOT_STATIC_LINK return std::make_unique<fml::NonOwnedMapping>(kDartVmSnapshotData, 0, // size nullptr, // release_func true // dontneed_safe ); #else // DART_SNAPSHOT_STATIC_LINK return SearchMapping( settings.vm_snapshot_data, // embedder_mapping_callback settings.vm_snapshot_data_path, // file_path settings.application_library_path, // native_library_path DartSnapshot::kVMDataSymbol, // native_library_symbol_name false // is_executable ); #endif // DART_SNAPSHOT_STATIC_LINK } static std::shared_ptr<const fml::Mapping> ResolveVMInstructions( const Settings& settings) { #if DART_SNAPSHOT_STATIC_LINK return std::make_unique<fml::NonOwnedMapping>(kDartVmSnapshotInstructions, 0, // size nullptr, // release_func true // dontneed_safe ); #else // DART_SNAPSHOT_STATIC_LINK return SearchMapping( settings.vm_snapshot_instr, // embedder_mapping_callback settings.vm_snapshot_instr_path, // file_path settings.application_library_path, // native_library_path DartSnapshot::kVMInstructionsSymbol, // native_library_symbol_name true // is_executable ); #endif // DART_SNAPSHOT_STATIC_LINK } static std::shared_ptr<const fml::Mapping> ResolveIsolateData( const Settings& settings) { #if DART_SNAPSHOT_STATIC_LINK return std::make_unique<fml::NonOwnedMapping>(kDartIsolateSnapshotData, 0, // size nullptr, // release_func true // dontneed_safe ); #else // DART_SNAPSHOT_STATIC_LINK return SearchMapping( settings.isolate_snapshot_data, // embedder_mapping_callback settings.isolate_snapshot_data_path, // file_path settings.application_library_path, // native_library_path DartSnapshot::kIsolateDataSymbol, // native_library_symbol_name false // is_executable ); #endif // DART_SNAPSHOT_STATIC_LINK } static std::shared_ptr<const fml::Mapping> ResolveIsolateInstructions( const Settings& settings) { #if DART_SNAPSHOT_STATIC_LINK return std::make_unique<fml::NonOwnedMapping>( kDartIsolateSnapshotInstructions, 0, // size nullptr, // release_func true // dontneed_safe ); #else // DART_SNAPSHOT_STATIC_LINK return SearchMapping( settings.isolate_snapshot_instr, // embedder_mapping_callback settings.isolate_snapshot_instr_path, // file_path settings.application_library_path, // native_library_path DartSnapshot::kIsolateInstructionsSymbol, // native_library_symbol_name true // is_executable ); #endif // DART_SNAPSHOT_STATIC_LINK } fml::RefPtr<const DartSnapshot> DartSnapshot::VMSnapshotFromSettings( const Settings& settings) { TRACE_EVENT0("flutter", "DartSnapshot::VMSnapshotFromSettings"); auto snapshot = fml::MakeRefCounted<DartSnapshot>(ResolveVMData(settings), // ResolveVMInstructions(settings) // ); if (snapshot->IsValid()) { return snapshot; } return nullptr; } fml::RefPtr<const DartSnapshot> DartSnapshot::IsolateSnapshotFromSettings( const Settings& settings) { TRACE_EVENT0("flutter", "DartSnapshot::IsolateSnapshotFromSettings"); auto snapshot = fml::MakeRefCounted<DartSnapshot>(ResolveIsolateData(settings), // ResolveIsolateInstructions(settings) // ); if (snapshot->IsValid()) { return snapshot; } return nullptr; } fml::RefPtr<DartSnapshot> DartSnapshot::IsolateSnapshotFromMappings( const std::shared_ptr<const fml::Mapping>& snapshot_data, const std::shared_ptr<const fml::Mapping>& snapshot_instructions) { auto snapshot = fml::MakeRefCounted<DartSnapshot>(snapshot_data, snapshot_instructions); if (snapshot->IsValid()) { return snapshot; } return nullptr; } fml::RefPtr<DartSnapshot> DartSnapshot::VMServiceIsolateSnapshotFromSettings( const Settings& settings) { #if DART_SNAPSHOT_STATIC_LINK return nullptr; #else // DART_SNAPSHOT_STATIC_LINK if (settings.vmservice_snapshot_library_path.empty()) { return nullptr; } std::shared_ptr<const fml::Mapping> snapshot_data = SearchMapping(nullptr, "", settings.vmservice_snapshot_library_path, DartSnapshot::kIsolateDataSymbol, false); std::shared_ptr<const fml::Mapping> snapshot_instructions = SearchMapping(nullptr, "", settings.vmservice_snapshot_library_path, DartSnapshot::kIsolateInstructionsSymbol, true); return IsolateSnapshotFromMappings(snapshot_data, snapshot_instructions); #endif // DART_SNAPSHOT_STATIC_LINK } DartSnapshot::DartSnapshot(std::shared_ptr<const fml::Mapping> data, std::shared_ptr<const fml::Mapping> instructions) : data_(std::move(data)), instructions_(std::move(instructions)) {} DartSnapshot::~DartSnapshot() = default; bool DartSnapshot::IsValid() const { return static_cast<bool>(data_); } bool DartSnapshot::IsValidForAOT() const { return data_ && instructions_; } const uint8_t* DartSnapshot::GetDataMapping() const { return data_ ? data_->GetMapping() : nullptr; } const uint8_t* DartSnapshot::GetInstructionsMapping() const { return instructions_ ? instructions_->GetMapping() : nullptr; } bool DartSnapshot::IsDontNeedSafe() const { if (data_ && !data_->IsDontNeedSafe()) { return false; } if (instructions_ && !instructions_->IsDontNeedSafe()) { return false; } return true; } bool DartSnapshot::IsNullSafetyEnabled(const fml::Mapping* kernel) const { return ::Dart_DetectNullSafety( nullptr, // script_uri (unsupported by Flutter) nullptr, // package_config (package resolution of parent used) nullptr, // original_working_directory (no package config) GetDataMapping(), // snapshot_data GetInstructionsMapping(), // snapshot_instructions kernel ? kernel->GetMapping() : nullptr, // kernel_buffer kernel ? kernel->GetSize() : 0u // kernel_buffer_size ); } } // namespace flutter
engine/runtime/dart_snapshot.cc/0
{ "file_path": "engine/runtime/dart_snapshot.cc", "repo_id": "engine", "token_count": 4374 }
292
// 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_RUNTIME_RUNTIME_DELEGATE_H_ #define FLUTTER_RUNTIME_RUNTIME_DELEGATE_H_ #include <memory> #include <vector> #include "flutter/assets/asset_manager.h" #include "flutter/flow/layers/layer_tree.h" #include "flutter/lib/ui/semantics/custom_accessibility_action.h" #include "flutter/lib/ui/semantics/semantics_node.h" #include "flutter/lib/ui/text/font_collection.h" #include "flutter/lib/ui/window/platform_message.h" #include "flutter/shell/common/platform_message_handler.h" #include "third_party/dart/runtime/include/dart_api.h" namespace flutter { class RuntimeDelegate { public: virtual std::string DefaultRouteName() = 0; virtual void ScheduleFrame(bool regenerate_layer_trees = true) = 0; virtual void OnAllViewsRendered() = 0; virtual void Render(int64_t view_id, std::unique_ptr<flutter::LayerTree> layer_tree, float device_pixel_ratio) = 0; virtual void UpdateSemantics(SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) = 0; virtual void HandlePlatformMessage( std::unique_ptr<PlatformMessage> message) = 0; virtual FontCollection& GetFontCollection() = 0; virtual std::shared_ptr<AssetManager> GetAssetManager() = 0; virtual void OnRootIsolateCreated() = 0; virtual void UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) = 0; virtual void SetNeedsReportTimings(bool value) = 0; virtual std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale( const std::vector<std::string>& supported_locale_data) = 0; virtual void RequestDartDeferredLibrary(intptr_t loading_unit_id) = 0; virtual std::weak_ptr<PlatformMessageHandler> GetPlatformMessageHandler() const = 0; virtual void SendChannelUpdate(std::string name, bool listening) = 0; virtual double GetScaledFontSize(double unscaled_font_size, int configuration_id) const = 0; protected: virtual ~RuntimeDelegate(); }; } // namespace flutter #endif // FLUTTER_RUNTIME_RUNTIME_DELEGATE_H_
engine/runtime/runtime_delegate.h/0
{ "file_path": "engine/runtime/runtime_delegate.h", "repo_id": "engine", "token_count": 854 }
293
// 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/shell/common/context_options.h" #include "flutter/common/graphics/persistent_cache.h" namespace flutter { GrContextOptions MakeDefaultContextOptions(ContextType type, std::optional<GrBackendApi> api) { GrContextOptions options; if (PersistentCache::cache_sksl()) { options.fShaderCacheStrategy = GrContextOptions::ShaderCacheStrategy::kSkSL; } PersistentCache::MarkStrategySet(); options.fPersistentCache = PersistentCache::GetCacheForProcess(); if (api.has_value() && api.value() == GrBackendApi::kOpenGL) { // Using stencil buffers has caused memory and performance regressions. // See b/226484927 for internal customer regressions doc. // Before enabling, we need to show a motivating case for where it will // improve performance on OpenGL backend. options.fAvoidStencilBuffers = true; // To get video playback on the widest range of devices, we limit Skia to // ES2 shading language when the ES3 external image extension is missing. options.fPreferExternalImagesOverES3 = true; } // TODO(goderbauer): remove option when skbug.com/7523 is fixed. options.fDisableGpuYUVConversion = true; options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo; options.fReducedShaderVariations = false; return options; }; } // namespace flutter
engine/shell/common/context_options.cc/0
{ "file_path": "engine/shell/common/context_options.cc", "repo_id": "engine", "token_count": 495 }
294
// 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 'dart:async' show scheduleMicrotask; import 'dart:convert' show json, utf8; import 'dart:isolate'; import 'dart:typed_data'; import 'dart:ui'; void expect(Object? a, Object? b) { if (a != b) { throw AssertionError('Expected $a to == $b'); } } void main() {} @pragma('vm:entry-point') void mainNotifyNative() { notifyNative(); } @pragma('vm:external-name', 'NativeReportTimingsCallback') external void nativeReportTimingsCallback(List<int> timings); @pragma('vm:external-name', 'NativeOnBeginFrame') external void nativeOnBeginFrame(int microseconds); @pragma('vm:external-name', 'NativeOnPointerDataPacket') external void nativeOnPointerDataPacket(List<int> sequences); @pragma('vm:entry-point') void onErrorA() { PlatformDispatcher.instance.onError = (Object error, StackTrace? stack) { notifyErrorA(error.toString()); return true; }; Future<void>.delayed(const Duration(seconds: 2)).then((_) { throw Exception('I should be coming from A'); }); } @pragma('vm:entry-point') void onErrorB() { PlatformDispatcher.instance.onError = (Object error, StackTrace? stack) { notifyErrorB(error.toString()); return true; }; throw Exception('I should be coming from B'); } @pragma('vm:external-name', 'NotifyErrorA') external void notifyErrorA(String message); @pragma('vm:external-name', 'NotifyErrorB') external void notifyErrorB(String message); @pragma('vm:entry-point') void drawFrames() { // Wait for native to tell us to start going. notifyNative(); PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF)); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); window.render(scene); scene.dispose(); picture.dispose(); }; PlatformDispatcher.instance.scheduleFrame(); } @pragma('vm:entry-point') void reportTimingsMain() { PlatformDispatcher.instance.onReportTimings = (List<FrameTiming> timings) { List<int> timestamps = []; for (FrameTiming t in timings) { for (FramePhase phase in FramePhase.values) { timestamps.add(t.timestampInMicroseconds(phase)); } } nativeReportTimingsCallback(timestamps); PlatformDispatcher.instance.onReportTimings = (List<FrameTiming> timings) {}; }; } @pragma('vm:entry-point') void onBeginFrameMain() { PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) { nativeOnBeginFrame(beginTime.inMicroseconds); }; PlatformDispatcher.instance.scheduleFrame(); } @pragma('vm:entry-point') void onPointerDataPacketMain() { PlatformDispatcher.instance.onPointerDataPacket = (PointerDataPacket packet) { List<int> sequence = <int>[]; for (PointerData data in packet.data) { sequence.add(PointerChange.values.indexOf(data.change)); } nativeOnPointerDataPacket(sequence); }; } @pragma('vm:entry-point') void emptyMain() {} @pragma('vm:entry-point') void reportMetrics() { window.onMetricsChanged = () { _reportMetrics( window.devicePixelRatio, window.physicalSize.width, window.physicalSize.height, ); }; } @pragma('vm:external-name', 'ReportMetrics') external void _reportMetrics(double devicePixelRatio, double width, double height); @pragma('vm:entry-point') void dummyReportTimingsMain() { PlatformDispatcher.instance.onReportTimings = (List<FrameTiming> timings) {}; } @pragma('vm:entry-point') void fixturesAreFunctionalMain() { sayHiFromFixturesAreFunctionalMain(); } @pragma('vm:external-name', 'SayHiFromFixturesAreFunctionalMain') external void sayHiFromFixturesAreFunctionalMain(); @pragma('vm:entry-point') @pragma('vm:external-name', 'NotifyNative') external void notifyNative(); @pragma('vm:entry-point') void thousandCallsToNative() { for (int i = 0; i < 1000; i++) { notifyNative(); } } void secondaryIsolateMain(String message) { print('Secondary isolate got message: ' + message); notifyNative(); } @pragma('vm:entry-point') void testCanLaunchSecondaryIsolate() { Isolate.spawn(secondaryIsolateMain, 'Hello from root isolate.'); notifyNative(); } @pragma('vm:entry-point') void testSkiaResourceCacheSendsResponse() { final PlatformMessageResponseCallback callback = (ByteData? data) { if (data == null) { throw 'Response must not be null.'; } final String response = utf8.decode(data.buffer.asUint8List()); final List<bool> jsonResponse = json.decode(response).cast<bool>(); if (jsonResponse[0] != true) { throw 'Response was not true'; } notifyNative(); }; const String jsonRequest = '''{ "method": "Skia.setResourceCacheMaxBytes", "args": 10000 }'''; PlatformDispatcher.instance.sendPlatformMessage( 'flutter/skia', ByteData.sublistView(utf8.encode(jsonRequest)), callback, ); } @pragma('vm:external-name', 'NotifyWidthHeight') external void notifyWidthHeight(int width, int height); @pragma('vm:entry-point') void canCreateImageFromDecompressedData() { const int imageWidth = 10; const int imageHeight = 10; final Uint8List pixels = Uint8List.fromList(List<int>.generate( imageWidth * imageHeight * 4, (int i) => i % 4 < 2 ? 0x00 : 0xFF, )); decodeImageFromPixels( pixels, imageWidth, imageHeight, PixelFormat.rgba8888, (Image image) { notifyWidthHeight(image.width, image.height); }, ); } @pragma('vm:entry-point') void canAccessIsolateLaunchData() { notifyMessage( utf8.decode( PlatformDispatcher.instance.getPersistentIsolateData()!.buffer.asUint8List(), ), ); } @pragma('vm:entry-point') void performanceModeImpactsNotifyIdle() { notifyNativeBool(false); PlatformDispatcher.instance.requestDartPerformanceMode(DartPerformanceMode.latency); notifyNativeBool(true); PlatformDispatcher.instance.requestDartPerformanceMode(DartPerformanceMode.balanced); } @pragma('vm:entry-point') void callNotifyDestroyed() { notifyDestroyed(); } @pragma('vm:external-name', 'NotifyMessage') external void notifyMessage(String string); @pragma('vm:entry-point') void canRegisterImageDecoders() { decodeImageFromList( // The test ImageGenerator will always behave the same regardless of input. Uint8List(1), (Image result) { notifyWidthHeight(result.width, result.height); }, ); } @pragma('vm:external-name', 'NotifyLocalTime') external void notifyLocalTime(String string); @pragma('vm:external-name', 'WaitFixture') external bool waitFixture(); // Return local date-time as a string, to an hour resolution. So, "2020-07-23 // 14:03:22" will become "2020-07-23 14". String localTimeAsString() { final now = DateTime.now().toLocal(); // This is: "$y-$m-$d $h:$min:$sec.$ms$us"; final timeStr = now.toString(); // Forward only "$y-$m-$d $h" for timestamp comparison. Not using DateTime // formatting since package:intl is not available. return timeStr.split(":")[0]; } @pragma('vm:entry-point') void localtimesMatch() { notifyLocalTime(localTimeAsString()); } @pragma('vm:entry-point') void timezonesChange() { do { notifyLocalTime(localTimeAsString()); } while (waitFixture()); } @pragma('vm:external-name', 'NotifyCanAccessResource') external void notifyCanAccessResource(bool success); @pragma('vm:external-name', 'NotifySetAssetBundlePath') external void notifySetAssetBundlePath(); @pragma('vm:entry-point') void canAccessResourceFromAssetDir() async { notifySetAssetBundlePath(); window.sendPlatformMessage( 'flutter/assets', ByteData.sublistView(utf8.encode('kernel_blob.bin')), (ByteData? byteData) { notifyCanAccessResource(byteData != null); }, ); } @pragma('vm:external-name', 'NotifyNativeWhenEngineRun') external void notifyNativeWhenEngineRun(bool success); @pragma('vm:external-name', 'NotifyNativeWhenEngineSpawn') external void notifyNativeWhenEngineSpawn(bool success); @pragma('vm:entry-point') void canReceiveArgumentsWhenEngineRun(List<String> args) { notifyNativeWhenEngineRun(args.length == 2 && args[0] == 'foo' && args[1] == 'bar'); } @pragma('vm:entry-point') void canReceiveArgumentsWhenEngineSpawn(List<String> args) { notifyNativeWhenEngineSpawn(args.length == 2 && args[0] == 'arg1' && args[1] == 'arg2'); } @pragma('vm:entry-point') void onBeginFrameWithNotifyNativeMain() { PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) { nativeOnBeginFrame(beginTime.inMicroseconds); }; notifyNative(); } @pragma('vm:entry-point') void frameCallback(Object? image, int durationMilliseconds, String decodeError) { if (image == null) { throw Exception('Expeccted image in frame callback to be non-null'); } } Picture CreateRedBox(Size size) { Paint paint = Paint() ..color = Color.fromARGB(255, 255, 0, 0) ..style = PaintingStyle.fill; PictureRecorder baseRecorder = PictureRecorder(); Canvas canvas = Canvas(baseRecorder); canvas.drawRect(Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint); return baseRecorder.endRecording(); } @pragma('vm:entry-point') void scene_with_red_box() { PlatformDispatcher.instance.onBeginFrame = (Duration duration) { SceneBuilder builder = SceneBuilder(); builder.pushOffset(0.0, 0.0); builder.addPicture(Offset(0.0, 0.0), CreateRedBox(Size(2.0, 2.0))); builder.pop(); PlatformDispatcher.instance.views.first.render(builder.build()); }; PlatformDispatcher.instance.scheduleFrame(); } @pragma('vm:external-name', 'NativeOnBeforeToImageSync') external void onBeforeToImageSync(); @pragma('vm:entry-point') Future<void> toImageSync() async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0xFFAAAAAA)); final Picture picture = recorder.endRecording(); onBeforeToImageSync(); final Image image = picture.toImageSync(20, 25); expect(image.width, 20); expect(image.height, 25); final ByteData dataBefore = (await image.toByteData())!; expect(dataBefore.lengthInBytes, 20 * 25 * 4); for (final int byte in dataBefore.buffer.asUint32List()) { expect(byte, 0xFFAAAAAA); } // Cause the rasterizer to get torn down. notifyNative(); final ByteData dataAfter = (await image.toByteData())!; expect(dataAfter.lengthInBytes, 20 * 25 * 4); for (final int byte in dataAfter.buffer.asUint32List()) { expect(byte, 0xFFAAAAAA); } // Verify that the image can be drawn successfully. final PictureRecorder recorder2 = PictureRecorder(); final Canvas canvas2 = Canvas(recorder2); canvas2.drawImage(image, Offset.zero, Paint()); final Picture picture2 = recorder2.endRecording(); picture.dispose(); picture2.dispose(); notifyNative(); } @pragma('vm:entry-point') Future<void> included() async { } Future<void> excluded() async { } class IsolateParam { const IsolateParam(this.sendPort, this.rawHandle); final SendPort sendPort; final int rawHandle; } @pragma('vm:entry-point') Future<void> runCallback(IsolateParam param) async { try { final Future<dynamic> Function() func = PluginUtilities.getCallbackFromHandle( CallbackHandle.fromRawHandle(param.rawHandle) )! as Future<dynamic> Function(); await func.call(); param.sendPort.send(true); } on NoSuchMethodError { param.sendPort.send(false); } } @pragma('vm:entry-point') @pragma('vm:external-name', 'NotifyNativeBool') external void notifyNativeBool(bool value); @pragma('vm:external-name', 'NotifyDestroyed') external void notifyDestroyed(); @pragma('vm:entry-point') Future<void> testPluginUtilitiesCallbackHandle() async { ReceivePort port = ReceivePort(); await Isolate.spawn( runCallback, IsolateParam( port.sendPort, PluginUtilities.getCallbackHandle(included)!.toRawHandle() ), onError: port.sendPort ); final dynamic result1 = await port.first; if (result1 != true) { print('Expected $result1 to == true'); notifyNativeBool(false); return; } port.close(); if (const bool.fromEnvironment('dart.vm.product')) { port = ReceivePort(); await Isolate.spawn( runCallback, IsolateParam( port.sendPort, PluginUtilities.getCallbackHandle(excluded)!.toRawHandle() ), onError: port.sendPort ); final dynamic result2 = await port.first; if (result2 != false) { print('Expected $result2 to == false'); notifyNativeBool(false); return; } port.close(); } notifyNativeBool(true); } @pragma('vm:entry-point') Future<void> testThatAssetLoadingHappensOnWorkerThread() async { try { await ImmutableBuffer.fromAsset('DoesNotExist'); } catch (err) { /* Do nothing */ } notifyNative(); } @pragma('vm:external-name', 'NativeReportViewIdsCallback') external void nativeReportViewIdsCallback(bool hasImplicitView, List<int> viewIds); List<int> getCurrentViewIds() { final List<int> result = PlatformDispatcher.instance.views .map((FlutterView view) => view.viewId) .toList() ..sort(); assert(result.toSet().length == result.length, 'Unexpected duplicate view ID found: $result'); return result; } bool listEquals<T>(List<T> a, List<T> b) { if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i += 1) { if (a[i] != b[i]) { return false; } } return true; } // This entrypoint reports whether there's an implicit view and the list of view // IDs using nativeReportViewIdsCallback on initialization and every time the // list of view IDs changes. @pragma('vm:entry-point') void testReportViewIds() { List<int> viewIds = getCurrentViewIds(); nativeReportViewIdsCallback(PlatformDispatcher.instance.implicitView != null, viewIds); PlatformDispatcher.instance.onMetricsChanged = () { final List<int> newViewIds = getCurrentViewIds(); if (!listEquals(viewIds, newViewIds)) { viewIds = newViewIds; nativeReportViewIdsCallback(PlatformDispatcher.instance.implicitView != null, viewIds); } }; } // Returns a list of [view_id 1, view_width 1, view_id 2, view_width 2, ...] // for all views. List<int> getCurrentViewWidths() { final List<int> result = <int>[]; for (final FlutterView view in PlatformDispatcher.instance.views) { result.add(view.viewId); result.add(view.physicalSize.width.round()); } return result; } @pragma('vm:external-name', 'NativeReportViewWidthsCallback') external void nativeReportViewWidthsCallback(List<int> viewWidthPacket); // This entrypoint reports the list of views and their widths using // nativeReportViewWidthsCallback on initialization and every onMetricsChanged. @pragma('vm:entry-point') void testReportViewWidths() { nativeReportViewWidthsCallback(getCurrentViewWidths()); PlatformDispatcher.instance.onMetricsChanged = () { nativeReportViewWidthsCallback(getCurrentViewWidths()); }; } void renderDummyToView(FlutterView view) { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF)); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); view.render(scene); scene.dispose(); picture.dispose(); } @pragma('vm:entry-point') void onDrawFrameRenderAllViews() { PlatformDispatcher.instance.onDrawFrame = () { for (final FlutterView view in PlatformDispatcher.instance.views) { renderDummyToView(view); } }; notifyNative(); } @pragma('vm:entry-point') void renderViewsInFrameAndOutOfFrame() { renderDummyToView(PlatformDispatcher.instance.view(id: 1)!); PlatformDispatcher.instance.onDrawFrame = () { renderDummyToView(PlatformDispatcher.instance.view(id: 2)!); }; PlatformDispatcher.instance.scheduleFrame(); } @pragma('vm:external-name', 'CaptureRootLayer') external _captureRootLayer(SceneBuilder sceneBuilder); @pragma('vm:entry-point') void renderTwiceForOneView() { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF)); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); PlatformDispatcher.instance.onBeginFrame = (_) { // Tell engine the correct layer tree. _captureRootLayer(builder); }; PlatformDispatcher.instance.onDrawFrame = () { final Scene scene = builder.build(); PlatformDispatcher.instance.implicitView!.render(scene); scene.dispose(); picture.dispose(); // Render a second time. This duplicate render should be ignored. renderDummyToView(PlatformDispatcher.instance.implicitView!); }; PlatformDispatcher.instance.scheduleFrame(); } @pragma('vm:entry-point') void renderSingleViewAndCallAfterOnDrawFrame() { PlatformDispatcher.instance.onDrawFrame = () { final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF)); final Picture picture = recorder.endRecording(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); PlatformDispatcher.instance.implicitView!.render(scene); // Notify the engine after the render before the disposal. // The view should have been submitted for rasterization at this moment. notifyNative(); scene.dispose(); picture.dispose(); }; PlatformDispatcher.instance.scheduleFrame(); } @pragma('vm:entry-point') void renderWarmUpImplicitView() { bool beginFrameCalled = false; PlatformDispatcher.instance.scheduleWarmUpFrame( beginFrame: () { expect(beginFrameCalled, false); beginFrameCalled = true; }, drawFrame: () { expect(beginFrameCalled, true); renderDummyToView(PlatformDispatcher.instance.implicitView!); }, ); } @pragma('vm:entry-point') void renderWarmUpView1and2() { bool beginFrameCalled = false; PlatformDispatcher.instance.scheduleWarmUpFrame( beginFrame: () { expect(beginFrameCalled, false); beginFrameCalled = true; }, drawFrame: () { expect(beginFrameCalled, true); for (final int viewId in <int>[1, 2]) { renderDummyToView(PlatformDispatcher.instance.view(id: viewId)!); } } ); }
engine/shell/common/fixtures/shell_test.dart/0
{ "file_path": "engine/shell/common/fixtures/shell_test.dart", "repo_id": "engine", "token_count": 6603 }
295
// 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_SHELL_COMMON_RESOURCE_CACHE_LIMIT_CALCULATOR_H_ #define FLUTTER_SHELL_COMMON_RESOURCE_CACHE_LIMIT_CALCULATOR_H_ #include <cstdint> #include <unordered_map> #include "flutter/fml/macros.h" #include "flutter/fml/memory/weak_ptr.h" namespace flutter { class ResourceCacheLimitItem { public: // The expected GPU resource cache limit in bytes. This will be called on the // platform thread. virtual size_t GetResourceCacheLimit() = 0; protected: virtual ~ResourceCacheLimitItem() = default; }; class ResourceCacheLimitCalculator { public: explicit ResourceCacheLimitCalculator(size_t max_bytes_threshold) : max_bytes_threshold_(max_bytes_threshold) {} ~ResourceCacheLimitCalculator() = default; // This will be called on the platform thread. void AddResourceCacheLimitItem( const fml::WeakPtr<ResourceCacheLimitItem>& item) { items_.push_back(item); } // The maximum GPU resource cache limit in bytes calculated by // 'ResourceCacheLimitItem's. This will be called on the platform thread. size_t GetResourceCacheMaxBytes(); private: std::vector<fml::WeakPtr<ResourceCacheLimitItem>> items_; size_t max_bytes_threshold_; FML_DISALLOW_COPY_AND_ASSIGN(ResourceCacheLimitCalculator); }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_RESOURCE_CACHE_LIMIT_CALCULATOR_H_
engine/shell/common/resource_cache_limit_calculator.h/0
{ "file_path": "engine/shell/common/resource_cache_limit_calculator.h", "repo_id": "engine", "token_count": 502 }
296
// 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_SHELL_COMMON_SHELL_TEST_EXTERNAL_VIEW_EMBEDDER_H_ #define FLUTTER_SHELL_COMMON_SHELL_TEST_EXTERNAL_VIEW_EMBEDDER_H_ #include "flutter/flow/embedded_views.h" #include "flutter/fml/raster_thread_merger.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief The external view embedder used by |ShellTestPlatformViewGL| /// class ShellTestExternalViewEmbedder final : public ExternalViewEmbedder { public: using EndFrameCallBack = std::function<void(bool, fml::RefPtr<fml::RasterThreadMerger>)>; ShellTestExternalViewEmbedder(const EndFrameCallBack& end_frame_call_back, PostPrerollResult post_preroll_result, bool support_thread_merging); ~ShellTestExternalViewEmbedder() = default; // Updates the post preroll result so the |PostPrerollAction| after always // returns the new `post_preroll_result`. void UpdatePostPrerollResult(PostPrerollResult post_preroll_result); // Gets the number of times the SubmitFlutterView method has been called in // the external view embedder. int GetSubmittedFrameCount(); // Returns the size of last submitted frame surface. SkISize GetLastSubmittedFrameSize(); // Returns the mutators stack for the given platform view. MutatorsStack GetStack(int64_t); // Returns the list of visited platform views. std::vector<int64_t> GetVisitedPlatformViews(); private: // |ExternalViewEmbedder| void CancelFrame() override; // |ExternalViewEmbedder| void BeginFrame(GrDirectContext* context, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override; // |ExternalViewEmbedder| void PrepareFlutterView(int64_t flutter_view_id, SkISize frame_size, double device_pixel_ratio) override; // |ExternalViewEmbedder| void PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<EmbeddedViewParams> params) override; // |ExternalViewEmbedder| PostPrerollResult PostPrerollAction( const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override; // |ExternalViewEmbedder| DlCanvas* CompositeEmbeddedView(int64_t view_id) override; // |ExternalViewEmbedder| void PushVisitedPlatformView(int64_t view_id) override; // |ExternalViewEmbedder| void PushFilterToVisitedPlatformViews( const std::shared_ptr<const DlImageFilter>& filter, const SkRect& filter_rect) override; // |ExternalViewEmbedder| void SubmitFlutterView( GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> frame) override; // |ExternalViewEmbedder| void EndFrame(bool should_resubmit_frame, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override; // |ExternalViewEmbedder| DlCanvas* GetRootCanvas() override; // |ExternalViewEmbedder| bool SupportsDynamicThreadMerging() override; const EndFrameCallBack end_frame_call_back_; PostPrerollResult post_preroll_result_; bool support_thread_merging_; SkISize frame_size_; std::map<int64_t, std::unique_ptr<EmbedderViewSlice>> slices_; std::map<int64_t, MutatorsStack> mutators_stacks_; std::map<int64_t, EmbeddedViewParams> current_composition_params_; std::vector<int64_t> visited_platform_views_; std::atomic<int> submitted_frame_count_; std::atomic<SkISize> last_submitted_frame_size_; FML_DISALLOW_COPY_AND_ASSIGN(ShellTestExternalViewEmbedder); }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_SHELL_TEST_EXTERNAL_VIEW_EMBEDDER_H_
engine/shell/common/shell_test_external_view_embedder.h/0
{ "file_path": "engine/shell/common/shell_test_external_view_embedder.h", "repo_id": "engine", "token_count": 1430 }
297
// 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/shell/common/snapshot_controller_skia.h" #include "display_list/image/dl_image.h" #include "flutter/flow/surface.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/common/snapshot_controller.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" namespace flutter { namespace { sk_sp<SkImage> DrawSnapshot( const sk_sp<SkSurface>& surface, const std::function<void(SkCanvas*)>& draw_callback) { if (surface == nullptr || surface->getCanvas() == nullptr) { return nullptr; } draw_callback(surface->getCanvas()); auto dContext = GrAsDirectContext(surface->recordingContext()); if (dContext) { dContext->flushAndSubmit(); } sk_sp<SkImage> device_snapshot; { TRACE_EVENT0("flutter", "MakeDeviceSnapshot"); device_snapshot = surface->makeImageSnapshot(); } if (device_snapshot == nullptr) { return nullptr; } { TRACE_EVENT0("flutter", "DeviceHostTransfer"); if (auto raster_image = device_snapshot->makeRasterImage()) { return raster_image; } } return nullptr; } } // namespace sk_sp<DlImage> SnapshotControllerSkia::DoMakeRasterSnapshot( SkISize size, std::function<void(SkCanvas*)> draw_callback) { TRACE_EVENT0("flutter", __FUNCTION__); sk_sp<SkImage> result; SkImageInfo image_info = SkImageInfo::MakeN32Premul( size.width(), size.height(), SkColorSpace::MakeSRGB()); std::unique_ptr<Surface> pbuffer_surface; Surface* snapshot_surface = nullptr; auto& delegate = GetDelegate(); if (delegate.GetSurface() && delegate.GetSurface()->GetContext()) { snapshot_surface = delegate.GetSurface().get(); } else if (delegate.GetSnapshotSurfaceProducer()) { pbuffer_surface = delegate.GetSnapshotSurfaceProducer()->CreateSnapshotSurface(); if (pbuffer_surface && pbuffer_surface->GetContext()) { snapshot_surface = pbuffer_surface.get(); } } if (!snapshot_surface) { // Raster surface is fine if there is no on screen surface. This might // happen in case of software rendering. sk_sp<SkSurface> sk_surface = SkSurfaces::Raster(image_info); result = DrawSnapshot(sk_surface, draw_callback); } else { delegate.GetIsGpuDisabledSyncSwitch()->Execute( fml::SyncSwitch::Handlers() .SetIfTrue([&] { sk_sp<SkSurface> surface = SkSurfaces::Raster(image_info); result = DrawSnapshot(surface, draw_callback); }) .SetIfFalse([&] { FML_DCHECK(snapshot_surface); auto context_switch = snapshot_surface->MakeRenderContextCurrent(); if (!context_switch->GetResult()) { return; } GrRecordingContext* context = snapshot_surface->GetContext(); auto max_size = context->maxRenderTargetSize(); double scale_factor = std::min( 1.0, static_cast<double>(max_size) / static_cast<double>(std::max(image_info.width(), image_info.height()))); // Scale down the render target size to the max supported by the // GPU if necessary. Exceeding the max would otherwise cause a // null result. if (scale_factor < 1.0) { image_info = image_info.makeWH( static_cast<double>(image_info.width()) * scale_factor, static_cast<double>(image_info.height()) * scale_factor); } // When there is an on screen surface, we need a render target // SkSurface because we want to access texture backed images. sk_sp<SkSurface> sk_surface = SkSurfaces::RenderTarget(context, // context skgpu::Budgeted::kNo, // budgeted image_info // image info ); if (!sk_surface) { FML_LOG(ERROR) << "DoMakeRasterSnapshot can not create GPU render target"; return; } sk_surface->getCanvas()->scale(scale_factor, scale_factor); result = DrawSnapshot(sk_surface, draw_callback); })); } // It is up to the caller to create a DlImageGPU version of this image // if the result will interact with the UI thread. return DlImage::Make(result); } sk_sp<DlImage> SnapshotControllerSkia::MakeRasterSnapshot( sk_sp<DisplayList> display_list, SkISize size) { return DoMakeRasterSnapshot(size, [display_list](SkCanvas* canvas) { DlSkCanvasAdapter(canvas).DrawDisplayList(display_list); }); } sk_sp<SkImage> SnapshotControllerSkia::ConvertToRasterImage( sk_sp<SkImage> image) { // If the rasterizer does not have a surface with a GrContext, then it will // be unable to render a cross-context SkImage. The caller will need to // create the raster image on the IO thread. if (GetDelegate().GetSurface() == nullptr || GetDelegate().GetSurface()->GetContext() == nullptr) { return nullptr; } if (image == nullptr) { return nullptr; } SkISize image_size = image->dimensions(); auto result = DoMakeRasterSnapshot( image_size, [image = std::move(image)](SkCanvas* canvas) { canvas->drawImage(image, 0, 0); }); return result->skia_image(); } } // namespace flutter
engine/shell/common/snapshot_controller_skia.cc/0
{ "file_path": "engine/shell/common/snapshot_controller_skia.cc", "repo_id": "engine", "token_count": 2446 }
298
#define FML_USED_ON_EMBEDDER #include <initializer_list> #include "flutter/common/settings.h" #include "flutter/common/task_runners.h" #include "flutter/shell/common/switches.h" #include "gtest/gtest.h" #include "thread_host.h" #include "vsync_waiter.h" namespace flutter { namespace testing { class TestVsyncWaiter : public VsyncWaiter { public: explicit TestVsyncWaiter(const TaskRunners& task_runners) : VsyncWaiter(task_runners) {} int await_vsync_call_count_ = 0; protected: void AwaitVSync() override { await_vsync_call_count_++; } }; TEST(VsyncWaiterTest, NoUnneededAwaitVsync) { using flutter::ThreadHost; std::string prefix = "vsync_waiter_test"; fml::MessageLoop::EnsureInitializedForCurrentThread(); auto task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); const flutter::TaskRunners task_runners(prefix, task_runner, task_runner, task_runner, task_runner); TestVsyncWaiter vsync_waiter(task_runners); vsync_waiter.ScheduleSecondaryCallback(1, [] {}); EXPECT_EQ(vsync_waiter.await_vsync_call_count_, 1); vsync_waiter.ScheduleSecondaryCallback(2, [] {}); EXPECT_EQ(vsync_waiter.await_vsync_call_count_, 1); } } // namespace testing } // namespace flutter
engine/shell/common/vsync_waiter_unittests.cc/0
{ "file_path": "engine/shell/common/vsync_waiter_unittests.cc", "repo_id": "engine", "token_count": 488 }
299
// 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 <Foundation/Foundation.h> #include <QuartzCore/QuartzCore.h> #include "flutter/shell/gpu/gpu_surface_metal_impeller.h" #include "gtest/gtest.h" #include "impeller/entity/mtl/entity_shaders.h" #include "impeller/entity/mtl/framebuffer_blend_shaders.h" #include "impeller/entity/mtl/modern_shaders.h" #include "impeller/renderer/backend/metal/context_mtl.h" namespace flutter { namespace testing { class TestGPUSurfaceMetalDelegate : public GPUSurfaceMetalDelegate { public: TestGPUSurfaceMetalDelegate() : GPUSurfaceMetalDelegate(MTLRenderTargetType::kCAMetalLayer) { layer_ = [[CAMetalLayer alloc] init]; } ~TestGPUSurfaceMetalDelegate() = default; GPUCAMetalLayerHandle GetCAMetalLayer(const SkISize& frame_info) const override { layer_.drawableSize = CGSizeMake(frame_info.width(), frame_info.height()); return (__bridge GPUCAMetalLayerHandle)(layer_); } bool PresentDrawable(GrMTLHandle drawable) const override { return true; } GPUMTLTextureInfo GetMTLTexture(const SkISize& frame_info) const override { return {}; } bool PresentTexture(GPUMTLTextureInfo texture) const override { return true; } bool AllowsDrawingWhenGpuDisabled() const override { return true; } void SetDevice() { layer_.device = ::MTLCreateSystemDefaultDevice(); } private: CAMetalLayer* layer_ = nil; }; static std::shared_ptr<impeller::ContextMTL> CreateImpellerContext() { std::vector<std::shared_ptr<fml::Mapping>> shader_mappings = { std::make_shared<fml::NonOwnedMapping>(impeller_entity_shaders_data, impeller_entity_shaders_length), std::make_shared<fml::NonOwnedMapping>(impeller_modern_shaders_data, impeller_modern_shaders_length), std::make_shared<fml::NonOwnedMapping>(impeller_framebuffer_blend_shaders_data, impeller_framebuffer_blend_shaders_length), }; auto sync_switch = std::make_shared<fml::SyncSwitch>(false); return impeller::ContextMTL::Create(shader_mappings, sync_switch, "Impeller Library"); } TEST(GPUSurfaceMetalImpeller, InvalidImpellerContextCreatesCausesSurfaceToBeInvalid) { auto delegate = std::make_shared<TestGPUSurfaceMetalDelegate>(); auto surface = std::make_shared<GPUSurfaceMetalImpeller>(delegate.get(), nullptr); ASSERT_FALSE(surface->IsValid()); } TEST(GPUSurfaceMetalImpeller, CanCreateValidSurface) { auto delegate = std::make_shared<TestGPUSurfaceMetalDelegate>(); auto surface = std::make_shared<GPUSurfaceMetalImpeller>(delegate.get(), CreateImpellerContext()); ASSERT_TRUE(surface->IsValid()); } TEST(GPUSurfaceMetalImpeller, AcquireFrameFromCAMetalLayerNullChecksDrawable) { auto delegate = std::make_shared<TestGPUSurfaceMetalDelegate>(); std::shared_ptr<Surface> surface = std::make_shared<GPUSurfaceMetalImpeller>(delegate.get(), CreateImpellerContext()); ASSERT_TRUE(surface->IsValid()); auto frame = surface->AcquireFrame(SkISize::Make(100, 100)); ASSERT_EQ(frame, nullptr); } TEST(GPUSurfaceMetalImpeller, AcquireFrameFromCAMetalLayerDoesNotRetainThis) { auto delegate = std::make_shared<TestGPUSurfaceMetalDelegate>(); delegate->SetDevice(); std::unique_ptr<Surface> surface = std::make_unique<GPUSurfaceMetalImpeller>(delegate.get(), CreateImpellerContext()); ASSERT_TRUE(surface->IsValid()); auto frame = surface->AcquireFrame(SkISize::Make(100, 100)); ASSERT_TRUE(frame); // Simulate a rasterizer teardown, e.g. due to going to the background. surface.reset(); ASSERT_TRUE(frame->Submit()); } } // namespace testing } // namespace flutter
engine/shell/gpu/gpu_surface_metal_impeller_unittests.mm/0
{ "file_path": "engine/shell/gpu/gpu_surface_metal_impeller_unittests.mm", "repo_id": "engine", "token_count": 1396 }
300
# 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("//build/config/android/config.gni") import("//build/toolchain/clang.gni") import("//flutter/build/bin_to_obj.gni") import("//flutter/build/zip_bundle.gni") import("//flutter/common/config.gni") import("//flutter/impeller/tools/impeller.gni") import("//flutter/shell/config.gni") import("//flutter/shell/gpu/gpu.gni") import("//flutter/shell/version/version.gni") import("//flutter/vulkan/config.gni") shell_gpu_configuration("android_gpu_configuration") { enable_software = true enable_gl = true enable_vulkan = true enable_metal = false } source_set("image_generator") { sources = [ "android_image_generator.cc", "android_image_generator.h", ] deps = [ "//flutter/fml", "//flutter/lib/ui:ui", "//flutter/skia", ] libs = [ "android", "jnigraphics", ] } executable("flutter_shell_native_unittests") { visibility = [ "*" ] testonly = true sources = [ "android_context_gl_impeller_unittests.cc", "android_context_gl_unittests.cc", "android_shell_holder_unittests.cc", "apk_asset_provider_unittests.cc", "flutter_shell_native_unittests.cc", "image_lru_unittests.cc", "platform_view_android_unittests.cc", ] public_configs = [ "//flutter:config" ] deps = [ ":flutter_shell_native_src", "//flutter/fml", "//flutter/shell/platform/android/jni:jni_mock", "//flutter/third_party/googletest:gmock", "//flutter/third_party/googletest:gtest", ] } shared_library("flutter_shell_native") { inputs = [ "android_exports.lst" ] output_name = "flutter" deps = [ ":flutter_shell_native_src" ] ldflags = [ "-Wl,--version-script=" + rebase_path("android_exports.lst") ] } bin_to_assembly("icudtl_asm") { deps = [] input = "//flutter/third_party/icu/flutter/icudtl.dat" symbol = "_binary_icudtl_dat_start" size_symbol = "_binary_icudtl_dat_size" executable = false } source_set("flutter_shell_native_src") { visibility = [ ":*" ] sources = [ "android_context_gl_impeller.cc", "android_context_gl_impeller.h", "android_context_gl_skia.cc", "android_context_gl_skia.h", "android_context_vulkan_impeller.cc", "android_context_vulkan_impeller.h", "android_display.cc", "android_display.h", "android_egl_surface.cc", "android_egl_surface.h", "android_environment_gl.cc", "android_environment_gl.h", "android_shell_holder.cc", "android_shell_holder.h", "android_surface_gl_impeller.cc", "android_surface_gl_impeller.h", "android_surface_gl_skia.cc", "android_surface_gl_skia.h", "android_surface_software.cc", "android_surface_software.h", "android_surface_vulkan_impeller.cc", "android_surface_vulkan_impeller.h", "apk_asset_provider.cc", "apk_asset_provider.h", "flutter_main.cc", "flutter_main.h", "image_external_texture.cc", "image_external_texture.h", "image_external_texture_gl.cc", "image_external_texture_gl.h", "image_external_texture_vk.cc", "image_external_texture_vk.h", "image_lru.cc", "image_lru.h", "library_loader.cc", "platform_message_handler_android.cc", "platform_message_handler_android.h", "platform_message_response_android.cc", "platform_message_response_android.h", "platform_view_android.cc", "platform_view_android.h", "platform_view_android_jni_impl.cc", "platform_view_android_jni_impl.h", "surface_texture_external_texture.cc", "surface_texture_external_texture.h", "surface_texture_external_texture_gl.cc", "surface_texture_external_texture_gl.h", "vsync_waiter_android.cc", "vsync_waiter_android.h", ] sources += get_target_outputs(":icudtl_asm") public_deps = [ ":android_gpu_configuration", ":icudtl_asm", ":image_generator", "//flutter/assets", "//flutter/common", "//flutter/common/graphics", "//flutter/flow", "//flutter/fml", "//flutter/impeller", "//flutter/impeller/toolkit/android", "//flutter/impeller/toolkit/egl", "//flutter/impeller/toolkit/gles", "//flutter/lib/ui", "//flutter/runtime", "//flutter/runtime:libdart", "//flutter/shell/common", "//flutter/shell/platform/android/context", "//flutter/shell/platform/android/external_view_embedder", "//flutter/shell/platform/android/jni", "//flutter/shell/platform/android/platform_view_android_delegate", "//flutter/shell/platform/android/surface", "//flutter/shell/platform/android/surface:native_window", "//flutter/skia", "//flutter/third_party/txt", "//flutter/vulkan", ] public_configs = [ "//flutter:config" ] defines = [] libs = [ "android", "EGL", "GLESv2", ] } action("gen_android_build_config_java") { script = "//flutter/tools/gen_android_buildconfig.py" build_config_java = "$target_gen_dir/io/flutter/BuildConfig.java" outputs = [ build_config_java ] args = [ "--out", rebase_path(build_config_java), "--runtime-mode", flutter_runtime_mode, ] } embedding_artifact_id = "flutter_embedding_$flutter_runtime_mode" embedding_jar_filename = "$embedding_artifact_id.jar" embedding_jar_path = "$root_out_dir/$embedding_jar_filename" embedding_sources_jar_filename = "$embedding_artifact_id-sources.jar" embedding_source_jar_path = "$root_out_dir/$embedding_sources_jar_filename" android_java_sources = [ "io/flutter/Build.java", "io/flutter/FlutterInjector.java", "io/flutter/Log.java", "io/flutter/app/FlutterActivity.java", "io/flutter/app/FlutterActivityDelegate.java", "io/flutter/app/FlutterActivityEvents.java", "io/flutter/app/FlutterApplication.java", "io/flutter/app/FlutterFragmentActivity.java", "io/flutter/app/FlutterPlayStoreSplitApplication.java", "io/flutter/app/FlutterPluginRegistry.java", "io/flutter/embedding/android/AndroidTouchProcessor.java", "io/flutter/embedding/android/ExclusiveAppComponent.java", "io/flutter/embedding/android/FlutterActivity.java", "io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java", "io/flutter/embedding/android/FlutterActivityLaunchConfigs.java", "io/flutter/embedding/android/FlutterEngineConfigurator.java", "io/flutter/embedding/android/FlutterEngineProvider.java", "io/flutter/embedding/android/FlutterFragment.java", "io/flutter/embedding/android/FlutterFragmentActivity.java", "io/flutter/embedding/android/FlutterImageView.java", "io/flutter/embedding/android/FlutterPlayStoreSplitApplication.java", "io/flutter/embedding/android/FlutterSurfaceView.java", "io/flutter/embedding/android/FlutterTextureView.java", "io/flutter/embedding/android/FlutterView.java", "io/flutter/embedding/android/KeyChannelResponder.java", "io/flutter/embedding/android/KeyData.java", "io/flutter/embedding/android/KeyEmbedderResponder.java", "io/flutter/embedding/android/KeyboardManager.java", "io/flutter/embedding/android/KeyboardMap.java", "io/flutter/embedding/android/MotionEventTracker.java", "io/flutter/embedding/android/RenderMode.java", "io/flutter/embedding/android/TransparencyMode.java", "io/flutter/embedding/android/WindowInfoRepositoryCallbackAdapterWrapper.java", "io/flutter/embedding/engine/FlutterEngine.java", "io/flutter/embedding/engine/FlutterEngineCache.java", "io/flutter/embedding/engine/FlutterEngineConnectionRegistry.java", "io/flutter/embedding/engine/FlutterEngineGroup.java", "io/flutter/embedding/engine/FlutterEngineGroupCache.java", "io/flutter/embedding/engine/FlutterJNI.java", "io/flutter/embedding/engine/FlutterOverlaySurface.java", "io/flutter/embedding/engine/FlutterShellArgs.java", "io/flutter/embedding/engine/dart/DartExecutor.java", "io/flutter/embedding/engine/dart/DartMessenger.java", "io/flutter/embedding/engine/dart/PlatformMessageHandler.java", "io/flutter/embedding/engine/dart/PlatformTaskQueue.java", "io/flutter/embedding/engine/deferredcomponents/DeferredComponentManager.java", "io/flutter/embedding/engine/deferredcomponents/PlayStoreDeferredComponentManager.java", "io/flutter/embedding/engine/loader/ApplicationInfoLoader.java", "io/flutter/embedding/engine/loader/FlutterApplicationInfo.java", "io/flutter/embedding/engine/loader/FlutterLoader.java", "io/flutter/embedding/engine/loader/ResourceExtractor.java", "io/flutter/embedding/engine/mutatorsstack/FlutterMutatorView.java", "io/flutter/embedding/engine/mutatorsstack/FlutterMutatorsStack.java", "io/flutter/embedding/engine/plugins/FlutterPlugin.java", "io/flutter/embedding/engine/plugins/PluginRegistry.java", "io/flutter/embedding/engine/plugins/activity/ActivityAware.java", "io/flutter/embedding/engine/plugins/activity/ActivityControlSurface.java", "io/flutter/embedding/engine/plugins/activity/ActivityPluginBinding.java", "io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverAware.java", "io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverControlSurface.java", "io/flutter/embedding/engine/plugins/broadcastreceiver/BroadcastReceiverPluginBinding.java", "io/flutter/embedding/engine/plugins/contentprovider/ContentProviderAware.java", "io/flutter/embedding/engine/plugins/contentprovider/ContentProviderControlSurface.java", "io/flutter/embedding/engine/plugins/contentprovider/ContentProviderPluginBinding.java", "io/flutter/embedding/engine/plugins/lifecycle/HiddenLifecycleReference.java", "io/flutter/embedding/engine/plugins/service/ServiceAware.java", "io/flutter/embedding/engine/plugins/service/ServiceControlSurface.java", "io/flutter/embedding/engine/plugins/service/ServicePluginBinding.java", "io/flutter/embedding/engine/plugins/shim/ShimPluginRegistry.java", "io/flutter/embedding/engine/plugins/shim/ShimRegistrar.java", "io/flutter/embedding/engine/plugins/util/GeneratedPluginRegister.java", "io/flutter/embedding/engine/renderer/FlutterRenderer.java", "io/flutter/embedding/engine/renderer/FlutterUiDisplayListener.java", "io/flutter/embedding/engine/renderer/RenderSurface.java", "io/flutter/embedding/engine/renderer/SurfaceTextureSurfaceProducer.java", "io/flutter/embedding/engine/renderer/SurfaceTextureWrapper.java", "io/flutter/embedding/engine/systemchannels/AccessibilityChannel.java", "io/flutter/embedding/engine/systemchannels/DeferredComponentChannel.java", "io/flutter/embedding/engine/systemchannels/KeyEventChannel.java", "io/flutter/embedding/engine/systemchannels/KeyboardChannel.java", "io/flutter/embedding/engine/systemchannels/LifecycleChannel.java", "io/flutter/embedding/engine/systemchannels/LocalizationChannel.java", "io/flutter/embedding/engine/systemchannels/MouseCursorChannel.java", "io/flutter/embedding/engine/systemchannels/NavigationChannel.java", "io/flutter/embedding/engine/systemchannels/PlatformChannel.java", "io/flutter/embedding/engine/systemchannels/PlatformViewsChannel.java", "io/flutter/embedding/engine/systemchannels/ProcessTextChannel.java", "io/flutter/embedding/engine/systemchannels/RestorationChannel.java", "io/flutter/embedding/engine/systemchannels/SettingsChannel.java", "io/flutter/embedding/engine/systemchannels/SpellCheckChannel.java", "io/flutter/embedding/engine/systemchannels/SystemChannel.java", "io/flutter/embedding/engine/systemchannels/TextInputChannel.java", "io/flutter/plugin/common/ActivityLifecycleListener.java", "io/flutter/plugin/common/BasicMessageChannel.java", "io/flutter/plugin/common/BinaryCodec.java", "io/flutter/plugin/common/BinaryMessenger.java", "io/flutter/plugin/common/ErrorLogResult.java", "io/flutter/plugin/common/EventChannel.java", "io/flutter/plugin/common/FlutterException.java", "io/flutter/plugin/common/JSONMessageCodec.java", "io/flutter/plugin/common/JSONMethodCodec.java", "io/flutter/plugin/common/JSONUtil.java", "io/flutter/plugin/common/MessageCodec.java", "io/flutter/plugin/common/MethodCall.java", "io/flutter/plugin/common/MethodChannel.java", "io/flutter/plugin/common/MethodCodec.java", "io/flutter/plugin/common/PluginRegistry.java", "io/flutter/plugin/common/StandardMessageCodec.java", "io/flutter/plugin/common/StandardMethodCodec.java", "io/flutter/plugin/common/StringCodec.java", "io/flutter/plugin/editing/FlutterTextUtils.java", "io/flutter/plugin/editing/ImeSyncDeferringInsetsCallback.java", "io/flutter/plugin/editing/InputConnectionAdaptor.java", "io/flutter/plugin/editing/ListenableEditingState.java", "io/flutter/plugin/editing/SpellCheckPlugin.java", "io/flutter/plugin/editing/TextEditingDelta.java", "io/flutter/plugin/editing/TextInputPlugin.java", "io/flutter/plugin/localization/LocalizationPlugin.java", "io/flutter/plugin/mouse/MouseCursorPlugin.java", "io/flutter/plugin/platform/AccessibilityEventsDelegate.java", "io/flutter/plugin/platform/ImageReaderPlatformViewRenderTarget.java", "io/flutter/plugin/platform/PlatformOverlayView.java", "io/flutter/plugin/platform/PlatformPlugin.java", "io/flutter/plugin/platform/PlatformView.java", "io/flutter/plugin/platform/PlatformViewFactory.java", "io/flutter/plugin/platform/PlatformViewRegistry.java", "io/flutter/plugin/platform/PlatformViewRegistryImpl.java", "io/flutter/plugin/platform/PlatformViewRenderTarget.java", "io/flutter/plugin/platform/PlatformViewWrapper.java", "io/flutter/plugin/platform/PlatformViewsAccessibilityDelegate.java", "io/flutter/plugin/platform/PlatformViewsController.java", "io/flutter/plugin/platform/SingleViewFakeWindowViewGroup.java", "io/flutter/plugin/platform/SingleViewPresentation.java", "io/flutter/plugin/platform/SingleViewWindowManager.java", "io/flutter/plugin/platform/SurfaceProducerPlatformViewRenderTarget.java", "io/flutter/plugin/platform/SurfaceTexturePlatformViewRenderTarget.java", "io/flutter/plugin/platform/VirtualDisplayController.java", "io/flutter/plugin/platform/WindowManagerHandler.java", "io/flutter/plugin/text/ProcessTextPlugin.java", "io/flutter/util/HandlerCompat.java", "io/flutter/util/PathUtils.java", "io/flutter/util/Preconditions.java", "io/flutter/util/Predicate.java", "io/flutter/util/TraceSection.java", "io/flutter/util/ViewUtils.java", "io/flutter/view/AccessibilityBridge.java", "io/flutter/view/AccessibilityViewEmbedder.java", "io/flutter/view/FlutterCallbackInformation.java", "io/flutter/view/FlutterMain.java", "io/flutter/view/FlutterNativeView.java", "io/flutter/view/FlutterRunArguments.java", "io/flutter/view/FlutterView.java", "io/flutter/view/TextureRegistry.java", "io/flutter/view/VsyncWaiter.java", ] embedding_dependencies_jars = [ "//third_party/android_embedding_dependencies/lib/activity-1.0.0.jar", "//third_party/android_embedding_dependencies/lib/annotation-1.2.0.jar", "//third_party/android_embedding_dependencies/lib/annotation-experimental-1.1.0.jar", "//third_party/android_embedding_dependencies/lib/annotations-13.0.jar", "//third_party/android_embedding_dependencies/lib/collection-1.1.0.jar", "//third_party/android_embedding_dependencies/lib/core-1.6.0.jar", "//third_party/android_embedding_dependencies/lib/core-1.8.0.jar", "//third_party/android_embedding_dependencies/lib/core-common-2.1.0.jar", "//third_party/android_embedding_dependencies/lib/core-runtime-2.0.0.jar", "//third_party/android_embedding_dependencies/lib/customview-1.0.0.jar", "//third_party/android_embedding_dependencies/lib/fragment-1.1.0.jar", "//third_party/android_embedding_dependencies/lib/kotlin-stdlib-1.5.31.jar", "//third_party/android_embedding_dependencies/lib/kotlin-stdlib-common-1.5.31.jar", "//third_party/android_embedding_dependencies/lib/kotlin-stdlib-jdk7-1.5.30.jar", "//third_party/android_embedding_dependencies/lib/kotlin-stdlib-jdk8-1.5.30.jar", "//third_party/android_embedding_dependencies/lib/kotlinx-coroutines-android-1.5.2.jar", "//third_party/android_embedding_dependencies/lib/kotlinx-coroutines-core-jvm-1.5.2.jar", "//third_party/android_embedding_dependencies/lib/lifecycle-common-2.2.0.jar", "//third_party/android_embedding_dependencies/lib/lifecycle-common-java8-2.2.0.jar", "//third_party/android_embedding_dependencies/lib/lifecycle-livedata-2.0.0.jar", "//third_party/android_embedding_dependencies/lib/lifecycle-livedata-core-2.0.0.jar", "//third_party/android_embedding_dependencies/lib/lifecycle-runtime-2.2.0.jar", "//third_party/android_embedding_dependencies/lib/lifecycle-viewmodel-2.1.0.jar", "//third_party/android_embedding_dependencies/lib/loader-1.0.0.jar", "//third_party/android_embedding_dependencies/lib/savedstate-1.0.0.jar", "//third_party/android_embedding_dependencies/lib/tracing-1.0.0.jar", "//third_party/android_embedding_dependencies/lib/versionedparcelable-1.1.1.jar", "//third_party/android_embedding_dependencies/lib/viewpager-1.0.0.jar", "//third_party/android_embedding_dependencies/lib/window-1.0.0-beta04.jar", "//third_party/android_embedding_dependencies/lib/window-java-1.0.0-beta04.jar", ] action("check_imports") { script = "//flutter/tools/android_illegal_imports.py" sources = android_java_sources stamp_file = "$root_out_dir/check_android_imports" # File does not actually get created, but GN expects us to have an output here. outputs = [ stamp_file ] args = [ "--stamp", rebase_path(stamp_file), "--files", ] + rebase_path(android_java_sources) } action("flutter_shell_java") { script = "//build/android/gyp/javac.py" depfile = "$target_gen_dir/$target_name.d" jar_path = embedding_jar_path source_jar_path = embedding_source_jar_path sources = android_java_sources sources += get_target_outputs(":gen_android_build_config_java") outputs = [ depfile, jar_path, jar_path + ".md5.stamp", source_jar_path, source_jar_path + ".md5.stamp", ] lambda_jar = "$android_sdk_build_tools/core-lambda-stubs.jar" inputs = [ android_sdk_jar, lambda_jar, ] + embedding_dependencies_jars _rebased_current_path = rebase_path(".") _rebased_jar_path = rebase_path(jar_path, root_build_dir) _rebased_source_jar_path = rebase_path(source_jar_path, root_build_dir) _rebased_depfile = rebase_path(depfile, root_build_dir) _rebased_android_sdk_jar = rebase_path(android_sdk_jar, root_build_dir) _rebased_lambda_jar = rebase_path(lambda_jar, root_build_dir) _rebased_classpath = [ _rebased_android_sdk_jar, _rebased_lambda_jar, ] + rebase_path(embedding_dependencies_jars, root_build_dir) if (host_os == "mac") { _javacbin = rebase_path("//third_party/java/openjdk/Contents/Home/bin/javac") _jarbin = rebase_path("//third_party/java/openjdk/Contents/Home/bin/jar") } else if (host_os == "win") { _javacbin = rebase_path("//third_party/java/openjdk/bin/javac.exe") _jarbin = rebase_path("//third_party/java/openjdk/bin/jar.exe") } else { _javacbin = rebase_path("//third_party/java/openjdk/bin/javac") _jarbin = rebase_path("//third_party/java/openjdk/bin/jar") } args = [ "--depfile=$_rebased_depfile", "--jar-path=$_rebased_jar_path", "--jar-source-path=$_rebased_source_jar_path", "--jar-source-base-dir=$_rebased_current_path", "--classpath=$_rebased_classpath", "--bootclasspath=$_rebased_android_sdk_jar", "--java-version=1.8", # Java 8 is required for backward compatibility. "--jar-bin=$_jarbin", "--javac-bin=$_javacbin", ] args += rebase_path(sources, root_build_dir) deps = [ ":check_imports", ":gen_android_build_config_java", ] } action("android_jar") { script = "//build/android/gyp/create_flutter_jar.py" if (stripped_symbols) { engine_library = "lib.stripped/libflutter.so" } else { engine_library = "libflutter.so" } inputs = [ "$root_build_dir/$embedding_jar_filename", "$root_build_dir/$engine_library", ] engine_artifact_id = string_replace(android_app_abi, "-", "_") + "_" + flutter_runtime_mode engine_jar_filename = "$engine_artifact_id.jar" outputs = [ "$root_build_dir/flutter.jar", "$root_build_dir/$engine_jar_filename", ] args = [ "--output", rebase_path("flutter.jar", root_build_dir, root_build_dir), "--output_native_jar", rebase_path(engine_jar_filename, root_build_dir, root_build_dir), "--dist_jar", rebase_path(embedding_jar_filename, root_build_dir, root_build_dir), "--native_lib", rebase_path("$engine_library", root_build_dir, root_build_dir), "--android_abi", "$android_app_abi", ] deps = [ ":flutter_shell_java", ":flutter_shell_native", ":pom_embedding", ":pom_libflutter", ] if (impeller_enable_vulkan_validation_layers) { assert(impeller_enable_vulkan) # We use a different toolchain here so that vulkan validation layers are # built against API level 26, which they require, rather than the default. # This is safe because the Engine can do a version check before loading the # .so for the validation layers. apilevel26_toolchain = "//build/toolchain/android:clang_arm64_apilevel26" validation_layer_target = "//third_party/vulkan_validation_layers($apilevel26_toolchain)" validation_layer_out_dir = get_label_info(validation_layer_target, "root_out_dir") deps += [ validation_layer_target ] args += [ "--native_lib", rebase_path("$validation_layer_out_dir/libVkLayer_khronos_validation.so"), ] if (current_cpu != "arm64") { # This may not be necessarily required anymore. It was kept to maintain # old behavior. assert(false, "Validation layers not supported for arch.") } } if (flutter_runtime_mode == "profile") { deps += [ "//flutter/shell/vmservice:vmservice_snapshot" ] args += [ "--native_lib", rebase_path( "$root_gen_dir/flutter/shell/vmservice/android/libs/$android_app_abi/libvmservice_snapshot.so", root_build_dir, root_build_dir), ] } } action("pom_libflutter") { script = "//flutter/tools/androidx/generate_pom_file.py" inputs = [ "//flutter/tools/androidx/files.json" ] artifact_id = string_replace(android_app_abi, "-", "_") + "_" + flutter_runtime_mode outputs = [ "$root_build_dir/$artifact_id.pom", "$root_build_dir/$artifact_id.maven-metadata.xml", ] args = [ "--destination", rebase_path(root_build_dir), "--engine-version", engine_version, "--engine-artifact-id", artifact_id, ] } action("pom_embedding") { script = "//flutter/tools/androidx/generate_pom_file.py" inputs = [ "//flutter/tools/androidx/files.json" ] artifact_id = "flutter_embedding_$flutter_runtime_mode" outputs = [ "$root_build_dir/$artifact_id.pom", "$root_build_dir/$artifact_id.maven-metadata.xml", ] args = [ "--destination", rebase_path(root_build_dir), "--engine-version", engine_version, "--engine-artifact-id", artifact_id, "--include-embedding-dependencies", "true", ] } # TODO(jsimmons): remove this placeholder when it is no longer used by the LUCI recipes group("robolectric_tests") { deps = [ ":android_jar" ] } zip_bundle("android_symbols") { output = "$android_zip_archive_dir/symbols.zip" files = [ { source = "$root_build_dir/libflutter.so" destination = "libflutter.so" }, ] deps = [ ":flutter_shell_native" ] } zip_bundle("flutter_jar_zip") { output = "$android_zip_archive_dir/artifacts.zip" files = [ { source = "$root_build_dir/flutter.jar" destination = "flutter.jar" }, ] deps = [ ":android_jar" ] } action("gen_android_javadoc") { script = "//flutter/tools/javadoc/gen_javadoc.py" sources = android_java_sources + embedding_dependencies_jars outputs = [ "$target_gen_dir/javadocs" ] args = [ "--out-dir", rebase_path(outputs[0]), "--android-source-root", rebase_path("."), "--build-config-path", rebase_path(target_gen_dir), "--third-party", rebase_path("//third_party"), "--quiet", ] deps = [ ":gen_android_build_config_java" ] } zip_bundle("android_javadoc") { output = "android-javadoc.zip" javadoc_dir = get_target_outputs(":gen_android_javadoc") files = [ { source = javadoc_dir[0] destination = "/" }, ] deps = [ ":gen_android_javadoc" ] } generated_file("android_entitlement_config") { outputs = [ "$target_gen_dir/android_entitlements.txt" ] contents = [ "gen_snapshot" ] deps = [] } if (target_cpu != "x86") { zip_bundle("gen_snapshot") { gen_snapshot_bin = "gen_snapshot" gen_snapshot_out_dir = get_label_info("$dart_src/runtime/bin:gen_snapshot($host_toolchain)", "root_out_dir") gen_snapshot_path = rebase_path("$gen_snapshot_out_dir/$gen_snapshot_bin") if (host_os == "linux") { output = "$android_zip_archive_dir/linux-x64.zip" } else if (host_os == "mac") { output = "$android_zip_archive_dir/darwin-x64.zip" } else if (host_os == "win") { output = "$android_zip_archive_dir/windows-x64.zip" gen_snapshot_bin = "gen_snapshot.exe" gen_snapshot_path = rebase_path("$root_out_dir/$gen_snapshot_bin") } files = [ { source = gen_snapshot_path destination = gen_snapshot_bin }, ] deps = [ "$dart_src/runtime/bin:gen_snapshot($host_toolchain)" ] if (host_os == "mac") { deps += [ ":android_entitlement_config" ] files += [ { source = "$target_gen_dir/android_entitlements.txt" destination = "entitlements.txt" }, ] } } # TODO(godofredoc): Remove gen_snapshot and rename new_gen_snapshot when v2 migration is complete. # BUG: https://github.com/flutter/flutter/issues/105351 zip_bundle("new_gen_snapshot") { gen_snapshot_bin = "gen_snapshot" gen_snapshot_out_dir = get_label_info("$dart_src/runtime/bin:gen_snapshot($host_toolchain)", "root_out_dir") gen_snapshot_path = rebase_path("$gen_snapshot_out_dir/$gen_snapshot_bin") if (host_os == "linux") { output = "$android_zip_archive_dir/$full_platform_name-$flutter_runtime_mode/linux-x64.zip" } else if (host_os == "mac") { output = "$android_zip_archive_dir/$full_platform_name-$flutter_runtime_mode/darwin-x64.zip" } else if (host_os == "win") { output = "$android_zip_archive_dir/$full_platform_name-$flutter_runtime_mode/windows-x64.zip" gen_snapshot_bin = "gen_snapshot.exe" gen_snapshot_path = rebase_path("$root_out_dir/$gen_snapshot_bin") } files = [ { source = gen_snapshot_path destination = gen_snapshot_bin }, ] deps = [ "$dart_src/runtime/bin:gen_snapshot($host_toolchain)" ] if (host_os == "mac") { deps += [ ":android_entitlement_config" ] files += [ { source = "$target_gen_dir/android_entitlements.txt" destination = "entitlements.txt" }, ] } } } if (host_os == "linux" && (target_cpu == "x64" || target_cpu == "arm64")) { zip_bundle("analyze_snapshot") { deps = [ "$dart_src/runtime/bin:analyze_snapshot($host_toolchain)" ] analyze_snapshot_bin = "analyze_snapshot" analyze_snapshot_out_dir = get_label_info( "$dart_src/runtime/bin:analyze_snapshot($host_toolchain)", "root_out_dir") analyze_snapshot_path = rebase_path("$analyze_snapshot_out_dir/$analyze_snapshot_bin") if (host_os == "linux") { output = "$android_zip_archive_dir/analyze-snapshot-linux-x64.zip" } else if (host_os == "mac") { output = "$android_zip_archive_dir/analyze-snapshot-darwin-x64.zip" } else if (host_os == "win") { output = "$android_zip_archive_dir/analyze-snapshot-windows-x64.zip" analyze_snapshot_bin = "analyze-snapshot.exe" analyze_snapshot_path = rebase_path("$root_out_dir/$analyze_snapshot_bin") } files = [ { source = analyze_snapshot_path destination = analyze_snapshot_bin }, ] } # TODO(godofredoc): Remove analyze_snapshot and rename new_analyze_snapshot when v2 migration is complete. # BUG: https://github.com/flutter/flutter/issues/105351 zip_bundle("new_analyze_snapshot") { deps = [ "$dart_src/runtime/bin:analyze_snapshot($host_toolchain)" ] analyze_snapshot_bin = "analyze_snapshot" analyze_snapshot_out_dir = get_label_info( "$dart_src/runtime/bin:analyze_snapshot($host_toolchain)", "root_out_dir") analyze_snapshot_path = rebase_path("$analyze_snapshot_out_dir/$analyze_snapshot_bin") if (host_os == "linux") { output = "$android_zip_archive_dir/$full_platform_name-$flutter_runtime_mode/analyze-snapshot-linux-x64.zip" } else if (host_os == "mac") { output = "$android_zip_archive_dir/$full_platform_name-$flutter_runtime_mode/analyze-snapshot-darwin-x64.zip" } else if (host_os == "win") { output = "$android_zip_archive_dir/$full_platform_name-$flutter_runtime_mode/analyze-snapshot-windows-x64.zip" analyze_snapshot_bin = "analyze-snapshot.exe" analyze_snapshot_path = rebase_path("$root_out_dir/$analyze_snapshot_bin") } files = [ { source = analyze_snapshot_path destination = analyze_snapshot_bin }, ] } } group("android") { deps = [ ":android_javadoc", ":android_symbols", ":flutter_jar_zip", ] if (target_cpu != "x86") { deps += [ ":gen_snapshot" ] } } # Renames embedding android artifacts and places them in the final # expected folder structure. action("embedding_jars") { script = "//flutter/build/android_artifacts.py" deps = [ ":flutter_shell_java", ":pom_embedding", ] sources = [ "$root_out_dir/flutter_embedding_$flutter_runtime_mode.jar", "$root_out_dir/flutter_embedding_$flutter_runtime_mode.pom", ] outputs = [] args = [] base_name = "$root_out_dir/zip_archives/download.flutter.io/io/flutter/" + "flutter_embedding_$flutter_runtime_mode/1.0.0-$engine_version/" + "flutter_embedding_$flutter_runtime_mode-1.0.0-${engine_version}" foreach(source, sources) { extension = get_path_info(source, "extension") name = get_path_info(source, "name") if (extension == "jar") { outputs += [ "${base_name}.jar", "${base_name}-sources.jar", ] args += [ "-i", "${name}.jar", rebase_path("${base_name}.jar"), "-i", "${name}-sources.jar", rebase_path("${base_name}-sources.jar"), ] } else { outputs += [ "${base_name}.${extension}" ] args += [ "-i", rebase_path(source), rebase_path("${base_name}.${extension}"), ] } } } # Renames android artifacts and places them in the final # expected folder structure. action("abi_jars") { script = "//flutter/build/android_artifacts.py" deps = [ ":android_jar", ":pom_libflutter", ] artifact_id = string_replace(android_app_abi, "-", "_") + "_" + flutter_runtime_mode sources = [ "$root_out_dir/${artifact_id}.jar", "$root_out_dir/${artifact_id}.pom", ] outputs = [] args = [] base_name = "$root_out_dir/zip_archives/download.flutter.io/io/flutter/" + "${artifact_id}/1.0.0-$engine_version/" + "${artifact_id}-1.0.0-${engine_version}" foreach(source, sources) { extension = get_path_info(source, "extension") name = get_path_info(source, "name") outputs += [ "${base_name}.${extension}" ] args += [ "-i", rebase_path(source), rebase_path("${base_name}.${extension}"), ] } }
engine/shell/platform/android/BUILD.gn/0
{ "file_path": "engine/shell/platform/android/BUILD.gn", "repo_id": "engine", "token_count": 12871 }
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/shell/platform/android/apk_asset_provider.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { class MockAPKAssetProviderImpl : public APKAssetProviderInternal { public: MOCK_METHOD(std::unique_ptr<fml::Mapping>, GetAsMapping, (const std::string& asset_name), (const, override)); }; TEST(APKAssetProvider, CloneAndEquals) { auto first_provider = std::make_unique<APKAssetProvider>( std::make_shared<MockAPKAssetProviderImpl>()); auto second_provider = std::make_unique<APKAssetProvider>( std::make_shared<MockAPKAssetProviderImpl>()); auto third_provider = first_provider->Clone(); ASSERT_NE(first_provider->GetImpl(), second_provider->GetImpl()); ASSERT_EQ(first_provider->GetImpl(), third_provider->GetImpl()); ASSERT_FALSE(*first_provider == *second_provider); ASSERT_TRUE(*first_provider == *third_provider); } } // namespace testing } // namespace flutter
engine/shell/platform/android/apk_asset_provider_unittests.cc/0
{ "file_path": "engine/shell/platform/android/apk_asset_provider_unittests.cc", "repo_id": "engine", "token_count": 415 }
302
// 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/shell/platform/android/image_external_texture.h" #include <android/hardware_buffer_jni.h> #include <android/sensor.h> #include "flutter/fml/platform/android/jni_util.h" #include "flutter/impeller/toolkit/android/proc_table.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" namespace flutter { ImageExternalTexture::ImageExternalTexture( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& image_texture_entry, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : Texture(id), image_texture_entry_(image_texture_entry), jni_facade_(jni_facade) {} // Implementing flutter::Texture. void ImageExternalTexture::Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) { if (state_ == AttachmentState::kDetached) { return; } Attach(context); const bool should_process_frame = !freeze; if (should_process_frame) { ProcessFrame(context, bounds); } if (dl_image_) { context.canvas->DrawImageRect( dl_image_, // image SkRect::Make(dl_image_->bounds()), // source rect bounds, // destination rect sampling, // sampling context.paint, // paint flutter::DlCanvas::SrcRectConstraint::kStrict // enforce edges ); } else { FML_LOG(INFO) << "No DlImage available for ImageExternalTexture to paint."; } } // Implementing flutter::Texture. void ImageExternalTexture::MarkNewFrameAvailable() { // NOOP. } // Implementing flutter::Texture. void ImageExternalTexture::OnTextureUnregistered() {} // Implementing flutter::ContextListener. void ImageExternalTexture::OnGrContextCreated() { state_ = AttachmentState::kUninitialized; } // Implementing flutter::ContextListener. void ImageExternalTexture::OnGrContextDestroyed() { if (state_ == AttachmentState::kAttached) { dl_image_.reset(); image_lru_.Clear(); Detach(); } state_ = AttachmentState::kDetached; } JavaLocalRef ImageExternalTexture::AcquireLatestImage() { JNIEnv* env = fml::jni::AttachCurrentThread(); FML_CHECK(env != nullptr); // ImageTextureEntry.acquireLatestImage. JavaLocalRef image_java = jni_facade_->ImageProducerTextureEntryAcquireLatestImage( JavaLocalRef(image_texture_entry_)); return image_java; } void ImageExternalTexture::CloseImage(const fml::jni::JavaRef<jobject>& image) { if (image.obj() == nullptr) { return; } jni_facade_->ImageClose(JavaLocalRef(image)); } void ImageExternalTexture::CloseHardwareBuffer( const fml::jni::JavaRef<jobject>& hardware_buffer) { if (hardware_buffer.obj() == nullptr) { return; } jni_facade_->HardwareBufferClose(JavaLocalRef(hardware_buffer)); } JavaLocalRef ImageExternalTexture::HardwareBufferFor( const fml::jni::JavaRef<jobject>& image) { if (image.obj() == nullptr) { return JavaLocalRef(); } // Image.getHardwareBuffer. return jni_facade_->ImageGetHardwareBuffer(JavaLocalRef(image)); } AHardwareBuffer* ImageExternalTexture::AHardwareBufferFor( const fml::jni::JavaRef<jobject>& hardware_buffer) { JNIEnv* env = fml::jni::AttachCurrentThread(); FML_CHECK(env != nullptr); const auto& proc = impeller::android::GetProcTable().AHardwareBuffer_fromHardwareBuffer; return proc ? proc(env, hardware_buffer.obj()) : nullptr; } } // namespace flutter
engine/shell/platform/android/image_external_texture.cc/0
{ "file_path": "engine/shell/platform/android/image_external_texture.cc", "repo_id": "engine", "token_count": 1495 }
303
// 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. package io.flutter.app; import android.app.Activity; import android.app.Application; import androidx.annotation.CallSuper; import io.flutter.FlutterInjector; /** * Flutter implementation of {@link android.app.Application}, managing application-level global * initializations. * * <p>Using this {@link android.app.Application} is not required when using APIs in the package * {@code io.flutter.embedding.android} since they self-initialize on first use. */ public class FlutterApplication extends Application { @Override @CallSuper public void onCreate() { super.onCreate(); FlutterInjector.instance().flutterLoader().startInitialization(this); } private Activity mCurrentActivity = null; public Activity getCurrentActivity() { return mCurrentActivity; } public void setCurrentActivity(Activity mCurrentActivity) { this.mCurrentActivity = mCurrentActivity; } }
engine/shell/platform/android/io/flutter/app/FlutterApplication.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/app/FlutterApplication.java", "repo_id": "engine", "token_count": 298 }
304
// 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. package io.flutter.embedding.android; import android.content.Context; import android.graphics.SurfaceTexture; import android.util.AttributeSet; import android.view.Surface; import android.view.TextureView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.Log; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.renderer.RenderSurface; /** * Paints a Flutter UI on a {@link SurfaceTexture}. * * <p>To begin rendering a Flutter UI, the owner of this {@code FlutterTextureView} must invoke * {@link #attachToRenderer(FlutterRenderer)} with the desired {@link FlutterRenderer}. * * <p>To stop rendering a Flutter UI, the owner of this {@code FlutterTextureView} must invoke * {@link #detachFromRenderer()}. * * <p>A {@code FlutterTextureView} is intended for situations where a developer needs to render a * Flutter UI, but does not require any keyboard input, gesture input, accessibility integrations or * any other interactivity beyond rendering. If standard interactivity is desired, consider using a * {@link FlutterView} which provides all of these behaviors and utilizes a {@code * FlutterTextureView} internally. */ public class FlutterTextureView extends TextureView implements RenderSurface { private static final String TAG = "FlutterTextureView"; private boolean isSurfaceAvailableForRendering = false; private boolean isPaused = false; @Nullable private FlutterRenderer flutterRenderer; @Nullable private Surface renderSurface; private boolean shouldNotify() { return flutterRenderer != null && !isPaused; } // Connects the {@code SurfaceTexture} beneath this {@code TextureView} with Flutter's native // code. // Callbacks are received by this Object and then those messages are forwarded to our // FlutterRenderer, and then on to the JNI bridge over to native Flutter code. private final SurfaceTextureListener surfaceTextureListener = new SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable( SurfaceTexture surfaceTexture, int width, int height) { Log.v(TAG, "SurfaceTextureListener.onSurfaceTextureAvailable()"); isSurfaceAvailableForRendering = true; // If we're already attached to a FlutterRenderer then we're now attached to both a // renderer // and the Android window, so we can begin rendering now. if (shouldNotify()) { connectSurfaceToRenderer(); } } @Override public void onSurfaceTextureSizeChanged( @NonNull SurfaceTexture surface, int width, int height) { Log.v(TAG, "SurfaceTextureListener.onSurfaceTextureSizeChanged()"); if (shouldNotify()) { changeSurfaceSize(width, height); } } @Override public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) { // Invoked every time a new frame is available. We don't care. } @Override public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) { Log.v(TAG, "SurfaceTextureListener.onSurfaceTextureDestroyed()"); isSurfaceAvailableForRendering = false; // If we're attached to a FlutterRenderer then we need to notify it that our // SurfaceTexture // has been destroyed. if (shouldNotify()) { disconnectSurfaceFromRenderer(); } // Definitively release the surface to avoid leaked closeables, just in case if (renderSurface != null) { renderSurface.release(); renderSurface = null; } // Return true to indicate that no further painting will take place // within this SurfaceTexture. return true; } }; /** Constructs a {@code FlutterTextureView} programmatically, without any XML attributes. */ public FlutterTextureView(@NonNull Context context) { this(context, null); } /** Constructs a {@code FlutterTextureView} in an XML-inflation-compliant manner. */ public FlutterTextureView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Listen for when our underlying SurfaceTexture becomes available, changes size, or // gets destroyed, and take the appropriate actions. setSurfaceTextureListener(surfaceTextureListener); } @Nullable @Override public FlutterRenderer getAttachedRenderer() { return flutterRenderer; } /** * Invoked by the owner of this {@code FlutterTextureView} when it wants to begin rendering a * Flutter UI to this {@code FlutterTextureView}. * * <p>If an Android {@link SurfaceTexture} is available, this method will give that {@link * SurfaceTexture} to the given {@link FlutterRenderer} to begin rendering Flutter's UI to this * {@code FlutterTextureView}. * * <p>If no Android {@link SurfaceTexture} is available yet, this {@code FlutterTextureView} will * wait until a {@link SurfaceTexture} becomes available and then give that {@link SurfaceTexture} * to the given {@link FlutterRenderer} to begin rendering Flutter's UI to this {@code * FlutterTextureView}. */ public void attachToRenderer(@NonNull FlutterRenderer flutterRenderer) { Log.v(TAG, "Attaching to FlutterRenderer."); if (this.flutterRenderer != null) { Log.v( TAG, "Already connected to a FlutterRenderer. Detaching from old one and attaching to new" + " one."); this.flutterRenderer.stopRenderingToSurface(); } this.flutterRenderer = flutterRenderer; resume(); } /** * Invoked by the owner of this {@code FlutterTextureView} when it no longer wants to render a * Flutter UI to this {@code FlutterTextureView}. * * <p>This method will cease any on-going rendering from Flutter to this {@code * FlutterTextureView}. */ public void detachFromRenderer() { if (flutterRenderer != null) { // If we're attached to an Android window then we were rendering a Flutter UI. Now that // this FlutterTextureView is detached from the FlutterRenderer, we need to stop rendering. // TODO(mattcarroll): introduce a isRendererConnectedToSurface() to wrap "getWindowToken() != // null" if (getWindowToken() != null) { Log.v(TAG, "Disconnecting FlutterRenderer from Android surface."); disconnectSurfaceFromRenderer(); } pause(); flutterRenderer = null; } else { Log.w(TAG, "detachFromRenderer() invoked when no FlutterRenderer was attached."); } } /** * Invoked by the owner of this {@code FlutterTextureView} when it should pause rendering Flutter * UI to this {@code FlutterTextureView}. */ public void pause() { if (flutterRenderer == null) { Log.w(TAG, "pause() invoked when no FlutterRenderer was attached."); return; } isPaused = true; } public void resume() { if (flutterRenderer == null) { Log.w(TAG, "resume() invoked when no FlutterRenderer was attached."); return; } // If we're already attached to an Android window then we're now attached to both a renderer // and the Android window. We can begin rendering now. if (isSurfaceAvailableForRendering) { Log.v( TAG, "Surface is available for rendering. Connecting FlutterRenderer to Android surface."); connectSurfaceToRenderer(); } isPaused = false; } /** * Manually set the render surface for this view. * * <p>This should only be used for testing purposes. */ @VisibleForTesting public void setRenderSurface(Surface renderSurface) { this.renderSurface = renderSurface; } // FlutterRenderer and getSurfaceTexture() must both be non-null. private void connectSurfaceToRenderer() { if (flutterRenderer == null || getSurfaceTexture() == null) { throw new IllegalStateException( "connectSurfaceToRenderer() should only be called when flutterRenderer and" + " getSurfaceTexture() are non-null."); } // Definitively release the surface to avoid leaked closeables, just in case if (renderSurface != null) { renderSurface.release(); renderSurface = null; } renderSurface = new Surface(getSurfaceTexture()); flutterRenderer.startRenderingToSurface(renderSurface, isPaused); } // FlutterRenderer must be non-null. private void changeSurfaceSize(int width, int height) { if (flutterRenderer == null) { throw new IllegalStateException( "changeSurfaceSize() should only be called when flutterRenderer is non-null."); } Log.v( TAG, "Notifying FlutterRenderer that Android surface size has changed to " + width + " x " + height); flutterRenderer.surfaceChanged(width, height); } // FlutterRenderer must be non-null. private void disconnectSurfaceFromRenderer() { if (flutterRenderer == null) { throw new IllegalStateException( "disconnectSurfaceFromRenderer() should only be called when flutterRenderer is" + " non-null."); } flutterRenderer.stopRenderingToSurface(); if (renderSurface != null) { renderSurface.release(); renderSurface = null; } } }
engine/shell/platform/android/io/flutter/embedding/android/FlutterTextureView.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterTextureView.java", "repo_id": "engine", "token_count": 3389 }
305
// 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. package io.flutter.embedding.engine; import static io.flutter.Build.API_LEVELS; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.ColorSpace; import android.graphics.ImageDecoder; import android.graphics.SurfaceTexture; import android.os.Build; import android.os.Looper; import android.util.DisplayMetrics; import android.util.Size; import android.util.TypedValue; import android.view.Surface; import android.view.SurfaceHolder; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import androidx.annotation.VisibleForTesting; import io.flutter.Log; import io.flutter.embedding.engine.FlutterEngine.EngineLifecycleListener; import io.flutter.embedding.engine.dart.PlatformMessageHandler; import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager; import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorsStack; import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener; import io.flutter.embedding.engine.renderer.SurfaceTextureWrapper; import io.flutter.embedding.engine.systemchannels.SettingsChannel; import io.flutter.plugin.common.StandardMessageCodec; import io.flutter.plugin.localization.LocalizationPlugin; import io.flutter.plugin.platform.PlatformViewsController; import io.flutter.util.Preconditions; import io.flutter.view.AccessibilityBridge; import io.flutter.view.FlutterCallbackInformation; import io.flutter.view.TextureRegistry; import java.io.IOException; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Interface between Flutter embedding's Java code and Flutter engine's C/C++ code. * * <p>Flutter's engine is built with C/C++. The Android Flutter embedding is responsible for * coordinating Android OS events and app user interactions with the C/C++ engine. Such coordination * requires messaging from an Android app in Java code to the C/C++ engine code. This communication * requires a JNI (Java Native Interface) API to cross the Java/native boundary. * * <p>The entirety of Flutter's JNI API is codified in {@code FlutterJNI}. There are multiple * reasons that all such calls are centralized in one class. First, JNI calls are inherently static * and contain no Java implementation, therefore there is little reason to associate calls with * different classes. Second, every JNI call must be registered in C/C++ code and this registration * becomes more complicated with every additional Java class that contains JNI calls. Third, most * Android developers are not familiar with native development or JNI intricacies, therefore it is * in the interest of future maintenance to reduce the API surface that includes JNI declarations. * Thus, all Flutter JNI calls are centralized in {@code FlutterJNI}. * * <p>Despite the fact that individual JNI calls are inherently static, there is state that exists * within {@code FlutterJNI}. Most calls within {@code FlutterJNI} correspond to a specific * "platform view", of which there may be many. Therefore, each {@code FlutterJNI} instance holds * onto a "native platform view ID" after {@link #attachToNative()}, which is shared with the native * C/C++ engine code. That ID is passed to every platform-view-specific native method. ID management * is handled within {@code FlutterJNI} so that developers don't have to hold onto that ID. * * <p>To connect part of an Android app to Flutter's C/C++ engine, instantiate a {@code FlutterJNI} * and then attach it to the native side: * * <pre>{@code * // Instantiate FlutterJNI and attach to the native side. * FlutterJNI flutterJNI = new FlutterJNI(); * flutterJNI.attachToNative(); * * // Use FlutterJNI as desired. flutterJNI.dispatchPointerDataPacket(...); * * // Destroy the connection to the native side and cleanup. * flutterJNI.detachFromNativeAndReleaseResources(); * }</pre> * * <p>To receive callbacks for certain events that occur on the native side, register listeners: * * <ol> * <li>{@link #addEngineLifecycleListener(FlutterEngine.EngineLifecycleListener)} * <li>{@link #addIsDisplayingFlutterUiListener(FlutterUiDisplayListener)} * </ol> * * To facilitate platform messages between Java and Dart running in Flutter, register a handler: * * <p>{@link #setPlatformMessageHandler(PlatformMessageHandler)} * * <p>To invoke a native method that is not associated with a platform view, invoke it statically: * * <p>{@code bool enabled = FlutterJNI.getIsSoftwareRenderingEnabled(); } */ @Keep public class FlutterJNI { private static final String TAG = "FlutterJNI"; // This serializes the invocation of platform message responses and the // attachment and detachment of the shell holder. This ensures that we don't // detach FlutterJNI on the platform thread while a background thread invokes // a message response. Typically accessing the shell holder happens on the // platform thread and doesn't require locking. private ReentrantReadWriteLock shellHolderLock = new ReentrantReadWriteLock(); // Prefer using the FlutterJNI.Factory so it's easier to test. public FlutterJNI() { // We cache the main looper so that we can ensure calls are made on the main thread // without consistently paying the synchronization cost of getMainLooper(). mainLooper = Looper.getMainLooper(); } /** * A factory for creating {@code FlutterJNI} instances. Useful for FlutterJNI injections during * tests. */ public static class Factory { /** @return a {@link FlutterJNI} instance. */ public FlutterJNI provideFlutterJNI() { return new FlutterJNI(); } } // BEGIN Methods related to loading for FlutterLoader. /** * Loads the libflutter.so C++ library. * * <p>This must be called before any other native methods, and can be overridden by tests to avoid * loading native libraries. * * <p>This method should only be called once across all FlutterJNI instances. */ public void loadLibrary() { if (FlutterJNI.loadLibraryCalled) { Log.w(TAG, "FlutterJNI.loadLibrary called more than once"); } System.loadLibrary("flutter"); FlutterJNI.loadLibraryCalled = true; } private static boolean loadLibraryCalled = false; private static native void nativePrefetchDefaultFontManager(); /** * Prefetch the default font manager provided by txt::GetDefaultFontManager() which is a * process-wide singleton owned by Skia. Note that, the first call to txt::GetDefaultFontManager() * will take noticeable time, but later calls will return a reference to the preexisting font * manager. * * <p>This method should only be called once across all FlutterJNI instances. */ public void prefetchDefaultFontManager() { if (FlutterJNI.prefetchDefaultFontManagerCalled) { Log.w(TAG, "FlutterJNI.prefetchDefaultFontManager called more than once"); } FlutterJNI.nativePrefetchDefaultFontManager(); FlutterJNI.prefetchDefaultFontManagerCalled = true; } private static boolean prefetchDefaultFontManagerCalled = false; private static native void nativeInit( @NonNull Context context, @NonNull String[] args, @Nullable String bundlePath, @NonNull String appStoragePath, @NonNull String engineCachesPath, long initTimeMillis); /** * Perform one time initialization of the Dart VM and Flutter engine. * * <p>This method must be called only once. Calling more than once will cause an exception. * * @param context The application context. * @param args Arguments to the Dart VM/Flutter engine. * @param bundlePath For JIT runtimes, the path to the Dart kernel file for the application. * @param appStoragePath The path to the application data directory. * @param engineCachesPath The path to the application cache directory. * @param initTimeMillis The time, in milliseconds, taken for initialization. */ public void init( @NonNull Context context, @NonNull String[] args, @Nullable String bundlePath, @NonNull String appStoragePath, @NonNull String engineCachesPath, long initTimeMillis) { if (FlutterJNI.initCalled) { Log.w(TAG, "FlutterJNI.init called more than once"); } FlutterJNI.nativeInit( context, args, bundlePath, appStoragePath, engineCachesPath, initTimeMillis); FlutterJNI.initCalled = true; } private static boolean initCalled = false; // END methods related to FlutterLoader @Nullable private static AsyncWaitForVsyncDelegate asyncWaitForVsyncDelegate; /** * This value is updated by the VsyncWaiter when it is initialized. * * <p>On API 17+, it is updated whenever the default display refresh rate changes. * * <p>It is defaulted to 60. */ private static float refreshRateFPS = 60.0f; private static float displayWidth = -1.0f; private static float displayHeight = -1.0f; private static float displayDensity = -1.0f; // This is set from native code via JNI. @Nullable private static String vmServiceUri; private native boolean nativeGetIsSoftwareRenderingEnabled(); /** * Checks launch settings for whether software rendering is requested. * * <p>The value is the same per program. */ @UiThread public boolean getIsSoftwareRenderingEnabled() { return nativeGetIsSoftwareRenderingEnabled(); } /** * VM Service URI for the VM instance. * * <p>Its value is set by the native engine once {@link #init(Context, String[], String, String, * String, long)} is run. */ @Nullable public static String getVMServiceUri() { return vmServiceUri; } /** * VM Service URI for the VM instance. * * <p>Its value is set by the native engine once {@link #init(Context, String[], String, String, * String, long)} is run. * * @deprecated replaced by {@link #getVMServiceUri()}. */ @Deprecated @Nullable public static String getObservatoryUri() { return vmServiceUri; } /** * Notifies the engine about the refresh rate of the display when the API level is below 30. * * <p>For API 30 and above, this value is ignored. * * <p>Calling this method multiple times will update the refresh rate for the next vsync period. * However, callers should avoid calling {@link android.view.Display#getRefreshRate} frequently, * since it is expensive on some vendor implementations. * * @param refreshRateFPS The refresh rate in nanoseconds. */ public void setRefreshRateFPS(float refreshRateFPS) { // This is ok because it only ever tracks the refresh rate of the main // display. If we ever need to support the refresh rate of other displays // on Android we will need to refactor this. Static lookup makes things a // bit easier on the C++ side. FlutterJNI.refreshRateFPS = refreshRateFPS; updateRefreshRate(); } public void updateDisplayMetrics(int displayId, float width, float height, float density) { FlutterJNI.displayWidth = width; FlutterJNI.displayHeight = height; FlutterJNI.displayDensity = density; if (!FlutterJNI.loadLibraryCalled) { return; } nativeUpdateDisplayMetrics(nativeShellHolderId); } private native void nativeUpdateDisplayMetrics(long nativeShellHolderId); public void updateRefreshRate() { if (!FlutterJNI.loadLibraryCalled) { return; } nativeUpdateRefreshRate(refreshRateFPS); } private native void nativeUpdateRefreshRate(float refreshRateFPS); /** * The Android vsync waiter implementation in C++ needs to know when a vsync signal arrives, which * is obtained via Java API. The delegate set here is called on the C++ side when the engine is * ready to wait for the next vsync signal. The delegate is expected to add a postFrameCallback to * the {@link android.view.Choreographer}, and call {@link onVsync} to notify the engine. * * @param delegate The delegate that will call the engine back on the next vsync signal. */ public void setAsyncWaitForVsyncDelegate(@Nullable AsyncWaitForVsyncDelegate delegate) { asyncWaitForVsyncDelegate = delegate; } // TODO(mattcarroll): add javadocs // Called by native. private static void asyncWaitForVsync(final long cookie) { if (asyncWaitForVsyncDelegate != null) { asyncWaitForVsyncDelegate.asyncWaitForVsync(cookie); } else { throw new IllegalStateException( "An AsyncWaitForVsyncDelegate must be registered with FlutterJNI before asyncWaitForVsync() is invoked."); } } private native void nativeOnVsync(long frameDelayNanos, long refreshPeriodNanos, long cookie); /** * Notifies the engine that the Choreographer has signaled a vsync. * * @param frameDelayNanos The time in nanoseconds when the frame started being rendered, * subtracted from the {@link System#nanoTime} timebase. * @param refreshPeriodNanos The display refresh period in nanoseconds. * @param cookie An opaque handle to the C++ VSyncWaiter object. */ public void onVsync(long frameDelayNanos, long refreshPeriodNanos, long cookie) { nativeOnVsync(frameDelayNanos, refreshPeriodNanos, cookie); } @NonNull @Deprecated public static native FlutterCallbackInformation nativeLookupCallbackInformation(long handle); // ----- Start FlutterTextUtils Methods ---- private native boolean nativeFlutterTextUtilsIsEmoji(int codePoint); public boolean isCodePointEmoji(int codePoint) { return nativeFlutterTextUtilsIsEmoji(codePoint); } private native boolean nativeFlutterTextUtilsIsEmojiModifier(int codePoint); public boolean isCodePointEmojiModifier(int codePoint) { return nativeFlutterTextUtilsIsEmojiModifier(codePoint); } private native boolean nativeFlutterTextUtilsIsEmojiModifierBase(int codePoint); public boolean isCodePointEmojiModifierBase(int codePoint) { return nativeFlutterTextUtilsIsEmojiModifierBase(codePoint); } private native boolean nativeFlutterTextUtilsIsVariationSelector(int codePoint); public boolean isCodePointVariantSelector(int codePoint) { return nativeFlutterTextUtilsIsVariationSelector(codePoint); } private native boolean nativeFlutterTextUtilsIsRegionalIndicator(int codePoint); public boolean isCodePointRegionalIndicator(int codePoint) { return nativeFlutterTextUtilsIsRegionalIndicator(codePoint); } // ----- End Engine FlutterTextUtils Methods ---- // Below represents the stateful part of the FlutterJNI instances that aren't static per program. // Conceptually, it represents a native shell instance. @Nullable private Long nativeShellHolderId; @Nullable private AccessibilityDelegate accessibilityDelegate; @Nullable private PlatformMessageHandler platformMessageHandler; @Nullable private LocalizationPlugin localizationPlugin; @Nullable private PlatformViewsController platformViewsController; @Nullable private DeferredComponentManager deferredComponentManager; @NonNull private final Set<EngineLifecycleListener> engineLifecycleListeners = new CopyOnWriteArraySet<>(); @NonNull private final Set<FlutterUiDisplayListener> flutterUiDisplayListeners = new CopyOnWriteArraySet<>(); @NonNull private final Looper mainLooper; // cached to avoid synchronization on repeat access. // ------ Start Native Attach/Detach Support ---- /** * Returns true if this instance of {@code FlutterJNI} is connected to Flutter's native engine via * a Java Native Interface (JNI). */ public boolean isAttached() { return nativeShellHolderId != null; } /** * Attaches this {@code FlutterJNI} instance to Flutter's native engine, which allows for * communication between Android code and Flutter's platform agnostic engine. * * <p>This method must not be invoked if {@code FlutterJNI} is already attached to native. */ @UiThread public void attachToNative() { ensureRunningOnMainThread(); ensureNotAttachedToNative(); shellHolderLock.writeLock().lock(); try { nativeShellHolderId = performNativeAttach(this); } finally { shellHolderLock.writeLock().unlock(); } } @VisibleForTesting public long performNativeAttach(@NonNull FlutterJNI flutterJNI) { return nativeAttach(flutterJNI); } private native long nativeAttach(@NonNull FlutterJNI flutterJNI); /** * Spawns a new FlutterJNI instance from the current instance. * * <p>This creates another native shell from the current shell. This causes the 2 shells to re-use * some of the shared resources, reducing the total memory consumption versus creating a new * FlutterJNI by calling its standard constructor. * * <p>This can only be called once the current FlutterJNI instance is attached by calling {@link * #attachToNative()}. * * <p>Static methods that should be only called once such as {@link #init(Context, String[], * String, String, String, long)} shouldn't be called again on the spawned FlutterJNI instance. */ @UiThread @NonNull public FlutterJNI spawn( @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @Nullable String initialRoute, @Nullable List<String> entrypointArgs) { ensureRunningOnMainThread(); ensureAttachedToNative(); FlutterJNI spawnedJNI = nativeSpawn( nativeShellHolderId, entrypointFunctionName, pathToEntrypointFunction, initialRoute, entrypointArgs); Preconditions.checkState( spawnedJNI.nativeShellHolderId != null && spawnedJNI.nativeShellHolderId != 0, "Failed to spawn new JNI connected shell from existing shell."); return spawnedJNI; } private native FlutterJNI nativeSpawn( long nativeSpawningShellId, @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @Nullable String initialRoute, @Nullable List<String> entrypointArgs); /** * Detaches this {@code FlutterJNI} instance from Flutter's native engine, which precludes any * further communication between Android code and Flutter's platform agnostic engine. * * <p>This method must not be invoked if {@code FlutterJNI} is not already attached to native. * * <p>Invoking this method will result in the release of all native-side resources that were set * up during {@link #attachToNative()} or {@link #spawn(String, String, String, List)}, or * accumulated thereafter. * * <p>It is permissible to re-attach this instance to native after detaching it from native. */ @UiThread public void detachFromNativeAndReleaseResources() { ensureRunningOnMainThread(); ensureAttachedToNative(); shellHolderLock.writeLock().lock(); try { nativeDestroy(nativeShellHolderId); nativeShellHolderId = null; } finally { shellHolderLock.writeLock().unlock(); } } private native void nativeDestroy(long nativeShellHolderId); private void ensureNotAttachedToNative() { if (nativeShellHolderId != null) { throw new RuntimeException( "Cannot execute operation because FlutterJNI is attached to native."); } } private void ensureAttachedToNative() { if (nativeShellHolderId == null) { throw new RuntimeException( "Cannot execute operation because FlutterJNI is not attached to native."); } } // ------ End Native Attach/Detach Support ---- // ----- Start Render Surface Support ----- /** * Adds a {@link FlutterUiDisplayListener}, which receives a callback when Flutter's engine * notifies {@code FlutterJNI} that Flutter is painting pixels to the {@link Surface} that was * provided to Flutter. */ @UiThread public void addIsDisplayingFlutterUiListener(@NonNull FlutterUiDisplayListener listener) { ensureRunningOnMainThread(); flutterUiDisplayListeners.add(listener); } /** * Removes a {@link FlutterUiDisplayListener} that was added with {@link * #addIsDisplayingFlutterUiListener(FlutterUiDisplayListener)}. */ @UiThread public void removeIsDisplayingFlutterUiListener(@NonNull FlutterUiDisplayListener listener) { ensureRunningOnMainThread(); flutterUiDisplayListeners.remove(listener); } public static native void nativeImageHeaderCallback( long imageGeneratorPointer, int width, int height); /** * Called by native as a fallback method of image decoding. There are other ways to decode images * on lower API levels, they involve copying the native data _and_ do not support any additional * formats, whereas ImageDecoder supports HEIF images. Unlike most other methods called from * native, this method is expected to be called on a worker thread, since it only uses thread safe * methods and may take multiple frames to complete. */ @SuppressWarnings("unused") @VisibleForTesting @Nullable public static Bitmap decodeImage(@NonNull ByteBuffer buffer, long imageGeneratorAddress) { if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { ImageDecoder.Source source = ImageDecoder.createSource(buffer); try { return ImageDecoder.decodeBitmap( source, (decoder, info, src) -> { // i.e. ARGB_8888 decoder.setTargetColorSpace(ColorSpace.get(ColorSpace.Named.SRGB)); // TODO(bdero): Switch to ALLOCATOR_HARDWARE for devices that have // `AndroidBitmap_getHardwareBuffer` (API 30+) available once Skia supports // `SkImage::MakeFromAHardwareBuffer` via dynamic lookups: // https://skia-review.googlesource.com/c/skia/+/428960 decoder.setAllocator(ImageDecoder.ALLOCATOR_SOFTWARE); Size size = info.getSize(); nativeImageHeaderCallback(imageGeneratorAddress, size.getWidth(), size.getHeight()); }); } catch (IOException e) { Log.e(TAG, "Failed to decode image", e); return null; } } return null; } // Called by native to notify first Flutter frame rendered. @SuppressWarnings("unused") @VisibleForTesting @UiThread public void onFirstFrame() { ensureRunningOnMainThread(); for (FlutterUiDisplayListener listener : flutterUiDisplayListeners) { listener.onFlutterUiDisplayed(); } } // TODO(mattcarroll): get native to call this when rendering stops. @VisibleForTesting @UiThread void onRenderingStopped() { ensureRunningOnMainThread(); for (FlutterUiDisplayListener listener : flutterUiDisplayListeners) { listener.onFlutterUiNoLongerDisplayed(); } } /** * Call this method when a {@link Surface} has been created onto which you would like Flutter to * paint. * * <p>See {@link android.view.SurfaceHolder.Callback#surfaceCreated(SurfaceHolder)} for an example * of where this call might originate. */ @UiThread public void onSurfaceCreated(@NonNull Surface surface) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeSurfaceCreated(nativeShellHolderId, surface); } private native void nativeSurfaceCreated(long nativeShellHolderId, @NonNull Surface surface); /** * In hybrid composition, call this method when the {@link Surface} has changed. * * <p>In hybrid composition, the root surfaces changes from {@link * android.view.SurfaceHolder#getSurface()} to {@link android.media.ImageReader#getSurface()} when * a platform view is in the current frame. */ @UiThread public void onSurfaceWindowChanged(@NonNull Surface surface) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeSurfaceWindowChanged(nativeShellHolderId, surface); } private native void nativeSurfaceWindowChanged( long nativeShellHolderId, @NonNull Surface surface); /** * Call this method when the {@link Surface} changes that was previously registered with {@link * #onSurfaceCreated(Surface)}. * * <p>See {@link android.view.SurfaceHolder.Callback#surfaceChanged(SurfaceHolder, int, int, int)} * for an example of where this call might originate. */ @UiThread public void onSurfaceChanged(int width, int height) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeSurfaceChanged(nativeShellHolderId, width, height); } private native void nativeSurfaceChanged(long nativeShellHolderId, int width, int height); /** * Call this method when the {@link Surface} is destroyed that was previously registered with * {@link #onSurfaceCreated(Surface)}. * * <p>See {@link android.view.SurfaceHolder.Callback#surfaceDestroyed(SurfaceHolder)} for an * example of where this call might originate. */ @UiThread public void onSurfaceDestroyed() { ensureRunningOnMainThread(); ensureAttachedToNative(); onRenderingStopped(); nativeSurfaceDestroyed(nativeShellHolderId); } private native void nativeSurfaceDestroyed(long nativeShellHolderId); /** * Call this method to notify Flutter of the current device viewport metrics that are applies to * the Flutter UI that is being rendered. * * <p>This method should be invoked with initial values upon attaching to native. Then, it should * be invoked any time those metrics change while {@code FlutterJNI} is attached to native. */ @UiThread public void setViewportMetrics( float devicePixelRatio, int physicalWidth, int physicalHeight, int physicalPaddingTop, int physicalPaddingRight, int physicalPaddingBottom, int physicalPaddingLeft, int physicalViewInsetTop, int physicalViewInsetRight, int physicalViewInsetBottom, int physicalViewInsetLeft, int systemGestureInsetTop, int systemGestureInsetRight, int systemGestureInsetBottom, int systemGestureInsetLeft, int physicalTouchSlop, int[] displayFeaturesBounds, int[] displayFeaturesType, int[] displayFeaturesState) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeSetViewportMetrics( nativeShellHolderId, devicePixelRatio, physicalWidth, physicalHeight, physicalPaddingTop, physicalPaddingRight, physicalPaddingBottom, physicalPaddingLeft, physicalViewInsetTop, physicalViewInsetRight, physicalViewInsetBottom, physicalViewInsetLeft, systemGestureInsetTop, systemGestureInsetRight, systemGestureInsetBottom, systemGestureInsetLeft, physicalTouchSlop, displayFeaturesBounds, displayFeaturesType, displayFeaturesState); } private native void nativeSetViewportMetrics( long nativeShellHolderId, float devicePixelRatio, int physicalWidth, int physicalHeight, int physicalPaddingTop, int physicalPaddingRight, int physicalPaddingBottom, int physicalPaddingLeft, int physicalViewInsetTop, int physicalViewInsetRight, int physicalViewInsetBottom, int physicalViewInsetLeft, int systemGestureInsetTop, int systemGestureInsetRight, int systemGestureInsetBottom, int systemGestureInsetLeft, int physicalTouchSlop, int[] displayFeaturesBounds, int[] displayFeaturesType, int[] displayFeaturesState); // ----- End Render Surface Support ----- // ------ Start Touch Interaction Support --- /** Sends a packet of pointer data to Flutter's engine. */ @UiThread public void dispatchPointerDataPacket(@NonNull ByteBuffer buffer, int position) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeDispatchPointerDataPacket(nativeShellHolderId, buffer, position); } private native void nativeDispatchPointerDataPacket( long nativeShellHolderId, @NonNull ByteBuffer buffer, int position); // ------ End Touch Interaction Support --- @UiThread public void setPlatformViewsController(@NonNull PlatformViewsController platformViewsController) { ensureRunningOnMainThread(); this.platformViewsController = platformViewsController; } // ------ Start Accessibility Support ----- /** * Sets the {@link AccessibilityDelegate} for the attached Flutter context. * * <p>The {@link AccessibilityDelegate} is responsible for maintaining an Android-side cache of * Flutter's semantics tree and custom accessibility actions. This cache should be hooked up to * Android's accessibility system. * * <p>See {@link AccessibilityBridge} for an example of an {@link AccessibilityDelegate} and the * surrounding responsibilities. */ @UiThread public void setAccessibilityDelegate(@Nullable AccessibilityDelegate accessibilityDelegate) { ensureRunningOnMainThread(); this.accessibilityDelegate = accessibilityDelegate; } /** * Invoked by native to send semantics tree updates from Flutter to Android. * * <p>The {@code buffer} and {@code strings} form a communication protocol that is implemented * here: * https://github.com/flutter/engine/blob/main/shell/platform/android/platform_view_android.cc#L207 */ @SuppressWarnings("unused") @UiThread private void updateSemantics( @NonNull ByteBuffer buffer, @NonNull String[] strings, @NonNull ByteBuffer[] stringAttributeArgs) { ensureRunningOnMainThread(); if (accessibilityDelegate != null) { accessibilityDelegate.updateSemantics(buffer, strings, stringAttributeArgs); } // TODO(mattcarroll): log dropped messages when in debug mode // (https://github.com/flutter/flutter/issues/25391) } /** * Invoked by native to send new custom accessibility events from Flutter to Android. * * <p>The {@code buffer} and {@code strings} form a communication protocol that is implemented * here: * https://github.com/flutter/engine/blob/main/shell/platform/android/platform_view_android.cc#L207 * * <p>// TODO(cbracken): expand these docs to include more actionable information. */ @SuppressWarnings("unused") @UiThread private void updateCustomAccessibilityActions( @NonNull ByteBuffer buffer, @NonNull String[] strings) { ensureRunningOnMainThread(); if (accessibilityDelegate != null) { accessibilityDelegate.updateCustomAccessibilityActions(buffer, strings); } // TODO(mattcarroll): log dropped messages when in debug mode // (https://github.com/flutter/flutter/issues/25391) } /** Sends a semantics action to Flutter's engine, without any additional arguments. */ public void dispatchSemanticsAction(int nodeId, @NonNull AccessibilityBridge.Action action) { dispatchSemanticsAction(nodeId, action, null); } /** Sends a semantics action to Flutter's engine, with additional arguments. */ public void dispatchSemanticsAction( int nodeId, @NonNull AccessibilityBridge.Action action, @Nullable Object args) { ensureAttachedToNative(); ByteBuffer encodedArgs = null; int position = 0; if (args != null) { encodedArgs = StandardMessageCodec.INSTANCE.encodeMessage(args); position = encodedArgs.position(); } dispatchSemanticsAction(nodeId, action.value, encodedArgs, position); } /** * Sends a semantics action to Flutter's engine, given arguments that are already encoded for the * engine. * * <p>To send a semantics action that has not already been encoded, see {@link * #dispatchSemanticsAction(int, AccessibilityBridge.Action)} and {@link * #dispatchSemanticsAction(int, AccessibilityBridge.Action, Object)}. */ @UiThread public void dispatchSemanticsAction( int nodeId, int action, @Nullable ByteBuffer args, int argsPosition) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeDispatchSemanticsAction(nativeShellHolderId, nodeId, action, args, argsPosition); } private native void nativeDispatchSemanticsAction( long nativeShellHolderId, int nodeId, int action, @Nullable ByteBuffer args, int argsPosition); /** * Instructs Flutter to enable/disable its semantics tree, which is used by Flutter to support * accessibility and related behaviors. */ @UiThread public void setSemanticsEnabled(boolean enabled) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeSetSemanticsEnabled(nativeShellHolderId, enabled); } private native void nativeSetSemanticsEnabled(long nativeShellHolderId, boolean enabled); // TODO(mattcarroll): figure out what flags are supported and add javadoc about when/why/where to // use this. @UiThread public void setAccessibilityFeatures(int flags) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeSetAccessibilityFeatures(nativeShellHolderId, flags); } private native void nativeSetAccessibilityFeatures(long nativeShellHolderId, int flags); // ------ End Accessibility Support ---- // ------ Start Texture Registration Support ----- /** * Gives control of a {@link SurfaceTexture} to Flutter so that Flutter can display that texture * within Flutter's UI. */ @UiThread public void registerTexture(long textureId, @NonNull SurfaceTextureWrapper textureWrapper) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeRegisterTexture( nativeShellHolderId, textureId, new WeakReference<SurfaceTextureWrapper>(textureWrapper)); } private native void nativeRegisterTexture( long nativeShellHolderId, long textureId, @NonNull WeakReference<SurfaceTextureWrapper> textureWrapper); /** * Registers a ImageTexture with the given id. * * <p>REQUIRED: Callers should eventually unregisterTexture with the same id. */ @UiThread public void registerImageTexture( long textureId, @NonNull TextureRegistry.ImageConsumer imageTexture) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeRegisterImageTexture( nativeShellHolderId, textureId, new WeakReference<TextureRegistry.ImageConsumer>(imageTexture)); } private native void nativeRegisterImageTexture( long nativeShellHolderId, long textureId, @NonNull WeakReference<TextureRegistry.ImageConsumer> imageTexture); /** * Call this method to inform Flutter that a texture previously registered with {@link * #registerTexture(long, SurfaceTextureWrapper)} has a new frame available. * * <p>Invoking this method instructs Flutter to update its presentation of the given texture so * that the new frame is displayed. */ @UiThread public void markTextureFrameAvailable(long textureId) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeMarkTextureFrameAvailable(nativeShellHolderId, textureId); } private native void nativeMarkTextureFrameAvailable(long nativeShellHolderId, long textureId); /** Schedule the engine to draw a frame but does not invalidate the layout tree. */ @UiThread public void scheduleFrame() { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeScheduleFrame(nativeShellHolderId); } private native void nativeScheduleFrame(long nativeShellHolderId); /** * Unregisters a texture that was registered with {@link #registerTexture(long, * SurfaceTextureWrapper)}. */ @UiThread public void unregisterTexture(long textureId) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeUnregisterTexture(nativeShellHolderId, textureId); } private native void nativeUnregisterTexture(long nativeShellHolderId, long textureId); // ------ Start Texture Registration Support ----- // ------ Start Dart Execution Support ------- /** * Executes a Dart entrypoint. * * <p>This can only be done once per JNI attachment because a Dart isolate can only be entered * once. */ @UiThread public void runBundleAndSnapshotFromLibrary( @NonNull String bundlePath, @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @NonNull AssetManager assetManager, @Nullable List<String> entrypointArgs) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeRunBundleAndSnapshotFromLibrary( nativeShellHolderId, bundlePath, entrypointFunctionName, pathToEntrypointFunction, assetManager, entrypointArgs); } private native void nativeRunBundleAndSnapshotFromLibrary( long nativeShellHolderId, @NonNull String bundlePath, @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @NonNull AssetManager manager, @Nullable List<String> entrypointArgs); // ------ End Dart Execution Support ------- // --------- Start Platform Message Support ------ /** * Sets the handler for all platform messages that come from the attached platform view to Java. * * <p>Communication between a specific Flutter context (Dart) and the host platform (Java) is * accomplished by passing messages. Messages can be sent from Java to Dart with the corresponding * {@code FlutterJNI} methods: * * <ul> * <li>{@link #dispatchPlatformMessage(String, ByteBuffer, int, int)} * <li>{@link #dispatchEmptyPlatformMessage(String, int)} * </ul> * * <p>{@code FlutterJNI} is also the recipient of all platform messages sent from its attached * Flutter context. {@code FlutterJNI} does not know what to do with these messages, so a handler * is exposed to allow these messages to be processed in whatever manner is desired: * * <p>{@code setPlatformMessageHandler(PlatformMessageHandler)} * * <p>If a message is received but no {@link PlatformMessageHandler} is registered, that message * will be dropped (ignored). Therefore, when using {@code FlutterJNI} to integrate a Flutter * context in an app, a {@link PlatformMessageHandler} must be registered for 2-way Java/Dart * communication to operate correctly. Moreover, the handler must be implemented such that * fundamental platform messages are handled as expected. See {@link * io.flutter.view.FlutterNativeView} for an example implementation. */ @UiThread public void setPlatformMessageHandler(@Nullable PlatformMessageHandler platformMessageHandler) { ensureRunningOnMainThread(); this.platformMessageHandler = platformMessageHandler; } private native void nativeCleanupMessageData(long messageData); /** * Destroys the resources provided sent to `handlePlatformMessage`. * * <p>This can be called on any thread. * * @param messageData the argument sent to handlePlatformMessage. */ public void cleanupMessageData(long messageData) { // This doesn't rely on being attached like other methods. nativeCleanupMessageData(messageData); } // Called by native on any thread. // TODO(mattcarroll): determine if message is nonull or nullable @SuppressWarnings("unused") @VisibleForTesting public void handlePlatformMessage( @NonNull final String channel, ByteBuffer message, final int replyId, final long messageData) { if (platformMessageHandler != null) { platformMessageHandler.handleMessageFromDart(channel, message, replyId, messageData); } else { nativeCleanupMessageData(messageData); } // TODO(mattcarroll): log dropped messages when in debug mode // (https://github.com/flutter/flutter/issues/25391) } // Called by native to respond to a platform message that we sent. // TODO(mattcarroll): determine if reply is nonull or nullable @SuppressWarnings("unused") private void handlePlatformMessageResponse(int replyId, ByteBuffer reply) { if (platformMessageHandler != null) { platformMessageHandler.handlePlatformMessageResponse(replyId, reply); } // TODO(mattcarroll): log dropped messages when in debug mode // (https://github.com/flutter/flutter/issues/25391) } /** * Sends an empty reply (identified by {@code responseId}) from Android to Flutter over the given * {@code channel}. */ @UiThread public void dispatchEmptyPlatformMessage(@NonNull String channel, int responseId) { ensureRunningOnMainThread(); if (isAttached()) { nativeDispatchEmptyPlatformMessage(nativeShellHolderId, channel, responseId); } else { Log.w( TAG, "Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: " + channel + ". Response ID: " + responseId); } } // Send an empty platform message to Dart. private native void nativeDispatchEmptyPlatformMessage( long nativeShellHolderId, @NonNull String channel, int responseId); /** Sends a reply {@code message} from Android to Flutter over the given {@code channel}. */ @UiThread public void dispatchPlatformMessage( @NonNull String channel, @Nullable ByteBuffer message, int position, int responseId) { ensureRunningOnMainThread(); if (isAttached()) { nativeDispatchPlatformMessage(nativeShellHolderId, channel, message, position, responseId); } else { Log.w( TAG, "Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: " + channel + ". Response ID: " + responseId); } } // Send a data-carrying platform message to Dart. private native void nativeDispatchPlatformMessage( long nativeShellHolderId, @NonNull String channel, @Nullable ByteBuffer message, int position, int responseId); // TODO(mattcarroll): differentiate between channel responses and platform responses. public void invokePlatformMessageEmptyResponseCallback(int responseId) { // Called on any thread. shellHolderLock.readLock().lock(); try { if (isAttached()) { nativeInvokePlatformMessageEmptyResponseCallback(nativeShellHolderId, responseId); } else { Log.w( TAG, "Tried to send a platform message response, but FlutterJNI was detached from native C++. Could not send. Response ID: " + responseId); } } finally { shellHolderLock.readLock().unlock(); } } // Send an empty response to a platform message received from Dart. private native void nativeInvokePlatformMessageEmptyResponseCallback( long nativeShellHolderId, int responseId); // TODO(mattcarroll): differentiate between channel responses and platform responses. public void invokePlatformMessageResponseCallback( int responseId, @NonNull ByteBuffer message, int position) { // Called on any thread. if (!message.isDirect()) { throw new IllegalArgumentException("Expected a direct ByteBuffer."); } shellHolderLock.readLock().lock(); try { if (isAttached()) { nativeInvokePlatformMessageResponseCallback( nativeShellHolderId, responseId, message, position); } else { Log.w( TAG, "Tried to send a platform message response, but FlutterJNI was detached from native C++. Could not send. Response ID: " + responseId); } } finally { shellHolderLock.readLock().unlock(); } } // Send a data-carrying response to a platform message received from Dart. private native void nativeInvokePlatformMessageResponseCallback( long nativeShellHolderId, int responseId, @Nullable ByteBuffer message, int position); // ------- End Platform Message Support ---- // ----- Start Engine Lifecycle Support ---- /** * Adds the given {@code engineLifecycleListener} to be notified of Flutter engine lifecycle * events, e.g., {@link EngineLifecycleListener#onPreEngineRestart()}. */ @UiThread public void addEngineLifecycleListener(@NonNull EngineLifecycleListener engineLifecycleListener) { ensureRunningOnMainThread(); engineLifecycleListeners.add(engineLifecycleListener); } /** * Removes the given {@code engineLifecycleListener}, which was previously added using {@link * #addIsDisplayingFlutterUiListener(FlutterUiDisplayListener)}. */ @UiThread public void removeEngineLifecycleListener( @NonNull EngineLifecycleListener engineLifecycleListener) { ensureRunningOnMainThread(); engineLifecycleListeners.remove(engineLifecycleListener); } // Called by native. @SuppressWarnings("unused") private void onPreEngineRestart() { for (EngineLifecycleListener listener : engineLifecycleListeners) { listener.onPreEngineRestart(); } } @SuppressWarnings("unused") @UiThread public void onDisplayOverlaySurface(int id, int x, int y, int width, int height) { ensureRunningOnMainThread(); if (platformViewsController == null) { throw new RuntimeException( "platformViewsController must be set before attempting to position an overlay surface"); } platformViewsController.onDisplayOverlaySurface(id, x, y, width, height); } @SuppressWarnings("unused") @UiThread public void onBeginFrame() { ensureRunningOnMainThread(); if (platformViewsController == null) { throw new RuntimeException( "platformViewsController must be set before attempting to begin the frame"); } platformViewsController.onBeginFrame(); } @SuppressWarnings("unused") @UiThread public void onEndFrame() { ensureRunningOnMainThread(); if (platformViewsController == null) { throw new RuntimeException( "platformViewsController must be set before attempting to end the frame"); } platformViewsController.onEndFrame(); } @SuppressWarnings("unused") @UiThread public FlutterOverlaySurface createOverlaySurface() { ensureRunningOnMainThread(); if (platformViewsController == null) { throw new RuntimeException( "platformViewsController must be set before attempting to position an overlay surface"); } return platformViewsController.createOverlaySurface(); } @SuppressWarnings("unused") @UiThread public void destroyOverlaySurfaces() { ensureRunningOnMainThread(); if (platformViewsController == null) { throw new RuntimeException( "platformViewsController must be set before attempting to destroy an overlay surface"); } platformViewsController.destroyOverlaySurfaces(); } // ----- End Engine Lifecycle Support ---- // ----- Start Localization Support ---- /** Sets the localization plugin that is used in various localization methods. */ @UiThread public void setLocalizationPlugin(@Nullable LocalizationPlugin localizationPlugin) { ensureRunningOnMainThread(); this.localizationPlugin = localizationPlugin; } /** Invoked by native to obtain the results of Android's locale resolution algorithm. */ @SuppressWarnings("unused") @VisibleForTesting public String[] computePlatformResolvedLocale(@NonNull String[] strings) { if (localizationPlugin == null) { return new String[0]; } List<Locale> supportedLocales = new ArrayList<Locale>(); final int localeDataLength = 3; for (int i = 0; i < strings.length; i += localeDataLength) { String languageCode = strings[i + 0]; String countryCode = strings[i + 1]; String scriptCode = strings[i + 2]; // Convert to Locales via LocaleBuilder if available (API 21+) to include scriptCode. Locale.Builder localeBuilder = new Locale.Builder(); if (!languageCode.isEmpty()) { localeBuilder.setLanguage(languageCode); } if (!countryCode.isEmpty()) { localeBuilder.setRegion(countryCode); } if (!scriptCode.isEmpty()) { localeBuilder.setScript(scriptCode); } supportedLocales.add(localeBuilder.build()); } Locale result = localizationPlugin.resolveNativeLocale(supportedLocales); if (result == null) { return new String[0]; } String[] output = new String[localeDataLength]; output[0] = result.getLanguage(); output[1] = result.getCountry(); output[2] = result.getScript(); return output; } // ----- End Localization Support ---- @Nullable public float getScaledFontSize(float fontSize, int configurationId) { final DisplayMetrics metrics = SettingsChannel.getPastDisplayMetrics(configurationId); if (metrics == null) { Log.e( TAG, "getScaledFontSize called with configurationId " + String.valueOf(configurationId) + ", which can't be found."); return -1f; } return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, fontSize, metrics) / metrics.density; } // ----- Start Deferred Components Support ---- /** Sets the deferred component manager that is used to download and install split features. */ @UiThread public void setDeferredComponentManager( @Nullable DeferredComponentManager deferredComponentManager) { ensureRunningOnMainThread(); this.deferredComponentManager = deferredComponentManager; if (deferredComponentManager != null) { deferredComponentManager.setJNI(this); } } /** * Called by dart to request that a Dart deferred library corresponding to loadingUnitId be * downloaded (if necessary) and loaded into the dart vm. * * <p>This method delegates the task to DeferredComponentManager, which handles the download and * loading of the dart library and any assets. * * @param loadingUnitId The loadingUnitId is assigned during compile time by gen_snapshot and is * automatically retrieved when loadLibrary() is called on a dart deferred library. */ @SuppressWarnings("unused") @UiThread public void requestDartDeferredLibrary(int loadingUnitId) { if (deferredComponentManager != null) { deferredComponentManager.installDeferredComponent(loadingUnitId, null); } else { // TODO(garyq): Add link to setup/instructions guide wiki. Log.e( TAG, "No DeferredComponentManager found. Android setup must be completed before using split AOT deferred components."); } } /** * Searches each of the provided paths for a valid Dart shared library .so file and resolves * symbols to load into the dart VM. * * <p>Successful loading of the dart library completes the future returned by loadLibrary() that * triggered the install/load process. * * @param loadingUnitId The loadingUnitId is assigned during compile time by gen_snapshot and is * automatically retrieved when loadLibrary() is called on a dart deferred library. This is * used to identify which Dart deferred library the resolved correspond to. * @param searchPaths An array of paths in which to look for valid dart shared libraries. This * supports paths within zipped apks as long as the apks are not compressed using the * `path/to/apk.apk!path/inside/apk/lib.so` format. Paths will be tried first to last and ends * when a library is successfully found. When the found library is invalid, no additional * paths will be attempted. */ @UiThread public void loadDartDeferredLibrary(int loadingUnitId, @NonNull String[] searchPaths) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeLoadDartDeferredLibrary(nativeShellHolderId, loadingUnitId, searchPaths); } private native void nativeLoadDartDeferredLibrary( long nativeShellHolderId, int loadingUnitId, @NonNull String[] searchPaths); /** * Adds the specified AssetManager as an APKAssetResolver in the Flutter Engine's AssetManager. * * <p>This may be used to update the engine AssetManager when a new deferred component is * installed and a new Android AssetManager is created with access to new assets. * * @param assetManager An android AssetManager that is able to access the newly downloaded assets. * @param assetBundlePath The subdirectory that the flutter assets are stored in. The typical * value is `flutter_assets`. */ @UiThread public void updateJavaAssetManager( @NonNull AssetManager assetManager, @NonNull String assetBundlePath) { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeUpdateJavaAssetManager(nativeShellHolderId, assetManager, assetBundlePath); } private native void nativeUpdateJavaAssetManager( long nativeShellHolderId, @NonNull AssetManager assetManager, @NonNull String assetBundlePath); /** * Indicates that a failure was encountered during the Android portion of downloading a dynamic * feature module and loading a dart deferred library, which is typically done by * DeferredComponentManager. * * <p>This will inform dart that the future returned by loadLibrary() should complete with an * error. * * @param loadingUnitId The loadingUnitId that corresponds to the dart deferred library that * failed to install. * @param error The error message to display. * @param isTransient When isTransient is false, new attempts to install will automatically result * in same error in Dart before the request is passed to Android. */ @SuppressWarnings("unused") @UiThread public void deferredComponentInstallFailure( int loadingUnitId, @NonNull String error, boolean isTransient) { ensureRunningOnMainThread(); nativeDeferredComponentInstallFailure(loadingUnitId, error, isTransient); } private native void nativeDeferredComponentInstallFailure( int loadingUnitId, @NonNull String error, boolean isTransient); // ----- End Deferred Components Support ---- // @SuppressWarnings("unused") @UiThread public void onDisplayPlatformView( int viewId, int x, int y, int width, int height, int viewWidth, int viewHeight, FlutterMutatorsStack mutatorsStack) { ensureRunningOnMainThread(); if (platformViewsController == null) { throw new RuntimeException( "platformViewsController must be set before attempting to position a platform view"); } platformViewsController.onDisplayPlatformView( viewId, x, y, width, height, viewWidth, viewHeight, mutatorsStack); } // TODO(mattcarroll): determine if this is nonull or nullable @UiThread public Bitmap getBitmap() { ensureRunningOnMainThread(); ensureAttachedToNative(); return nativeGetBitmap(nativeShellHolderId); } // TODO(mattcarroll): determine if this is nonull or nullable private native Bitmap nativeGetBitmap(long nativeShellHolderId); /** * Notifies the Dart VM of a low memory event, or that the application is in a state such that now * is an appropriate time to free resources, such as going to the background. * * <p>This is distinct from sending a SystemChannel message about low memory, which only notifies * the running Flutter application. */ @UiThread public void notifyLowMemoryWarning() { ensureRunningOnMainThread(); ensureAttachedToNative(); nativeNotifyLowMemoryWarning(nativeShellHolderId); } private native void nativeNotifyLowMemoryWarning(long nativeShellHolderId); private void ensureRunningOnMainThread() { if (Looper.myLooper() != mainLooper) { throw new RuntimeException( "Methods marked with @UiThread must be executed on the main thread. Current thread: " + Thread.currentThread().getName()); } } /** * Delegate responsible for creating and updating Android-side caches of Flutter's semantics tree * and custom accessibility actions. * * <p>{@link AccessibilityBridge} is an example of an {@code AccessibilityDelegate}. */ public interface AccessibilityDelegate { /** * Sends new custom accessibility actions from Flutter to Android. * * <p>Implementers are expected to maintain an Android-side cache of custom accessibility * actions. This method provides new actions to add to that cache. */ void updateCustomAccessibilityActions(@NonNull ByteBuffer buffer, @NonNull String[] strings); /** * Sends new {@code SemanticsNode} information from Flutter to Android. * * <p>Implementers are expected to maintain an Android-side cache of Flutter's semantics tree. * This method provides updates from Flutter for the Android-side semantics tree cache. */ void updateSemantics( @NonNull ByteBuffer buffer, @NonNull String[] strings, @NonNull ByteBuffer[] stringAttributeArgs); } public interface AsyncWaitForVsyncDelegate { void asyncWaitForVsync(final long cookie); } }
engine/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java", "repo_id": "engine", "token_count": 18036 }
306
// 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. package io.flutter.embedding.engine.plugins; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.Set; public interface PluginRegistry { /** * Attaches the given {@code plugin} to the {@link io.flutter.embedding.engine.FlutterEngine} * associated with this {@code PluginRegistry}. */ void add(@NonNull FlutterPlugin plugin); /** * Attaches the given {@code plugins} to the {@link io.flutter.embedding.engine.FlutterEngine} * associated with this {@code PluginRegistry}. */ void add(@NonNull Set<FlutterPlugin> plugins); /** * Returns true if a plugin of the given type is currently attached to the {@link * io.flutter.embedding.engine.FlutterEngine} associated with this {@code PluginRegistry}. */ boolean has(@NonNull Class<? extends FlutterPlugin> pluginClass); /** * Returns the instance of a plugin that is currently attached to the {@link * io.flutter.embedding.engine.FlutterEngine} associated with this {@code PluginRegistry}, which * matches the given {@code pluginClass}. * * <p>If no matching plugin is found, {@code null} is returned. */ @Nullable FlutterPlugin get(@NonNull Class<? extends FlutterPlugin> pluginClass); /** * Detaches the plugin of the given type from the {@link * io.flutter.embedding.engine.FlutterEngine} associated with this {@code PluginRegistry}. * * <p>If no such plugin exists, this method does nothing. */ void remove(@NonNull Class<? extends FlutterPlugin> pluginClass); /** * Detaches the plugins of the given types from the {@link * io.flutter.embedding.engine.FlutterEngine} associated with this {@code PluginRegistry}. * * <p>If no such plugins exist, this method does nothing. */ void remove(@NonNull Set<Class<? extends FlutterPlugin>> plugins); /** * Detaches all plugins that are currently attached to the {@link * io.flutter.embedding.engine.FlutterEngine} associated with this {@code PluginRegistry}. * * <p>If no plugins are currently attached, this method does nothing. */ void removeAll(); }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/PluginRegistry.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/PluginRegistry.java", "repo_id": "engine", "token_count": 691 }
307
// 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. package io.flutter.embedding.engine.plugins.util; import androidx.annotation.NonNull; import io.flutter.Log; import io.flutter.embedding.engine.FlutterEngine; import java.lang.reflect.Method; public class GeneratedPluginRegister { private static final String TAG = "GeneratedPluginsRegister"; /** * Registers all plugins that an app lists in its pubspec.yaml. * * <p>In order to allow each plugin to listen to calls from Dart via Platform Channels, each * plugin is given a chance to initialize and set up Platform Channel listeners in {@link * io.flutter.embedding.engine.plugins.FlutterPlugin#onAttachedToEngine(io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding)}. * * <p>The list of plugins that need to be set up is not known to the Flutter engine. The Flutter * tools generates it at build time based on the plugin dependencies specified in the Flutter * project's pubspec.yaml. * * <p>The Flutter tools generates that list in a class called {@code GeneratedPluginRegistrant}. * That class contains generated code to register every plugin in the pubspec.yaml with a {@link * FlutterEngine}. That code's file is generated in the Flutter project's directory. * * <p>In a normal full-Flutter application, the {@link * io.flutter.embedding.android.FlutterActivity} will automatically call the {@code * GeneratedPluginRegistrant} to register all plugins. In a typical full-Flutter application, the * {@link io.flutter.embedding.android.FlutterActivity} creates a {@link * io.flutter.embedding.engine.FlutterEngine}. When a {@link * io.flutter.embedding.engine.FlutterEngine} is explicitly created, it automatically registers * plugins during its construction. * * <p>Since the {@link io.flutter.embedding.engine.FlutterEngine} belongs to the Flutter engine * and the GeneratedPluginRegistrant class belongs to the app project, the {@link * io.flutter.embedding.engine.FlutterEngine} cannot place a compile-time dependency on * GeneratedPluginRegistrant to invoke it. Instead, this class uses reflection to attempt to * locate the generated file and then uses it at runtime. * * <p>This method fizzles if the GeneratedPluginRegistrant cannot be found or invoked. This * situation should never occur, but if any eventuality comes up that prevents an app from using * this behavior, that app can still write code that explicitly registers plugins. * * <p>To disable this automatic plugin registration behavior: * * <ul> * <li>If you manually construct {@link io.flutter.embedding.engine.FlutterEngine}s, construct * the {@link io.flutter.embedding.engine.FlutterEngine} with the {@code * automaticallyRegisterPlugins} construction parameter set to false. * <li>If you let the {@link io.flutter.embedding.android.FlutterActivity} or {@link * io.flutter.embedding.android.FlutterFragmentActivity} construct a {@link * io.flutter.embedding.engine.FlutterEngine} implicitly, override the {@code * configureFlutterEngine} implementation and don't call through to the superclass * implementation. * </ul> * * <p>Disabling the automatic plugin registration or deferring it by calling this method * explicitly may be useful in fine tuning the application launch latency characteristics for your * application. * * <p>It's also possible to not use GeneratedPluginRegistrant and this method at all in order to * fine tune not only when plugins are registered but which plugins are registered when. * Inspecting the content of the GeneratedPluginRegistrant class will reveal that it's just going * through each of the plugins referenced in pubspec.yaml and calling {@link * io.flutter.embedding.engine.plugins.FlutterPlugin#onAttachedToEngine(io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding)} * on each plugin. That code can be copy pasted and invoked directly per plugin to determine which * plugin gets registered when in your own application's code. Note that when that's done without * using the GeneratedPluginRegistrant, updating pubspec.yaml will no longer automatically update * the list of plugins being registered. */ public static void registerGeneratedPlugins(@NonNull FlutterEngine flutterEngine) { try { Class<?> generatedPluginRegistrant = Class.forName("io.flutter.plugins.GeneratedPluginRegistrant"); Method registrationMethod = generatedPluginRegistrant.getDeclaredMethod("registerWith", FlutterEngine.class); registrationMethod.invoke(null, flutterEngine); } catch (Exception e) { Log.e( TAG, "Tried to automatically register plugins with FlutterEngine (" + flutterEngine + ") but could not find or invoke the GeneratedPluginRegistrant."); Log.e(TAG, "Received exception while registering", e); } } }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/util/GeneratedPluginRegister.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/util/GeneratedPluginRegister.java", "repo_id": "engine", "token_count": 1546 }
308
// 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. package io.flutter.embedding.engine.systemchannels; import android.content.pm.PackageManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.StandardMethodCodec; import java.util.ArrayList; import java.util.Map; /** * {@link ProcessTextChannel} is a platform channel that is used by the framework to initiate text * processing feature in the embedding and for the embedding to send back the results. * * <p>When the framework needs to query the list of text processing actions (for instance to expose * them in the selected text context menu), it will send to the embedding the message {@code * ProcessText.queryTextActions}. In response, the {@link io.flutter.plugin.text.ProcessTextPlugin} * will return a map of all activities that can process text. The map keys are generated IDs and the * values are the activities labels. On the first request, the {@link * io.flutter.plugin.text.ProcessTextPlugin} will make a call to Android's package manager to query * all activities that can be performed for the {@code Intent.ACTION_PROCESS_TEXT} intent. * * <p>When a text processing action has to be executed, the framework will send to the embedding the * message {@code ProcessText.processTextAction} with the {@code int id} of the choosen text action * and the {@code String} of text to process as arguments. In response, the {@link * io.flutter.plugin.text.ProcessTextPlugin} will make a call to the Android application activity to * start the activity exposing the text action. The {@link io.flutter.plugin.text.ProcessTextPlugin} * will return the processed text if there is one, or null if the activity did not return a * transformed text. * * <p>{@link io.flutter.plugin.text.ProcessTextPlugin} implements {@link ProcessTextMethodHandler} * that parses incoming messages from Flutter. */ public class ProcessTextChannel { private static final String TAG = "ProcessTextChannel"; private static final String CHANNEL_NAME = "flutter/processtext"; private static final String METHOD_QUERY_TEXT_ACTIONS = "ProcessText.queryTextActions"; private static final String METHOD_PROCESS_TEXT_ACTION = "ProcessText.processTextAction"; public final MethodChannel channel; public final PackageManager packageManager; private ProcessTextMethodHandler processTextMethodHandler; @NonNull public final MethodChannel.MethodCallHandler parsingMethodHandler = new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { if (processTextMethodHandler == null) { return; } String method = call.method; Object args = call.arguments; switch (method) { case METHOD_QUERY_TEXT_ACTIONS: try { Map<String, String> actions = processTextMethodHandler.queryTextActions(); result.success(actions); } catch (IllegalStateException exception) { result.error("error", exception.getMessage(), null); } break; case METHOD_PROCESS_TEXT_ACTION: try { final ArrayList<Object> argumentList = (ArrayList<Object>) args; String id = (String) (argumentList.get(0)); String text = (String) (argumentList.get(1)); boolean readOnly = (boolean) (argumentList.get(2)); processTextMethodHandler.processTextAction(id, text, readOnly, result); } catch (IllegalStateException exception) { result.error("error", exception.getMessage(), null); } break; default: result.notImplemented(); break; } } }; public ProcessTextChannel( @NonNull DartExecutor dartExecutor, @NonNull PackageManager packageManager) { this.packageManager = packageManager; channel = new MethodChannel(dartExecutor, CHANNEL_NAME, StandardMethodCodec.INSTANCE); channel.setMethodCallHandler(parsingMethodHandler); } /** * Sets the {@link ProcessTextMethodHandler} which receives all requests to the text processing * feature sent through this channel. */ public void setMethodHandler(@Nullable ProcessTextMethodHandler processTextMethodHandler) { this.processTextMethodHandler = processTextMethodHandler; } public interface ProcessTextMethodHandler { /** Requests the map of text actions. Each text action has a unique id and a localized label. */ Map<String, String> queryTextActions(); /** * Requests to run a text action on a given input text. * * @param id The ID of the text action returned by {@code ProcessText.queryTextActions}. * @param input The text to be processed. * @param readOnly Indicates to the activity if the processed text will be used as read-only. * see * https://developer.android.com/reference/android/content/Intent#EXTRA_PROCESS_TEXT_READONLY * @param result The method channel result instance used to reply. */ void processTextAction( @NonNull String id, @NonNull String input, @NonNull boolean readOnly, @NonNull MethodChannel.Result result); } }
engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/ProcessTextChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/ProcessTextChannel.java", "repo_id": "engine", "token_count": 1885 }
309
// 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. package io.flutter.plugin.common; import androidx.annotation.Nullable; import java.nio.ByteBuffer; /** * A message encoding/decoding mechanism. * * <p>Both operations throw {@link IllegalArgumentException}, if conversion fails. */ public interface MessageCodec<T> { /** * Encodes the specified message into binary. * * @param message the T message, possibly null. * @return a ByteBuffer containing the encoding between position 0 and the current position, or * null, if message is null. */ @Nullable ByteBuffer encodeMessage(@Nullable T message); /** * Decodes the specified message from binary. * * <p><b>Warning:</b> The ByteBuffer is "direct" and it won't be valid beyond this call. Storing * the ByteBuffer and using it later and will lead to a {@code java.nio.BufferUnderflowException}. * If you want to retain the data you'll need to copy it. * * @param message the {@link ByteBuffer} message, possibly null. * @return a T value representation of the bytes between the given buffer's current position and * its limit, or null, if message is null. */ @Nullable T decodeMessage(@Nullable ByteBuffer message); }
engine/shell/platform/android/io/flutter/plugin/common/MessageCodec.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/MessageCodec.java", "repo_id": "engine", "token_count": 399 }
310
// 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. package io.flutter.plugin.mouse; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.view.PointerIcon; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; import java.util.HashMap; /** A mandatory plugin that handles mouse cursor requests. */ @TargetApi(API_LEVELS.API_24) @RequiresApi(API_LEVELS.API_24) public class MouseCursorPlugin { @NonNull private final MouseCursorViewDelegate mView; @NonNull private final MouseCursorChannel mouseCursorChannel; public MouseCursorPlugin( @NonNull MouseCursorViewDelegate view, @NonNull MouseCursorChannel mouseCursorChannel) { mView = view; this.mouseCursorChannel = mouseCursorChannel; mouseCursorChannel.setMethodHandler( new MouseCursorChannel.MouseCursorMethodHandler() { @Override public void activateSystemCursor(@NonNull String kind) { mView.setPointerIcon(resolveSystemCursor(kind)); } }); } /** * Return a pointer icon object for a system cursor. * * <p>This method guarantees to return a non-null object. */ private PointerIcon resolveSystemCursor(@NonNull String kind) { if (MouseCursorPlugin.systemCursorConstants == null) { // Initialize the map when first used, because the map can grow big in the future (~70) // and most mobile devices will not use them. MouseCursorPlugin.systemCursorConstants = new HashMap<String, Integer>() { private static final long serialVersionUID = 1L; { put("alias", PointerIcon.TYPE_ALIAS); put("allScroll", PointerIcon.TYPE_ALL_SCROLL); put("basic", PointerIcon.TYPE_ARROW); put("cell", PointerIcon.TYPE_CELL); put("click", PointerIcon.TYPE_HAND); put("contextMenu", PointerIcon.TYPE_CONTEXT_MENU); put("copy", PointerIcon.TYPE_COPY); put("forbidden", PointerIcon.TYPE_NO_DROP); put("grab", PointerIcon.TYPE_GRAB); put("grabbing", PointerIcon.TYPE_GRABBING); put("help", PointerIcon.TYPE_HELP); put("move", PointerIcon.TYPE_ALL_SCROLL); put("none", PointerIcon.TYPE_NULL); put("noDrop", PointerIcon.TYPE_NO_DROP); put("precise", PointerIcon.TYPE_CROSSHAIR); put("text", PointerIcon.TYPE_TEXT); put("resizeColumn", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); put("resizeDown", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); put("resizeUpLeft", PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW); put("resizeDownRight", PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW); put("resizeLeft", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); put("resizeLeftRight", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); put("resizeRight", PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW); put("resizeRow", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); put("resizeUp", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); put("resizeUpDown", PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW); put("resizeUpLeft", PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW); put("resizeUpRight", PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW); put("resizeUpLeftDownRight", PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW); put("resizeUpRightDownLeft", PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW); put("verticalText", PointerIcon.TYPE_VERTICAL_TEXT); put("wait", PointerIcon.TYPE_WAIT); put("zoomIn", PointerIcon.TYPE_ZOOM_IN); put("zoomOut", PointerIcon.TYPE_ZOOM_OUT); } }; } final int cursorConstant = MouseCursorPlugin.systemCursorConstants.getOrDefault(kind, PointerIcon.TYPE_ARROW); return mView.getSystemPointerIcon(cursorConstant); } /** * Detaches the text input plugin from the platform views controller. * * <p>The MouseCursorPlugin instance should not be used after calling this. */ public void destroy() { mouseCursorChannel.setMethodHandler(null); } /** * A map from Flutter's system cursor {@code kind} to Android's pointer icon constants. * * <p>It is null until the first time a system cursor is requested, at which time it is filled * with the entire mapping. */ @NonNull private static HashMap<String, Integer> systemCursorConstants; /** * Delegate interface for requesting the system to display a pointer icon object. * * <p>Typically implemented by an {@link android.view.View}, such as a {@code FlutterView}. */ public interface MouseCursorViewDelegate { /** * Gets a system pointer icon object for the given {@code type}. * * <p>If typeis not recognized, returns the default pointer icon. * * <p>This is typically implemented by calling {@link android.view.PointerIcon#getSystemIcon} * with the context associated with this view. */ @NonNull public PointerIcon getSystemPointerIcon(int type); /** * Request the pointer to display the specified icon object. * * <p>If the delegate is implemented by a {@link android.view.View}, then this method is * automatically implemented by View. */ public void setPointerIcon(@NonNull PointerIcon icon); } }
engine/shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.java", "repo_id": "engine", "token_count": 2322 }
311
package io.flutter.plugin.platform; import static io.flutter.Build.API_LEVELS; import android.annotation.TargetApi; import android.view.Surface; import io.flutter.view.TextureRegistry.SurfaceProducer; @TargetApi(API_LEVELS.API_29) public class SurfaceProducerPlatformViewRenderTarget implements PlatformViewRenderTarget { private static final String TAG = "SurfaceProducerRenderTarget"; private SurfaceProducer producer; public SurfaceProducerPlatformViewRenderTarget(SurfaceProducer producer) { this.producer = producer; } // Called when the render target should be resized. public void resize(int width, int height) { this.producer.setSize(width, height); } // Returns the currently specified width. public int getWidth() { return this.producer.getWidth(); } // Returns the currently specified height. public int getHeight() { return this.producer.getHeight(); } // The id of this render target. public long getId() { return this.producer.id(); } // Releases backing resources. public void release() { this.producer.release(); this.producer = null; } // Returns true in the case that backing resource have been released. public boolean isReleased() { return this.producer == null; } // Returns the Surface to be rendered on to. public Surface getSurface() { return this.producer.getSurface(); } public void scheduleFrame() { this.producer.scheduleFrame(); } }
engine/shell/platform/android/io/flutter/plugin/platform/SurfaceProducerPlatformViewRenderTarget.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/SurfaceProducerPlatformViewRenderTarget.java", "repo_id": "engine", "token_count": 441 }
312
# 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/testing/testing.gni") source_set("platform_view_android_delegate") { sources = [ "platform_view_android_delegate.cc", "platform_view_android_delegate.h", ] public_configs = [ "//flutter:config" ] deps = [ "//flutter/common", "//flutter/fml", "//flutter/lib/ui", "//flutter/shell/common", "//flutter/shell/platform/android/jni", "//flutter/skia", ] } test_fixtures("platform_view_android_delegate_fixtures") { fixtures = [] } executable("platform_view_android_delegate_unittests") { testonly = true sources = [ "platform_view_android_delegate_unittests.cc" ] deps = [ ":platform_view_android_delegate", ":platform_view_android_delegate_fixtures", "//flutter/shell/platform/android/jni:jni_mock", "//flutter/testing", "//flutter/testing:dart", "//flutter/third_party/txt", ] }
engine/shell/platform/android/platform_view_android_delegate/BUILD.gn/0
{ "file_path": "engine/shell/platform/android/platform_view_android_delegate/BUILD.gn", "repo_id": "engine", "token_count": 413 }
313
// 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/shell/platform/android/surface_texture_external_texture.h" #include <GLES/glext.h> #include <utility> #include "flutter/display_list/effects/dl_color_source.h" #include "third_party/skia/include/core/SkAlphaType.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h" #include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" namespace flutter { SurfaceTextureExternalTexture::SurfaceTextureExternalTexture( int64_t id, const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade) : Texture(id), jni_facade_(jni_facade), surface_texture_(surface_texture), transform_(SkMatrix::I()) {} SurfaceTextureExternalTexture::~SurfaceTextureExternalTexture() {} void SurfaceTextureExternalTexture::OnGrContextCreated() { state_ = AttachmentState::kUninitialized; } void SurfaceTextureExternalTexture::MarkNewFrameAvailable() { // NOOP. } void SurfaceTextureExternalTexture::Paint(PaintContext& context, const SkRect& bounds, bool freeze, const DlImageSampling sampling) { if (state_ == AttachmentState::kDetached) { return; } const bool should_process_frame = !freeze || ShouldUpdate() || dl_image_ == nullptr; if (should_process_frame) { ProcessFrame(context, bounds); } FML_CHECK(state_ == AttachmentState::kAttached); if (dl_image_) { DlAutoCanvasRestore autoRestore(context.canvas, true); // The incoming texture is vertically flipped, so we flip it // back. OpenGL's coordinate system has Positive Y equivalent to up, while // Skia's coordinate system has Negative Y equvalent to up. context.canvas->Translate(bounds.x(), bounds.y() + bounds.height()); context.canvas->Scale(bounds.width(), -bounds.height()); if (!transform_.isIdentity()) { DlImageColorSource source(dl_image_, DlTileMode::kClamp, DlTileMode::kClamp, sampling, &transform_); DlPaint paintWithShader; if (context.paint) { paintWithShader = *context.paint; } paintWithShader.setColorSource(&source); context.canvas->DrawRect(SkRect::MakeWH(1, 1), paintWithShader); } else { context.canvas->DrawImage(dl_image_, {0, 0}, sampling, context.paint); } } else { FML_LOG(WARNING) << "No DlImage available for SurfaceTextureExternalTexture to paint."; } } void SurfaceTextureExternalTexture::OnGrContextDestroyed() { if (state_ == AttachmentState::kAttached) { Detach(); } state_ = AttachmentState::kDetached; } void SurfaceTextureExternalTexture::OnTextureUnregistered() {} void SurfaceTextureExternalTexture::Detach() { jni_facade_->SurfaceTextureDetachFromGLContext( fml::jni::ScopedJavaLocalRef<jobject>(surface_texture_)); dl_image_.reset(); } void SurfaceTextureExternalTexture::Attach(int gl_tex_id) { jni_facade_->SurfaceTextureAttachToGLContext( fml::jni::ScopedJavaLocalRef<jobject>(surface_texture_), gl_tex_id); state_ = AttachmentState::kAttached; } bool SurfaceTextureExternalTexture::ShouldUpdate() { return jni_facade_->SurfaceTextureShouldUpdate( fml::jni::ScopedJavaLocalRef<jobject>(surface_texture_)); } void SurfaceTextureExternalTexture::Update() { jni_facade_->SurfaceTextureUpdateTexImage( fml::jni::ScopedJavaLocalRef<jobject>(surface_texture_)); jni_facade_->SurfaceTextureGetTransformMatrix( fml::jni::ScopedJavaLocalRef<jobject>(surface_texture_), transform_); // Android's SurfaceTexture transform matrix works on texture coordinate // lookups in the range 0.0-1.0, while Skia's Shader transform matrix works on // the image itself, as if it were inscribed inside a clip rect. // An Android transform that scales lookup by 0.5 (displaying 50% of the // texture) is the same as a Skia transform by 2.0 (scaling 50% of the image // outside of the virtual "clip rect"), so we invert the incoming matrix. SkMatrix inverted; if (!transform_.invert(&inverted)) { FML_LOG(FATAL) << "Invalid (not invertable) SurfaceTexture transformation matrix"; } transform_ = inverted; } } // namespace flutter
engine/shell/platform/android/surface_texture_external_texture.cc/0
{ "file_path": "engine/shell/platform/android/surface_texture_external_texture.cc", "repo_id": "engine", "token_count": 1752 }
314
package io.flutter.embedding.android; import static io.flutter.Build.API_LEVELS; import static junit.framework.TestCase.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import android.annotation.TargetApi; import android.view.KeyEvent; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.systemchannels.KeyEventChannel; import io.flutter.embedding.engine.systemchannels.KeyEventChannel.EventResponseHandler; import io.flutter.embedding.engine.systemchannels.KeyEventChannel.FlutterKeyEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) @TargetApi(API_LEVELS.API_28) public class KeyChannelResponderTest { @Mock KeyEventChannel keyEventChannel; KeyChannelResponder channelResponder; @Before public void setUp() { MockitoAnnotations.openMocks(this); channelResponder = new KeyChannelResponder(keyEventChannel); } @Test public void primaryResponderTest() { final int[] completionCallbackInvocationCounter = {0}; doAnswer( invocation -> { ((EventResponseHandler) invocation.getArgument(2)).onFrameworkResponse(true); return null; }) .when(keyEventChannel) .sendFlutterKeyEvent( any(FlutterKeyEvent.class), any(boolean.class), any(EventResponseHandler.class)); final KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, 65); channelResponder.handleEvent( keyEvent, (canHandleEvent) -> { completionCallbackInvocationCounter[0]++; }); assertEquals(completionCallbackInvocationCounter[0], 1); } }
engine/shell/platform/android/test/io/flutter/embedding/android/KeyChannelResponderTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/KeyChannelResponderTest.java", "repo_id": "engine", "token_count": 667 }
315
// 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. package io.flutter.embedding.engine.loader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.os.Bundle; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import java.io.StringReader; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.stubbing.Answer; import org.robolectric.annotation.Config; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class ApplicationInfoLoaderTest { @Test public void itGeneratesCorrectApplicationInfoWithDefaultManifest() { FlutterApplicationInfo info = ApplicationInfoLoader.load(ApplicationProvider.getApplicationContext()); assertNotNull(info); assertEquals("libapp.so", info.aotSharedLibraryName); assertEquals("vm_snapshot_data", info.vmSnapshotData); assertEquals("isolate_snapshot_data", info.isolateSnapshotData); assertEquals("flutter_assets", info.flutterAssetsDir); assertEquals("", info.domainNetworkPolicy); assertNull(info.nativeLibraryDir); } @SuppressWarnings("deprecation") // getApplicationInfo private Context generateMockContext(Bundle metadata, String networkPolicyXml) throws Exception { Context context = mock(Context.class); PackageManager packageManager = mock(PackageManager.class); ApplicationInfo applicationInfo = mock(ApplicationInfo.class); applicationInfo.metaData = metadata; Resources resources = mock(Resources.class); when(context.getPackageManager()).thenReturn(packageManager); when(context.getResources()).thenReturn(resources); when(context.getPackageName()).thenReturn(""); when(packageManager.getApplicationInfo(anyString(), anyInt())).thenReturn(applicationInfo); if (networkPolicyXml != null) { metadata.putInt(ApplicationInfoLoader.NETWORK_POLICY_METADATA_KEY, 5); doAnswer(invocationOnMock -> createMockResourceParser(networkPolicyXml)) .when(resources) .getXml(5); } return context; } @Test public void itGeneratesCorrectApplicationInfoWithCustomValues() throws Exception { Bundle bundle = new Bundle(); bundle.putString(ApplicationInfoLoader.PUBLIC_AOT_SHARED_LIBRARY_NAME, "testaot"); bundle.putString(ApplicationInfoLoader.PUBLIC_VM_SNAPSHOT_DATA_KEY, "testvmsnapshot"); bundle.putString(ApplicationInfoLoader.PUBLIC_ISOLATE_SNAPSHOT_DATA_KEY, "testisolatesnapshot"); bundle.putString(ApplicationInfoLoader.PUBLIC_FLUTTER_ASSETS_DIR_KEY, "testassets"); Context context = generateMockContext(bundle, null); FlutterApplicationInfo info = ApplicationInfoLoader.load(context); assertNotNull(info); assertEquals("testaot", info.aotSharedLibraryName); assertEquals("testvmsnapshot", info.vmSnapshotData); assertEquals("testisolatesnapshot", info.isolateSnapshotData); assertEquals("testassets", info.flutterAssetsDir); assertNull(info.nativeLibraryDir); assertEquals("", info.domainNetworkPolicy); } @Test public void itGeneratesCorrectNetworkPolicy() throws Exception { Bundle bundle = new Bundle(); String networkPolicyXml = "<network-security-config>" + "<domain-config cleartextTrafficPermitted=\"false\">" + "<domain includeSubdomains=\"true\">secure.example.com</domain>" + "</domain-config>" + "</network-security-config>"; Context context = generateMockContext(bundle, networkPolicyXml); FlutterApplicationInfo info = ApplicationInfoLoader.load(context); assertNotNull(info); assertEquals("[[\"secure.example.com\",true,false]]", info.domainNetworkPolicy); } @Test public void itHandlesBogusInformationInNetworkPolicy() throws Exception { Bundle bundle = new Bundle(); String networkPolicyXml = "<network-security-config>" + "<domain-config cleartextTrafficPermitted=\"false\">" + "<domain includeSubdomains=\"true\">secure.example.com</domain>" + "<pin-set expiration=\"2018-01-01\">" + "<pin digest=\"SHA-256\">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>" + "<!-- backup pin -->" + "<pin digest=\"SHA-256\">fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=</pin>" + "</pin-set>" + "</domain-config>" + "</network-security-config>"; Context context = generateMockContext(bundle, networkPolicyXml); FlutterApplicationInfo info = ApplicationInfoLoader.load(context); assertNotNull(info); assertEquals("[[\"secure.example.com\",true,false]]", info.domainNetworkPolicy); } @Test public void itHandlesNestedSubDomains() throws Exception { Bundle bundle = new Bundle(); String networkPolicyXml = "<network-security-config>" + "<domain-config cleartextTrafficPermitted=\"true\">" + "<domain includeSubdomains=\"true\">example.com</domain>" + "<domain-config>" + "<domain includeSubdomains=\"true\">insecure.example.com</domain>" + "</domain-config>" + "<domain-config cleartextTrafficPermitted=\"false\">" + "<domain includeSubdomains=\"true\">secure.example.com</domain>" + "</domain-config>" + "</domain-config>" + "</network-security-config>"; Context context = generateMockContext(bundle, networkPolicyXml); FlutterApplicationInfo info = ApplicationInfoLoader.load(context); assertNotNull(info); assertEquals( "[[\"example.com\",true,true],[\"insecure.example.com\",true,true],[\"secure.example.com\",true,false]]", info.domainNetworkPolicy); } // The following ridiculousness is needed because Android gives no way for us // to customize XmlResourceParser. We have to mock it and tie each method // we use to an actual Xml parser. private XmlResourceParser createMockResourceParser(String xml) throws Exception { final XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser(); xpp.setInput(new StringReader(xml)); XmlResourceParser resourceParser = mock(XmlResourceParser.class); final Answer<Object> invokeMethodOnRealParser = invocation -> invocation.getMethod().invoke(xpp, invocation.getArguments()); when(resourceParser.next()).thenAnswer(invokeMethodOnRealParser); when(resourceParser.getName()).thenAnswer(invokeMethodOnRealParser); when(resourceParser.getEventType()).thenAnswer(invokeMethodOnRealParser); when(resourceParser.getText()).thenAnswer(invokeMethodOnRealParser); when(resourceParser.getAttributeCount()).thenAnswer(invokeMethodOnRealParser); when(resourceParser.getAttributeName(anyInt())).thenAnswer(invokeMethodOnRealParser); when(resourceParser.getAttributeValue(anyInt())).thenAnswer(invokeMethodOnRealParser); when(resourceParser.getAttributeValue(anyString(), anyString())) .thenAnswer(invokeMethodOnRealParser); when(resourceParser.getAttributeBooleanValue(any(), anyString(), anyBoolean())) .thenAnswer( invocation -> { Object[] args = invocation.getArguments(); String result = xpp.getAttributeValue((String) args[0], (String) args[1]); if (result == null) { return (Boolean) args[2]; } return Boolean.parseBoolean(result); }); return resourceParser; } }
engine/shell/platform/android/test/io/flutter/embedding/engine/loader/ApplicationInfoLoaderTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/loader/ApplicationInfoLoaderTest.java", "repo_id": "engine", "token_count": 2891 }
316
package io.flutter.external; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import android.content.Intent; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode; import io.flutter.embedding.android.RenderMode; import io.flutter.embedding.android.RobolectricFlutterActivity; import io.flutter.embedding.android.TransparencyMode; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterLaunchTests { @Test public void launchFlutterActivity_with_defaultIntent_expect_defaultConfiguration() { Intent intent = FlutterActivity.createDefaultIntent(ApplicationProvider.getApplicationContext()); FlutterActivity flutterActivity = RobolectricFlutterActivity.createFlutterActivity(intent); assertEquals("main", flutterActivity.getDartEntrypointFunctionName()); assertEquals("/", flutterActivity.getInitialRoute()); assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); assertTrue(flutterActivity.shouldAttachEngineToActivity()); assertNull(flutterActivity.getCachedEngineId()); assertTrue(flutterActivity.shouldDestroyEngineWithHost()); assertEquals( BackgroundMode.opaque, RobolectricFlutterActivity.getBackgroundMode(flutterActivity)); assertEquals(RenderMode.surface, flutterActivity.getRenderMode()); assertEquals(TransparencyMode.opaque, flutterActivity.getTransparencyMode()); } }
engine/shell/platform/android/test/io/flutter/external/FlutterLaunchTests.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/external/FlutterLaunchTests.java", "repo_id": "engine", "token_count": 557 }
317
// 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. package io.flutter.plugin.platform; import static android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; import static android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS; import static io.flutter.Build.API_LEVELS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.net.Uri; import android.os.Build; import android.view.View; import android.view.Window; import android.view.WindowInsetsController; import android.view.WindowManager; import androidx.activity.OnBackPressedCallback; import androidx.fragment.app.FragmentActivity; import androidx.test.core.app.ApplicationProvider; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.embedding.engine.systemchannels.PlatformChannel.Brightness; import io.flutter.embedding.engine.systemchannels.PlatformChannel.ClipboardContentFormat; import io.flutter.embedding.engine.systemchannels.PlatformChannel.SystemChromeStyle; import io.flutter.plugin.platform.PlatformPlugin.PlatformPluginDelegate; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLooper; @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class PlatformPluginTest { private final Context ctx = ApplicationProvider.getApplicationContext(); private final PlatformChannel mockPlatformChannel = mock(PlatformChannel.class); private ClipboardManager clipboardManager; private ClipboardContentFormat clipboardFormat; public void setUpForTextClipboardTests(Activity mockActivity) { clipboardManager = spy(ctx.getSystemService(ClipboardManager.class)); when(mockActivity.getSystemService(Context.CLIPBOARD_SERVICE)).thenReturn(clipboardManager); clipboardFormat = ClipboardContentFormat.PLAIN_TEXT; } @Test public void platformPlugin_getClipboardDataIsNonNullWhenPlainTextCopied() throws IOException { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); setUpForTextClipboardTests(mockActivity); // Primary clip contains non-text media. ClipData clip = ClipData.newPlainText("label", "Text"); assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); clipboardManager.setPrimaryClip(clip); assertNotNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); } @Test public void platformPlugin_getClipboardDataIsNonNullWhenIOExceptionThrown() throws IOException { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); setUpForTextClipboardTests(mockActivity); ContentResolver contentResolver = mock(ContentResolver.class); ClipData.Item mockItem = mock(ClipData.Item.class); Uri mockUri = mock(Uri.class); AssetFileDescriptor mockAssetFileDescriptor = mock(AssetFileDescriptor.class); when(mockActivity.getContentResolver()).thenReturn(contentResolver); when(mockUri.getScheme()).thenReturn("content"); when(mockItem.getText()).thenReturn(null); when(mockItem.getUri()).thenReturn(mockUri); when(contentResolver.openTypedAssetFileDescriptor(any(Uri.class), any(), any())) .thenReturn(mockAssetFileDescriptor); when(mockItem.coerceToText(mockActivity)).thenReturn("something non-null"); doThrow(new IOException()).when(mockAssetFileDescriptor).close(); ClipData clip = new ClipData("label", new String[0], mockItem); assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); clipboardManager.setPrimaryClip(clip); assertNotNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); } @Test public void platformPlugin_getClipboardDataIsNonNullWhenContentUriWithTextProvided() throws IOException { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); setUpForTextClipboardTests(mockActivity); ContentResolver contentResolver = mock(ContentResolver.class); ClipData.Item mockItem = mock(ClipData.Item.class); Uri mockUri = mock(Uri.class); when(mockActivity.getContentResolver()).thenReturn(contentResolver); when(mockUri.getScheme()).thenReturn("content"); when(mockItem.getText()).thenReturn(null); when(mockItem.getUri()).thenReturn(mockUri); when(contentResolver.openTypedAssetFileDescriptor(any(Uri.class), any(), any())) .thenReturn(mock(AssetFileDescriptor.class)); when(mockItem.coerceToText(mockActivity)).thenReturn("something non-null"); ClipData clip = new ClipData("label", new String[0], mockItem); assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); clipboardManager.setPrimaryClip(clip); assertNotNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); } @Test public void platformPlugin_getClipboardDataIsNullWhenContentUriProvidedContainsNoText() throws IOException { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); setUpForTextClipboardTests(mockActivity); ContentResolver contentResolver = ctx.getContentResolver(); when(mockActivity.getContentResolver()).thenReturn(contentResolver); Uri uri = Uri.parse("content://media/external_primary/images/media/"); ClipData clip = ClipData.newUri(contentResolver, "URI", uri); clipboardManager.setPrimaryClip(clip); assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); } @Test public void platformPlugin_getClipboardDataIsNullWhenNonContentUriProvided() throws IOException { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); setUpForTextClipboardTests(mockActivity); ContentResolver contentResolver = ctx.getContentResolver(); when(mockActivity.getContentResolver()).thenReturn(contentResolver); Uri uri = Uri.parse("file:///"); ClipData clip = ClipData.newUri(contentResolver, "URI", uri); clipboardManager.setPrimaryClip(clip); assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); } @Test public void platformPlugin_getClipboardDataIsNullWhenItemHasNoTextNorUri() throws IOException { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); setUpForTextClipboardTests(mockActivity); ClipData.Item mockItem = mock(ClipData.Item.class); when(mockItem.getText()).thenReturn(null); when(mockItem.getUri()).thenReturn(null); ClipData clip = new ClipData("label", new String[0], mockItem); clipboardManager.setPrimaryClip(clip); assertNull(platformPlugin.mPlatformMessageHandler.getClipboardData(clipboardFormat)); } @SuppressWarnings("deprecation") // ClipboardManager.getText @Config(sdk = API_LEVELS.API_28) @Test public void platformPlugin_hasStrings() { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); setUpForTextClipboardTests(mockActivity); // Plain text ClipData clip = ClipData.newPlainText("label", "Text"); clipboardManager.setPrimaryClip(clip); assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); // Empty plain text clip = ClipData.newPlainText("", ""); clipboardManager.setPrimaryClip(clip); // Without actually accessing clipboard data (preferred behavior), it is not possible to // distinguish between empty and non-empty string contents. assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); // HTML text clip = ClipData.newHtmlText("motto", "Don't be evil", "<b>Don't</b> be evil"); clipboardManager.setPrimaryClip(clip); assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); // Text MIME type clip = new ClipData("label", new String[] {"text/something"}, new ClipData.Item("content")); clipboardManager.setPrimaryClip(clip); assertTrue(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); // Other MIME type clip = new ClipData( "label", new String[] {"application/octet-stream"}, new ClipData.Item("content")); clipboardManager.setPrimaryClip(clip); assertFalse(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { // Empty clipboard clipboardManager.clearPrimaryClip(); assertFalse(platformPlugin.mPlatformMessageHandler.clipboardHasStrings()); } // Verify that the clipboard contents are never accessed. verify(clipboardManager, never()).getPrimaryClip(); verify(clipboardManager, never()).getText(); } @Config(sdk = API_LEVELS.API_29) @Test public void setNavigationBarDividerColor() { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { // Default style test SystemChromeStyle style = new SystemChromeStyle( 0XFF000000, // statusBarColor Brightness.LIGHT, // statusBarIconBrightness true, // systemStatusBarContrastEnforced 0XFFC70039, // systemNavigationBarColor Brightness.LIGHT, // systemNavigationBarIconBrightness 0XFF006DB3, // systemNavigationBarDividerColor true); // systemNavigationBarContrastEnforced platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindow).setStatusBarColor(0xFF000000); verify(fakeWindow).setNavigationBarColor(0XFFC70039); verify(fakeWindow).setNavigationBarDividerColor(0XFF006DB3); verify(fakeWindow).setStatusBarContrastEnforced(true); verify(fakeWindow).setNavigationBarContrastEnforced(true); // Regression test for https://github.com/flutter/flutter/issues/88431 // A null brightness should not affect changing color settings. style = new SystemChromeStyle( 0XFF006DB3, // statusBarColor null, // statusBarIconBrightness false, // systemStatusBarContrastEnforced 0XFF000000, // systemNavigationBarColor null, // systemNavigationBarIconBrightness 0XFF006DB3, // systemNavigationBarDividerColor false); // systemNavigationBarContrastEnforced platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindow).setStatusBarColor(0XFF006DB3); verify(fakeWindow).setNavigationBarColor(0XFF000000); verify(fakeWindow, times(2)).setNavigationBarDividerColor(0XFF006DB3); verify(fakeWindow).setStatusBarContrastEnforced(false); verify(fakeWindow).setNavigationBarContrastEnforced(false); // Null contrasts values should be allowed. style = new SystemChromeStyle( 0XFF006DB3, // statusBarColor null, // statusBarIconBrightness null, // systemStatusBarContrastEnforced 0XFF000000, // systemNavigationBarColor null, // systemNavigationBarIconBrightness 0XFF006DB3, // systemNavigationBarDividerColor null); // systemNavigationBarContrastEnforced platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindow, times(2)).setStatusBarColor(0XFF006DB3); verify(fakeWindow, times(2)).setNavigationBarColor(0XFF000000); verify(fakeWindow, times(3)).setNavigationBarDividerColor(0XFF006DB3); // Count is 1 each from earlier calls verify(fakeWindow, times(1)).setStatusBarContrastEnforced(true); verify(fakeWindow, times(1)).setNavigationBarContrastEnforced(true); verify(fakeWindow, times(1)).setStatusBarContrastEnforced(false); verify(fakeWindow, times(1)).setNavigationBarContrastEnforced(false); } } @Config(sdk = API_LEVELS.API_30) @Test public void setNavigationBarIconBrightness() { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); if (Build.VERSION.SDK_INT >= API_LEVELS.API_30) { WindowInsetsController fakeWindowInsetsController = mock(WindowInsetsController.class); when(fakeWindow.getInsetsController()).thenReturn(fakeWindowInsetsController); SystemChromeStyle style = new SystemChromeStyle( null, // statusBarColor null, // statusBarIconBrightness null, // systemStatusBarContrastEnforced null, // systemNavigationBarColor Brightness.LIGHT, // systemNavigationBarIconBrightness null, // systemNavigationBarDividerColor null); // systemNavigationBarContrastEnforced platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindowInsetsController) .setSystemBarsAppearance(0, APPEARANCE_LIGHT_NAVIGATION_BARS); style = new SystemChromeStyle( null, // statusBarColor null, // statusBarIconBrightness null, // systemStatusBarContrastEnforced null, // systemNavigationBarColor Brightness.DARK, // systemNavigationBarIconBrightness null, // systemNavigationBarDividerColor null); // systemNavigationBarContrastEnforced platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindowInsetsController) .setSystemBarsAppearance( APPEARANCE_LIGHT_NAVIGATION_BARS, APPEARANCE_LIGHT_NAVIGATION_BARS); } } @Config(sdk = API_LEVELS.API_30) @Test public void setStatusBarIconBrightness() { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); if (Build.VERSION.SDK_INT >= API_LEVELS.API_30) { WindowInsetsController fakeWindowInsetsController = mock(WindowInsetsController.class); when(fakeWindow.getInsetsController()).thenReturn(fakeWindowInsetsController); SystemChromeStyle style = new SystemChromeStyle( null, // statusBarColor Brightness.LIGHT, // statusBarIconBrightness null, // systemStatusBarContrastEnforced null, // systemNavigationBarColor null, // systemNavigationBarIconBrightness null, // systemNavigationBarDividerColor null); // systemNavigationBarContrastEnforced platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindowInsetsController).setSystemBarsAppearance(0, APPEARANCE_LIGHT_STATUS_BARS); style = new SystemChromeStyle( null, // statusBarColor Brightness.DARK, // statusBarIconBrightness null, // systemStatusBarContrastEnforced null, // systemNavigationBarColor null, // systemNavigationBarIconBrightness null, // systemNavigationBarDividerColor null); // systemNavigationBarContrastEnforced platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindowInsetsController) .setSystemBarsAppearance(APPEARANCE_LIGHT_STATUS_BARS, APPEARANCE_LIGHT_STATUS_BARS); } } @SuppressWarnings("deprecation") // SYSTEM_UI_FLAG_*, setSystemUiVisibility @Config(sdk = API_LEVELS.API_29) @Test public void setSystemUiMode() { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { platformPlugin.mPlatformMessageHandler.showSystemUiMode( PlatformChannel.SystemUiMode.LEAN_BACK); verify(fakeDecorView) .setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); platformPlugin.mPlatformMessageHandler.showSystemUiMode( PlatformChannel.SystemUiMode.IMMERSIVE); verify(fakeDecorView) .setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); platformPlugin.mPlatformMessageHandler.showSystemUiMode( PlatformChannel.SystemUiMode.IMMERSIVE_STICKY); verify(fakeDecorView) .setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } if (Build.VERSION.SDK_INT >= API_LEVELS.API_29) { platformPlugin.mPlatformMessageHandler.showSystemUiMode( PlatformChannel.SystemUiMode.EDGE_TO_EDGE); verify(fakeDecorView) .setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } } @SuppressWarnings("deprecation") // SYSTEM_UI_FLAG_FULLSCREEN @Test public void setSystemUiModeListener_overlaysAreHidden() { ActivityController<Activity> controller = Robolectric.buildActivity(Activity.class); controller.setup(); Activity fakeActivity = controller.get(); PlatformPlugin platformPlugin = new PlatformPlugin(fakeActivity, mockPlatformChannel); // Subscribe to system UI visibility events. platformPlugin.mPlatformMessageHandler.setSystemUiChangeListener(); // Simulate system UI changed to full screen. fakeActivity .getWindow() .getDecorView() .dispatchSystemUiVisibilityChanged(View.SYSTEM_UI_FLAG_FULLSCREEN); // No events should have been sent to the platform channel yet. They are scheduled for // the next frame. verify(mockPlatformChannel, never()).systemChromeChanged(anyBoolean()); // Simulate the next frame. ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); // Now the platform channel should receive the event. verify(mockPlatformChannel).systemChromeChanged(false); } @SuppressWarnings("deprecation") // dispatchSystemUiVisibilityChanged @Test public void setSystemUiModeListener_overlaysAreVisible() { ActivityController<Activity> controller = Robolectric.buildActivity(Activity.class); controller.setup(); Activity fakeActivity = controller.get(); PlatformPlugin platformPlugin = new PlatformPlugin(fakeActivity, mockPlatformChannel); // Subscribe to system Ui visibility events. platformPlugin.mPlatformMessageHandler.setSystemUiChangeListener(); // Simulate system UI changed to *not* full screen. fakeActivity.getWindow().getDecorView().dispatchSystemUiVisibilityChanged(0); // No events should have been sent to the platform channel yet. They are scheduled for // the next frame. verify(mockPlatformChannel, never()).systemChromeChanged(anyBoolean()); // Simulate the next frame. ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); // Now the platform channel should receive the event. verify(mockPlatformChannel).systemChromeChanged(true); } @SuppressWarnings("deprecation") // SYSTEM_UI_FLAG_*, setSystemUiVisibility @Config(sdk = API_LEVELS.API_28) @Test public void doNotEnableEdgeToEdgeOnOlderSdk() { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); platformPlugin.mPlatformMessageHandler.showSystemUiMode( PlatformChannel.SystemUiMode.EDGE_TO_EDGE); verify(fakeDecorView, never()) .setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } @SuppressWarnings("deprecation") // FLAG_TRANSLUCENT_STATUS, FLAG_TRANSLUCENT_NAVIGATION @Config(sdk = API_LEVELS.API_29) @Test public void verifyWindowFlagsSetToStyleOverlays() { View fakeDecorView = mock(View.class); Window fakeWindow = mock(Window.class); Activity mockActivity = mock(Activity.class); when(fakeWindow.getDecorView()).thenReturn(fakeDecorView); when(mockActivity.getWindow()).thenReturn(fakeWindow); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); SystemChromeStyle style = new SystemChromeStyle( 0XFF000000, Brightness.LIGHT, true, 0XFFC70039, Brightness.LIGHT, 0XFF006DB3, true); platformPlugin.mPlatformMessageHandler.setSystemUiOverlayStyle(style); verify(fakeWindow).addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); verify(fakeWindow) .clearFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } @Test public void setFrameworkHandlesBackFlutterActivity() { Activity mockActivity = mock(Activity.class); PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); platformPlugin.mPlatformMessageHandler.setFrameworkHandlesBack(true); verify(mockPlatformPluginDelegate, times(1)).setFrameworkHandlesBack(true); } @Test public void testPlatformPluginDelegateNull() throws Exception { Activity mockActivity = mock(Activity.class); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel, null /*platformPluginDelegate*/); try { platformPlugin.mPlatformMessageHandler.setFrameworkHandlesBack(true); } catch (NullPointerException e) { // Not expected fail("NullPointerException was thrown"); } } @Test public void popSystemNavigatorFlutterActivity() { Activity mockActivity = mock(Activity.class); PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(false); platformPlugin.mPlatformMessageHandler.popSystemNavigator(); verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); verify(mockActivity, times(1)).finish(); } @Test public void doesNotDoAnythingByDefaultIfPopSystemNavigatorOverridden() { Activity mockActivity = mock(Activity.class); PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(true); platformPlugin.mPlatformMessageHandler.popSystemNavigator(); verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); // No longer perform the default action when overridden. verify(mockActivity, never()).finish(); } @SuppressWarnings("deprecation") // Robolectric.setupActivity. // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 @Test public void popSystemNavigatorFlutterFragment() { // Migrate to ActivityScenario by following https://github.com/robolectric/robolectric/pull/4736 FragmentActivity activity = spy(Robolectric.setupActivity(FragmentActivity.class)); final AtomicBoolean onBackPressedCalled = new AtomicBoolean(false); OnBackPressedCallback backCallback = new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { onBackPressedCalled.set(true); } }; activity.getOnBackPressedDispatcher().addCallback(backCallback); PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(false); PlatformPlugin platformPlugin = new PlatformPlugin(activity, mockPlatformChannel, mockPlatformPluginDelegate); platformPlugin.mPlatformMessageHandler.popSystemNavigator(); verify(activity, never()).finish(); verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); assertTrue(onBackPressedCalled.get()); } @SuppressWarnings("deprecation") // Robolectric.setupActivity. // TODO(reidbaker): https://github.com/flutter/flutter/issues/133151 @Test public void doesNotDoAnythingByDefaultIfFragmentPopSystemNavigatorOverridden() { FragmentActivity activity = spy(Robolectric.setupActivity(FragmentActivity.class)); PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(true); PlatformPlugin platformPlugin = new PlatformPlugin(activity, mockPlatformChannel, mockPlatformPluginDelegate); platformPlugin.mPlatformMessageHandler.popSystemNavigator(); verify(mockPlatformPluginDelegate, times(1)).popSystemNavigator(); // No longer perform the default action when overridden. verify(activity, never()).finish(); } @Test public void setRequestedOrientationFlutterFragment() { FragmentActivity mockFragmentActivity = mock(FragmentActivity.class); PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); when(mockPlatformPluginDelegate.popSystemNavigator()).thenReturn(false); PlatformPlugin platformPlugin = new PlatformPlugin(mockFragmentActivity, mockPlatformChannel, mockPlatformPluginDelegate); platformPlugin.mPlatformMessageHandler.setPreferredOrientations(0); verify(mockFragmentActivity, times(1)).setRequestedOrientation(0); } @Test public void performsDefaultBehaviorWhenNoDelegateProvided() { Activity mockActivity = mock(Activity.class); PlatformChannel mockPlatformChannel = mock(PlatformChannel.class); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel); platformPlugin.mPlatformMessageHandler.popSystemNavigator(); verify(mockActivity, times(1)).finish(); } @Test public void startChoosenActivityWhenSharingText() { Activity mockActivity = mock(Activity.class); PlatformChannel mockPlatformChannel = mock(PlatformChannel.class); PlatformPluginDelegate mockPlatformPluginDelegate = mock(PlatformPluginDelegate.class); PlatformPlugin platformPlugin = new PlatformPlugin(mockActivity, mockPlatformChannel, mockPlatformPluginDelegate); // Mock Intent.createChooser (in real application it opens a chooser where the user can // select which application will be used to share the selected text). Intent choosenIntent = new Intent(); MockedStatic<Intent> intentClass = mockStatic(Intent.class); ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); intentClass .when(() -> Intent.createChooser(intentCaptor.capture(), any())) .thenReturn(choosenIntent); final String expectedContent = "Flutter"; platformPlugin.mPlatformMessageHandler.share(expectedContent); // Activity.startActivity should have been called. verify(mockActivity, times(1)).startActivity(choosenIntent); // The intent action created by the plugin and passed to Intent.createChooser should be // 'Intent.ACTION_SEND'. Intent sendToIntent = intentCaptor.getValue(); assertEquals(sendToIntent.getAction(), Intent.ACTION_SEND); assertEquals(sendToIntent.getType(), "text/plain"); assertEquals(sendToIntent.getStringExtra(Intent.EXTRA_TEXT), expectedContent); } }
engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformPluginTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/platform/PlatformPluginTest.java", "repo_id": "engine", "token_count": 11381 }
318
// 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/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h" #include <memory> #include <string> #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h" #include "gtest/gtest.h" namespace flutter { namespace { class TestBinaryMessenger : public BinaryMessenger { public: void Send(const std::string& channel, const uint8_t* message, const size_t message_size, BinaryReply reply) const override { send_called_ = true; int length = static_cast<int>(message_size); last_message_ = std::vector<uint8_t>(message, message + length * sizeof(uint8_t)); } void SetMessageHandler(const std::string& channel, BinaryMessageHandler handler) override { last_message_handler_channel_ = channel; last_message_handler_ = handler; } bool send_called() { return send_called_; } std::string last_message_handler_channel() { return last_message_handler_channel_; } BinaryMessageHandler last_message_handler() { return last_message_handler_; } std::vector<uint8_t> last_message() { return last_message_; } private: mutable bool send_called_ = false; std::string last_message_handler_channel_; BinaryMessageHandler last_message_handler_; mutable std::vector<uint8_t> last_message_; }; } // namespace // Tests that SetMessageHandler sets a handler that correctly interacts with // the binary messenger. TEST(BasicMessageChannelTest, Registration) { TestBinaryMessenger messenger; const std::string channel_name("some_channel"); const StandardMessageCodec& codec = StandardMessageCodec::GetInstance(); BasicMessageChannel channel(&messenger, channel_name, &codec); bool callback_called = false; const std::string message_value("hello"); channel.SetMessageHandler( [&callback_called, message_value](const auto& message, auto reply) { callback_called = true; // Ensure that the wrapper received a correctly decoded message and a // reply. EXPECT_EQ(std::get<std::string>(message), message_value); EXPECT_NE(reply, nullptr); }); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_NE(messenger.last_message_handler(), nullptr); // Send a test message to trigger the handler test assertions. auto message = codec.EncodeMessage(EncodableValue(message_value)); messenger.last_message_handler()( message->data(), message->size(), [](const uint8_t* reply, const size_t reply_size) {}); EXPECT_EQ(callback_called, true); } // Tests that SetMessageHandler with a null handler unregisters the handler. TEST(BasicMessageChannelTest, Unregistration) { TestBinaryMessenger messenger; const std::string channel_name("some_channel"); BasicMessageChannel channel(&messenger, channel_name, &flutter::StandardMessageCodec::GetInstance()); channel.SetMessageHandler([](const auto& message, auto reply) {}); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_NE(messenger.last_message_handler(), nullptr); channel.SetMessageHandler(nullptr); EXPECT_EQ(messenger.last_message_handler_channel(), channel_name); EXPECT_EQ(messenger.last_message_handler(), nullptr); } // Tests that calling Resize generates the binary message expected by the Dart // implementation. TEST(BasicMessageChannelTest, Resize) { TestBinaryMessenger messenger; const std::string channel_name("flutter/test"); BasicMessageChannel channel(&messenger, channel_name, &flutter::StandardMessageCodec::GetInstance()); channel.Resize(3); // Because the Dart implementation for the control channel implements its own // custom deserialization logic, this test compares the generated bytes array // to the expected one (for instance, the deserialization logic expects the // size parameter of the resize method call to be an uint32). // // The expected content was created from the following Dart code: // MethodCall call = MethodCall('resize', ['flutter/test',3]); // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); const int expected_message_size = 29; EXPECT_EQ(messenger.send_called(), true); EXPECT_EQ(static_cast<int>(messenger.last_message().size()), expected_message_size); int expected[expected_message_size] = { 7, 6, 114, 101, 115, 105, 122, 101, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 3, 3, 0, 0, 0}; for (int i = 0; i < expected_message_size; i++) { EXPECT_EQ(messenger.last_message()[i], expected[i]); } } // Tests that calling SetWarnsOnOverflow generates the binary message expected // by the Dart implementation. TEST(BasicMessageChannelTest, SetWarnsOnOverflow) { TestBinaryMessenger messenger; const std::string channel_name("flutter/test"); BasicMessageChannel channel(&messenger, channel_name, &flutter::StandardMessageCodec::GetInstance()); channel.SetWarnsOnOverflow(false); // Because the Dart implementation for the control channel implements its own // custom deserialization logic, this test compares the generated bytes array // to the expected one. // // The expected content was created from the following Dart code: // MethodCall call = MethodCall('overflow',['flutter/test', true]); // StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List(); const int expected_message_size = 27; EXPECT_EQ(messenger.send_called(), true); EXPECT_EQ(static_cast<int>(messenger.last_message().size()), expected_message_size); int expected[expected_message_size] = { 7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12, 102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1}; for (int i = 0; i < expected_message_size; i++) { EXPECT_EQ(messenger.last_message()[i], expected[i]); } } } // namespace flutter
engine/shell/platform/common/client_wrapper/basic_message_channel_unittests.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/basic_message_channel_unittests.cc", "repo_id": "engine", "token_count": 2126 }
319
// 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_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_FUNCTIONS_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_FUNCTIONS_H_ #include <memory> #include "event_sink.h" #include "event_stream_handler.h" namespace flutter { class EncodableValue; // Handler types for each of the StreamHandler setup and teardown // requests. template <typename T> using StreamHandlerListen = std::function<std::unique_ptr<StreamHandlerError<T>>( const T* arguments, std::unique_ptr<EventSink<T>>&& events)>; template <typename T> using StreamHandlerCancel = std::function<std::unique_ptr<StreamHandlerError<T>>(const T* arguments)>; // An implementation of StreamHandler that pass calls through to // provided function objects. template <typename T = EncodableValue> class StreamHandlerFunctions : public StreamHandler<T> { public: // Creates a handler object that calls the provided functions // for the corresponding StreamHandler outcomes. StreamHandlerFunctions(StreamHandlerListen<T> on_listen, StreamHandlerCancel<T> on_cancel) : on_listen_(on_listen), on_cancel_(on_cancel) {} virtual ~StreamHandlerFunctions() = default; // Prevent copying. StreamHandlerFunctions(StreamHandlerFunctions const&) = delete; StreamHandlerFunctions& operator=(StreamHandlerFunctions const&) = delete; protected: // |flutter::StreamHandler| std::unique_ptr<StreamHandlerError<T>> OnListenInternal( const T* arguments, std::unique_ptr<EventSink<T>>&& events) override { if (on_listen_) { return on_listen_(arguments, std::move(events)); } auto error = std::make_unique<StreamHandlerError<T>>( "error", "No OnListen handler set", nullptr); return std::move(error); } // |flutter::StreamHandler| std::unique_ptr<StreamHandlerError<T>> OnCancelInternal( const T* arguments) override { if (on_cancel_) { return on_cancel_(arguments); } auto error = std::make_unique<StreamHandlerError<T>>( "error", "No OnCancel handler set", nullptr); return std::move(error); } StreamHandlerListen<T> on_listen_; StreamHandlerCancel<T> on_cancel_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_EVENT_STREAM_HANDLER_FUNCTIONS_H_
engine/shell/platform/common/client_wrapper/include/flutter/event_stream_handler_functions.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/event_stream_handler_functions.h", "repo_id": "engine", "token_count": 915 }
320
// 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/plugin_registrar.h" #include <iostream> #include <map> #include "binary_messenger_impl.h" #include "include/flutter/engine_method_result.h" #include "include/flutter/method_channel.h" #include "texture_registrar_impl.h" namespace flutter { // ===== PluginRegistrar ===== PluginRegistrar::PluginRegistrar(FlutterDesktopPluginRegistrarRef registrar) : registrar_(registrar) { auto core_messenger = FlutterDesktopPluginRegistrarGetMessenger(registrar_); messenger_ = std::make_unique<BinaryMessengerImpl>(core_messenger); auto texture_registrar = FlutterDesktopRegistrarGetTextureRegistrar(registrar_); texture_registrar_ = std::make_unique<TextureRegistrarImpl>(texture_registrar); } PluginRegistrar::~PluginRegistrar() { // This must always be the first call. ClearPlugins(); // Explicitly cleared to facilitate testing of destruction order. messenger_.reset(); } void PluginRegistrar::AddPlugin(std::unique_ptr<Plugin> plugin) { plugins_.insert(std::move(plugin)); } void PluginRegistrar::ClearPlugins() { plugins_.clear(); } // ===== PluginRegistrarManager ===== // static PluginRegistrarManager* PluginRegistrarManager::GetInstance() { static PluginRegistrarManager* instance = new PluginRegistrarManager(); return instance; } PluginRegistrarManager::PluginRegistrarManager() = default; // static void PluginRegistrarManager::OnRegistrarDestroyed( FlutterDesktopPluginRegistrarRef registrar) { GetInstance()->registrars()->erase(registrar); } } // namespace flutter
engine/shell/platform/common/client_wrapper/plugin_registrar.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/plugin_registrar.cc", "repo_id": "engine", "token_count": 545 }
321
// 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_SHELL_PLATFORM_COMMON_FLUTTER_PLATFORM_NODE_DELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_FLUTTER_PLATFORM_NODE_DELEGATE_H_ #include "flutter/fml/mapping.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/third_party/accessibility/ax/ax_event_generator.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.h" namespace flutter { typedef ui::AXNode::AXID AccessibilityNodeId; //------------------------------------------------------------------------------ /// The platform node delegate to be used in accessibility bridge. This /// class is responsible for providing native accessibility object with /// appropriate information, such as accessibility label/value/bounds. /// /// While most methods have default implementations and are ready to be used /// as-is, the subclasses must override the GetNativeViewAccessible to return /// native accessibility objects. To do that, subclasses should create and /// maintain AXPlatformNode[s] which delegate their accessibility attributes to /// this class. /// /// For desktop platforms, subclasses also need to override the GetBoundsRect /// to apply window-to-screen transform. /// /// This class transforms bounds assuming the device pixel ratio is 1.0. See /// the https://github.com/flutter/flutter/issues/74283 for more information. class FlutterPlatformNodeDelegate : public ui::AXPlatformNodeDelegateBase { public: //---------------------------------------------------------------------------- /// The required interface to be able to own the flutter platform node /// delegate. class OwnerBridge { public: virtual ~OwnerBridge() = default; //--------------------------------------------------------------------------- /// @brief Gets the rectangular bounds of the ax node relative to /// global coordinate /// /// @param[in] node The ax node to look up. /// @param[in] offscreen the bool reference to hold the result whether /// the ax node is outside of its ancestors' bounds. /// @param[in] clip_bounds whether to clip the result if the ax node cannot /// be fully contained in its ancestors' bounds. virtual gfx::RectF RelativeToGlobalBounds(const ui::AXNode* node, bool& offscreen, bool clip_bounds) = 0; protected: friend class FlutterPlatformNodeDelegate; //--------------------------------------------------------------------------- /// @brief Dispatch accessibility action back to the Flutter framework. /// These actions are generated in the native accessibility /// system when users interact with the assistive technologies. /// For example, a /// FlutterSemanticsAction::kFlutterSemanticsActionTap is /// fired when user click or touch the screen. /// /// @param[in] target The semantics node id of the action /// target. /// @param[in] action The generated flutter semantics action. /// @param[in] data Additional data associated with the /// action. virtual void DispatchAccessibilityAction(AccessibilityNodeId target, FlutterSemanticsAction action, fml::MallocMapping data) = 0; //--------------------------------------------------------------------------- /// @brief Get the native accessibility node with the given id. /// /// @param[in] id The id of the native accessibility node you /// want to retrieve. virtual gfx::NativeViewAccessible GetNativeAccessibleFromId( AccessibilityNodeId id) = 0; //--------------------------------------------------------------------------- /// @brief Get the last id of the node that received accessibility /// focus. virtual AccessibilityNodeId GetLastFocusedId() = 0; //--------------------------------------------------------------------------- /// @brief Update the id of the node that is currently foucsed by the /// native accessibility system. /// /// @param[in] node_id The id of the focused node. virtual void SetLastFocusedId(AccessibilityNodeId node_id) = 0; }; FlutterPlatformNodeDelegate(); // |ui::AXPlatformNodeDelegateBase| virtual ~FlutterPlatformNodeDelegate() override; // |ui::AXPlatformNodeDelegateBase| const ui::AXUniqueId& GetUniqueId() const override { return unique_id_; } // |ui::AXPlatformNodeDelegateBase| const ui::AXNodeData& GetData() const override; // |ui::AXPlatformNodeDelegateBase| bool AccessibilityPerformAction(const ui::AXActionData& data) override; // |ui::AXPlatformNodeDelegateBase| gfx::NativeViewAccessible GetParent() override; // |ui::AXPlatformNodeDelegateBase| gfx::NativeViewAccessible GetFocus() override; // |ui::AXPlatformNodeDelegateBase| int GetChildCount() const override; // |ui::AXPlatformNodeDelegateBase| gfx::NativeViewAccessible ChildAtIndex(int index) override; // |ui::AXPlatformNodeDelegateBase| gfx::Rect GetBoundsRect( const ui::AXCoordinateSystem coordinate_system, const ui::AXClippingBehavior clipping_behavior, ui::AXOffscreenResult* offscreen_result) const override; // |ui::AXPlatformNodeDelegateBase| gfx::NativeViewAccessible GetLowestPlatformAncestor() const override; // |ui::AXPlatformNodeDelegateBase| ui::AXNodePosition::AXPositionInstance CreateTextPositionAt( int offset) const override; //------------------------------------------------------------------------------ /// @brief Called only once, immediately after construction. The /// constructor doesn't take any arguments because in the Windows /// subclass we use a special function to construct a COM object. /// Subclasses must call super. virtual void Init(std::weak_ptr<OwnerBridge> bridge, ui::AXNode* node); //------------------------------------------------------------------------------ /// @brief Gets the underlying ax node for this platform node delegate. ui::AXNode* GetAXNode() const; //------------------------------------------------------------------------------ /// @brief Gets the owner of this platform node delegate. This is useful /// when you want to get the information about surrounding nodes /// of this platform node delegate, e.g. the global rect of this /// platform node delegate. This pointer is only safe in the /// platform thread. std::weak_ptr<OwnerBridge> GetOwnerBridge() const; // Get the platform node represented by this delegate. virtual ui::AXPlatformNode* GetPlatformNode() const; // |ui::AXPlatformNodeDelegateBase| virtual ui::AXPlatformNode* GetFromNodeID(int32_t id) override; // |ui::AXPlatformNodeDelegateBase| virtual ui::AXPlatformNode* GetFromTreeIDAndNodeID( const ui::AXTreeID& tree_id, int32_t node_id) override; // |ui::AXPlatformNodeDelegateBase| virtual const ui::AXTree::Selection GetUnignoredSelection() const override; private: ui::AXNode* ax_node_; std::weak_ptr<OwnerBridge> bridge_; ui::AXUniqueId unique_id_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_FLUTTER_PLATFORM_NODE_DELEGATE_H_
engine/shell/platform/common/flutter_platform_node_delegate.h/0
{ "file_path": "engine/shell/platform/common/flutter_platform_node_delegate.h", "repo_id": "engine", "token_count": 2587 }
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. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_ namespace flutter { // Enumerates the provided menus that a platform may support. // Must be kept in sync with the framework enum in widgets/menu.dart. enum class PlatformProvidedMenu { // orderFrontStandardAboutPanel macOS provided menu kAbout, // terminate macOS provided menu kQuit, // Services macOS provided submenu. kServicesSubmenu, // hide macOS provided menu kHide, // hideOtherApplications macOS provided menu kHideOtherApplications, // unhideAllApplications macOS provided menu kShowAllApplications, // startSpeaking macOS provided menu kStartSpeaking, // stopSpeaking macOS provided menu kStopSpeaking, // toggleFullScreen macOS provided menu kToggleFullScreen, // performMiniaturize macOS provided menu kMinimizeWindow, // performZoom macOS provided menu kZoomWindow, // arrangeInFront macOS provided menu kArrangeWindowsInFront, }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_
engine/shell/platform/common/platform_provided_menu.h/0
{ "file_path": "engine/shell/platform/common/platform_provided_menu.h", "repo_id": "engine", "token_count": 382 }
323
# 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. declare_args() { # Whether or not to include desktop embedding targets in the build. enable_desktop_embeddings = true }
engine/shell/platform/config.gni/0
{ "file_path": "engine/shell/platform/config.gni", "repo_id": "engine", "token_count": 78 }
324