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. #include "impeller/core/allocator.h" #include "impeller/base/validation.h" #include "impeller/core/device_buffer.h" #include "impeller/core/formats.h" #include "impeller/core/range.h" namespace impeller { Allocator::Allocator() = default; Allocator::~Allocator() = default; std::shared_ptr<DeviceBuffer> Allocator::CreateBufferWithCopy( const uint8_t* buffer, size_t length) { DeviceBufferDescriptor desc; desc.size = length; desc.storage_mode = StorageMode::kHostVisible; auto new_buffer = CreateBuffer(desc); if (!new_buffer) { return nullptr; } auto entire_range = Range{0, length}; if (!new_buffer->CopyHostBuffer(buffer, entire_range)) { return nullptr; } return new_buffer; } std::shared_ptr<DeviceBuffer> Allocator::CreateBufferWithCopy( const fml::Mapping& mapping) { return CreateBufferWithCopy(mapping.GetMapping(), mapping.GetSize()); } std::shared_ptr<DeviceBuffer> Allocator::CreateBuffer( const DeviceBufferDescriptor& desc) { return OnCreateBuffer(desc); } std::shared_ptr<Texture> Allocator::CreateTexture( const TextureDescriptor& desc) { const auto max_size = GetMaxTextureSizeSupported(); if (desc.size.width > max_size.width || desc.size.height > max_size.height) { VALIDATION_LOG << "Requested texture size " << desc.size << " exceeds maximum supported size of " << max_size; return nullptr; } if (desc.mip_count > desc.size.MipCount()) { VALIDATION_LOG << "Requested mip_count " << desc.mip_count << " exceeds maximum supported for size " << desc.size; TextureDescriptor corrected_desc = desc; corrected_desc.mip_count = desc.size.MipCount(); return OnCreateTexture(corrected_desc); } return OnCreateTexture(desc); } uint16_t Allocator::MinimumBytesPerRow(PixelFormat format) const { return BytesPerPixelForPixelFormat(format); } } // namespace impeller
engine/impeller/core/allocator.cc/0
{ "file_path": "engine/impeller/core/allocator.cc", "repo_id": "engine", "token_count": 730 }
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_IMPELLER_CORE_PLATFORM_H_ #define FLUTTER_IMPELLER_CORE_PLATFORM_H_ #include <cstddef> #include "flutter/fml/build_config.h" #include "flutter/fml/macros.h" namespace impeller { constexpr size_t DefaultUniformAlignment() { #if FML_OS_IOS && !TARGET_OS_SIMULATOR return 16u; #else return 256u; #endif } } // namespace impeller #endif // FLUTTER_IMPELLER_CORE_PLATFORM_H_
engine/impeller/core/platform.h/0
{ "file_path": "engine/impeller/core/platform.h", "repo_id": "engine", "token_count": 218 }
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. #ifndef FLUTTER_IMPELLER_CORE_TEXTURE_DESCRIPTOR_H_ #define FLUTTER_IMPELLER_CORE_TEXTURE_DESCRIPTOR_H_ #include "impeller/core/formats.h" #include "impeller/geometry/size.h" namespace impeller { //------------------------------------------------------------------------------ /// @brief Additional compression to apply to a texture. This value is /// ignored on platforms which do not support it. /// /// Lossy compression is only supported on iOS 15+ on A15 chips. enum class CompressionType { kLossless, kLossy, }; constexpr const char* CompressionTypeToString(CompressionType type) { switch (type) { case CompressionType::kLossless: return "Lossless"; case CompressionType::kLossy: return "Lossy"; } FML_UNREACHABLE(); } //------------------------------------------------------------------------------ /// @brief A lightweight object that describes the attributes of a texture /// that can then used an allocator to create that texture. /// struct TextureDescriptor { StorageMode storage_mode = StorageMode::kDeviceTransient; TextureType type = TextureType::kTexture2D; PixelFormat format = PixelFormat::kUnknown; ISize size; size_t mip_count = 1u; // Size::MipCount is usually appropriate. TextureUsageMask usage = TextureUsage::kShaderRead; SampleCount sample_count = SampleCount::kCount1; CompressionType compression_type = CompressionType::kLossless; constexpr size_t GetByteSizeOfBaseMipLevel() const { if (!IsValid()) { return 0u; } return size.Area() * BytesPerPixelForPixelFormat(format); } constexpr size_t GetBytesPerRow() const { if (!IsValid()) { return 0u; } return size.width * BytesPerPixelForPixelFormat(format); } constexpr bool SamplingOptionsAreValid() const { const auto count = static_cast<uint64_t>(sample_count); return IsMultisampleCapable(type) ? count > 1 : count == 1; } constexpr bool operator==(const TextureDescriptor& other) const { return size == other.size && // storage_mode == other.storage_mode && // format == other.format && // usage == other.usage && // sample_count == other.sample_count && // type == other.type && // compression_type == other.compression_type && // mip_count == other.mip_count; } constexpr bool operator!=(const TextureDescriptor& other) const { return !(*this == other); } constexpr bool IsValid() const { return format != PixelFormat::kUnknown && // !size.IsEmpty() && // mip_count >= 1u && // SamplingOptionsAreValid(); } }; std::string TextureDescriptorToString(const TextureDescriptor& desc); } // namespace impeller #endif // FLUTTER_IMPELLER_CORE_TEXTURE_DESCRIPTOR_H_
engine/impeller/core/texture_descriptor.h/0
{ "file_path": "engine/impeller/core/texture_descriptor.h", "repo_id": "engine", "token_count": 1186 }
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_IMPELLER_DISPLAY_LIST_SKIA_CONVERSIONS_H_ #define FLUTTER_IMPELLER_DISPLAY_LIST_SKIA_CONVERSIONS_H_ #include "display_list/dl_color.h" #include "display_list/effects/dl_color_source.h" #include "impeller/core/formats.h" #include "impeller/geometry/color.h" #include "impeller/geometry/path.h" #include "impeller/geometry/path_builder.h" #include "impeller/geometry/point.h" #include "impeller/geometry/rect.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/core/SkPoint.h" #include "third_party/skia/include/core/SkRRect.h" #include "third_party/skia/include/core/SkRSXform.h" #include "third_party/skia/include/core/SkTextBlob.h" namespace impeller { namespace skia_conversions { Rect ToRect(const SkRect& rect); std::optional<Rect> ToRect(const SkRect* rect); std::vector<Rect> ToRects(const SkRect tex[], int count); std::vector<Point> ToPoints(const SkPoint points[], int count); Point ToPoint(const SkPoint& point); Size ToSize(const SkPoint& point); Color ToColor(const flutter::DlColor& color); std::vector<Matrix> ToRSXForms(const SkRSXform xform[], int count); PathBuilder::RoundingRadii ToRoundingRadii(const SkRRect& rrect); Path ToPath(const SkPath& path, Point shift = Point(0, 0)); Path ToPath(const SkRRect& rrect); Path PathDataFromTextBlob(const sk_sp<SkTextBlob>& blob, Point shift = Point(0, 0)); std::optional<impeller::PixelFormat> ToPixelFormat(SkColorType type); /// @brief Convert display list colors + stops into impeller colors and stops, /// taking care to ensure that the stops monotonically increase from 0.0 to 1.0. /// /// The general process is: /// * Ensure that the first gradient stop value is 0.0. If not, insert a new /// stop with a value of 0.0 and use the first gradient color as this new /// stops color. /// * Ensure the last gradient stop value is 1.0. If not, insert a new stop /// with a value of 1.0 and use the last gradient color as this stops color. /// * Clamp all gradient values between the values of 0.0 and 1.0. /// * For all stop values, ensure that the values are monotonically increasing /// by clamping each value to a minimum of the previous stop value and itself. /// For example, with stop values of 0.0, 0.5, 0.4, 1.0, we would clamp such /// that the values were 0.0, 0.5, 0.5, 1.0. void ConvertStops(const flutter::DlGradientColorSourceBase* gradient, std::vector<Color>& colors, std::vector<float>& stops); } // namespace skia_conversions } // namespace impeller #endif // FLUTTER_IMPELLER_DISPLAY_LIST_SKIA_CONVERSIONS_H_
engine/impeller/display_list/skia_conversions.h/0
{ "file_path": "engine/impeller/display_list/skia_conversions.h", "repo_id": "engine", "token_count": 1032 }
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. #ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_ANONYMOUS_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_ANONYMOUS_CONTENTS_H_ #include <functional> #include <memory> #include "flutter/fml/macros.h" #include "impeller/entity/contents/contents.h" namespace impeller { class AnonymousContents final : public Contents { public: static std::shared_ptr<Contents> Make(RenderProc render_proc, CoverageProc coverage_proc); // |Contents| ~AnonymousContents() override; // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; // |Contents| std::optional<Rect> GetCoverage(const Entity& entity) const override; private: RenderProc render_proc_; CoverageProc coverage_proc_; AnonymousContents(RenderProc render_proc, CoverageProc coverage_proc); AnonymousContents(const AnonymousContents&) = delete; AnonymousContents& operator=(const AnonymousContents&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_ANONYMOUS_CONTENTS_H_
engine/impeller/entity/contents/anonymous_contents.h/0
{ "file_path": "engine/impeller/entity/contents/anonymous_contents.h", "repo_id": "engine", "token_count": 443 }
243
// 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_ENTITY_CONTENTS_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENTS_H_ #include <functional> #include <memory> #include <vector> #include "flutter/fml/macros.h" #include "impeller/core/sampler_descriptor.h" #include "impeller/core/texture.h" #include "impeller/geometry/color.h" #include "impeller/geometry/rect.h" #include "impeller/renderer/snapshot.h" #include "impeller/typographer/lazy_glyph_atlas.h" namespace impeller { class ContentContext; struct ContentContextOptions; class Entity; class Surface; class RenderPass; class FilterContents; ContentContextOptions OptionsFromPass(const RenderPass& pass); ContentContextOptions OptionsFromPassAndEntity(const RenderPass& pass, const Entity& entity); class Contents { public: /// A procedure that filters a given unpremultiplied color to produce a new /// unpremultiplied color. using ColorFilterProc = std::function<Color(Color)>; struct ClipCoverage { enum class Type { kNoChange, kAppend, kRestore }; Type type = Type::kNoChange; std::optional<Rect> coverage = std::nullopt; }; using RenderProc = std::function<bool(const ContentContext& renderer, const Entity& entity, RenderPass& pass)>; using CoverageProc = std::function<std::optional<Rect>(const Entity& entity)>; static std::shared_ptr<Contents> MakeAnonymous(RenderProc render_proc, CoverageProc coverage_proc); Contents(); virtual ~Contents(); /// @brief Add any text data to the specified lazy atlas. The scale parameter /// must be used again later when drawing the text. virtual void PopulateGlyphAtlas( const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas, Scalar scale) {} virtual bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const = 0; //---------------------------------------------------------------------------- /// @brief Get the area of the render pass that will be affected when this /// contents is rendered. /// /// During rendering, coverage coordinates count pixels from the top /// left corner of the framebuffer. /// /// @return The coverage rectangle. An `std::nullopt` result means that /// rendering this contents has no effect on the output color. /// virtual std::optional<Rect> GetCoverage(const Entity& entity) const = 0; //---------------------------------------------------------------------------- /// @brief Hint that specifies the coverage area of this Contents that will /// actually be used during rendering. This is for optimization /// purposes only and can not be relied on as a clip. May optionally /// affect the result of `GetCoverage()`. /// void SetCoverageHint(std::optional<Rect> coverage_hint); const std::optional<Rect>& GetCoverageHint() const; //---------------------------------------------------------------------------- /// @brief Whether this Contents only emits opaque source colors from the /// fragment stage. This value does not account for any entity /// properties (e.g. the blend mode), clips/visibility culling, or /// inherited opacity. /// virtual bool IsOpaque() const; //---------------------------------------------------------------------------- /// @brief Given the current pass space bounding rectangle of the clip /// buffer, return the expected clip coverage after this draw call. /// This should only be implemented for contents that may write to the /// clip buffer. /// /// During rendering, coverage coordinates count pixels from the top /// left corner of the framebuffer. /// virtual ClipCoverage GetClipCoverage( const Entity& entity, const std::optional<Rect>& current_clip_coverage) const; //---------------------------------------------------------------------------- /// @brief Render this contents to a snapshot, respecting the entity's /// transform, path, clip depth, and blend mode. /// The result texture size is always the size of /// `GetCoverage(entity)`. /// virtual std::optional<Snapshot> RenderToSnapshot( const ContentContext& renderer, const Entity& entity, std::optional<Rect> coverage_limit = std::nullopt, const std::optional<SamplerDescriptor>& sampler_descriptor = std::nullopt, bool msaa_enabled = true, int32_t mip_count = 1, const std::string& label = "Snapshot") const; virtual bool ShouldRender(const Entity& entity, const std::optional<Rect> clip_coverage) const; //---------------------------------------------------------------------------- /// @brief Return the color source's intrinsic size, if available. /// /// For example, a gradient has a size based on its end and beginning /// points, ignoring any tiling. Solid colors and runtime effects have /// no size. /// std::optional<Size> GetColorSourceSize() const; void SetColorSourceSize(Size size); //---------------------------------------------------------------------------- /// @brief Whether or not this contents can accept the opacity peephole /// optimization. /// /// By default all contents return false. Contents are responsible /// for determining whether or not their own geometries intersect in /// a way that makes accepting opacity impossible. It is always safe /// to return false, especially if computing overlap would be /// computationally expensive. /// virtual bool CanInheritOpacity(const Entity& entity) const; //---------------------------------------------------------------------------- /// @brief Inherit the provided opacity. /// /// Use of this method is invalid if CanAcceptOpacity returns false. /// virtual void SetInheritedOpacity(Scalar opacity); //---------------------------------------------------------------------------- /// @brief Returns a color if this Contents will flood the given `target_size` /// with a color. This output color is the "Source" color that will be /// used for the Entity's blend operation. /// /// This is useful for absorbing full screen solid color draws into /// subpass clear colors. /// virtual std::optional<Color> AsBackgroundColor(const Entity& entity, ISize target_size) const; //---------------------------------------------------------------------------- /// @brief Cast to a filter. Returns `nullptr` if this Contents is not a /// filter. /// virtual const FilterContents* AsFilter() const; //---------------------------------------------------------------------------- /// @brief If possible, applies a color filter to this contents inputs on /// the CPU. /// /// This method will either fully apply the color filter or /// perform no action. Partial/incorrect application of the color /// filter will never occur. /// /// @param[in] color_filter_proc A function that filters a given /// unpremultiplied color to produce a new /// unpremultiplied color. /// /// @return True if the color filter was able to be fully applied to all /// all relevant inputs. Otherwise, this operation is a no-op and /// false is returned. /// [[nodiscard]] virtual bool ApplyColorFilter( const ColorFilterProc& color_filter_proc); private: std::optional<Rect> coverage_hint_; std::optional<Size> color_source_size_; Contents(const Contents&) = delete; Contents& operator=(const Contents&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENTS_H_
engine/impeller/entity/contents/contents.h/0
{ "file_path": "engine/impeller/entity/contents/contents.h", "repo_id": "engine", "token_count": 2690 }
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. #include "impeller/entity/contents/filters/inputs/filter_contents_filter_input.h" #include <utility> #include "impeller/base/strings.h" #include "impeller/entity/contents/filters/filter_contents.h" namespace impeller { FilterContentsFilterInput::FilterContentsFilterInput( std::shared_ptr<FilterContents> filter) : filter_(std::move(filter)) {} FilterContentsFilterInput::~FilterContentsFilterInput() = default; FilterInput::Variant FilterContentsFilterInput::GetInput() const { return filter_; } std::optional<Snapshot> FilterContentsFilterInput::GetSnapshot( const std::string& label, const ContentContext& renderer, const Entity& entity, std::optional<Rect> coverage_limit, int32_t mip_count) const { if (!snapshot_.has_value()) { snapshot_ = filter_->RenderToSnapshot( renderer, // renderer entity, // entity coverage_limit, // coverage_limit std::nullopt, // sampler_descriptor true, // msaa_enabled /*mip_count=*/mip_count, SPrintF("Filter to %s Filter Snapshot", label.c_str())); // label } return snapshot_; } std::optional<Rect> FilterContentsFilterInput::GetCoverage( const Entity& entity) const { return filter_->GetCoverage(entity); } std::optional<Rect> FilterContentsFilterInput::GetSourceCoverage( const Matrix& effect_transform, const Rect& output_limit) const { return filter_->GetSourceCoverage(effect_transform, output_limit); } Matrix FilterContentsFilterInput::GetLocalTransform( const Entity& entity) const { return filter_->GetLocalTransform(entity.GetTransform()); } Matrix FilterContentsFilterInput::GetTransform(const Entity& entity) const { return filter_->GetTransform(entity.GetTransform()); } void FilterContentsFilterInput::PopulateGlyphAtlas( const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas, Scalar scale) { filter_->PopulateGlyphAtlas(lazy_glyph_atlas, scale); } bool FilterContentsFilterInput::IsTranslationOnly() const { return filter_->IsTranslationOnly(); } bool FilterContentsFilterInput::IsLeaf() const { return false; } void FilterContentsFilterInput::SetLeafInputs( const FilterInput::Vector& inputs) { filter_->SetLeafInputs(inputs); } void FilterContentsFilterInput::SetEffectTransform(const Matrix& matrix) { filter_->SetEffectTransform(matrix); } void FilterContentsFilterInput::SetRenderingMode( Entity::RenderingMode rendering_mode) { filter_->SetRenderingMode(rendering_mode); } } // namespace impeller
engine/impeller/entity/contents/filters/inputs/filter_contents_filter_input.cc/0
{ "file_path": "engine/impeller/entity/contents/filters/inputs/filter_contents_filter_input.cc", "repo_id": "engine", "token_count": 916 }
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. #ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MORPHOLOGY_FILTER_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MORPHOLOGY_FILTER_CONTENTS_H_ #include <memory> #include <optional> #include "impeller/entity/contents/filters/filter_contents.h" #include "impeller/entity/contents/filters/inputs/filter_input.h" namespace impeller { class DirectionalMorphologyFilterContents final : public FilterContents { public: DirectionalMorphologyFilterContents(); ~DirectionalMorphologyFilterContents() override; void SetRadius(Radius radius); void SetDirection(Vector2 direction); void SetMorphType(MorphType morph_type); // |FilterContents| std::optional<Rect> GetFilterCoverage( const FilterInput::Vector& inputs, const Entity& entity, const Matrix& effect_transform) const override; // |FilterContents| std::optional<Rect> GetFilterSourceCoverage( const Matrix& effect_transform, const Rect& output_limit) const override; private: // |FilterContents| std::optional<Entity> RenderFilter( const FilterInput::Vector& input_textures, const ContentContext& renderer, const Entity& entity, const Matrix& effect_transform, const Rect& coverage, const std::optional<Rect>& coverage_hint) const override; Radius radius_; Vector2 direction_; MorphType morph_type_; DirectionalMorphologyFilterContents( const DirectionalMorphologyFilterContents&) = delete; DirectionalMorphologyFilterContents& operator=( const DirectionalMorphologyFilterContents&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MORPHOLOGY_FILTER_CONTENTS_H_
engine/impeller/entity/contents/filters/morphology_filter_contents.h/0
{ "file_path": "engine/impeller/entity/contents/filters/morphology_filter_contents.h", "repo_id": "engine", "token_count": 611 }
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 "impeller/entity/contents/scene_contents.h" #include "impeller/core/formats.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/contents/tiled_texture_contents.h" #include "impeller/entity/entity.h" #include "impeller/geometry/path_builder.h" #include "impeller/scene/camera.h" #include "impeller/scene/scene.h" namespace impeller { SceneContents::SceneContents() = default; SceneContents::~SceneContents() = default; void SceneContents::SetCameraTransform(Matrix matrix) { camera_transform_ = matrix; } void SceneContents::SetNode(std::shared_ptr<scene::Node> node) { node_ = std::move(node); } bool SceneContents::Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { if (!node_) { return true; } auto coverage = GetCoverage(entity); if (!coverage.has_value()) { return true; } // This happens for CoverGeometry (DrawPaint). In this situation, // Draw the scene to the full layer. if (coverage.value().IsMaximum()) { coverage = Rect::MakeSize(pass.GetRenderTargetSize()); } RenderTarget subpass_target; if (renderer.GetContext()->GetCapabilities()->SupportsOffscreenMSAA()) { subpass_target = renderer.GetRenderTargetCache()->CreateOffscreenMSAA( *renderer.GetContext(), // context ISize(coverage.value().GetSize()), // size /*mip_count=*/1, "SceneContents", // label RenderTarget::AttachmentConfigMSAA{ .storage_mode = StorageMode::kDeviceTransient, .resolve_storage_mode = StorageMode::kDevicePrivate, .load_action = LoadAction::kClear, .store_action = StoreAction::kMultisampleResolve, }, // color_attachment_config RenderTarget::AttachmentConfig{ .storage_mode = StorageMode::kDeviceTransient, .load_action = LoadAction::kDontCare, .store_action = StoreAction::kDontCare, } // stencil_attachment_config ); } else { subpass_target = renderer.GetRenderTargetCache()->CreateOffscreen( *renderer.GetContext(), // context ISize(coverage.value().GetSize()), // size /*mip_count=*/1, "SceneContents", // label RenderTarget::AttachmentConfig{ .storage_mode = StorageMode::kDevicePrivate, .load_action = LoadAction::kClear, .store_action = StoreAction::kStore, }, // color_attachment_config RenderTarget::AttachmentConfig{ .storage_mode = StorageMode::kDeviceTransient, .load_action = LoadAction::kClear, .store_action = StoreAction::kDontCare, } // stencil_attachment_config ); } if (!subpass_target.IsValid()) { return false; } scene::Scene scene(renderer.GetSceneContext()); scene.GetRoot().AddChild(node_); if (!scene.Render(subpass_target, camera_transform_)) { return false; } // Render the texture to the pass. TiledTextureContents contents; contents.SetGeometry(GetGeometry()); contents.SetTexture(subpass_target.GetRenderTargetTexture()); contents.SetEffectTransform( Matrix::MakeScale(1 / entity.GetTransform().GetScale())); return contents.Render(renderer, entity, pass); } } // namespace impeller
engine/impeller/entity/contents/scene_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/scene_contents.cc", "repo_id": "engine", "token_count": 1361 }
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 "impeller/entity/contents/tiled_texture_contents.h" #include "fml/logging.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/texture_fill.vert.h" #include "impeller/entity/tiled_texture_fill.frag.h" #include "impeller/entity/tiled_texture_fill_external.frag.h" #include "impeller/renderer/render_pass.h" namespace impeller { static std::optional<SamplerAddressMode> TileModeToAddressMode( Entity::TileMode tile_mode, const Capabilities& capabilities) { switch (tile_mode) { case Entity::TileMode::kClamp: return SamplerAddressMode::kClampToEdge; break; case Entity::TileMode::kMirror: return SamplerAddressMode::kMirror; break; case Entity::TileMode::kRepeat: return SamplerAddressMode::kRepeat; break; case Entity::TileMode::kDecal: if (capabilities.SupportsDecalSamplerAddressMode()) { return SamplerAddressMode::kDecal; } return std::nullopt; } } TiledTextureContents::TiledTextureContents() = default; TiledTextureContents::~TiledTextureContents() = default; void TiledTextureContents::SetTexture(std::shared_ptr<Texture> texture) { texture_ = std::move(texture); } void TiledTextureContents::SetTileModes(Entity::TileMode x_tile_mode, Entity::TileMode y_tile_mode) { x_tile_mode_ = x_tile_mode; y_tile_mode_ = y_tile_mode; } void TiledTextureContents::SetSamplerDescriptor(SamplerDescriptor desc) { sampler_descriptor_ = std::move(desc); } void TiledTextureContents::SetColorFilter(ColorFilterProc color_filter) { color_filter_ = std::move(color_filter); } std::shared_ptr<Texture> TiledTextureContents::CreateFilterTexture( const ContentContext& renderer) const { if (!color_filter_) { return nullptr; } auto color_filter_contents = color_filter_(FilterInput::Make(texture_)); auto snapshot = color_filter_contents->RenderToSnapshot( renderer, // renderer Entity(), // entity std::nullopt, // coverage_limit std::nullopt, // sampler_descriptor true, // msaa_enabled /*mip_count=*/1, "TiledTextureContents Snapshot"); // label if (snapshot.has_value()) { return snapshot.value().texture; } return nullptr; } SamplerDescriptor TiledTextureContents::CreateSamplerDescriptor( const Capabilities& capabilities) const { SamplerDescriptor descriptor = sampler_descriptor_; auto width_mode = TileModeToAddressMode(x_tile_mode_, capabilities); auto height_mode = TileModeToAddressMode(y_tile_mode_, capabilities); if (width_mode.has_value()) { descriptor.width_address_mode = width_mode.value(); } if (height_mode.has_value()) { descriptor.height_address_mode = height_mode.value(); } return descriptor; } bool TiledTextureContents::UsesEmulatedTileMode( const Capabilities& capabilities) const { return !TileModeToAddressMode(x_tile_mode_, capabilities).has_value() || !TileModeToAddressMode(y_tile_mode_, capabilities).has_value(); } // |Contents| bool TiledTextureContents::IsOpaque() const { if (GetOpacityFactor() < 1 || x_tile_mode_ == Entity::TileMode::kDecal || y_tile_mode_ == Entity::TileMode::kDecal) { return false; } if (color_filter_) { return false; } return texture_->IsOpaque(); } bool TiledTextureContents::Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { if (texture_ == nullptr) { return true; } using VS = TextureFillVertexShader; using FS = TiledTextureFillFragmentShader; using FSExternal = TiledTextureFillExternalFragmentShader; const auto texture_size = texture_->GetSize(); if (texture_size.IsEmpty()) { return true; } bool is_external_texture = texture_->GetTextureDescriptor().type == TextureType::kTextureExternalOES; bool uses_emulated_tile_mode = UsesEmulatedTileMode(renderer.GetDeviceCapabilities()); VS::FrameInfo frame_info; frame_info.texture_sampler_y_coord_scale = texture_->GetYCoordScale(); frame_info.alpha = GetOpacityFactor(); PipelineBuilderMethod pipeline_method; #ifdef IMPELLER_ENABLE_OPENGLES if (is_external_texture) { pipeline_method = &ContentContext::GetTiledTextureExternalPipeline; } else { pipeline_method = uses_emulated_tile_mode ? &ContentContext::GetTiledTexturePipeline : &ContentContext::GetTexturePipeline; } #else pipeline_method = uses_emulated_tile_mode ? &ContentContext::GetTiledTexturePipeline : &ContentContext::GetTexturePipeline; #endif // IMPELLER_ENABLE_OPENGLES PipelineBuilderCallback pipeline_callback = [&renderer, &pipeline_method](ContentContextOptions options) { return (renderer.*pipeline_method)(options); }; return ColorSourceContents::DrawGeometry<VS>( renderer, entity, pass, pipeline_callback, frame_info, [this, &renderer, &is_external_texture, &uses_emulated_tile_mode](RenderPass& pass) { auto& host_buffer = renderer.GetTransientsBuffer(); if (uses_emulated_tile_mode) { pass.SetCommandLabel("TiledTextureFill"); } else { pass.SetCommandLabel("TextureFill"); } if (is_external_texture) { FSExternal::FragInfo frag_info; frag_info.x_tile_mode = static_cast<Scalar>(x_tile_mode_); frag_info.y_tile_mode = static_cast<Scalar>(y_tile_mode_); FSExternal::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); } else if (uses_emulated_tile_mode) { FS::FragInfo frag_info; frag_info.x_tile_mode = static_cast<Scalar>(x_tile_mode_); frag_info.y_tile_mode = static_cast<Scalar>(y_tile_mode_); FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); } if (is_external_texture) { SamplerDescriptor sampler_desc; // OES_EGL_image_external states that only CLAMP_TO_EDGE is valid, so // we emulate all other tile modes here by remapping the texture // coordinates. sampler_desc.width_address_mode = SamplerAddressMode::kClampToEdge; sampler_desc.height_address_mode = SamplerAddressMode::kClampToEdge; // Also, external textures cannot be bound to color filters, so ignore // this case for now. FML_DCHECK(!color_filter_) << "Color filters are not currently " "supported for external textures."; FSExternal::BindSAMPLEREXTERNALOESTextureSampler( pass, texture_, renderer.GetContext()->GetSamplerLibrary()->GetSampler( sampler_desc)); } else { if (color_filter_) { auto filtered_texture = CreateFilterTexture(renderer); if (!filtered_texture) { return false; } FS::BindTextureSampler( pass, filtered_texture, renderer.GetContext()->GetSamplerLibrary()->GetSampler( CreateSamplerDescriptor(renderer.GetDeviceCapabilities()))); } else { FS::BindTextureSampler( pass, texture_, renderer.GetContext()->GetSamplerLibrary()->GetSampler( CreateSamplerDescriptor(renderer.GetDeviceCapabilities()))); } } return true; }, /*enable_uvs=*/true, /*texture_coverage=*/Rect::MakeSize(texture_size), /*effect_transform=*/GetInverseEffectTransform()); } std::optional<Snapshot> TiledTextureContents::RenderToSnapshot( const ContentContext& renderer, const Entity& entity, std::optional<Rect> coverage_limit, const std::optional<SamplerDescriptor>& sampler_descriptor, bool msaa_enabled, int32_t mip_count, const std::string& label) const { std::optional<Rect> geometry_coverage = GetGeometry()->GetCoverage({}); if (GetInverseEffectTransform().IsIdentity() && GetGeometry()->IsAxisAlignedRect() && (!geometry_coverage.has_value() || Rect::MakeSize(texture_->GetSize()) .Contains(geometry_coverage.value()))) { auto coverage = GetCoverage(entity); if (!coverage.has_value()) { return std::nullopt; } auto scale = Vector2(coverage->GetSize() / Size(texture_->GetSize())); return Snapshot{ .texture = texture_, .transform = Matrix::MakeTranslation(coverage->GetOrigin()) * Matrix::MakeScale(scale), .sampler_descriptor = sampler_descriptor.value_or(sampler_descriptor_), .opacity = GetOpacityFactor(), }; } return Contents::RenderToSnapshot( renderer, // renderer entity, // entity std::nullopt, // coverage_limit sampler_descriptor.value_or(sampler_descriptor_), // sampler_descriptor true, // msaa_enabled /*mip_count=*/1, label); // label } } // namespace impeller
engine/impeller/entity/contents/tiled_texture_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/tiled_texture_contents.cc", "repo_id": "engine", "token_count": 3934 }
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_IMPELLER_ENTITY_ENTITY_PLAYGROUND_H_ #define FLUTTER_IMPELLER_ENTITY_ENTITY_PLAYGROUND_H_ #include "impeller/playground/playground_test.h" #include "flutter/fml/macros.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/entity.h" #include "impeller/entity/entity_pass.h" #include "impeller/typographer/typographer_context.h" namespace impeller { class EntityPlayground : public PlaygroundTest { public: using EntityPlaygroundCallback = std::function<bool(ContentContext& context, RenderPass& pass)>; EntityPlayground(); ~EntityPlayground(); void SetTypographerContext( std::shared_ptr<TypographerContext> typographer_context); bool OpenPlaygroundHere(Entity entity); bool OpenPlaygroundHere(EntityPass& entity_pass); bool OpenPlaygroundHere(EntityPlaygroundCallback callback); std::shared_ptr<ContentContext> GetContentContext() const; private: std::shared_ptr<TypographerContext> typographer_context_; EntityPlayground(const EntityPlayground&) = delete; EntityPlayground& operator=(const EntityPlayground&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_ENTITY_PLAYGROUND_H_
engine/impeller/entity/entity_playground.h/0
{ "file_path": "engine/impeller/entity/entity_playground.h", "repo_id": "engine", "token_count": 433 }
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_IMPELLER_ENTITY_GEOMETRY_POINT_FIELD_GEOMETRY_H_ #define FLUTTER_IMPELLER_ENTITY_GEOMETRY_POINT_FIELD_GEOMETRY_H_ #include "impeller/entity/geometry/geometry.h" namespace impeller { class PointFieldGeometry final : public Geometry { public: PointFieldGeometry(std::vector<Point> points, Scalar radius, bool round); ~PointFieldGeometry() = default; static size_t ComputeCircleDivisions(Scalar scaled_radius, bool round); private: // |Geometry| GeometryResult GetPositionBuffer(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; // |Geometry| GeometryResult GetPositionUVBuffer(Rect texture_coverage, Matrix effect_transform, const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; // |Geometry| GeometryVertexType GetVertexType() const override; // |Geometry| std::optional<Rect> GetCoverage(const Matrix& transform) const override; GeometryResult GetPositionBufferGPU( const ContentContext& renderer, const Entity& entity, RenderPass& pass, std::optional<Rect> texture_coverage = std::nullopt, std::optional<Matrix> effect_transform = std::nullopt) const; std::optional<VertexBufferBuilder<SolidFillVertexShader::PerVertexData>> GetPositionBufferCPU(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const; std::vector<Point> points_; Scalar radius_; bool round_; PointFieldGeometry(const PointFieldGeometry&) = delete; PointFieldGeometry& operator=(const PointFieldGeometry&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_POINT_FIELD_GEOMETRY_H_
engine/impeller/entity/geometry/point_field_geometry.h/0
{ "file_path": "engine/impeller/entity/geometry/point_field_geometry.h", "repo_id": "engine", "token_count": 850 }
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. precision mediump float; #include <impeller/texture.glsl> #include <impeller/types.glsl> uniform f16sampler2D texture_sampler_src; uniform FragInfo { float16_t input_alpha; } frag_info; in vec2 v_texture_coords; out f16vec4 frag_color; void main() { frag_color = texture(texture_sampler_src, v_texture_coords) * frag_info.input_alpha; }
engine/impeller/entity/shaders/blending/blend.frag/0
{ "file_path": "engine/impeller/entity/shaders/blending/blend.frag", "repo_id": "engine", "token_count": 186 }
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. precision mediump float; #include <impeller/color.glsl> #include <impeller/types.glsl> // A color filter that applies the sRGB gamma curve to the color. // // This filter is used so that the colors are suitable for display in monitors. uniform f16sampler2D input_texture; uniform FragInfo { float16_t input_alpha; } frag_info; in highp vec2 v_texture_coords; out f16vec4 frag_color; void main() { f16vec4 input_color = texture(input_texture, v_texture_coords) * frag_info.input_alpha; f16vec4 color = IPHalfUnpremultiply(input_color); for (int i = 0; i < 3; i++) { if (color[i] <= 0.0031308hf) { color[i] = (color[i]) * 12.92hf; } else { color[i] = 1.055hf * pow(color[i], (1.0hf / 2.4hf)) - 0.055hf; } } frag_color = IPHalfPremultiply(color); }
engine/impeller/entity/shaders/linear_to_srgb_filter.frag/0
{ "file_path": "engine/impeller/entity/shaders/linear_to_srgb_filter.frag", "repo_id": "engine", "token_count": 374 }
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. #extension GL_AMD_gpu_shader_half_float : enable #extension GL_AMD_gpu_shader_half_float_fetch : enable #extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable uniform FragInfo { float16_t half_1; f16vec2 half_2; f16vec3 half_3; f16vec4 half_4; } frag_info; out vec4 frag_color; void main() { frag_color = vec4(0); }
engine/impeller/fixtures/half.frag/0
{ "file_path": "engine/impeller/fixtures/half.frag", "repo_id": "engine", "token_count": 187 }
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. layout(location = 0) uniform vec2 iResolution; layout(location = 1) uniform float iTime; layout(location = 0) out vec4 fragColor; void main() { vec2 uv = gl_FragCoord.xy / iResolution; float t = 4 * iTime; vec3 col = 0.5 + 0.5 * cos(t + uv.xyx + vec3(0, 1, 4)); fragColor = vec4(col, 1.0); }
engine/impeller/fixtures/runtime_stage_example.frag/0
{ "file_path": "engine/impeller/fixtures/runtime_stage_example.frag", "repo_id": "engine", "token_count": 166 }
254
// 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_GEOMETRY_COLOR_H_ #define FLUTTER_IMPELLER_GEOMETRY_COLOR_H_ #include <stdint.h> #include <algorithm> #include <array> #include <cstdint> #include <cstdlib> #include <ostream> #include <type_traits> #include "impeller/geometry/scalar.h" #include "impeller/geometry/type_traits.h" #define IMPELLER_FOR_EACH_BLEND_MODE(V) \ V(Clear) \ V(Source) \ V(Destination) \ V(SourceOver) \ V(DestinationOver) \ V(SourceIn) \ V(DestinationIn) \ V(SourceOut) \ V(DestinationOut) \ V(SourceATop) \ V(DestinationATop) \ V(Xor) \ V(Plus) \ V(Modulate) \ V(Screen) \ V(Overlay) \ V(Darken) \ V(Lighten) \ V(ColorDodge) \ V(ColorBurn) \ V(HardLight) \ V(SoftLight) \ V(Difference) \ V(Exclusion) \ V(Multiply) \ V(Hue) \ V(Saturation) \ V(Color) \ V(Luminosity) namespace impeller { struct ColorHSB; struct Vector4; enum class YUVColorSpace { kBT601LimitedRange, kBT601FullRange }; /// All blend modes assume that both the source (fragment output) and /// destination (first color attachment) have colors with premultiplied alpha. enum class BlendMode : uint8_t { // The following blend modes are able to be used as pipeline blend modes or // via `BlendFilterContents`. kClear = 0, kSource, kDestination, kSourceOver, kDestinationOver, kSourceIn, kDestinationIn, kSourceOut, kDestinationOut, kSourceATop, kDestinationATop, kXor, kPlus, kModulate, // The following blend modes use equations that are not available for // pipelines on most graphics devices without extensions, and so they are // only able to be used via `BlendFilterContents`. kScreen, kOverlay, kDarken, kLighten, kColorDodge, kColorBurn, kHardLight, kSoftLight, kDifference, kExclusion, kMultiply, kHue, kSaturation, kColor, kLuminosity, kLast = kLuminosity, }; const char* BlendModeToString(BlendMode blend_mode); /// 4x5 matrix for transforming the color and alpha components of a Bitmap. /// /// [ a, b, c, d, e, /// f, g, h, i, j, /// k, l, m, n, o, /// p, q, r, s, t ] /// /// When applied to a color [R, G, B, A], the resulting color is computed as: /// /// R’ = a*R + b*G + c*B + d*A + e; /// G’ = f*R + g*G + h*B + i*A + j; /// B’ = k*R + l*G + m*B + n*A + o; /// A’ = p*R + q*G + r*B + s*A + t; /// /// That resulting color [R’, G’, B’, A’] then has each channel clamped to the 0 /// to 1 range. struct ColorMatrix { Scalar array[20]; }; /** * Represents a RGBA color */ struct Color { /** * The red color component (0 to 1) */ Scalar red = 0.0; /** * The green color component (0 to 1) */ Scalar green = 0.0; /** * The blue color component (0 to 1) */ Scalar blue = 0.0; /** * The alpha component of the color (0 to 1) */ Scalar alpha = 0.0; constexpr Color() {} explicit Color(const ColorHSB& hsbColor); explicit Color(const Vector4& value); constexpr Color(Scalar r, Scalar g, Scalar b, Scalar a) : red(r), green(g), blue(b), alpha(a) {} static constexpr Color MakeRGBA8(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { return Color( static_cast<Scalar>(r) / 255.0f, static_cast<Scalar>(g) / 255.0f, static_cast<Scalar>(b) / 255.0f, static_cast<Scalar>(a) / 255.0f); } /// @brief Convert this color to a 32-bit representation. static constexpr uint32_t ToIColor(Color color) { return (((std::lround(color.alpha * 255.0f) & 0xff) << 24) | ((std::lround(color.red * 255.0f) & 0xff) << 16) | ((std::lround(color.green * 255.0f) & 0xff) << 8) | ((std::lround(color.blue * 255.0f) & 0xff) << 0)) & 0xFFFFFFFF; } constexpr inline bool operator==(const Color& c) const { return ScalarNearlyEqual(red, c.red) && ScalarNearlyEqual(green, c.green) && ScalarNearlyEqual(blue, c.blue) && ScalarNearlyEqual(alpha, c.alpha); } constexpr inline Color operator+(const Color& c) const { return {red + c.red, green + c.green, blue + c.blue, alpha + c.alpha}; } template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator+(T value) const { auto v = static_cast<Scalar>(value); return {red + v, green + v, blue + v, alpha + v}; } constexpr inline Color operator-(const Color& c) const { return {red - c.red, green - c.green, blue - c.blue, alpha - c.alpha}; } template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator-(T value) const { auto v = static_cast<Scalar>(value); return {red - v, green - v, blue - v, alpha - v}; } constexpr inline Color operator*(const Color& c) const { return {red * c.red, green * c.green, blue * c.blue, alpha * c.alpha}; } template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator*(T value) const { auto v = static_cast<Scalar>(value); return {red * v, green * v, blue * v, alpha * v}; } constexpr inline Color operator/(const Color& c) const { return {red * c.red, green * c.green, blue * c.blue, alpha * c.alpha}; } template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator/(T value) const { auto v = static_cast<Scalar>(value); return {red / v, green / v, blue / v, alpha / v}; } constexpr Color Premultiply() const { return {red * alpha, green * alpha, blue * alpha, alpha}; } constexpr Color Unpremultiply() const { if (ScalarNearlyEqual(alpha, 0.0f)) { return Color::BlackTransparent(); } return {red / alpha, green / alpha, blue / alpha, alpha}; } /** * @brief Return a color that is linearly interpolated between colors a * and b, according to the value of t. * * @param a The lower color. * @param b The upper color. * @param t A value between 0.0f and 1.0f, inclusive. * @return constexpr Color */ constexpr static Color Lerp(Color a, Color b, Scalar t) { return a + (b - a) * t; } constexpr Color Clamp01() const { return Color(std::clamp(red, 0.0f, 1.0f), std::clamp(green, 0.0f, 1.0f), std::clamp(blue, 0.0f, 1.0f), std::clamp(alpha, 0.0f, 1.0f)); } /** * @brief Convert to R8G8B8A8 representation. * * @return constexpr std::array<u_int8, 4> */ constexpr std::array<uint8_t, 4> ToR8G8B8A8() const { uint8_t r = std::round(red * 255.0f); uint8_t g = std::round(green * 255.0f); uint8_t b = std::round(blue * 255.0f); uint8_t a = std::round(alpha * 255.0f); return {r, g, b, a}; } static constexpr Color White() { return {1.0f, 1.0f, 1.0f, 1.0f}; } static constexpr Color Black() { return {0.0f, 0.0f, 0.0f, 1.0f}; } static constexpr Color WhiteTransparent() { return {1.0f, 1.0f, 1.0f, 0.0f}; } static constexpr Color BlackTransparent() { return {0.0f, 0.0f, 0.0f, 0.0f}; } static constexpr Color Red() { return {1.0f, 0.0f, 0.0f, 1.0f}; } static constexpr Color Green() { return {0.0f, 1.0f, 0.0f, 1.0f}; } static constexpr Color Blue() { return {0.0f, 0.0f, 1.0f, 1.0f}; } constexpr Color WithAlpha(Scalar new_alpha) const { return {red, green, blue, new_alpha}; } static constexpr Color AliceBlue() { return {240.0f / 255.0f, 248.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color AntiqueWhite() { return {250.0f / 255.0f, 235.0f / 255.0f, 215.0f / 255.0f, 1.0f}; } static constexpr Color Aqua() { return {0.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color AquaMarine() { return {127.0f / 255.0f, 255.0f / 255.0f, 212.0f / 255.0f, 1.0f}; } static constexpr Color Azure() { return {240.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color Beige() { return {245.0f / 255.0f, 245.0f / 255.0f, 220.0f / 255.0f, 1.0f}; } static constexpr Color Bisque() { return {255.0f / 255.0f, 228.0f / 255.0f, 196.0f / 255.0f, 1.0f}; } static constexpr Color BlanchedAlmond() { return {255.0f / 255.0f, 235.0f / 255.0f, 205.0f / 255.0f, 1.0f}; } static constexpr Color BlueViolet() { return {138.0f / 255.0f, 43.0f / 255.0f, 226.0f / 255.0f, 1.0f}; } static constexpr Color Brown() { return {165.0f / 255.0f, 42.0f / 255.0f, 42.0f / 255.0f, 1.0f}; } static constexpr Color BurlyWood() { return {222.0f / 255.0f, 184.0f / 255.0f, 135.0f / 255.0f, 1.0f}; } static constexpr Color CadetBlue() { return {95.0f / 255.0f, 158.0f / 255.0f, 160.0f / 255.0f, 1.0f}; } static constexpr Color Chartreuse() { return {127.0f / 255.0f, 255.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color Chocolate() { return {210.0f / 255.0f, 105.0f / 255.0f, 30.0f / 255.0f, 1.0f}; } static constexpr Color Coral() { return {255.0f / 255.0f, 127.0f / 255.0f, 80.0f / 255.0f, 1.0f}; } static constexpr Color CornflowerBlue() { return {100.0f / 255.0f, 149.0f / 255.0f, 237.0f / 255.0f, 1.0f}; } static constexpr Color Cornsilk() { return {255.0f / 255.0f, 248.0f / 255.0f, 220.0f / 255.0f, 1.0f}; } static constexpr Color Crimson() { return {220.0f / 255.0f, 20.0f / 255.0f, 60.0f / 255.0f, 1.0f}; } static constexpr Color Cyan() { return {0.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color DarkBlue() { return {0.0f / 255.0f, 0.0f / 255.0f, 139.0f / 255.0f, 1.0f}; } static constexpr Color DarkCyan() { return {0.0f / 255.0f, 139.0f / 255.0f, 139.0f / 255.0f, 1.0f}; } static constexpr Color DarkGoldenrod() { return {184.0f / 255.0f, 134.0f / 255.0f, 11.0f / 255.0f, 1.0f}; } static constexpr Color DarkGray() { return {169.0f / 255.0f, 169.0f / 255.0f, 169.0f / 255.0f, 1.0f}; } static constexpr Color DarkGreen() { return {0.0f / 255.0f, 100.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color DarkGrey() { return {169.0f / 255.0f, 169.0f / 255.0f, 169.0f / 255.0f, 1.0f}; } static constexpr Color DarkKhaki() { return {189.0f / 255.0f, 183.0f / 255.0f, 107.0f / 255.0f, 1.0f}; } static constexpr Color DarkMagenta() { return {139.0f / 255.0f, 0.0f / 255.0f, 139.0f / 255.0f, 1.0f}; } static constexpr Color DarkOliveGreen() { return {85.0f / 255.0f, 107.0f / 255.0f, 47.0f / 255.0f, 1.0f}; } static constexpr Color DarkOrange() { return {255.0f / 255.0f, 140.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color DarkOrchid() { return {153.0f / 255.0f, 50.0f / 255.0f, 204.0f / 255.0f, 1.0f}; } static constexpr Color DarkRed() { return {139.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color DarkSalmon() { return {233.0f / 255.0f, 150.0f / 255.0f, 122.0f / 255.0f, 1.0f}; } static constexpr Color DarkSeagreen() { return {143.0f / 255.0f, 188.0f / 255.0f, 143.0f / 255.0f, 1.0f}; } static constexpr Color DarkSlateBlue() { return {72.0f / 255.0f, 61.0f / 255.0f, 139.0f / 255.0f, 1.0f}; } static constexpr Color DarkSlateGray() { return {47.0f / 255.0f, 79.0f / 255.0f, 79.0f / 255.0f, 1.0f}; } static constexpr Color DarkSlateGrey() { return {47.0f / 255.0f, 79.0f / 255.0f, 79.0f / 255.0f, 1.0f}; } static constexpr Color DarkTurquoise() { return {0.0f / 255.0f, 206.0f / 255.0f, 209.0f / 255.0f, 1.0f}; } static constexpr Color DarkViolet() { return {148.0f / 255.0f, 0.0f / 255.0f, 211.0f / 255.0f, 1.0f}; } static constexpr Color DeepPink() { return {255.0f / 255.0f, 20.0f / 255.0f, 147.0f / 255.0f, 1.0f}; } static constexpr Color DeepSkyBlue() { return {0.0f / 255.0f, 191.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color DimGray() { return {105.0f / 255.0f, 105.0f / 255.0f, 105.0f / 255.0f, 1.0f}; } static constexpr Color DimGrey() { return {105.0f / 255.0f, 105.0f / 255.0f, 105.0f / 255.0f, 1.0f}; } static constexpr Color DodgerBlue() { return {30.0f / 255.0f, 144.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color Firebrick() { return {178.0f / 255.0f, 34.0f / 255.0f, 34.0f / 255.0f, 1.0f}; } static constexpr Color FloralWhite() { return {255.0f / 255.0f, 250.0f / 255.0f, 240.0f / 255.0f, 1.0f}; } static constexpr Color ForestGreen() { return {34.0f / 255.0f, 139.0f / 255.0f, 34.0f / 255.0f, 1.0f}; } static constexpr Color Fuchsia() { return {255.0f / 255.0f, 0.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color Gainsboro() { return {220.0f / 255.0f, 220.0f / 255.0f, 220.0f / 255.0f, 1.0f}; } static constexpr Color Ghostwhite() { return {248.0f / 255.0f, 248.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color Gold() { return {255.0f / 255.0f, 215.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color Goldenrod() { return {218.0f / 255.0f, 165.0f / 255.0f, 32.0f / 255.0f, 1.0f}; } static constexpr Color Gray() { return {128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; } static constexpr Color GreenYellow() { return {173.0f / 255.0f, 255.0f / 255.0f, 47.0f / 255.0f, 1.0f}; } static constexpr Color Grey() { return {128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; } static constexpr Color Honeydew() { return {240.0f / 255.0f, 255.0f / 255.0f, 240.0f / 255.0f, 1.0f}; } static constexpr Color HotPink() { return {255.0f / 255.0f, 105.0f / 255.0f, 180.0f / 255.0f, 1.0f}; } static constexpr Color IndianRed() { return {205.0f / 255.0f, 92.0f / 255.0f, 92.0f / 255.0f, 1.0f}; } static constexpr Color Indigo() { return {75.0f / 255.0f, 0.0f / 255.0f, 130.0f / 255.0f, 1.0f}; } static constexpr Color Ivory() { return {255.0f / 255.0f, 255.0f / 255.0f, 240.0f / 255.0f, 1.0f}; } static constexpr Color Khaki() { return {240.0f / 255.0f, 230.0f / 255.0f, 140.0f / 255.0f, 1.0f}; } static constexpr Color Lavender() { return {230.0f / 255.0f, 230.0f / 255.0f, 250.0f / 255.0f, 1.0f}; } static constexpr Color LavenderBlush() { return {255.0f / 255.0f, 240.0f / 255.0f, 245.0f / 255.0f, 1.0f}; } static constexpr Color LawnGreen() { return {124.0f / 255.0f, 252.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color LemonChiffon() { return {255.0f / 255.0f, 250.0f / 255.0f, 205.0f / 255.0f, 1.0f}; } static constexpr Color LightBlue() { return {173.0f / 255.0f, 216.0f / 255.0f, 230.0f / 255.0f, 1.0f}; } static constexpr Color LightCoral() { return {240.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; } static constexpr Color LightCyan() { return {224.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color LightGoldenrodYellow() { return {50.0f / 255.0f, 250.0f / 255.0f, 210.0f / 255.0f, 1.0f}; } static constexpr Color LightGray() { return {211.0f / 255.0f, 211.0f / 255.0f, 211.0f / 255.0f, 1.0f}; } static constexpr Color LightGreen() { return {144.0f / 255.0f, 238.0f / 255.0f, 144.0f / 255.0f, 1.0f}; } static constexpr Color LightGrey() { return {211.0f / 255.0f, 211.0f / 255.0f, 211.0f / 255.0f, 1.0f}; } static constexpr Color LightPink() { return {255.0f / 255.0f, 182.0f / 255.0f, 193.0f / 255.0f, 1.0f}; } static constexpr Color LightSalmon() { return {255.0f / 255.0f, 160.0f / 255.0f, 122.0f / 255.0f, 1.0f}; } static constexpr Color LightSeaGreen() { return {32.0f / 255.0f, 178.0f / 255.0f, 170.0f / 255.0f, 1.0f}; } static constexpr Color LightSkyBlue() { return {135.0f / 255.0f, 206.0f / 255.0f, 250.0f / 255.0f, 1.0f}; } static constexpr Color LightSlateGray() { return {119.0f / 255.0f, 136.0f / 255.0f, 153.0f / 255.0f, 1.0f}; } static constexpr Color LightSlateGrey() { return {119.0f / 255.0f, 136.0f / 255.0f, 153.0f / 255.0f, 1.0f}; } static constexpr Color LightSteelBlue() { return {176.0f / 255.0f, 196.0f / 255.0f, 222.0f / 255.0f, 1.0f}; } static constexpr Color LightYellow() { return {255.0f / 255.0f, 255.0f / 255.0f, 224.0f / 255.0f, 1.0f}; } static constexpr Color Lime() { return {0.0f / 255.0f, 255.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color LimeGreen() { return {50.0f / 255.0f, 205.0f / 255.0f, 50.0f / 255.0f, 1.0f}; } static constexpr Color Linen() { return {250.0f / 255.0f, 240.0f / 255.0f, 230.0f / 255.0f, 1.0f}; } static constexpr Color Magenta() { return {255.0f / 255.0f, 0.0f / 255.0f, 255.0f / 255.0f, 1.0f}; } static constexpr Color Maroon() { return {128.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color MediumAquamarine() { return {102.0f / 255.0f, 205.0f / 255.0f, 170.0f / 255.0f, 1.0f}; } static constexpr Color MediumBlue() { return {0.0f / 255.0f, 0.0f / 255.0f, 205.0f / 255.0f, 1.0f}; } static constexpr Color MediumOrchid() { return {186.0f / 255.0f, 85.0f / 255.0f, 211.0f / 255.0f, 1.0f}; } static constexpr Color MediumPurple() { return {147.0f / 255.0f, 112.0f / 255.0f, 219.0f / 255.0f, 1.0f}; } static constexpr Color MediumSeagreen() { return {60.0f / 255.0f, 179.0f / 255.0f, 113.0f / 255.0f, 1.0f}; } static constexpr Color MediumSlateBlue() { return {123.0f / 255.0f, 104.0f / 255.0f, 238.0f / 255.0f, 1.0f}; } static constexpr Color MediumSpringGreen() { return {0.0f / 255.0f, 250.0f / 255.0f, 154.0f / 255.0f, 1.0f}; } static constexpr Color MediumTurquoise() { return {72.0f / 255.0f, 209.0f / 255.0f, 204.0f / 255.0f, 1.0f}; } static constexpr Color MediumVioletRed() { return {199.0f / 255.0f, 21.0f / 255.0f, 133.0f / 255.0f, 1.0f}; } static constexpr Color MidnightBlue() { return {25.0f / 255.0f, 25.0f / 255.0f, 112.0f / 255.0f, 1.0f}; } static constexpr Color MintCream() { return {245.0f / 255.0f, 255.0f / 255.0f, 250.0f / 255.0f, 1.0f}; } static constexpr Color MistyRose() { return {255.0f / 255.0f, 228.0f / 255.0f, 225.0f / 255.0f, 1.0f}; } static constexpr Color Moccasin() { return {255.0f / 255.0f, 228.0f / 255.0f, 181.0f / 255.0f, 1.0f}; } static constexpr Color NavajoWhite() { return {255.0f / 255.0f, 222.0f / 255.0f, 173.0f / 255.0f, 1.0f}; } static constexpr Color Navy() { return {0.0f / 255.0f, 0.0f / 255.0f, 128.0f / 255.0f, 1.0f}; } static constexpr Color OldLace() { return {253.0f / 255.0f, 245.0f / 255.0f, 230.0f / 255.0f, 1.0f}; } static constexpr Color Olive() { return {128.0f / 255.0f, 128.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color OliveDrab() { return {107.0f / 255.0f, 142.0f / 255.0f, 35.0f / 255.0f, 1.0f}; } static constexpr Color Orange() { return {255.0f / 255.0f, 165.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color OrangeRed() { return {255.0f / 255.0f, 69.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color Orchid() { return {218.0f / 255.0f, 112.0f / 255.0f, 214.0f / 255.0f, 1.0f}; } static constexpr Color PaleGoldenrod() { return {238.0f / 255.0f, 232.0f / 255.0f, 170.0f / 255.0f, 1.0f}; } static constexpr Color PaleGreen() { return {152.0f / 255.0f, 251.0f / 255.0f, 152.0f / 255.0f, 1.0f}; } static constexpr Color PaleTurquoise() { return {175.0f / 255.0f, 238.0f / 255.0f, 238.0f / 255.0f, 1.0f}; } static constexpr Color PaleVioletRed() { return {219.0f / 255.0f, 112.0f / 255.0f, 147.0f / 255.0f, 1.0f}; } static constexpr Color PapayaWhip() { return {255.0f / 255.0f, 239.0f / 255.0f, 213.0f / 255.0f, 1.0f}; } static constexpr Color Peachpuff() { return {255.0f / 255.0f, 218.0f / 255.0f, 185.0f / 255.0f, 1.0f}; } static constexpr Color Peru() { return {205.0f / 255.0f, 133.0f / 255.0f, 63.0f / 255.0f, 1.0f}; } static constexpr Color Pink() { return {255.0f / 255.0f, 192.0f / 255.0f, 203.0f / 255.0f, 1.0f}; } static constexpr Color Plum() { return {221.0f / 255.0f, 160.0f / 255.0f, 221.0f / 255.0f, 1.0f}; } static constexpr Color PowderBlue() { return {176.0f / 255.0f, 224.0f / 255.0f, 230.0f / 255.0f, 1.0f}; } static constexpr Color Purple() { return {128.0f / 255.0f, 0.0f / 255.0f, 128.0f / 255.0f, 1.0f}; } static constexpr Color RosyBrown() { return {188.0f / 255.0f, 143.0f / 255.0f, 143.0f / 255.0f, 1.0f}; } static constexpr Color RoyalBlue() { return {65.0f / 255.0f, 105.0f / 255.0f, 225.0f / 255.0f, 1.0f}; } static constexpr Color SaddleBrown() { return {139.0f / 255.0f, 69.0f / 255.0f, 19.0f / 255.0f, 1.0f}; } static constexpr Color Salmon() { return {250.0f / 255.0f, 128.0f / 255.0f, 114.0f / 255.0f, 1.0f}; } static constexpr Color SandyBrown() { return {244.0f / 255.0f, 164.0f / 255.0f, 96.0f / 255.0f, 1.0f}; } static constexpr Color Seagreen() { return {46.0f / 255.0f, 139.0f / 255.0f, 87.0f / 255.0f, 1.0f}; } static constexpr Color Seashell() { return {255.0f / 255.0f, 245.0f / 255.0f, 238.0f / 255.0f, 1.0f}; } static constexpr Color Sienna() { return {160.0f / 255.0f, 82.0f / 255.0f, 45.0f / 255.0f, 1.0f}; } static constexpr Color Silver() { return {192.0f / 255.0f, 192.0f / 255.0f, 192.0f / 255.0f, 1.0f}; } static constexpr Color SkyBlue() { return {135.0f / 255.0f, 206.0f / 255.0f, 235.0f / 255.0f, 1.0f}; } static constexpr Color SlateBlue() { return {106.0f / 255.0f, 90.0f / 255.0f, 205.0f / 255.0f, 1.0f}; } static constexpr Color SlateGray() { return {112.0f / 255.0f, 128.0f / 255.0f, 144.0f / 255.0f, 1.0f}; } static constexpr Color SlateGrey() { return {112.0f / 255.0f, 128.0f / 255.0f, 144.0f / 255.0f, 1.0f}; } static constexpr Color Snow() { return {255.0f / 255.0f, 250.0f / 255.0f, 250.0f / 255.0f, 1.0f}; } static constexpr Color SpringGreen() { return {0.0f / 255.0f, 255.0f / 255.0f, 127.0f / 255.0f, 1.0f}; } static constexpr Color SteelBlue() { return {70.0f / 255.0f, 130.0f / 255.0f, 180.0f / 255.0f, 1.0f}; } static constexpr Color Tan() { return {210.0f / 255.0f, 180.0f / 255.0f, 140.0f / 255.0f, 1.0f}; } static constexpr Color Teal() { return {0.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; } static constexpr Color Thistle() { return {216.0f / 255.0f, 191.0f / 255.0f, 216.0f / 255.0f, 1.0f}; } static constexpr Color Tomato() { return {255.0f / 255.0f, 99.0f / 255.0f, 71.0f / 255.0f, 1.0f}; } static constexpr Color Turquoise() { return {64.0f / 255.0f, 224.0f / 255.0f, 208.0f / 255.0f, 1.0f}; } static constexpr Color Violet() { return {238.0f / 255.0f, 130.0f / 255.0f, 238.0f / 255.0f, 1.0f}; } static constexpr Color Wheat() { return {245.0f / 255.0f, 222.0f / 255.0f, 179.0f / 255.0f, 1.0f}; } static constexpr Color Whitesmoke() { return {245.0f / 255.0f, 245.0f / 255.0f, 245.0f / 255.0f, 1.0f}; } static constexpr Color Yellow() { return {255.0f / 255.0f, 255.0f / 255.0f, 0.0f / 255.0f, 1.0f}; } static constexpr Color YellowGreen() { return {154.0f / 255.0f, 205.0f / 255.0f, 50.0f / 255.0f, 1.0f}; } static Color Random() { return { // This method is not used for cryptographic purposes. // NOLINTBEGIN(clang-analyzer-security.insecureAPI.rand) static_cast<Scalar>((std::rand() % 255) / 255.0f), // static_cast<Scalar>((std::rand() % 255) / 255.0f), // static_cast<Scalar>((std::rand() % 255) / 255.0f), // // NOLINTEND(clang-analyzer-security.insecureAPI.rand) 1.0f // }; } /// @brief Blends an unpremultiplied destination color into a given /// unpremultiplied source color to form a new unpremultiplied color. /// /// If either the source or destination are premultiplied, the result /// will be incorrect. Color Blend(Color source, BlendMode blend_mode) const; /// @brief A color filter that transforms colors through a 4x5 color matrix. /// /// This filter can be used to change the saturation of pixels, convert /// from YUV to RGB, etc. /// /// Each channel of the output color is clamped to the 0 to 1 range. /// /// @see `ColorMatrix` Color ApplyColorMatrix(const ColorMatrix& color_matrix) const; /// @brief Convert the color from linear space to sRGB space. /// /// The color is assumed to be unpremultiplied. If the color is /// premultipled, the conversion output will be incorrect. Color LinearToSRGB() const; /// @brief Convert the color from sRGB space to linear space. /// /// The color is assumed to be unpremultiplied. If the color is /// premultipled, the conversion output will be incorrect. Color SRGBToLinear() const; constexpr bool IsTransparent() const { return alpha == 0.0f; } constexpr bool IsOpaque() const { return alpha == 1.0f; } }; template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator+(T value, const Color& c) { return c + static_cast<Scalar>(value); } template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator-(T value, const Color& c) { auto v = static_cast<Scalar>(value); return {v - c.red, v - c.green, v - c.blue, v - c.alpha}; } template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator*(T value, const Color& c) { return c * static_cast<Scalar>(value); } template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr inline Color operator/(T value, const Color& c) { auto v = static_cast<Scalar>(value); return {v / c.red, v / c.green, v / c.blue, v / c.alpha}; } std::string ColorToString(const Color& color); /** * Represents a color by its constituent hue, saturation, brightness and alpha */ struct ColorHSB { /** * The hue of the color (0 to 1) */ Scalar hue; /** * The saturation of the color (0 to 1) */ Scalar saturation; /** * The brightness of the color (0 to 1) */ Scalar brightness; /** * The alpha of the color (0 to 1) */ Scalar alpha; constexpr ColorHSB(Scalar h, Scalar s, Scalar b, Scalar a) : hue(h), saturation(s), brightness(b), alpha(a) {} static ColorHSB FromRGB(Color rgb); Color ToRGBA() const; }; static_assert(sizeof(Color) == 4 * sizeof(Scalar)); } // namespace impeller namespace std { inline std::ostream& operator<<(std::ostream& out, const impeller::Color& c) { out << "(" << c.red << ", " << c.green << ", " << c.blue << ", " << c.alpha << ")"; return out; } } // namespace std #endif // FLUTTER_IMPELLER_GEOMETRY_COLOR_H_
engine/impeller/geometry/color.h/0
{ "file_path": "engine/impeller/geometry/color.h", "repo_id": "engine", "token_count": 12755 }
255
// 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 "path_builder.h" #include <cmath> namespace impeller { PathBuilder::PathBuilder() { AddContourComponent({}); } PathBuilder::~PathBuilder() = default; Path PathBuilder::CopyPath(FillType fill) { prototype_.fill = fill; return Path(prototype_); } Path PathBuilder::TakePath(FillType fill) { prototype_.fill = fill; UpdateBounds(); return Path(std::move(prototype_)); } void PathBuilder::Reserve(size_t point_size, size_t verb_size) { prototype_.points.reserve(point_size); prototype_.components.reserve(verb_size); } PathBuilder& PathBuilder::MoveTo(Point point, bool relative) { current_ = relative ? current_ + point : point; subpath_start_ = current_; AddContourComponent(current_); return *this; } PathBuilder& PathBuilder::Close() { LineTo(subpath_start_); SetContourClosed(true); AddContourComponent(current_); return *this; } PathBuilder& PathBuilder::LineTo(Point point, bool relative) { point = relative ? current_ + point : point; AddLinearComponent(current_, point); current_ = point; return *this; } PathBuilder& PathBuilder::HorizontalLineTo(Scalar x, bool relative) { Point endpoint = relative ? Point{current_.x + x, current_.y} : Point{x, current_.y}; AddLinearComponent(current_, endpoint); current_ = endpoint; return *this; } PathBuilder& PathBuilder::VerticalLineTo(Scalar y, bool relative) { Point endpoint = relative ? Point{current_.x, current_.y + y} : Point{current_.x, y}; AddLinearComponent(current_, endpoint); current_ = endpoint; return *this; } PathBuilder& PathBuilder::QuadraticCurveTo(Point controlPoint, Point point, bool relative) { point = relative ? current_ + point : point; controlPoint = relative ? current_ + controlPoint : controlPoint; AddQuadraticComponent(current_, controlPoint, point); current_ = point; return *this; } PathBuilder& PathBuilder::SetConvexity(Convexity value) { prototype_.convexity = value; return *this; } PathBuilder& PathBuilder::CubicCurveTo(Point controlPoint1, Point controlPoint2, Point point, bool relative) { controlPoint1 = relative ? current_ + controlPoint1 : controlPoint1; controlPoint2 = relative ? current_ + controlPoint2 : controlPoint2; point = relative ? current_ + point : point; AddCubicComponent(current_, controlPoint1, controlPoint2, point); current_ = point; return *this; } PathBuilder& PathBuilder::AddQuadraticCurve(Point p1, Point cp, Point p2) { MoveTo(p1); AddQuadraticComponent(p1, cp, p2); return *this; } PathBuilder& PathBuilder::AddCubicCurve(Point p1, Point cp1, Point cp2, Point p2) { MoveTo(p1); AddCubicComponent(p1, cp1, cp2, p2); return *this; } PathBuilder& PathBuilder::AddRect(Rect rect) { auto origin = rect.GetOrigin(); auto size = rect.GetSize(); auto tl = origin; auto bl = origin + Point{0.0, size.height}; auto br = origin + size; auto tr = origin + Point{size.width, 0.0}; MoveTo(tl); LineTo(tr); LineTo(br); LineTo(bl); Close(); return *this; } PathBuilder& PathBuilder::AddCircle(const Point& c, Scalar r) { return AddOval(Rect::MakeXYWH(c.x - r, c.y - r, 2.0f * r, 2.0f * r)); } PathBuilder& PathBuilder::AddRoundedRect(Rect rect, Scalar radius) { return radius <= 0.0 ? AddRect(rect) : AddRoundedRect(rect, RoundingRadii(radius)); } PathBuilder& PathBuilder::AddRoundedRect(Rect rect, Size radii) { return radii.width <= 0 || radii.height <= 0 ? AddRect(rect) : AddRoundedRect(rect, RoundingRadii(radii)); } PathBuilder& PathBuilder::AddRoundedRect(Rect rect, RoundingRadii radii) { if (radii.AreAllZero()) { return AddRect(rect); } auto rect_origin = rect.GetOrigin(); auto rect_size = rect.GetSize(); current_ = rect_origin + Point{radii.top_left.x, 0.0}; MoveTo({rect_origin.x + radii.top_left.x, rect_origin.y}); //---------------------------------------------------------------------------- // Top line. // AddLinearComponent( {rect_origin.x + radii.top_left.x, rect_origin.y}, {rect_origin.x + rect_size.width - radii.top_right.x, rect_origin.y}); //---------------------------------------------------------------------------- // Top right arc. // AddRoundedRectTopRight(rect, radii); //---------------------------------------------------------------------------- // Right line. // AddLinearComponent( {rect_origin.x + rect_size.width, rect_origin.y + radii.top_right.y}, {rect_origin.x + rect_size.width, rect_origin.y + rect_size.height - radii.bottom_right.y}); //---------------------------------------------------------------------------- // Bottom right arc. // AddRoundedRectBottomRight(rect, radii); //---------------------------------------------------------------------------- // Bottom line. // AddLinearComponent( {rect_origin.x + rect_size.width - radii.bottom_right.x, rect_origin.y + rect_size.height}, {rect_origin.x + radii.bottom_left.x, rect_origin.y + rect_size.height}); //---------------------------------------------------------------------------- // Bottom left arc. // AddRoundedRectBottomLeft(rect, radii); //---------------------------------------------------------------------------- // Left line. // AddLinearComponent( {rect_origin.x, rect_origin.y + rect_size.height - radii.bottom_left.y}, {rect_origin.x, rect_origin.y + radii.top_left.y}); //---------------------------------------------------------------------------- // Top left arc. // AddRoundedRectTopLeft(rect, radii); Close(); return *this; } PathBuilder& PathBuilder::AddRoundedRectTopLeft(Rect rect, RoundingRadii radii) { const auto magic_top_left = radii.top_left * kArcApproximationMagic; const auto corner = rect.GetOrigin(); AddCubicComponent({corner.x, corner.y + radii.top_left.y}, {corner.x, corner.y + radii.top_left.y - magic_top_left.y}, {corner.x + radii.top_left.x - magic_top_left.x, corner.y}, {corner.x + radii.top_left.x, corner.y}); return *this; } PathBuilder& PathBuilder::AddRoundedRectTopRight(Rect rect, RoundingRadii radii) { const auto magic_top_right = radii.top_right * kArcApproximationMagic; const auto corner = rect.GetOrigin() + Point{rect.GetWidth(), 0}; AddCubicComponent( {corner.x - radii.top_right.x, corner.y}, {corner.x - radii.top_right.x + magic_top_right.x, corner.y}, {corner.x, corner.y + radii.top_right.y - magic_top_right.y}, {corner.x, corner.y + radii.top_right.y}); return *this; } PathBuilder& PathBuilder::AddRoundedRectBottomRight(Rect rect, RoundingRadii radii) { const auto magic_bottom_right = radii.bottom_right * kArcApproximationMagic; const auto corner = rect.GetOrigin() + rect.GetSize(); AddCubicComponent( {corner.x, corner.y - radii.bottom_right.y}, {corner.x, corner.y - radii.bottom_right.y + magic_bottom_right.y}, {corner.x - radii.bottom_right.x + magic_bottom_right.x, corner.y}, {corner.x - radii.bottom_right.x, corner.y}); return *this; } PathBuilder& PathBuilder::AddRoundedRectBottomLeft(Rect rect, RoundingRadii radii) { const auto magic_bottom_left = radii.bottom_left * kArcApproximationMagic; const auto corner = rect.GetOrigin() + Point{0, rect.GetHeight()}; AddCubicComponent( {corner.x + radii.bottom_left.x, corner.y}, {corner.x + radii.bottom_left.x - magic_bottom_left.x, corner.y}, {corner.x, corner.y - radii.bottom_left.y + magic_bottom_left.y}, {corner.x, corner.y - radii.bottom_left.y}); return *this; } void PathBuilder::AddContourComponent(const Point& destination, bool is_closed) { auto& components = prototype_.components; auto& contours = prototype_.contours; if (components.size() > 0 && components.back().type == Path::ComponentType::kContour) { // Never insert contiguous contours. contours.back() = ContourComponent(destination, is_closed); } else { contours.emplace_back(ContourComponent(destination, is_closed)); components.emplace_back(Path::ComponentType::kContour, contours.size() - 1); } prototype_.bounds.reset(); } void PathBuilder::AddLinearComponent(const Point& p1, const Point& p2) { auto& points = prototype_.points; auto index = points.size(); points.emplace_back(p1); points.emplace_back(p2); prototype_.components.emplace_back(Path::ComponentType::kLinear, index); prototype_.bounds.reset(); } void PathBuilder::AddQuadraticComponent(const Point& p1, const Point& cp, const Point& p2) { auto& points = prototype_.points; auto index = points.size(); points.emplace_back(p1); points.emplace_back(cp); points.emplace_back(p2); prototype_.components.emplace_back(Path::ComponentType::kQuadratic, index); prototype_.bounds.reset(); } void PathBuilder::AddCubicComponent(const Point& p1, const Point& cp1, const Point& cp2, const Point& p2) { auto& points = prototype_.points; auto index = points.size(); points.emplace_back(p1); points.emplace_back(cp1); points.emplace_back(cp2); points.emplace_back(p2); prototype_.components.emplace_back(Path::ComponentType::kCubic, index); prototype_.bounds.reset(); } void PathBuilder::SetContourClosed(bool is_closed) { prototype_.contours.back().is_closed = is_closed; } PathBuilder& PathBuilder::AddArc(const Rect& oval_bounds, Radians start, Radians sweep, bool use_center) { if (sweep.radians < 0) { start.radians += sweep.radians; sweep.radians *= -1; } sweep.radians = std::min(k2Pi, sweep.radians); start.radians = std::fmod(start.radians, k2Pi); const Point center = oval_bounds.GetCenter(); const Point radius = center - oval_bounds.GetOrigin(); Vector2 p1_unit(std::cos(start.radians), std::sin(start.radians)); if (use_center) { MoveTo(center); LineTo(center + p1_unit * radius); } else { MoveTo(center + p1_unit * radius); } while (sweep.radians > 0) { Vector2 p2_unit; Scalar quadrant_angle; if (sweep.radians < kPiOver2) { quadrant_angle = sweep.radians; p2_unit = Vector2(std::cos(start.radians + quadrant_angle), std::sin(start.radians + quadrant_angle)); } else { quadrant_angle = kPiOver2; p2_unit = Vector2(-p1_unit.y, p1_unit.x); } Vector2 arc_cp_lengths = (quadrant_angle / kPiOver2) * kArcApproximationMagic * radius; Point p1 = center + p1_unit * radius; Point p2 = center + p2_unit * radius; Point cp1 = p1 + Vector2(-p1_unit.y, p1_unit.x) * arc_cp_lengths; Point cp2 = p2 + Vector2(p2_unit.y, -p2_unit.x) * arc_cp_lengths; AddCubicComponent(p1, cp1, cp2, p2); current_ = p2; start.radians += quadrant_angle; sweep.radians -= quadrant_angle; p1_unit = p2_unit; } if (use_center) { Close(); } return *this; } PathBuilder& PathBuilder::AddOval(const Rect& container) { const Point c = container.GetCenter(); const Point r = c - container.GetOrigin(); const Point m = r * kArcApproximationMagic; MoveTo({c.x, c.y - r.y}); //---------------------------------------------------------------------------- // Top right arc. // AddCubicComponent({c.x, c.y - r.y}, // p1 {c.x + m.x, c.y - r.y}, // cp1 {c.x + r.x, c.y - m.y}, // cp2 {c.x + r.x, c.y} // p2 ); //---------------------------------------------------------------------------- // Bottom right arc. // AddCubicComponent({c.x + r.x, c.y}, // p1 {c.x + r.x, c.y + m.y}, // cp1 {c.x + m.x, c.y + r.y}, // cp2 {c.x, c.y + r.y} // p2 ); //---------------------------------------------------------------------------- // Bottom left arc. // AddCubicComponent({c.x, c.y + r.y}, // p1 {c.x - m.x, c.y + r.y}, // cp1 {c.x - r.x, c.y + m.y}, // cp2 {c.x - r.x, c.y} // p2 ); //---------------------------------------------------------------------------- // Top left arc. // AddCubicComponent({c.x - r.x, c.y}, // p1 {c.x - r.x, c.y - m.y}, // cp1 {c.x - m.x, c.y - r.y}, // cp2 {c.x, c.y - r.y} // p2 ); Close(); return *this; } PathBuilder& PathBuilder::AddLine(const Point& p1, const Point& p2) { MoveTo(p1); AddLinearComponent(p1, p2); return *this; } PathBuilder& PathBuilder::AddPath(const Path& path) { auto linear = [&](size_t index, const LinearPathComponent& l) { AddLinearComponent(l.p1, l.p2); }; auto quadratic = [&](size_t index, const QuadraticPathComponent& q) { AddQuadraticComponent(q.p1, q.cp, q.p2); }; auto cubic = [&](size_t index, const CubicPathComponent& c) { AddCubicComponent(c.p1, c.cp1, c.cp2, c.p2); }; auto move = [&](size_t index, const ContourComponent& m) { AddContourComponent(m.destination); }; path.EnumerateComponents(linear, quadratic, cubic, move); return *this; } PathBuilder& PathBuilder::Shift(Point offset) { for (auto& point : prototype_.points) { point += offset; } for (auto& contour : prototype_.contours) { contour.destination += offset; } prototype_.bounds.reset(); return *this; } PathBuilder& PathBuilder::SetBounds(Rect bounds) { prototype_.bounds = bounds; return *this; } void PathBuilder::UpdateBounds() { if (!prototype_.bounds.has_value()) { auto min_max = GetMinMaxCoveragePoints(); if (!min_max.has_value()) { prototype_.bounds.reset(); return; } auto min = min_max->first; auto max = min_max->second; const auto difference = max - min; prototype_.bounds = Rect::MakeXYWH(min.x, min.y, difference.x, difference.y); } } std::optional<std::pair<Point, Point>> PathBuilder::GetMinMaxCoveragePoints() const { auto& points = prototype_.points; if (points.empty()) { return std::nullopt; } std::optional<Point> min, max; auto clamp = [&min, &max](const Point& point) { if (min.has_value()) { min = min->Min(point); } else { min = point; } if (max.has_value()) { max = max->Max(point); } else { max = point; } }; for (const auto& component : prototype_.components) { switch (component.type) { case Path::ComponentType::kLinear: { auto* linear = reinterpret_cast<const LinearPathComponent*>( &points[component.index]); clamp(linear->p1); clamp(linear->p2); break; } case Path::ComponentType::kQuadratic: for (const auto& extrema : reinterpret_cast<const QuadraticPathComponent*>( &points[component.index]) ->Extrema()) { clamp(extrema); } break; case Path::ComponentType::kCubic: for (const auto& extrema : reinterpret_cast<const CubicPathComponent*>( &points[component.index]) ->Extrema()) { clamp(extrema); } break; case Path::ComponentType::kContour: break; } } if (!min.has_value() || !max.has_value()) { return std::nullopt; } return std::make_pair(min.value(), max.value()); } } // namespace impeller
engine/impeller/geometry/path_builder.cc/0
{ "file_path": "engine/impeller/geometry/path_builder.cc", "repo_id": "engine", "token_count": 6898 }
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. #ifndef FLUTTER_IMPELLER_GEOMETRY_SHEAR_H_ #define FLUTTER_IMPELLER_GEOMETRY_SHEAR_H_ #include <string> namespace impeller { struct Shear { union { struct { double xy = 0.0; double xz = 0.0; double yz = 0.0; }; double e[3]; }; Shear() {} Shear(double xy, double xz, double yz) : xy(xy), xz(xz), yz(yz) {} bool operator==(const Shear& o) const { return xy == o.xy && xz == o.xz && yz == o.yz; } bool operator!=(const Shear& o) const { return !(*this == o); } }; } // namespace impeller #endif // FLUTTER_IMPELLER_GEOMETRY_SHEAR_H_
engine/impeller/geometry/shear.h/0
{ "file_path": "engine/impeller/geometry/shear.h", "repo_id": "engine", "token_count": 319 }
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. #ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_DIGEST_H_ #define FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_DIGEST_H_ #include <map> #include <string> #include <vector> #include "flutter/fml/macros.h" #include "flutter/impeller/golden_tests/working_directory.h" namespace impeller { namespace testing { /// Manages a global variable for tracking instances of golden images. class GoldenDigest { public: static GoldenDigest* Instance(); void AddDimension(const std::string& name, const std::string& value); void AddImage(const std::string& test_name, const std::string& filename, int32_t width, int32_t height); /// Writes a "digest.json" file to `working_directory`. /// /// Returns `true` on success. bool Write(WorkingDirectory* working_directory); private: GoldenDigest(const GoldenDigest&) = delete; GoldenDigest& operator=(const GoldenDigest&) = delete; GoldenDigest(); struct Entry { std::string test_name; std::string filename; int32_t width; int32_t height; double max_diff_pixels_percent; int32_t max_color_delta; }; static GoldenDigest* instance_; std::vector<Entry> entries_; std::map<std::string, std::string> dimensions_; }; } // namespace testing } // namespace impeller #endif // FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_DIGEST_H_
engine/impeller/golden_tests/golden_digest.h/0
{ "file_path": "engine/impeller/golden_tests/golden_digest.h", "repo_id": "engine", "token_count": 557 }
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. import("//flutter/impeller/tools/impeller.gni") import("//flutter/testing/testing.gni") impeller_component("playground") { testonly = true sources = [ "playground.cc", "playground.h", "playground_impl.cc", "playground_impl.h", "switches.cc", "switches.h", "widgets.cc", "widgets.h", # Swiftshader is Vulkan backend specific but the utilities are not. "backend/vulkan/swiftshader_utilities.cc", "backend/vulkan/swiftshader_utilities.h", ] deps = [ "../renderer/backend" ] if (impeller_enable_metal) { sources += [ "backend/metal/playground_impl_mtl.h", "backend/metal/playground_impl_mtl.mm", ] } if (impeller_enable_opengles) { sources += [ "backend/gles/playground_impl_gles.cc", "backend/gles/playground_impl_gles.h", ] } if (impeller_enable_vulkan) { sources += [ "backend/vulkan/playground_impl_vk.cc", "backend/vulkan/playground_impl_vk.h", ] } public_deps = [ "../fixtures:shader_fixtures", "../renderer", "../scene/shaders", "image:image_skia_backend", "imgui:imgui_impeller_backend", "//flutter/fml", "//flutter/testing:testing_lib", "//flutter/third_party/glfw", "//flutter/third_party/imgui:imgui_glfw", ] if (impeller_supports_rendering) { public_deps += [ "../entity:entity_shaders", "../entity:framebuffer_blend_entity_shaders", "../entity:modern_entity_shaders", ] } if (is_mac) { frameworks = [ "AppKit.framework", "QuartzCore.framework", ] } } impeller_component("playground_test") { testonly = true sources = [ "compute_playground_test.cc", "compute_playground_test.h", "playground_test.cc", "playground_test.h", ] public_deps = [ ":playground", "//flutter/testing:testing_lib", ] }
engine/impeller/playground/BUILD.gn/0
{ "file_path": "engine/impeller/playground/BUILD.gn", "repo_id": "engine", "token_count": 886 }
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. #include "impeller/playground/image/compressed_image.h" namespace impeller { CompressedImage::CompressedImage(std::shared_ptr<const fml::Mapping> allocation) : source_(std::move(allocation)) {} CompressedImage::~CompressedImage() = default; bool CompressedImage::IsValid() const { return static_cast<bool>(source_); } } // namespace impeller
engine/impeller/playground/image/compressed_image.cc/0
{ "file_path": "engine/impeller/playground/image/compressed_image.cc", "repo_id": "engine", "token_count": 157 }
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. #ifndef FLUTTER_IMPELLER_PLAYGROUND_SWITCHES_H_ #define FLUTTER_IMPELLER_PLAYGROUND_SWITCHES_H_ #include <chrono> #include <optional> #include "flutter/fml/command_line.h" #include "flutter/fml/macros.h" namespace impeller { struct PlaygroundSwitches { bool enable_playground = false; // If specified, the playgrounds will render for at least the duration // specified in the timeout. If the timeout is zero, exactly one frame will be // rendered in the playground. std::optional<std::chrono::milliseconds> timeout; bool enable_vulkan_validation = false; //---------------------------------------------------------------------------- /// Seek a SwiftShader library in known locations and use it when running /// Vulkan. It is a fatal error to provide this option and not have the test /// find a SwiftShader implementation. /// bool use_swiftshader = false; /// Attempt to use Angle on the system instead of the available OpenGL ES /// implementation. This is on-by-default on macOS due to the broken-ness in /// the deprecated OpenGL implementation. On other platforms, it this opt-in /// via the flag with the system OpenGL ES implementation used by fault. /// bool use_angle = false; PlaygroundSwitches(); explicit PlaygroundSwitches(const fml::CommandLine& args); }; } // namespace impeller #endif // FLUTTER_IMPELLER_PLAYGROUND_SWITCHES_H_
engine/impeller/playground/switches.h/0
{ "file_path": "engine/impeller/playground/switches.h", "repo_id": "engine", "token_count": 434 }
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. #include "impeller/renderer/backend/gles/command_buffer_gles.h" #include "impeller/base/config.h" #include "impeller/renderer/backend/gles/blit_pass_gles.h" #include "impeller/renderer/backend/gles/render_pass_gles.h" namespace impeller { CommandBufferGLES::CommandBufferGLES(std::weak_ptr<const Context> context, ReactorGLES::Ref reactor) : CommandBuffer(std::move(context)), reactor_(std::move(reactor)), is_valid_(reactor_ && reactor_->IsValid()) {} CommandBufferGLES::~CommandBufferGLES() = default; // |CommandBuffer| void CommandBufferGLES::SetLabel(const std::string& label) const { // Cannot support. } // |CommandBuffer| bool CommandBufferGLES::IsValid() const { return is_valid_; } // |CommandBuffer| bool CommandBufferGLES::OnSubmitCommands(CompletionCallback callback) { const auto result = reactor_->React(); if (callback) { callback(result ? CommandBuffer::Status::kCompleted : CommandBuffer::Status::kError); } return result; } // |CommandBuffer| void CommandBufferGLES::OnWaitUntilScheduled() { reactor_->GetProcTable().Flush(); } // |CommandBuffer| std::shared_ptr<RenderPass> CommandBufferGLES::OnCreateRenderPass( RenderTarget target) { if (!IsValid()) { return nullptr; } auto context = context_.lock(); if (!context) { return nullptr; } auto pass = std::shared_ptr<RenderPassGLES>( new RenderPassGLES(context, target, reactor_)); if (!pass->IsValid()) { return nullptr; } return pass; } // |CommandBuffer| std::shared_ptr<BlitPass> CommandBufferGLES::OnCreateBlitPass() { if (!IsValid()) { return nullptr; } auto pass = std::shared_ptr<BlitPassGLES>(new BlitPassGLES(reactor_)); if (!pass->IsValid()) { return nullptr; } return pass; } // |CommandBuffer| std::shared_ptr<ComputePass> CommandBufferGLES::OnCreateComputePass() { // Compute passes aren't supported until GLES 3.2, at which point Vulkan is // available anyway. return nullptr; } } // namespace impeller
engine/impeller/renderer/backend/gles/command_buffer_gles.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/command_buffer_gles.cc", "repo_id": "engine", "token_count": 798 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_GLES_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_GLES_H_ #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" #include "impeller/renderer/backend/gles/buffer_bindings_gles.h" #include "impeller/renderer/backend/gles/handle_gles.h" #include "impeller/renderer/backend/gles/reactor_gles.h" #include "impeller/renderer/pipeline.h" namespace impeller { class PipelineLibraryGLES; class PipelineGLES final : public Pipeline<PipelineDescriptor>, public BackendCast<PipelineGLES, Pipeline<PipelineDescriptor>> { public: // |Pipeline| ~PipelineGLES() override; const HandleGLES& GetProgramHandle() const; [[nodiscard]] bool BindProgram() const; [[nodiscard]] bool UnbindProgram() const; BufferBindingsGLES* GetBufferBindings() const; [[nodiscard]] bool BuildVertexDescriptor(const ProcTableGLES& gl, GLuint program); private: friend PipelineLibraryGLES; ReactorGLES::Ref reactor_; HandleGLES handle_; std::unique_ptr<BufferBindingsGLES> buffer_bindings_; bool is_valid_ = false; // |Pipeline| bool IsValid() const override; PipelineGLES(ReactorGLES::Ref reactor, std::weak_ptr<PipelineLibrary> library, const PipelineDescriptor& desc); PipelineGLES(const PipelineGLES&) = delete; PipelineGLES& operator=(const PipelineGLES&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_GLES_H_
engine/impeller/renderer/backend/gles/pipeline_gles.h/0
{ "file_path": "engine/impeller/renderer/backend/gles/pipeline_gles.h", "repo_id": "engine", "token_count": 669 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_LIBRARY_GLES_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_LIBRARY_GLES_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "impeller/base/comparable.h" #include "impeller/base/thread.h" #include "impeller/renderer/shader_key.h" #include "impeller/renderer/shader_library.h" namespace impeller { class ShaderLibraryGLES final : public ShaderLibrary { public: // |ShaderLibrary| ~ShaderLibraryGLES() override; // |ShaderLibrary| bool IsValid() const override; private: friend class ContextGLES; const UniqueID library_id_; mutable RWMutex functions_mutex_; ShaderFunctionMap functions_ IPLR_GUARDED_BY(functions_mutex_); bool is_valid_ = false; explicit ShaderLibraryGLES( const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries); // |ShaderLibrary| std::shared_ptr<const ShaderFunction> GetFunction(std::string_view name, ShaderStage stage) override; // |ShaderLibrary| void RegisterFunction(std::string name, ShaderStage stage, std::shared_ptr<fml::Mapping> code, RegistrationCallback callback) override; // |ShaderLibrary| void UnregisterFunction(std::string name, ShaderStage stage) override; ShaderLibraryGLES(const ShaderLibraryGLES&) = delete; ShaderLibraryGLES& operator=(const ShaderLibraryGLES&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_LIBRARY_GLES_H_
engine/impeller/renderer/backend/gles/shader_library_gles.h/0
{ "file_path": "engine/impeller/renderer/backend/gles/shader_library_gles.h", "repo_id": "engine", "token_count": 705 }
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. #include "impeller/renderer/backend/metal/allocator_mtl.h" #include "flutter/fml/build_config.h" #include "flutter/fml/logging.h" #include "impeller/base/validation.h" #include "impeller/renderer/backend/metal/device_buffer_mtl.h" #include "impeller/renderer/backend/metal/formats_mtl.h" #include "impeller/renderer/backend/metal/texture_mtl.h" namespace impeller { static bool DeviceSupportsDeviceTransientTargets(id<MTLDevice> device) { // Refer to the "Memoryless render targets" feature in the table below: // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf if (@available(ios 13.0, tvos 13.0, macos 10.15, *)) { return [device supportsFamily:MTLGPUFamilyApple2]; } else { #if FML_OS_IOS // This is perhaps redundant. But, just in case we somehow get into a case // where Impeller runs on iOS versions less than 8.0 and/or without A8 // GPUs, we explicitly check feature set support. return [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v1]; #else // MacOS devices with Apple GPUs are only available with macos 10.15 and // above. So, if we are here, it is safe to assume that memory-less targets // are not supported. return false; #endif } FML_UNREACHABLE(); } static bool DeviceHasUnifiedMemoryArchitecture(id<MTLDevice> device) { if (@available(ios 13.0, tvos 13.0, macOS 10.15, *)) { return [device hasUnifiedMemory]; } else { #if FML_OS_IOS // iOS devices where the availability check can fail always have had UMA. return true; #else // Mac devices where the availability check can fail have never had UMA. return false; #endif } FML_UNREACHABLE(); } static ISize DeviceMaxTextureSizeSupported(id<MTLDevice> device) { // Since Apple didn't expose API for us to get the max texture size, we have // to use hardcoded data from // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf // According to the feature set table, there are two supported max sizes : // 16384 and 8192 for devices flutter support. The former is used on macs and // latest ios devices. The latter is used on old ios devices. if (@available(macOS 10.15, iOS 13, tvOS 13, *)) { if ([device supportsFamily:MTLGPUFamilyApple3] || [device supportsFamily:MTLGPUFamilyMacCatalyst1] || [device supportsFamily:MTLGPUFamilyMac1]) { return {16384, 16384}; } return {8192, 8192}; } else { #if FML_OS_IOS if ([device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily4_v1] || [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) { return {16384, 16384}; } #endif #if FML_OS_MACOSX return {16384, 16384}; #endif return {8192, 8192}; } } static bool SupportsLossyTextureCompression(id<MTLDevice> device) { #ifdef FML_OS_IOS_SIMULATOR return false; #else if (@available(macOS 10.15, iOS 13, tvOS 13, *)) { return [device supportsFamily:MTLGPUFamilyApple8]; } return false; #endif } AllocatorMTL::AllocatorMTL(id<MTLDevice> device, std::string label) : device_(device), allocator_label_(std::move(label)) { if (!device_) { return; } supports_memoryless_targets_ = DeviceSupportsDeviceTransientTargets(device_); supports_uma_ = DeviceHasUnifiedMemoryArchitecture(device_); max_texture_supported_ = DeviceMaxTextureSizeSupported(device_); is_valid_ = true; } AllocatorMTL::~AllocatorMTL() = default; bool AllocatorMTL::IsValid() const { return is_valid_; } static MTLResourceOptions ToMTLResourceOptions(StorageMode type, bool supports_memoryless_targets, bool supports_uma) { switch (type) { case StorageMode::kHostVisible: #if FML_OS_IOS return MTLResourceStorageModeShared; #else if (supports_uma) { return MTLResourceStorageModeShared; } else { return MTLResourceStorageModeManaged; } #endif case StorageMode::kDevicePrivate: return MTLResourceStorageModePrivate; case StorageMode::kDeviceTransient: if (supports_memoryless_targets) { // Device may support but the OS has not been updated. if (@available(macOS 11.0, *)) { return MTLResourceStorageModeMemoryless; } else { return MTLResourceStorageModePrivate; } } else { return MTLResourceStorageModePrivate; } FML_UNREACHABLE(); } FML_UNREACHABLE(); } static MTLStorageMode ToMTLStorageMode(StorageMode mode, bool supports_memoryless_targets, bool supports_uma) { switch (mode) { case StorageMode::kHostVisible: #if FML_OS_IOS return MTLStorageModeShared; #else if (supports_uma) { return MTLStorageModeShared; } else { return MTLStorageModeManaged; } #endif case StorageMode::kDevicePrivate: return MTLStorageModePrivate; case StorageMode::kDeviceTransient: if (supports_memoryless_targets) { // Device may support but the OS has not been updated. if (@available(macOS 11.0, *)) { return MTLStorageModeMemoryless; } else { return MTLStorageModePrivate; } } else { return MTLStorageModePrivate; } FML_UNREACHABLE(); } FML_UNREACHABLE(); } std::shared_ptr<DeviceBuffer> AllocatorMTL::OnCreateBuffer( const DeviceBufferDescriptor& desc) { const auto resource_options = ToMTLResourceOptions( desc.storage_mode, supports_memoryless_targets_, supports_uma_); const auto storage_mode = ToMTLStorageMode( desc.storage_mode, supports_memoryless_targets_, supports_uma_); auto buffer = [device_ newBufferWithLength:desc.size options:resource_options]; if (!buffer) { return nullptr; } return std::shared_ptr<DeviceBufferMTL>(new DeviceBufferMTL(desc, // buffer, // storage_mode // )); } std::shared_ptr<Texture> AllocatorMTL::OnCreateTexture( const TextureDescriptor& desc) { if (!IsValid()) { return nullptr; } auto mtl_texture_desc = ToMTLTextureDescriptor(desc); if (!mtl_texture_desc) { VALIDATION_LOG << "Texture descriptor was invalid."; return nullptr; } mtl_texture_desc.storageMode = ToMTLStorageMode( desc.storage_mode, supports_memoryless_targets_, supports_uma_); if (@available(macOS 12.5, ios 15.0, *)) { if (desc.compression_type == CompressionType::kLossy && SupportsLossyTextureCompression(device_)) { mtl_texture_desc.compressionType = MTLTextureCompressionTypeLossy; } } auto texture = [device_ newTextureWithDescriptor:mtl_texture_desc]; if (!texture) { return nullptr; } return TextureMTL::Create(desc, texture); } uint16_t AllocatorMTL::MinimumBytesPerRow(PixelFormat format) const { return static_cast<uint16_t>([device_ minimumLinearTextureAlignmentForPixelFormat:ToMTLPixelFormat(format)]); } ISize AllocatorMTL::GetMaxTextureSizeSupported() const { return max_texture_supported_; } } // namespace impeller
engine/impeller/renderer/backend/metal/allocator_mtl.mm/0
{ "file_path": "engine/impeller/renderer/backend/metal/allocator_mtl.mm", "repo_id": "engine", "token_count": 3010 }
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. #include "impeller/renderer/backend/metal/device_buffer_mtl.h" #include "flutter/fml/logging.h" #include "impeller/base/validation.h" #include "impeller/renderer/backend/metal/formats_mtl.h" #include "impeller/renderer/backend/metal/texture_mtl.h" namespace impeller { DeviceBufferMTL::DeviceBufferMTL(DeviceBufferDescriptor desc, id<MTLBuffer> buffer, MTLStorageMode storage_mode) : DeviceBuffer(desc), buffer_(buffer), storage_mode_(storage_mode) {} DeviceBufferMTL::~DeviceBufferMTL() = default; id<MTLBuffer> DeviceBufferMTL::GetMTLBuffer() const { return buffer_; } uint8_t* DeviceBufferMTL::OnGetContents() const { if (storage_mode_ != MTLStorageModeShared) { return nullptr; } return reinterpret_cast<uint8_t*>(buffer_.contents); } std::shared_ptr<Texture> DeviceBufferMTL::AsTexture( Allocator& allocator, const TextureDescriptor& descriptor, uint16_t row_bytes) const { auto mtl_texture_desc = ToMTLTextureDescriptor(descriptor); if (!mtl_texture_desc) { VALIDATION_LOG << "Texture descriptor was invalid."; return nullptr; } if (@available(iOS 13.0, macos 10.15, *)) { mtl_texture_desc.resourceOptions = buffer_.resourceOptions; } auto texture = [buffer_ newTextureWithDescriptor:mtl_texture_desc offset:0 bytesPerRow:row_bytes]; if (!texture) { return nullptr; } return TextureMTL::Create(descriptor, texture); } [[nodiscard]] bool DeviceBufferMTL::OnCopyHostBuffer(const uint8_t* source, Range source_range, size_t offset) { auto dest = static_cast<uint8_t*>(buffer_.contents); if (!dest) { return false; } if (source) { ::memmove(dest + offset, source + source_range.offset, source_range.length); } // MTLStorageModeManaged is never present on always returns false on iOS. But // the compiler is mad that `didModifyRange:` appears in a TU meant for iOS. So, // just compile it away. #if !FML_OS_IOS if (storage_mode_ == MTLStorageModeManaged) { [buffer_ didModifyRange:NSMakeRange(offset, source_range.length)]; } #endif return true; } void DeviceBufferMTL::Flush(std::optional<Range> range) const { #if !FML_OS_IOS auto flush_range = range.value_or(Range{0, GetDeviceBufferDescriptor().size}); if (storage_mode_ == MTLStorageModeManaged) { [buffer_ didModifyRange:NSMakeRange(flush_range.offset, flush_range.length)]; } #endif } bool DeviceBufferMTL::SetLabel(const std::string& label) { if (label.empty()) { return false; } [buffer_ setLabel:@(label.c_str())]; return true; } bool DeviceBufferMTL::SetLabel(const std::string& label, Range range) { if (label.empty()) { return false; } [buffer_ addDebugMarker:@(label.c_str()) range:NSMakeRange(range.offset, range.length)]; return true; } } // namespace impeller
engine/impeller/renderer/backend/metal/device_buffer_mtl.mm/0
{ "file_path": "engine/impeller/renderer/backend/metal/device_buffer_mtl.mm", "repo_id": "engine", "token_count": 1319 }
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. #include "impeller/renderer/backend/metal/sampler_library_mtl.h" #include "impeller/renderer/backend/metal/formats_mtl.h" #include "impeller/renderer/backend/metal/sampler_mtl.h" namespace impeller { SamplerLibraryMTL::SamplerLibraryMTL(id<MTLDevice> device) : device_(device) {} SamplerLibraryMTL::~SamplerLibraryMTL() = default; static const std::unique_ptr<const Sampler> kNullSampler = nullptr; const std::unique_ptr<const Sampler>& SamplerLibraryMTL::GetSampler( SamplerDescriptor descriptor) { auto found = samplers_.find(descriptor); if (found != samplers_.end()) { return found->second; } if (!device_) { return kNullSampler; } auto desc = [[MTLSamplerDescriptor alloc] init]; desc.minFilter = ToMTLSamplerMinMagFilter(descriptor.min_filter); desc.magFilter = ToMTLSamplerMinMagFilter(descriptor.mag_filter); desc.mipFilter = ToMTLSamplerMipFilter(descriptor.mip_filter); desc.sAddressMode = ToMTLSamplerAddressMode(descriptor.width_address_mode); desc.tAddressMode = ToMTLSamplerAddressMode(descriptor.height_address_mode); desc.rAddressMode = ToMTLSamplerAddressMode(descriptor.depth_address_mode); if (@available(iOS 14.0, macos 10.12, *)) { desc.borderColor = MTLSamplerBorderColorTransparentBlack; } if (!descriptor.label.empty()) { desc.label = @(descriptor.label.c_str()); } auto mtl_sampler = [device_ newSamplerStateWithDescriptor:desc]; if (!mtl_sampler) { return kNullSampler; } auto sampler = std::unique_ptr<SamplerMTL>(new SamplerMTL(descriptor, mtl_sampler)); return (samplers_[descriptor] = std::move(sampler)); } } // namespace impeller
engine/impeller/renderer/backend/metal/sampler_library_mtl.mm/0
{ "file_path": "engine/impeller/renderer/backend/metal/sampler_library_mtl.mm", "repo_id": "engine", "token_count": 654 }
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("//flutter/vulkan/config.gni") import("../../../tools/impeller.gni") impeller_component("vulkan_unittests") { testonly = true sources = [ "allocator_vk_unittests.cc", "blit_command_vk_unittests.cc", "command_encoder_vk_unittests.cc", "command_pool_vk_unittests.cc", "context_vk_unittests.cc", "descriptor_pool_vk_unittests.cc", "driver_info_vk_unittests.cc", "fence_waiter_vk_unittests.cc", "render_pass_cache_unittests.cc", "resource_manager_vk_unittests.cc", "test/gpu_tracer_unittests.cc", "test/mock_vulkan.cc", "test/mock_vulkan.h", "test/mock_vulkan_unittests.cc", "test/swapchain_unittests.cc", ] deps = [ ":vulkan", "../../../playground:playground_test", "//flutter/testing:testing_lib", ] } impeller_component("vulkan") { sources = [ "allocator_vk.cc", "allocator_vk.h", "barrier_vk.cc", "barrier_vk.h", "blit_command_vk.cc", "blit_command_vk.h", "blit_pass_vk.cc", "blit_pass_vk.h", "capabilities_vk.cc", "capabilities_vk.h", "command_buffer_vk.cc", "command_buffer_vk.h", "command_encoder_vk.cc", "command_encoder_vk.h", "command_pool_vk.cc", "command_pool_vk.h", "command_queue_vk.cc", "command_queue_vk.h", "compute_pass_vk.cc", "compute_pass_vk.h", "compute_pipeline_vk.cc", "compute_pipeline_vk.h", "context_vk.cc", "context_vk.h", "debug_report_vk.cc", "debug_report_vk.h", "descriptor_pool_vk.cc", "descriptor_pool_vk.h", "device_buffer_vk.cc", "device_buffer_vk.h", "device_holder_vk.h", "driver_info_vk.cc", "driver_info_vk.h", "fence_waiter_vk.cc", "fence_waiter_vk.h", "formats_vk.cc", "formats_vk.h", "gpu_tracer_vk.cc", "gpu_tracer_vk.h", "limits_vk.h", "pipeline_cache_vk.cc", "pipeline_cache_vk.h", "pipeline_library_vk.cc", "pipeline_library_vk.h", "pipeline_vk.cc", "pipeline_vk.h", "queue_vk.cc", "queue_vk.h", "render_pass_builder_vk.cc", "render_pass_builder_vk.h", "render_pass_vk.cc", "render_pass_vk.h", "resource_manager_vk.cc", "resource_manager_vk.h", "sampler_library_vk.cc", "sampler_library_vk.h", "sampler_vk.cc", "sampler_vk.h", "shader_function_vk.cc", "shader_function_vk.h", "shader_library_vk.cc", "shader_library_vk.h", "shared_object_vk.cc", "shared_object_vk.h", "surface_context_vk.cc", "surface_context_vk.h", "swapchain/khr/khr_surface_vk.cc", "swapchain/khr/khr_surface_vk.h", "swapchain/khr/khr_swapchain_image_vk.cc", "swapchain/khr/khr_swapchain_image_vk.h", "swapchain/khr/khr_swapchain_impl_vk.cc", "swapchain/khr/khr_swapchain_impl_vk.h", "swapchain/khr/khr_swapchain_vk.cc", "swapchain/khr/khr_swapchain_vk.h", "texture_source_vk.cc", "texture_source_vk.h", "texture_vk.cc", "texture_vk.h", "tracked_objects_vk.cc", "tracked_objects_vk.h", "vertex_descriptor_vk.cc", "vertex_descriptor_vk.h", "vk.h", "vma.cc", "vma.h", "yuv_conversion_library_vk.cc", "yuv_conversion_library_vk.h", "yuv_conversion_vk.cc", "yuv_conversion_vk.h", ] if (is_android) { sources += [ "android/ahb_texture_source_vk.cc", "android/ahb_texture_source_vk.h", ] } public_deps = [ "../../:renderer", "../../../shader_archive", "//flutter/flutter_vma", "//flutter/fml", "//flutter/third_party/vulkan-deps/vulkan-headers/src:vulkan_headers", "//flutter/third_party/vulkan_memory_allocator", ] }
engine/impeller/renderer/backend/vulkan/BUILD.gn/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/BUILD.gn", "repo_id": "engine", "token_count": 1976 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_BUFFER_VK_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_BUFFER_VK_H_ #include "impeller/base/backend_cast.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/command_buffer.h" namespace impeller { class ContextVK; class CommandEncoderFactoryVK; class CommandEncoderVK; class CommandBufferVK final : public CommandBuffer, public BackendCast<CommandBufferVK, CommandBuffer>, public std::enable_shared_from_this<CommandBufferVK> { public: // |CommandBuffer| ~CommandBufferVK() override; const std::shared_ptr<CommandEncoderVK>& GetEncoder(); private: friend class ContextVK; std::shared_ptr<CommandEncoderVK> encoder_; std::shared_ptr<CommandEncoderFactoryVK> encoder_factory_; CommandBufferVK(std::weak_ptr<const Context> context, std::shared_ptr<CommandEncoderFactoryVK> encoder_factory); // |CommandBuffer| void SetLabel(const std::string& label) const override; // |CommandBuffer| bool IsValid() const override; // |CommandBuffer| bool OnSubmitCommands(CompletionCallback callback) override; // |CommandBuffer| void OnWaitUntilScheduled() override; // |CommandBuffer| std::shared_ptr<RenderPass> OnCreateRenderPass(RenderTarget target) override; // |CommandBuffer| std::shared_ptr<BlitPass> OnCreateBlitPass() override; // |CommandBuffer| std::shared_ptr<ComputePass> OnCreateComputePass() override; CommandBufferVK(const CommandBufferVK&) = delete; CommandBufferVK& operator=(const CommandBufferVK&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_BUFFER_VK_H_
engine/impeller/renderer/backend/vulkan/command_buffer_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/command_buffer_vk.h", "repo_id": "engine", "token_count": 640 }
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. #include "impeller/renderer/backend/vulkan/debug_report_vk.h" #include "impeller/base/validation.h" #include "impeller/renderer/backend/vulkan/capabilities_vk.h" namespace impeller { DebugReportVK::DebugReportVK(const CapabilitiesVK& caps, const vk::Instance& instance) { if (!caps.AreValidationsEnabled()) { is_valid_ = true; return; } vk::DebugUtilsMessengerCreateInfoEXT messenger_info; messenger_info.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError; messenger_info.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation; messenger_info.pUserData = this; messenger_info.pfnUserCallback = DebugUtilsMessengerCallback; auto messenger = instance.createDebugUtilsMessengerEXTUnique(messenger_info); if (messenger.result != vk::Result::eSuccess) { FML_LOG(ERROR) << "Could not create debug messenger: " << vk::to_string(messenger.result); return; } messenger_ = std::move(messenger.value); is_valid_ = true; } DebugReportVK::~DebugReportVK() = default; bool DebugReportVK::IsValid() const { return is_valid_; } static std::string JoinLabels(const VkDebugUtilsLabelEXT* labels, size_t count) { std::stringstream stream; for (size_t i = 0u; i < count; i++) { stream << labels[i].pLabelName; if (i != count - 1u) { stream << ", "; } } return stream.str(); } static std::string JoinVKDebugUtilsObjectNameInfoEXT( const VkDebugUtilsObjectNameInfoEXT* names, size_t count) { std::stringstream stream; for (size_t i = 0u; i < count; i++) { stream << vk::to_string(vk::ObjectType(names[i].objectType)) << " [" << names[i].objectHandle << "] ["; if (names[i].pObjectName != nullptr) { stream << names[i].pObjectName; } else { stream << "UNNAMED"; } stream << "]"; if (i != count - 1u) { stream << ", "; } } return stream.str(); } VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportVK::DebugUtilsMessengerCallback( VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* callback_data, void* debug_report) { auto result = reinterpret_cast<DebugReportVK*>(debug_report) ->OnDebugCallback( static_cast<vk::DebugUtilsMessageSeverityFlagBitsEXT>( severity), // static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(type), // callback_data // ); switch (result) { case Result::kContinue: return VK_FALSE; case Result::kAbort: return VK_TRUE; } return VK_FALSE; } DebugReportVK::Result DebugReportVK::OnDebugCallback( vk::DebugUtilsMessageSeverityFlagBitsEXT severity, vk::DebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* data) { // This is a real issue caused by INPUT_ATTACHMENT_BIT not being a supported // `VkSurfaceCapabilitiesKHR::supportedUsageFlags` on any platform other than // Android. This is necessary for all the framebuffer fetch related tests. We // can get away with suppressing this on macOS but this must be fixed. if (data->messageIdNumber == 0x2c36905d) { return Result::kContinue; } std::vector<std::pair<std::string, std::string>> items; items.emplace_back("Severity", vk::to_string(severity)); items.emplace_back("Type", vk::to_string(type)); if (data->pMessageIdName) { items.emplace_back("ID Name", data->pMessageIdName); } items.emplace_back("ID Number", std::to_string(data->messageIdNumber)); if (auto queues = JoinLabels(data->pQueueLabels, data->queueLabelCount); !queues.empty()) { items.emplace_back("Queue Breadcrumbs", std::move(queues)); } else { items.emplace_back("Queue Breadcrumbs", "[NONE]"); } if (auto cmd_bufs = JoinLabels(data->pCmdBufLabels, data->cmdBufLabelCount); !cmd_bufs.empty()) { items.emplace_back("CMD Buffer Breadcrumbs", std::move(cmd_bufs)); } else { items.emplace_back("CMD Buffer Breadcrumbs", "[NONE]"); } if (auto related = JoinVKDebugUtilsObjectNameInfoEXT(data->pObjects, data->objectCount); !related.empty()) { items.emplace_back("Related Objects", std::move(related)); } if (data->pMessage) { items.emplace_back("Trigger", data->pMessage); } size_t padding = 0; for (const auto& item : items) { padding = std::max(padding, item.first.size()); } padding += 1; std::stringstream stream; stream << std::endl; stream << "--- Vulkan Debug Report ----------------------------------------"; stream << std::endl; for (const auto& item : items) { stream << "| " << std::setw(static_cast<int>(padding)) << item.first << std::setw(0) << ": " << item.second << std::endl; } stream << "-----------------------------------------------------------------"; if (type == vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance) { FML_LOG(INFO) << stream.str(); } else { VALIDATION_LOG << stream.str(); } return Result::kContinue; } } // namespace impeller
engine/impeller/renderer/backend/vulkan/debug_report_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/debug_report_vk.cc", "repo_id": "engine", "token_count": 2161 }
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. #include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" #include <memory> #include <optional> #include <thread> #include <utility> #include "fml/logging.h" #include "fml/trace_event.h" #include "impeller/base/validation.h" #include "impeller/renderer/backend/vulkan/command_buffer_vk.h" #include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "vulkan/vulkan.hpp" namespace impeller { static constexpr uint32_t kPoolSize = 128u; GPUTracerVK::GPUTracerVK(std::weak_ptr<ContextVK> context, bool enable_gpu_tracing) : context_(std::move(context)) { if (!enable_gpu_tracing) { return; } timestamp_period_ = context_.lock() ->GetDeviceHolder() ->GetPhysicalDevice() .getProperties() .limits.timestampPeriod; if (timestamp_period_ <= 0) { // The device does not support timestamp queries. return; } // Disable tracing in release mode. #ifdef IMPELLER_DEBUG enabled_ = true; #endif // IMPELLER_DEBUG } void GPUTracerVK::InitializeQueryPool(const ContextVK& context) { if (!enabled_) { return; } Lock lock(trace_state_mutex_); std::shared_ptr<CommandBuffer> buffer = context.CreateCommandBuffer(); CommandBufferVK& buffer_vk = CommandBufferVK::Cast(*buffer); for (auto i = 0u; i < kTraceStatesSize; i++) { vk::QueryPoolCreateInfo info; info.queryCount = kPoolSize; info.queryType = vk::QueryType::eTimestamp; auto [status, pool] = context.GetDevice().createQueryPoolUnique(info); if (status != vk::Result::eSuccess) { VALIDATION_LOG << "Failed to create query pool."; return; } trace_states_[i].query_pool = std::move(pool); buffer_vk.GetEncoder()->GetCommandBuffer().resetQueryPool( trace_states_[i].query_pool.get(), 0, kPoolSize); } if (!context.GetCommandQueue()->Submit({buffer}).ok()) { VALIDATION_LOG << "Failed to reset query pool for trace events."; enabled_ = false; } } bool GPUTracerVK::IsEnabled() const { return enabled_; } void GPUTracerVK::MarkFrameStart() { if (!enabled_) { return; } FML_DCHECK(!in_frame_); in_frame_ = true; raster_thread_id_ = std::this_thread::get_id(); } void GPUTracerVK::MarkFrameEnd() { in_frame_ = false; if (!enabled_) { return; } Lock lock(trace_state_mutex_); current_state_ = (current_state_ + 1) % kTraceStatesSize; auto& state = trace_states_[current_state_]; // If there are still pending buffers on the trace state we're switching to, // that means that a cmd buffer we were relying on to signal this likely // never finished. This shouldn't happen unless there is a bug in the // encoder logic. We set it to zero anyway to prevent a validation error // from becoming a memory leak. FML_DCHECK(state.pending_buffers == 0u); state.pending_buffers = 0; state.current_index = 0; } std::unique_ptr<GPUProbe> GPUTracerVK::CreateGPUProbe() { return std::make_unique<GPUProbe>(weak_from_this()); } void GPUTracerVK::RecordCmdBufferStart(const vk::CommandBuffer& buffer, GPUProbe& probe) { if (!enabled_ || std::this_thread::get_id() != raster_thread_id_ || !in_frame_) { return; } Lock lock(trace_state_mutex_); auto& state = trace_states_[current_state_]; // Reset previously completed queries. if (!states_to_reset_.empty()) { for (auto i = 0u; i < states_to_reset_.size(); i++) { buffer.resetQueryPool(trace_states_[states_to_reset_[i]].query_pool.get(), 0, kPoolSize); } states_to_reset_.clear(); } // We size the query pool to kPoolSize, but Flutter applications can create an // unbounded amount of work per frame. If we encounter this, stop recording // cmds. if (state.current_index >= kPoolSize) { return; } buffer.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, trace_states_[current_state_].query_pool.get(), state.current_index); state.current_index += 1; probe.index_ = current_state_; state.pending_buffers += 1; } void GPUTracerVK::RecordCmdBufferEnd(const vk::CommandBuffer& buffer, GPUProbe& probe) { if (!enabled_ || std::this_thread::get_id() != raster_thread_id_ || !in_frame_ || !probe.index_.has_value()) { return; } Lock lock(trace_state_mutex_); GPUTraceState& state = trace_states_[current_state_]; if (state.current_index >= kPoolSize) { return; } buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, state.query_pool.get(), state.current_index); state.current_index += 1; } void GPUTracerVK::OnFenceComplete(size_t frame_index) { if (!enabled_) { return; } size_t pending = 0; size_t query_count = 0; vk::QueryPool pool; { Lock lock(trace_state_mutex_); GPUTraceState& state = trace_states_[frame_index]; FML_DCHECK(state.pending_buffers > 0); state.pending_buffers -= 1; pending = state.pending_buffers; query_count = state.current_index; pool = state.query_pool.get(); } if (pending == 0) { std::vector<uint64_t> bits(query_count); std::shared_ptr<ContextVK> context = context_.lock(); if (!context) { return; } auto result = context->GetDevice().getQueryPoolResults( pool, 0, query_count, query_count * sizeof(uint64_t), bits.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64); // This may return VK_NOT_READY if the query couldn't be completed, or if // there are queries still pending. From local testing, this happens // occassionally on very expensive frames. Its unclear if we can do anything // about this, because by design this should only signal after all cmd // buffers have signaled. Adding VK_QUERY_RESULT_WAIT_BIT to the flags // passed to getQueryPoolResults seems like it would fix this, but actually // seems to result in more stuck query errors. Better to just drop them and // move on. if (result == vk::Result::eSuccess) { uint64_t smallest_timestamp = std::numeric_limits<uint64_t>::max(); uint64_t largest_timestamp = 0; for (auto i = 0u; i < bits.size(); i++) { smallest_timestamp = std::min(smallest_timestamp, bits[i]); largest_timestamp = std::max(largest_timestamp, bits[i]); } auto gpu_ms = (((largest_timestamp - smallest_timestamp) * timestamp_period_) / 1000000); FML_TRACE_COUNTER("flutter", "GPUTracer", reinterpret_cast<int64_t>(this), // Trace Counter ID "FrameTimeMS", gpu_ms); } // Record this query to be reset the next time a command is recorded. Lock lock(trace_state_mutex_); states_to_reset_.push_back(frame_index); } } GPUProbe::GPUProbe(const std::weak_ptr<GPUTracerVK>& tracer) : tracer_(tracer) {} GPUProbe::~GPUProbe() { if (!index_.has_value()) { return; } auto tracer = tracer_.lock(); if (!tracer) { return; } tracer->OnFenceComplete(index_.value()); } void GPUProbe::RecordCmdBufferStart(const vk::CommandBuffer& buffer) { auto tracer = tracer_.lock(); if (!tracer) { return; } tracer->RecordCmdBufferStart(buffer, *this); } void GPUProbe::RecordCmdBufferEnd(const vk::CommandBuffer& buffer) { auto tracer = tracer_.lock(); if (!tracer) { return; } tracer->RecordCmdBufferEnd(buffer, *this); } } // namespace impeller
engine/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc", "repo_id": "engine", "token_count": 3085 }
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. #include "impeller/renderer/backend/vulkan/resource_manager_vk.h" #include "flutter/fml/cpu_affinity.h" #include "flutter/fml/thread.h" #include "flutter/fml/trace_event.h" #include "fml/logging.h" namespace impeller { std::shared_ptr<ResourceManagerVK> ResourceManagerVK::Create() { // It will be tempting to refactor this to create the waiter thread in the // static method instead of the constructor. However, that causes the // destructor never to be called, and the thread never terminates! // // See https://github.com/flutter/flutter/issues/134482. return std::shared_ptr<ResourceManagerVK>(new ResourceManagerVK()); } ResourceManagerVK::ResourceManagerVK() : waiter_([&]() { Start(); }) {} ResourceManagerVK::~ResourceManagerVK() { FML_DCHECK(waiter_.get_id() != std::this_thread::get_id()) << "The ResourceManager being destructed on its own spawned thread is a " << "sign that ContextVK was not properly destroyed. A usual fix for this " << "is to ensure that ContextVK is shutdown (i.e. context->Shutdown()) " "before the ResourceManager is destroyed (i.e. at the end of a test)."; Terminate(); waiter_.join(); } void ResourceManagerVK::Start() { // It's possible for Start() to be called when terminating: // { ResourceManagerVK::Create(); } // // ... so no FML_DCHECK here. fml::Thread::SetCurrentThreadName(fml::Thread::ThreadConfig{"IplrVkResMgr"}); // While this code calls destructors it doesn't need to be particularly fast // with them, as long as it doesn't interrupt raster thread. fml::RequestAffinity(fml::CpuAffinity::kEfficiency); bool should_exit = false; while (!should_exit) { std::unique_lock lock(reclaimables_mutex_); // Wait until there are reclaimable resource or if the manager should be // torn down. reclaimables_cv_.wait( lock, [&]() { return !reclaimables_.empty() || should_exit_; }); // Don't reclaim resources when the lock is being held as this may gate // further reclaimables from being registered. Reclaimables resources_to_collect; std::swap(resources_to_collect, reclaimables_); // We can't read the ivar outside the lock. Read it here instead. should_exit = should_exit_; // We know what to collect. Unlock before doing anything else. lock.unlock(); // Claim all resources while tracing. { TRACE_EVENT0("Impeller", "ReclaimResources"); resources_to_collect.clear(); // Redundant because of scope but here so // we can add a trace around it. } } } void ResourceManagerVK::Reclaim(std::unique_ptr<ResourceVK> resource) { if (!resource) { return; } { std::scoped_lock lock(reclaimables_mutex_); reclaimables_.emplace_back(std::move(resource)); } reclaimables_cv_.notify_one(); } void ResourceManagerVK::Terminate() { // The thread should not be terminated more than once. FML_DCHECK(!should_exit_); { std::scoped_lock lock(reclaimables_mutex_); should_exit_ = true; } reclaimables_cv_.notify_one(); } } // namespace impeller
engine/impeller/renderer/backend/vulkan/resource_manager_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/resource_manager_vk.cc", "repo_id": "engine", "token_count": 1089 }
272
KHR Swapchain ============= An implementation of a Vulkan swapchain that depends on [`VK_KHR_swapchain`](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_swapchain.html). This swapchain is available on most platforms but may not be ideal on all. But, it is a good fallback.
engine/impeller/renderer/backend/vulkan/swapchain/khr/README.md/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/swapchain/khr/README.md", "repo_id": "engine", "token_count": 96 }
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. #include "impeller/renderer/backend/vulkan/texture_vk.h" #include "impeller/renderer/backend/vulkan/command_buffer_vk.h" #include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/formats_vk.h" #include "impeller/renderer/backend/vulkan/sampler_vk.h" namespace impeller { TextureVK::TextureVK(std::weak_ptr<Context> context, std::shared_ptr<TextureSourceVK> source) : Texture(source->GetTextureDescriptor()), context_(std::move(context)), source_(std::move(source)) {} TextureVK::~TextureVK() = default; void TextureVK::SetLabel(std::string_view label) { auto context = context_.lock(); if (!context) { // The context may have died. return; } ContextVK::Cast(*context).SetDebugName(GetImage(), label); ContextVK::Cast(*context).SetDebugName(GetImageView(), label); } bool TextureVK::OnSetContents(const uint8_t* contents, size_t length, size_t slice) { if (!IsValid() || !contents) { return false; } const auto& desc = GetTextureDescriptor(); // Out of bounds access. if (length != desc.GetByteSizeOfBaseMipLevel()) { VALIDATION_LOG << "Illegal to set contents for invalid size."; return false; } auto context = context_.lock(); if (!context) { VALIDATION_LOG << "Context died before setting contents on texture."; return false; } auto staging_buffer = context->GetResourceAllocator()->CreateBufferWithCopy(contents, length); if (!staging_buffer) { VALIDATION_LOG << "Could not create staging buffer."; return false; } auto cmd_buffer = context->CreateCommandBuffer(); if (!cmd_buffer) { return false; } const auto encoder = CommandBufferVK::Cast(*cmd_buffer).GetEncoder(); if (!encoder->Track(staging_buffer) || !encoder->Track(source_)) { return false; } const auto& vk_cmd_buffer = encoder->GetCommandBuffer(); BarrierVK barrier; barrier.cmd_buffer = vk_cmd_buffer; barrier.new_layout = vk::ImageLayout::eTransferDstOptimal; barrier.src_access = {}; barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe; barrier.dst_access = vk::AccessFlagBits::eTransferWrite; barrier.dst_stage = vk::PipelineStageFlagBits::eTransfer; if (!SetLayout(barrier)) { return false; } vk::BufferImageCopy copy; copy.bufferOffset = 0u; copy.bufferRowLength = 0u; // 0u means tightly packed per spec. copy.bufferImageHeight = 0u; // 0u means tightly packed per spec. copy.imageOffset.x = 0u; copy.imageOffset.y = 0u; copy.imageOffset.z = 0u; copy.imageExtent.width = desc.size.width; copy.imageExtent.height = desc.size.height; copy.imageExtent.depth = 1u; copy.imageSubresource.aspectMask = ToImageAspectFlags(GetTextureDescriptor().format); copy.imageSubresource.mipLevel = 0u; copy.imageSubresource.baseArrayLayer = slice; copy.imageSubresource.layerCount = 1u; vk_cmd_buffer.copyBufferToImage( DeviceBufferVK::Cast(*staging_buffer).GetBuffer(), // src buffer GetImage(), // dst image barrier.new_layout, // dst image layout 1u, // region count &copy // regions ); // Transition to shader-read. { BarrierVK barrier; barrier.cmd_buffer = vk_cmd_buffer; barrier.src_access = vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eTransferWrite; barrier.src_stage = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eTransfer; barrier.dst_access = vk::AccessFlagBits::eShaderRead; barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader; barrier.new_layout = vk::ImageLayout::eShaderReadOnlyOptimal; if (!SetLayout(barrier)) { return false; } } return context->GetCommandQueue()->Submit({cmd_buffer}).ok(); } bool TextureVK::OnSetContents(std::shared_ptr<const fml::Mapping> mapping, size_t slice) { // Vulkan has no threading restrictions. So we can pass this data along to the // client rendering API immediately. return OnSetContents(mapping->GetMapping(), mapping->GetSize(), slice); } bool TextureVK::IsValid() const { return !!source_; } ISize TextureVK::GetSize() const { return GetTextureDescriptor().size; } vk::Image TextureVK::GetImage() const { return source_->GetImage(); } vk::ImageView TextureVK::GetImageView() const { return source_->GetImageView(); } std::shared_ptr<const TextureSourceVK> TextureVK::GetTextureSource() const { return source_; } bool TextureVK::SetLayout(const BarrierVK& barrier) const { return source_ ? source_->SetLayout(barrier).ok() : false; } vk::ImageLayout TextureVK::SetLayoutWithoutEncoding( vk::ImageLayout layout) const { return source_ ? source_->SetLayoutWithoutEncoding(layout) : vk::ImageLayout::eUndefined; } vk::ImageLayout TextureVK::GetLayout() const { return source_ ? source_->GetLayout() : vk::ImageLayout::eUndefined; } vk::ImageView TextureVK::GetRenderTargetView() const { return source_->GetRenderTargetView(); } void TextureVK::SetCachedFramebuffer( const SharedHandleVK<vk::Framebuffer>& framebuffer) { source_->SetCachedFramebuffer(framebuffer); } void TextureVK::SetCachedRenderPass( const SharedHandleVK<vk::RenderPass>& render_pass) { source_->SetCachedRenderPass(render_pass); } SharedHandleVK<vk::Framebuffer> TextureVK::GetCachedFramebuffer() const { return source_->GetCachedFramebuffer(); } SharedHandleVK<vk::RenderPass> TextureVK::GetCachedRenderPass() const { return source_->GetCachedRenderPass(); } void TextureVK::SetMipMapGenerated() { mipmap_generated_ = true; } bool TextureVK::IsSwapchainImage() const { return source_->IsSwapchainImage(); } std::shared_ptr<SamplerVK> TextureVK::GetImmutableSamplerVariant( const SamplerVK& sampler) const { if (!source_) { return nullptr; } auto conversion = source_->GetYUVConversion(); if (!conversion) { // Most textures don't need a sampler conversion and will go down this path. // Only needed for YUV sampling from external textures. return nullptr; } return sampler.CreateVariantForConversion(std::move(conversion)); } } // namespace impeller
engine/impeller/renderer/backend/vulkan/texture_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/texture_vk.cc", "repo_id": "engine", "token_count": 2499 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_BLIT_PASS_H_ #define FLUTTER_IMPELLER_RENDERER_BLIT_PASS_H_ #include <string> #include "impeller/core/device_buffer.h" #include "impeller/core/texture.h" namespace impeller { class HostBuffer; class Allocator; //------------------------------------------------------------------------------ /// @brief Blit passes encode blit into the underlying command buffer. /// /// Blit passes can be obtained from the command buffer in which /// the pass is meant to encode commands into. /// /// @see `CommandBuffer` /// class BlitPass { public: virtual ~BlitPass(); virtual bool IsValid() const = 0; void SetLabel(std::string label); //---------------------------------------------------------------------------- /// @brief Record a command to copy the contents of one texture to /// another texture. The blit area is limited by the intersection /// of the texture coverage with respect the source region and /// destination origin. /// No work is encoded into the command buffer at this time. /// /// @param[in] source The texture to read for copying. /// @param[in] destination The texture to overwrite using the source /// contents. /// @param[in] source_region The optional region of the source texture /// to use for copying. If not specified, the /// full size of the source texture is used. /// @param[in] destination_origin The origin to start writing to in the /// destination texture. /// @param[in] label The optional debug label to give the /// command. /// /// @return If the command was valid for subsequent commitment. /// bool AddCopy(std::shared_ptr<Texture> source, std::shared_ptr<Texture> destination, std::optional<IRect> source_region = std::nullopt, IPoint destination_origin = {}, std::string label = ""); //---------------------------------------------------------------------------- /// @brief Record a command to copy the contents of the buffer to /// the texture. /// No work is encoded into the command buffer at this time. /// /// @param[in] source The texture to read for copying. /// @param[in] destination The buffer to overwrite using the source /// contents. /// @param[in] source_region The optional region of the source texture /// to use for copying. If not specified, the /// full size of the source texture is used. /// @param[in] destination_origin The origin to start writing to in the /// destination texture. /// @param[in] label The optional debug label to give the /// command. /// /// @return If the command was valid for subsequent commitment. /// bool AddCopy(std::shared_ptr<Texture> source, std::shared_ptr<DeviceBuffer> destination, std::optional<IRect> source_region = std::nullopt, size_t destination_offset = 0, std::string label = ""); //---------------------------------------------------------------------------- /// @brief Record a command to copy the contents of the buffer to /// the texture. /// No work is encoded into the command buffer at this time. /// /// @param[in] source The buffer view to read for copying. /// @param[in] destination The texture to overwrite using the source /// contents. /// @param[in] destination_offset The offset to start writing to in the /// destination buffer. /// @param[in] label The optional debug label to give the /// command. /// /// @return If the command was valid for subsequent commitment. /// bool AddCopy(BufferView source, std::shared_ptr<Texture> destination, IPoint destination_origin = {}, std::string label = ""); //---------------------------------------------------------------------------- /// @brief Record a command to generate all mip levels for a texture. /// No work is encoded into the command buffer at this time. /// /// @param[in] texture The texture to generate mipmaps for. /// @param[in] label The optional debug label to give the command. /// /// @return If the command was valid for subsequent commitment. /// bool GenerateMipmap(std::shared_ptr<Texture> texture, std::string label = ""); //---------------------------------------------------------------------------- /// @brief Encode the recorded commands to the underlying command buffer. /// /// @param transients_allocator The transients allocator. /// /// @return If the commands were encoded to the underlying command /// buffer. /// virtual bool EncodeCommands( const std::shared_ptr<Allocator>& transients_allocator) const = 0; protected: explicit BlitPass(); virtual void OnSetLabel(std::string label) = 0; virtual bool OnCopyTextureToTextureCommand( std::shared_ptr<Texture> source, std::shared_ptr<Texture> destination, IRect source_region, IPoint destination_origin, std::string label) = 0; virtual bool OnCopyTextureToBufferCommand( std::shared_ptr<Texture> source, std::shared_ptr<DeviceBuffer> destination, IRect source_region, size_t destination_offset, std::string label) = 0; virtual bool OnCopyBufferToTextureCommand( BufferView source, std::shared_ptr<Texture> destination, IPoint destination_origin, std::string label) = 0; virtual bool OnGenerateMipmapCommand(std::shared_ptr<Texture> texture, std::string label) = 0; private: BlitPass(const BlitPass&) = delete; BlitPass& operator=(const BlitPass&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BLIT_PASS_H_
engine/impeller/renderer/blit_pass.h/0
{ "file_path": "engine/impeller/renderer/blit_pass.h", "repo_id": "engine", "token_count": 2511 }
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_IMPELLER_RENDERER_COMPUTE_PIPELINE_DESCRIPTOR_H_ #define FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_DESCRIPTOR_H_ #include <functional> #include <future> #include <map> #include <memory> #include <string> #include <string_view> #include <type_traits> #include <unordered_map> #include "flutter/fml/hash_combine.h" #include "flutter/fml/macros.h" #include "impeller/base/comparable.h" #include "impeller/core/formats.h" #include "impeller/core/shader_types.h" #include "impeller/tessellator/tessellator.h" namespace impeller { class ShaderFunction; template <typename T> class Pipeline; class ComputePipelineDescriptor final : public Comparable<ComputePipelineDescriptor> { public: ComputePipelineDescriptor(); ~ComputePipelineDescriptor(); ComputePipelineDescriptor& SetLabel(std::string label); const std::string& GetLabel() const; ComputePipelineDescriptor& SetStageEntrypoint( std::shared_ptr<const ShaderFunction> function); std::shared_ptr<const ShaderFunction> GetStageEntrypoint() const; // Comparable<ComputePipelineDescriptor> std::size_t GetHash() const override; // Comparable<PipelineDescriptor> bool IsEqual(const ComputePipelineDescriptor& other) const override; template <size_t Size> bool RegisterDescriptorSetLayouts( const std::array<DescriptorSetLayout, Size>& inputs) { return RegisterDescriptorSetLayouts(inputs.data(), inputs.size()); } bool RegisterDescriptorSetLayouts(const DescriptorSetLayout desc_set_layout[], size_t count); const std::vector<DescriptorSetLayout>& GetDescriptorSetLayouts() const; private: std::string label_; std::shared_ptr<const ShaderFunction> entrypoint_; std::vector<DescriptorSetLayout> descriptor_set_layouts_; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_DESCRIPTOR_H_
engine/impeller/renderer/compute_pipeline_descriptor.h/0
{ "file_path": "engine/impeller/renderer/compute_pipeline_descriptor.h", "repo_id": "engine", "token_count": 743 }
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. #include "impeller/renderer/pipeline_library.h" namespace impeller { PipelineLibrary::PipelineLibrary() = default; PipelineLibrary::~PipelineLibrary() = default; PipelineFuture<PipelineDescriptor> PipelineLibrary::GetPipeline( std::optional<PipelineDescriptor> descriptor) { if (descriptor.has_value()) { return GetPipeline(descriptor.value()); } auto promise = std::make_shared< std::promise<std::shared_ptr<Pipeline<PipelineDescriptor>>>>(); promise->set_value(nullptr); return {descriptor, promise->get_future()}; } PipelineFuture<ComputePipelineDescriptor> PipelineLibrary::GetPipeline( std::optional<ComputePipelineDescriptor> descriptor) { if (descriptor.has_value()) { return GetPipeline(descriptor.value()); } auto promise = std::make_shared< std::promise<std::shared_ptr<Pipeline<ComputePipelineDescriptor>>>>(); promise->set_value(nullptr); return {descriptor, promise->get_future()}; } } // namespace impeller
engine/impeller/renderer/pipeline_library.cc/0
{ "file_path": "engine/impeller/renderer/pipeline_library.cc", "repo_id": "engine", "token_count": 393 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_SHADER_FUNCTION_H_ #define FLUTTER_IMPELLER_RENDERER_SHADER_FUNCTION_H_ #include <string> #include "flutter/fml/hash_combine.h" #include "flutter/fml/macros.h" #include "impeller/base/comparable.h" #include "impeller/core/shader_types.h" namespace impeller { class ShaderFunction : public Comparable<ShaderFunction> { public: // |Comparable<ShaderFunction>| virtual ~ShaderFunction(); ShaderStage GetStage() const; const std::string& GetName() const; // |Comparable<ShaderFunction>| std::size_t GetHash() const override; // |Comparable<ShaderFunction>| bool IsEqual(const ShaderFunction& other) const override; protected: ShaderFunction(UniqueID parent_library_id, std::string name, ShaderStage stage); private: UniqueID parent_library_id_; std::string name_; ShaderStage stage_; ShaderFunction(const ShaderFunction&) = delete; ShaderFunction& operator=(const ShaderFunction&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_SHADER_FUNCTION_H_
engine/impeller/renderer/shader_function.h/0
{ "file_path": "engine/impeller/renderer/shader_function.h", "repo_id": "engine", "token_count": 452 }
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. #include "impeller/renderer/vertex_descriptor.h" namespace impeller { VertexDescriptor::VertexDescriptor() = default; VertexDescriptor::~VertexDescriptor() = default; void VertexDescriptor::SetStageInputs( const ShaderStageIOSlot* const stage_inputs[], size_t count, const ShaderStageBufferLayout* const stage_layout[], size_t layout_count) { inputs_.reserve(inputs_.size() + count); layouts_.reserve(layouts_.size() + layout_count); for (size_t i = 0; i < count; i++) { inputs_.emplace_back(*stage_inputs[i]); } for (size_t i = 0; i < layout_count; i++) { layouts_.emplace_back(*stage_layout[i]); } } void VertexDescriptor::SetStageInputs( const std::vector<ShaderStageIOSlot>& inputs, const std::vector<ShaderStageBufferLayout>& layout) { inputs_.insert(inputs_.end(), inputs.begin(), inputs.end()); layouts_.insert(layouts_.end(), layout.begin(), layout.end()); } void VertexDescriptor::RegisterDescriptorSetLayouts( const DescriptorSetLayout desc_set_layout[], size_t count) { desc_set_layouts_.reserve(desc_set_layouts_.size() + count); for (size_t i = 0; i < count; i++) { uses_input_attachments_ |= desc_set_layout[i].descriptor_type == DescriptorType::kInputAttachment; desc_set_layouts_.emplace_back(desc_set_layout[i]); } } // |Comparable<VertexDescriptor>| size_t VertexDescriptor::GetHash() const { auto seed = fml::HashCombine(); for (const auto& input : inputs_) { fml::HashCombineSeed(seed, input.GetHash()); } for (const auto& layout : layouts_) { fml::HashCombineSeed(seed, layout.GetHash()); } return seed; } // |Comparable<VertexDescriptor>| bool VertexDescriptor::IsEqual(const VertexDescriptor& other) const { return inputs_ == other.inputs_ && layouts_ == other.layouts_; } const std::vector<ShaderStageIOSlot>& VertexDescriptor::GetStageInputs() const { return inputs_; } const std::vector<ShaderStageBufferLayout>& VertexDescriptor::GetStageLayouts() const { return layouts_; } const std::vector<DescriptorSetLayout>& VertexDescriptor::GetDescriptorSetLayouts() const { return desc_set_layouts_; } bool VertexDescriptor::UsesInputAttacments() const { return uses_input_attachments_; } } // namespace impeller
engine/impeller/renderer/vertex_descriptor.cc/0
{ "file_path": "engine/impeller/renderer/vertex_descriptor.cc", "repo_id": "engine", "token_count": 878 }
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. #include "impeller/scene/animation/animation_player.h" #include <memory> #include <unordered_map> #include "flutter/fml/time/time_point.h" #include "impeller/base/timing.h" #include "impeller/scene/node.h" namespace impeller { namespace scene { AnimationPlayer::AnimationPlayer() = default; AnimationPlayer::~AnimationPlayer() = default; AnimationPlayer::AnimationPlayer(AnimationPlayer&&) = default; AnimationPlayer& AnimationPlayer::operator=(AnimationPlayer&&) = default; AnimationClip* AnimationPlayer::AddAnimation( const std::shared_ptr<Animation>& animation, Node* bind_target) { if (!animation) { VALIDATION_LOG << "Cannot add null animation."; return nullptr; } AnimationClip clip(animation, bind_target); // Record all of the unique default transforms that this AnimationClip // will mutate. for (const auto& binding : clip.bindings_) { auto decomp = binding.node->GetLocalTransform().Decompose(); if (!decomp.has_value()) { continue; } target_transforms_.insert( {binding.node, AnimationTransforms{.bind_pose = decomp.value()}}); } auto result = clips_.insert({animation->GetName(), std::move(clip)}); return &result.first->second; } AnimationClip* AnimationPlayer::GetClip(const std::string& name) const { auto result = clips_.find(name); if (result == clips_.end()) { return nullptr; } return const_cast<AnimationClip*>(&result->second); } void AnimationPlayer::Update() { if (!previous_time_.has_value()) { previous_time_ = Clock::now(); } auto new_time = Clock::now(); auto delta_time = new_time - previous_time_.value(); previous_time_ = new_time; // Reset the animated pose state. for (auto& [node, transforms] : target_transforms_) { transforms.animated_pose = transforms.bind_pose; } // Compute a weight multiplier for normalizing the animation. Scalar total_weight = 0; for (auto& [_, clip] : clips_) { total_weight += clip.GetWeight(); } Scalar weight_multiplier = total_weight > 1 ? 1 / total_weight : 1; // Update and apply all clips to the animation pose state. for (auto& [_, clip] : clips_) { clip.Advance(delta_time); clip.ApplyToBindings(target_transforms_, weight_multiplier); } // Apply the animated pose to the bound joints. for (auto& [node, transforms] : target_transforms_) { node->SetLocalTransform(Matrix(transforms.animated_pose)); } } } // namespace scene } // namespace impeller
engine/impeller/scene/animation/animation_player.cc/0
{ "file_path": "engine/impeller/scene/animation/animation_player.cc", "repo_id": "engine", "token_count": 858 }
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. #include <filesystem> #include <memory> #include "flutter/fml/backtrace.h" #include "flutter/fml/command_line.h" #include "flutter/fml/file.h" #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "impeller/base/strings.h" #include "impeller/compiler/utilities.h" #include "impeller/scene/importer/importer.h" #include "impeller/scene/importer/scene_flatbuffers.h" #include "impeller/scene/importer/switches.h" #include "impeller/scene/importer/types.h" #include "third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h" namespace impeller { namespace scene { namespace importer { // Sets the file access mode of the file at path 'p' to 0644. static bool SetPermissiveAccess(const std::filesystem::path& p) { auto permissions = std::filesystem::perms::owner_read | std::filesystem::perms::owner_write | std::filesystem::perms::group_read | std::filesystem::perms::others_read; std::error_code error; std::filesystem::permissions(p, permissions, error); if (error) { std::cerr << "Failed to set access on file '" << p << "': " << error.message() << std::endl; return false; } return true; } bool Main(const fml::CommandLine& command_line) { fml::InstallCrashHandler(); if (command_line.HasOption("help")) { Switches::PrintHelp(std::cout); return true; } Switches switches(command_line); if (!switches.AreValid(std::cerr)) { std::cerr << "Invalid flags specified." << std::endl; Switches::PrintHelp(std::cerr); return false; } auto source_file_mapping = fml::FileMapping::CreateReadOnly(switches.source_file_name); if (!source_file_mapping) { std::cerr << "Could not open input file." << std::endl; return false; } fb::SceneT scene; bool success = false; switch (switches.input_type) { case SourceType::kGLTF: success = ParseGLTF(*source_file_mapping, scene); break; case SourceType::kUnknown: std::cerr << "Unknown input type." << std::endl; return false; } if (!success) { std::cerr << "Failed to parse input file." << std::endl; return false; } flatbuffers::FlatBufferBuilder builder; builder.Finish(fb::Scene::Pack(builder, &scene), fb::SceneIdentifier()); auto output_file_name = std::filesystem::absolute( std::filesystem::current_path() / switches.output_file_name); fml::NonOwnedMapping mapping(builder.GetCurrentBufferPointer(), builder.GetSize()); if (!fml::WriteAtomically(*switches.working_directory, compiler::Utf8FromPath(output_file_name).c_str(), mapping)) { std::cerr << "Could not write file to " << switches.output_file_name << std::endl; return false; } // Tools that consume the geometry data expect the access mode to be 0644. if (!SetPermissiveAccess(output_file_name)) { return false; } return true; } } // namespace importer } // namespace scene } // namespace impeller int main(int argc, char const* argv[]) { return impeller::scene::importer::Main( fml::CommandLineFromPlatformOrArgcArgv(argc, argv)) ? EXIT_SUCCESS : EXIT_FAILURE; }
engine/impeller/scene/importer/scenec_main.cc/0
{ "file_path": "engine/impeller/scene/importer/scenec_main.cc", "repo_id": "engine", "token_count": 1307 }
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. #ifndef FLUTTER_IMPELLER_SCENE_SCENE_CONTEXT_H_ #define FLUTTER_IMPELLER_SCENE_SCENE_CONTEXT_H_ #include <memory> #include "impeller/core/host_buffer.h" #include "impeller/renderer/context.h" #include "impeller/renderer/pipeline.h" #include "impeller/renderer/pipeline_descriptor.h" #include "impeller/scene/pipeline_key.h" namespace impeller { namespace scene { struct SceneContextOptions { SampleCount sample_count = SampleCount::kCount1; PrimitiveType primitive_type = PrimitiveType::kTriangle; struct Hash { constexpr std::size_t operator()(const SceneContextOptions& o) const { return fml::HashCombine(o.sample_count, o.primitive_type); } }; struct Equal { constexpr bool operator()(const SceneContextOptions& lhs, const SceneContextOptions& rhs) const { return lhs.sample_count == rhs.sample_count && lhs.primitive_type == rhs.primitive_type; } }; void ApplyToPipelineDescriptor(const Capabilities& capabilities, PipelineDescriptor& desc) const; }; class SceneContext { public: explicit SceneContext(std::shared_ptr<Context> context); ~SceneContext(); bool IsValid() const; std::shared_ptr<Pipeline<PipelineDescriptor>> GetPipeline( PipelineKey key, SceneContextOptions opts) const; std::shared_ptr<Context> GetContext() const; std::shared_ptr<Texture> GetPlaceholderTexture() const; HostBuffer& GetTransientsBuffer() const { return *host_buffer_; } private: class PipelineVariants { public: virtual ~PipelineVariants() = default; virtual std::shared_ptr<Pipeline<PipelineDescriptor>> GetPipeline( Context& context, SceneContextOptions opts) = 0; }; template <class PipelineT> class PipelineVariantsT final : public PipelineVariants { public: explicit PipelineVariantsT(Context& context) { auto desc = PipelineT::Builder::MakeDefaultPipelineDescriptor(context); if (!desc.has_value()) { is_valid_ = false; return; } // Apply default ContentContextOptions to the descriptor. SceneContextOptions{}.ApplyToPipelineDescriptor( /*capabilities=*/*context.GetCapabilities(), /*desc=*/desc.value()); variants_[{}] = std::make_unique<PipelineT>(context, desc); }; // |PipelineVariants| std::shared_ptr<Pipeline<PipelineDescriptor>> GetPipeline( Context& context, SceneContextOptions opts) { if (auto found = variants_.find(opts); found != variants_.end()) { return found->second->WaitAndGet(); } auto prototype = variants_.find({}); // The prototype must always be initialized in the constructor. FML_CHECK(prototype != variants_.end()); auto variant_future = prototype->second->WaitAndGet()->CreateVariant( [&context, &opts, variants_count = variants_.size()](PipelineDescriptor& desc) { opts.ApplyToPipelineDescriptor(*context.GetCapabilities(), desc); desc.SetLabel( SPrintF("%s V#%zu", desc.GetLabel().c_str(), variants_count)); }); auto variant = std::make_unique<PipelineT>(std::move(variant_future)); auto variant_pipeline = variant->WaitAndGet(); variants_[opts] = std::move(variant); return variant_pipeline; } bool IsValid() const { return is_valid_; } private: bool is_valid_ = true; std::unordered_map<SceneContextOptions, std::unique_ptr<PipelineT>, SceneContextOptions::Hash, SceneContextOptions::Equal> variants_; }; template <typename VertexShader, typename FragmentShader> /// Creates a PipelineVariantsT for the given vertex and fragment shaders. /// /// If a pipeline could not be created, returns nullptr. std::unique_ptr<PipelineVariants> MakePipelineVariants(Context& context) { auto pipeline = PipelineVariantsT<RenderPipelineT<VertexShader, FragmentShader>>( context); if (!pipeline.IsValid()) { return nullptr; } return std::make_unique< PipelineVariantsT<RenderPipelineT<VertexShader, FragmentShader>>>( std::move(pipeline)); } std::unordered_map<PipelineKey, std::unique_ptr<PipelineVariants>, PipelineKey::Hash, PipelineKey::Equal> pipelines_; std::shared_ptr<Context> context_; bool is_valid_ = false; // A 1x1 opaque white texture that can be used as a placeholder binding. // Available for the lifetime of the scene context std::shared_ptr<Texture> placeholder_texture_; std::shared_ptr<HostBuffer> host_buffer_; SceneContext(const SceneContext&) = delete; SceneContext& operator=(const SceneContext&) = delete; }; } // namespace scene } // namespace impeller #endif // FLUTTER_IMPELLER_SCENE_SCENE_CONTEXT_H_
engine/impeller/scene/scene_context.h/0
{ "file_path": "engine/impeller/scene/scene_context.h", "repo_id": "engine", "token_count": 1992 }
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. #include "impeller/shader_archive/shader_archive.h" #include <array> #include <string> #include <utility> #include "impeller/base/validation.h" #include "impeller/shader_archive/shader_archive_flatbuffers.h" namespace impeller { constexpr ArchiveShaderType ToShaderType(fb::Stage stage) { switch (stage) { case fb::Stage::kVertex: return ArchiveShaderType::kVertex; case fb::Stage::kFragment: return ArchiveShaderType::kFragment; case fb::Stage::kCompute: return ArchiveShaderType::kCompute; } FML_UNREACHABLE(); } ShaderArchive::ShaderArchive(std::shared_ptr<const fml::Mapping> payload) : payload_(std::move(payload)) { if (!payload_ || payload_->GetMapping() == nullptr) { VALIDATION_LOG << "Shader mapping was absent."; return; } if (!fb::ShaderArchiveBufferHasIdentifier(payload_->GetMapping())) { VALIDATION_LOG << "Invalid shader archive magic."; return; } auto shader_archive = fb::GetShaderArchive(payload_->GetMapping()); if (!shader_archive) { return; } if (auto items = shader_archive->items()) { for (auto i = items->begin(), end = items->end(); i != end; i++) { ShaderKey key; key.name = i->name()->str(); key.type = ToShaderType(i->stage()); shaders_[key] = std::make_shared<fml::NonOwnedMapping>( i->mapping()->Data(), i->mapping()->size(), [payload = payload_](auto, auto) { // The pointers are into the base payload. Instead of copying the // data, just hold onto the payload. }); } } is_valid_ = true; } ShaderArchive::ShaderArchive(ShaderArchive&&) = default; ShaderArchive::~ShaderArchive() = default; bool ShaderArchive::IsValid() const { return is_valid_; } size_t ShaderArchive::GetShaderCount() const { return shaders_.size(); } std::shared_ptr<fml::Mapping> ShaderArchive::GetMapping( ArchiveShaderType type, std::string name) const { ShaderKey key; key.type = type; key.name = std::move(name); auto found = shaders_.find(key); return found == shaders_.end() ? nullptr : found->second; } size_t ShaderArchive::IterateAllShaders( const std::function<bool(ArchiveShaderType type, const std::string& name, const std::shared_ptr<fml::Mapping>& mapping)>& callback) const { if (!IsValid() || !callback) { return 0u; } size_t count = 0u; for (const auto& shader : shaders_) { count++; if (!callback(shader.first.type, shader.first.name, shader.second)) { break; } } return count; } } // namespace impeller
engine/impeller/shader_archive/shader_archive.cc/0
{ "file_path": "engine/impeller/shader_archive/shader_archive.cc", "repo_id": "engine", "token_count": 1107 }
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. #ifndef FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_ #define FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_ #include <functional> #include <memory> #include <vector> #include "impeller/core/formats.h" #include "impeller/geometry/path.h" #include "impeller/geometry/point.h" #include "impeller/geometry/trig.h" struct TESStesselator; namespace impeller { void DestroyTessellator(TESStesselator* tessellator); using CTessellator = std::unique_ptr<TESStesselator, decltype(&DestroyTessellator)>; //------------------------------------------------------------------------------ /// @brief A utility that generates triangles of the specified fill type /// given a polyline. This happens on the CPU. /// /// This object is not thread safe, and its methods must not be /// called from multiple threads. /// class Tessellator { private: /// Essentially just a vector of Trig objects, but supports storing a /// reference to either a cached vector or a locally generated vector. /// The constructor will fill the vector with quarter circular samples /// for the indicated number of equal divisions if the vector is new. class Trigs { public: explicit Trigs(std::vector<Trig>& trigs, size_t divisions) : trigs_(trigs) { init(divisions); FML_DCHECK(trigs_.size() == divisions + 1); } explicit Trigs(size_t divisions) : local_storage_(std::make_unique<std::vector<Trig>>()), trigs_(*local_storage_) { init(divisions); FML_DCHECK(trigs_.size() == divisions + 1); } // Utility forwards of the indicated vector methods. auto inline size() const { return trigs_.size(); } auto inline begin() const { return trigs_.begin(); } auto inline end() const { return trigs_.end(); } private: // nullptr if a cached vector is used, otherwise the actual storage std::unique_ptr<std::vector<Trig>> local_storage_; // Whether or not a cached vector or the local storage is used, this // this reference will always be valid std::vector<Trig>& trigs_; // Fill the vector with the indicated number of equal divisions of // trigonometric values if it is empty. void init(size_t divisions); }; public: enum class Result { kSuccess, kInputError, kTessellationError, }; /// @brief A callback function for a |VertexGenerator| to deliver /// the vertices it computes as |Point| objects. using TessellatedVertexProc = std::function<void(const Point& p)>; /// @brief An object which produces a list of vertices as |Point|s that /// tessellate a previously provided shape and delivers the vertices /// through a |TessellatedVertexProc| callback. /// /// The object can also provide advance information on how many /// vertices it will generate. /// /// @see |Tessellator::FilledCircle| /// @see |Tessellator::StrokedCircle| /// @see |Tessellator::RoundCapLine| /// @see |Tessellator::FilledEllipse| class VertexGenerator { public: /// @brief Returns the |PrimitiveType| that describes the relationship /// among the list of vertices produced by the |GenerateVertices| /// method. /// /// Most generators will deliver |kTriangleStrip| triangles virtual PrimitiveType GetTriangleType() const = 0; /// @brief Returns the number of vertices that the generator plans to /// produce, if known. /// /// This value is advisory only and can be used to reserve space /// where the vertices will be placed, but the count may be an /// estimate. /// /// Implementations are encouraged to avoid overestimating /// the count by too large a number and to provide a best /// guess so as to minimize potential buffer reallocations /// as the vertices are delivered. virtual size_t GetVertexCount() const = 0; /// @brief Generate the vertices and deliver them in the necessary /// order (as required by the PrimitiveType) to the given /// callback function. virtual void GenerateVertices(const TessellatedVertexProc& proc) const = 0; }; /// @brief The |VertexGenerator| implementation common to all shapes /// that are based on a polygonal representation of an ellipse. class EllipticalVertexGenerator : public virtual VertexGenerator { public: /// |VertexGenerator| PrimitiveType GetTriangleType() const override { return PrimitiveType::kTriangleStrip; } /// |VertexGenerator| size_t GetVertexCount() const override { return trigs_.size() * vertices_per_trig_; } /// |VertexGenerator| void GenerateVertices(const TessellatedVertexProc& proc) const override { impl_(trigs_, data_, proc); } private: friend class Tessellator; struct Data { // Circles and Ellipses only use one of these points. // RoundCapLines use both as the endpoints of the unexpanded line. // A round rect can specify its interior rectangle by using the // 2 points as opposing corners. const Point reference_centers[2]; // Circular shapes have the same value in radii.width and radii.height const Size radii; // half_width is only used in cases where the generator will be // generating 2 different outlines, such as StrokedCircle const Scalar half_width; }; typedef void GeneratorProc(const Trigs& trigs, const Data& data, const TessellatedVertexProc& proc); GeneratorProc& impl_; const Trigs trigs_; const Data data_; const size_t vertices_per_trig_; EllipticalVertexGenerator(GeneratorProc& generator, Trigs&& trigs, PrimitiveType triangle_type, size_t vertices_per_trig, Data&& data); }; Tessellator(); ~Tessellator(); /// @brief A callback that returns the results of the tessellation. /// /// The index buffer may not be populated, in which case [indices] will /// be nullptr and indices_count will be 0. using BuilderCallback = std::function<bool(const float* vertices, size_t vertices_count, const uint16_t* indices, size_t indices_count)>; //---------------------------------------------------------------------------- /// @brief Generates filled triangles from the path. A callback is /// invoked once for the entire tessellation. /// /// @param[in] path The path to tessellate. /// @param[in] tolerance The tolerance value for conversion of the path to /// a polyline. This value is often derived from the /// Matrix::GetMaxBasisLength of the CTM applied to the /// path for rendering. /// @param[in] callback The callback, return false to indicate failure. /// /// @return The result status of the tessellation. /// Tessellator::Result Tessellate(const Path& path, Scalar tolerance, const BuilderCallback& callback); //---------------------------------------------------------------------------- /// @brief Given a convex path, create a triangle fan structure. /// /// @param[in] path The path to tessellate. /// @param[in] tolerance The tolerance value for conversion of the path to /// a polyline. This value is often derived from the /// Matrix::GetMaxBasisLength of the CTM applied to the /// path for rendering. /// /// @return A point vector containing the vertices in triangle strip format. /// std::vector<Point> TessellateConvex(const Path& path, Scalar tolerance); //---------------------------------------------------------------------------- /// @brief Create a temporary polyline. Only one per-process can exist at /// a time. /// /// The tessellator itself is not a thread safe class and should /// only be used from the raster thread. Path::Polyline CreateTempPolyline(const Path& path, Scalar tolerance); /// @brief The pixel tolerance used by the algorighm to determine how /// many divisions to create for a circle. /// /// No point on the polygon of vertices should deviate from the /// true circle by more than this tolerance. static constexpr Scalar kCircleTolerance = 0.1f; /// @brief Create a |VertexGenerator| that can produce vertices for /// a filled circle of the given radius around the given center /// with enough polygon sub-divisions to provide reasonable /// fidelity when viewed under the given view transform. /// /// Note that the view transform is only used to choose the /// number of sample points to use per quarter circle and the /// returned points are not transformed by it, instead they are /// relative to the coordinate space of the center point. EllipticalVertexGenerator FilledCircle(const Matrix& view_transform, const Point& center, Scalar radius); /// @brief Create a |VertexGenerator| that can produce vertices for /// a stroked circle of the given radius and half_width around /// the given shared center with enough polygon sub-divisions /// to provide reasonable fidelity when viewed under the given /// view transform. The outer edge of the stroked circle is /// generated at (radius + half_width) and the inner edge is /// generated at (radius - half_width). /// /// Note that the view transform is only used to choose the /// number of sample points to use per quarter circle and the /// returned points are not transformed by it, instead they are /// relative to the coordinate space of the center point. EllipticalVertexGenerator StrokedCircle(const Matrix& view_transform, const Point& center, Scalar radius, Scalar half_width); /// @brief Create a |VertexGenerator| that can produce vertices for /// a line with round end caps of the given radius with enough /// polygon sub-divisions to provide reasonable fidelity when /// viewed under the given view transform. /// /// Note that the view transform is only used to choose the /// number of sample points to use per quarter circle and the /// returned points are not transformed by it, instead they are /// relative to the coordinate space of the two points. EllipticalVertexGenerator RoundCapLine(const Matrix& view_transform, const Point& p0, const Point& p1, Scalar radius); /// @brief Create a |VertexGenerator| that can produce vertices for /// a filled ellipse inscribed within the given bounds with /// enough polygon sub-divisions to provide reasonable /// fidelity when viewed under the given view transform. /// /// Note that the view transform is only used to choose the /// number of sample points to use per quarter circle and the /// returned points are not transformed by it, instead they are /// relative to the coordinate space of the bounds. EllipticalVertexGenerator FilledEllipse(const Matrix& view_transform, const Rect& bounds); /// @brief Create a |VertexGenerator| that can produce vertices for /// a filled round rect within the given bounds and corner radii /// with enough polygon sub-divisions to provide reasonable /// fidelity when viewed under the given view transform. /// /// Note that the view transform is only used to choose the /// number of sample points to use per quarter circle and the /// returned points are not transformed by it, instead they are /// relative to the coordinate space of the bounds. EllipticalVertexGenerator FilledRoundRect(const Matrix& view_transform, const Rect& bounds, const Size& radii); private: /// Used for polyline generation. std::unique_ptr<std::vector<Point>> point_buffer_; CTessellator c_tessellator_; // Data for variouos Circle/EllipseGenerator classes, cached per // Tessellator instance which is usually the foreground life of an app // if not longer. static constexpr size_t kCachedTrigCount = 300; std::vector<Trig> precomputed_trigs_[kCachedTrigCount]; Trigs GetTrigsForDivisions(size_t divisions); static void GenerateFilledCircle(const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc); static void GenerateStrokedCircle(const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc); static void GenerateRoundCapLine(const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc); static void GenerateFilledEllipse(const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc); static void GenerateFilledRoundRect( const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc); Tessellator(const Tessellator&) = delete; Tessellator& operator=(const Tessellator&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_
engine/impeller/tessellator/tessellator.h/0
{ "file_path": "engine/impeller/tessellator/tessellator.h", "repo_id": "engine", "token_count": 5635 }
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. #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/testing/testing.h" #include "impeller/toolkit/android/choreographer.h" #include "impeller/toolkit/android/hardware_buffer.h" #include "impeller/toolkit/android/proc_table.h" #include "impeller/toolkit/android/surface_control.h" #include "impeller/toolkit/android/surface_transaction.h" namespace impeller::android::testing { TEST(ToolkitAndroidTest, CanCreateProcTable) { ProcTable proc_table; ASSERT_TRUE(proc_table.IsValid()); } TEST(ToolkitAndroidTest, GuardsAgainstZeroSizedDescriptors) { auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({0, 0}); ASSERT_GT(desc.size.width, 0u); ASSERT_GT(desc.size.height, 0u); } TEST(ToolkitAndroidTest, CanCreateHardwareBuffer) { if (!HardwareBuffer::IsAvailableOnPlatform()) { GTEST_SKIP() << "Hardware buffers are not supported on this platform."; } ASSERT_TRUE(HardwareBuffer::IsAvailableOnPlatform()); auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({100, 100}); ASSERT_TRUE(desc.IsAllocatable()); HardwareBuffer buffer(desc); ASSERT_TRUE(buffer.IsValid()); } TEST(ToolkitAndroidTest, CanGetHardwareBufferIDs) { if (!HardwareBuffer::IsAvailableOnPlatform()) { GTEST_SKIP() << "Hardware buffers are not supported on this platform."; } ASSERT_TRUE(HardwareBuffer::IsAvailableOnPlatform()); if (!GetProcTable().AHardwareBuffer_getId.IsAvailable()) { GTEST_SKIP() << "Hardware buffer IDs are not available on this platform."; } auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({100, 100}); ASSERT_TRUE(desc.IsAllocatable()); HardwareBuffer buffer(desc); ASSERT_TRUE(buffer.IsValid()); ASSERT_TRUE(buffer.GetSystemUniqueID().has_value()); } TEST(ToolkitAndroidTest, CanDescribeHardwareBufferHandles) { if (!HardwareBuffer::IsAvailableOnPlatform()) { GTEST_SKIP() << "Hardware buffers are not supported on this platform."; } ASSERT_TRUE(HardwareBuffer::IsAvailableOnPlatform()); auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({100, 100}); ASSERT_TRUE(desc.IsAllocatable()); HardwareBuffer buffer(desc); ASSERT_TRUE(buffer.IsValid()); auto a_desc = HardwareBuffer::Describe(buffer.GetHandle()); ASSERT_TRUE(a_desc.has_value()); ASSERT_EQ(a_desc->width, 100u); // NOLINT ASSERT_EQ(a_desc->height, 100u); // NOLINT } TEST(ToolkitAndroidTest, CanApplySurfaceTransaction) { if (!SurfaceTransaction::IsAvailableOnPlatform()) { GTEST_SKIP() << "Surface controls are not supported on this platform."; } ASSERT_TRUE(SurfaceTransaction::IsAvailableOnPlatform()); SurfaceTransaction transaction; ASSERT_TRUE(transaction.IsValid()); fml::AutoResetWaitableEvent event; ASSERT_TRUE(transaction.Apply([&event]() { event.Signal(); })); event.Wait(); } TEST(ToolkitAndroidTest, SurfacControlsAreAvailable) { if (!SurfaceControl::IsAvailableOnPlatform()) { GTEST_SKIP() << "Surface controls are not supported on this platform."; } ASSERT_TRUE(SurfaceControl::IsAvailableOnPlatform()); } TEST(ToolkitAndroidTest, ChoreographerIsAvailable) { if (!Choreographer::IsAvailableOnPlatform()) { GTEST_SKIP() << "Choreographer is not supported on this platform."; } ASSERT_TRUE(Choreographer::IsAvailableOnPlatform()); } TEST(ToolkitAndroidTest, CanPostAndNotWaitForFrameCallbacks) { if (!Choreographer::IsAvailableOnPlatform()) { GTEST_SKIP() << "Choreographer is not supported on this platform."; } const auto& choreographer = Choreographer::GetInstance(); ASSERT_TRUE(choreographer.IsValid()); ASSERT_TRUE(choreographer.PostFrameCallback([](auto) {})); } TEST(ToolkitAndroidTest, CanPostAndWaitForFrameCallbacks) { if (!Choreographer::IsAvailableOnPlatform()) { GTEST_SKIP() << "Choreographer is not supported on this platform."; } if ((true)) { GTEST_SKIP() << "Disabled till the test harness is in an Android activity. " "Running it without one will hang because the choreographer " "frame callback will never execute."; } const auto& choreographer = Choreographer::GetInstance(); ASSERT_TRUE(choreographer.IsValid()); fml::AutoResetWaitableEvent event; ASSERT_TRUE(choreographer.PostFrameCallback( [&event](auto point) { event.Signal(); })); event.Wait(); } } // namespace impeller::android::testing
engine/impeller/toolkit/android/toolkit_android_unittests.cc/0
{ "file_path": "engine/impeller/toolkit/android/toolkit_android_unittests.cc", "repo_id": "engine", "token_count": 1490 }
285
#include "flutter/impeller/toolkit/gles/texture.h" namespace impeller {}
engine/impeller/toolkit/gles/texture.cc/0
{ "file_path": "engine/impeller/toolkit/gles/texture.cc", "repo_id": "engine", "token_count": 28 }
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. #include "impeller/typographer/typographer_context.h" #include <utility> namespace impeller { TypographerContext::TypographerContext() { is_valid_ = true; } TypographerContext::~TypographerContext() = default; bool TypographerContext::IsValid() const { return is_valid_; } } // namespace impeller
engine/impeller/typographer/typographer_context.cc/0
{ "file_path": "engine/impeller/typographer/typographer_context.cc", "repo_id": "engine", "token_count": 141 }
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. #ifndef FLUTTER_LIB_GPU_FORMATS_H_ #define FLUTTER_LIB_GPU_FORMATS_H_ #include "fml/logging.h" #include "impeller/core/formats.h" #include "impeller/core/shader_types.h" // ATTENTION! ATTENTION! ATTENTION! // All enums defined in this file must exactly match the contents and order of // the corresponding enums defined in `gpu/lib/src/formats.dart`. namespace flutter { namespace gpu { enum class FlutterGPUStorageMode { kHostVisible, kDevicePrivate, kDeviceTransient, }; constexpr impeller::StorageMode ToImpellerStorageMode( FlutterGPUStorageMode value) { switch (value) { case FlutterGPUStorageMode::kHostVisible: return impeller::StorageMode::kHostVisible; case FlutterGPUStorageMode::kDevicePrivate: return impeller::StorageMode::kDevicePrivate; case FlutterGPUStorageMode::kDeviceTransient: return impeller::StorageMode::kDeviceTransient; } } constexpr impeller::StorageMode ToImpellerStorageMode(int value) { return ToImpellerStorageMode(static_cast<FlutterGPUStorageMode>(value)); } enum class FlutterGPUPixelFormat { kUnknown, kA8UNormInt, kR8UNormInt, kR8G8UNormInt, kR8G8B8A8UNormInt, kR8G8B8A8UNormIntSRGB, kB8G8R8A8UNormInt, kB8G8R8A8UNormIntSRGB, kR32G32B32A32Float, kR16G16B16A16Float, kB10G10R10XR, kB10G10R10XRSRGB, kB10G10R10A10XR, kS8UInt, kD24UnormS8Uint, kD32FloatS8UInt, }; constexpr impeller::PixelFormat ToImpellerPixelFormat( FlutterGPUPixelFormat value) { switch (value) { case FlutterGPUPixelFormat::kUnknown: return impeller::PixelFormat::kUnknown; case FlutterGPUPixelFormat::kA8UNormInt: return impeller::PixelFormat::kA8UNormInt; case FlutterGPUPixelFormat::kR8UNormInt: return impeller::PixelFormat::kR8UNormInt; case FlutterGPUPixelFormat::kR8G8UNormInt: return impeller::PixelFormat::kR8G8UNormInt; case FlutterGPUPixelFormat::kR8G8B8A8UNormInt: return impeller::PixelFormat::kR8G8B8A8UNormInt; case FlutterGPUPixelFormat::kR8G8B8A8UNormIntSRGB: return impeller::PixelFormat::kR8G8B8A8UNormIntSRGB; case FlutterGPUPixelFormat::kB8G8R8A8UNormInt: return impeller::PixelFormat::kB8G8R8A8UNormInt; case FlutterGPUPixelFormat::kB8G8R8A8UNormIntSRGB: return impeller::PixelFormat::kB8G8R8A8UNormIntSRGB; case FlutterGPUPixelFormat::kR32G32B32A32Float: return impeller::PixelFormat::kR32G32B32A32Float; case FlutterGPUPixelFormat::kR16G16B16A16Float: return impeller::PixelFormat::kR16G16B16A16Float; case FlutterGPUPixelFormat::kB10G10R10XR: return impeller::PixelFormat::kB10G10R10XR; case FlutterGPUPixelFormat::kB10G10R10XRSRGB: return impeller::PixelFormat::kB10G10R10XRSRGB; case FlutterGPUPixelFormat::kB10G10R10A10XR: return impeller::PixelFormat::kB10G10R10A10XR; case FlutterGPUPixelFormat::kS8UInt: return impeller::PixelFormat::kS8UInt; case FlutterGPUPixelFormat::kD24UnormS8Uint: return impeller::PixelFormat::kD24UnormS8Uint; case FlutterGPUPixelFormat::kD32FloatS8UInt: return impeller::PixelFormat::kD32FloatS8UInt; } } constexpr impeller::PixelFormat ToImpellerPixelFormat(int value) { return ToImpellerPixelFormat(static_cast<FlutterGPUPixelFormat>(value)); } constexpr FlutterGPUPixelFormat FromImpellerPixelFormat( impeller::PixelFormat value) { switch (value) { case impeller::PixelFormat::kUnknown: return FlutterGPUPixelFormat::kUnknown; case impeller::PixelFormat::kA8UNormInt: return FlutterGPUPixelFormat::kA8UNormInt; case impeller::PixelFormat::kR8UNormInt: return FlutterGPUPixelFormat::kR8UNormInt; case impeller::PixelFormat::kR8G8UNormInt: return FlutterGPUPixelFormat::kR8G8UNormInt; case impeller::PixelFormat::kR8G8B8A8UNormInt: return FlutterGPUPixelFormat::kR8G8B8A8UNormInt; case impeller::PixelFormat::kR8G8B8A8UNormIntSRGB: return FlutterGPUPixelFormat::kR8G8B8A8UNormIntSRGB; case impeller::PixelFormat::kB8G8R8A8UNormInt: return FlutterGPUPixelFormat::kB8G8R8A8UNormInt; case impeller::PixelFormat::kB8G8R8A8UNormIntSRGB: return FlutterGPUPixelFormat::kB8G8R8A8UNormIntSRGB; case impeller::PixelFormat::kR32G32B32A32Float: return FlutterGPUPixelFormat::kR32G32B32A32Float; case impeller::PixelFormat::kR16G16B16A16Float: return FlutterGPUPixelFormat::kR16G16B16A16Float; case impeller::PixelFormat::kB10G10R10XR: return FlutterGPUPixelFormat::kB10G10R10XR; case impeller::PixelFormat::kB10G10R10XRSRGB: return FlutterGPUPixelFormat::kB10G10R10XRSRGB; case impeller::PixelFormat::kB10G10R10A10XR: return FlutterGPUPixelFormat::kB10G10R10A10XR; case impeller::PixelFormat::kS8UInt: return FlutterGPUPixelFormat::kS8UInt; case impeller::PixelFormat::kD24UnormS8Uint: return FlutterGPUPixelFormat::kD24UnormS8Uint; case impeller::PixelFormat::kD32FloatS8UInt: return FlutterGPUPixelFormat::kD32FloatS8UInt; } } enum class FlutterGPUTextureCoordinateSystem { kUploadFromHost, kRenderToTexture, }; constexpr impeller::TextureCoordinateSystem ToImpellerTextureCoordinateSystem( FlutterGPUTextureCoordinateSystem value) { switch (value) { case FlutterGPUTextureCoordinateSystem::kUploadFromHost: return impeller::TextureCoordinateSystem::kUploadFromHost; case FlutterGPUTextureCoordinateSystem::kRenderToTexture: return impeller::TextureCoordinateSystem::kRenderToTexture; } } constexpr impeller::TextureCoordinateSystem ToImpellerTextureCoordinateSystem( int value) { return ToImpellerTextureCoordinateSystem( static_cast<FlutterGPUTextureCoordinateSystem>(value)); } enum class FlutterGPUBlendFactor { kZero, kOne, kSourceColor, kOneMinusSourceColor, kSourceAlpha, kOneMinusSourceAlpha, kDestinationColor, kOneMinusDestinationColor, kDestinationAlpha, kOneMinusDestinationAlpha, kSourceAlphaSaturated, kBlendColor, kOneMinusBlendColor, kBlendAlpha, kOneMinusBlendAlpha, }; constexpr impeller::BlendFactor ToImpellerBlendFactor( FlutterGPUBlendFactor value) { switch (value) { case FlutterGPUBlendFactor::kZero: return impeller::BlendFactor::kZero; case FlutterGPUBlendFactor::kOne: return impeller::BlendFactor::kOne; case FlutterGPUBlendFactor::kSourceColor: return impeller::BlendFactor::kSourceColor; case FlutterGPUBlendFactor::kOneMinusSourceColor: return impeller::BlendFactor::kOneMinusSourceColor; case FlutterGPUBlendFactor::kSourceAlpha: return impeller::BlendFactor::kSourceAlpha; case FlutterGPUBlendFactor::kOneMinusSourceAlpha: return impeller::BlendFactor::kOneMinusSourceAlpha; case FlutterGPUBlendFactor::kDestinationColor: return impeller::BlendFactor::kDestinationColor; case FlutterGPUBlendFactor::kOneMinusDestinationColor: return impeller::BlendFactor::kOneMinusDestinationColor; case FlutterGPUBlendFactor::kDestinationAlpha: return impeller::BlendFactor::kDestinationAlpha; case FlutterGPUBlendFactor::kOneMinusDestinationAlpha: return impeller::BlendFactor::kOneMinusDestinationAlpha; case FlutterGPUBlendFactor::kSourceAlphaSaturated: return impeller::BlendFactor::kSourceAlphaSaturated; case FlutterGPUBlendFactor::kBlendColor: return impeller::BlendFactor::kBlendColor; case FlutterGPUBlendFactor::kOneMinusBlendColor: return impeller::BlendFactor::kOneMinusBlendColor; case FlutterGPUBlendFactor::kBlendAlpha: return impeller::BlendFactor::kBlendAlpha; case FlutterGPUBlendFactor::kOneMinusBlendAlpha: return impeller::BlendFactor::kOneMinusBlendAlpha; } } constexpr impeller::BlendFactor ToImpellerBlendFactor(int value) { return ToImpellerBlendFactor(static_cast<FlutterGPUBlendFactor>(value)); } enum class FlutterGPUBlendOperation { kAdd, kSubtract, kReverseSubtract, }; constexpr impeller::BlendOperation ToImpellerBlendOperation( FlutterGPUBlendOperation value) { switch (value) { case FlutterGPUBlendOperation::kAdd: return impeller::BlendOperation::kAdd; case FlutterGPUBlendOperation::kSubtract: return impeller::BlendOperation::kSubtract; case FlutterGPUBlendOperation::kReverseSubtract: return impeller::BlendOperation::kReverseSubtract; } } constexpr impeller::BlendOperation ToImpellerBlendOperation(int value) { return ToImpellerBlendOperation(static_cast<FlutterGPUBlendOperation>(value)); } enum class FlutterGPULoadAction { kDontCare, kLoad, kClear, }; constexpr impeller::LoadAction ToImpellerLoadAction( FlutterGPULoadAction value) { switch (value) { case FlutterGPULoadAction::kDontCare: return impeller::LoadAction::kDontCare; case FlutterGPULoadAction::kLoad: return impeller::LoadAction::kLoad; case FlutterGPULoadAction::kClear: return impeller::LoadAction::kClear; } } constexpr impeller::LoadAction ToImpellerLoadAction(int value) { return ToImpellerLoadAction(static_cast<FlutterGPULoadAction>(value)); } enum class FlutterGPUStoreAction { kDontCare, kStore, kMultisampleResolve, kStoreAndMultisampleResolve, }; constexpr impeller::StoreAction ToImpellerStoreAction( FlutterGPUStoreAction value) { switch (value) { case FlutterGPUStoreAction::kDontCare: return impeller::StoreAction::kDontCare; case FlutterGPUStoreAction::kStore: return impeller::StoreAction::kStore; case FlutterGPUStoreAction::kMultisampleResolve: return impeller::StoreAction::kMultisampleResolve; case FlutterGPUStoreAction::kStoreAndMultisampleResolve: return impeller::StoreAction::kStoreAndMultisampleResolve; } } constexpr impeller::StoreAction ToImpellerStoreAction(int value) { return ToImpellerStoreAction(static_cast<FlutterGPUStoreAction>(value)); } enum class FlutterGPUShaderStage { kVertex, kFragment, }; constexpr impeller::ShaderStage ToImpellerShaderStage( FlutterGPUShaderStage value) { switch (value) { case FlutterGPUShaderStage::kVertex: return impeller::ShaderStage::kVertex; case FlutterGPUShaderStage::kFragment: return impeller::ShaderStage::kFragment; } } constexpr impeller::ShaderStage ToImpellerShaderStage(int value) { return ToImpellerShaderStage(static_cast<FlutterGPUShaderStage>(value)); } constexpr FlutterGPUShaderStage FromImpellerShaderStage( impeller::ShaderStage value) { switch (value) { case impeller::ShaderStage::kVertex: return FlutterGPUShaderStage::kVertex; case impeller::ShaderStage::kFragment: return FlutterGPUShaderStage::kFragment; case impeller::ShaderStage::kUnknown: case impeller::ShaderStage::kCompute: FML_LOG(FATAL) << "Invalid Flutter GPU ShaderStage " << static_cast<size_t>(value); FML_UNREACHABLE(); } } enum class FlutterGPUMinMagFilter { kNearest, kLinear, }; constexpr impeller::MinMagFilter ToImpellerMinMagFilter( FlutterGPUMinMagFilter value) { switch (value) { case FlutterGPUMinMagFilter::kNearest: return impeller::MinMagFilter::kNearest; case FlutterGPUMinMagFilter::kLinear: return impeller::MinMagFilter::kLinear; } } constexpr impeller::MinMagFilter ToImpellerMinMagFilter(int value) { return ToImpellerMinMagFilter(static_cast<FlutterGPUMinMagFilter>(value)); } enum class FlutterGPUMipFilter { kNearest, kLinear, }; constexpr impeller::MipFilter ToImpellerMipFilter(FlutterGPUMipFilter value) { switch (value) { case FlutterGPUMipFilter::kNearest: return impeller::MipFilter::kNearest; case FlutterGPUMipFilter::kLinear: return impeller::MipFilter::kLinear; } } constexpr impeller::MipFilter ToImpellerMipFilter(int value) { return ToImpellerMipFilter(static_cast<FlutterGPUMipFilter>(value)); } enum class FlutterGPUSamplerAddressMode { kClampToEdge, kRepeat, kMirror, }; constexpr impeller::SamplerAddressMode ToImpellerSamplerAddressMode( FlutterGPUSamplerAddressMode value) { switch (value) { case FlutterGPUSamplerAddressMode::kClampToEdge: return impeller::SamplerAddressMode::kClampToEdge; case FlutterGPUSamplerAddressMode::kRepeat: return impeller::SamplerAddressMode::kRepeat; case FlutterGPUSamplerAddressMode::kMirror: return impeller::SamplerAddressMode::kMirror; } } constexpr impeller::SamplerAddressMode ToImpellerSamplerAddressMode(int value) { return ToImpellerSamplerAddressMode( static_cast<FlutterGPUSamplerAddressMode>(value)); } enum class FlutterGPUIndexType { k16bit, k32bit, }; constexpr impeller::IndexType ToImpellerIndexType(FlutterGPUIndexType value) { switch (value) { case FlutterGPUIndexType::k16bit: return impeller::IndexType::k16bit; case FlutterGPUIndexType::k32bit: return impeller::IndexType::k32bit; } } constexpr impeller::IndexType ToImpellerIndexType(int value) { return ToImpellerIndexType(static_cast<FlutterGPUIndexType>(value)); } enum class FlutterGPUPrimitiveType { kTriangle, kTriangleStrip, kLine, kLineStrip, kPoint, }; constexpr impeller::PrimitiveType ToImpellerPrimitiveType( FlutterGPUPrimitiveType value) { switch (value) { case FlutterGPUPrimitiveType::kTriangle: return impeller::PrimitiveType::kTriangle; case FlutterGPUPrimitiveType::kTriangleStrip: return impeller::PrimitiveType::kTriangleStrip; case FlutterGPUPrimitiveType::kLine: return impeller::PrimitiveType::kLine; case FlutterGPUPrimitiveType::kLineStrip: return impeller::PrimitiveType::kLineStrip; case FlutterGPUPrimitiveType::kPoint: return impeller::PrimitiveType::kPoint; } } constexpr impeller::PrimitiveType ToImpellerPrimitiveType(int value) { return ToImpellerPrimitiveType(static_cast<FlutterGPUPrimitiveType>(value)); } enum class FlutterGPUCompareFunction { kNever, kAlways, kLess, kEqual, kLessEqual, kGreater, kNotEqual, kGreaterEqual, }; constexpr impeller::CompareFunction ToImpellerCompareFunction( FlutterGPUCompareFunction value) { switch (value) { case FlutterGPUCompareFunction::kNever: return impeller::CompareFunction::kNever; case FlutterGPUCompareFunction::kAlways: return impeller::CompareFunction::kAlways; case FlutterGPUCompareFunction::kLess: return impeller::CompareFunction::kLess; case FlutterGPUCompareFunction::kEqual: return impeller::CompareFunction::kEqual; case FlutterGPUCompareFunction::kLessEqual: return impeller::CompareFunction::kLessEqual; case FlutterGPUCompareFunction::kGreater: return impeller::CompareFunction::kGreater; case FlutterGPUCompareFunction::kNotEqual: return impeller::CompareFunction::kNotEqual; case FlutterGPUCompareFunction::kGreaterEqual: return impeller::CompareFunction::kGreaterEqual; } } constexpr impeller::CompareFunction ToImpellerCompareFunction(int value) { return ToImpellerCompareFunction( static_cast<FlutterGPUCompareFunction>(value)); } enum class FlutterGPUStencilOperation { kKeep, kZero, kSetToReferenceValue, kIncrementClamp, kDecrementClamp, kInvert, kIncrementWrap, kDecrementWrap, }; constexpr impeller::StencilOperation ToImpellerStencilOperation( FlutterGPUStencilOperation value) { switch (value) { case FlutterGPUStencilOperation::kKeep: return impeller::StencilOperation::kKeep; case FlutterGPUStencilOperation::kZero: return impeller::StencilOperation::kZero; case FlutterGPUStencilOperation::kSetToReferenceValue: return impeller::StencilOperation::kSetToReferenceValue; case FlutterGPUStencilOperation::kIncrementClamp: return impeller::StencilOperation::kIncrementClamp; case FlutterGPUStencilOperation::kDecrementClamp: return impeller::StencilOperation::kDecrementClamp; case FlutterGPUStencilOperation::kInvert: return impeller::StencilOperation::kInvert; case FlutterGPUStencilOperation::kIncrementWrap: return impeller::StencilOperation::kIncrementWrap; case FlutterGPUStencilOperation::kDecrementWrap: return impeller::StencilOperation::kDecrementWrap; } } constexpr impeller::StencilOperation ToImpellerStencilOperation(int value) { return ToImpellerStencilOperation( static_cast<FlutterGPUStencilOperation>(value)); } } // namespace gpu } // namespace flutter #endif // FLUTTER_LIB_GPU_FORMATS_H_
engine/lib/gpu/formats.h/0
{ "file_path": "engine/lib/gpu/formats.h", "repo_id": "engine", "token_count": 6252 }
288
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_GPU_RENDER_PASS_H_ #define FLUTTER_LIB_GPU_RENDER_PASS_H_ #include <map> #include <memory> #include "flutter/lib/gpu/command_buffer.h" #include "flutter/lib/gpu/export.h" #include "flutter/lib/ui/dart_wrapper.h" #include "fml/memory/ref_ptr.h" #include "impeller/core/formats.h" #include "impeller/core/vertex_buffer.h" #include "impeller/renderer/command.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/render_target.h" #include "lib/gpu/device_buffer.h" #include "lib/gpu/host_buffer.h" #include "lib/gpu/render_pipeline.h" #include "lib/gpu/texture.h" namespace flutter { namespace gpu { class RenderPass : public RefCountedDartWrappable<RenderPass> { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(RenderPass); public: RenderPass(); ~RenderPass() override; const std::shared_ptr<const impeller::Context>& GetContext() const; impeller::Command& GetCommand(); const impeller::Command& GetCommand() const; impeller::RenderTarget& GetRenderTarget(); const impeller::RenderTarget& GetRenderTarget() const; impeller::ColorAttachmentDescriptor& GetColorAttachmentDescriptor( size_t color_attachment_index); impeller::DepthAttachmentDescriptor& GetDepthAttachmentDescriptor(); impeller::VertexBuffer& GetVertexBuffer(); bool Begin(flutter::gpu::CommandBuffer& command_buffer); void SetPipeline(fml::RefPtr<RenderPipeline> pipeline); /// Lookup an Impeller pipeline by building a descriptor based on the current /// command state. std::shared_ptr<impeller::Pipeline<impeller::PipelineDescriptor>> GetOrCreatePipeline(); impeller::Command ProvisionRasterCommand(); bool Draw(); private: impeller::RenderTarget render_target_; std::shared_ptr<impeller::RenderPass> render_pass_; // Command encoding state. impeller::Command command_; fml::RefPtr<RenderPipeline> render_pipeline_; impeller::PipelineDescriptor pipeline_descriptor_; // Pipeline descriptor layout state. We always keep track of this state, but // we'll only apply it as necessary to match the RenderTarget. std::map<size_t, impeller::ColorAttachmentDescriptor> color_descriptors_; impeller::StencilAttachmentDescriptor stencil_front_desc_; impeller::StencilAttachmentDescriptor stencil_back_desc_; impeller::DepthAttachmentDescriptor depth_desc_; // Command state. impeller::VertexBuffer vertex_buffer_; FML_DISALLOW_COPY_AND_ASSIGN(RenderPass); }; } // namespace gpu } // namespace flutter //---------------------------------------------------------------------------- /// Exports /// extern "C" { FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_Initialize(Dart_Handle wrapper); FLUTTER_GPU_EXPORT extern Dart_Handle InternalFlutterGpu_RenderPass_SetColorAttachment( flutter::gpu::RenderPass* wrapper, int color_attachment_index, int load_action, int store_action, int clear_color, flutter::gpu::Texture* texture, Dart_Handle resolve_texture_wrapper); FLUTTER_GPU_EXPORT extern Dart_Handle InternalFlutterGpu_RenderPass_SetDepthStencilAttachment( flutter::gpu::RenderPass* wrapper, int depth_load_action, int depth_store_action, float depth_clear_value, int stencil_load_action, int stencil_store_action, int stencil_clear_value, flutter::gpu::Texture* texture); FLUTTER_GPU_EXPORT extern Dart_Handle InternalFlutterGpu_RenderPass_Begin( flutter::gpu::RenderPass* wrapper, flutter::gpu::CommandBuffer* command_buffer); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_BindPipeline( flutter::gpu::RenderPass* wrapper, flutter::gpu::RenderPipeline* pipeline); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_BindVertexBufferDevice( flutter::gpu::RenderPass* wrapper, flutter::gpu::DeviceBuffer* device_buffer, int offset_in_bytes, int length_in_bytes, int vertex_count); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_BindVertexBufferHost( flutter::gpu::RenderPass* wrapper, flutter::gpu::HostBuffer* host_buffer, int offset_in_bytes, int length_in_bytes, int vertex_count); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_BindIndexBufferDevice( flutter::gpu::RenderPass* wrapper, flutter::gpu::DeviceBuffer* device_buffer, int offset_in_bytes, int length_in_bytes, int index_type, int index_count); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_BindIndexBufferHost( flutter::gpu::RenderPass* wrapper, flutter::gpu::HostBuffer* host_buffer, int offset_in_bytes, int length_in_bytes, int index_type, int index_count); FLUTTER_GPU_EXPORT extern bool InternalFlutterGpu_RenderPass_BindUniformDevice( flutter::gpu::RenderPass* wrapper, flutter::gpu::Shader* shader, Dart_Handle uniform_name_handle, flutter::gpu::DeviceBuffer* device_buffer, int offset_in_bytes, int length_in_bytes); FLUTTER_GPU_EXPORT extern bool InternalFlutterGpu_RenderPass_BindUniformHost( flutter::gpu::RenderPass* wrapper, flutter::gpu::Shader* shader, Dart_Handle uniform_name_handle, flutter::gpu::HostBuffer* host_buffer, int offset_in_bytes, int length_in_bytes); FLUTTER_GPU_EXPORT extern bool InternalFlutterGpu_RenderPass_BindTexture( flutter::gpu::RenderPass* wrapper, flutter::gpu::Shader* shader, Dart_Handle uniform_name_handle, flutter::gpu::Texture* texture, int min_filter, int mag_filter, int mip_filter, int width_address_mode, int height_address_mode); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_ClearBindings( flutter::gpu::RenderPass* wrapper); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_SetColorBlendEnable( flutter::gpu::RenderPass* wrapper, int color_attachment_index, bool enable); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_SetColorBlendEquation( flutter::gpu::RenderPass* wrapper, int color_attachment_index, int color_blend_operation, int source_color_blend_factor, int destination_color_blend_factor, int alpha_blend_operation, int source_alpha_blend_factor, int destination_alpha_blend_factor); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_SetDepthWriteEnable( flutter::gpu::RenderPass* wrapper, bool enable); FLUTTER_GPU_EXPORT extern void InternalFlutterGpu_RenderPass_SetDepthCompareOperation( flutter::gpu::RenderPass* wrapper, int compare_operation); FLUTTER_GPU_EXPORT extern bool InternalFlutterGpu_RenderPass_Draw( flutter::gpu::RenderPass* wrapper); } // extern "C" #endif // FLUTTER_LIB_GPU_RENDER_PASS_H_
engine/lib/gpu/render_pass.h/0
{ "file_path": "engine/lib/gpu/render_pass.h", "repo_id": "engine", "token_count": 2427 }
289
# Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # Note: if you edit this file, you must also generate libraries.json in this # directory: # # dart third_party/dart/tools/yaml2json.dart flutter/lib/snapshot/libraries.yaml flutter/lib/snapshot/libraries.json # # We currently have several different files that needs to be updated when # changing libraries, sources, and patch files. See # https://github.com/dart-lang/sdk/issues/28836. flutter: include: - {path: "../../../third_party/dart/sdk/lib/libraries.json", target: vm_common} libraries: ui: uri: "../../lib/ui/ui.dart"
engine/lib/snapshot/libraries.yaml/0
{ "file_path": "engine/lib/snapshot/libraries.yaml", "repo_id": "engine", "token_count": 252 }
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. #include "flutter/lib/ui/dart_ui.h" #include <mutex> #include <string_view> #include "flutter/common/constants.h" #include "flutter/common/settings.h" #include "flutter/fml/build_config.h" #include "flutter/lib/ui/compositing/scene.h" #include "flutter/lib/ui/compositing/scene_builder.h" #include "flutter/lib/ui/dart_runtime_hooks.h" #include "flutter/lib/ui/isolate_name_server/isolate_name_server_natives.h" #include "flutter/lib/ui/painting/canvas.h" #include "flutter/lib/ui/painting/codec.h" #include "flutter/lib/ui/painting/color_filter.h" #include "flutter/lib/ui/painting/engine_layer.h" #include "flutter/lib/ui/painting/fragment_program.h" #include "flutter/lib/ui/painting/fragment_shader.h" #include "flutter/lib/ui/painting/gradient.h" #include "flutter/lib/ui/painting/image.h" #include "flutter/lib/ui/painting/image_descriptor.h" #include "flutter/lib/ui/painting/image_filter.h" #include "flutter/lib/ui/painting/image_shader.h" #include "flutter/lib/ui/painting/immutable_buffer.h" #include "flutter/lib/ui/painting/path.h" #include "flutter/lib/ui/painting/path_measure.h" #include "flutter/lib/ui/painting/picture.h" #include "flutter/lib/ui/painting/picture_recorder.h" #include "flutter/lib/ui/painting/vertices.h" #include "flutter/lib/ui/semantics/semantics_update.h" #include "flutter/lib/ui/semantics/semantics_update_builder.h" #include "flutter/lib/ui/semantics/string_attribute.h" #include "flutter/lib/ui/text/font_collection.h" #include "flutter/lib/ui/text/paragraph.h" #include "flutter/lib/ui/text/paragraph_builder.h" #include "flutter/lib/ui/window/platform_configuration.h" #include "flutter/lib/ui/window/platform_isolate.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/logging/dart_error.h" #ifdef IMPELLER_ENABLE_3D #include "flutter/lib/ui/painting/scene/scene_node.h" #include "flutter/lib/ui/painting/scene/scene_shader.h" #endif // IMPELLER_ENABLE_3D using tonic::ToDart; namespace flutter { typedef CanvasImage Image; typedef CanvasPathMeasure PathMeasure; typedef CanvasGradient Gradient; typedef CanvasPath Path; // List of native static functions used as @Native functions. // Items are tuples of ('function_name', 'parameter_count'), where: // 'function_name' is the fully qualified name of the native function. // 'parameter_count' is the number of parameters the function has. // // These are used to: // - Instantiate FfiDispatcher templates to automatically create FFI Native // bindings. // If the name does not match a native function, the template will fail to // instatiate, resulting in a compile time error. // - Resolve the native function pointer associated with an @Native function. // If there is a mismatch between name or parameter count an @Native is // trying to resolve, an exception will be thrown. #define FFI_FUNCTION_LIST(V) \ /* Constructors */ \ V(Canvas::Create) \ V(ColorFilter::Create) \ V(FragmentProgram::Create) \ V(ReusableFragmentShader::Create) \ V(Gradient::Create) \ V(ImageFilter::Create) \ V(ImageShader::Create) \ V(ParagraphBuilder::Create) \ V(PathMeasure::Create) \ V(Path::Create) \ V(PictureRecorder::Create) \ V(SceneBuilder::Create) \ V(SemanticsUpdateBuilder::Create) \ /* Other */ \ V(FontCollection::LoadFontFromList) \ V(ImageDescriptor::initEncoded) \ V(ImmutableBuffer::init) \ V(ImmutableBuffer::initFromAsset) \ V(ImmutableBuffer::initFromFile) \ V(ImageDescriptor::initRaw) \ V(IsolateNameServerNatives::LookupPortByName) \ V(IsolateNameServerNatives::RegisterPortWithName) \ V(IsolateNameServerNatives::RemovePortNameMapping) \ V(NativeStringAttribute::initLocaleStringAttribute) \ V(NativeStringAttribute::initSpellOutStringAttribute) \ V(PlatformConfigurationNativeApi::DefaultRouteName) \ V(PlatformConfigurationNativeApi::ScheduleFrame) \ V(PlatformConfigurationNativeApi::EndWarmUpFrame) \ V(PlatformConfigurationNativeApi::Render) \ V(PlatformConfigurationNativeApi::UpdateSemantics) \ V(PlatformConfigurationNativeApi::SetNeedsReportTimings) \ V(PlatformConfigurationNativeApi::SetIsolateDebugName) \ V(PlatformConfigurationNativeApi::RequestDartPerformanceMode) \ V(PlatformConfigurationNativeApi::GetPersistentIsolateData) \ V(PlatformConfigurationNativeApi::ComputePlatformResolvedLocale) \ V(PlatformConfigurationNativeApi::SendPlatformMessage) \ V(PlatformConfigurationNativeApi::RespondToPlatformMessage) \ V(PlatformConfigurationNativeApi::GetRootIsolateToken) \ V(PlatformConfigurationNativeApi::RegisterBackgroundIsolate) \ V(PlatformConfigurationNativeApi::SendPortPlatformMessage) \ V(PlatformConfigurationNativeApi::SendChannelUpdate) \ V(PlatformConfigurationNativeApi::GetScaledFontSize) \ V(PlatformIsolateNativeApi::IsRunningOnPlatformThread) \ V(PlatformIsolateNativeApi::Spawn) \ V(DartRuntimeHooks::Logger_PrintDebugString) \ V(DartRuntimeHooks::Logger_PrintString) \ V(DartRuntimeHooks::ScheduleMicrotask) \ V(DartRuntimeHooks::GetCallbackHandle) \ V(DartRuntimeHooks::GetCallbackFromHandle) \ V(DartPluginRegistrant_EnsureInitialized) \ V(Vertices::init) // List of native instance methods used as @Native functions. // Items are tuples of ('class_name', 'method_name', 'parameter_count'), where: // 'class_name' is the name of the class containing the method. // 'method_name' is the name of the method. // 'parameter_count' is the number of parameters the method has including the // implicit `this` parameter. // // These are used to: // - Instantiate FfiDispatcher templates to automatically create FFI Native // bindings. // If the name does not match a native function, the template will fail to // instatiate, resulting in a compile time error. // - Resolve the native function pointer associated with an @Native function. // If there is a mismatch between names or parameter count an @Native is // trying to resolve, an exception will be thrown. #define FFI_METHOD_LIST(V) \ V(Canvas, clipPath) \ V(Canvas, clipRect) \ V(Canvas, clipRRect) \ V(Canvas, drawArc) \ V(Canvas, drawAtlas) \ V(Canvas, drawCircle) \ V(Canvas, drawColor) \ V(Canvas, drawDRRect) \ V(Canvas, drawImage) \ V(Canvas, drawImageNine) \ V(Canvas, drawImageRect) \ V(Canvas, drawLine) \ V(Canvas, drawOval) \ V(Canvas, drawPaint) \ V(Canvas, drawPath) \ V(Canvas, drawPicture) \ V(Canvas, drawPoints) \ V(Canvas, drawRRect) \ V(Canvas, drawRect) \ V(Canvas, drawShadow) \ V(Canvas, drawVertices) \ V(Canvas, getDestinationClipBounds) \ V(Canvas, getLocalClipBounds) \ V(Canvas, getSaveCount) \ V(Canvas, getTransform) \ V(Canvas, restore) \ V(Canvas, restoreToCount) \ V(Canvas, rotate) \ V(Canvas, save) \ V(Canvas, saveLayer) \ V(Canvas, saveLayerWithoutBounds) \ V(Canvas, scale) \ V(Canvas, skew) \ V(Canvas, transform) \ V(Canvas, translate) \ V(Codec, dispose) \ V(Codec, frameCount) \ V(Codec, getNextFrame) \ V(Codec, repetitionCount) \ V(ColorFilter, initLinearToSrgbGamma) \ V(ColorFilter, initMatrix) \ V(ColorFilter, initMode) \ V(ColorFilter, initSrgbToLinearGamma) \ V(EngineLayer, dispose) \ V(FragmentProgram, initFromAsset) \ V(ReusableFragmentShader, Dispose) \ V(ReusableFragmentShader, SetImageSampler) \ V(ReusableFragmentShader, ValidateSamplers) \ V(Gradient, initLinear) \ V(Gradient, initRadial) \ V(Gradient, initSweep) \ V(Gradient, initTwoPointConical) \ V(Image, dispose) \ V(Image, width) \ V(Image, height) \ V(Image, toByteData) \ V(Image, colorSpace) \ V(ImageDescriptor, bytesPerPixel) \ V(ImageDescriptor, dispose) \ V(ImageDescriptor, height) \ V(ImageDescriptor, instantiateCodec) \ V(ImageDescriptor, width) \ V(ImageFilter, initBlur) \ V(ImageFilter, initDilate) \ V(ImageFilter, initErode) \ V(ImageFilter, initColorFilter) \ V(ImageFilter, initComposeFilter) \ V(ImageFilter, initMatrix) \ V(ImageShader, dispose) \ V(ImageShader, initWithImage) \ V(ImmutableBuffer, dispose) \ V(ImmutableBuffer, length) \ V(ParagraphBuilder, addPlaceholder) \ V(ParagraphBuilder, addText) \ V(ParagraphBuilder, build) \ V(ParagraphBuilder, pop) \ V(ParagraphBuilder, pushStyle) \ V(Paragraph, alphabeticBaseline) \ V(Paragraph, computeLineMetrics) \ V(Paragraph, didExceedMaxLines) \ V(Paragraph, dispose) \ V(Paragraph, getClosestGlyphInfo) \ V(Paragraph, getGlyphInfoAt) \ V(Paragraph, getLineBoundary) \ V(Paragraph, getLineMetricsAt) \ V(Paragraph, getLineNumberAt) \ V(Paragraph, getNumberOfLines) \ V(Paragraph, getPositionForOffset) \ V(Paragraph, getRectsForPlaceholders) \ V(Paragraph, getRectsForRange) \ V(Paragraph, getWordBoundary) \ V(Paragraph, height) \ V(Paragraph, ideographicBaseline) \ V(Paragraph, layout) \ V(Paragraph, longestLine) \ V(Paragraph, maxIntrinsicWidth) \ V(Paragraph, minIntrinsicWidth) \ V(Paragraph, paint) \ V(Paragraph, width) \ V(PathMeasure, setPath) \ V(PathMeasure, getLength) \ V(PathMeasure, getPosTan) \ V(PathMeasure, getSegment) \ V(PathMeasure, isClosed) \ V(PathMeasure, nextContour) \ V(Path, addArc) \ V(Path, addOval) \ V(Path, addPath) \ V(Path, addPathWithMatrix) \ V(Path, addPolygon) \ V(Path, addRRect) \ V(Path, addRect) \ V(Path, arcTo) \ V(Path, arcToPoint) \ V(Path, clone) \ V(Path, close) \ V(Path, conicTo) \ V(Path, contains) \ V(Path, cubicTo) \ V(Path, extendWithPath) \ V(Path, extendWithPathAndMatrix) \ V(Path, getBounds) \ V(Path, getFillType) \ V(Path, lineTo) \ V(Path, moveTo) \ V(Path, op) \ V(Path, quadraticBezierTo) \ V(Path, relativeArcToPoint) \ V(Path, relativeConicTo) \ V(Path, relativeCubicTo) \ V(Path, relativeLineTo) \ V(Path, relativeMoveTo) \ V(Path, relativeQuadraticBezierTo) \ V(Path, reset) \ V(Path, setFillType) \ V(Path, shift) \ V(Path, transform) \ V(PictureRecorder, endRecording) \ V(Picture, GetAllocationSize) \ V(Picture, dispose) \ V(Picture, toImage) \ V(Picture, toImageSync) \ V(SceneBuilder, addPerformanceOverlay) \ V(SceneBuilder, addPicture) \ V(SceneBuilder, addPlatformView) \ V(SceneBuilder, addRetained) \ V(SceneBuilder, addTexture) \ V(SceneBuilder, build) \ V(SceneBuilder, pop) \ V(SceneBuilder, pushBackdropFilter) \ V(SceneBuilder, pushClipPath) \ V(SceneBuilder, pushClipRRect) \ V(SceneBuilder, pushClipRect) \ V(SceneBuilder, pushColorFilter) \ V(SceneBuilder, pushImageFilter) \ V(SceneBuilder, pushOffset) \ V(SceneBuilder, pushOpacity) \ V(SceneBuilder, pushShaderMask) \ V(SceneBuilder, pushTransformHandle) \ V(SceneBuilder, setCheckerboardOffscreenLayers) \ V(SceneBuilder, setCheckerboardRasterCacheImages) \ V(SceneBuilder, setRasterizerTracingThreshold) \ V(Scene, dispose) \ V(Scene, toImage) \ V(Scene, toImageSync) \ V(SemanticsUpdateBuilder, build) \ V(SemanticsUpdateBuilder, updateCustomAction) \ V(SemanticsUpdateBuilder, updateNode) \ V(SemanticsUpdate, dispose) \ V(Vertices, dispose) #ifdef IMPELLER_ENABLE_3D #define FFI_FUNCTION_LIST_3D(V) \ V(SceneNode::Create) \ V(SceneShader::Create) #define FFI_METHOD_LIST_3D(V) \ V(SceneNode, initFromAsset) \ V(SceneNode, initFromTransform) \ V(SceneNode, AddChild) \ V(SceneNode, SetTransform) \ V(SceneNode, SetAnimationState) \ V(SceneNode, SeekAnimation) \ V(SceneShader, SetCameraTransform) \ V(SceneShader, Dispose) #endif // IMPELLER_ENABLE_3D #define FFI_FUNCTION_INSERT(FUNCTION) \ g_function_dispatchers.insert(std::make_pair( \ std::string_view(#FUNCTION), \ reinterpret_cast<void*>( \ tonic::FfiDispatcher<void, decltype(&FUNCTION), &FUNCTION>::Call))); #define FFI_METHOD_INSERT(CLASS, METHOD) \ g_function_dispatchers.insert( \ std::make_pair(std::string_view(#CLASS "::" #METHOD), \ reinterpret_cast<void*>( \ tonic::FfiDispatcher<CLASS, decltype(&CLASS::METHOD), \ &CLASS::METHOD>::Call))); namespace { std::once_flag g_dispatchers_init_flag; std::unordered_map<std::string_view, void*> g_function_dispatchers; void* ResolveFfiNativeFunction(const char* name, uintptr_t args) { auto it = g_function_dispatchers.find(name); return (it != g_function_dispatchers.end()) ? it->second : nullptr; } void InitDispatcherMap() { FFI_FUNCTION_LIST(FFI_FUNCTION_INSERT) FFI_METHOD_LIST(FFI_METHOD_INSERT) #ifdef IMPELLER_ENABLE_3D FFI_FUNCTION_LIST_3D(FFI_FUNCTION_INSERT) FFI_METHOD_LIST_3D(FFI_METHOD_INSERT) #endif // IMPELLER_ENABLE_3D } } // anonymous namespace void DartUI::InitForIsolate(const Settings& settings) { std::call_once(g_dispatchers_init_flag, InitDispatcherMap); auto dart_ui = Dart_LookupLibrary(ToDart("dart:ui")); if (Dart_IsError(dart_ui)) { Dart_PropagateError(dart_ui); } // Set up FFI Native resolver for dart:ui. Dart_Handle result = Dart_SetFfiNativeResolver(dart_ui, ResolveFfiNativeFunction); if (Dart_IsError(result)) { Dart_PropagateError(result); } if (settings.enable_impeller) { result = Dart_SetField(dart_ui, ToDart("_impellerEnabled"), Dart_True()); if (Dart_IsError(result)) { Dart_PropagateError(result); } } result = Dart_SetField(dart_ui, ToDart("_implicitViewId"), Dart_NewInteger(kFlutterImplicitViewId)); if (Dart_IsError(result)) { Dart_PropagateError(result); } } } // namespace flutter
engine/lib/ui/dart_ui.cc/0
{ "file_path": "engine/lib/ui/dart_ui.cc", "repo_id": "engine", "token_count": 10772 }
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. part of dart.ui; @pragma('vm:entry-point') void _addView( int viewId, double devicePixelRatio, double width, double height, double viewPaddingTop, double viewPaddingRight, double viewPaddingBottom, double viewPaddingLeft, double viewInsetTop, double viewInsetRight, double viewInsetBottom, double viewInsetLeft, double systemGestureInsetTop, double systemGestureInsetRight, double systemGestureInsetBottom, double systemGestureInsetLeft, double physicalTouchSlop, List<double> displayFeaturesBounds, List<int> displayFeaturesType, List<int> displayFeaturesState, int displayId, ) { final _ViewConfiguration viewConfiguration = _buildViewConfiguration( devicePixelRatio, width, height, viewPaddingTop, viewPaddingRight, viewPaddingBottom, viewPaddingLeft, viewInsetTop, viewInsetRight, viewInsetBottom, viewInsetLeft, systemGestureInsetTop, systemGestureInsetRight, systemGestureInsetBottom, systemGestureInsetLeft, physicalTouchSlop, displayFeaturesBounds, displayFeaturesType, displayFeaturesState, displayId, ); PlatformDispatcher.instance._addView(viewId, viewConfiguration); } @pragma('vm:entry-point') void _removeView(int viewId) { PlatformDispatcher.instance._removeView(viewId); } @pragma('vm:entry-point') void _updateDisplays( List<int> ids, List<double> widths, List<double> heights, List<double> devicePixelRatios, List<double> refreshRates, ) { assert(ids.length == widths.length); assert(ids.length == heights.length); assert(ids.length == devicePixelRatios.length); assert(ids.length == refreshRates.length); final List<Display> displays = <Display>[]; for (int index = 0; index < ids.length; index += 1) { final int displayId = ids[index]; displays.add(Display._( id: displayId, size: Size(widths[index], heights[index]), devicePixelRatio: devicePixelRatios[index], refreshRate: refreshRates[index], )); } PlatformDispatcher.instance._updateDisplays(displays); } List<DisplayFeature> _decodeDisplayFeatures({ required List<double> bounds, required List<int> type, required List<int> state, required double devicePixelRatio, }) { assert(bounds.length / 4 == type.length, 'Bounds are rectangles, requiring 4 measurements each'); assert(type.length == state.length); final List<DisplayFeature> result = <DisplayFeature>[]; for(int i = 0; i < type.length; i++) { final int rectOffset = i * 4; result.add(DisplayFeature( bounds: Rect.fromLTRB( bounds[rectOffset] / devicePixelRatio, bounds[rectOffset + 1] / devicePixelRatio, bounds[rectOffset + 2] / devicePixelRatio, bounds[rectOffset + 3] / devicePixelRatio, ), type: DisplayFeatureType.values[type[i]], state: state[i] < DisplayFeatureState.values.length ? DisplayFeatureState.values[state[i]] : DisplayFeatureState.unknown, )); } return result; } _ViewConfiguration _buildViewConfiguration( double devicePixelRatio, double width, double height, double viewPaddingTop, double viewPaddingRight, double viewPaddingBottom, double viewPaddingLeft, double viewInsetTop, double viewInsetRight, double viewInsetBottom, double viewInsetLeft, double systemGestureInsetTop, double systemGestureInsetRight, double systemGestureInsetBottom, double systemGestureInsetLeft, double physicalTouchSlop, List<double> displayFeaturesBounds, List<int> displayFeaturesType, List<int> displayFeaturesState, int displayId, ) { return _ViewConfiguration( devicePixelRatio: devicePixelRatio, size: Size(width, height), viewPadding: ViewPadding._( top: viewPaddingTop, right: viewPaddingRight, bottom: viewPaddingBottom, left: viewPaddingLeft, ), viewInsets: ViewPadding._( top: viewInsetTop, right: viewInsetRight, bottom: viewInsetBottom, left: viewInsetLeft, ), padding: ViewPadding._( top: math.max(0.0, viewPaddingTop - viewInsetTop), right: math.max(0.0, viewPaddingRight - viewInsetRight), bottom: math.max(0.0, viewPaddingBottom - viewInsetBottom), left: math.max(0.0, viewPaddingLeft - viewInsetLeft), ), systemGestureInsets: ViewPadding._( top: math.max(0.0, systemGestureInsetTop), right: math.max(0.0, systemGestureInsetRight), bottom: math.max(0.0, systemGestureInsetBottom), left: math.max(0.0, systemGestureInsetLeft), ), gestureSettings: GestureSettings( physicalTouchSlop: physicalTouchSlop == _kUnsetGestureSetting ? null : physicalTouchSlop, ), displayFeatures: _decodeDisplayFeatures( bounds: displayFeaturesBounds, type: displayFeaturesType, state: displayFeaturesState, devicePixelRatio: devicePixelRatio, ), displayId: displayId, ); } @pragma('vm:entry-point') void _updateWindowMetrics( int viewId, double devicePixelRatio, double width, double height, double viewPaddingTop, double viewPaddingRight, double viewPaddingBottom, double viewPaddingLeft, double viewInsetTop, double viewInsetRight, double viewInsetBottom, double viewInsetLeft, double systemGestureInsetTop, double systemGestureInsetRight, double systemGestureInsetBottom, double systemGestureInsetLeft, double physicalTouchSlop, List<double> displayFeaturesBounds, List<int> displayFeaturesType, List<int> displayFeaturesState, int displayId, ) { final _ViewConfiguration viewConfiguration = _buildViewConfiguration( devicePixelRatio, width, height, viewPaddingTop, viewPaddingRight, viewPaddingBottom, viewPaddingLeft, viewInsetTop, viewInsetRight, viewInsetBottom, viewInsetLeft, systemGestureInsetTop, systemGestureInsetRight, systemGestureInsetBottom, systemGestureInsetLeft, physicalTouchSlop, displayFeaturesBounds, displayFeaturesType, displayFeaturesState, displayId, ); PlatformDispatcher.instance._updateWindowMetrics(viewId, viewConfiguration); } typedef _LocaleClosure = String Function(); @pragma('vm:entry-point') _LocaleClosure? _getLocaleClosure() => PlatformDispatcher.instance._localeClosure; @pragma('vm:entry-point') void _updateLocales(List<String> locales) { PlatformDispatcher.instance._updateLocales(locales); } @pragma('vm:entry-point') void _updateUserSettingsData(String jsonData) { PlatformDispatcher.instance._updateUserSettingsData(jsonData); } @pragma('vm:entry-point') void _updateInitialLifecycleState(String state) { PlatformDispatcher.instance._updateInitialLifecycleState(state); } @pragma('vm:entry-point') void _updateSemanticsEnabled(bool enabled) { PlatformDispatcher.instance._updateSemanticsEnabled(enabled); } @pragma('vm:entry-point') void _updateAccessibilityFeatures(int values) { PlatformDispatcher.instance._updateAccessibilityFeatures(values); } @pragma('vm:entry-point') void _dispatchPlatformMessage(String name, ByteData? data, int responseId) { PlatformDispatcher.instance._dispatchPlatformMessage(name, data, responseId); } @pragma('vm:entry-point') void _dispatchPointerDataPacket(ByteData packet) { PlatformDispatcher.instance._dispatchPointerDataPacket(packet); } @pragma('vm:entry-point') void _dispatchSemanticsAction(int nodeId, int action, ByteData? args) { PlatformDispatcher.instance._dispatchSemanticsAction(nodeId, action, args); } @pragma('vm:entry-point') void _beginFrame(int microseconds, int frameNumber) { PlatformDispatcher.instance._beginFrame(microseconds); PlatformDispatcher.instance._updateFrameData(frameNumber); } @pragma('vm:entry-point') void _reportTimings(List<int> timings) { PlatformDispatcher.instance._reportTimings(timings); } @pragma('vm:entry-point') void _drawFrame() { PlatformDispatcher.instance._drawFrame(); } @pragma('vm:entry-point') bool _onError(Object error, StackTrace? stackTrace) { return PlatformDispatcher.instance._dispatchError(error, stackTrace ?? StackTrace.empty); } typedef _ListStringArgFunction = Object? Function(List<String> args); @pragma('vm:entry-point') void _runMain(Function startMainIsolateFunction, Function userMainFunction, List<String> args) { startMainIsolateFunction(() { // ignore: avoid_dynamic_calls if (userMainFunction is _ListStringArgFunction) { userMainFunction(args); } else { userMainFunction(); // ignore: avoid_dynamic_calls } }, null); } /// Invokes [callback] inside the given [zone]. void _invoke(void Function()? callback, Zone zone) { if (callback == null) { return; } if (identical(zone, Zone.current)) { callback(); } else { zone.runGuarded(callback); } } /// Invokes [callback] inside the given [zone] passing it [arg]. /// /// The 1 in the name refers to the number of arguments expected by /// the callback (and thus passed to this function, in addition to the /// callback itself and the zone in which the callback is executed). void _invoke1<A>(void Function(A a)? callback, Zone zone, A arg) { if (callback == null) { return; } if (identical(zone, Zone.current)) { callback(arg); } else { zone.runUnaryGuarded<A>(callback, arg); } } /// Invokes [callback] inside the given [zone] passing it [arg1] and [arg2]. /// /// The 2 in the name refers to the number of arguments expected by /// the callback (and thus passed to this function, in addition to the /// callback itself and the zone in which the callback is executed). void _invoke2<A1, A2>(void Function(A1 a1, A2 a2)? callback, Zone zone, A1 arg1, A2 arg2) { if (callback == null) { return; } if (identical(zone, Zone.current)) { callback(arg1, arg2); } else { zone.runGuarded(() { callback(arg1, arg2); }); } } /// Invokes [callback] inside the given [zone] passing it [arg1], [arg2], and [arg3]. /// /// The 3 in the name refers to the number of arguments expected by /// the callback (and thus passed to this function, in addition to the /// callback itself and the zone in which the callback is executed). void _invoke3<A1, A2, A3>(void Function(A1 a1, A2 a2, A3 a3)? callback, Zone zone, A1 arg1, A2 arg2, A3 arg3) { if (callback == null) { return; } if (identical(zone, Zone.current)) { callback(arg1, arg2, arg3); } else { zone.runGuarded(() { callback(arg1, arg2, arg3); }); } } bool _isLoopback(String host) { if (host.isEmpty) { return false; } if ('localhost' == host) { return true; } try { return InternetAddress(host).isLoopback; } on ArgumentError { return false; } } /// Loopback connections are always allowed. /// Zone override with 'flutter.io.allow_http' takes first priority. /// If zone override is not provided, engine setting is checked. @pragma('vm:entry-point') void Function(Uri) _getHttpConnectionHookClosure(bool mayInsecurelyConnectToAllDomains) { return (Uri uri) { final Object? zoneOverride = Zone.current[#flutter.io.allow_http]; if (zoneOverride == true) { return; } if (zoneOverride == false && uri.isScheme('http')) { // Going to _isLoopback check before throwing } else if (mayInsecurelyConnectToAllDomains || uri.isScheme('https')) { // In absence of zone override, if engine setting allows the connection // or if connection is to `https`, allow the connection. return; } // Loopback connections are always allowed // Check at last resort to avoid debug annoyance of try/on ArgumentError if (_isLoopback(uri.host)) { return; } throw UnsupportedError( 'Non-https connection "$uri" is not supported by the platform. ' 'Refer to https://flutter.dev/docs/release/breaking-changes/network-policy-ios-android.'); }; }
engine/lib/ui/hooks.dart/0
{ "file_path": "engine/lib/ui/hooks.dart", "repo_id": "engine", "token_count": 4270 }
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. #include "flutter/lib/ui/painting/codec.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" #include "third_party/tonic/dart_state.h" #include "third_party/tonic/logging/dart_invoke.h" #include "third_party/tonic/typed_data/typed_list.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, Codec); void Codec::dispose() { ClearDartWrapper(); } } // namespace flutter
engine/lib/ui/painting/codec.cc/0
{ "file_path": "engine/lib/ui/painting/codec.cc", "repo_id": "engine", "token_count": 216 }
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/lib/ui/painting/gradient.h" #include "flutter/lib/ui/floating_point.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 { typedef CanvasGradient Gradient; // Because the C++ name doesn't match the Dart name. IMPLEMENT_WRAPPERTYPEINFO(ui, Gradient); void CanvasGradient::Create(Dart_Handle wrapper) { UIDartState::ThrowIfUIOperationsProhibited(); auto res = fml::MakeRefCounted<CanvasGradient>(); res->AssociateWithDartWrapper(wrapper); } void CanvasGradient::initLinear(const tonic::Float32List& end_points, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, const tonic::Float64List& matrix4) { FML_DCHECK(end_points.num_elements() == 4); FML_DCHECK(colors.num_elements() == color_stops.num_elements() || color_stops.data() == nullptr); static_assert(sizeof(SkPoint) == sizeof(float) * 2, "SkPoint doesn't use floats."); static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor doesn't use int32_t."); SkMatrix sk_matrix; bool has_matrix = matrix4.data() != nullptr; if (has_matrix) { sk_matrix = ToSkMatrix(matrix4); } SkPoint p0 = SkPoint::Make(end_points[0], end_points[1]); SkPoint p1 = SkPoint::Make(end_points[2], end_points[3]); const DlColor* colors_array = reinterpret_cast<const DlColor*>(colors.data()); dl_shader_ = DlColorSource::MakeLinear( p0, p1, colors.num_elements(), colors_array, color_stops.data(), tile_mode, has_matrix ? &sk_matrix : nullptr); // Just a sanity check, all gradient shaders should be thread-safe FML_DCHECK(dl_shader_->isUIThreadSafe()); } void CanvasGradient::initRadial(double center_x, double center_y, double radius, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, const tonic::Float64List& matrix4) { FML_DCHECK(colors.num_elements() == color_stops.num_elements() || color_stops.data() == nullptr); static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor doesn't use int32_t."); SkMatrix sk_matrix; bool has_matrix = matrix4.data() != nullptr; if (has_matrix) { sk_matrix = ToSkMatrix(matrix4); } const DlColor* colors_array = reinterpret_cast<const DlColor*>(colors.data()); dl_shader_ = DlColorSource::MakeRadial( SkPoint::Make(SafeNarrow(center_x), SafeNarrow(center_y)), SafeNarrow(radius), colors.num_elements(), colors_array, color_stops.data(), tile_mode, has_matrix ? &sk_matrix : nullptr); // Just a sanity check, all gradient shaders should be thread-safe FML_DCHECK(dl_shader_->isUIThreadSafe()); } void CanvasGradient::initSweep(double center_x, double center_y, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, double start_angle, double end_angle, const tonic::Float64List& matrix4) { FML_DCHECK(colors.num_elements() == color_stops.num_elements() || color_stops.data() == nullptr); static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor doesn't use int32_t."); SkMatrix sk_matrix; bool has_matrix = matrix4.data() != nullptr; if (has_matrix) { sk_matrix = ToSkMatrix(matrix4); } const DlColor* colors_array = reinterpret_cast<const DlColor*>(colors.data()); dl_shader_ = DlColorSource::MakeSweep( SkPoint::Make(SafeNarrow(center_x), SafeNarrow(center_y)), SafeNarrow(start_angle) * 180.0f / static_cast<float>(M_PI), SafeNarrow(end_angle) * 180.0f / static_cast<float>(M_PI), colors.num_elements(), colors_array, color_stops.data(), tile_mode, has_matrix ? &sk_matrix : nullptr); // Just a sanity check, all gradient shaders should be thread-safe FML_DCHECK(dl_shader_->isUIThreadSafe()); } void CanvasGradient::initTwoPointConical(double start_x, double start_y, double start_radius, double end_x, double end_y, double end_radius, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, const tonic::Float64List& matrix4) { FML_DCHECK(colors.num_elements() == color_stops.num_elements() || color_stops.data() == nullptr); static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor doesn't use int32_t."); SkMatrix sk_matrix; bool has_matrix = matrix4.data() != nullptr; if (has_matrix) { sk_matrix = ToSkMatrix(matrix4); } const DlColor* colors_array = reinterpret_cast<const DlColor*>(colors.data()); dl_shader_ = DlColorSource::MakeConical( SkPoint::Make(SafeNarrow(start_x), SafeNarrow(start_y)), SafeNarrow(start_radius), SkPoint::Make(SafeNarrow(end_x), SafeNarrow(end_y)), SafeNarrow(end_radius), colors.num_elements(), colors_array, color_stops.data(), tile_mode, has_matrix ? &sk_matrix : nullptr); // Just a sanity check, all gradient shaders should be thread-safe FML_DCHECK(dl_shader_->isUIThreadSafe()); } CanvasGradient::CanvasGradient() = default; CanvasGradient::~CanvasGradient() = default; } // namespace flutter
engine/lib/ui/painting/gradient.cc/0
{ "file_path": "engine/lib/ui/painting/gradient.cc", "repo_id": "engine", "token_count": 2980 }
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. #include "flutter/lib/ui/painting/image_encoding.h" #include "flutter/lib/ui/painting/image_encoding_impl.h" #include <memory> #include <utility> #include "flutter/common/task_runners.h" #include "flutter/fml/build_config.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/status_or.h" #include "flutter/fml/trace_event.h" #include "flutter/lib/ui/painting/image.h" #if IMPELLER_SUPPORTS_RENDERING #include "flutter/lib/ui/painting/image_encoding_impeller.h" #endif // IMPELLER_SUPPORTS_RENDERING #include "flutter/lib/ui/painting/image_encoding_skia.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/encode/SkPngEncoder.h" #include "third_party/tonic/dart_persistent_value.h" #include "third_party/tonic/logging/dart_invoke.h" #include "third_party/tonic/typed_data/typed_list.h" using tonic::DartInvoke; using tonic::DartPersistentValue; using tonic::ToDart; namespace impeller { class Context; } // namespace impeller namespace flutter { namespace { void FinalizeSkData(void* isolate_callback_data, void* peer) { SkData* buffer = reinterpret_cast<SkData*>(peer); buffer->unref(); } void InvokeDataCallback(std::unique_ptr<DartPersistentValue> callback, fml::StatusOr<sk_sp<SkData>>&& buffer) { std::shared_ptr<tonic::DartState> dart_state = callback->dart_state().lock(); if (!dart_state) { return; } tonic::DartState::Scope scope(dart_state); if (!buffer.ok()) { std::string error_copy(buffer.status().message()); Dart_Handle dart_string = ToDart(error_copy); DartInvoke(callback->value(), {Dart_Null(), dart_string}); return; } // Skia will not modify the buffer, and it is backed by memory that is // read/write, so Dart can be given direct access to the buffer through an // external Uint8List. void* bytes = const_cast<void*>(buffer.value()->data()); const intptr_t length = buffer.value()->size(); void* peer = reinterpret_cast<void*>(buffer.value().release()); Dart_Handle dart_data = Dart_NewExternalTypedDataWithFinalizer( Dart_TypedData_kUint8, bytes, length, peer, length, FinalizeSkData); DartInvoke(callback->value(), {dart_data, Dart_Null()}); } sk_sp<SkData> CopyImageByteData(const sk_sp<SkImage>& raster_image, SkColorType color_type, SkAlphaType alpha_type) { FML_DCHECK(raster_image); SkPixmap pixmap; if (!raster_image->peekPixels(&pixmap)) { FML_LOG(ERROR) << "Could not copy pixels from the raster image."; return nullptr; } // The color types already match. No need to swizzle. Return early. if (pixmap.colorType() == color_type && pixmap.alphaType() == alpha_type) { return SkData::MakeWithCopy(pixmap.addr(), pixmap.computeByteSize()); } // Perform swizzle if the type doesnt match the specification. auto surface = SkSurfaces::Raster( SkImageInfo::Make(raster_image->width(), raster_image->height(), color_type, alpha_type, nullptr)); if (!surface) { FML_LOG(ERROR) << "Could not set up the surface for swizzle."; return nullptr; } surface->writePixels(pixmap, 0, 0); if (!surface->peekPixels(&pixmap)) { FML_LOG(ERROR) << "Pixel address is not available."; return nullptr; } return SkData::MakeWithCopy(pixmap.addr(), pixmap.computeByteSize()); } void EncodeImageAndInvokeDataCallback( const sk_sp<DlImage>& image, std::unique_ptr<DartPersistentValue> callback, ImageByteFormat format, const fml::RefPtr<fml::TaskRunner>& ui_task_runner, const fml::RefPtr<fml::TaskRunner>& raster_task_runner, const fml::RefPtr<fml::TaskRunner>& io_task_runner, const fml::WeakPtr<GrDirectContext>& resource_context, const fml::TaskRunnerAffineWeakPtr<SnapshotDelegate>& snapshot_delegate, const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch, const std::shared_ptr<impeller::Context>& impeller_context, bool is_impeller_enabled) { auto callback_task = fml::MakeCopyable([callback = std::move(callback)]( fml::StatusOr<sk_sp<SkData>>&& encoded) mutable { InvokeDataCallback(std::move(callback), std::move(encoded)); }); // The static leak checker gets confused by the use of fml::MakeCopyable in // EncodeImage. // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) auto encode_task = [callback_task = std::move(callback_task), format, ui_task_runner](const fml::StatusOr<sk_sp<SkImage>>& raster_image) { if (raster_image.ok()) { sk_sp<SkData> encoded = EncodeImage(raster_image.value(), format); ui_task_runner->PostTask([callback_task = callback_task, encoded = std::move(encoded)]() mutable { callback_task(std::move(encoded)); }); } else { ui_task_runner->PostTask([callback_task = callback_task, raster_image = raster_image]() mutable { callback_task(raster_image.status()); }); } }; FML_DCHECK(image); #if IMPELLER_SUPPORTS_RENDERING if (is_impeller_enabled) { ImageEncodingImpeller::ConvertImageToRaster( image, encode_task, raster_task_runner, io_task_runner, is_gpu_disabled_sync_switch, impeller_context); return; } #endif // IMPELLER_SUPPORTS_RENDERING ConvertImageToRasterSkia(image, encode_task, raster_task_runner, io_task_runner, resource_context, snapshot_delegate, is_gpu_disabled_sync_switch); } } // namespace Dart_Handle EncodeImage(CanvasImage* canvas_image, int format, Dart_Handle callback_handle) { if (!canvas_image) { return ToDart("encode called with non-genuine Image."); } if (!Dart_IsClosure(callback_handle)) { return ToDart("Callback must be a function."); } ImageByteFormat image_format = static_cast<ImageByteFormat>(format); auto callback = std::make_unique<DartPersistentValue>( tonic::DartState::Current(), callback_handle); const auto& task_runners = UIDartState::Current()->GetTaskRunners(); // The static leak checker gets confused by the use of fml::MakeCopyable. // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) task_runners.GetIOTaskRunner()->PostTask(fml::MakeCopyable( [callback = std::move(callback), image = canvas_image->image(), image_format, ui_task_runner = task_runners.GetUITaskRunner(), raster_task_runner = task_runners.GetRasterTaskRunner(), io_task_runner = task_runners.GetIOTaskRunner(), io_manager = UIDartState::Current()->GetIOManager(), snapshot_delegate = UIDartState::Current()->GetSnapshotDelegate(), is_impeller_enabled = UIDartState::Current()->IsImpellerEnabled()]() mutable { EncodeImageAndInvokeDataCallback( image, std::move(callback), image_format, ui_task_runner, raster_task_runner, io_task_runner, io_manager->GetResourceContext(), snapshot_delegate, io_manager->GetIsGpuDisabledSyncSwitch(), io_manager->GetImpellerContext(), is_impeller_enabled); })); return Dart_Null(); } sk_sp<SkData> EncodeImage(const sk_sp<SkImage>& raster_image, ImageByteFormat format) { TRACE_EVENT0("flutter", __FUNCTION__); if (!raster_image) { return nullptr; } switch (format) { case kPNG: { auto png_image = SkPngEncoder::Encode(nullptr, raster_image.get(), {}); if (png_image == nullptr) { FML_LOG(ERROR) << "Could not convert raster image to PNG."; return nullptr; }; return png_image; } case kRawRGBA: return CopyImageByteData(raster_image, kRGBA_8888_SkColorType, kPremul_SkAlphaType); case kRawStraightRGBA: return CopyImageByteData(raster_image, kRGBA_8888_SkColorType, kUnpremul_SkAlphaType); case kRawUnmodified: return CopyImageByteData(raster_image, raster_image->colorType(), raster_image->alphaType()); case kRawExtendedRgba128: return CopyImageByteData(raster_image, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType); } FML_LOG(ERROR) << "Unknown error encoding image."; return nullptr; } } // namespace flutter
engine/lib/ui/painting/image_encoding.cc/0
{ "file_path": "engine/lib/ui/painting/image_encoding.cc", "repo_id": "engine", "token_count": 3593 }
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. #include "flutter/lib/ui/painting/image_generator_registry.h" #include "flutter/fml/mapping.h" #include "flutter/shell/common/shell_test.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/codec/SkCodecAnimation.h" namespace flutter { namespace testing { static sk_sp<SkData> LoadValidImageFixture() { auto fixture_mapping = OpenFixtureAsMapping("DashInNooglerHat.jpg"); // Remap to sk_sp<SkData>. SkData::ReleaseProc on_release = [](const void* ptr, void* context) -> void { delete reinterpret_cast<fml::FileMapping*>(context); }; auto data = SkData::MakeWithProc(fixture_mapping->GetMapping(), fixture_mapping->GetSize(), on_release, fixture_mapping.get()); if (data) { fixture_mapping.release(); } return data; } TEST_F(ShellTest, CreateCompatibleReturnsBuiltinImageGeneratorForValidImage) { auto data = LoadValidImageFixture(); // Fetch the generator and query for basic info ImageGeneratorRegistry registry; auto result = registry.CreateCompatibleGenerator(data); auto info = result->GetInfo(); ASSERT_EQ(info.width(), 3024); ASSERT_EQ(info.height(), 4032); } TEST_F(ShellTest, CreateCompatibleReturnsNullptrForInvalidImage) { ImageGeneratorRegistry registry; auto result = registry.CreateCompatibleGenerator(SkData::MakeEmpty()); ASSERT_EQ(result, nullptr); } class FakeImageGenerator : public ImageGenerator { public: explicit FakeImageGenerator(int identifiableFakeWidth) : info_(SkImageInfo::Make(identifiableFakeWidth, identifiableFakeWidth, SkColorType::kRGBA_8888_SkColorType, SkAlphaType::kOpaque_SkAlphaType)){}; ~FakeImageGenerator() = default; const SkImageInfo& GetInfo() { return info_; } unsigned int GetFrameCount() const { return 1; } unsigned int GetPlayCount() const { return 1; } const ImageGenerator::FrameInfo GetFrameInfo(unsigned int frame_index) { return {std::nullopt, 0, SkCodecAnimation::DisposalMethod::kKeep}; } SkISize GetScaledDimensions(float scale) { return SkISize::Make(info_.width(), info_.height()); } bool GetPixels(const SkImageInfo& info, void* pixels, size_t row_bytes, unsigned int frame_index, std::optional<unsigned int> prior_frame) { return false; }; private: SkImageInfo info_; }; TEST_F(ShellTest, PositivePriorityTakesPrecedentOverDefaultGenerators) { ImageGeneratorRegistry registry; const int fake_width = 1337; registry.AddFactory( [fake_width](const sk_sp<SkData>& buffer) { return std::make_unique<FakeImageGenerator>(fake_width); }, 1); // Fetch the generator and query for basic info. auto result = registry.CreateCompatibleGenerator(LoadValidImageFixture()); ASSERT_EQ(result->GetInfo().width(), fake_width); } TEST_F(ShellTest, DefaultGeneratorsTakePrecedentOverNegativePriority) { ImageGeneratorRegistry registry; registry.AddFactory( [](const sk_sp<SkData>& buffer) { return std::make_unique<FakeImageGenerator>(1337); }, -1); // Fetch the generator and query for basic info. auto result = registry.CreateCompatibleGenerator(LoadValidImageFixture()); // If the real width of the image pops out, then the default generator was // returned rather than the fake one. ASSERT_EQ(result->GetInfo().width(), 3024); } TEST_F(ShellTest, DefaultGeneratorsTakePrecedentOverZeroPriority) { ImageGeneratorRegistry registry; registry.AddFactory( [](const sk_sp<SkData>& buffer) { return std::make_unique<FakeImageGenerator>(1337); }, 0); // Fetch the generator and query for basic info. auto result = registry.CreateCompatibleGenerator(LoadValidImageFixture()); // If the real width of the image pops out, then the default generator was // returned rather than the fake one. ASSERT_EQ(result->GetInfo().width(), 3024); } TEST_F(ShellTest, ImageGeneratorsWithSamePriorityCascadeChronologically) { ImageGeneratorRegistry registry; // Add 2 factories with the same high priority. registry.AddFactory( [](const sk_sp<SkData>& buffer) { return std::make_unique<FakeImageGenerator>(1337); }, 5); registry.AddFactory( [](const sk_sp<SkData>& buffer) { return std::make_unique<FakeImageGenerator>(7777); }, 5); // Feed empty data so that Skia's image generators will reject it, but ours // won't. auto result = registry.CreateCompatibleGenerator(SkData::MakeEmpty()); ASSERT_EQ(result->GetInfo().width(), 1337); } } // namespace testing } // namespace flutter
engine/lib/ui/painting/image_generator_registry_unittests.cc/0
{ "file_path": "engine/lib/ui/painting/image_generator_registry_unittests.cc", "repo_id": "engine", "token_count": 1794 }
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. #include "flutter/lib/ui/painting/path.h" #include <memory> #include "flutter/common/task_runners.h" #include "flutter/fml/synchronization/waitable_event.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, PathVolatilityOldPathsBecomeNonVolatile) { auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); auto native_validate_path = [message_latch](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); intptr_t peer = 0; Dart_Handle result = Dart_GetNativeInstanceField( handle, tonic::DartWrappable::kPeerIndex, &peer); EXPECT_FALSE(Dart_IsError(result)); CanvasPath* path = reinterpret_cast<CanvasPath*>(peer); EXPECT_TRUE(path); EXPECT_TRUE(path->path().isVolatile()); std::shared_ptr<VolatilePathTracker> tracker = UIDartState::Current()->GetVolatilePathTracker(); EXPECT_TRUE(tracker); for (int i = 0; i < VolatilePathTracker::kFramesOfVolatility; i++) { EXPECT_TRUE(path->path().isVolatile()); tracker->OnFrame(); } EXPECT_FALSE(path->path().isVolatile()); message_latch->Signal(); }; Settings settings = CreateSettingsForFixture(); TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform CreateNewThread(), // raster CreateNewThread(), // ui CreateNewThread() // io ); AddNativeCallback("ValidatePath", CREATE_NATIVE_ENTRY(native_validate_path)); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("createPath"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); DestroyShell(std::move(shell), task_runners); } TEST_F(ShellTest, PathVolatilityGCRemovesPathFromTracker) { static_assert(VolatilePathTracker::kFramesOfVolatility > 1); auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); auto native_validate_path = [message_latch](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); intptr_t peer = 0; Dart_Handle result = Dart_GetNativeInstanceField( handle, tonic::DartWrappable::kPeerIndex, &peer); EXPECT_FALSE(Dart_IsError(result)); CanvasPath* path = reinterpret_cast<CanvasPath*>(peer); EXPECT_TRUE(path); EXPECT_TRUE(path->path().isVolatile()); std::shared_ptr<VolatilePathTracker> tracker = UIDartState::Current()->GetVolatilePathTracker(); EXPECT_TRUE(tracker); EXPECT_EQ(GetLiveTrackedPathCount(tracker), 1ul); EXPECT_TRUE(path->path().isVolatile()); tracker->OnFrame(); EXPECT_EQ(GetLiveTrackedPathCount(tracker), 1ul); EXPECT_TRUE(path->path().isVolatile()); // simulate GC path->Release(); EXPECT_EQ(GetLiveTrackedPathCount(tracker), 0ul); tracker->OnFrame(); EXPECT_EQ(GetLiveTrackedPathCount(tracker), 0ul); message_latch->Signal(); }; Settings settings = CreateSettingsForFixture(); TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform CreateNewThread(), // raster CreateNewThread(), // ui CreateNewThread() // io ); AddNativeCallback("ValidatePath", CREATE_NATIVE_ENTRY(native_validate_path)); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("createPath"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); DestroyShell(std::move(shell), task_runners); } // Screen diffing tests use deterministic rendering. Allowing a path to be // volatile or not for an individual frame can result in minor pixel differences // that cause the test to fail. // If deterministic rendering is enabled, the tracker should be disabled and // paths should always be non-volatile. TEST_F(ShellTest, DeterministicRenderingDisablesPathVolatility) { auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); auto native_validate_path = [message_latch](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); intptr_t peer = 0; Dart_Handle result = Dart_GetNativeInstanceField( handle, tonic::DartWrappable::kPeerIndex, &peer); EXPECT_FALSE(Dart_IsError(result)); CanvasPath* path = reinterpret_cast<CanvasPath*>(peer); EXPECT_TRUE(path); EXPECT_FALSE(path->path().isVolatile()); std::shared_ptr<VolatilePathTracker> tracker = UIDartState::Current()->GetVolatilePathTracker(); EXPECT_TRUE(tracker); EXPECT_FALSE(tracker->enabled()); for (int i = 0; i < VolatilePathTracker::kFramesOfVolatility; i++) { tracker->OnFrame(); EXPECT_FALSE(path->path().isVolatile()); } EXPECT_FALSE(path->path().isVolatile()); message_latch->Signal(); }; Settings settings = CreateSettingsForFixture(); settings.skia_deterministic_rendering_on_cpu = true; TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform CreateNewThread(), // raster CreateNewThread(), // ui CreateNewThread() // io ); AddNativeCallback("ValidatePath", CREATE_NATIVE_ENTRY(native_validate_path)); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("createPath"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); DestroyShell(std::move(shell), task_runners); } } // namespace testing } // namespace flutter
engine/lib/ui/painting/path_unittests.cc/0
{ "file_path": "engine/lib/ui/painting/path_unittests.cc", "repo_id": "engine", "token_count": 2535 }
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/lib/ui/painting/vertices.h" #include <algorithm> #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, Vertices); Vertices::Vertices() {} Vertices::~Vertices() {} bool Vertices::init(Dart_Handle vertices_handle, DlVertexMode vertex_mode, Dart_Handle positions_handle, Dart_Handle texture_coordinates_handle, Dart_Handle colors_handle, Dart_Handle indices_handle) { UIDartState::ThrowIfUIOperationsProhibited(); tonic::Float32List positions(positions_handle); tonic::Float32List texture_coordinates(texture_coordinates_handle); tonic::Int32List colors(colors_handle); tonic::Uint16List indices(indices_handle); if (!positions.data()) { return false; } DlVertices::Builder::Flags flags; if (texture_coordinates.data()) { flags = flags | DlVertices::Builder::kHasTextureCoordinates; } if (colors.data()) { flags = flags | DlVertices::Builder::kHasColors; } DlVertices::Builder builder(vertex_mode, positions.num_elements() / 2, flags, indices.num_elements()); if (!builder.is_valid()) { return false; } // positions are required for SkVertices::Builder builder.store_vertices(positions.data()); if (texture_coordinates.data()) { // SkVertices::Builder assumes equal numbers of elements FML_DCHECK(positions.num_elements() == texture_coordinates.num_elements()); builder.store_texture_coordinates(texture_coordinates.data()); } if (colors.data()) { // SkVertices::Builder assumes equal numbers of elements FML_DCHECK(positions.num_elements() / 2 == colors.num_elements()); builder.store_colors(reinterpret_cast<const SkColor*>(colors.data())); } if (indices.data() && indices.num_elements() > 0) { builder.store_indices(indices.data()); } positions.Release(); texture_coordinates.Release(); colors.Release(); indices.Release(); auto vertices = fml::MakeRefCounted<Vertices>(); vertices->vertices_ = builder.build(); vertices->AssociateWithDartWrapper(vertices_handle); return true; } void Vertices::dispose() { vertices_.reset(); ClearDartWrapper(); } } // namespace flutter
engine/lib/ui/painting/vertices.cc/0
{ "file_path": "engine/lib/ui/painting/vertices.cc", "repo_id": "engine", "token_count": 945 }
298
// 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_SEMANTICS_SEMANTICS_UPDATE_BUILDER_H_ #define FLUTTER_LIB_UI_SEMANTICS_SEMANTICS_UPDATE_BUILDER_H_ #include <any> #include <list> #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/semantics/semantics_update.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/tonic/typed_data/typed_list.h" namespace flutter { class SemanticsUpdateBuilder : public RefCountedDartWrappable<SemanticsUpdateBuilder> { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(SemanticsUpdateBuilder); public: static void Create(Dart_Handle wrapper) { UIDartState::ThrowIfUIOperationsProhibited(); auto res = fml::MakeRefCounted<SemanticsUpdateBuilder>(); res->AssociateWithDartWrapper(wrapper); } ~SemanticsUpdateBuilder() override; 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, std::string identifier, std::string label, const std::vector<NativeStringAttribute*>& labelAttributes, std::string value, const std::vector<NativeStringAttribute*>& valueAttributes, std::string increasedValue, const std::vector<NativeStringAttribute*>& increasedValueAttributes, std::string decreasedValue, const std::vector<NativeStringAttribute*>& decreasedValueAttributes, std::string hint, const std::vector<NativeStringAttribute*>& hintAttributes, std::string tooltip, int textDirection, const tonic::Float64List& transform, const tonic::Int32List& childrenInTraversalOrder, const tonic::Int32List& childrenInHitTestOrder, const tonic::Int32List& customAccessibilityActions); void updateCustomAction(int id, std::string label, std::string hint, int overrideId); void build(Dart_Handle semantics_update_handle); private: explicit SemanticsUpdateBuilder(); SemanticsNodeUpdates nodes_; CustomAccessibilityActionUpdates actions_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_SEMANTICS_SEMANTICS_UPDATE_BUILDER_H_
engine/lib/ui/semantics/semantics_update_builder.h/0
{ "file_path": "engine/lib/ui/semantics/semantics_update_builder.h", "repo_id": "engine", "token_count": 1008 }
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 "flutter/benchmarking/benchmarking.h" #include "flutter/common/settings.h" #include "flutter/lib/ui/volatile_path_tracker.h" #include "flutter/lib/ui/window/platform_message_response_dart.h" #include "flutter/runtime/dart_vm_lifecycle.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/dart_isolate_runner.h" #include "flutter/testing/fixture_test.h" #include <future> namespace flutter { class Fixture : public testing::FixtureTest { void TestBody() override {}; }; static void BM_PlatformMessageResponseDartComplete(benchmark::State& state) { ThreadHost thread_host(ThreadHost::ThreadHostConfig( "test", ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi)); TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), thread_host.raster_thread->GetTaskRunner(), thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner()); Fixture fixture; auto settings = fixture.CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); auto isolate = testing::RunDartCodeInIsolate(vm_ref, settings, task_runners, "main", {}, testing::GetDefaultKernelFilePath(), {}); while (state.KeepRunning()) { state.PauseTiming(); bool successful = isolate->RunInIsolateScope([&]() -> bool { // Simulate a message of 3 MB std::vector<uint8_t> data(3 << 20, 0); std::unique_ptr<fml::Mapping> mapping = std::make_unique<fml::DataMapping>(data); Dart_Handle library = Dart_RootLibrary(); Dart_Handle closure = Dart_GetField(library, Dart_NewStringFromCString("messageCallback")); auto message = fml::MakeRefCounted<PlatformMessageResponseDart>( tonic::DartPersistentValue(isolate->get(), closure), thread_host.ui_thread->GetTaskRunner(), ""); message->Complete(std::move(mapping)); return true; }); FML_CHECK(successful); state.ResumeTiming(); // We skip timing everything above because the copy triggered by // message->Complete is a task posted on the UI thread. The following wait // for a UI task would let us know when that copy is done. std::promise<bool> completed; task_runners.GetUITaskRunner()->PostTask( [&completed] { completed.set_value(true); }); completed.get_future().wait(); } } static void BM_PathVolatilityTracker(benchmark::State& state) { ThreadHost thread_host(ThreadHost::ThreadHostConfig( "test", ThreadHost::Type::kPlatform | ThreadHost::Type::kRaster | ThreadHost::Type::kIo | ThreadHost::Type::kUi)); TaskRunners task_runners("test", thread_host.platform_thread->GetTaskRunner(), thread_host.raster_thread->GetTaskRunner(), thread_host.ui_thread->GetTaskRunner(), thread_host.io_thread->GetTaskRunner()); VolatilePathTracker tracker(task_runners.GetUITaskRunner(), true); while (state.KeepRunning()) { std::vector<std::shared_ptr<VolatilePathTracker::TrackedPath>> paths; constexpr int path_count = 1000; for (int i = 0; i < path_count; i++) { auto path = std::make_shared<VolatilePathTracker::TrackedPath>(); path->path = SkPath(); path->path.setIsVolatile(true); paths.push_back(std::move(path)); } fml::AutoResetWaitableEvent latch; task_runners.GetUITaskRunner()->PostTask([&]() { for (const auto& path : paths) { tracker.Track(path); } latch.Signal(); }); latch.Wait(); task_runners.GetUITaskRunner()->PostTask([&]() { tracker.OnFrame(); }); for (int i = 0; i < path_count - 10; ++i) { paths[i].reset(); } task_runners.GetUITaskRunner()->PostTask([&]() { tracker.OnFrame(); }); latch.Reset(); task_runners.GetUITaskRunner()->PostTask([&]() { latch.Signal(); }); latch.Wait(); } } BENCHMARK(BM_PlatformMessageResponseDartComplete) ->Unit(benchmark::kMicrosecond); BENCHMARK(BM_PathVolatilityTracker)->Unit(benchmark::kMillisecond); } // namespace flutter
engine/lib/ui/ui_benchmarks.cc/0
{ "file_path": "engine/lib/ui/ui_benchmarks.cc", "repo_id": "engine", "token_count": 1720 }
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. #ifndef FLUTTER_LIB_UI_WINDOW_PLATFORM_MESSAGE_H_ #define FLUTTER_LIB_UI_WINDOW_PLATFORM_MESSAGE_H_ #include <string> #include <vector> #include "flutter/fml/memory/ref_counted.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/lib/ui/window/platform_message_response.h" namespace flutter { class PlatformMessage { public: PlatformMessage(std::string channel, fml::MallocMapping data, fml::RefPtr<PlatformMessageResponse> response); PlatformMessage(std::string channel, fml::RefPtr<PlatformMessageResponse> response); ~PlatformMessage(); const std::string& channel() const { return channel_; } const fml::MallocMapping& data() const { return data_; } bool hasData() { return has_data_; } const fml::RefPtr<PlatformMessageResponse>& response() const { return response_; } fml::MallocMapping releaseData() { return std::move(data_); } private: std::string channel_; fml::MallocMapping data_; bool has_data_; fml::RefPtr<PlatformMessageResponse> response_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_WINDOW_PLATFORM_MESSAGE_H_
engine/lib/ui/window/platform_message.h/0
{ "file_path": "engine/lib/ui/window/platform_message.h", "repo_id": "engine", "token_count": 478 }
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/lib/ui/window/pointer_data.h" #include <cstring> #include "gtest/gtest.h" #include "pointer_data_packet.h" namespace flutter { namespace testing { void CreateSimpleSimulatedPointerData(PointerData& data, // NOLINT PointerData::Change change, int64_t device, double dx, double dy, int64_t buttons) { data.time_stamp = 0; data.change = change; data.kind = PointerData::DeviceKind::kTouch; data.signal_kind = PointerData::SignalKind::kNone; data.device = device; data.pointer_identifier = 0; data.physical_x = dx; data.physical_y = dy; data.physical_delta_x = 0.0; data.physical_delta_y = 0.0; data.buttons = buttons; data.obscured = 0; data.synthesized = 0; data.pressure = 0.0; data.pressure_min = 0.0; data.pressure_max = 0.0; data.distance = 0.0; data.distance_max = 0.0; data.size = 0.0; data.radius_major = 0.0; data.radius_minor = 0.0; data.radius_min = 0.0; data.radius_max = 0.0; data.orientation = 0.0; data.tilt = 0.0; data.platformData = 0; data.scroll_delta_x = 0.0; data.scroll_delta_y = 0.0; } TEST(PointerDataPacketTest, CanGetPointerData) { auto packet = std::make_unique<PointerDataPacket>(1); PointerData data; CreateSimpleSimulatedPointerData(data, PointerData::Change::kAdd, 1, 2.0, 3.0, 4); packet->SetPointerData(0, data); PointerData data_recovered = packet->GetPointerData(0); ASSERT_EQ(data_recovered.physical_x, 2.0); ASSERT_EQ(data_recovered.physical_y, 3.0); } TEST(PointerDataPacketTest, CanGetLength) { auto packet = std::make_unique<PointerDataPacket>(6); ASSERT_EQ(packet->GetLength(), (size_t)6); } } // namespace testing } // namespace flutter
engine/lib/ui/window/pointer_data_packet_unittests.cc/0
{ "file_path": "engine/lib/ui/window/pointer_data_packet_unittests.cc", "repo_id": "engine", "token_count": 939 }
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. import 'dart:async'; import 'dart:io' as io; import 'dart:typed_data'; import 'package:archive/archive.dart'; import 'package:archive/archive_io.dart'; import 'package:http/http.dart'; import 'package:path/path.dart' as path; import 'common.dart'; import 'environment.dart'; import 'exceptions.dart'; const String _chromeExecutableVar = 'CHROME_EXECUTABLE'; /// Returns the installation of Chrome, installing it if necessary. /// /// If [requestedVersion] is null, uses the version specified on the /// command-line. If not specified on the command-line, uses the version /// specified in the "browser_lock.yaml" file. /// /// If [requestedVersion] is not null, installs that version. The value /// may be "latest" (the latest available build of Chrome), "system" /// (manually installed Chrome on the current operating system), or an /// exact build nuber, such as 695653. Build numbers can be found here: /// /// https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Linux_x64/ Future<BrowserInstallation> getOrInstallChrome( String requestedVersion, { StringSink? infoLog, }) async { infoLog ??= io.stdout; // When running on LUCI, if we specify the "chrome_and_driver" dependency, // then the bot will download Chrome from CIPD and place it in a cache and // set the environment variable CHROME_EXECUTABLE. if (io.Platform.environment.containsKey(_chromeExecutableVar)) { infoLog.writeln('Using Chrome from $_chromeExecutableVar variable: ' '${io.Platform.environment[_chromeExecutableVar]}'); return BrowserInstallation( version: 'cipd', executable: io.Platform.environment[_chromeExecutableVar]!, ); } if (requestedVersion == 'system') { return BrowserInstallation( version: 'system', executable: await _findSystemChromeExecutable(), ); } ChromeInstaller? installer; try { installer = requestedVersion == 'latest' ? await ChromeInstaller.latest() : ChromeInstaller(version: requestedVersion); if (installer.isInstalled) { infoLog.writeln( 'Installation was skipped because Chrome version ${installer.version} is already installed.'); } else { infoLog.writeln('Installing Chrome version: ${installer.version}'); await installer.install(); final BrowserInstallation installation = installer.getInstallation()!; infoLog.writeln( 'Installations complete. To launch it run ${installation.executable}'); } return installer.getInstallation()!; } finally { installer?.close(); } } Future<String> _findSystemChromeExecutable() async { final io.ProcessResult which = await io.Process.run('which', <String>['google-chrome']); if (which.exitCode != 0) { throw BrowserInstallerException( 'Failed to locate system Chrome installation.'); } return which.stdout as String; } /// Manages the installation of a particular [version] of Chrome. class ChromeInstaller { factory ChromeInstaller({ required String version, }) { if (version == 'system') { throw BrowserInstallerException( 'Cannot install system version of Chrome. System Chrome must be installed manually.'); } if (version == 'latest') { throw BrowserInstallerException( 'Expected a concrete Chromer version, but got $version. Maybe use ChromeInstaller.latest()?'); } final io.Directory chromeInstallationDir = io.Directory( path.join(environment.webUiDartToolDir.path, 'chrome'), ); final io.Directory versionDir = io.Directory( path.join(chromeInstallationDir.path, version), ); return ChromeInstaller._( version: version, chromeInstallationDir: chromeInstallationDir, versionDir: versionDir, ); } ChromeInstaller._({ required this.version, required this.chromeInstallationDir, required this.versionDir, }); static Future<ChromeInstaller> latest() async { final String latestVersion = await fetchLatestChromeVersion(); return ChromeInstaller(version: latestVersion); } /// Chrome version managed by this installer. final String version; /// HTTP client used to download Chrome. final Client client = Client(); /// Root directory that contains Chrome versions. final io.Directory chromeInstallationDir; /// Installation directory for Chrome of the requested [version]. final io.Directory versionDir; bool get isInstalled { return versionDir.existsSync(); } BrowserInstallation? getInstallation() { if (!isInstalled) { return null; } return BrowserInstallation( version: version, executable: PlatformBinding.instance.getChromeExecutablePath(versionDir), ); } Future<void> install() async { if (isLuci) { throw StateError( 'Rejecting attempt to install Chromium on LUCI. LUCI is expected to ' 'provide Chromium as a CIPD dependency managed using .ci.yaml.', ); } if (versionDir.existsSync()) { versionDir.deleteSync(recursive: true); } versionDir.createSync(recursive: true); final String url = PlatformBinding.instance.getChromeDownloadUrl(version); print('Downloading Chrome from $url'); final StreamedResponse download = await client.send(Request( 'GET', Uri.parse(url), )); final io.File downloadedFile = io.File(path.join(versionDir.path, 'chrome.zip')); await download.stream.pipe(downloadedFile.openWrite()); /// Windows LUCI bots does not have a `unzip`. Instead we are /// using `archive` pub package. /// /// We didn't use `archive` on Mac/Linux since the new files have /// permission issues. For now we are not able change file permissions /// from dart. /// See: https://github.com/dart-lang/sdk/issues/15078. if (io.Platform.isWindows) { final Stopwatch stopwatch = Stopwatch()..start(); // Read the Zip file from disk. final Uint8List bytes = downloadedFile.readAsBytesSync(); final Archive archive = ZipDecoder().decodeBytes(bytes); // Extract the contents of the Zip archive to disk. for (final ArchiveFile file in archive) { final String filename = file.name; if (file.isFile) { final List<int> data = file.content as List<int>; io.File(path.joinAll(<String>[ versionDir.path, // Remove the "chrome-win/" path prefix, which is the Windows // convention for Chromium directory structure. ...path.split(filename).skip(1), ])) ..createSync(recursive: true) ..writeAsBytesSync(data); } } stopwatch.stop(); print( 'The unzip took ${stopwatch.elapsedMilliseconds ~/ 1000} seconds.' ); } else { // We have to unzip into a temporary directory and then copy the files // out because our tests expect the files to be direct children of the // version directory. However, the zip file contains a top-level directory // named e.g. 'chrome-linux'. We need to copy the files out of that // directory and into the version directory. final io.Directory tmpDir = await io.Directory.systemTemp.createTemp(); final io.Directory unzipDir = tmpDir; final io.ProcessResult unzipResult = await io.Process.run('unzip', <String>[ downloadedFile.path, '-d', unzipDir.path, ]); if (unzipResult.exitCode != 0) { throw BrowserInstallerException( 'Failed to unzip the downloaded Chrome archive ${downloadedFile.path}.\n' 'With the version path ${versionDir.path}\n' 'The unzip process exited with code ${unzipResult.exitCode}.'); } final io.Directory topLevelDir = await tmpDir.list().single as io.Directory; await for (final io.FileSystemEntity entity in topLevelDir.list()) { await entity .rename(path.join(versionDir.path, path.basename(entity.path))); } await tmpDir.delete(recursive: true); } downloadedFile.deleteSync(); } void close() { client.close(); } } /// Fetches the latest available Chrome build version. Future<String> fetchLatestChromeVersion() async { final Client client = Client(); try { final Response response = await client.get(Uri.parse( 'https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2FLAST_CHANGE?alt=media')); if (response.statusCode != 200) { throw BrowserInstallerException( 'Failed to fetch latest Chrome version. Server returned status code ${response.statusCode}'); } return response.body; } finally { client.close(); } }
engine/lib/web_ui/dev/chrome_installer.dart/0
{ "file_path": "engine/lib/web_ui/dev/chrome_installer.dart", "repo_id": "engine", "token_count": 3063 }
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. import 'dart:io' as io; import 'package:path/path.dart' as path; import 'package:yaml/yaml.dart'; import 'environment.dart'; /// Returns the browser configuration based on the `package_lock.yaml` file in /// the current engine workspace. final PackageLock packageLock = PackageLock(); /// Provides access to the contents of the `package_lock.yaml` file. class PackageLock { factory PackageLock() { final io.File lockFile = io.File( path.join(environment.webUiRootDir.path, 'dev', 'package_lock.yaml'), ); final YamlMap yaml = loadYaml(lockFile.readAsStringSync()) as YamlMap; return PackageLock._fromYaml(yaml); } PackageLock._fromYaml(YamlMap yaml) : chromeLock = ChromeLock._fromYaml(yaml['chrome'] as YamlMap), firefoxLock = FirefoxLock._fromYaml(yaml['firefox'] as YamlMap), edgeLock = EdgeLock._fromYaml(yaml['edge'] as YamlMap), esbuildLock = EsbuildLock._fromYaml(yaml['esbuild'] as YamlMap); final ChromeLock chromeLock; final FirefoxLock firefoxLock; final EdgeLock edgeLock; final EsbuildLock esbuildLock; } class ChromeLock { ChromeLock._fromYaml(YamlMap yaml) : version = yaml['version'] as String; /// The full version of Chromium represented by this lock. E.g: '119.0.6045.9' final String version; } class FirefoxLock { FirefoxLock._fromYaml(YamlMap yaml) : version = yaml['version'] as String; final String version; } class EdgeLock { EdgeLock._fromYaml(YamlMap yaml) : launcherVersion = yaml['launcher_version'] as String; final String launcherVersion; } class EsbuildLock { EsbuildLock._fromYaml(YamlMap yaml) : version = yaml['version'] as String; final String version; }
engine/lib/web_ui/dev/package_lock.dart/0
{ "file_path": "engine/lib/web_ui/dev/package_lock.dart", "repo_id": "engine", "token_count": 625 }
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. // See https://github.com/flutter/engine/blob/main/lib/ui/geometry.dart for // documentation of APIs. part of ui; double toDegrees(double radians) { return radians * 180 / math.pi; } abstract class OffsetBase { const OffsetBase(this._dx, this._dy); final double _dx; final double _dy; bool get isInfinite => _dx >= double.infinity || _dy >= double.infinity; bool get isFinite => _dx.isFinite && _dy.isFinite; bool operator <(OffsetBase other) => _dx < other._dx && _dy < other._dy; bool operator <=(OffsetBase other) => _dx <= other._dx && _dy <= other._dy; bool operator >(OffsetBase other) => _dx > other._dx && _dy > other._dy; bool operator >=(OffsetBase other) => _dx >= other._dx && _dy >= other._dy; @override bool operator ==(Object other) { return other is OffsetBase && other._dx == _dx && other._dy == _dy; } @override int get hashCode => Object.hash(_dx, _dy); @override String toString() => 'OffsetBase(${_dx.toStringAsFixed(1)}, ${_dy.toStringAsFixed(1)})'; } class Offset extends OffsetBase { const Offset(super.dx, super.dy); factory Offset.fromDirection(double direction, [ double distance = 1.0 ]) { return Offset(distance * math.cos(direction), distance * math.sin(direction)); } double get dx => _dx; double get dy => _dy; double get distance => math.sqrt(dx * dx + dy * dy); double get distanceSquared => dx * dx + dy * dy; double get direction => math.atan2(dy, dx); static const Offset zero = Offset(0.0, 0.0); // This is included for completeness, because [Size.infinite] exists. static const Offset infinite = Offset(double.infinity, double.infinity); Offset scale(double scaleX, double scaleY) => Offset(dx * scaleX, dy * scaleY); Offset translate(double translateX, double translateY) => Offset(dx + translateX, dy + translateY); Offset operator -() => Offset(-dx, -dy); Offset operator -(Offset other) => Offset(dx - other.dx, dy - other.dy); Offset operator +(Offset other) => Offset(dx + other.dx, dy + other.dy); Offset operator *(double operand) => Offset(dx * operand, dy * operand); Offset operator /(double operand) => Offset(dx / operand, dy / operand); Offset operator ~/(double operand) => Offset((dx ~/ operand).toDouble(), (dy ~/ operand).toDouble()); Offset operator %(double operand) => Offset(dx % operand, dy % operand); Rect operator &(Size other) => Rect.fromLTWH(dx, dy, other.width, other.height); static Offset? lerp(Offset? a, Offset? b, double t) { if (b == null) { if (a == null) { return null; } else { return a * (1.0 - t); } } else { if (a == null) { return b * t; } else { return Offset(_lerpDouble(a.dx, b.dx, t), _lerpDouble(a.dy, b.dy, t)); } } } @override bool operator ==(Object other) { return other is Offset && other.dx == dx && other.dy == dy; } @override int get hashCode => Object.hash(dx, dy); @override String toString() => 'Offset(${dx.toStringAsFixed(1)}, ${dy.toStringAsFixed(1)})'; } class Size extends OffsetBase { const Size(super.width, super.height); // Used by the rendering library's _DebugSize hack. Size.copy(Size source) : super(source.width, source.height); const Size.square(double dimension) : super(dimension, dimension); // ignore: use_super_parameters const Size.fromWidth(double width) : super(width, double.infinity); const Size.fromHeight(double height) : super(double.infinity, height); const Size.fromRadius(double radius) : super(radius * 2.0, radius * 2.0); double get width => _dx; double get height => _dy; double get aspectRatio { if (height != 0.0) { return width / height; } if (width > 0.0) { return double.infinity; } if (width < 0.0) { return double.negativeInfinity; } return 0.0; } static const Size zero = Size(0.0, 0.0); static const Size infinite = Size(double.infinity, double.infinity); bool get isEmpty => width <= 0.0 || height <= 0.0; OffsetBase operator -(OffsetBase other) { if (other is Size) { return Offset(width - other.width, height - other.height); } if (other is Offset) { return Size(width - other.dx, height - other.dy); } throw ArgumentError(other); } Size operator +(Offset other) => Size(width + other.dx, height + other.dy); Size operator *(double operand) => Size(width * operand, height * operand); Size operator /(double operand) => Size(width / operand, height / operand); Size operator ~/(double operand) => Size((width ~/ operand).toDouble(), (height ~/ operand).toDouble()); Size operator %(double operand) => Size(width % operand, height % operand); double get shortestSide => math.min(width.abs(), height.abs()); double get longestSide => math.max(width.abs(), height.abs()); // Convenience methods that do the equivalent of calling the similarly named // methods on a Rect constructed from the given origin and this size. Offset topLeft(Offset origin) => origin; Offset topCenter(Offset origin) => Offset(origin.dx + width / 2.0, origin.dy); Offset topRight(Offset origin) => Offset(origin.dx + width, origin.dy); Offset centerLeft(Offset origin) => Offset(origin.dx, origin.dy + height / 2.0); Offset center(Offset origin) => Offset(origin.dx + width / 2.0, origin.dy + height / 2.0); Offset centerRight(Offset origin) => Offset(origin.dx + width, origin.dy + height / 2.0); Offset bottomLeft(Offset origin) => Offset(origin.dx, origin.dy + height); Offset bottomCenter(Offset origin) => Offset(origin.dx + width / 2.0, origin.dy + height); Offset bottomRight(Offset origin) => Offset(origin.dx + width, origin.dy + height); bool contains(Offset offset) { return offset.dx >= 0.0 && offset.dx < width && offset.dy >= 0.0 && offset.dy < height; } Size get flipped => Size(height, width); static Size? lerp(Size? a, Size? b, double t) { if (b == null) { if (a == null) { return null; } else { return a * (1.0 - t); } } else { if (a == null) { return b * t; } else { return Size(_lerpDouble(a.width, b.width, t), _lerpDouble(a.height, b.height, t)); } } } // We don't compare the runtimeType because of _DebugSize in the framework. @override bool operator ==(Object other) { return other is Size && other._dx == _dx && other._dy == _dy; } @override int get hashCode => Object.hash(_dx, _dy); @override String toString() => 'Size(${width.toStringAsFixed(1)}, ${height.toStringAsFixed(1)})'; } class Rect { const Rect.fromLTRB(this.left, this.top, this.right, this.bottom); const Rect.fromLTWH(double left, double top, double width, double height) : this.fromLTRB(left, top, left + width, top + height); Rect.fromCircle({ required Offset center, required double radius }) : this.fromCenter( center: center, width: radius * 2, height: radius * 2, ); Rect.fromCenter({ required Offset center, required double width, required double height }) : this.fromLTRB( center.dx - width / 2, center.dy - height / 2, center.dx + width / 2, center.dy + height / 2, ); Rect.fromPoints(Offset a, Offset b) : this.fromLTRB( math.min(a.dx, b.dx), math.min(a.dy, b.dy), math.max(a.dx, b.dx), math.max(a.dy, b.dy), ); final double left; final double top; final double right; final double bottom; double get width => right - left; double get height => bottom - top; Size get size => Size(width, height); bool get hasNaN => left.isNaN || top.isNaN || right.isNaN || bottom.isNaN; static const Rect zero = Rect.fromLTRB(0.0, 0.0, 0.0, 0.0); static const double _giantScalar = 1.0E+9; // matches kGiantRect from layer.h static const Rect largest = Rect.fromLTRB(-_giantScalar, -_giantScalar, _giantScalar, _giantScalar); // included for consistency with Offset and Size bool get isInfinite { return left >= double.infinity || top >= double.infinity || right >= double.infinity || bottom >= double.infinity; } bool get isFinite => left.isFinite && top.isFinite && right.isFinite && bottom.isFinite; bool get isEmpty => left >= right || top >= bottom; Rect shift(Offset offset) { return Rect.fromLTRB(left + offset.dx, top + offset.dy, right + offset.dx, bottom + offset.dy); } Rect translate(double translateX, double translateY) { return Rect.fromLTRB(left + translateX, top + translateY, right + translateX, bottom + translateY); } Rect inflate(double delta) { return Rect.fromLTRB(left - delta, top - delta, right + delta, bottom + delta); } Rect deflate(double delta) => inflate(-delta); Rect intersect(Rect other) { return Rect.fromLTRB( math.max(left, other.left), math.max(top, other.top), math.min(right, other.right), math.min(bottom, other.bottom), ); } Rect expandToInclude(Rect other) { return Rect.fromLTRB( math.min(left, other.left), math.min(top, other.top), math.max(right, other.right), math.max(bottom, other.bottom), ); } bool overlaps(Rect other) { if (right <= other.left || other.right <= left) { return false; } if (bottom <= other.top || other.bottom <= top) { return false; } return true; } double get shortestSide => math.min(width.abs(), height.abs()); double get longestSide => math.max(width.abs(), height.abs()); Offset get topLeft => Offset(left, top); Offset get topCenter => Offset(left + width / 2.0, top); Offset get topRight => Offset(right, top); Offset get centerLeft => Offset(left, top + height / 2.0); Offset get center => Offset(left + width / 2.0, top + height / 2.0); Offset get centerRight => Offset(right, top + height / 2.0); Offset get bottomLeft => Offset(left, bottom); Offset get bottomCenter => Offset(left + width / 2.0, bottom); Offset get bottomRight => Offset(right, bottom); bool contains(Offset offset) { return offset.dx >= left && offset.dx < right && offset.dy >= top && offset.dy < bottom; } static Rect? lerp(Rect? a, Rect? b, double t) { if (b == null) { if (a == null) { return null; } else { final double k = 1.0 - t; return Rect.fromLTRB(a.left * k, a.top * k, a.right * k, a.bottom * k); } } else { if (a == null) { return Rect.fromLTRB(b.left * t, b.top * t, b.right * t, b.bottom * t); } else { return Rect.fromLTRB( _lerpDouble(a.left, b.left, t), _lerpDouble(a.top, b.top, t), _lerpDouble(a.right, b.right, t), _lerpDouble(a.bottom, b.bottom, t), ); } } } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (runtimeType != other.runtimeType) { return false; } return other is Rect && other.left == left && other.top == top && other.right == right && other.bottom == bottom; } @override int get hashCode => Object.hash(left, top, right, bottom); @override String toString() => 'Rect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})'; } class Radius { const Radius.circular(double radius) : this.elliptical(radius, radius); const Radius.elliptical(this.x, this.y); final double x; final double y; static const Radius zero = Radius.circular(0.0); Radius clamp({Radius? minimum, Radius? maximum}) { minimum ??= const Radius.circular(-double.infinity); maximum ??= const Radius.circular(double.infinity); return Radius.elliptical( clampDouble(x, minimum.x, maximum.x), clampDouble(y, minimum.y, maximum.y), ); } Radius clampValues({ double? minimumX, double? minimumY, double? maximumX, double? maximumY, }) { return Radius.elliptical( clampDouble(x, minimumX ?? -double.infinity, maximumX ?? double.infinity), clampDouble(y, minimumY ?? -double.infinity, maximumY ?? double.infinity), ); } Radius operator -() => Radius.elliptical(-x, -y); Radius operator -(Radius other) => Radius.elliptical(x - other.x, y - other.y); Radius operator +(Radius other) => Radius.elliptical(x + other.x, y + other.y); Radius operator *(double operand) => Radius.elliptical(x * operand, y * operand); Radius operator /(double operand) => Radius.elliptical(x / operand, y / operand); Radius operator ~/(double operand) => Radius.elliptical((x ~/ operand).toDouble(), (y ~/ operand).toDouble()); Radius operator %(double operand) => Radius.elliptical(x % operand, y % operand); static Radius? lerp(Radius? a, Radius? b, double t) { if (b == null) { if (a == null) { return null; } else { final double k = 1.0 - t; return Radius.elliptical(a.x * k, a.y * k); } } else { if (a == null) { return Radius.elliptical(b.x * t, b.y * t); } else { return Radius.elliptical( _lerpDouble(a.x, b.x, t), _lerpDouble(a.y, b.y, t), ); } } } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (runtimeType != other.runtimeType) { return false; } return other is Radius && other.x == x && other.y == y; } @override int get hashCode => Object.hash(x, y); @override String toString() { return x == y ? 'Radius.circular(${x.toStringAsFixed(1)})' : 'Radius.elliptical(${x.toStringAsFixed(1)}, ' '${y.toStringAsFixed(1)})'; } } class RRect { const RRect.fromLTRBXY( double left, double top, double right, double bottom, double radiusX, double radiusY, ) : this._raw( top: top, left: left, right: right, bottom: bottom, tlRadiusX: radiusX, tlRadiusY: radiusY, trRadiusX: radiusX, trRadiusY: radiusY, blRadiusX: radiusX, blRadiusY: radiusY, brRadiusX: radiusX, brRadiusY: radiusY, uniformRadii: radiusX == radiusY, ); RRect.fromLTRBR( double left, double top, double right, double bottom, Radius radius, ) : this._raw( top: top, left: left, right: right, bottom: bottom, tlRadiusX: radius.x, tlRadiusY: radius.y, trRadiusX: radius.x, trRadiusY: radius.y, blRadiusX: radius.x, blRadiusY: radius.y, brRadiusX: radius.x, brRadiusY: radius.y, uniformRadii: radius.x == radius.y, ); RRect.fromRectXY(Rect rect, double radiusX, double radiusY) : this._raw( top: rect.top, left: rect.left, right: rect.right, bottom: rect.bottom, tlRadiusX: radiusX, tlRadiusY: radiusY, trRadiusX: radiusX, trRadiusY: radiusY, blRadiusX: radiusX, blRadiusY: radiusY, brRadiusX: radiusX, brRadiusY: radiusY, uniformRadii: radiusX == radiusY, ); RRect.fromRectAndRadius(Rect rect, Radius radius) : this._raw( top: rect.top, left: rect.left, right: rect.right, bottom: rect.bottom, tlRadiusX: radius.x, tlRadiusY: radius.y, trRadiusX: radius.x, trRadiusY: radius.y, blRadiusX: radius.x, blRadiusY: radius.y, brRadiusX: radius.x, brRadiusY: radius.y, uniformRadii: radius.x == radius.y, ); RRect.fromLTRBAndCorners( double left, double top, double right, double bottom, { Radius topLeft = Radius.zero, Radius topRight = Radius.zero, Radius bottomRight = Radius.zero, Radius bottomLeft = Radius.zero, }) : this._raw( top: top, left: left, right: right, bottom: bottom, tlRadiusX: topLeft.x, tlRadiusY: topLeft.y, trRadiusX: topRight.x, trRadiusY: topRight.y, blRadiusX: bottomLeft.x, blRadiusY: bottomLeft.y, brRadiusX: bottomRight.x, brRadiusY: bottomRight.y, uniformRadii: topLeft.x == topLeft.y && topLeft.x == topRight.x && topLeft.x == topRight.y && topLeft.x == bottomLeft.x && topLeft.x == bottomLeft.y && topLeft.x == bottomRight.x && topLeft.x == bottomRight.y, ); RRect.fromRectAndCorners( Rect rect, { Radius topLeft = Radius.zero, Radius topRight = Radius.zero, Radius bottomRight = Radius.zero, Radius bottomLeft = Radius.zero, }) : this._raw( top: rect.top, left: rect.left, right: rect.right, bottom: rect.bottom, tlRadiusX: topLeft.x, tlRadiusY: topLeft.y, trRadiusX: topRight.x, trRadiusY: topRight.y, blRadiusX: bottomLeft.x, blRadiusY: bottomLeft.y, brRadiusX: bottomRight.x, brRadiusY: bottomRight.y, uniformRadii: topLeft.x == topLeft.y && topLeft.x == topRight.x && topLeft.x == topRight.y && topLeft.x == bottomLeft.x && topLeft.x == bottomLeft.y && topLeft.x == bottomRight.x && topLeft.x == bottomRight.y, ); const RRect._raw({ this.left = 0.0, this.top = 0.0, this.right = 0.0, this.bottom = 0.0, this.tlRadiusX = 0.0, this.tlRadiusY = 0.0, this.trRadiusX = 0.0, this.trRadiusY = 0.0, this.brRadiusX = 0.0, this.brRadiusY = 0.0, this.blRadiusX = 0.0, this.blRadiusY = 0.0, bool uniformRadii = false, }) : assert(tlRadiusX >= 0), assert(tlRadiusY >= 0), assert(trRadiusX >= 0), assert(trRadiusY >= 0), assert(brRadiusX >= 0), assert(brRadiusY >= 0), assert(blRadiusX >= 0), assert(blRadiusY >= 0), webOnlyUniformRadii = uniformRadii; final double left; final double top; final double right; final double bottom; final double tlRadiusX; final double tlRadiusY; Radius get tlRadius => Radius.elliptical(tlRadiusX, tlRadiusY); final double trRadiusX; final double trRadiusY; Radius get trRadius => Radius.elliptical(trRadiusX, trRadiusY); final double brRadiusX; final double brRadiusY; Radius get brRadius => Radius.elliptical(brRadiusX, brRadiusY); final double blRadiusX; final double blRadiusY; // webOnly final bool webOnlyUniformRadii; Radius get blRadius => Radius.elliptical(blRadiusX, blRadiusY); static const RRect zero = RRect._raw(); RRect shift(Offset offset) { return RRect._raw( left: left + offset.dx, top: top + offset.dy, right: right + offset.dx, bottom: bottom + offset.dy, tlRadiusX: tlRadiusX, tlRadiusY: tlRadiusY, trRadiusX: trRadiusX, trRadiusY: trRadiusY, blRadiusX: blRadiusX, blRadiusY: blRadiusY, brRadiusX: brRadiusX, brRadiusY: brRadiusY, ); } RRect inflate(double delta) { return RRect._raw( left: left - delta, top: top - delta, right: right + delta, bottom: bottom + delta, tlRadiusX: math.max(0, tlRadiusX + delta), tlRadiusY: math.max(0, tlRadiusY + delta), trRadiusX: math.max(0, trRadiusX + delta), trRadiusY: math.max(0, trRadiusY + delta), blRadiusX: math.max(0, blRadiusX + delta), blRadiusY: math.max(0, blRadiusY + delta), brRadiusX: math.max(0, brRadiusX + delta), brRadiusY: math.max(0, brRadiusY + delta), ); } RRect deflate(double delta) => inflate(-delta); double get width => right - left; double get height => bottom - top; Rect get outerRect => Rect.fromLTRB(left, top, right, bottom); Rect get safeInnerRect { const double kInsetFactor = 0.29289321881; // 1-cos(pi/4) final double leftRadius = math.max(blRadiusX, tlRadiusX); final double topRadius = math.max(tlRadiusY, trRadiusY); final double rightRadius = math.max(trRadiusX, brRadiusX); final double bottomRadius = math.max(brRadiusY, blRadiusY); return Rect.fromLTRB( left + leftRadius * kInsetFactor, top + topRadius * kInsetFactor, right - rightRadius * kInsetFactor, bottom - bottomRadius * kInsetFactor ); } Rect get middleRect { final double leftRadius = math.max(blRadiusX, tlRadiusX); final double topRadius = math.max(tlRadiusY, trRadiusY); final double rightRadius = math.max(trRadiusX, brRadiusX); final double bottomRadius = math.max(brRadiusY, blRadiusY); return Rect.fromLTRB( left + leftRadius, top + topRadius, right - rightRadius, bottom - bottomRadius ); } Rect get wideMiddleRect { final double topRadius = math.max(tlRadiusY, trRadiusY); final double bottomRadius = math.max(brRadiusY, blRadiusY); return Rect.fromLTRB( left, top + topRadius, right, bottom - bottomRadius ); } Rect get tallMiddleRect { final double leftRadius = math.max(blRadiusX, tlRadiusX); final double rightRadius = math.max(trRadiusX, brRadiusX); return Rect.fromLTRB( left + leftRadius, top, right - rightRadius, bottom ); } bool get isEmpty => left >= right || top >= bottom; bool get isFinite => left.isFinite && top.isFinite && right.isFinite && bottom.isFinite; bool get isRect { return (tlRadiusX == 0.0 || tlRadiusY == 0.0) && (trRadiusX == 0.0 || trRadiusY == 0.0) && (blRadiusX == 0.0 || blRadiusY == 0.0) && (brRadiusX == 0.0 || brRadiusY == 0.0); } bool get isStadium { return tlRadius == trRadius && trRadius == brRadius && brRadius == blRadius && (width <= 2.0 * tlRadiusX || height <= 2.0 * tlRadiusY); } bool get isEllipse { return tlRadius == trRadius && trRadius == brRadius && brRadius == blRadius && width <= 2.0 * tlRadiusX && height <= 2.0 * tlRadiusY; } bool get isCircle => width == height && isEllipse; double get shortestSide => math.min(width.abs(), height.abs()); double get longestSide => math.max(width.abs(), height.abs()); bool get hasNaN => left.isNaN || top.isNaN || right.isNaN || bottom.isNaN || trRadiusX.isNaN || trRadiusY.isNaN || tlRadiusX.isNaN || tlRadiusY.isNaN || brRadiusX.isNaN || brRadiusY.isNaN || blRadiusX.isNaN || blRadiusY.isNaN; Offset get center => Offset(left + width / 2.0, top + height / 2.0); // Returns the minimum between min and scale to which radius1 and radius2 // should be scaled with in order not to exceed the limit. double _getMin(double min, double radius1, double radius2, double limit) { final double sum = radius1 + radius2; if (sum > limit && sum != 0.0) { return math.min(min, limit / sum); } return min; } RRect scaleRadii() { double scale = 1.0; final double absWidth = width.abs(); final double absHeight = height.abs(); scale = _getMin(scale, blRadiusY, tlRadiusY, absHeight); scale = _getMin(scale, tlRadiusX, trRadiusX, absWidth); scale = _getMin(scale, trRadiusY, brRadiusY, absHeight); scale = _getMin(scale, brRadiusX, blRadiusX, absWidth); if (scale < 1.0) { return RRect._raw( top: top, left: left, right: right, bottom: bottom, tlRadiusX: tlRadiusX * scale, tlRadiusY: tlRadiusY * scale, trRadiusX: trRadiusX * scale, trRadiusY: trRadiusY * scale, blRadiusX: blRadiusX * scale, blRadiusY: blRadiusY * scale, brRadiusX: brRadiusX * scale, brRadiusY: brRadiusY * scale, ); } return RRect._raw( top: top, left: left, right: right, bottom: bottom, tlRadiusX: tlRadiusX, tlRadiusY: tlRadiusY, trRadiusX: trRadiusX, trRadiusY: trRadiusY, blRadiusX: blRadiusX, blRadiusY: blRadiusY, brRadiusX: brRadiusX, brRadiusY: brRadiusY, ); } bool contains(Offset point) { if (point.dx < left || point.dx >= right || point.dy < top || point.dy >= bottom) { return false; } // outside bounding box final RRect scaled = scaleRadii(); double x; double y; double radiusX; double radiusY; // check whether point is in one of the rounded corner areas // x, y -> translate to ellipse center if (point.dx < left + scaled.tlRadiusX && point.dy < top + scaled.tlRadiusY) { x = point.dx - left - scaled.tlRadiusX; y = point.dy - top - scaled.tlRadiusY; radiusX = scaled.tlRadiusX; radiusY = scaled.tlRadiusY; } else if (point.dx > right - scaled.trRadiusX && point.dy < top + scaled.trRadiusY) { x = point.dx - right + scaled.trRadiusX; y = point.dy - top - scaled.trRadiusY; radiusX = scaled.trRadiusX; radiusY = scaled.trRadiusY; } else if (point.dx > right - scaled.brRadiusX && point.dy > bottom - scaled.brRadiusY) { x = point.dx - right + scaled.brRadiusX; y = point.dy - bottom + scaled.brRadiusY; radiusX = scaled.brRadiusX; radiusY = scaled.brRadiusY; } else if (point.dx < left + scaled.blRadiusX && point.dy > bottom - scaled.blRadiusY) { x = point.dx - left - scaled.blRadiusX; y = point.dy - bottom + scaled.blRadiusY; radiusX = scaled.blRadiusX; radiusY = scaled.blRadiusY; } else { return true; // inside and not within the rounded corner area } x = x / radiusX; y = y / radiusY; // check if the point is outside the unit circle if (x * x + y * y > 1.0) { return false; } return true; } static RRect? lerp(RRect? a, RRect? b, double t) { if (b == null) { if (a == null) { return null; } else { final double k = 1.0 - t; return RRect._raw( left: a.left * k, top: a.top * k, right: a.right * k, bottom: a.bottom * k, tlRadiusX: math.max(0, a.tlRadiusX * k), tlRadiusY: math.max(0, a.tlRadiusY * k), trRadiusX: math.max(0, a.trRadiusX * k), trRadiusY: math.max(0, a.trRadiusY * k), brRadiusX: math.max(0, a.brRadiusX * k), brRadiusY: math.max(0, a.brRadiusY * k), blRadiusX: math.max(0, a.blRadiusX * k), blRadiusY: math.max(0, a.blRadiusY * k), ); } } else { if (a == null) { return RRect._raw( left: b.left * t, top: b.top * t, right: b.right * t, bottom: b.bottom * t, tlRadiusX: math.max(0, b.tlRadiusX * t), tlRadiusY: math.max(0, b.tlRadiusY * t), trRadiusX: math.max(0, b.trRadiusX * t), trRadiusY: math.max(0, b.trRadiusY * t), brRadiusX: math.max(0, b.brRadiusX * t), brRadiusY: math.max(0, b.brRadiusY * t), blRadiusX: math.max(0, b.blRadiusX * t), blRadiusY: math.max(0, b.blRadiusY * t), ); } else { return RRect._raw( left: _lerpDouble(a.left, b.left, t), top: _lerpDouble(a.top, b.top, t), right: _lerpDouble(a.right, b.right, t), bottom: _lerpDouble(a.bottom, b.bottom, t), tlRadiusX: math.max(0, _lerpDouble(a.tlRadiusX, b.tlRadiusX, t)), tlRadiusY: math.max(0, _lerpDouble(a.tlRadiusY, b.tlRadiusY, t)), trRadiusX: math.max(0, _lerpDouble(a.trRadiusX, b.trRadiusX, t)), trRadiusY: math.max(0, _lerpDouble(a.trRadiusY, b.trRadiusY, t)), brRadiusX: math.max(0, _lerpDouble(a.brRadiusX, b.brRadiusX, t)), brRadiusY: math.max(0, _lerpDouble(a.brRadiusY, b.brRadiusY, t)), blRadiusX: math.max(0, _lerpDouble(a.blRadiusX, b.blRadiusX, t)), blRadiusY: math.max(0, _lerpDouble(a.blRadiusY, b.blRadiusY, t)), ); } } } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (runtimeType != other.runtimeType) { return false; } return other is RRect && other.left == left && other.top == top && other.right == right && other.bottom == bottom && other.tlRadiusX == tlRadiusX && other.tlRadiusY == tlRadiusY && other.trRadiusX == trRadiusX && other.trRadiusY == trRadiusY && other.blRadiusX == blRadiusX && other.blRadiusY == blRadiusY && other.brRadiusX == brRadiusX && other.brRadiusY == brRadiusY; } @override int get hashCode => Object.hash(left, top, right, bottom, tlRadiusX, tlRadiusY, trRadiusX, trRadiusY, blRadiusX, blRadiusY, brRadiusX, brRadiusY); @override String toString() { final String rect = '${left.toStringAsFixed(1)}, ' '${top.toStringAsFixed(1)}, ' '${right.toStringAsFixed(1)}, ' '${bottom.toStringAsFixed(1)}'; if (tlRadius == trRadius && trRadius == brRadius && brRadius == blRadius) { if (tlRadius.x == tlRadius.y) { return 'RRect.fromLTRBR($rect, ${tlRadius.x.toStringAsFixed(1)})'; } return 'RRect.fromLTRBXY($rect, ${tlRadius.x.toStringAsFixed(1)}, ${tlRadius.y.toStringAsFixed(1)})'; } return 'RRect.fromLTRBAndCorners(' '$rect, ' 'topLeft: $tlRadius, ' 'topRight: $trRadius, ' 'bottomRight: $brRadius, ' 'bottomLeft: $blRadius' ')'; } } // Modeled after Skia's SkRSXform. class RSTransform { RSTransform(double scos, double ssin, double tx, double ty) { _value ..[0] = scos ..[1] = ssin ..[2] = tx ..[3] = ty; } factory RSTransform.fromComponents({ required double rotation, required double scale, required double anchorX, required double anchorY, required double translateX, required double translateY, }) { final double scos = math.cos(rotation) * scale; final double ssin = math.sin(rotation) * scale; final double tx = translateX + -scos * anchorX + ssin * anchorY; final double ty = translateY + -ssin * anchorX - scos * anchorY; return RSTransform(scos, ssin, tx, ty); } final Float32List _value = Float32List(4); double get scos => _value[0]; double get ssin => _value[1]; double get tx => _value[2]; double get ty => _value[3]; }
engine/lib/web_ui/lib/geometry.dart/0
{ "file_path": "engine/lib/web_ui/lib/geometry.dart", "repo_id": "engine", "token_count": 13615 }
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. import 'configuration.dart'; import 'js_interop/js_app.dart'; import 'js_interop/js_loader.dart'; import 'platform_dispatcher.dart'; import 'view_embedder/flutter_view_manager.dart'; /// The type of a function that initializes an engine (in Dart). typedef InitEngineFn = Future<void> Function([JsFlutterConfiguration? params]); /// A class that controls the coarse lifecycle of a Flutter app. class AppBootstrap { /// Construct an AppBootstrap. AppBootstrap({required InitEngineFn initializeEngine, required Function runApp}) : _initializeEngine = initializeEngine, _runApp = runApp; // A function to initialize the engine. final InitEngineFn _initializeEngine; // A function to run the app. // // TODO(dit): Be more strict with the typedef of this function, so we can add // typed params to the function. (See InitEngineFn). final Function _runApp; /// Immediately bootstraps the app. /// /// This calls `initEngine` and `runApp` in succession. Future<void> autoStart() async { await _initializeEngine(); await _runApp(); } /// Creates an engine initializer that runs our encapsulated initEngine function. FlutterEngineInitializer prepareEngineInitializer() { return FlutterEngineInitializer( // This is a convenience method that lets the programmer call "autoStart" // from JavaScript immediately after the main.dart.js has loaded. // Returns a promise that resolves to the Flutter app that was started. autoStart: () async { await autoStart(); // Return the App that was just started return _prepareFlutterApp(); }, // Calls [_initEngine], and returns a JS Promise that resolves to an // app runner object. initializeEngine: ([JsFlutterConfiguration? configuration]) async { await _initializeEngine(configuration); return _prepareAppRunner(); } ); } /// Creates an appRunner that runs our encapsulated runApp function. FlutterAppRunner _prepareAppRunner() { return FlutterAppRunner(runApp: ([RunAppFnParameters? params]) async { await _runApp(); return _prepareFlutterApp(); }); } FlutterViewManager get viewManager => EnginePlatformDispatcher.instance.viewManager; /// Represents the App that was just started, and its JS API. FlutterApp _prepareFlutterApp() { return FlutterApp( addView: (JsFlutterViewOptions options) { assert(configuration.multiViewEnabled, 'Cannot addView when multiView is not enabled'); return viewManager.createAndRegisterView(options).viewId; }, removeView: (int viewId) { assert(configuration.multiViewEnabled, 'Cannot removeView when multiView is not enabled'); return viewManager.disposeAndUnregisterView(viewId); } ); } }
engine/lib/web_ui/lib/src/engine/app_bootstrap.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/app_bootstrap.dart", "repo_id": "engine", "token_count": 940 }
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. import 'package:ui/ui.dart' as ui; import '../../engine.dart' show kProfileApplyFrame, kProfilePrerollFrame; import '../profiler.dart'; import '../vector_math.dart'; import 'canvas.dart'; import 'embedded_views.dart'; import 'layer.dart'; import 'n_way_canvas.dart'; import 'picture_recorder.dart'; import 'raster_cache.dart'; /// A tree of [Layer]s that, together with a [Size] compose a frame. class LayerTree { LayerTree(this.rootLayer); /// The root of the layer tree. final RootLayer rootLayer; /// The devicePixelRatio of the frame to paint this layer tree into. double? devicePixelRatio; /// Performs a preroll phase before painting the layer tree. /// /// In this phase, the paint boundary for each layer is computed and /// pictures are registered with the raster cache as potential candidates /// to raster. If [ignoreRasterCache] is `true`, then there will be no /// attempt to register pictures to cache. void preroll(Frame frame, {bool ignoreRasterCache = false}) { final PrerollContext context = PrerollContext( ignoreRasterCache ? null : frame.rasterCache, frame.viewEmbedder, ); rootLayer.preroll(context, Matrix4.identity()); } /// Paints the layer tree into the given [frame]. /// /// If [ignoreRasterCache] is `true`, then the raster cache will /// not be used. void paint(Frame frame, {bool ignoreRasterCache = false}) { final CkNWayCanvas internalNodesCanvas = CkNWayCanvas(); internalNodesCanvas.addCanvas(frame.canvas); final Iterable<CkCanvas> overlayCanvases = frame.viewEmbedder!.getOverlayCanvases(); overlayCanvases.forEach(internalNodesCanvas.addCanvas); final PaintContext context = PaintContext( internalNodesCanvas, frame.canvas, ignoreRasterCache ? null : frame.rasterCache, frame.viewEmbedder, ); if (rootLayer.needsPainting) { rootLayer.paint(context); } } /// Flattens the tree into a single [ui.Picture]. /// /// This picture does not contain any platform views. ui.Picture flatten(ui.Size size) { final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(ui.Offset.zero & size); final PrerollContext prerollContext = PrerollContext(null, null); rootLayer.preroll(prerollContext, Matrix4.identity()); final CkNWayCanvas internalNodesCanvas = CkNWayCanvas(); internalNodesCanvas.addCanvas(canvas); final PaintContext paintContext = PaintContext(internalNodesCanvas, canvas, null, null); if (rootLayer.needsPainting) { rootLayer.paint(paintContext); } return recorder.endRecording(); } } /// A single frame to be rendered. class Frame { Frame(this.canvas, this.rasterCache, this.viewEmbedder); /// The canvas to render this frame to. final CkCanvas canvas; /// A cache of pre-rastered pictures. final RasterCache? rasterCache; /// The platform view embedder. final HtmlViewEmbedder? viewEmbedder; /// Rasterize the given layer tree into this frame. bool raster(LayerTree layerTree, {bool ignoreRasterCache = false}) { timeAction<void>(kProfilePrerollFrame, () { layerTree.preroll(this, ignoreRasterCache: ignoreRasterCache); }); timeAction<void>(kProfileApplyFrame, () { layerTree.paint(this, ignoreRasterCache: ignoreRasterCache); }); return true; } } /// The state of the compositor, which is persisted between frames. class CompositorContext { /// A cache of pictures, which is shared between successive frames. RasterCache? rasterCache; /// Acquire a frame using this compositor's settings. Frame acquireFrame(CkCanvas canvas, HtmlViewEmbedder? viewEmbedder) { return Frame(canvas, rasterCache, viewEmbedder); } }
engine/lib/web_ui/lib/src/engine/canvaskit/layer_tree.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/layer_tree.dart", "repo_id": "engine", "token_count": 1299 }
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. import 'dart:async'; import 'dart:math' as math; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; enum CanvasKitVariant { /// The appropriate variant is chosen based on the browser. /// /// This is the default variant. auto, /// The full variant that can be used in any browser. full, /// The variant that is optimized for Chromium browsers. /// /// WARNING: In most cases, you should use [auto] instead of this variant. Using /// this variant in a non-Chromium browser will result in a broken app. chromium, } class CanvasKitRenderer implements Renderer { static CanvasKitRenderer get instance => _instance; static late CanvasKitRenderer _instance; Future<void>? _initialized; @override String get rendererTag => 'canvaskit'; late final SkiaFontCollection _fontCollection = SkiaFontCollection(); @override SkiaFontCollection get fontCollection => _fontCollection; /// The scene host, where the root canvas and overlay canvases are added to. DomElement? _sceneHost; DomElement? get sceneHost => _sceneHost; Rasterizer _rasterizer = _createRasterizer(); static Rasterizer _createRasterizer() { if (isSafari || isFirefox) { return MultiSurfaceRasterizer(); } return OffscreenCanvasRasterizer(); } /// Override the rasterizer with the given [_rasterizer]. Used in tests. void debugOverrideRasterizer(Rasterizer testRasterizer) { _rasterizer = testRasterizer; } set resourceCacheMaxBytes(int bytes) => _rasterizer.setResourceCacheMaxBytes(bytes); /// A surface used specifically for `Picture.toImage` when software rendering /// is supported. final Surface pictureToImageSurface = Surface(); // Listens for view creation events from the view manager. StreamSubscription<int>? _onViewCreatedListener; // Listens for view disposal events from the view manager. StreamSubscription<int>? _onViewDisposedListener; @override Future<void> initialize() async { _initialized ??= () async { if (windowFlutterCanvasKit != null) { canvasKit = windowFlutterCanvasKit!; } else if (windowFlutterCanvasKitLoaded != null) { // CanvasKit is being preloaded by flutter.js. Wait for it to complete. canvasKit = await promiseToFuture<CanvasKit>(windowFlutterCanvasKitLoaded!); } else { canvasKit = await downloadCanvasKit(); windowFlutterCanvasKit = canvasKit; } // Views may have been registered before this renderer was initialized. // Create rasterizers for them and then start listening for new view // creation/disposal events. final FlutterViewManager viewManager = EnginePlatformDispatcher.instance.viewManager; if (_onViewCreatedListener == null) { for (final EngineFlutterView view in viewManager.views) { _onViewCreated(view.viewId); } } _onViewCreatedListener ??= viewManager.onViewCreated.listen(_onViewCreated); _onViewDisposedListener ??= viewManager.onViewDisposed.listen(_onViewDisposed); _instance = this; }(); return _initialized; } @override ui.Paint createPaint() => CkPaint(); @override ui.Vertices createVertices( ui.VertexMode mode, List<ui.Offset> positions, { List<ui.Offset>? textureCoordinates, List<ui.Color>? colors, List<int>? indices, }) => CkVertices(mode, positions, textureCoordinates: textureCoordinates, colors: colors, indices: indices); @override ui.Vertices createVerticesRaw( ui.VertexMode mode, Float32List positions, { Float32List? textureCoordinates, Int32List? colors, Uint16List? indices, }) => CkVertices.raw(mode, positions, textureCoordinates: textureCoordinates, colors: colors, indices: indices); @override ui.Canvas createCanvas(ui.PictureRecorder recorder, [ui.Rect? cullRect]) => CanvasKitCanvas(recorder, cullRect); @override ui.Gradient createLinearGradient( ui.Offset from, ui.Offset to, List<ui.Color> colors, [List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix4]) => CkGradientLinear(from, to, colors, colorStops, tileMode, matrix4); @override ui.Gradient createRadialGradient( ui.Offset center, double radius, List<ui.Color> colors, [ List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix4, ]) => CkGradientRadial(center, radius, colors, colorStops, tileMode, matrix4); @override ui.Gradient createConicalGradient(ui.Offset focal, double focalRadius, ui.Offset center, double radius, List<ui.Color> colors, [List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, Float32List? matrix]) => CkGradientConical(focal, focalRadius, center, radius, colors, colorStops, tileMode, matrix); @override ui.Gradient createSweepGradient(ui.Offset center, List<ui.Color> colors, [List<double>? colorStops, ui.TileMode tileMode = ui.TileMode.clamp, double startAngle = 0.0, double endAngle = math.pi * 2, Float32List? matrix4]) => CkGradientSweep( center, colors, colorStops, tileMode, startAngle, endAngle, matrix4); @override ui.PictureRecorder createPictureRecorder() => CkPictureRecorder(); @override ui.SceneBuilder createSceneBuilder() => LayerSceneBuilder(); @override ui.ImageFilter createBlurImageFilter( {double sigmaX = 0.0, double sigmaY = 0.0, ui.TileMode tileMode = ui.TileMode.clamp}) => CkImageFilter.blur(sigmaX: sigmaX, sigmaY: sigmaY, tileMode: tileMode); @override ui.ImageFilter createDilateImageFilter( {double radiusX = 0.0, double radiusY = 0.0}) { // TODO(fzyzcjy): implement dilate. https://github.com/flutter/flutter/issues/101085 throw UnimplementedError( 'ImageFilter.dilate not implemented for CanvasKit.'); } @override ui.ImageFilter createErodeImageFilter( {double radiusX = 0.0, double radiusY = 0.0}) { // TODO(fzyzcjy): implement erode. https://github.com/flutter/flutter/issues/101085 throw UnimplementedError( 'ImageFilter.erode not implemented for CanvasKit.'); } @override ui.ImageFilter createMatrixImageFilter(Float64List matrix4, {ui.FilterQuality filterQuality = ui.FilterQuality.low}) => CkImageFilter.matrix(matrix: matrix4, filterQuality: filterQuality); @override ui.ImageFilter composeImageFilters( {required ui.ImageFilter outer, required ui.ImageFilter inner}) { if (outer is EngineColorFilter) { final CkColorFilter colorFilter = createCkColorFilter(outer)!; outer = CkColorFilterImageFilter(colorFilter: colorFilter); } if (inner is EngineColorFilter) { final CkColorFilter colorFilter = createCkColorFilter(inner)!; inner = CkColorFilterImageFilter(colorFilter: colorFilter); } return CkImageFilter.compose( outer: outer as CkImageFilter, inner: inner as CkImageFilter); } @override Future<ui.Codec> instantiateImageCodec(Uint8List list, {int? targetWidth, int? targetHeight, bool allowUpscaling = true}) async => skiaInstantiateImageCodec(list, targetWidth, targetHeight); @override Future<ui.Codec> instantiateImageCodecFromUrl(Uri uri, {ui_web.ImageCodecChunkCallback? chunkCallback}) => skiaInstantiateWebImageCodec(uri.toString(), chunkCallback); @override ui.Image createImageFromImageBitmap(DomImageBitmap imageBitmap) { final SkImage? skImage = canvasKit.MakeLazyImageFromImageBitmap(imageBitmap, true); if (skImage == null) { throw Exception('Failed to convert image bitmap to an SkImage.'); } return CkImage(skImage); } @override void decodeImageFromPixels(Uint8List pixels, int width, int height, ui.PixelFormat format, ui.ImageDecoderCallback callback, {int? rowBytes, int? targetWidth, int? targetHeight, bool allowUpscaling = true}) => skiaDecodeImageFromPixels(pixels, width, height, format, callback, rowBytes: rowBytes, targetWidth: targetWidth, targetHeight: targetHeight, allowUpscaling: allowUpscaling); @override ui.ImageShader createImageShader( ui.Image image, ui.TileMode tmx, ui.TileMode tmy, Float64List matrix4, ui.FilterQuality? filterQuality) => CkImageShader(image, tmx, tmy, matrix4, filterQuality); @override ui.Path createPath() => CkPath(); @override ui.Path copyPath(ui.Path src) => CkPath.from(src as CkPath); @override ui.Path combinePaths(ui.PathOperation op, ui.Path path1, ui.Path path2) => CkPath.combine(op, path1, path2); @override ui.TextStyle createTextStyle( {ui.Color? color, ui.TextDecoration? decoration, ui.Color? decorationColor, ui.TextDecorationStyle? decorationStyle, double? decorationThickness, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, ui.TextBaseline? textBaseline, String? fontFamily, List<String>? fontFamilyFallback, double? fontSize, double? letterSpacing, double? wordSpacing, double? height, ui.TextLeadingDistribution? leadingDistribution, ui.Locale? locale, ui.Paint? background, ui.Paint? foreground, List<ui.Shadow>? shadows, List<ui.FontFeature>? fontFeatures, List<ui.FontVariation>? fontVariations}) => CkTextStyle( color: color, decoration: decoration, decorationColor: decorationColor, decorationStyle: decorationStyle, decorationThickness: decorationThickness, fontWeight: fontWeight, fontStyle: fontStyle, textBaseline: textBaseline, fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback, fontSize: fontSize, letterSpacing: letterSpacing, wordSpacing: wordSpacing, height: height, leadingDistribution: leadingDistribution, locale: locale, background: background as CkPaint?, foreground: foreground as CkPaint?, shadows: shadows, fontFeatures: fontFeatures, fontVariations: fontVariations, ); @override ui.ParagraphStyle createParagraphStyle( {ui.TextAlign? textAlign, ui.TextDirection? textDirection, int? maxLines, String? fontFamily, double? fontSize, double? height, ui.TextHeightBehavior? textHeightBehavior, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, ui.StrutStyle? strutStyle, String? ellipsis, ui.Locale? locale}) => CkParagraphStyle( textAlign: textAlign, textDirection: textDirection, maxLines: maxLines, fontFamily: fontFamily, fontSize: fontSize, height: height, textHeightBehavior: textHeightBehavior, fontWeight: fontWeight, fontStyle: fontStyle, strutStyle: strutStyle, ellipsis: ellipsis, locale: locale, ); @override ui.StrutStyle createStrutStyle( {String? fontFamily, List<String>? fontFamilyFallback, double? fontSize, double? height, ui.TextLeadingDistribution? leadingDistribution, double? leading, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, bool? forceStrutHeight}) => CkStrutStyle( fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback, fontSize: fontSize, height: height, leadingDistribution: leadingDistribution, leading: leading, fontWeight: fontWeight, fontStyle: fontStyle, forceStrutHeight: forceStrutHeight, ); @override ui.ParagraphBuilder createParagraphBuilder(ui.ParagraphStyle style) => CkParagraphBuilder(style); // TODO(harryterkelsen): Merge this logic with the async logic in // [EngineScene], https://github.com/flutter/flutter/issues/142072. @override Future<void> renderScene(ui.Scene scene, ui.FlutterView view) async { assert(_rasterizers.containsKey(view.viewId), "Unable to render to a view which hasn't been registered"); final ViewRasterizer rasterizer = _rasterizers[view.viewId]!; final RenderQueue renderQueue = rasterizer.queue; final FrameTimingRecorder? recorder = FrameTimingRecorder.frameTimingsEnabled ? FrameTimingRecorder() : null; if (renderQueue.current != null) { // If a scene is already queued up, drop it and queue this one up instead // so that the scene view always displays the most recently requested scene. renderQueue.next?.completer.complete(); final Completer<void> completer = Completer<void>(); renderQueue.next = (scene: scene, completer: completer, recorder: recorder); return completer.future; } final Completer<void> completer = Completer<void>(); renderQueue.current = (scene: scene, completer: completer, recorder: recorder); unawaited(_kickRenderLoop(rasterizer)); return completer.future; } Future<void> _kickRenderLoop(ViewRasterizer rasterizer) async { final RenderQueue renderQueue = rasterizer.queue; final RenderRequest current = renderQueue.current!; try { await _renderScene(current.scene, rasterizer, current.recorder); current.completer.complete(); } catch (error, stackTrace) { current.completer.completeError(error, stackTrace); } renderQueue.current = renderQueue.next; renderQueue.next = null; if (renderQueue.current == null) { return; } else { return _kickRenderLoop(rasterizer); } } Future<void> _renderScene(ui.Scene scene, ViewRasterizer rasterizer, FrameTimingRecorder? recorder) async { // "Build finish" and "raster start" happen back-to-back because we // render on the same thread, so there's no overhead from hopping to // another thread. // // CanvasKit works differently from the HTML renderer in that in HTML // we update the DOM in SceneBuilder.build, which is these function calls // here are CanvasKit-only. recorder?.recordBuildFinish(); recorder?.recordRasterStart(); await rasterizer.draw((scene as LayerScene).layerTree); recorder?.recordRasterFinish(); recorder?.submitTimings(); } // Map from view id to the associated Rasterizer for that view. final Map<int, ViewRasterizer> _rasterizers = <int, ViewRasterizer>{}; void _onViewCreated(int viewId) { final EngineFlutterView view = EnginePlatformDispatcher.instance.viewManager[viewId]!; _rasterizers[view.viewId] = _rasterizer.createViewRasterizer(view); } void _onViewDisposed(int viewId) { // The view has already been disposed. if (!_rasterizers.containsKey(viewId)) { return; } final ViewRasterizer rasterizer = _rasterizers.remove(viewId)!; rasterizer.dispose(); } ViewRasterizer? debugGetRasterizerForView(EngineFlutterView view) { return _rasterizers[view.viewId]; } /// Disposes this renderer. void dispose() { _onViewCreatedListener?.cancel(); _onViewDisposedListener?.cancel(); for (final ViewRasterizer rasterizer in _rasterizers.values) { rasterizer.dispose(); } _rasterizers.clear(); } /// Clears the state of this renderer. Used in tests. void debugClear() { for (final ViewRasterizer rasterizer in _rasterizers.values) { rasterizer.debugClear(); } } @override void clearFragmentProgramCache() { _programs.clear(); } static final Map<String, Future<ui.FragmentProgram>> _programs = <String, Future<ui.FragmentProgram>>{}; @override Future<ui.FragmentProgram> createFragmentProgram(String assetKey) { if (_programs.containsKey(assetKey)) { return _programs[assetKey]!; } return _programs[assetKey] = ui_web.assetManager.load(assetKey).then((ByteData data) { return CkFragmentProgram.fromBytes(assetKey, data.buffer.asUint8List()); }); } @override ui.LineMetrics createLineMetrics( {required bool hardBreak, required double ascent, required double descent, required double unscaledAscent, required double height, required double width, required double left, required double baseline, required int lineNumber}) => EngineLineMetrics( hardBreak: hardBreak, ascent: ascent, descent: descent, unscaledAscent: unscaledAscent, height: height, width: width, left: left, baseline: baseline, lineNumber: lineNumber); }
engine/lib/web_ui/lib/src/engine/canvaskit/renderer.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/renderer.dart", "repo_id": "engine", "token_count": 6857 }
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. import 'dart:async'; import 'dart:convert'; import 'dart:js_interop'; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; class FontAsset { FontAsset(this.asset, this.descriptors); final String asset; final Map<String, String> descriptors; } class FontFamily { FontFamily(this.name, this.fontAssets); final String name; final List<FontAsset> fontAssets; } class FontManifest { FontManifest(this.families); final List<FontFamily> families; } Future<FontManifest> fetchFontManifest(ui_web.AssetManager assetManager) async { final HttpFetchResponse response = await assetManager.loadAsset('FontManifest.json') as HttpFetchResponse; if (!response.hasPayload) { printWarning('Font manifest does not exist at `${response.url}` - ignoring.'); return FontManifest(<FontFamily>[]); } final Converter<List<int>, Object?> decoder = const Utf8Decoder().fuse(const JsonDecoder()); Object? fontManifestJson; final Sink<List<int>> inputSink = decoder.startChunkedConversion( ChunkedConversionSink<Object?>.withCallback( (List<Object?> accumulated) { if (accumulated.length != 1) { throw AssertionError('There was a problem trying to load FontManifest.json'); } fontManifestJson = accumulated.first; } )); await response.read((JSUint8Array chunk) => inputSink.add(chunk.toDart)); inputSink.close(); if (fontManifestJson == null) { throw AssertionError('There was a problem trying to load FontManifest.json'); } final List<FontFamily> families = (fontManifestJson! as List<dynamic>).map( (dynamic fontFamilyJson) { final Map<String, dynamic> fontFamily = fontFamilyJson as Map<String, dynamic>; final String familyName = fontFamily.readString('family'); final List<dynamic> fontAssets = fontFamily.readList('fonts'); return FontFamily(familyName, fontAssets.map((dynamic fontAssetJson) { String? asset; final Map<String, String> descriptors = <String, String>{}; for (final MapEntry<String, dynamic> descriptor in (fontAssetJson as Map<String, dynamic>).entries) { if (descriptor.key == 'asset') { asset = descriptor.value as String; } else { // Sometimes these descriptors are strings, and sometimes numbers, so we stringify them here. descriptors[descriptor.key] = '${descriptor.value}'; } } if (asset == null) { throw AssertionError("Invalid Font manifest, missing 'asset' key on font."); } return FontAsset(asset, descriptors); }).toList()); }).toList(); return FontManifest(families); } abstract class FontLoadError extends Error { FontLoadError(this.url); String url; String get message; } class FontNotFoundError extends FontLoadError { FontNotFoundError(super.url); @override String get message => 'Font asset not found at url $url.'; } class FontDownloadError extends FontLoadError { FontDownloadError(super.url, this.error); dynamic error; @override String get message => 'Failed to download font asset at url $url with error: $error.'; } class FontInvalidDataError extends FontLoadError { FontInvalidDataError(super.url); @override String get message => 'Invalid data for font asset at url $url.'; } class AssetFontsResult { AssetFontsResult(this.loadedFonts, this.fontFailures); /// A list of asset keys for fonts that were successfully loaded. final List<String> loadedFonts; /// A map of the asset keys to failures for fonts that failed to load. final Map<String, FontLoadError> fontFailures; } abstract class FlutterFontCollection { /// Loads a font directly from font data. Future<bool> loadFontFromList(Uint8List list, {String? fontFamily}); /// Completes when fonts from FontManifest.json have been loaded. Future<AssetFontsResult> loadAssetFonts(FontManifest manifest); // The font fallback manager for this font collection. HTML renderer doesn't // have a font fallback manager and just relies on the browser to fall back // properly. FontFallbackManager? get fontFallbackManager; // Reset the state of font fallbacks. Only to be used in testing. void debugResetFallbackFonts(); // Unregisters all fonts. void clear(); }
engine/lib/web_ui/lib/src/engine/fonts.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/fonts.dart", "repo_id": "engine", "token_count": 1516 }
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. import 'dart:math' as math; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../../validators.dart'; import '../../vector_math.dart'; import 'conic.dart'; import 'cubic.dart'; import 'path_iterator.dart'; import 'path_metrics.dart'; import 'path_ref.dart'; import 'path_utils.dart'; import 'path_windings.dart'; import 'tangent.dart'; /// A complex, one-dimensional subset of a plane. /// /// Path consist of segments of various types, such as lines, /// arcs, or beziers. Subpaths can be open or closed, and can /// self-intersect. /// /// Stores the verbs and points as they are given to us, with exceptions: /// - we only record "Close" if it was immediately preceded by Move | Line | Quad | Cubic /// - we insert a Move(0,0) if Line | Quad | Cubic is our first command /// /// The iterator does more cleanup, especially if forceClose == true /// 1. If we encounter degenerate segments, remove them /// 2. if we encounter Close, return a cons'd up Line() first (if the curr-pt != start-pt) /// 3. if we encounter Move without a preceding Close, and forceClose is true, goto #2 /// 4. if we encounter Line | Quad | Cubic after Close, cons up a Move class SurfacePath implements ui.Path { SurfacePath() : pathRef = PathRef() { _resetFields(); } /// Creates a copy of another [Path]. SurfacePath.from(SurfacePath source) : pathRef = PathRef()..copy(source.pathRef, 0, 0) { _copyFields(source); } /// Creates a shifted copy of another [Path]. SurfacePath.shiftedFrom(SurfacePath source, double offsetX, double offsetY) : pathRef = PathRef.shiftedFrom(source.pathRef, offsetX, offsetY) { _copyFields(source); } SurfacePath.shallowCopy(SurfacePath source) : pathRef = PathRef.shallowCopy(source.pathRef) { _copyFields(source); } // Initial valid of last move to index so we can detect if a move to // needs to be inserted after contour closure. See [close]. static const int kInitialLastMoveToIndexValue = 0; PathRef pathRef; ui.PathFillType _fillType = ui.PathFillType.nonZero; // Store point index + 1 of last moveTo instruction. // If contour has been closed or path is in initial state, the value is // negated. int fLastMoveToIndex = kInitialLastMoveToIndexValue; int _convexityType = SPathConvexityType.kUnknown; int _firstDirection = SPathDirection.kUnknown; void _resetFields() { fLastMoveToIndex = kInitialLastMoveToIndexValue; _fillType = ui.PathFillType.nonZero; _resetAfterEdit(); } void _resetAfterEdit() { _convexityType = SPathConvexityType.kUnknown; _firstDirection = SPathDirection.kUnknown; } void _copyFields(SurfacePath source) { _fillType = source._fillType; fLastMoveToIndex = source.fLastMoveToIndex; _convexityType = source._convexityType; _firstDirection = source._firstDirection; } /// Determines how the interior of this path is calculated. /// /// Defaults to the non-zero winding rule, [PathFillType.nonZero]. @override ui.PathFillType get fillType => _fillType; @override set fillType(ui.PathFillType value) { _fillType = value; } /// Returns true if [SurfacePath] contain equal verbs and equal weights. bool isInterpolatable(SurfacePath compare) => compare.pathRef.countVerbs() == pathRef.countVerbs() && compare.pathRef.countPoints() == pathRef.countPoints() && compare.pathRef.countWeights() == pathRef.countWeights(); bool interpolate(SurfacePath ending, double weight, SurfacePath out) { final int pointCount = pathRef.countPoints(); if (pointCount != ending.pathRef.countPoints()) { return false; } if (pointCount == 0) { return true; } out.reset(); out.addPathWithMode(this, 0, 0, null, SPathAddPathMode.kAppend); PathRef.interpolate(ending.pathRef, weight, out.pathRef); return true; } /// Clears the [Path] object, returning it to the /// same state it had when it was created. The _current point_ is /// reset to the origin. @override void reset() { if (pathRef.countVerbs() != 0) { pathRef = PathRef(); _resetFields(); } } /// Sets [SurfacePath] to its initial state, preserving internal storage. /// Removes verb array, SkPoint array, and weights, and sets FillType to /// kWinding. Internal storage associated with SkPath is retained. /// /// Use rewind() instead of reset() if SkPath storage will be reused and /// performance is critical. void rewind() { pathRef.rewind(); _resetFields(); } /// Returns if contour is closed. /// /// Contour is closed if [SurfacePath] verb array was last modified by /// close(). When stroked, closed contour draws join instead of cap at first /// and last point. bool get isLastContourClosed { final int verbCount = pathRef.countVerbs(); return verbCount > 0 && (pathRef.atVerb(verbCount - 1) == SPathVerb.kClose); } /// Returns true for finite SkPoint array values between negative SK_ScalarMax /// and positive SK_ScalarMax. Returns false for any SkPoint array value of /// SK_ScalarInfinity, SK_ScalarNegativeInfinity, or SK_ScalarNaN. bool get isFinite { _debugValidate(); return pathRef.isFinite; } void _debugValidate() { assert(pathRef.isValid); } /// Return true if path is a single line and returns points in out. bool isLine(Float32List out) { assert(out.length >= 4); final int verbCount = pathRef.countPoints(); if (2 == verbCount && pathRef.atVerb(0) == SPathVerb.kMove && pathRef.atVerb(1) != SPathVerb.kLine) { out[0] = pathRef.points[0]; out[1] = pathRef.points[1]; out[2] = pathRef.points[2]; out[3] = pathRef.points[3]; return true; } return false; } /// Starts a new subpath at the given coordinate. @override void moveTo(double x, double y) { // remember our index final int pointIndex = pathRef.growForVerb(SPathVerb.kMove, 0); fLastMoveToIndex = pointIndex + 1; pathRef.setPoint(pointIndex, x, y); _resetAfterEdit(); } /// Starts a new subpath at the given offset from the current point. @override void relativeMoveTo(double dx, double dy) { final int pointCount = pathRef.countPoints(); if (pointCount == 0) { moveTo(dx, dy); } else { int pointIndex = (pointCount - 1) * 2; final double lastPointX = pathRef.points[pointIndex++]; final double lastPointY = pathRef.points[pointIndex]; moveTo(lastPointX + dx, lastPointY + dy); } } void _injectMoveToIfNeeded() { if (fLastMoveToIndex <= 0) { double x, y; if (pathRef.countPoints() == 0) { x = y = 0.0; } else { int pointIndex = 2 * (-fLastMoveToIndex - 1); x = pathRef.points[pointIndex++]; y = pathRef.points[pointIndex]; } moveTo(x, y); } } /// Adds a straight line segment from the current point to the given /// point. @override void lineTo(double x, double y) { if (fLastMoveToIndex <= 0) { _injectMoveToIfNeeded(); } final int pointIndex = pathRef.growForVerb(SPathVerb.kLine, 0); pathRef.setPoint(pointIndex, x, y); _resetAfterEdit(); } /// Adds a straight line segment from the current point to the point /// at the given offset from the current point. @override void relativeLineTo(double dx, double dy) { final int pointCount = pathRef.countPoints(); if (pointCount == 0) { lineTo(dx, dy); } else { int pointIndex = (pointCount - 1) * 2; final double lastPointX = pathRef.points[pointIndex++]; final double lastPointY = pathRef.points[pointIndex]; lineTo(lastPointX + dx, lastPointY + dy); } } /// Adds a quadratic bezier segment that curves from the current /// point to the given point (x2,y2), using the control point /// (x1,y1). @override void quadraticBezierTo(double x1, double y1, double x2, double y2) { _injectMoveToIfNeeded(); _quadTo(x1, y1, x2, y2); } /// Adds a quadratic bezier segment that curves from the current /// point to the point at the offset (x2,y2) from the current point, /// using the control point at the offset (x1,y1) from the current /// point. @override void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2) { final int pointCount = pathRef.countPoints(); if (pointCount == 0) { quadraticBezierTo(x1, y1, x2, y2); } else { int pointIndex = (pointCount - 1) * 2; final double lastPointX = pathRef.points[pointIndex++]; final double lastPointY = pathRef.points[pointIndex]; quadraticBezierTo( x1 + lastPointX, y1 + lastPointY, x2 + lastPointX, y2 + lastPointY); } } void _quadTo(double x1, double y1, double x2, double y2) { final int pointIndex = pathRef.growForVerb(SPathVerb.kQuad, 0); pathRef.setPoint(pointIndex, x1, y1); pathRef.setPoint(pointIndex + 1, x2, y2); _resetAfterEdit(); } /// Adds a bezier segment that curves from the current point to the /// given point (x2,y2), using the control points (x1,y1) and the /// weight w. If the weight is greater than 1, then the curve is a /// hyperbola; if the weight equals 1, it's a parabola; and if it is /// less than 1, it is an ellipse. @override void conicTo(double x1, double y1, double x2, double y2, double w) { _injectMoveToIfNeeded(); final int pointIndex = pathRef.growForVerb(SPathVerb.kConic, w); pathRef.setPoint(pointIndex, x1, y1); pathRef.setPoint(pointIndex + 1, x2, y2); _resetAfterEdit(); } /// Adds a bezier segment that curves from the current point to the /// point at the offset (x2,y2) from the current point, using the /// control point at the offset (x1,y1) from the current point and /// the weight w. If the weight is greater than 1, then the curve is /// a hyperbola; if the weight equals 1, it's a parabola; and if it /// is less than 1, it is an ellipse. @override void relativeConicTo(double x1, double y1, double x2, double y2, double w) { final int pointCount = pathRef.countPoints(); if (pointCount == 0) { conicTo(x1, y1, x2, y2, w); } else { int pointIndex = (pointCount - 1) * 2; final double lastPointX = pathRef.points[pointIndex++]; final double lastPointY = pathRef.points[pointIndex]; conicTo(lastPointX + x1, lastPointY + y1, lastPointX + x2, lastPointY + y2, w); } } /// Adds a cubic bezier segment that curves from the current point /// to the given point (x3,y3), using the control points (x1,y1) and /// (x2,y2). @override void cubicTo( double x1, double y1, double x2, double y2, double x3, double y3) { _injectMoveToIfNeeded(); final int pointIndex = pathRef.growForVerb(SPathVerb.kCubic, 0); pathRef.setPoint(pointIndex, x1, y1); pathRef.setPoint(pointIndex + 1, x2, y2); pathRef.setPoint(pointIndex + 2, x3, y3); _resetAfterEdit(); } /// Adds a cubic bezier segment that curves from the current point /// to the point at the offset (x3,y3) from the current point, using /// the control points at the offsets (x1,y1) and (x2,y2) from the /// current point. @override void relativeCubicTo( double x1, double y1, double x2, double y2, double x3, double y3) { final int pointCount = pathRef.countPoints(); if (pointCount == 0) { cubicTo(x1, y1, x2, y2, x3, y3); } else { int pointIndex = (pointCount - 1) * 2; final double lastPointX = pathRef.points[pointIndex++]; final double lastPointY = pathRef.points[pointIndex]; cubicTo(x1 + lastPointX, y1 + lastPointY, x2 + lastPointX, y2 + lastPointY, x3 + lastPointX, y3 + lastPointY); } } /// Closes the last subpath, as if a straight line had been drawn /// from the current point to the first point of the subpath. @override void close() { _debugValidate(); // Don't add verb if it is the first instruction or close as already // been added. final int verbCount = pathRef.countVerbs(); if (verbCount != 0 && pathRef.atVerb(verbCount - 1) != SPathVerb.kClose) { pathRef.growForVerb(SPathVerb.kClose, 0); } if (fLastMoveToIndex >= 0) { // Signal that we need a moveTo to follow next if not specified. fLastMoveToIndex = -fLastMoveToIndex; } _resetAfterEdit(); } /// Adds a new subpath that consists of four lines that outline the /// given rectangle. @override void addRect(ui.Rect rect) { addRectWithDirection(rect, SPathDirection.kCW, 0); } bool _hasOnlyMoveTos() { final int verbCount = pathRef.countVerbs(); for (int i = 0; i < verbCount; i++) { switch (pathRef.atVerb(i)) { case SPathVerb.kLine: case SPathVerb.kQuad: case SPathVerb.kConic: case SPathVerb.kCubic: return false; } } return true; } void addRectWithDirection(ui.Rect rect, int direction, int startIndex) { assert(direction != SPathDirection.kUnknown); final bool isRect = _hasOnlyMoveTos(); // SkAutoDisableDirectionCheck. final int finalDirection = _hasOnlyMoveTos() ? direction : SPathDirection.kUnknown; final int pointIndex0 = pathRef.growForVerb(SPathVerb.kMove, 0); fLastMoveToIndex = pointIndex0 + 1; final int pointIndex1 = pathRef.growForVerb(SPathVerb.kLine, 0); final int pointIndex2 = pathRef.growForVerb(SPathVerb.kLine, 0); final int pointIndex3 = pathRef.growForVerb(SPathVerb.kLine, 0); pathRef.growForVerb(SPathVerb.kClose, 0); if (direction == SPathDirection.kCW) { pathRef.setPoint(pointIndex0, rect.left, rect.top); pathRef.setPoint(pointIndex1, rect.right, rect.top); pathRef.setPoint(pointIndex2, rect.right, rect.bottom); pathRef.setPoint(pointIndex3, rect.left, rect.bottom); } else { pathRef.setPoint(pointIndex3, rect.left, rect.bottom); pathRef.setPoint(pointIndex2, rect.right, rect.bottom); pathRef.setPoint(pointIndex1, rect.right, rect.top); pathRef.setPoint(pointIndex0, rect.left, rect.top); } pathRef.setIsRect(isRect, direction == SPathDirection.kCCW, 0); _resetAfterEdit(); // SkAutoDisableDirectionCheck. _firstDirection = finalDirection; // TODO(ferhat): optimize by setting pathRef bounds if bounds are already computed. } /// If the `forceMoveTo` argument is false, adds a straight line /// segment and an arc segment. /// /// If the `forceMoveTo` argument is true, starts a new subpath /// consisting of an arc segment. /// /// In either case, the arc segment consists of the arc that follows /// the edge of the oval bounded by the given rectangle, from /// startAngle radians around the oval up to startAngle + sweepAngle /// radians around the oval, with zero radians being the point on /// the right hand side of the oval that crosses the horizontal line /// that intersects the center of the rectangle and with positive /// angles going clockwise around the oval. /// /// The line segment added if `forceMoveTo` is false starts at the /// current point and ends at the start of the arc. @override void arcTo( ui.Rect rect, double startAngle, double sweepAngle, bool forceMoveTo) { assert(rectIsValid(rect)); // If width or height is 0, we still stroke a line, only abort if both // are empty. if (rect.width == 0 && rect.height == 0) { return; } if (pathRef.countPoints() == 0) { forceMoveTo = true; } final ui.Offset? lonePoint = _arcIsLonePoint(rect, startAngle, sweepAngle); if (lonePoint != null) { if (forceMoveTo) { moveTo(lonePoint.dx, lonePoint.dy); } else { lineTo(lonePoint.dx, lonePoint.dy); } } // Convert angles to unit vectors. double stopAngle = startAngle + sweepAngle; final double cosStart = math.cos(startAngle); final double sinStart = math.sin(startAngle); double cosStop = math.cos(stopAngle); double sinStop = math.sin(stopAngle); // If the sweep angle is nearly (but less than) 360, then due to precision // loss in radians-conversion and/or sin/cos, we may end up with coincident // vectors, which will fool quad arc build into doing nothing (bad) instead // of drawing a nearly complete circle (good). // e.g. canvas.drawArc(0, 359.99, ...) // -vs- canvas.drawArc(0, 359.9, ...) // Detect this edge case, and tweak the stop vector. if (SPath.nearlyEqual(cosStart, cosStop) && SPath.nearlyEqual(sinStart, sinStop)) { final double sweep = sweepAngle.abs() * 180.0 / math.pi; if (sweep <= 360 && sweep > 359) { // Use tiny angle (in radians) to tweak. final double deltaRad = sweepAngle < 0 ? -1.0 / 512.0 : 1.0 / 512.0; do { stopAngle -= deltaRad; cosStop = math.cos(stopAngle); sinStop = math.sin(stopAngle); } while (cosStart == cosStop && sinStart == sinStop); } } final int dir = sweepAngle > 0 ? SPathDirection.kCW : SPathDirection.kCCW; final double endAngle = startAngle + sweepAngle; final double radiusX = rect.width / 2.0; final double radiusY = rect.height / 2.0; final double px = rect.center.dx + (radiusX * math.cos(endAngle)); final double py = rect.center.dy + (radiusY * math.sin(endAngle)); // At this point, we know that the arc is not a lone point, but // startV == stopV indicates that the sweepAngle is too small such that // angles_to_unit_vectors cannot handle it if (cosStart == cosStop && sinStart == sinStop) { // Add moveTo to start point if forceMoveTo is true. Otherwise a lineTo // unless we're sufficiently close to start point currently. This prevents // spurious lineTos when adding a series of contiguous arcs from the same // oval. if (forceMoveTo) { moveTo(px, py); } else { _lineToIfNotTooCloseToLastPoint(px, py); } // We are done with tiny sweep approximated by line. return; } // Convert arc defined by start/end unit vectors to conics (max 5). // Dot product final double x = (cosStart * cosStop) + (sinStart * sinStop); // Cross product double y = (cosStart * sinStop) - (sinStart * cosStop); final double absY = y.abs(); // Check for coincident vectors (angle is nearly 0 or 180). // The cross product for angles 0 and 180 will be zero, we use the // dot product sign to distinguish between the two. if (absY <= SPath.scalarNearlyZero && x > 0 && ((y >= 0 && dir == SPathDirection.kCW) || (y <= 0 && dir == SPathDirection.kCCW))) { // No conics, just use single line to connect point. if (forceMoveTo) { moveTo(px, py); } else { _lineToIfNotTooCloseToLastPoint(px, py); } return; } // Normalize to clockwise if (dir == SPathDirection.kCCW) { y = -y; } // Use 1 conic per quadrant of a circle. // 0..90 -> quadrant 0 // 90..180 -> quadrant 1 // 180..270 -> quadrant 2 // 270..360 -> quadrant 3 const List<ui.Offset> quadPoints = <ui.Offset>[ ui.Offset(1, 0), ui.Offset(1, 1), ui.Offset(0, 1), ui.Offset(-1, 1), ui.Offset(-1, 0), ui.Offset(-1, -1), ui.Offset(0, -1), ui.Offset(1, -1), ]; int quadrant = 0; if (0 == y) { // 180 degrees between vectors. quadrant = 2; assert((x + 1).abs() <= SPath.scalarNearlyZero); } else if (0 == x) { // Dot product 0 means 90 degrees between vectors. assert((absY - 1) <= SPath.scalarNearlyZero); quadrant = y > 0 ? 1 : 3; // 90 or 270 } else { if (y < 0) { quadrant += 2; } if ((x < 0) != (y < 0)) { quadrant += 1; } } final List<Conic> conics = <Conic>[]; const double quadrantWeight = SPath.scalarRoot2Over2; int conicCount = quadrant; for (int i = 0; i < conicCount; i++) { final int quadPointIndex = i * 2; final ui.Offset p0 = quadPoints[quadPointIndex]; final ui.Offset p1 = quadPoints[quadPointIndex + 1]; final ui.Offset p2 = quadPoints[quadPointIndex + 2]; conics .add(Conic(p0.dx, p0.dy, p1.dx, p1.dy, p2.dx, p2.dy, quadrantWeight)); } // Now compute any remaining ( < 90degree ) arc for last conic. final double finalPx = x; final double finalPy = y; final ui.Offset lastQuadrantPoint = quadPoints[quadrant * 2]; // Dot product between last quadrant vector and last point on arc. final double dot = (x * lastQuadrantPoint.dx) + (y * lastQuadrantPoint.dy); if (dot < 1) { // Compute the bisector vector and then rescale to be the off curve point. // Length is cos(theta/2) using half angle identity we get // length = sqrt(2 / (1 + cos(theta)). We already have cos from computing // dot. Computed weight is cos(theta/2). double offCurveX = lastQuadrantPoint.dx + x; double offCurveY = lastQuadrantPoint.dy + y; final double cosThetaOver2 = math.sqrt((1.0 + dot) / 2.0); final double unscaledLength = math.sqrt((offCurveX * offCurveX) + (offCurveY * offCurveY)); assert(unscaledLength > SPath.scalarNearlyZero); offCurveX /= cosThetaOver2 * unscaledLength; offCurveY /= cosThetaOver2 * unscaledLength; if (!SPath.nearlyEqual(offCurveX, lastQuadrantPoint.dx) || !SPath.nearlyEqual(offCurveY, lastQuadrantPoint.dy)) { conics.add(Conic(lastQuadrantPoint.dx, lastQuadrantPoint.dy, offCurveX, offCurveY, finalPx, finalPy, cosThetaOver2)); ++conicCount; } } // Any points we generate based on unit vectors cos/sinStart , cos/sinStop // we rotate to start vector, scale by rect.width/2 rect.height/2 and // then translate to center point. final double scaleX = rect.width / 2; final bool ccw = dir == SPathDirection.kCCW; final double scaleY = rect.height / 2; final double centerX = rect.center.dx; final double centerY = rect.center.dy; for (final Conic conic in conics) { double x = conic.p0x; double y = ccw ? -conic.p0y : conic.p0y; conic.p0x = (cosStart * x - sinStart * y) * scaleX + centerX; conic.p0y = (cosStart * y + sinStart * x) * scaleY + centerY; x = conic.p1x; y = ccw ? -conic.p1y : conic.p1y; conic.p1x = (cosStart * x - sinStart * y) * scaleX + centerX; conic.p1y = (cosStart * y + sinStart * x) * scaleY + centerY; x = conic.p2x; y = ccw ? -conic.p2y : conic.p2y; conic.p2x = (cosStart * x - sinStart * y) * scaleX + centerX; conic.p2y = (cosStart * y + sinStart * x) * scaleY + centerY; } // Now output points. final double firstConicPx = conics[0].p0x; final double firstConicPy = conics[0].p0y; if (forceMoveTo) { moveTo(firstConicPx, firstConicPy); } else { _lineToIfNotTooCloseToLastPoint(firstConicPx, firstConicPy); } for (int i = 0; i < conicCount; i++) { final Conic conic = conics[i]; conicTo(conic.p1x, conic.p1y, conic.p2x, conic.p2y, conic.fW); } _resetAfterEdit(); } void _lineToIfNotTooCloseToLastPoint(double px, double py) { final int pointCount = pathRef.countPoints(); if (pointCount != 0) { final ui.Offset lastPoint = pathRef.atPoint(pointCount - 1); final double lastPointX = lastPoint.dx; final double lastPointY = lastPoint.dy; if (!SPath.nearlyEqual(px, lastPointX) || !SPath.nearlyEqual(py, lastPointY)) { lineTo(px, py); } } } /// Appends up to four conic curves weighted to describe an oval of `radius` /// and rotated by `rotation` (measured in degrees and clockwise). /// /// The first curve begins from the last point in the path and the last ends /// at `arcEnd`. The curves follow a path in a direction determined by /// `clockwise` and `largeArc` in such a way that the sweep angle /// is always less than 360 degrees. /// /// A simple line is appended if either radii are zero or the last /// point in the path is `arcEnd`. The radii are scaled to fit the last path /// point if both are greater than zero but too small to describe an arc. /// /// See Conversion from endpoint to center parametrization described in /// https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter /// as reference for implementation. @override void arcToPoint( ui.Offset arcEnd, { ui.Radius radius = ui.Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true, }) { assert(offsetIsValid(arcEnd)); assert(radiusIsValid(radius)); _injectMoveToIfNeeded(); final int pointCount = pathRef.countPoints(); double lastPointX, lastPointY; if (pointCount == 0) { lastPointX = lastPointY = 0; } else { int pointIndex = (pointCount - 1) * 2; lastPointX = pathRef.points[pointIndex++]; lastPointY = pathRef.points[pointIndex]; } // lastPointX, lastPointY are the coordinates of start point on path, // x,y is final point of arc. final double x = arcEnd.dx; final double y = arcEnd.dy; // rx,ry are the radii of the eclipse (semi-major/semi-minor axis) double rx = radius.x.abs(); double ry = radius.y.abs(); // If the current point and target point for the arc are identical, it // should be treated as a zero length path. This ensures continuity in // animations. final bool isSamePoint = lastPointX == x && lastPointY == y; // If rx = 0 or ry = 0 then this arc is treated as a straight line segment // (a "lineto") joining the endpoints. // http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters if (isSamePoint || rx.toInt() == 0 || ry.toInt() == 0) { if (rx == 0 || ry == 0) { lineTo(x, y); return; } } // As an intermediate point to finding center parametrization, place the // origin on the midpoint between start/end points and rotate to align // coordinate axis with axes of the ellipse. final double midPointX = (lastPointX - x) / 2.0; final double midPointY = (lastPointY - y) / 2.0; // Convert rotation or radians. final double xAxisRotation = math.pi * rotation / 180.0; // Cache cos/sin value. final double cosXAxisRotation = math.cos(xAxisRotation); final double sinXAxisRotation = math.sin(xAxisRotation); // Calculate rotated midpoint. final double xPrime = (cosXAxisRotation * midPointX) + (sinXAxisRotation * midPointY); final double yPrime = (-sinXAxisRotation * midPointX) + (cosXAxisRotation * midPointY); // Check if the radii are big enough to draw the arc, scale radii if not. // http://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii double rxSquare = rx * rx; double rySquare = ry * ry; final double xPrimeSquare = xPrime * xPrime; final double yPrimeSquare = yPrime * yPrime; double radiiScale = (xPrimeSquare / rxSquare) + (yPrimeSquare / rySquare); if (radiiScale > 1) { radiiScale = math.sqrt(radiiScale); rx *= radiiScale; ry *= radiiScale; rxSquare = rx * rx; rySquare = ry * ry; } // Switch to unit vectors double unitPts0x = (lastPointX * cosXAxisRotation + lastPointY * sinXAxisRotation) / rx; double unitPts0y = (lastPointY * cosXAxisRotation - lastPointX * sinXAxisRotation) / ry; double unitPts1x = (x * cosXAxisRotation + y * sinXAxisRotation) / rx; double unitPts1y = (y * cosXAxisRotation - x * sinXAxisRotation) / ry; double deltaX = unitPts1x - unitPts0x; double deltaY = unitPts1y - unitPts0y; final double d = deltaX * deltaX + deltaY * deltaY; double scaleFactor = math.sqrt(math.max(1 / d - 0.25, 0.0)); // largeArc is false if arc is spanning less than or equal to 180 degrees. // clockwise is false if arc sweeps through decreasing angles or true // if sweeping through increasing angles. // rotation is the angle from the x-axis of the current coordinate // system to the x-axis of the eclipse. if (largeArc == clockwise) { scaleFactor = -scaleFactor; } deltaX *= scaleFactor; deltaY *= scaleFactor; // Compute transformed center. eq. 5.2 final double centerPointX = (unitPts0x + unitPts1x) / 2 - deltaY; final double centerPointY = (unitPts0y + unitPts1y) / 2 + deltaX; unitPts0x -= centerPointX; unitPts0y -= centerPointY; unitPts1x -= centerPointX; unitPts1y -= centerPointY; // Calculate start angle and sweep. final double theta1 = math.atan2(unitPts0y, unitPts0x); final double theta2 = math.atan2(unitPts1y, unitPts1x); double thetaArc = theta2 - theta1; if (clockwise && thetaArc < 0) { thetaArc += math.pi * 2.0; } else if (!clockwise && thetaArc > 0) { thetaArc -= math.pi * 2.0; } // Guard against tiny angles. See skbug.com/9272. if (thetaArc.abs() < (math.pi / (1000.0 * 1000.0))) { lineTo(x, y); return; } // The arc may be slightly bigger than 1/4 circle, so allow up to 1/3rd. final int segments = (thetaArc / (2.0 * math.pi / 3.0)).abs().ceil(); final double thetaWidth = thetaArc / segments; final double t = math.tan(thetaWidth / 2.0); if (!t.isFinite) { return; } final double w = math.sqrt(0.5 + math.cos(thetaWidth) * 0.5); double startTheta = theta1; // Computing the arc width introduces rounding errors that cause arcs // to start outside their marks. A round rect may lose convexity as a // result. If the input values are on integers, place the conic on // integers as well. final bool expectIntegers = SPath.nearlyEqual(math.pi / 2 - thetaWidth.abs(), 0) && SPath.isInteger(rx) && SPath.isInteger(ry) && SPath.isInteger(x) && SPath.isInteger(y); for (int i = 0; i < segments; i++) { final double endTheta = startTheta + thetaWidth; final double sinEndTheta = SPath.snapToZero(math.sin(endTheta)); final double cosEndTheta = SPath.snapToZero(math.cos(endTheta)); double unitPts1x = cosEndTheta + centerPointX; double unitPts1y = sinEndTheta + centerPointY; double unitPts0x = unitPts1x + t * sinEndTheta; double unitPts0y = unitPts1y - t * cosEndTheta; unitPts0x = unitPts0x * rx; unitPts0y = unitPts0y * ry; unitPts1x = unitPts1x * rx; unitPts1y = unitPts1y * ry; double xStart = unitPts0x * cosXAxisRotation - unitPts0y * sinXAxisRotation; double yStart = unitPts0y * cosXAxisRotation + unitPts0x * sinXAxisRotation; double xEnd = unitPts1x * cosXAxisRotation - unitPts1y * sinXAxisRotation; double yEnd = unitPts1y * cosXAxisRotation + unitPts1x * sinXAxisRotation; if (expectIntegers) { xStart = (xStart + 0.5).floorToDouble(); yStart = (yStart + 0.5).floorToDouble(); xEnd = (xEnd + 0.5).floorToDouble(); yEnd = (yEnd + 0.5).floorToDouble(); } conicTo(xStart, yStart, xEnd, yEnd, w); startTheta = endTheta; } } /// Appends up to four conic curves weighted to describe an oval of `radius` /// and rotated by `rotation` (measured in degrees and clockwise). /// /// The last path point is described by (px, py). /// /// The first curve begins from the last point in the path and the last ends /// at `arcEndDelta.dx + px` and `arcEndDelta.dy + py`. The curves follow a /// path in a direction determined by `clockwise` and `largeArc` /// in such a way that the sweep angle is always less than 360 degrees. /// /// A simple line is appended if either radii are zero, or, both /// `arcEndDelta.dx` and `arcEndDelta.dy` are zero. The radii are scaled to /// fit the last path point if both are greater than zero but too small to /// describe an arc. @override void relativeArcToPoint( ui.Offset arcEndDelta, { ui.Radius radius = ui.Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true, }) { assert(offsetIsValid(arcEndDelta)); assert(radiusIsValid(radius)); final int pointCount = pathRef.countPoints(); double lastPointX, lastPointY; if (pointCount == 0) { lastPointX = lastPointY = 0; } else { int pointIndex = (pointCount - 1) * 2; lastPointX = pathRef.points[pointIndex++]; lastPointY = pathRef.points[pointIndex]; } arcToPoint( ui.Offset(lastPointX + arcEndDelta.dx, lastPointY + arcEndDelta.dy), radius: radius, rotation: rotation, largeArc: largeArc, clockwise: clockwise); } /// Adds a new subpath that consists of a curve that forms the /// ellipse that fills the given rectangle. /// /// To add a circle, pass an appropriate rectangle as `oval`. /// [Rect.fromCircle] can be used to easily describe the circle's center /// [Offset] and radius. @override void addOval(ui.Rect oval) { _addOval(oval, SPathDirection.kCW, 0); } void _addOval(ui.Rect oval, int direction, int startIndex) { assert(rectIsValid(oval)); assert(direction != SPathDirection.kUnknown); final bool isOval = _hasOnlyMoveTos(); const double weight = SPath.scalarRoot2Over2; final double left = oval.left; final double right = oval.right; final double centerX = (left + right) / 2.0; final double top = oval.top; final double bottom = oval.bottom; final double centerY = (top + bottom) / 2.0; if (direction == SPathDirection.kCW) { moveTo(right, centerY); conicTo(right, bottom, centerX, bottom, weight); conicTo(left, bottom, left, centerY, weight); conicTo(left, top, centerX, top, weight); conicTo(right, top, right, centerY, weight); } else { moveTo(right, centerY); conicTo(right, top, centerX, top, weight); conicTo(left, top, left, centerY, weight); conicTo(left, bottom, centerX, bottom, weight); conicTo(right, bottom, right, centerY, weight); } close(); pathRef.setIsOval(isOval, direction == SPathDirection.kCCW, 0); _resetAfterEdit(); // AutoDisableDirectionCheck if (isOval) { _firstDirection = direction; } else { _firstDirection = SPathDirection.kUnknown; } } /// Appends arc to path, as the start of new contour. Arc added is part of /// ellipse bounded by oval, from startAngle through sweepAngle. Both /// startAngle and sweepAngle are measured in degrees, /// where zero degrees is aligned with the positive x-axis, /// and positive sweeps extends arc clockwise. /// /// If sweepAngle <= -360, or sweepAngle >= 360; and startAngle modulo 90 /// is nearly zero, append oval instead of arc. Otherwise, sweepAngle values /// are treated modulo 360, and arc may or may not draw depending on numeric /// rounding. @override void addArc(ui.Rect oval, double startAngle, double sweepAngle) { assert(rectIsValid(oval)); if (0 == sweepAngle) { return; } const double kFullCircleAngle = math.pi * 2; if (sweepAngle >= kFullCircleAngle || sweepAngle <= -kFullCircleAngle) { // We can treat the arc as an oval if it begins at one of our legal starting positions. final double startOver90 = startAngle / (math.pi / 2.0); final double startOver90I = (startOver90 + 0.5).floorToDouble(); final double error = startOver90 - startOver90I; if (SPath.nearlyEqual(error, 0)) { // Index 1 is at startAngle == 0. double startIndex = startOver90I + 1.0 % 4.0; startIndex = startIndex < 0 ? startIndex + 4.0 : startIndex; _addOval( oval, sweepAngle > 0 ? SPathDirection.kCW : SPathDirection.kCCW, startIndex.toInt()); return; } } arcTo(oval, startAngle, sweepAngle, true); } /// Adds a new subpath with a sequence of line segments that connect the given /// points. /// /// If `close` is true, a final line segment will be added that connects the /// last point to the first point. /// /// The `points` argument is interpreted as offsets from the origin. @override void addPolygon(List<ui.Offset> points, bool close) { final int pointCount = points.length; if (pointCount <= 0) { return; } final int pointIndex = pathRef.growForVerb(SPathVerb.kMove, 0); fLastMoveToIndex = pointIndex + 1; pathRef.setPoint(pointIndex, points[0].dx, points[0].dy); pathRef.growForRepeatedVerb(SPathVerb.kLine, pointCount - 1); for (int i = 1; i < pointCount; i++) { pathRef.setPoint(pointIndex + i, points[i].dx, points[i].dy); } if (close) { this.close(); } _resetAfterEdit(); _debugValidate(); } /// Adds a new subpath that consists of the straight lines and /// curves needed to form the rounded rectangle described by the /// argument. @override void addRRect(ui.RRect rrect) { _addRRect(rrect, SPathDirection.kCW, 6); } void _addRRect(ui.RRect rrect, int direction, int startIndex) { assert(rrectIsValid(rrect)); assert(direction != SPathDirection.kUnknown); final bool isRRect = _hasOnlyMoveTos(); final ui.Rect bounds = rrect.outerRect; if (rrect.isRect || rrect.isEmpty) { // degenerate(rect) => radii points are collapsing. addRectWithDirection(bounds, direction, (startIndex + 1) ~/ 2); } else if (isRRectOval(rrect)) { // degenerate(oval) => line points are collapsing. _addOval(bounds, direction, startIndex ~/ 2); } else { const double weight = SPath.scalarRoot2Over2; final double left = bounds.left; final double right = bounds.right; final double top = bounds.top; final double bottom = bounds.bottom; final double width = right - left; final double height = bottom - top; // Proportionally scale down all radii to fit. Find the minimum ratio // of a side and the radii on that side (for all four sides) and use // that to scale down _all_ the radii. This algorithm is from the // W3 spec (http://www.w3.org/TR/css3-background/) section 5.5 final double tlRadiusX = math.max(0, rrect.tlRadiusX); final double trRadiusX = math.max(0, rrect.trRadiusX); final double blRadiusX = math.max(0, rrect.blRadiusX); final double brRadiusX = math.max(0, rrect.brRadiusX); final double tlRadiusY = math.max(0, rrect.tlRadiusY); final double trRadiusY = math.max(0, rrect.trRadiusY); final double blRadiusY = math.max(0, rrect.blRadiusY); final double brRadiusY = math.max(0, rrect.brRadiusY); double scale = _computeMinScale(tlRadiusX, trRadiusX, width, 1.0); scale = _computeMinScale(blRadiusX, brRadiusX, width, scale); scale = _computeMinScale(tlRadiusY, trRadiusY, height, scale); scale = _computeMinScale(blRadiusY, brRadiusY, height, scale); // Inlined version of: moveTo(left, bottom - scale * blRadiusY); lineTo(left, top + scale * tlRadiusY); conicTo(left, top, left + scale * tlRadiusX, top, weight); lineTo(right - scale * trRadiusX, top); conicTo(right, top, right, top + scale * trRadiusY, weight); lineTo(right, bottom - scale * brRadiusY); conicTo(right, bottom, right - scale * brRadiusX, bottom, weight); lineTo(left + scale * blRadiusX, bottom); conicTo(left, bottom, left, bottom - scale * blRadiusY, weight); close(); // SkAutoDisableDirectionCheck. _firstDirection = isRRect ? direction : SPathDirection.kUnknown; pathRef.setIsRRect( isRRect, direction == SPathDirection.kCCW, startIndex % 8, rrect); } _debugValidate(); } /// Adds a new subpath that consists of the given `path` offset by the given /// `offset`. /// /// If `matrix4` is specified, the path will be transformed by this matrix /// after the matrix is translated by the given offset. The matrix is a 4x4 /// matrix stored in column major order. @override void addPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { addPathWithMode(path, offset.dx, offset.dy, matrix4 == null ? null : toMatrix32(matrix4), SPathAddPathMode.kAppend); } /// Adds a new subpath that consists of the given `path` offset by the given /// `offset`, and using the given [mode]. /// /// If `matrix4` is not null, the path will be transformed by this matrix /// after the matrix is translated by the given offset. void addPathWithMode(ui.Path path, double offsetX, double offsetY, Float32List? matrix4, int mode) { SurfacePath source = path as SurfacePath; if (source.pathRef.isEmpty) { return; } // Detect if we're trying to add ourself, set source to a copy. if (source.pathRef == pathRef) { source = SurfacePath.from(this); } final int previousPointCount = pathRef.countPoints(); // Fast path add points,verbs if matrix doesn't have perspective and // we are not extending. if (mode == SPathAddPathMode.kAppend && (matrix4 == null || _isSimple2dTransform(matrix4))) { pathRef.append(source.pathRef); } else { bool firstVerb = true; final PathRefIterator iter = PathRefIterator(source.pathRef); final Float32List outPts = Float32List(PathRefIterator.kMaxBufferSize); int verb; while ((verb = iter.next(outPts)) != SPath.kDoneVerb) { switch (verb) { case SPath.kMoveVerb: final double point0X = matrix4 == null ? outPts[0] + offsetX : (matrix4[0] * (outPts[0] + offsetX)) + (matrix4[4] * (outPts[1] + offsetY)) + matrix4[12]; final double point0Y = matrix4 == null ? outPts[1] + offsetY : (matrix4[1] * (outPts[0] + offsetX)) + (matrix4[5] * (outPts[1] + offsetY)) + matrix4[13] + offsetY; if (firstVerb && !pathRef.isEmpty) { assert(mode == SPathAddPathMode.kExtend); // In case last contour is closed inject move to. _injectMoveToIfNeeded(); double lastPointX; double lastPointY; if (previousPointCount == 0) { lastPointX = lastPointY = 0; } else { int listIndex = 2 * (previousPointCount - 1); lastPointX = pathRef.points[listIndex++]; lastPointY = pathRef.points[listIndex]; } // don't add lineTo if it is degenerate. if (fLastMoveToIndex <= 0 || (previousPointCount != 0) || lastPointX != point0X || lastPointY != point0Y) { lineTo(outPts[0], outPts[1]); } } else { moveTo(outPts[0], outPts[1]); } case SPath.kLineVerb: lineTo(outPts[2], outPts[3]); case SPath.kQuadVerb: _quadTo(outPts[2], outPts[3], outPts[4], outPts[5]); case SPath.kConicVerb: conicTo( outPts[2], outPts[3], outPts[4], outPts[5], iter.conicWeight); case SPath.kCubicVerb: cubicTo(outPts[2], outPts[3], outPts[4], outPts[5], outPts[6], outPts[7]); case SPath.kCloseVerb: close(); } firstVerb = false; } } // Shift [fLastMoveToIndex] by existing point count. if (source.fLastMoveToIndex >= 0) { fLastMoveToIndex = previousPointCount + source.fLastMoveToIndex; } // Translate/transform all points. final int newPointCount = pathRef.countPoints(); final Float32List points = pathRef.points; for (int p = previousPointCount * 2; p < (newPointCount * 2); p += 2) { if (matrix4 == null) { points[p] += offsetX; points[p + 1] += offsetY; } else { final double x = points[p]; final double y = points[p + 1]; points[p] = (matrix4[0] * x) + (matrix4[4] * y) + (matrix4[12] + offsetX); points[p + 1] = (matrix4[1] * x) + (matrix4[5] * y) + (matrix4[13] + offsetY); } } _resetAfterEdit(); } /// Adds the given path to this path by extending the current segment of this /// path with the first segment of the given path. /// /// If `matrix4` is specified, the path will be transformed by this matrix /// after the matrix is translated by the given `offset`. The matrix is a 4x4 /// matrix stored in column major order. @override void extendWithPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { assert(offsetIsValid(offset)); addPathWithMode(path, offset.dx, offset.dy, matrix4 == null ? null : toMatrix32(matrix4), SPathAddPathMode.kExtend); } /// Tests to see if the given point is within the path. (That is, whether the /// point would be in the visible portion of the path if the path was used /// with [Canvas.clipPath].) /// /// The `point` argument is interpreted as an offset from the origin. /// /// Returns true if the point is in the path, and false otherwise. /// /// Note: Not very efficient, it creates a canvas, plays path and calls /// Context2D isPointInPath. If performance becomes issue, retaining /// RawRecordingCanvas can remove create/remove rootElement cost. @override bool contains(ui.Offset point) { assert(offsetIsValid(point)); if (pathRef.isEmpty) { return false; } // Check bounds including right/bottom. final ui.Rect bounds = getBounds(); final double x = point.dx; final double y = point.dy; if (x < bounds.left || y < bounds.top || x > bounds.right || y > bounds.bottom) { return false; } final PathWinding windings = PathWinding(pathRef, point.dx, point.dy); final bool evenOddFill = ui.PathFillType.evenOdd == _fillType; int w = windings.w; if (evenOddFill) { w &= 1; } if (w != 0) { return true; } final int onCurveCount = windings.onCurveCount; if (onCurveCount <= 1) { return onCurveCount != 0; } if ((onCurveCount & 1) != 0 || evenOddFill) { return (onCurveCount & 1) != 0; } // If the point touches an even number of curves, and the fill is winding, // check for coincidence. Count coincidence as places where the on curve // points have identical tangents. final PathIterator iter = PathIterator(pathRef, true); final Float32List buffer = Float32List(8 + 10); final List<ui.Offset> tangents = <ui.Offset>[]; bool done = false; do { final int oldCount = tangents.length; switch (iter.next(buffer)) { case SPath.kMoveVerb: case SPath.kCloseVerb: break; case SPath.kLineVerb: tangentLine(buffer, x, y, tangents); case SPath.kQuadVerb: tangentQuad(buffer, x, y, tangents); case SPath.kConicVerb: tangentConic(buffer, x, y, iter.conicWeight, tangents); case SPath.kCubicVerb: tangentCubic(buffer, x, y, tangents); case SPath.kDoneVerb: done = true; } if (tangents.length > oldCount) { final int last = tangents.length - 1; final ui.Offset tangent = tangents[last]; if (SPath.nearlyEqual(lengthSquaredOffset(tangent), 0)) { tangents.removeAt(last); } else { for (int index = 0; index < last; ++index) { final ui.Offset test = tangents[index]; final double crossProduct = test.dx * tangent.dy - test.dy * tangent.dx; if (SPath.nearlyEqual(crossProduct, 0) && SPath.scalarSignedAsInt(tangent.dx * test.dx) <= 0 && SPath.scalarSignedAsInt(tangent.dy * test.dy) <= 0) { final ui.Offset offset = tangents.removeAt(last); if (index != tangents.length) { tangents[index] = offset; } break; } } } } } while (!done); return tangents.isNotEmpty; } /// Returns a copy of the path with all the segments of every /// subpath translated by the given offset. @override SurfacePath shift(ui.Offset offset) => SurfacePath.shiftedFrom(this, offset.dx, offset.dy); /// Returns a copy of the path with all the segments of every /// sub path transformed by the given matrix. @override SurfacePath transform(Float64List matrix4) { final SurfacePath newPath = SurfacePath.from(this); newPath._transform(matrix4); return newPath; } void _transform(Float64List m) { pathRef.startEdit(); final int pointCount = pathRef.countPoints(); final Float32List points = pathRef.points; final int len = pointCount * 2; for (int i = 0; i < len; i += 2) { final double x = points[i]; final double y = points[i + 1]; final double w = 1.0 / ((m[3] * x) + (m[7] * y) + m[15]); final double transformedX = ((m[0] * x) + (m[4] * y) + m[12]) * w; final double transformedY = ((m[1] * x) + (m[5] * y) + m[13]) * w; points[i] = transformedX; points[i + 1] = transformedY; } // TODO(ferhat): optimize for axis aligned or scale/translate type transforms. _convexityType = SPathConvexityType.kUnknown; } void setConvexityType(int value) { _convexityType = value; } int _setComputedConvexity(int value) { assert(value != SPathConvexityType.kUnknown); setConvexityType(value); return value; } /// Returns the convexity type, computing if needed. Never returns kUnknown. int get convexityType { if (_convexityType != SPathConvexityType.kUnknown) { return _convexityType; } return _internalGetConvexity(); } /// Returns the current convexity type, skips computing if unknown. /// /// Provides a signal to path users if convexity has been calculated in /// which case _firstDirection is a valid result. int getConvexityTypeOrUnknown() => _convexityType; /// Returns true if the path is convex. If necessary, it will first compute /// the convexity. bool get isConvex => SPathConvexityType.kConvex == convexityType; // Computes convexity and first direction. int _internalGetConvexity() { final Float32List pts = Float32List(20); PathIterator iter = PathIterator(pathRef, true); // Check to see if path changes direction more than three times as quick // concave test. int pointCount = pathRef.countPoints(); // Last moveTo index may exceed point count if data comes from fuzzer. if (0 < fLastMoveToIndex && fLastMoveToIndex < pointCount) { pointCount = fLastMoveToIndex; } if (pointCount > 3) { int pointIndex = 0; // only consider the last of the initial move tos while (SPath.kMoveVerb == iter.next(pts)) { pointIndex++; } --pointIndex; final int convexity = Convexicator.bySign(pathRef, pointIndex, pointCount - pointIndex); if (SPathConvexityType.kConcave == convexity) { setConvexityType(SPathConvexityType.kConcave); return SPathConvexityType.kConcave; } else if (SPathConvexityType.kUnknown == convexity) { return SPathConvexityType.kUnknown; } iter = PathIterator(pathRef, true); } else if (!pathRef.isFinite) { return SPathConvexityType.kUnknown; } // Path passed quick concave check, now compute actual convexity. int contourCount = 0; int count; final Convexicator state = Convexicator(); int verb; while ((verb = iter.next(pts)) != SPath.kDoneVerb) { switch (verb) { case SPath.kMoveVerb: // If we have more than 1 contour bail out. if (++contourCount > 1) { return _setComputedConvexity(SPathConvexityType.kConcave); } state.setMovePt(pts[0], pts[1]); count = 0; case SPath.kLineVerb: count = 1; case SPath.kQuadVerb: count = 2; case SPath.kConicVerb: count = 2; case SPath.kCubicVerb: count = 3; case SPath.kCloseVerb: if (!state.close()) { if (!state.isFinite) { return SPathConvexityType.kUnknown; } return _setComputedConvexity(SPathConvexityType.kConcave); } count = 0; default: return _setComputedConvexity(SPathConvexityType.kConcave); } final int len = count * 2; for (int i = 2; i <= len; i += 2) { if (!state.addPoint(pts[i], pts[i + 1])) { if (!state.isFinite) { return SPathConvexityType.kUnknown; } return _setComputedConvexity(SPathConvexityType.kConcave); } } } if (_firstDirection == SPathDirection.kUnknown) { if (state.firstDirection == SPathDirection.kUnknown && !pathRef.getBounds().isEmpty) { return _setComputedConvexity(state.reversals < 3 ? SPathConvexityType.kConvex : SPathConvexityType.kConcave); } _firstDirection = state.firstDirection; } _setComputedConvexity(SPathConvexityType.kConvex); return _convexityType; } /// Computes the bounding rectangle for this path. /// /// A path containing only axis-aligned points on the same straight line will /// have no area, and therefore `Rect.isEmpty` will return true for such a /// path. Consider checking `rect.width + rect.height > 0.0` instead, or /// using the [computeMetrics] API to check the path length. /// /// For many more elaborate paths, the bounds may be inaccurate. For example, /// when a path contains a circle, the points used to compute the bounds are /// the circle's implied control points, which form a square around the /// circle; if the circle has a transformation applied using [transform] then /// that square is rotated, and the (axis-aligned, non-rotated) bounding box /// therefore ends up grossly overestimating the actual area covered by the /// circle. // see https://skia.org/user/api/SkPath_Reference#SkPath_getBounds @override ui.Rect getBounds() { if (pathRef.isRRect != -1 || pathRef.isOval != -1) { return pathRef.getBounds(); } if (!pathRef.fBoundsIsDirty && pathRef.cachedBounds != null) { return pathRef.cachedBounds!; } bool ltrbInitialized = false; double left = 0.0, top = 0.0, right = 0.0, bottom = 0.0; double minX = 0.0, maxX = 0.0, minY = 0.0, maxY = 0.0; final PathRefIterator iter = PathRefIterator(pathRef); final Float32List points = pathRef.points; int verb; CubicBounds? cubicBounds; QuadBounds? quadBounds; ConicBounds? conicBounds; while ((verb = iter.nextIndex()) != SPath.kDoneVerb) { final int pIndex = iter.iterIndex; switch (verb) { case SPath.kMoveVerb: minX = maxX = points[pIndex]; minY = maxY = points[pIndex + 1]; case SPath.kLineVerb: minX = maxX = points[pIndex + 2]; minY = maxY = points[pIndex + 3]; case SPath.kQuadVerb: quadBounds ??= QuadBounds(); quadBounds.calculateBounds(points, pIndex); minX = quadBounds.minX; minY = quadBounds.minY; maxX = quadBounds.maxX; maxY = quadBounds.maxY; case SPath.kConicVerb: conicBounds ??= ConicBounds(); conicBounds.calculateBounds(points, iter.conicWeight, pIndex); minX = conicBounds.minX; minY = conicBounds.minY; maxX = conicBounds.maxX; maxY = conicBounds.maxY; case SPath.kCubicVerb: cubicBounds ??= CubicBounds(); cubicBounds.calculateBounds(points, pIndex); minX = cubicBounds.minX; minY = cubicBounds.minY; maxX = cubicBounds.maxX; maxY = cubicBounds.maxY; } if (!ltrbInitialized) { left = minX; right = maxX; top = minY; bottom = maxY; ltrbInitialized = true; } else { left = math.min(left, minX); right = math.max(right, maxX); top = math.min(top, minY); bottom = math.max(bottom, maxY); } } final ui.Rect newBounds = ltrbInitialized ? ui.Rect.fromLTRB(left, top, right, bottom) : ui.Rect.zero; pathRef.getBounds(); pathRef.cachedBounds = newBounds; return newBounds; } /// Creates a [PathMetrics] object for this path. /// /// If `forceClosed` is set to true, the contours of the path will be measured /// as if they had been closed, even if they were not explicitly closed. @override SurfacePathMetrics computeMetrics({bool forceClosed = false}) { return SurfacePathMetrics(pathRef, forceClosed); } /// Detects if path is rounded rectangle. /// /// Returns rounded rectangle or null. /// /// Used for web optimization of physical shape represented as /// a persistent div. ui.RRect? toRoundedRect() => pathRef.getRRect(); /// Detects if path is simple rectangle. /// /// Returns rectangle or null. /// /// Used for web optimization of physical shape represented as /// a persistent div. !Warning it does not detect if closed, don't use this /// for optimizing strokes. ui.Rect? toRect() => pathRef.getRect(); /// Detects if path is a vertical or horizontal line. /// /// Returns LTRB or null. /// /// Used for web optimization of physical shape represented as /// a persistent div. ui.Rect? toStraightLine() => pathRef.getStraightLine(); /// Detects if path is simple oval. /// /// Returns bounding rectangle or null. /// /// Used for web optimization of physical shape represented as /// a persistent div. ui.Rect? toCircle() => pathRef.isOval == -1 ? null : pathRef.getBounds(); /// Returns if Path is empty. /// Empty Path may have FillType but has no points, verbs or weights. /// Constructor, reset and rewind makes SkPath empty. bool get isEmpty => 0 == pathRef.countVerbs(); @override String toString() { String result = super.toString(); assert(() { final StringBuffer sb = StringBuffer(); sb.write('Path('); final PathRefIterator iter = PathRefIterator(pathRef); final Float32List points = pathRef.points; int verb; while ((verb = iter.nextIndex()) != SPath.kDoneVerb) { final int pIndex = iter.iterIndex; switch (verb) { case SPath.kMoveVerb: sb.write('MoveTo(${points[pIndex]}, ${points[pIndex + 1]})'); case SPath.kLineVerb: sb.write('LineTo(${points[pIndex + 2]}, ${points[pIndex + 3]})'); case SPath.kQuadVerb: sb.write('Quad(${points[pIndex + 2]}, ${points[pIndex + 3]},' ' ${points[pIndex + 3]}, ${points[pIndex + 4]})'); case SPath.kConicVerb: sb.write('Conic(${points[pIndex + 2]}, ${points[pIndex + 3]},' ' ${points[pIndex + 3]}, ${points[pIndex + 4]}, w = ${iter.conicWeight})'); case SPath.kCubicVerb: sb.write('Cubic(${points[pIndex + 2]}, ${points[pIndex + 3]},' ' ${points[pIndex + 3]}, ${points[pIndex + 4]}, ' ' ${points[pIndex + 5]}, ${points[pIndex + 6]})'); case SPath.kCloseVerb: sb.write('Close()'); } if (iter.peek() != SPath.kDoneVerb) { sb.write(' '); } } sb.write(')'); result = sb.toString(); return true; }()); return result; } } // Returns Offset if arc is lone point and should be approximated with // moveTo/lineTo. ui.Offset? _arcIsLonePoint(ui.Rect oval, double startAngle, double sweepAngle) { if (0 == sweepAngle && (0 == startAngle || 360.0 == startAngle)) { // This path can be used to move into and out of ovals. If not // treated as a special case the moves can distort the oval's // bounding box (and break the circle special case). return ui.Offset(oval.right, oval.center.dy); } return null; } // Computed scaling factor for opposing sides with corner radius given // a [limit] max width or height. double _computeMinScale( double radius1, double radius2, double limit, double scale) { final double totalRadius = radius1 + radius2; if (totalRadius <= limit) { // Radii fit within the limit so return existing scale factor. return scale; } return math.min(limit / totalRadius, scale); } bool _isSimple2dTransform(Float32List m) => m[15] == 1.0 && // start reading from the last element to eliminate range checks in subsequent reads. m[14] == 0.0 && // z translation is NOT simple // m[13] - y translation is simple // m[12] - x translation is simple m[11] == 0.0 && m[10] == 1.0 && m[9] == 0.0 && m[8] == 0.0 && m[7] == 0.0 && m[6] == 0.0 && // m[5] - scale y is simple // m[4] - 2D rotation is simple m[3] == 0.0 && m[2] == 0.0; // m[1] - 2D rotation is simple // m[0] - scale x is simple
engine/lib/web_ui/lib/src/engine/html/path/path.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/path/path.dart", "repo_id": "engine", "token_count": 24535 }
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. import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../../engine.dart' show FrameTimingRecorder, kProfileApplyFrame, kProfilePrerollFrame; import '../display.dart'; import '../dom.dart'; import '../picture.dart'; import '../profiler.dart'; import '../util.dart'; import '../vector_math.dart'; import 'backdrop_filter.dart'; import 'clip.dart'; import 'color_filter.dart'; import 'image_filter.dart'; import 'offset.dart'; import 'opacity.dart'; import 'path_to_svg_clip.dart'; import 'picture.dart'; import 'platform_view.dart'; import 'scene.dart'; import 'shader_mask.dart'; import 'surface.dart'; import 'transform.dart'; class SurfaceSceneBuilder implements ui.SceneBuilder { SurfaceSceneBuilder() { _surfaceStack.add(PersistedScene(_lastFrameScene)); } final List<PersistedContainerSurface> _surfaceStack = <PersistedContainerSurface>[]; /// The scene built by this scene builder. /// /// This getter should only be called after all surfaces are built. PersistedScene get _persistedScene { return _surfaceStack.first as PersistedScene; } /// The surface currently being built. PersistedContainerSurface get _currentSurface => _surfaceStack.last; T _pushSurface<T extends PersistedContainerSurface>(T surface) { // Only attempt to update if the update is requested and the surface is in // the live tree. if (surface.oldLayer != null) { assert(surface.oldLayer!.runtimeType == surface.runtimeType); assert(debugAssertSurfaceState( surface.oldLayer!, PersistedSurfaceState.active)); surface.oldLayer!.state = PersistedSurfaceState.pendingUpdate; } _adoptSurface(surface); _surfaceStack.add(surface); return surface; } /// Adds [surface] to the surface tree. /// /// This is used by tests. void debugAddSurface(PersistedSurface surface) { assert(() { _addSurface(surface); return true; }()); } void _addSurface(PersistedSurface surface) { _adoptSurface(surface); } void _adoptSurface(PersistedSurface surface) { _currentSurface.appendChild(surface); } /// Pushes an offset operation onto the operation stack. /// /// This is equivalent to [pushTransform] with a matrix with only translation. /// /// See [pop] for details about the operation stack. @override ui.OffsetEngineLayer pushOffset( double dx, double dy, { ui.OffsetEngineLayer? oldLayer, }) { return _pushSurface<PersistedOffset>( PersistedOffset(oldLayer as PersistedOffset?, dx, dy)); } /// Pushes a transform operation onto the operation stack. /// /// The objects are transformed by the given matrix before rasterization. /// /// See [pop] for details about the operation stack. @override ui.TransformEngineLayer pushTransform( Float64List matrix4, { ui.TransformEngineLayer? oldLayer, }) { if (matrix4.length != 16) { throw ArgumentError('"matrix4" must have 16 entries.'); } final Float32List matrix; if (_surfaceStack.length == 1) { // Top level transform contains view configuration to scale // scene to devicepixelratio. Use identity instead since CSS uses // logical device pixels. if (!ui_web.debugEmulateFlutterTesterEnvironment) { assert(matrix4[0] == EngineFlutterDisplay.instance.devicePixelRatio && matrix4[5] == EngineFlutterDisplay.instance.devicePixelRatio); } matrix = Matrix4.identity().storage; } else { matrix = toMatrix32(matrix4); } return _pushSurface<PersistedTransform>( PersistedTransform(oldLayer as PersistedTransform?, matrix)); } /// Pushes a rectangular clip operation onto the operation stack. /// /// Rasterization outside the given rectangle is discarded. /// /// 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]). @override ui.ClipRectEngineLayer pushClipRect( ui.Rect rect, { ui.Clip clipBehavior = ui.Clip.antiAlias, ui.ClipRectEngineLayer? oldLayer, }) { return _pushSurface<PersistedClipRect>( PersistedClipRect(oldLayer as PersistedClipRect?, rect, clipBehavior)); } /// Pushes a rounded-rectangular clip operation onto the operation stack. /// /// Rasterization outside the given rounded rectangle is discarded. /// /// See [pop] for details about the operation stack. @override ui.ClipRRectEngineLayer pushClipRRect( ui.RRect rrect, { ui.Clip? clipBehavior, ui.ClipRRectEngineLayer? oldLayer, }) { return _pushSurface<PersistedClipRRect>( PersistedClipRRect(oldLayer, rrect, clipBehavior)); } /// Pushes a path clip operation onto the operation stack. /// /// Rasterization outside the given path is discarded. /// /// See [pop] for details about the operation stack. @override ui.ClipPathEngineLayer pushClipPath( ui.Path path, { ui.Clip clipBehavior = ui.Clip.antiAlias, ui.ClipPathEngineLayer? oldLayer, }) { return _pushSurface<PersistedClipPath>( PersistedClipPath(oldLayer as PersistedClipPath?, path, clipBehavior)); } /// 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). /// /// See [pop] for details about the operation stack. @override ui.OpacityEngineLayer pushOpacity( int alpha, { ui.Offset offset = ui.Offset.zero, ui.OpacityEngineLayer? oldLayer, }) { return _pushSurface<PersistedOpacity>( PersistedOpacity(oldLayer as PersistedOpacity?, alpha, offset)); } /// 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. @override ui.ColorFilterEngineLayer pushColorFilter( ui.ColorFilter filter, { ui.ColorFilterEngineLayer? oldLayer, }) { return _pushSurface<PersistedColorFilter>( PersistedColorFilter(oldLayer as PersistedColorFilter?, filter)); } /// 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. @override ui.ImageFilterEngineLayer pushImageFilter( ui.ImageFilter filter, { ui.Offset offset = ui.Offset.zero, ui.ImageFilterEngineLayer? oldLayer, }) { return _pushSurface<PersistedImageFilter>( PersistedImageFilter(oldLayer as PersistedImageFilter?, filter, offset)); } /// Pushes a backdrop filter operation onto the operation stack. /// /// The given filter is applied to the current contents of the scene prior to /// rasterizing the child layers. /// /// The [blendMode] argument is required for [ui.SceneBuilder] compatibility, but is /// ignored by the DOM renderer. /// /// See [pop] for details about the operation stack. @override ui.BackdropFilterEngineLayer pushBackdropFilter( ui.ImageFilter filter, { ui.BlendMode blendMode = ui.BlendMode.srcOver, ui.BackdropFilterEngineLayer? oldLayer, }) { return _pushSurface<PersistedBackdropFilter>(PersistedBackdropFilter( oldLayer as PersistedBackdropFilter?, filter)); } /// 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. /// /// See [pop] for details about the operation stack. @override ui.ShaderMaskEngineLayer pushShaderMask( ui.Shader shader, ui.Rect maskRect, ui.BlendMode blendMode, { ui.ShaderMaskEngineLayer? oldLayer, ui.FilterQuality filterQuality = ui.FilterQuality.low, }) { return _pushSurface<PersistedShaderMask>(PersistedShaderMask( oldLayer as PersistedShaderMask?, shader, maskRect, blendMode, filterQuality)); } /// 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 [addToScene] for its children layers. @override void addRetained(ui.EngineLayer retainedLayer) { final PersistedContainerSurface retainedSurface = retainedLayer as PersistedContainerSurface; assert(debugAssertSurfaceState(retainedSurface, PersistedSurfaceState.active, PersistedSurfaceState.released, )); retainedSurface.tryRetain(); _adoptSurface(retainedSurface); } /// 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. @override void pop() { assert(_surfaceStack.isNotEmpty); _surfaceStack.removeLast(); } /// 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 /// [FlutterView.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. @override void addPerformanceOverlay(int enabledOptions, ui.Rect bounds) { _addPerformanceOverlay( enabledOptions, bounds.left, bounds.right, bounds.top, bounds.bottom); } /// Whether we've already warned the user about the lack of the performance /// overlay or not. /// /// We use this to avoid spamming the console with redundant warning messages. static bool _didWarnAboutPerformanceOverlay = false; void _addPerformanceOverlay( int enabledOptions, double left, double right, double top, double bottom, ) { if (!_didWarnAboutPerformanceOverlay) { _didWarnAboutPerformanceOverlay = true; printWarning("The performance overlay isn't supported on the web"); } } /// Adds a [Picture] to the scene. /// /// The picture is rasterized at the given offset. @override void addPicture( ui.Offset offset, ui.Picture picture, { bool isComplexHint = false, bool willChangeHint = false, }) { int hints = 0; if (isComplexHint) { hints |= 1; } if (willChangeHint) { hints |= 2; } _addSurface(PersistedPicture( offset.dx, offset.dy, picture as EnginePicture, hints)); } /// Adds a backend texture to the scene. /// /// The texture is scaled to the given size and rasterized at the given /// offset. @override void addTexture( int textureId, { ui.Offset offset = ui.Offset.zero, double width = 0.0, double height = 0.0, bool freeze = false, ui.FilterQuality filterQuality = ui.FilterQuality.low, }) { _addTexture(offset.dx, offset.dy, width, height, textureId, filterQuality); } void _addTexture(double dx, double dy, double width, double height, int textureId, ui.FilterQuality filterQuality) { // In test mode, allow this to be a no-op. if (!ui_web.debugEmulateFlutterTesterEnvironment) { throw UnimplementedError('Textures are not supported in Flutter Web'); } } /// Adds a platform view (e.g an iOS UIView) to the scene. /// /// Only supported on iOS, this is currently a no-op on other platforms. /// /// 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. @override void addPlatformView( int viewId, { ui.Offset offset = ui.Offset.zero, double width = 0.0, double height = 0.0, }) { _addPlatformView(offset.dx, offset.dy, width, height, viewId); } void _addPlatformView( double dx, double dy, double width, double height, int viewId, ) { _addSurface(PersistedPlatformView(viewId, dx, dy, width, height)); } /// 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. @override 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). @override void setCheckerboardRasterCacheImages(bool checkerboard) {} /// Sets whether the compositor should checkerboard layers that are rendered /// to offscreen bitmaps. /// /// This is only useful for debugging purposes. @override void setCheckerboardOffscreenLayers(bool checkerboard) {} /// The scene recorded in the last frame. /// /// This is a surface tree that holds onto the DOM elements that can be reused /// on the next frame. static PersistedScene? _lastFrameScene; /// Returns the computed persisted scene graph recorded in the last frame. /// /// This is only available in debug mode. It returns `null` in profile and /// release modes. static PersistedScene? get debugLastFrameScene { PersistedScene? result; assert(() { result = _lastFrameScene; return true; }()); return result; } /// Discards information about previously rendered frames, including DOM /// elements and cached canvases. /// /// After calling this function new canvases will be created for the /// subsequent scene. This is useful when tests need predictable canvas /// sizes. If the cache is not cleared, then canvases allocated in one test /// may be reused in another test. static void debugForgetFrameScene() { _lastFrameScene?.rootElement?.remove(); _lastFrameScene = null; resetSvgClipIds(); recycledCanvases.clear(); } /// 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. @override SurfaceScene build() { // "Build finish" and "raster start" happen back-to-back because we // render on the same thread, so there's no overhead from hopping to // another thread. // // In the HTML renderer we time the beginning of the rasterization phase // (counter-intuitively) in SceneBuilder.build because DOM updates happen // here. This is different from CanvasKit. final FrameTimingRecorder? recorder = FrameTimingRecorder.frameTimingsEnabled ? FrameTimingRecorder() : null; recorder?.recordBuildFinish(); recorder?.recordRasterStart(); timeAction<void>(kProfilePrerollFrame, () { while (_surfaceStack.length > 1) { // Auto-pop layers that were pushed without a corresponding pop. pop(); } _persistedScene.preroll(PrerollSurfaceContext()); }); return timeAction<SurfaceScene>(kProfileApplyFrame, () { if (_lastFrameScene == null) { _persistedScene.build(); } else { _persistedScene.update(_lastFrameScene!); } commitScene(_persistedScene); _lastFrameScene = _persistedScene; return SurfaceScene(_persistedScene.rootElement, timingRecorder: recorder); }); } /// Set properties on the linked scene. These properties include its bounds, /// as well as whether it can be the target of focus events or not. @override void setProperties( double width, double height, double insetTop, double insetRight, double insetBottom, double insetLeft, bool focusable, ) { throw UnimplementedError(); } }
engine/lib/web_ui/lib/src/engine/html/scene_builder.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/scene_builder.dart", "repo_id": "engine", "token_count": 5989 }
311
// 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'; // Some APIs we need on typed arrays that are not exposed by the dart sdk yet extension TypedArrayExtension on JSTypedArray { external JSTypedArray slice(JSNumber start, JSNumber end); external void set(JSTypedArray source, JSNumber start); external JSNumber get length; } // These are constructors on `Uint8Array` that we need that aren't exposed in // the dart sdk yet @JS('Uint8Array') @staticInterop class JSUint8Array1 { external factory JSUint8Array1._create1(JSAny bufferOrLength); external factory JSUint8Array1._create3( JSArrayBuffer buffer, JSNumber start, JSNumber length, ); } JSUint8Array createUint8ArrayFromBuffer(JSArrayBuffer buffer) => JSUint8Array1._create1(buffer) as JSUint8Array; JSUint8Array createUint8ArrayFromSubBuffer( JSArrayBuffer buffer, int start, int length, ) => JSUint8Array1._create3(buffer, start.toJS, length.toJS) as JSUint8Array; JSUint8Array createUint8ArrayFromLength(int length) => JSUint8Array1._create1(length.toJS) as JSUint8Array;
engine/lib/web_ui/lib/src/engine/js_interop/js_typed_data.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/js_interop/js_typed_data.dart", "repo_id": "engine", "token_count": 399 }
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 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../dom.dart'; import '../util.dart'; import 'slots.dart'; /// This class handles the lifecycle of Platform Views in the DOM of a Flutter Web App. /// /// There are three important parts of Platform Views. This class manages two of /// them: /// /// * `factories`: The functions used to render the contents of any given Platform /// View by its `viewType`. /// * `contents`: The result [DomElement] of calling a `factory` function. /// /// The third part is `slots`, which are created on demand by the /// [createPlatformViewSlot] function. /// /// This class keeps a registry of `factories`, `contents` so the framework can /// CRUD Platform Views as needed, regardless of the rendering backend. class PlatformViewManager { PlatformViewManager() { // Register some default factories. registerFactory( ui_web.PlatformViewRegistry.defaultVisibleViewType, _defaultFactory, ); registerFactory( ui_web.PlatformViewRegistry.defaultInvisibleViewType, _defaultFactory, isVisible: false, ); } /// The shared instance of PlatformViewManager shared across the engine to handle /// rendering of PlatformViews into the web app. static PlatformViewManager instance = PlatformViewManager(); // The factory functions, indexed by the viewType final Map<String, Function> _factories = <String, Function>{}; // The references to content tags, indexed by their framework-given ID. final Map<int, DomElement> _contents = <int, DomElement>{}; final Set<String> _invisibleViews = <String>{}; final Map<int, String> _viewIdToType = <int, String>{}; /// Returns `true` if the passed in `viewType` has been registered before. /// /// See [registerFactory] to understand how factories are registered. bool knowsViewType(String viewType) { return _factories.containsKey(viewType); } /// Returns `true` if the passed in `viewId` has been rendered (and not disposed) before. /// /// See [renderContent] and [createPlatformViewSlot] to understand how platform views are /// rendered. bool knowsViewId(int viewId) { return _contents.containsKey(viewId); } /// Returns the cached contents of [viewId], to be injected into the DOM. /// /// This is only used by the active `Renderer` object when a platform view needs /// to be injected in the DOM, through `FlutterView.DomManager.injectPlatformView`. /// /// This may return null, if [renderContent] was not called before this. The /// framework seems to allow/need this for some tests, so it is allowed here /// as well. /// /// App programmers should not access this directly, and instead use [getViewById]. DomElement? getSlottedContent(int viewId) { return _contents[viewId]; } /// Returns the HTML element created by a registered factory for [viewId]. /// /// Throws an [AssertionError] if [viewId] hasn't been rendered before. DomElement getViewById(int viewId) { assert(knowsViewId(viewId), 'No view has been rendered for viewId: $viewId'); // `_contents[viewId]` is the <flt-platform-view> element created by us. The // first (and only) child of that is the element created by the user-supplied // factory function. return _contents[viewId]!.firstElementChild!; } /// Registers a `factoryFunction` that knows how to render a Platform View of `viewType`. /// /// `viewType` is selected by the programmer, but it can't be overridden once /// it's been set. /// /// `factoryFunction` needs to be a [PlatformViewFactory]. bool registerFactory(String viewType, Function factoryFunction, {bool isVisible = true}) { assert( factoryFunction is ui_web.PlatformViewFactory || factoryFunction is ui_web.ParameterizedPlatformViewFactory, 'Factory signature is invalid. Expected either ' '{${ui_web.PlatformViewFactory}} or {${ui_web.ParameterizedPlatformViewFactory}} ' 'but got: {${factoryFunction.runtimeType}}', ); if (_factories.containsKey(viewType)) { return false; } _factories[viewType] = factoryFunction; if (!isVisible) { _invisibleViews.add(viewType); } return true; } /// Creates the HTML markup for the `contents` of a Platform View. /// /// The result of this call is cached in the `_contents` Map, so the active /// renderer can inject it as needed. /// /// The resulting DOM for the `contents` of a Platform View looks like this: /// /// ```html /// <flt-platform-view id="flt-pv-VIEW_ID" slot="..."> /// <arbitrary-html-elements /> /// </flt-platform-view-slot> /// ``` /// /// The `arbitrary-html-elements` are the result of the call to the user-supplied /// `factory` function for this Platform View (see [registerFactory]). /// /// The outer `flt-platform-view` tag is a simple wrapper that we add to have /// a place where to attach the `slot` property, that will tell the browser /// what `slot` tag will reveal this `contents`, **without modifying the returned /// html from the `factory` function**. DomElement renderContent( String viewType, int viewId, Object? params, ) { assert(knowsViewType(viewType), 'Attempted to render contents of unregistered viewType: $viewType'); final String slotName = getPlatformViewSlotName(viewId); _viewIdToType[viewId] = viewType; return _contents.putIfAbsent(viewId, () { final DomElement wrapper = domDocument .createElement('flt-platform-view') ..id = getPlatformViewDomId(viewId) ..setAttribute('slot', slotName); final Function factoryFunction = _factories[viewType]!; final DomElement content; if (factoryFunction is ui_web.ParameterizedPlatformViewFactory) { content = factoryFunction(viewId, params: params) as DomElement; } else { factoryFunction as ui_web.PlatformViewFactory; content = factoryFunction(viewId) as DomElement; } _ensureContentCorrectlySized(content, viewType); wrapper.append(content); return wrapper; }); } /// Removes a PlatformView by its `viewId` from the manager, and from the DOM. /// /// Once a view has been cleared, calls to [knowsViewId] will fail, as if it had /// never been rendered before. void clearPlatformView(int viewId) { // Remove from our cache, and then from the DOM... _contents.remove(viewId)?.remove(); } /// Attempt to ensure that the contents of the user-supplied DOM element will /// fill the space allocated for this platform view by the framework. void _ensureContentCorrectlySized(DomElement content, String viewType) { // Scrutinize closely any other modifications to `content`. // We shouldn't modify users' returned `content` if at all possible. // Note there's also no getContent(viewId) function anymore, to prevent // from later modifications too. if (content.style.height.isEmpty) { printWarning('Height of Platform View type: [$viewType] may not be set.' ' Defaulting to `height: 100%`.\n' 'Set `style.height` to any appropriate value to stop this message.'); content.style.height = '100%'; } if (content.style.width.isEmpty) { printWarning('Width of Platform View type: [$viewType] may not be set.' ' Defaulting to `width: 100%`.\n' 'Set `style.width` to any appropriate value to stop this message.'); content.style.width = '100%'; } } /// Returns `true` if the given [viewId] is for an invisible platform view. bool isInvisible(int viewId) { final String? viewType = _viewIdToType[viewId]; return viewType != null && _invisibleViews.contains(viewType); } /// Returns `true` if the given [viewId] is a platform view with a visible /// component. bool isVisible(int viewId) => !isInvisible(viewId); /// Clears the state. Used in tests. void debugClear() { _contents.keys.toList().forEach(clearPlatformView); _factories.clear(); _contents.clear(); _invisibleViews.clear(); _viewIdToType.clear(); } } DomElement _defaultFactory( int viewId, { Object? params, }) { params!; params as Map<Object?, Object?>; return domDocument.createElement(params.readString('tagName')) ..style.width = '100%' ..style.height = '100%'; }
engine/lib/web_ui/lib/src/engine/platform_views/content_manager.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/platform_views/content_manager.dart", "repo_id": "engine", "token_count": 2753 }
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. import 'dart:async'; import 'dart:typed_data'; import '../dom.dart'; import '../services.dart'; import '../util.dart'; /// Determines the assertiveness level of the accessibility announcement. /// /// It is used to set the priority with which assistive technology should treat announcements. /// /// The order of this enum must match the order of the values in semantics_event.dart in framework. enum Assertiveness { polite, assertive, } /// Duration for which a live message will be present in the DOM for the screen /// reader to announce it. /// /// This was determined by trial and error with some extra buffer added. Duration liveMessageDuration = const Duration(milliseconds: 300); /// Sets [liveMessageDuration] to reduce the delay in tests. void setLiveMessageDurationForTest(Duration duration) { liveMessageDuration = duration; } /// Makes accessibility announcements using `aria-live` DOM elements. class AccessibilityAnnouncements { /// Creates a new instance with its own DOM elements used for announcements. factory AccessibilityAnnouncements({required DomElement hostElement}) { final DomHTMLElement politeElement = _createElement(Assertiveness.polite); final DomHTMLElement assertiveElement = _createElement(Assertiveness.assertive); hostElement.append(politeElement); hostElement.append(assertiveElement); return AccessibilityAnnouncements._(politeElement, assertiveElement); } AccessibilityAnnouncements._(this._politeElement, this._assertiveElement); /// A live region element with `aria-live` set to "polite", used to announce /// accouncements politely. final DomHTMLElement _politeElement; /// A live region element with `aria-live` set to "assertive", used to announce /// accouncements assertively. final DomHTMLElement _assertiveElement; /// Whether to append a non-breaking space to the end of the message /// before outputting it. /// /// It's used to work around a VoiceOver bug where announcing the same message /// repeatedly results in subsequent messages not being announced despite the /// fact that the previous announcement was already removed from the DOM a /// long while back. See https://github.com/flutter/flutter/issues/142250. bool _appendSpace = false; /// Looks up the element used to announce messages of the given [assertiveness]. DomHTMLElement ariaLiveElementFor(Assertiveness assertiveness) { switch (assertiveness) { case Assertiveness.polite: return _politeElement; case Assertiveness.assertive: return _assertiveElement; } } /// Makes an accessibity announcement from a message sent by the framework /// over the 'flutter/accessibility' channel. /// /// The encoded message is passed as [data], and will be decoded using [codec]. void handleMessage(StandardMessageCodec codec, ByteData? data) { final Map<dynamic, dynamic> inputMap = codec.decodeMessage(data) as Map<dynamic, dynamic>; final Map<dynamic, dynamic> dataMap = inputMap.readDynamicJson('data'); final String? message = dataMap.tryString('message'); if (message != null && message.isNotEmpty) { /// The default value for assertiveness is `polite`. final int assertivenessIndex = dataMap.tryInt('assertiveness') ?? 0; final Assertiveness assertiveness = Assertiveness.values[assertivenessIndex]; announce(message, assertiveness); } } /// Makes an accessibility announcement using an `aria-live` element. /// /// [message] is the text of the announcement. /// /// [assertiveness] controls how interruptive the announcement is. void announce(String message, Assertiveness assertiveness) { final DomHTMLElement ariaLiveElement = ariaLiveElementFor(assertiveness); final DomHTMLDivElement messageElement = createDomHTMLDivElement(); // See the doc-comment for [_appendSpace] for the rationale. messageElement.text = _appendSpace ? '$message\u00A0' : message; _appendSpace = !_appendSpace; ariaLiveElement.append(messageElement); Timer(liveMessageDuration, () => messageElement.remove()); } static DomHTMLElement _createElement(Assertiveness assertiveness) { final String ariaLiveValue = (assertiveness == Assertiveness.assertive) ? 'assertive' : 'polite'; final DomHTMLElement liveRegion = createDomElement('flt-announcement-$ariaLiveValue') as DomHTMLElement; liveRegion.style ..position = 'fixed' ..overflow = 'hidden' ..transform = 'translate(-99999px, -99999px)' ..width = '1px' ..height = '1px'; liveRegion.setAttribute('aria-live', ariaLiveValue); return liveRegion; } }
engine/lib/web_ui/lib/src/engine/semantics/accessibility.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/semantics/accessibility.dart", "repo_id": "engine", "token_count": 1380 }
314
// 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:collection'; import 'dart:typed_data'; abstract class _TypedDataBuffer<E> extends ListBase<E> { _TypedDataBuffer(List<E> buffer) : _buffer = buffer, _length = buffer.length; static const int _initialLength = 8; /// The underlying data buffer. /// /// This is always both a List<E> and a TypedData, which we don't have a type /// for here. For example, for a `Uint8Buffer`, this is a `Uint8List`. List<E> _buffer; /// Returns a view of [_buffer] as a [TypedData]. TypedData get _typedBuffer => _buffer as TypedData; /// The length of the list being built. int _length; @override int get length => _length; @override E operator [](int index) { if (index >= length) { throw RangeError.index(index, this); } return _buffer[index]; } @override void operator []=(int index, E value) { if (index >= length) { throw RangeError.index(index, this); } _buffer[index] = value; } @override set length(int newLength) { if (newLength < _length) { final E defaultValue = _defaultValue; for (int i = newLength; i < _length; i++) { _buffer[i] = defaultValue; } } else if (newLength > _buffer.length) { List<E> newBuffer; if (_buffer.isEmpty) { newBuffer = _createBuffer(newLength); } else { newBuffer = _createBiggerBuffer(newLength); } newBuffer.setRange(0, _length, _buffer); _buffer = newBuffer; } _length = newLength; } void _add(E value) { if (_length == _buffer.length) { _grow(_length); } _buffer[_length++] = value; } // We override the default implementation of `add` because it grows the list // by setting the length in increments of one. We want to grow by doubling // capacity in most cases. @override void add(E value) { _add(value); } /// Appends all objects of [values] to the end of this buffer. /// /// This adds values from [start] (inclusive) to [end] (exclusive) in /// [values]. If [end] is omitted, it defaults to adding all elements of /// [values] after [start]. /// /// The [start] value must be non-negative. The [values] iterable must have at /// least [start] elements, and if [end] is specified, it must be greater than /// or equal to [start] and [values] must have at least [end] elements. @override void addAll(Iterable<E> values, [int start = 0, int? end]) { RangeError.checkNotNegative(start, 'start'); if (end != null && start > end) { throw RangeError.range(end, start, null, 'end'); } _addAll(values, start, end); } /// Inserts all objects of [values] at position [index] in this list. /// /// This adds values from [start] (inclusive) to [end] (exclusive) in /// [values]. If [end] is omitted, it defaults to adding all elements of /// [values] after [start]. /// /// The [start] value must be non-negative. The [values] iterable must have at /// least [start] elements, and if [end] is specified, it must be greater than /// or equal to [start] and [values] must have at least [end] elements. @override void insertAll(int index, Iterable<E> values, [int start = 0, int? end]) { IndexError.check(index, _length + 1, indexable: this, name: 'index'); RangeError.checkNotNegative(start, 'start'); if (end != null) { if (start > end) { throw RangeError.range(end, start, null, 'end'); } if (start == end) { return; } } // If we're adding to the end of the list anyway, use [_addAll]. This lets // us avoid converting [values] into a list even if [end] is null, since we // can add values iteratively to the end of the list. We can't do so in the // center because copying the trailing elements every time is non-linear. if (index == _length) { _addAll(values, start, end); return; } if (end == null && values is List) { end = values.length; } if (end != null) { _insertKnownLength(index, values, start, end); return; } // Add elements at end, growing as appropriate, then put them back at // position [index] using flip-by-double-reverse. int writeIndex = _length; int skipCount = start; for (final E value in values) { if (skipCount > 0) { skipCount--; continue; } if (writeIndex == _buffer.length) { _grow(writeIndex); } _buffer[writeIndex++] = value; } if (skipCount > 0) { throw StateError('Too few elements'); } if (end != null && writeIndex < end) { throw RangeError.range(end, start, writeIndex, 'end'); } // Swap [index.._length) and [_length..writeIndex) by double-reversing. _reverse(_buffer, index, _length); _reverse(_buffer, _length, writeIndex); _reverse(_buffer, index, writeIndex); _length = writeIndex; return; } // Reverses the range [start..end) of buffer. static void _reverse(List<Object?> buffer, int start, int end) { end--; // Point to last element, not after last element. while (start < end) { final Object? first = buffer[start]; final Object? last = buffer[end]; buffer[end] = first; buffer[start] = last; start++; end--; } } /// Does the same thing as [addAll]. /// /// This allows [addAll] and [insertAll] to share implementation without a /// subclass unexpectedly overriding both when it intended to only override /// [addAll]. void _addAll(Iterable<E> values, [int start = 0, int? end]) { if (values is List<E>) { end ??= values.length; } // If we know the length of the segment to add, do so with [addRange]. This // way we know how much to grow the buffer in advance, and it may be even // more efficient for typed data input. if (end != null) { _insertKnownLength(_length, values, start, end); return; } // Otherwise, just add values one at a time. int i = 0; for (final E value in values) { if (i >= start) { add(value); } i++; } if (i < start) { throw StateError('Too few elements'); } } /// Like [insertAll], but with a guaranteed non-`null` [start] and [end]. void _insertKnownLength(int index, Iterable<E> values, int start, int end) { if (start > values.length || end > values.length) { throw StateError('Too few elements'); } final int valuesLength = end - start; final int newLength = _length + valuesLength; _ensureCapacity(newLength); _buffer.setRange( index + valuesLength, _length + valuesLength, _buffer, index); _buffer.setRange(index, index + valuesLength, values, start); _length = newLength; } @override void insert(int index, E element) { if (index < 0 || index > _length) { throw RangeError.range(index, 0, _length); } if (_length < _buffer.length) { _buffer.setRange(index + 1, _length + 1, _buffer, index); _buffer[index] = element; _length++; return; } final List<E> newBuffer = _createBiggerBuffer(null); newBuffer.setRange(0, index, _buffer); newBuffer.setRange(index + 1, _length + 1, _buffer, index); newBuffer[index] = element; _length++; _buffer = newBuffer; } /// Ensures that [_buffer] is at least [requiredCapacity] long, /// /// Grows the buffer if necessary, preserving existing data. void _ensureCapacity(int requiredCapacity) { if (requiredCapacity <= _buffer.length) { return; } final List<E> newBuffer = _createBiggerBuffer(requiredCapacity); newBuffer.setRange(0, _length, _buffer); _buffer = newBuffer; } /// Create a bigger buffer. /// /// This method determines how much bigger a bigger buffer should /// be. If [requiredCapacity] is not null, it will be at least that /// size. It will always have at least have double the capacity of /// the current buffer. List<E> _createBiggerBuffer(int? requiredCapacity) { int newLength = _buffer.length * 2; if (requiredCapacity != null && newLength < requiredCapacity) { newLength = requiredCapacity; } else if (newLength < _initialLength) { newLength = _initialLength; } return _createBuffer(newLength); } /// Grows the buffer. /// /// This copies the first [length] elements into the new buffer. void _grow(int length) { _buffer = _createBiggerBuffer(null)..setRange(0, length, _buffer); } @override void setRange(int start, int end, Iterable<E> source, [int skipCount = 0]) { if (end > _length) { throw RangeError.range(end, 0, _length); } _setRange(start, end, source, skipCount); } /// Like [setRange], but with no bounds checking. void _setRange(int start, int end, Iterable<E> source, int skipCount) { if (source is _TypedDataBuffer<E>) { _buffer.setRange(start, end, source._buffer, skipCount); } else { _buffer.setRange(start, end, source, skipCount); } } // TypedData. int get elementSizeInBytes => _typedBuffer.elementSizeInBytes; int get lengthInBytes => _length * _typedBuffer.elementSizeInBytes; int get offsetInBytes => _typedBuffer.offsetInBytes; /// Returns the underlying [ByteBuffer]. /// /// The returned buffer may be replaced by operations that change the [length] /// of this list. /// /// The buffer may be larger than [lengthInBytes] bytes, but never smaller. ByteBuffer get buffer => _typedBuffer.buffer; // Specialization for the specific type. // Return zero for integers, 0.0 for floats, etc. // Used to fill buffer when changing length. E get _defaultValue; // Create a new typed list to use as buffer. List<E> _createBuffer(int size); } abstract class _IntBuffer extends _TypedDataBuffer<int> { _IntBuffer(super.buffer); @override int get _defaultValue => 0; } class Uint8Buffer extends _IntBuffer { Uint8Buffer([int initialLength = 0]) : super(Uint8List(initialLength)); @override Uint8List _createBuffer(int size) => Uint8List(size); }
engine/lib/web_ui/lib/src/engine/services/buffers.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/services/buffers.dart", "repo_id": "engine", "token_count": 3659 }
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. import 'dart:ffi'; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; enum PathDirection { clockwise, counterClockwise, } enum PathArcSize { small, large, } class SkwasmPath extends SkwasmObjectWrapper<RawPath> implements ui.Path { factory SkwasmPath() { return SkwasmPath.fromHandle(pathCreate()); } factory SkwasmPath.from(SkwasmPath source) { return SkwasmPath.fromHandle(pathCopy(source.handle)); } SkwasmPath.fromHandle(PathHandle handle) : super(handle, _registry); static final SkwasmFinalizationRegistry<RawPath> _registry = SkwasmFinalizationRegistry<RawPath>(pathDispose); @override ui.PathFillType get fillType => ui.PathFillType.values[pathGetFillType(handle)]; @override set fillType(ui.PathFillType fillType) => pathSetFillType(handle, fillType.index); @override void moveTo(double x, double y) => pathMoveTo(handle, x, y); @override void relativeMoveTo(double x, double y) => pathRelativeMoveTo(handle, x, y); @override void lineTo(double x, double y) => pathLineTo(handle, x, y); @override void relativeLineTo(double x, double y) => pathRelativeMoveTo(handle, x, y); @override void quadraticBezierTo(double x1, double y1, double x2, double y2) => pathQuadraticBezierTo(handle, x1, y1, x2, y2); @override void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2) => pathRelativeQuadraticBezierTo(handle, x1, y1, x2, y2); @override void cubicTo( double x1, double y1, double x2, double y2, double x3, double y3) => pathCubicTo(handle, x1, y1, x2, y2, x3, y3); @override void relativeCubicTo( double x1, double y1, double x2, double y2, double x3, double y3) => pathRelativeCubicTo(handle, x1, y1, x2, y2, x3, y3); @override void conicTo(double x1, double y1, double x2, double y2, double w) => pathConicTo(handle, x1, y1, x2, y2, w); @override void relativeConicTo(double x1, double y1, double x2, double y2, double w) => pathRelativeConicTo(handle, x1, y1, x2, y2, w); @override void arcTo( ui.Rect rect, double startAngle, double sweepAngle, bool forceMoveTo) { withStackScope((StackScope s) { pathArcToOval( handle, s.convertRectToNative(rect), ui.toDegrees(startAngle), ui.toDegrees(sweepAngle), forceMoveTo ); }); } @override void arcToPoint( ui.Offset arcEnd, { ui.Radius radius = ui.Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true, }) { final PathArcSize arcSize = largeArc ? PathArcSize.large : PathArcSize.small; final PathDirection pathDirection = clockwise ? PathDirection.clockwise : PathDirection.counterClockwise; pathArcToRotated( handle, radius.x, radius.y, ui.toDegrees(rotation), arcSize.index, pathDirection.index, arcEnd.dx, arcEnd.dy ); } @override void relativeArcToPoint( ui.Offset arcEndDelta, { ui.Radius radius = ui.Radius.zero, double rotation = 0.0, bool largeArc = false, bool clockwise = true, }) { final PathArcSize arcSize = largeArc ? PathArcSize.large : PathArcSize.small; final PathDirection pathDirection = clockwise ? PathDirection.clockwise : PathDirection.counterClockwise; pathRelativeArcToRotated( handle, radius.x, radius.y, ui.toDegrees(rotation), arcSize.index, pathDirection.index, arcEndDelta.dx, arcEndDelta.dy ); } @override void addRect(ui.Rect rect) { withStackScope((StackScope s) { pathAddRect(handle, s.convertRectToNative(rect)); }); } @override void addOval(ui.Rect rect) { withStackScope((StackScope s) { pathAddOval(handle, s.convertRectToNative(rect)); }); } @override void addArc(ui.Rect rect, double startAngle, double sweepAngle) { withStackScope((StackScope s) { pathAddArc( handle, s.convertRectToNative(rect), ui.toDegrees(startAngle), ui.toDegrees(sweepAngle) ); }); } @override void addPolygon(List<ui.Offset> points, bool close) { withStackScope((StackScope s) { pathAddPolygon(handle, s.convertPointArrayToNative(points), points.length, close); }); } @override void addRRect(ui.RRect rrect) { withStackScope((StackScope s) { pathAddRRect(handle, s.convertRRectToNative(rrect)); }); } @override void addPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { _addPath(path, offset, false, matrix4: matrix4); } @override void extendWithPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { _addPath(path, offset, true, matrix4: matrix4); } void _addPath(ui.Path path, ui.Offset offset, bool extend, {Float64List? matrix4}) { assert(path is SkwasmPath); withStackScope((StackScope s) { final Pointer<Float> convertedMatrix = s.convertMatrix4toSkMatrix(matrix4 ?? Matrix4.identity().toFloat64()); convertedMatrix[2] += offset.dx; convertedMatrix[5] += offset.dy; pathAddPath(handle, (path as SkwasmPath).handle, convertedMatrix, extend); }); } @override void close() => pathClose(handle); @override void reset() => pathReset(handle); @override bool contains(ui.Offset point) => pathContains(handle, point.dx, point.dy); @override ui.Path shift(ui.Offset offset) => transform(Matrix4.translationValues(offset.dx, offset.dy, 0.0).toFloat64()); @override ui.Path transform(Float64List matrix4) { return withStackScope((StackScope s) { final PathHandle newPathHandle = pathCopy(handle); pathTransform(newPathHandle, s.convertMatrix4toSkMatrix(matrix4)); return SkwasmPath.fromHandle(newPathHandle); }); } @override ui.Rect getBounds() { return withStackScope((StackScope s) { final Pointer<Float> rectBuffer = s.allocFloatArray(4); pathGetBounds(handle, rectBuffer); return s.convertRectFromNative(rectBuffer); }); } static SkwasmPath combine( ui.PathOperation operation, SkwasmPath path1, SkwasmPath path2) => SkwasmPath.fromHandle(pathCombine( operation.index, path1.handle, path2.handle)); @override ui.PathMetrics computeMetrics({bool forceClosed = false}) { return SkwasmPathMetrics(path: this, forceClosed: forceClosed); } }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/path.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/path.dart", "repo_id": "engine", "token_count": 2770 }
316
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:ffi'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; final class RawSurface extends Opaque {} typedef SurfaceHandle = Pointer<RawSurface>; final class RawRenderCallback extends Opaque {} typedef OnRenderCallbackHandle = Pointer<RawRenderCallback>; typedef CallbackId = int; @Native<SurfaceHandle Function()>(symbol: 'surface_create', isLeaf: true) external SurfaceHandle surfaceCreate(); @Native<UnsignedLong Function(SurfaceHandle)>(symbol: 'surface_getThreadId', isLeaf: true) external int surfaceGetThreadId(SurfaceHandle handle); @Native<Void Function(SurfaceHandle, OnRenderCallbackHandle)>( symbol: 'surface_setCallbackHandler', isLeaf: true) external void surfaceSetCallbackHandler( SurfaceHandle surface, OnRenderCallbackHandle callback, ); @Native<Void Function(SurfaceHandle)>( symbol: 'surface_destroy', isLeaf: true) external void surfaceDestroy(SurfaceHandle surface); @Native<Int32 Function(SurfaceHandle, Pointer<PictureHandle>, Int)>( symbol: 'surface_renderPictures', isLeaf: true) external CallbackId surfaceRenderPictures(SurfaceHandle surface, Pointer<PictureHandle> picture, int count); @Native<Int32 Function( SurfaceHandle, ImageHandle, Int )>(symbol: 'surface_rasterizeImage', isLeaf: true) external CallbackId surfaceRasterizeImage( SurfaceHandle handle, ImageHandle image, int format, );
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_surface.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_surface.dart", "repo_id": "engine", "token_count": 477 }
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. import 'dart:js_interop'; import 'dom.dart'; @JS() @staticInterop class SVGElement extends DomElement {} SVGElement createSVGElement(String tag) => domDocument.createElementNS('http://www.w3.org/2000/svg', tag) as SVGElement; @JS() @staticInterop class SVGGraphicsElement extends SVGElement {} @JS() @staticInterop class SVGSVGElement extends SVGGraphicsElement {} SVGSVGElement createSVGSVGElement() { final SVGElement el = createSVGElement('svg'); el.setAttribute('version', '1.1'); return el as SVGSVGElement; } extension SVGSVGElementExtension on SVGSVGElement { external SVGNumber createSVGNumber(); external SVGAnimatedLength? get height; external SVGAnimatedLength? get width; } @JS() @staticInterop class SVGClipPathElement extends SVGGraphicsElement {} SVGClipPathElement createSVGClipPathElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'clipPath') as SVGClipPathElement; @JS() @staticInterop class SVGDefsElement extends SVGGraphicsElement {} SVGDefsElement createSVGDefsElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'defs') as SVGDefsElement; @JS() @staticInterop class SVGGeometryElement extends SVGGraphicsElement {} @JS() @staticInterop class SVGPathElement extends SVGGeometryElement {} SVGPathElement createSVGPathElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'path') as SVGPathElement; @JS() @staticInterop class SVGFilterElement extends SVGElement {} extension SVGFilterElementExtension on SVGFilterElement { external SVGAnimatedEnumeration? get filterUnits; external SVGAnimatedLength? get height; external SVGAnimatedLength? get width; external SVGAnimatedLength? get x; external SVGAnimatedLength? get y; } SVGFilterElement createSVGFilterElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'filter') as SVGFilterElement; @JS() @staticInterop class SVGAnimatedLength {} extension SVGAnimatedLengthExtension on SVGAnimatedLength { external SVGLength? get baseVal; } @JS() @staticInterop class SVGLength {} extension SVGLengthExtension on SVGLength { @JS('valueAsString') external set _valueAsString(JSString? value); set valueAsString(String? value) => _valueAsString = value?.toJS; @JS('newValueSpecifiedUnits') external JSVoid _newValueSpecifiedUnits(JSNumber unitType, JSNumber valueInSpecifiedUnits); void newValueSpecifiedUnits(int unitType, num valueInSpecifiedUnits) => _newValueSpecifiedUnits(unitType.toJS, valueInSpecifiedUnits.toJS); } const int svgLengthTypeNumber = 1; @JS() @staticInterop class SVGAnimatedEnumeration {} extension SVGAnimatedEnumerationExtenson on SVGAnimatedEnumeration { @JS('baseVal') external set _baseVal(JSNumber? value); set baseVal(int? value) => _baseVal = value?.toJS; } @JS() @staticInterop class SVGFEColorMatrixElement extends SVGElement {} extension SVGFEColorMatrixElementExtension on SVGFEColorMatrixElement { external SVGAnimatedEnumeration? get type; external SVGAnimatedString? get result; external SVGAnimatedNumberList? get values; } SVGFEColorMatrixElement createSVGFEColorMatrixElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feColorMatrix') as SVGFEColorMatrixElement; @JS() @staticInterop class SVGFEFloodElement extends SVGElement {} extension SVGFEFloodElementExtension on SVGFEFloodElement { external SVGAnimatedString? get result; } SVGFEFloodElement createSVGFEFloodElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feFlood') as SVGFEFloodElement; @JS() @staticInterop class SVGFEBlendElement extends SVGElement {} extension SVGFEBlendElementExtension on SVGFEBlendElement { external SVGAnimatedString? get in1; external SVGAnimatedString? get in2; external SVGAnimatedEnumeration? get mode; } SVGFEBlendElement createSVGFEBlendElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feBlend') as SVGFEBlendElement; @JS() @staticInterop class SVGFEImageElement extends SVGElement {} extension SVGFEImageElementExtension on SVGFEImageElement { external SVGAnimatedLength? get height; external SVGAnimatedLength? get width; external SVGAnimatedString? get result; external SVGAnimatedLength? get x; external SVGAnimatedLength? get y; external SVGAnimatedString? get href; } SVGFEImageElement createSVGFEImageElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feImage') as SVGFEImageElement; @JS() @staticInterop class SVGFECompositeElement extends SVGElement {} SVGFECompositeElement createSVGFECompositeElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feComposite') as SVGFECompositeElement; extension SVGFEBlendCompositeExtension on SVGFECompositeElement { external SVGAnimatedString? get in1; external SVGAnimatedString? get in2; external SVGAnimatedNumber? get k1; external SVGAnimatedNumber? get k2; external SVGAnimatedNumber? get k3; external SVGAnimatedNumber? get k4; external SVGAnimatedEnumeration? get operator; external SVGAnimatedString? get result; } @JS() @staticInterop class SVGAnimatedString {} extension SVGAnimatedStringExtension on SVGAnimatedString { @JS('baseVal') external set _baseVal(JSString? value); set baseVal(String? value) => _baseVal = value?.toJS; } @JS() @staticInterop class SVGAnimatedNumber {} extension SVGAnimatedNumberExtension on SVGAnimatedNumber { @JS('baseVal') external set _baseVal(JSNumber? value); set baseVal(num? value) => _baseVal = value?.toJS; } @JS() @staticInterop class SVGAnimatedNumberList {} extension SVGAnimatedNumberListExtension on SVGAnimatedNumberList { external SVGNumberList? get baseVal; } @JS() @staticInterop class SVGNumberList {} extension SVGNumberListExtension on SVGNumberList { external SVGNumber appendItem(SVGNumber newItem); } @JS() @staticInterop class SVGNumber {} extension SVGNumberExtension on SVGNumber { @JS('value') external set _value(JSNumber? value); set value(num? v) => _value = v?.toJS; }
engine/lib/web_ui/lib/src/engine/svg.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/svg.dart", "repo_id": "engine", "token_count": 2110 }
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. import '../util.dart'; import 'word_break_properties.dart'; enum _FindBreakDirection { forward(step: 1), backward(step: -1); const _FindBreakDirection({required this.step}); final int step; } /// [WordBreaker] exposes static methods to identify word boundaries. abstract final class WordBreaker { /// It starts from [index] and tries to find the next word boundary in [text]. static int nextBreakIndex(String text, int index) => _findBreakIndex(_FindBreakDirection.forward, text, index); /// It starts from [index] and tries to find the previous word boundary in /// [text]. static int prevBreakIndex(String text, int index) => _findBreakIndex(_FindBreakDirection.backward, text, index); static int _findBreakIndex( _FindBreakDirection direction, String text, int index, ) { int i = index; while (i >= 0 && i <= text.length) { i += direction.step; if (_isBreak(text, i)) { break; } } return clampInt(i, 0, text.length); } /// Find out if there's a word break between [index - 1] and [index]. /// http://unicode.org/reports/tr29/#Word_Boundary_Rules static bool _isBreak(String? text, int index) { // Break at the start and end of text. // WB1: sot ÷ Any // WB2: Any ÷ eot if (index <= 0 || index >= text!.length) { return true; } // Do not break inside surrogate pair if (_isUtf16Surrogate(text.codeUnitAt(index - 1))) { return false; } final WordCharProperty immediateRight = wordLookup.find(text, index); WordCharProperty immediateLeft = wordLookup.find(text, index - 1); // Do not break within CRLF. // WB3: CR × LF if (immediateLeft == WordCharProperty.CR && immediateRight == WordCharProperty.LF) { return false; } // Otherwise break before and after Newlines (including CR and LF) // WB3a: (Newline | CR | LF) ÷ if (_oneOf( immediateLeft, WordCharProperty.Newline, WordCharProperty.CR, WordCharProperty.LF, )) { return true; } // WB3b: ÷ (Newline | CR | LF) if (_oneOf( immediateRight, WordCharProperty.Newline, WordCharProperty.CR, WordCharProperty.LF, )) { return true; } // WB3c: ZWJ × \p{Extended_Pictographic} // TODO(mdebbar): What's the right way to implement this? // Keep horizontal whitespace together. // WB3d: WSegSpace × WSegSpace if (immediateLeft == WordCharProperty.WSegSpace && immediateRight == WordCharProperty.WSegSpace) { return false; } // Ignore Format and Extend characters, except after sot, CR, LF, and // Newline. // WB4: X (Extend | Format | ZWJ)* → X if (_oneOf( immediateRight, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )) { // The Extend|Format|ZWJ character is to the right, so it is attached // to a character to the left, don't split here return false; } // We've reached the end of an Extend|Format|ZWJ sequence, collapse it. int l = 0; while (_oneOf( immediateLeft, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )) { l++; if (index - l - 1 < 0) { // Reached the beginning of text. return true; } immediateLeft = wordLookup.find(text, index - l - 1); } // Do not break between most letters. // WB5: (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter) if (_isAHLetter(immediateLeft) && _isAHLetter(immediateRight)) { return false; } // Some tests beyond this point require more context. We need to get that // context while also respecting rule WB4. So ignore Format, Extend and ZWJ. // Skip all Format, Extend and ZWJ to the right. int r = 0; WordCharProperty? nextRight; do { r++; nextRight = wordLookup.find(text, index + r); } while (_oneOf( nextRight, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )); // Skip all Format, Extend and ZWJ to the left. WordCharProperty? nextLeft; do { l++; nextLeft = wordLookup.find(text, index - l - 1); } while (_oneOf( nextLeft, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )); // Do not break letters across certain punctuation. // WB6: (AHLetter) × (MidLetter | MidNumLet | Single_Quote) (AHLetter) if (_isAHLetter(immediateLeft) && _oneOf( immediateRight, WordCharProperty.MidLetter, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && _isAHLetter(nextRight)) { return false; } // WB7: (AHLetter) (MidLetter | MidNumLet | Single_Quote) × (AHLetter) if (_isAHLetter(nextLeft) && _oneOf( immediateLeft, WordCharProperty.MidLetter, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && _isAHLetter(immediateRight)) { return false; } // WB7a: Hebrew_Letter × Single_Quote if (immediateLeft == WordCharProperty.HebrewLetter && immediateRight == WordCharProperty.SingleQuote) { return false; } // WB7b: Hebrew_Letter × Double_Quote Hebrew_Letter if (immediateLeft == WordCharProperty.HebrewLetter && immediateRight == WordCharProperty.DoubleQuote && nextRight == WordCharProperty.HebrewLetter) { return false; } // WB7c: Hebrew_Letter Double_Quote × Hebrew_Letter if (nextLeft == WordCharProperty.HebrewLetter && immediateLeft == WordCharProperty.DoubleQuote && immediateRight == WordCharProperty.HebrewLetter) { return false; } // Do not break within sequences of digits, or digits adjacent to letters // (“3a”, or “A3”). // WB8: Numeric × Numeric if (immediateLeft == WordCharProperty.Numeric && immediateRight == WordCharProperty.Numeric) { return false; } // WB9: AHLetter × Numeric if (_isAHLetter(immediateLeft) && immediateRight == WordCharProperty.Numeric) { return false; } // WB10: Numeric × AHLetter if (immediateLeft == WordCharProperty.Numeric && _isAHLetter(immediateRight)) { return false; } // Do not break within sequences, such as “3.2” or “3,456.789”. // WB11: Numeric (MidNum | MidNumLet | Single_Quote) × Numeric if (nextLeft == WordCharProperty.Numeric && _oneOf( immediateLeft, WordCharProperty.MidNum, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && immediateRight == WordCharProperty.Numeric) { return false; } // WB12: Numeric × (MidNum | MidNumLet | Single_Quote) Numeric if (immediateLeft == WordCharProperty.Numeric && _oneOf( immediateRight, WordCharProperty.MidNum, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && nextRight == WordCharProperty.Numeric) { return false; } // Do not break between Katakana. // WB13: Katakana × Katakana if (immediateLeft == WordCharProperty.Katakana && immediateRight == WordCharProperty.Katakana) { return false; } // Do not break from extenders. // WB13a: (AHLetter | Numeric | Katakana | ExtendNumLet) × ExtendNumLet if (_oneOf( immediateLeft, WordCharProperty.ALetter, WordCharProperty.HebrewLetter, WordCharProperty.Numeric, WordCharProperty.Katakana, WordCharProperty.ExtendNumLet, ) && immediateRight == WordCharProperty.ExtendNumLet) { return false; } // WB13b: ExtendNumLet × (AHLetter | Numeric | Katakana) if (immediateLeft == WordCharProperty.ExtendNumLet && _oneOf( immediateRight, WordCharProperty.ALetter, WordCharProperty.HebrewLetter, WordCharProperty.Numeric, WordCharProperty.Katakana, )) { return false; } // Do not break within emoji flag sequences. That is, do not break between // regional indicator (RI) symbols if there is an odd number of RI // characters before the break point. // WB15: sot (RI RI)* RI × RI // TODO(mdebbar): implement this. // WB16: [^RI] (RI RI)* RI × RI // TODO(mdebbar): implement this. // Otherwise, break everywhere (including around ideographs). // WB999: Any ÷ Any return true; } static bool _isUtf16Surrogate(int value) { return value & 0xF800 == 0xD800; } static bool _oneOf( WordCharProperty? value, WordCharProperty choice1, WordCharProperty choice2, [ WordCharProperty? choice3, WordCharProperty? choice4, WordCharProperty? choice5, ]) { if (value == choice1) { return true; } if (value == choice2) { return true; } if (choice3 != null && value == choice3) { return true; } if (choice4 != null && value == choice4) { return true; } if (choice5 != null && value == choice5) { return true; } return false; } static bool _isAHLetter(WordCharProperty? property) { return _oneOf(property, WordCharProperty.ALetter, WordCharProperty.HebrewLetter); } }
engine/lib/web_ui/lib/src/engine/text/word_breaker.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/text/word_breaker.dart", "repo_id": "engine", "token_count": 3794 }
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. import 'package:ui/src/engine/dom.dart'; import 'custom_element_embedding_strategy.dart'; import 'full_page_embedding_strategy.dart'; /// Controls how a Flutter app is placed, sized and measured on the page. /// /// The base class handles general behavior (like hot-restart cleanup), and then /// each specialization enables different types of DOM embeddings: /// /// * [FullPageEmbeddingStrategy] - The default behavior, where flutter takes /// control of the whole page. /// * [CustomElementEmbeddingStrategy] - Flutter is rendered inside a custom host /// element, provided by the web app programmer through the engine /// initialization. abstract class EmbeddingStrategy { factory EmbeddingStrategy.create({DomElement? hostElement}) { if (hostElement != null) { return CustomElementEmbeddingStrategy(hostElement); } else { return FullPageEmbeddingStrategy(); } } /// The host element in which the Flutter view is embedded. DomElement get hostElement; /// The global event target for the Flutter view. DomEventTarget get globalEventTarget; /// Attaches the view root element into the hostElement. void attachViewRoot(DomElement rootElement); }
engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/embedding_strategy.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/embedding_strategy.dart", "repo_id": "engine", "token_count": 380 }
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. import 'package:meta/meta.dart'; import 'package:ui/src/engine.dart'; import 'url_strategy.dart'; /// Function type that handles pop state events. typedef EventListener = dynamic Function(Object event); /// Encapsulates all calls to DOM apis, which allows the [UrlStrategy] classes /// to be platform agnostic and testable. /// /// For convenience, the [PlatformLocation] class can be used by implementations /// of [UrlStrategy] to interact with DOM apis like pushState, popState, etc. abstract interface class PlatformLocation { /// Registers an event listener for the `popstate` event. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate void addPopStateListener(EventListener fn); /// Unregisters the given listener (added by [addPopStateListener]) from the /// `popstate` event. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate void removePopStateListener(EventListener fn); /// The `pathname` part of the URL in the browser address bar. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname String get pathname; /// The `query` part of the URL in the browser address bar. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/Location/search String get search; /// The `hash]` part of the URL in the browser address bar. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/Location/hash String? get hash; /// The `state` in the current history entry. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/state Object? get state; /// Adds a new entry to the browser history stack. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState void pushState(Object? state, String title, String url); /// Replaces the current entry in the browser history stack. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState void replaceState(Object? state, String title, String url); /// Moves forwards or backwards through the history stack. /// /// A negative [count] value causes a backward move in the history stack. And /// a positive [count] value causs a forward move. /// /// Examples: /// /// * `go(-2)` moves back 2 steps in history. /// * `go(3)` moves forward 3 steps in hisotry. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/go void go(int count); /// The base href where the Flutter app is being served. /// /// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base String? getBaseHref(); } final Map<EventListener, DomEventListener> _popStateListenersCache = <EventListener, DomEventListener>{}; /// Delegates to real browser APIs to provide platform location functionality. class BrowserPlatformLocation implements PlatformLocation { /// Default constructor for [BrowserPlatformLocation]. const BrowserPlatformLocation(); DomLocation get _location => domWindow.location; DomHistory get _history => domWindow.history; @visibleForTesting DomEventListener getOrCreateDomEventListener(EventListener fn) { return _popStateListenersCache.putIfAbsent(fn, () => createDomEventListener(fn)); } @override void addPopStateListener(EventListener fn) { domWindow.addEventListener('popstate', getOrCreateDomEventListener(fn)); } @override void removePopStateListener(EventListener fn) { assert( _popStateListenersCache.containsKey(fn), 'Removing a listener that was never added or was removed already.', ); domWindow.removeEventListener('popstate', getOrCreateDomEventListener(fn)); _popStateListenersCache.remove(fn); } @override String get pathname => _location.pathname!; @override String get search => _location.search!; @override String get hash => _location.locationHash; @override Object? get state => _history.state; @override void pushState(Object? state, String title, String url) { _history.pushState(state, title, url); } @override void replaceState(Object? state, String title, String url) { _history.replaceState(state, title, url); } @override void go(int count) { _history.go(count); } @override String? getBaseHref() => domDocument.baseUri; }
engine/lib/web_ui/lib/ui_web/src/ui_web/navigation/platform_location.dart/0
{ "file_path": "engine/lib/web_ui/lib/ui_web/src/ui_web/navigation/platform_location.dart", "repo_id": "engine", "token_count": 1373 }
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. // This file adds JavaScript APIs that are accessible to the C++ layer. // See: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#implement-a-c-api-in-javascript mergeInto(LibraryManager.library, { $skwasm_support_setup__postset: 'skwasm_support_setup();', $skwasm_support_setup: function() { const handleToCanvasMap = new Map(); const associatedObjectsMap = new Map(); // This value represents the difference between the time origin of the main // thread and whichever web worker this code is running on. This is so that // when we report frame timings, that they are in the same time domain // regardless of whether they are captured on the main thread or the web // worker. let timeOriginDelta; _skwasm_setAssociatedObjectOnThread = function(threadId, pointer, object) { PThread.pthreads[threadId].postMessage({ skwasmMessage: 'setAssociatedObject', pointer, object, }, [object]); }; _skwasm_getAssociatedObject = function(pointer) { return associatedObjectsMap.get(pointer); }; _skwasm_syncTimeOriginForThread = function(threadId) { PThread.pthreads[threadId].postMessage({ skwasmMessage: 'syncTimeOrigin', timeOrigin: performance.timeOrigin, }); } _skwasm_registerMessageListener = function(threadId) { const eventListener = function({data}) { const skwasmMessage = data.skwasmMessage; if (!skwasmMessage) { return; } switch (skwasmMessage) { case 'syncTimeOrigin': timeOriginDelta = performance.timeOrigin - data.timeOrigin; return; case 'renderPictures': _surface_renderPicturesOnWorker( data.surface, data.pictures, data.pictureCount, data.callbackId, performance.now() + timeOriginDelta); return; case 'onRenderComplete': _surface_onRenderComplete( data.surface, data.callbackId, { "imageBitmaps": data.imageBitmaps, "rasterStartMilliseconds": data.rasterStart, "rasterEndMilliseconds": data.rasterEnd, }, ); return; case 'setAssociatedObject': associatedObjectsMap.set(data.pointer, data.object); return; case 'disposeAssociatedObject': const pointer = data.pointer; const object = associatedObjectsMap.get(pointer); if (object.close) { object.close(); } associatedObjectsMap.delete(pointer); return; default: console.warn(`unrecognized skwasm message: ${skwasmMessage}`); } }; if (!threadId) { addEventListener("message", eventListener); } else { PThread.pthreads[threadId].addEventListener("message", eventListener); } }; _skwasm_dispatchRenderPictures = function(threadId, surfaceHandle, pictures, pictureCount, callbackId) { PThread.pthreads[threadId].postMessage({ skwasmMessage: 'renderPictures', surface: surfaceHandle, pictures, pictureCount, callbackId, }); }; _skwasm_createOffscreenCanvas = function(width, height) { const canvas = new OffscreenCanvas(width, height); var contextAttributes = { majorVersion: 2, alpha: true, depth: true, stencil: true, antialias: false, premultipliedAlpha: true, preserveDrawingBuffer: false, powerPreference: 'default', failIfMajorPerformanceCaveat: false, enableExtensionsByDefault: true, }; const contextHandle = GL.createContext(canvas, contextAttributes); handleToCanvasMap.set(contextHandle, canvas); return contextHandle; }; _skwasm_resizeCanvas = function(contextHandle, width, height) { const canvas = handleToCanvasMap.get(contextHandle); canvas.width = width; canvas.height = height; }; _skwasm_captureImageBitmap = function(contextHandle, width, height, imagePromises) { if (!imagePromises) imagePromises = Array(); const canvas = handleToCanvasMap.get(contextHandle); imagePromises.push(createImageBitmap(canvas, 0, 0, width, height)); return imagePromises; }; _skwasm_resolveAndPostImages = async function(surfaceHandle, imagePromises, rasterStart, callbackId) { const imageBitmaps = imagePromises ? await Promise.all(imagePromises) : []; const rasterEnd = performance.now() + timeOriginDelta; postMessage({ skwasmMessage: 'onRenderComplete', surface: surfaceHandle, callbackId, imageBitmaps, rasterStart, rasterEnd, }, [...imageBitmaps]); }; _skwasm_createGlTextureFromTextureSource = function(textureSource, width, height) { const glCtx = GL.currentContext.GLctx; const newTexture = glCtx.createTexture(); glCtx.bindTexture(glCtx.TEXTURE_2D, newTexture); glCtx.pixelStorei(glCtx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); glCtx.texImage2D(glCtx.TEXTURE_2D, 0, glCtx.RGBA, width, height, 0, glCtx.RGBA, glCtx.UNSIGNED_BYTE, textureSource); glCtx.pixelStorei(glCtx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); glCtx.bindTexture(glCtx.TEXTURE_2D, null); const textureId = GL.getNewId(GL.textures); GL.textures[textureId] = newTexture; return textureId; }; _skwasm_disposeAssociatedObjectOnThread = function(threadId, pointer) { PThread.pthreads[threadId].postMessage({ skwasmMessage: 'disposeAssociatedObject', pointer, }); }; }, skwasm_setAssociatedObjectOnThread: function () {}, skwasm_setAssociatedObjectOnThread__deps: ['$skwasm_support_setup'], skwasm_getAssociatedObject: function () {}, skwasm_getAssociatedObject__deps: ['$skwasm_support_setup'], skwasm_disposeAssociatedObjectOnThread: function () {}, skwasm_disposeAssociatedObjectOnThread__deps: ['$skwasm_support_setup'], skwasm_syncTimeOriginForThread: function() {}, skwasm_syncTimeOriginForThread__deps: ['$skwasm_support_setup'], skwasm_registerMessageListener: function() {}, skwasm_registerMessageListener__deps: ['$skwasm_support_setup'], skwasm_dispatchRenderPictures: function() {}, skwasm_dispatchRenderPictures__deps: ['$skwasm_support_setup'], skwasm_createOffscreenCanvas: function () {}, skwasm_createOffscreenCanvas__deps: ['$skwasm_support_setup'], skwasm_resizeCanvas: function () {}, skwasm_resizeCanvas__deps: ['$skwasm_support_setup'], skwasm_captureImageBitmap: function () {}, skwasm_captureImageBitmap__deps: ['$skwasm_support_setup'], skwasm_resolveAndPostImages: function () {}, skwasm_resolveAndPostImages__deps: ['$skwasm_support_setup'], skwasm_createGlTextureFromTextureSource: function () {}, skwasm_createGlTextureFromTextureSource__deps: ['$skwasm_support_setup'], });
engine/lib/web_ui/skwasm/library_skwasm_support.js/0
{ "file_path": "engine/lib/web_ui/skwasm/library_skwasm_support.js", "repo_id": "engine", "token_count": 2958 }
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_LIB_WEB_UI_SKWASM_WRAPPERS_H_ #define FLUTTER_LIB_WEB_UI_SKWASM_WRAPPERS_H_ #include <emscripten/html5_webgl.h> #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/modules/skparagraph/include/FontCollection.h" #include "third_party/skia/modules/skparagraph/include/TypefaceFontProvider.h" namespace Skwasm { struct SurfaceWrapper { EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context; sk_sp<GrDirectContext> grContext; sk_sp<SkSurface> surface; }; inline void makeCurrent(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE handle) { if (!handle) return; int result = emscripten_webgl_make_context_current(handle); if (result != EMSCRIPTEN_RESULT_SUCCESS) { printf("make_context failed: %d", result); } } struct FlutterFontCollection { sk_sp<skia::textlayout::FontCollection> collection; sk_sp<skia::textlayout::TypefaceFontProvider> provider; }; } // namespace Skwasm #endif // FLUTTER_LIB_WEB_UI_SKWASM_WRAPPERS_H_
engine/lib/web_ui/skwasm/wrappers.h/0
{ "file_path": "engine/lib/web_ui/skwasm/wrappers.h", "repo_id": "engine", "token_count": 442 }
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. import 'dart:async'; import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine/canvaskit/image.dart'; import 'package:ui/ui.dart' as ui; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { setUpCanvasKitTest(); test('toImage succeeds', () async { final ui.Image image = await _createImage(); expect(image.runtimeType.toString(), equals('CkImage')); image.dispose(); }); test('Image constructor invokes onCreate once', () async { int onCreateInvokedCount = 0; ui.Image? createdImage; ui.Image.onCreate = (ui.Image image) { onCreateInvokedCount++; createdImage = image; }; final ui.Image image1 = await _createImage(); expect(onCreateInvokedCount, 1); expect(createdImage, image1); final ui.Image image2 = await _createImage(); expect(onCreateInvokedCount, 2); expect(createdImage, image2); ui.Image.onCreate = null; }); test('dispose() invokes onDispose once', () async { int onDisposeInvokedCount = 0; ui.Image? disposedImage; ui.Image.onDispose = (ui.Image image) { onDisposeInvokedCount++; disposedImage = image; }; final ui.Image image1 = await _createImage()..dispose(); expect(onDisposeInvokedCount, 1); expect(disposedImage, image1); final ui.Image image2 = await _createImage()..dispose(); expect(onDisposeInvokedCount, 2); expect(disposedImage, image2); ui.Image.onDispose = null; }); test('fetchImage fetches image in chunks', () async { final List<int> cumulativeBytesLoadedInvocations = <int>[]; final List<int> expectedTotalBytesInvocations = <int>[]; final Uint8List result = await fetchImage('/long_test_payload?length=100000&chunk=1000', (int cumulativeBytesLoaded, int expectedTotalBytes) { cumulativeBytesLoadedInvocations.add(cumulativeBytesLoaded); expectedTotalBytesInvocations.add(expectedTotalBytes); }); // Check that image payload was chunked. expect(cumulativeBytesLoadedInvocations, hasLength(greaterThan(1))); // Check that reported total byte count is the same across all invocations. for (final int expectedTotalBytes in expectedTotalBytesInvocations) { expect(expectedTotalBytes, 100000); } // Check that cumulative byte count grows with each invocation. cumulativeBytesLoadedInvocations.reduce((int previous, int next) { expect(next, greaterThan(previous)); return next; }); // Check that the last cumulative byte count matches the total byte count. expect(cumulativeBytesLoadedInvocations.last, 100000); // Check the contents of the returned data. expect( result, List<int>.generate(100000, (int i) => i & 0xFF), ); }); } Future<ui.Image> _createImage() => _createPicture().toImage(10, 10); ui.Picture _createPicture() { final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); const ui.Rect rect = ui.Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); canvas.clipRect(rect); return recorder.endRecording(); }
engine/lib/web_ui/test/canvaskit/image_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/image_test.dart", "repo_id": "engine", "token_count": 1169 }
324
// 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('chrome || safari || firefox') library; import 'dart:async'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import '../engine/semantics/semantics_test.dart'; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } // Run the same semantics tests in CanvasKit mode because as of today we do not // yet share platform view logic with the HTML renderer, which affects // semantics. Future<void> testMain() async { group('CanvasKit semantics', () { setUpCanvasKitTest(withImplicitView: true); runSemanticsTests(); }); }
engine/lib/web_ui/test/canvaskit/semantics_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/semantics_test.dart", "repo_id": "engine", "token_count": 236 }
325
// 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:quiver/testing/async.dart'; import 'package:quiver/time.dart'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine/alarm_clock.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group(AlarmClock, () { _alarmClockTests(); }); } void _alarmClockTests() { int callCount = 0; void testCallback() { callCount += 1; } setUp(() { callCount = 0; }); testAsync('AlarmClock calls the callback in the future', (FakeAsync fakeAsync) { final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24)); final AlarmClock alarm = AlarmClock(clock.now); alarm.callback = testCallback; // There should be no timers scheduled until we set a non-null datetime. expect(fakeAsync.nonPeriodicTimerCount, 0); alarm.datetime = clock.fromNow(minutes: 1); // There should be exactly 1 timer scheduled. expect(fakeAsync.nonPeriodicTimerCount, 1); // No time has passed; the callback should not be called. expect(callCount, 0); // Not enough time has passed; the callback should not be called. fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); // Exactly 1 minute has passed; fire the callback. fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 1); // Timers should be cleaned up. expect(fakeAsync.nonPeriodicTimerCount, 0); // Rescheduling. alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); fakeAsync.elapse(const Duration(minutes: 1)); expect(fakeAsync.nonPeriodicTimerCount, 0); expect(callCount, 2); }); testAsync('AlarmClock does nothing when new datetime is the same', (FakeAsync fakeAsync) { final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24)); final AlarmClock alarm = AlarmClock(clock.now); alarm.callback = testCallback; alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); alarm.datetime = alarm.datetime!.add(Duration.zero); expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); fakeAsync.elapse(const Duration(seconds: 30)); alarm.datetime = alarm.datetime!.add(Duration.zero); expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); fakeAsync.elapse(const Duration(seconds: 30)); expect(fakeAsync.nonPeriodicTimerCount, 0); expect(callCount, 1); }); testAsync('AlarmClock does not call the callback in the past', (FakeAsync fakeAsync) { final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24)); final AlarmClock alarm = AlarmClock(clock.now); alarm.callback = testCallback; alarm.datetime = clock.ago(minutes: 1); // No timers scheduled for past dates. expect(fakeAsync.nonPeriodicTimerCount, 0); expect(callCount, 0); }); testAsync('AlarmClock reschedules to a future time', (FakeAsync fakeAsync) { final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24)); final AlarmClock alarm = AlarmClock(clock.now); alarm.callback = testCallback; alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); // Reschedule. alarm.datetime = alarm.datetime!.add(const Duration(minutes: 1)); fakeAsync.elapse(const Duration(minutes: 1)); // Still no calls because we rescheduled. expect(callCount, 0); fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 1); expect(fakeAsync.nonPeriodicTimerCount, 0); }); testAsync('AlarmClock reschedules to an earlier time', (FakeAsync fakeAsync) { final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24)); final AlarmClock alarm = AlarmClock(clock.now); alarm.callback = testCallback; alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); // Reschedule to an earlier time that's still in the future. alarm.datetime = alarm.datetime!.subtract(const Duration(seconds: 15)); fakeAsync.elapse(const Duration(seconds: 45)); expect(callCount, 1); expect(fakeAsync.nonPeriodicTimerCount, 0); }); testAsync('AlarmClock cancels the timer when datetime is null', (FakeAsync fakeAsync) { final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24)); final AlarmClock alarm = AlarmClock(clock.now); alarm.callback = testCallback; alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); // Cancel. alarm.datetime = null; expect(fakeAsync.nonPeriodicTimerCount, 0); expect(callCount, 0); // Make sure nothing fires even if we wait long enough. fakeAsync.elapse(const Duration(minutes: 2)); expect(callCount, 0); expect(fakeAsync.nonPeriodicTimerCount, 0); }); testAsync('AlarmClock cancels the timer when datetime is in the past', (FakeAsync fakeAsync) { final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24)); final AlarmClock alarm = AlarmClock(clock.now); alarm.callback = testCallback; alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); expect(fakeAsync.nonPeriodicTimerCount, 1); // Cancel. alarm.datetime = clock.ago(seconds: 1); expect(fakeAsync.nonPeriodicTimerCount, 0); expect(callCount, 0); // Make sure nothing fires even if we wait long enough. fakeAsync.elapse(const Duration(minutes: 2)); expect(callCount, 0); expect(fakeAsync.nonPeriodicTimerCount, 0); }); } typedef FakeAsyncTest = void Function(FakeAsync); void testAsync(String description, FakeAsyncTest fn) { test(description, () { FakeAsync().run(fn); }); }
engine/lib/web_ui/test/engine/alarm_clock_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/alarm_clock_test.dart", "repo_id": "engine", "token_count": 2176 }
326
// 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 'package:quiver/testing/async.dart'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui_web/src/ui_web.dart'; import '../common/matchers.dart'; import '../common/spy.dart'; import '../common/test_initialization.dart'; EngineFlutterWindow get implicitView => EnginePlatformDispatcher.instance.implicitView!; Map<String, dynamic> _wrapOriginState(dynamic state) { return <String, dynamic>{'origin': true, 'state': state}; } Map<String, dynamic> _tagStateWithSerialCount(dynamic state, int serialCount) { return <String, dynamic> { 'serialCount': serialCount, 'state': state, }; } const Map<String, bool> flutterState = <String, bool>{'flutter': true}; const MethodCodec codec = JSONMethodCodec(); void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { setUpAll(() async { await bootstrapAndRunApp(withImplicitView: true); }); test('createHistoryForExistingState', () { TestUrlStrategy strategy; BrowserHistory history; // No url strategy. history = createHistoryForExistingState(null); expect(history, isA<MultiEntriesBrowserHistory>()); expect(history.urlStrategy, isNull); // Random history state. strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(<dynamic, dynamic>{'foo': 123.0}, null, '/'), ); history = createHistoryForExistingState(strategy); expect(history, isA<MultiEntriesBrowserHistory>()); expect(history.urlStrategy, strategy); // Multi-entry history state. final Map<dynamic, dynamic> state = <dynamic, dynamic>{ 'serialCount': 1.0, 'state': <dynamic, dynamic>{'foo': 123.0}, }; strategy = TestUrlStrategy.fromEntry(TestHistoryEntry(state, null, '/')); history = createHistoryForExistingState(strategy); expect(history, isA<MultiEntriesBrowserHistory>()); expect(history.urlStrategy, strategy); // Single-entry history "origin" state. strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(<dynamic, dynamic>{'origin': true}, null, '/'), ); history = createHistoryForExistingState(strategy); expect(history, isA<SingleEntryBrowserHistory>()); expect(history.urlStrategy, strategy); // Single-entry history "flutter" state. strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(<dynamic, dynamic>{'flutter': true}, null, '/'), ); history = createHistoryForExistingState(strategy); expect(history, isA<SingleEntryBrowserHistory>()); expect(history.urlStrategy, strategy); }); group('$SingleEntryBrowserHistory', () { final PlatformMessagesSpy spy = PlatformMessagesSpy(); setUp(() async { spy.setUp(); }); tearDown(() async { spy.tearDown(); await implicitView.resetHistory(); }); test('basic setup works', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ); await implicitView.debugInitializeHistory(strategy, useSingle: true); // There should be two entries: origin and flutter. expect(strategy.history, hasLength(2)); // The origin entry is set up but its path should remain unchanged. final TestHistoryEntry originEntry = strategy.history[0]; expect(originEntry.state, _wrapOriginState('initial state')); expect(originEntry.url, '/initial'); // The flutter entry is pushed and its path should be derived from the // origin entry. final TestHistoryEntry flutterEntry = strategy.history[1]; expect(flutterEntry.state, flutterState); expect(flutterEntry.url, '/initial'); // The flutter entry is the current entry. expect(strategy.currentEntry, flutterEntry); }); test('disposes of its listener without touching history', () async { const String unwrappedOriginState = 'initial state'; final Map<String, dynamic> wrappedOriginState = _wrapOriginState(unwrappedOriginState); final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(unwrappedOriginState, null, '/initial'), ); expect(strategy.listeners, isEmpty); await implicitView.debugInitializeHistory(strategy, useSingle: true); // There should be one `popstate` listener and two history entries. expect(strategy.listeners, hasLength(1)); expect(strategy.history, hasLength(2)); expect(strategy.history[0].state, wrappedOriginState); expect(strategy.history[0].url, '/initial'); expect(strategy.history[1].state, flutterState); expect(strategy.history[1].url, '/initial'); FakeAsync().run((FakeAsync fakeAsync) { implicitView.browserHistory.dispose(); // The `TestUrlStrategy` implementation uses microtasks to schedule the // removal of event listeners. fakeAsync.flushMicrotasks(); }); // After disposing, there should no listeners, and the history entries // remain unaffected. expect(strategy.listeners, isEmpty); expect(strategy.history, hasLength(2)); expect(strategy.history[0].state, wrappedOriginState); expect(strategy.history[0].url, '/initial'); expect(strategy.history[1].state, flutterState); expect(strategy.history[1].url, '/initial'); // An extra call to dispose should be safe. FakeAsync().run((FakeAsync fakeAsync) { expect(() => implicitView.browserHistory.dispose(), returnsNormally); fakeAsync.flushMicrotasks(); }); // Same expectations should remain true after the second dispose. expect(strategy.listeners, isEmpty); expect(strategy.history, hasLength(2)); expect(strategy.history[0].state, wrappedOriginState); expect(strategy.history[0].url, '/initial'); expect(strategy.history[1].state, flutterState); expect(strategy.history[1].url, '/initial'); // Can still teardown after being disposed. await implicitView.browserHistory.tearDown(); expect(strategy.history, hasLength(2)); expect(strategy.currentEntry.state, unwrappedOriginState); expect(strategy.currentEntry.url, '/initial'); }); test('disposes gracefully when url strategy is null', () async { await implicitView.debugInitializeHistory(null, useSingle: true); expect(() => implicitView.browserHistory.dispose(), returnsNormally); }); test('browser back button pops routes correctly', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(null, null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: true); // Initially, we should be on the flutter entry. expect(strategy.history, hasLength(2)); expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/home'); await routeUpdated('/page1'); // The number of entries shouldn't change. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); // But the url of the current entry (flutter entry) should be updated. expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/page1'); // No platform messages have been sent so far. expect(spy.messages, isEmpty); // Clicking back should take us to page1. await strategy.go(-1); // First, the framework should've received a `popRoute` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'popRoute'); expect(spy.messages[0].methodArguments, isNull); // We still have 2 entries. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); // The url of the current entry (flutter entry) should go back to /home. expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/home'); }); test('multiple browser back clicks', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(null, null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: true); await routeUpdated('/page1'); await routeUpdated('/page2'); // Make sure we are on page2. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/page2'); // Back to page1. await strategy.go(-1); // 1. The engine sends a `popRoute` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'popRoute'); expect(spy.messages[0].methodArguments, isNull); spy.messages.clear(); // 2. The framework sends a `routePopped` platform message. await routeUpdated('/page1'); // 3. The history state should reflect that /page1 is currently active. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/page1'); // Back to home. await strategy.go(-1); // 1. The engine sends a `popRoute` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'popRoute'); expect(spy.messages[0].methodArguments, isNull); spy.messages.clear(); // 2. The framework sends a `routePopped` platform message. await routeUpdated('/home'); // 3. The history state should reflect that /page1 is currently active. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/home'); // The next browser back will exit the app. We store the strategy locally // because it will be remove from the browser history class once it exits // the app. final TestUrlStrategy originalStrategy = strategy; await originalStrategy.go(-1); // 1. The engine sends a `popRoute` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'popRoute'); expect(spy.messages[0].methodArguments, isNull); spy.messages.clear(); // 2. The framework sends a `SystemNavigator.pop` platform message // because there are no more routes to pop. await systemNavigatorPop(); // 3. The active entry doesn't belong to our history anymore because we // navigated past it. expect(originalStrategy.currentEntryIndex, -1); }); test('handle user-provided url', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(null, null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: true); await strategy.simulateUserTypingUrl('/page3'); // This delay is necessary to wait for [BrowserHistory] because it // performs a `back` operation which results in a new event loop. await Future<void>.delayed(Duration.zero); // 1. The engine sends a `pushRoute` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRoute'); expect(spy.messages[0].methodArguments, '/page3'); spy.messages.clear(); // 2. The framework sends a `routePushed` platform message. await routeUpdated('/page3'); // 3. The history state should reflect that /page3 is currently active. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/page3'); // Back to home. await strategy.go(-1); // 1. The engine sends a `popRoute` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'popRoute'); expect(spy.messages[0].methodArguments, isNull); spy.messages.clear(); // 2. The framework sends a `routePopped` platform message. await routeUpdated('/home'); // 3. The history state should reflect that /page1 is currently active. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/home'); }); test('user types unknown url', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(null, null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: true); await strategy.simulateUserTypingUrl('/unknown'); // This delay is necessary to wait for [BrowserHistory] because it // performs a `back` operation which results in a new event loop. await Future<void>.delayed(Duration.zero); // 1. The engine sends a `pushRoute` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRoute'); expect(spy.messages[0].methodArguments, '/unknown'); spy.messages.clear(); // 2. The framework doesn't recognize the route name and ignores it. // 3. The history state should reflect that /home is currently active. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, flutterState); expect(strategy.currentEntry.url, '/home'); }); }); group('$MultiEntriesBrowserHistory', () { final PlatformMessagesSpy spy = PlatformMessagesSpy(); setUp(() async { spy.setUp(); }); tearDown(() async { spy.tearDown(); await implicitView.resetHistory(); }); test('basic setup works', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/initial'), ); await implicitView.debugInitializeHistory(strategy, useSingle: false); // There should be only one entry. expect(strategy.history, hasLength(1)); // The origin entry is tagged and its path should remain unchanged. final TestHistoryEntry taggedOriginEntry = strategy.history[0]; expect(taggedOriginEntry.state, _tagStateWithSerialCount('initial state', 0)); expect(taggedOriginEntry.url, '/initial'); }); test('disposes of its listener without touching history', () async { const String untaggedState = 'initial state'; final Map<String, dynamic> taggedState = _tagStateWithSerialCount(untaggedState, 0); final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry(untaggedState, null, '/initial'), ); expect(strategy.listeners, isEmpty); await implicitView.debugInitializeHistory(strategy, useSingle: false); // There should be one `popstate` listener and one history entry. expect(strategy.listeners, hasLength(1)); expect(strategy.history, hasLength(1)); expect(strategy.history.single.state, taggedState); expect(strategy.history.single.url, '/initial'); FakeAsync().run((FakeAsync fakeAsync) { implicitView.browserHistory.dispose(); // The `TestUrlStrategy` implementation uses microtasks to schedule the // removal of event listeners. fakeAsync.flushMicrotasks(); }); // After disposing, there should no listeners, and the history entries // remain unaffected. expect(strategy.listeners, isEmpty); expect(strategy.history, hasLength(1)); expect(strategy.history.single.state, taggedState); expect(strategy.history.single.url, '/initial'); // An extra call to dispose should be safe. FakeAsync().run((FakeAsync fakeAsync) { expect(() => implicitView.browserHistory.dispose(), returnsNormally); fakeAsync.flushMicrotasks(); }); // Same expectations should remain true after the second dispose. expect(strategy.listeners, isEmpty); expect(strategy.history, hasLength(1)); expect(strategy.history.single.state, taggedState); expect(strategy.history.single.url, '/initial'); // Can still teardown after being disposed. await implicitView.browserHistory.tearDown(); expect(strategy.history, hasLength(1)); expect(strategy.history.single.state, untaggedState); expect(strategy.history.single.url, '/initial'); }); test('disposes gracefully when url strategy is null', () async { await implicitView.debugInitializeHistory(null, useSingle: false); expect(() => implicitView.browserHistory.dispose(), returnsNormally); }); test('browser back button push route information correctly', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: false); // Initially, we should be on the flutter entry. expect(strategy.history, hasLength(1)); expect(strategy.currentEntry.state, _tagStateWithSerialCount('initial state', 0)); expect(strategy.currentEntry.url, '/home'); await routeInformationUpdated('/page1', 'page1 state'); // Should have two history entries now. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); // But the url of the current entry (flutter entry) should be updated. expect(strategy.currentEntry.state, _tagStateWithSerialCount('page1 state', 1)); expect(strategy.currentEntry.url, '/page1'); // No platform messages have been sent so far. expect(spy.messages, isEmpty); // Clicking back should take us to page1. await strategy.go(-1); // First, the framework should've received a `pushRouteInformation` // platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRouteInformation'); expect(spy.messages[0].methodArguments, <dynamic, dynamic>{ 'location': '/home', 'state': 'initial state', }); // There are still two browser history entries, but we are back to the // original state. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 0); expect(strategy.currentEntry.state, _tagStateWithSerialCount('initial state', 0)); expect(strategy.currentEntry.url, '/home'); }); test('multiple browser back clicks', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: false); await routeInformationUpdated('/page1', 'page1 state'); await routeInformationUpdated('/page2', 'page2 state'); // Make sure we are on page2. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 2); expect(strategy.currentEntry.state, _tagStateWithSerialCount('page2 state', 2)); expect(strategy.currentEntry.url, '/page2'); // Back to page1. await strategy.go(-1); // 1. The engine sends a `pushRouteInformation` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRouteInformation'); expect(spy.messages[0].methodArguments, <dynamic, dynamic>{ 'location': '/page1', 'state': 'page1 state', }); spy.messages.clear(); // 2. The history state should reflect that /page1 is currently active. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, _tagStateWithSerialCount('page1 state', 1)); expect(strategy.currentEntry.url, '/page1'); // Back to home. await strategy.go(-1); // 1. The engine sends a `pushRouteInformation` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRouteInformation'); expect(spy.messages[0].methodArguments, <dynamic, dynamic>{ 'location': '/home', 'state': 'initial state', }); spy.messages.clear(); // 2. The history state should reflect that /page1 is currently active. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 0); expect(strategy.currentEntry.state, _tagStateWithSerialCount('initial state', 0)); expect(strategy.currentEntry.url, '/home'); }); test('handle user-provided url', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: false); await strategy.simulateUserTypingUrl('/page3'); // This delay is necessary to wait for [BrowserHistory] because it // performs a `back` operation which results in a new event loop. await Future<void>.delayed(Duration.zero); // 1. The engine sends a `pushRouteInformation` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRouteInformation'); expect(spy.messages[0].methodArguments, <dynamic, dynamic>{ 'location': '/page3', 'state': null, }); spy.messages.clear(); // 2. The history state should reflect that /page3 is currently active. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, _tagStateWithSerialCount(null, 1)); expect(strategy.currentEntry.url, '/page3'); // Back to home. await strategy.go(-1); // 1. The engine sends a `pushRouteInformation` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRouteInformation'); expect(spy.messages[0].methodArguments, <dynamic, dynamic>{ 'location': '/home', 'state': 'initial state', }); spy.messages.clear(); // 2. The history state should reflect that /page1 is currently active. expect(strategy.history, hasLength(2)); expect(strategy.currentEntryIndex, 0); expect(strategy.currentEntry.state, _tagStateWithSerialCount('initial state', 0)); expect(strategy.currentEntry.url, '/home'); }); test('forward button works', () async { final TestUrlStrategy strategy = TestUrlStrategy.fromEntry( const TestHistoryEntry('initial state', null, '/home'), ); await implicitView.debugInitializeHistory(strategy, useSingle: false); await routeInformationUpdated('/page1', 'page1 state'); await routeInformationUpdated('/page2', 'page2 state'); // Make sure we are on page2. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 2); expect(strategy.currentEntry.state, _tagStateWithSerialCount('page2 state', 2)); expect(strategy.currentEntry.url, '/page2'); // Back to page1. await strategy.go(-1); // 1. The engine sends a `pushRouteInformation` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRouteInformation'); expect(spy.messages[0].methodArguments, <dynamic, dynamic>{ 'location': '/page1', 'state': 'page1 state', }); spy.messages.clear(); // 2. The history state should reflect that /page1 is currently active. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 1); expect(strategy.currentEntry.state, _tagStateWithSerialCount('page1 state', 1)); expect(strategy.currentEntry.url, '/page1'); // Forward to page2 await strategy.go(1); // 1. The engine sends a `pushRouteInformation` platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/navigation'); expect(spy.messages[0].methodName, 'pushRouteInformation'); expect(spy.messages[0].methodArguments, <dynamic, dynamic>{ 'location': '/page2', 'state': 'page2 state', }); spy.messages.clear(); // 2. The history state should reflect that /page2 is currently active. expect(strategy.history, hasLength(3)); expect(strategy.currentEntryIndex, 2); expect(strategy.currentEntry.state, _tagStateWithSerialCount('page2 state', 2)); expect(strategy.currentEntry.url, '/page2'); }); }); group('$HashUrlStrategy', () { late TestPlatformLocation location; setUp(() { location = TestPlatformLocation(); }); tearDown(() { location = TestPlatformLocation(); }); test('leading slash is optional', () { final HashUrlStrategy strategy = HashUrlStrategy(location); location.hash = '#/'; expect(strategy.getPath(), '/'); location.hash = '#/foo'; expect(strategy.getPath(), '/foo'); location.hash = '#foo'; expect(strategy.getPath(), 'foo'); }); test('path should not be empty', () { final HashUrlStrategy strategy = HashUrlStrategy(location); location.hash = ''; expect(strategy.getPath(), '/'); location.hash = '#'; expect(strategy.getPath(), '/'); }); test('prepareExternalUrl', () { const String internalUrl = '/menu?foo=bar'; final HashUrlStrategy strategy = HashUrlStrategy(location); location.pathname = '/'; expect(strategy.prepareExternalUrl(internalUrl), '/#/menu?foo=bar'); location.pathname = '/main'; expect(strategy.prepareExternalUrl(internalUrl), '/main#/menu?foo=bar'); location.search = '?foo=bar'; expect( strategy.prepareExternalUrl(internalUrl), '/main?foo=bar#/menu?foo=bar', ); }); test('removes /#/ from the home page', () { const String internalUrl = '/'; final HashUrlStrategy strategy = HashUrlStrategy(location); location.pathname = '/'; expect(strategy.prepareExternalUrl(internalUrl), '/'); location.pathname = '/main'; expect(strategy.prepareExternalUrl(internalUrl), '/main'); location.search = '?foo=bar'; expect( strategy.prepareExternalUrl(internalUrl), '/main?foo=bar', ); }); test('addPopStateListener fn unwraps DomPopStateEvent state', () { final HashUrlStrategy strategy = HashUrlStrategy(location); const String expected = 'expected value'; final List<Object?> states = <Object?>[]; // Put the popStates received from the `location` in a list strategy.addPopStateListener(states.add); // Simulate a popstate with a null state: location.debugTriggerPopState(null); expect(states, hasLength(1)); expect(states[0], isNull); // Simulate a popstate event with `expected` as its 'state'. location.debugTriggerPopState(expected); expect(states, hasLength(2)); final Object? state = states[1]; expect(state, isNotNull); // flutter/flutter#125228 expect(state, isNot(isA<DomEvent>())); expect(state, expected); }); }); group('$BrowserPlatformLocation', () { test('getOrCreateDomEventListener caches funcions', () { const BrowserPlatformLocation location = BrowserPlatformLocation(); void myListener(Object event) {} expect( identical( location.getOrCreateDomEventListener(myListener), location.getOrCreateDomEventListener(myListener), ), isTrue, ); }); test('throws if removing an invalid listener', () { const BrowserPlatformLocation location = BrowserPlatformLocation(); void myAddedListener(Object event) {} void myNonAddedListener(Object event) {} location.addPopStateListener(myAddedListener); expect(() => location.removePopStateListener(myAddedListener), returnsNormally); // Removing the same listener twice should throw. expect(() => location.removePopStateListener(myAddedListener), throwsAssertionError); // A listener that was never added. expect(() => location.removePopStateListener(myNonAddedListener), throwsAssertionError); }); test('returns a non-empty baseUri', () { const BrowserPlatformLocation location = BrowserPlatformLocation(); expect(location.getBaseHref(), isNotNull); }); }); } Future<void> routeUpdated(String routeName) { final Completer<void> completer = Completer<void>(); EnginePlatformDispatcher.instance.sendPlatformMessage( 'flutter/navigation', codec.encodeMethodCall(MethodCall( 'routeUpdated', <String, dynamic>{'routeName': routeName}, )), (_) => completer.complete(), ); return completer.future; } Future<void> routeInformationUpdated(String location, dynamic state) { final Completer<void> completer = Completer<void>(); EnginePlatformDispatcher.instance.sendPlatformMessage( 'flutter/navigation', codec.encodeMethodCall(MethodCall( 'routeInformationUpdated', <String, dynamic>{'location': location, 'state': state}, )), (_) => completer.complete(), ); return completer.future; } Future<void> systemNavigatorPop() { final Completer<void> completer = Completer<void>(); EnginePlatformDispatcher.instance.sendPlatformMessage( 'flutter/platform', codec.encodeMethodCall(const MethodCall('SystemNavigator.pop')), (_) => completer.complete(), ); return completer.future; } /// A mock implementation of [PlatformLocation] that doesn't access the browser. class TestPlatformLocation implements PlatformLocation { @override String? hash; @override dynamic state; List<EventListener> popStateListeners = <EventListener>[]; @override String pathname = ''; @override String search = ''; /// Calls all the registered `popStateListeners` with a 'popstate' /// event with value `state` void debugTriggerPopState(Object? state) { final DomEvent event = createDomPopStateEvent( 'popstate', <Object, Object>{ if (state != null) 'state': state, }, ); for (final EventListener listener in popStateListeners) { listener(event); } } @override void addPopStateListener(EventListener fn) { popStateListeners.add(fn); } @override void removePopStateListener(EventListener fn) { throw UnimplementedError(); } @override void pushState(dynamic state, String title, String url) { throw UnimplementedError(); } @override void replaceState(dynamic state, String title, String url) { throw UnimplementedError(); } @override void go(int count) { throw UnimplementedError(); } @override String getBaseHref() => '/'; }
engine/lib/web_ui/test/engine/history_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/history_test.dart", "repo_id": "engine", "token_count": 11392 }
327
// 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; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group(ViewFocusBinding, () { late List<ui.ViewFocusEvent> dispatchedViewFocusEvents; late EnginePlatformDispatcher dispatcher; setUp(() { domDocument.activeElement?.blur(); EngineSemantics.instance.semanticsEnabled = false; dispatcher = EnginePlatformDispatcher.instance; dispatchedViewFocusEvents = <ui.ViewFocusEvent>[]; dispatcher.onViewFocusChange = dispatchedViewFocusEvents.add; }); test('The view is focusable and reachable by keyboard when registered', () async { final EngineFlutterView view = createAndRegisterView(dispatcher); // The root element should have a tabindex="0" to make the flutter view // focusable and reachable by the keyboard. expect(view.dom.rootElement.getAttribute('tabindex'), '0'); }); test('The view is focusable but not reachable by keyboard when focused', () async { final EngineFlutterView view = createAndRegisterView(dispatcher); view.dom.rootElement.focus(); // The root element should have a tabindex="-1" to make the flutter view // focusable but not reachable by the keyboard. expect(view.dom.rootElement.getAttribute('tabindex'), '-1'); }); test('marks the focusable views as reachable by the keyboard or not', () async { final EngineFlutterView view1 = createAndRegisterView(dispatcher); final EngineFlutterView view2 = createAndRegisterView(dispatcher); expect(view1.dom.rootElement.getAttribute('tabindex'), '0'); expect(view2.dom.rootElement.getAttribute('tabindex'), '0'); view1.dom.rootElement.focus(); expect(view1.dom.rootElement.getAttribute('tabindex'), '-1'); expect(view2.dom.rootElement.getAttribute('tabindex'), '0'); view2.dom.rootElement.focus(); expect(view1.dom.rootElement.getAttribute('tabindex'), '0'); expect(view2.dom.rootElement.getAttribute('tabindex'), '-1'); view2.dom.rootElement.blur(); expect(view1.dom.rootElement.getAttribute('tabindex'), '0'); expect(view2.dom.rootElement.getAttribute('tabindex'), '0'); }); test('never marks the views as focusable with semantincs enabled', () async { EngineSemantics.instance.semanticsEnabled = true; final EngineFlutterView view1 = createAndRegisterView(dispatcher); final EngineFlutterView view2 = createAndRegisterView(dispatcher); expect(view1.dom.rootElement.getAttribute('tabindex'), isNull); expect(view2.dom.rootElement.getAttribute('tabindex'), isNull); view1.dom.rootElement.focus(); expect(view1.dom.rootElement.getAttribute('tabindex'), isNull); expect(view2.dom.rootElement.getAttribute('tabindex'), isNull); view2.dom.rootElement.focus(); expect(view1.dom.rootElement.getAttribute('tabindex'), isNull); expect(view2.dom.rootElement.getAttribute('tabindex'), isNull); view2.dom.rootElement.blur(); expect(view1.dom.rootElement.getAttribute('tabindex'), isNull); expect(view2.dom.rootElement.getAttribute('tabindex'), isNull); }); test('fires a focus event - a view was focused', () async { final EngineFlutterView view = createAndRegisterView(dispatcher); view.dom.rootElement.focus(); expect(dispatchedViewFocusEvents, hasLength(1)); expect(dispatchedViewFocusEvents[0].viewId, view.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); }); test('fires a focus event - a view was unfocused', () async { final EngineFlutterView view = createAndRegisterView(dispatcher); view.dom.rootElement.focus(); view.dom.rootElement.blur(); expect(dispatchedViewFocusEvents, hasLength(2)); expect(dispatchedViewFocusEvents[0].viewId, view.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); expect(dispatchedViewFocusEvents[1].viewId, view.viewId); expect(dispatchedViewFocusEvents[1].state, ui.ViewFocusState.unfocused); expect(dispatchedViewFocusEvents[1].direction, ui.ViewFocusDirection.undefined); }); test('fires a focus event - focus transitions between views', () async { final EngineFlutterView view1 = createAndRegisterView(dispatcher); final EngineFlutterView view2 = createAndRegisterView(dispatcher); view1.dom.rootElement.focus(); view2.dom.rootElement.focus(); // The statements simulate the user pressing shift + tab in the keyboard. // Synthetic keyboard events do not trigger focus changes. domDocument.body!.pressTabKey(shift: true); view1.dom.rootElement.focus(); domDocument.body!.releaseTabKey(); expect(dispatchedViewFocusEvents, hasLength(3)); expect(dispatchedViewFocusEvents[0].viewId, view1.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); expect(dispatchedViewFocusEvents[1].viewId, view2.viewId); expect(dispatchedViewFocusEvents[1].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[1].direction, ui.ViewFocusDirection.forward); expect(dispatchedViewFocusEvents[2].viewId, view1.viewId); expect(dispatchedViewFocusEvents[2].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[2].direction, ui.ViewFocusDirection.backward); }); test('fires a focus event - focus transitions on and off views', () async { final EngineFlutterView view1 = createAndRegisterView(dispatcher); final EngineFlutterView view2 = createAndRegisterView(dispatcher); view1.dom.rootElement.focus(); view2.dom.rootElement.focus(); view2.dom.rootElement.blur(); expect(dispatchedViewFocusEvents, hasLength(3)); expect(dispatchedViewFocusEvents[0].viewId, view1.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); expect(dispatchedViewFocusEvents[1].viewId, view2.viewId); expect(dispatchedViewFocusEvents[1].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[1].direction, ui.ViewFocusDirection.forward); expect(dispatchedViewFocusEvents[2].viewId, view2.viewId); expect(dispatchedViewFocusEvents[2].state, ui.ViewFocusState.unfocused); expect(dispatchedViewFocusEvents[2].direction, ui.ViewFocusDirection.undefined); }); test('requestViewFocusChange focuses the view', () { final EngineFlutterView view = createAndRegisterView(dispatcher); dispatcher.requestViewFocusChange( viewId: view.viewId, state: ui.ViewFocusState.focused, direction: ui.ViewFocusDirection.forward, ); expect(domDocument.activeElement, view.dom.rootElement); expect(dispatchedViewFocusEvents, hasLength(1)); expect(dispatchedViewFocusEvents[0].viewId, view.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); }); test('requestViewFocusChange blurs the view', () { final EngineFlutterView view = createAndRegisterView(dispatcher); dispatcher.requestViewFocusChange( viewId: view.viewId, state: ui.ViewFocusState.focused, direction: ui.ViewFocusDirection.forward, ); dispatcher.requestViewFocusChange( viewId: view.viewId, state: ui.ViewFocusState.unfocused, direction: ui.ViewFocusDirection.undefined, ); expect(domDocument.activeElement, isNot(view.dom.rootElement)); expect(dispatchedViewFocusEvents, hasLength(2)); expect(dispatchedViewFocusEvents[0].viewId, view.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); expect(dispatchedViewFocusEvents[1].viewId, view.viewId); expect(dispatchedViewFocusEvents[1].state, ui.ViewFocusState.unfocused); expect(dispatchedViewFocusEvents[1].direction, ui.ViewFocusDirection.undefined); }); test('requestViewFocusChange does nothing if the view does not exist', () { final EngineFlutterView view = createAndRegisterView(dispatcher); dispatcher.requestViewFocusChange( viewId: 5094555, state: ui.ViewFocusState.focused, direction: ui.ViewFocusDirection.forward, ); expect(domDocument.activeElement, isNot(view.dom.rootElement)); expect(dispatchedViewFocusEvents, isEmpty); }); test('requestViewFocusChange does nothing if the view is already focused', () { final EngineFlutterView view = createAndRegisterView(dispatcher); dispatcher.requestViewFocusChange( viewId: view.viewId, state: ui.ViewFocusState.focused, direction: ui.ViewFocusDirection.forward, ); dispatcher.requestViewFocusChange( viewId: view.viewId, state: ui.ViewFocusState.focused, direction: ui.ViewFocusDirection.forward, ); expect(dispatchedViewFocusEvents, hasLength(1)); expect(dispatchedViewFocusEvents[0].viewId, view.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); }); test('requestViewFocusChange does not move the focus to the view', () { final DomElement input = createDomElement('input'); final EngineFlutterView view = createAndRegisterView(dispatcher); view.dom.rootElement.append(input); input.focus(); dispatcher.requestViewFocusChange( viewId: view.viewId, state: ui.ViewFocusState.focused, direction: ui.ViewFocusDirection.forward, ); expect(domDocument.activeElement, input); expect(dispatchedViewFocusEvents, hasLength(1)); expect(dispatchedViewFocusEvents[0].viewId, view.viewId); expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused); expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.forward); }); }); } EngineFlutterView createAndRegisterView(EnginePlatformDispatcher dispatcher) { final DomElement div = createDomElement('div'); final EngineFlutterView view = EngineFlutterView(dispatcher, div); domDocument.body!.append(div); dispatcher.viewManager.registerView(view); return view; } extension on DomElement { void pressTabKey({bool shift = false}) { dispatchKeyboardEvent(type: 'keydown', key: 'Tab', shiftKey: shift); } void releaseTabKey({bool shift = false}) { dispatchKeyboardEvent(type: 'keyup', key: 'Tab', shiftKey: shift); } void dispatchKeyboardEvent({ required String type, required String key, bool shiftKey = false, }) { dispatchEvent( createDomKeyboardEvent(type, <String, Object>{'key': key, 'shiftKey': shiftKey}), ); } }
engine/lib/web_ui/test/engine/platform_dispatcher/view_focus_binding_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/platform_dispatcher/view_focus_binding_test.dart", "repo_id": "engine", "token_count": 4122 }
328
// 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 '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/rendering.dart'; import '../../common/test_initialization.dart'; import 'semantics_tester.dart'; const String _rootStyle = 'style="filter: opacity(0%); color: rgba(0, 0, 0, 0)"'; DateTime _testTime = DateTime(2023, 2, 17); EngineSemantics semantics() => EngineSemantics.instance; EngineSemanticsOwner owner() => EnginePlatformDispatcher.instance.implicitView!.semantics; void main() { internalBootstrapBrowserTest(() { return testMain; }); } Future<void> testMain() async { await bootstrapAndRunApp(withImplicitView: true); setUpRenderingForTests(); test('renders label text as DOM', () async { semantics() ..debugOverrideTimestampFunction(() => _testTime) ..semanticsEnabled = true; // Add a node with a label - expect a <span> { final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode( id: 0, label: 'Hello', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), ); tester.apply(); expectSemanticsTree(owner(), ''' <sem role="text" $_rootStyle>Hello</sem>''' ); final SemanticsObject node = owner().debugSemanticsTree![0]!; expect(node.primaryRole?.role, PrimaryRole.generic); expect( reason: 'A node with a label should get a LabelAndValue role', node.primaryRole!.debugSecondaryRoles, contains(Role.labelAndValue), ); } // Change label - expect both <span> and aria-label to be updated. { final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode( id: 0, label: 'World', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), ); tester.apply(); expectSemanticsTree(owner(), ''' <sem role="text" $_rootStyle>World</sem>''' ); } // Empty the label - expect the <span> to be removed. { final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode( id: 0, label: '', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), ); tester.apply(); expectSemanticsTree(owner(), '<sem role="text" $_rootStyle></sem>'); } semantics().semanticsEnabled = false; }); test('does not add a span in container nodes', () async { semantics() ..debugOverrideTimestampFunction(() => _testTime) ..semanticsEnabled = true; final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode( id: 0, label: 'I am a parent', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), children: <SemanticsNodeUpdate>[ tester.updateNode( id: 1, label: 'I am a child', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), ), ], ); tester.apply(); expectSemanticsTree(owner(), ''' <sem aria-label="I am a parent" role="group" $_rootStyle> <sem-c> <sem role="text">I am a child</sem> </sem-c> </sem>''' ); semantics().semanticsEnabled = false; }); test('adds a span when a leaf becomes a parent, and vice versa', () async { semantics() ..debugOverrideTimestampFunction(() => _testTime) ..semanticsEnabled = true; // A leaf node with a label - expect <span> { final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode( id: 0, label: 'I am a leaf', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), ); tester.apply(); expectSemanticsTree(owner(), ''' <sem role="text" $_rootStyle>I am a leaf</sem>''' ); } // Add a child - expect <span> to be removed from the parent. { final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode( id: 0, label: 'I am a parent', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), children: <SemanticsNodeUpdate>[ tester.updateNode( id: 1, label: 'I am a child', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), ), ], ); tester.apply(); expectSemanticsTree(owner(), ''' <sem aria-label="I am a parent" role="group" $_rootStyle> <sem-c> <sem role="text">I am a child</sem> </sem-c> </sem>''' ); } // Remove the child - expect the <span> to be readded to the former parent. { final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode( id: 0, label: 'I am a leaf again', transform: Matrix4.identity().toFloat64(), rect: const ui.Rect.fromLTRB(0, 0, 100, 50), ); tester.apply(); expectSemanticsTree(owner(), ''' <sem role="text" $_rootStyle>I am a leaf again</sem>''' ); } semantics().semanticsEnabled = false; }); }
engine/lib/web_ui/test/engine/semantics/semantics_crawler_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/semantics/semantics_crawler_test.dart", "repo_id": "engine", "token_count": 2395 }
329
// 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:js_util' as js_util; import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine/browser_detection.dart'; import 'package:ui/src/engine/dom.dart'; import 'package:ui/src/engine/raw_keyboard.dart'; import 'package:ui/src/engine/services.dart'; import 'package:ui/src/engine/text_editing/autofill_hint.dart'; import 'package:ui/src/engine/text_editing/input_type.dart'; import 'package:ui/src/engine/text_editing/text_editing.dart'; import 'package:ui/src/engine/util.dart'; import 'package:ui/src/engine/vector_math.dart'; import 'package:ui/ui.dart' as ui; import '../common/spy.dart'; import '../common/test_initialization.dart'; /// The `keyCode` of the "Enter" key. const int _kReturnKeyCode = 13; const MethodCodec codec = JSONMethodCodec(); /// Add unit tests for [FirefoxTextEditingStrategy]. // TODO(mdebbar): https://github.com/flutter/flutter/issues/46891 DefaultTextEditingStrategy? editingStrategy; EditingState? lastEditingState; TextEditingDeltaState? editingDeltaState; String? lastInputAction; final InputConfiguration singlelineConfig = InputConfiguration(); final Map<String, dynamic> flutterSinglelineConfig = createFlutterConfig('text'); final InputConfiguration multilineConfig = InputConfiguration( inputType: EngineInputType.multiline, inputAction: 'TextInputAction.newline', ); final Map<String, dynamic> flutterMultilineConfig = createFlutterConfig('multiline'); void trackEditingState(EditingState? editingState, TextEditingDeltaState? textEditingDeltaState) { lastEditingState = editingState; editingDeltaState = textEditingDeltaState; } void trackInputAction(String? inputAction) { lastInputAction = inputAction; } void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false ); tearDown(() { lastEditingState = null; editingDeltaState = null; lastInputAction = null; cleanTextEditingStrategy(); cleanTestFlags(); clearBackUpDomElementIfExists(); }); group('$GloballyPositionedTextEditingStrategy', () { late HybridTextEditing testTextEditing; setUp(() { testTextEditing = HybridTextEditing(); editingStrategy = GloballyPositionedTextEditingStrategy(testTextEditing); testTextEditing.debugTextEditingStrategyOverride = editingStrategy; testTextEditing.configuration = singlelineConfig; }); test('Creates element when enabled and removes it when disabled', () { expect( domDocument.getElementsByTagName('input'), hasLength(0), ); // The focus initially is on the body. expect(domDocument.activeElement, domDocument.body); expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); expect( defaultTextEditingRoot.querySelectorAll('input'), hasLength(1), ); final DomElement input = defaultTextEditingRoot.querySelector('input')!; // Now the editing element should have focus. expect(domDocument.activeElement, input); expect(defaultTextEditingRoot.ownerDocument?.activeElement, input); expect(editingStrategy!.domElement, input); expect(input.getAttribute('type'), null); // Input is appended to the right point of the DOM. expect(defaultTextEditingRoot.contains(editingStrategy!.domElement), isTrue); editingStrategy!.disable(); expect( defaultTextEditingRoot.querySelectorAll('input'), hasLength(0), ); // The focus is back to the body. expect(domDocument.activeElement, domDocument.body); expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); }); test('Respects read-only config', () { final InputConfiguration config = InputConfiguration( readOnly: true, ); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(1)); final DomElement input = defaultTextEditingRoot.querySelector('input')!; expect(editingStrategy!.domElement, input); expect(input.getAttribute('readonly'), 'readonly'); editingStrategy!.disable(); }); test('Knows how to create password fields', () { final InputConfiguration config = InputConfiguration( obscureText: true, ); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(1)); final DomElement input = defaultTextEditingRoot.querySelector('input')!; expect(editingStrategy!.domElement, input); expect(input.getAttribute('type'), 'password'); editingStrategy!.disable(); }); test('Knows how to create non-default text actions', () { final InputConfiguration config = InputConfiguration( inputAction: 'TextInputAction.send' ); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(1)); final DomElement input = defaultTextEditingRoot.querySelector('input')!; expect(editingStrategy!.domElement, input); if (operatingSystem == OperatingSystem.iOs || operatingSystem == OperatingSystem.android){ expect(input.getAttribute('enterkeyhint'), 'send'); } else { expect(input.getAttribute('enterkeyhint'), null); } editingStrategy!.disable(); }); test('Knows to turn autocorrect off', () { final InputConfiguration config = InputConfiguration( autocorrect: false, ); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(1)); final DomElement input = defaultTextEditingRoot.querySelector('input')!; expect(editingStrategy!.domElement, input); expect(input.getAttribute('autocorrect'), 'off'); editingStrategy!.disable(); }); test('Knows to turn autocorrect on', () { final InputConfiguration config = InputConfiguration(); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(1)); final DomElement input = defaultTextEditingRoot.querySelector('input')!; expect(editingStrategy!.domElement, input); expect(input.getAttribute('autocorrect'), 'on'); editingStrategy!.disable(); }); test('Knows to turn autofill off', () { final InputConfiguration config = InputConfiguration(); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(1)); final DomElement input = defaultTextEditingRoot.querySelector('input')!; expect(editingStrategy!.domElement, input); expect(input.getAttribute('autocomplete'), 'off'); editingStrategy!.disable(); }); test('Can read editing state correctly', () { editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); final DomHTMLInputElement input = editingStrategy!.domElement! as DomHTMLInputElement; input.value = 'foo bar'; input.dispatchEvent(createDomEvent('Event', 'input')); expect( lastEditingState, EditingState(text: 'foo bar', baseOffset: 7, extentOffset: 7), ); input.setSelectionRange(4, 6); domDocument.dispatchEvent(createDomEvent('Event', 'selectionchange')); expect( lastEditingState, EditingState(text: 'foo bar', baseOffset: 4, extentOffset: 6), ); // There should be no input action. expect(lastInputAction, isNull); }); test('Can set editing state correctly', () { editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); editingStrategy!.setEditingState( EditingState(text: 'foo bar baz', baseOffset: 2, extentOffset: 7)); checkInputEditingState(editingStrategy!.domElement, 'foo bar baz', 2, 7); // There should be no input action. expect(lastInputAction, isNull); }); test('Multi-line mode also works', () { // The textarea element is created lazily. expect(domDocument.getElementsByTagName('textarea'), hasLength(0)); editingStrategy!.enable( multilineConfig, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('textarea'), hasLength(1)); final DomHTMLTextAreaElement textarea = defaultTextEditingRoot.querySelector('textarea')! as DomHTMLTextAreaElement; // Now the textarea should have focus. expect(defaultTextEditingRoot.ownerDocument?.activeElement, textarea); expect(editingStrategy!.domElement, textarea); textarea.value = 'foo\nbar'; textarea.dispatchEvent(createDomEvent('Event', 'input')); textarea.setSelectionRange(4, 6); domDocument.dispatchEvent(createDomEvent('Event', 'selectionchange')); // Can read textarea state correctly (and preserves new lines). expect( lastEditingState, EditingState(text: 'foo\nbar', baseOffset: 4, extentOffset: 6), ); // Can set textarea state correctly (and preserves new lines). editingStrategy!.setEditingState( EditingState(text: 'bar\nbaz', baseOffset: 2, extentOffset: 7)); checkTextAreaEditingState(textarea, 'bar\nbaz', 2, 7); editingStrategy!.disable(); // The textarea should be cleaned up. expect(defaultTextEditingRoot.querySelectorAll('textarea'), hasLength(0)); // The focus is back to the body. expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); // There should be no input action. expect(lastInputAction, isNull); }); test('Same instance can be re-enabled with different config', () { // Make sure there's nothing in the DOM yet. expect(domDocument.getElementsByTagName('input'), hasLength(0)); expect(domDocument.getElementsByTagName('textarea'), hasLength(0)); // Use single-line config and expect an `<input>` to be created. editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(1)); expect(defaultTextEditingRoot.querySelectorAll('textarea'), hasLength(0)); // Disable and check that all DOM elements were removed. editingStrategy!.disable(); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(0)); expect(defaultTextEditingRoot.querySelectorAll('textarea'), hasLength(0)); // Use multi-line config and expect an `<textarea>` to be created. editingStrategy!.enable( multilineConfig, onChange: trackEditingState, onAction: trackInputAction, ); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(0)); expect(defaultTextEditingRoot.querySelectorAll('textarea'), hasLength(1)); // Disable again and check that all DOM elements were removed. editingStrategy!.disable(); expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(0)); expect(defaultTextEditingRoot.querySelectorAll('textarea'), hasLength(0)); // There should be no input action. expect(lastInputAction, isNull); }); test('Triggers input action', () { final InputConfiguration config = InputConfiguration(); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); // No input action so far. expect(lastInputAction, isNull); dispatchKeyboardEvent( editingStrategy!.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); expect(lastInputAction, 'TextInputAction.done'); }); test('handling keyboard event prevents triggering input action', () { final ui.PlatformMessageCallback? savedCallback = ui.PlatformDispatcher.instance.onPlatformMessage; bool markTextEventHandled = false; ui.PlatformDispatcher.instance.onPlatformMessage = (String channel, ByteData? data, ui.PlatformMessageResponseCallback? callback) { final ByteData response = const JSONMessageCodec() .encodeMessage(<String, dynamic>{'handled': markTextEventHandled})!; callback!(response); }; RawKeyboard.initialize(); final InputConfiguration config = InputConfiguration(); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); // No input action so far. expect(lastInputAction, isNull); markTextEventHandled = true; dispatchKeyboardEvent( editingStrategy!.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); // Input action prevented by platform message callback. expect(lastInputAction, isNull); markTextEventHandled = false; dispatchKeyboardEvent( editingStrategy!.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); // Input action received. expect(lastInputAction, 'TextInputAction.done'); ui.PlatformDispatcher.instance.onPlatformMessage = savedCallback; RawKeyboard.instance?.dispose(); }); test('Triggers input action in multi-line mode', () { final InputConfiguration config = InputConfiguration( inputType: EngineInputType.multiline, ); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); // No input action so far. expect(lastInputAction, isNull); final DomKeyboardEvent event = dispatchKeyboardEvent( editingStrategy!.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); // Input action is triggered! expect(lastInputAction, 'TextInputAction.done'); // And default behavior of keyboard event shouldn't have been prevented. expect(event.defaultPrevented, isFalse); }); test('Triggers input action in multiline-none mode', () { final InputConfiguration config = InputConfiguration( inputType: EngineInputType.multilineNone, ); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); // No input action so far. expect(lastInputAction, isNull); final DomKeyboardEvent event = dispatchKeyboardEvent( editingStrategy!.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); // Input action is triggered! expect(lastInputAction, 'TextInputAction.done'); // And default behavior of keyboard event shouldn't have been prevented. expect(event.defaultPrevented, isFalse); }); test('Triggers input action and prevent new line key event for single line field', () { // Regression test for https://github.com/flutter/flutter/issues/113559 final InputConfiguration config = InputConfiguration(); editingStrategy!.enable( config, onChange: trackEditingState, onAction: trackInputAction, ); // No input action so far. expect(lastInputAction, isNull); final DomKeyboardEvent event = dispatchKeyboardEvent( editingStrategy!.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); expect(lastInputAction, 'TextInputAction.done'); // And default behavior of keyboard event should have been prevented. expect(event.defaultPrevented, isTrue); }); test('globally positions and sizes its DOM element', () { editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); expect(editingStrategy!.isEnabled, isTrue); // No geometry should be set until setEditableSizeAndTransform is called. expect(editingStrategy!.domElement!.style.transform, ''); expect(editingStrategy!.domElement!.style.width, ''); expect(editingStrategy!.domElement!.style.height, ''); testTextEditing.acceptCommand(TextInputSetEditableSizeAndTransform(geometry: EditableTextGeometry( width: 13, height: 12, globalTransform: Matrix4.translationValues(14, 15, 0).storage, )), () {}); // setEditableSizeAndTransform calls placeElement, so expecting geometry to be applied. expect(editingStrategy!.domElement!.style.transform, 'matrix(1, 0, 0, 1, 14, 15)'); expect(editingStrategy!.domElement!.style.width, '13px'); expect(editingStrategy!.domElement!.style.height, '12px'); }); test('updateElementPlacement() should not call placeElement() when in mid-composition', () { final HybridTextEditing testTextEditing = HybridTextEditing(); final GlobalTextEditingStrategySpy editingStrategy = GlobalTextEditingStrategySpy(testTextEditing); testTextEditing.debugTextEditingStrategyOverride = editingStrategy; testTextEditing.configuration = singlelineConfig; editingStrategy.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); expect(editingStrategy.isEnabled, isTrue); // placeElement() called from enable() expect(editingStrategy.placeElementCount, 1); // No geometry should be set until setEditableSizeAndTransform is called. expect(editingStrategy.domElement!.style.transform, ''); expect(editingStrategy.domElement!.style.width, ''); expect(editingStrategy.domElement!.style.height, ''); // set some composing text. editingStrategy.composingText = '뮤'; testTextEditing.acceptCommand(TextInputSetEditableSizeAndTransform(geometry: EditableTextGeometry( width: 13, height: 12, globalTransform: Matrix4.translationValues(14, 15, 0).storage, )), () {}); // placeElement() should not be called again. expect(editingStrategy.placeElementCount, 1); // geometry should be applied. expect(editingStrategy.domElement!.style.transform, 'matrix(1, 0, 0, 1, 14, 15)'); expect(editingStrategy.domElement!.style.width, '13px'); expect(editingStrategy.domElement!.style.height, '12px'); // set composing text to null. editingStrategy.composingText = null; testTextEditing.acceptCommand(TextInputSetEditableSizeAndTransform(geometry: EditableTextGeometry( width: 10, height: 10, globalTransform: Matrix4.translationValues(11, 12, 0).storage, )), () {}); // placeElement() should be called again. expect(editingStrategy.placeElementCount, 2); // geometry should be updated. expect(editingStrategy.domElement!.style.transform, 'matrix(1, 0, 0, 1, 11, 12)'); expect(editingStrategy.domElement!.style.width, '10px'); expect(editingStrategy.domElement!.style.height, '10px'); }); }); group('$HybridTextEditing', () { HybridTextEditing? textEditing; final PlatformMessagesSpy spy = PlatformMessagesSpy(); int clientId = 0; /// Emulates sending of a message by the framework to the engine. void sendFrameworkMessage(ByteData? message) { textEditing!.channel.handleTextInput(message, (ByteData? data) {}); } /// Sends the necessary platform messages to activate a text field and show /// the keyboard. /// /// Returns the `clientId` used in the platform message. int showKeyboard({ required String inputType, String? inputAction, bool decimal = false, bool isMultiline = false, }) { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[ ++clientId, createFlutterConfig(inputType, inputAction: inputAction, decimal: decimal, isMultiline: isMultiline), ], ); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); return clientId; } void hideKeyboard() { const MethodCall hide = MethodCall('TextInput.hide'); sendFrameworkMessage(codec.encodeMethodCall(hide)); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); } String? getEditingInputMode() { return textEditing!.strategy.domElement!.getAttribute('inputmode'); } setUp(() { textEditing = HybridTextEditing(); spy.setUp(); }); tearDown(() { spy.tearDown(); if (textEditing!.isEditing) { textEditing!.stopEditing(); } textEditing = null; }); test('TextInput.requestAutofill', () async { const MethodCall requestAutofill = MethodCall('TextInput.requestAutofill'); sendFrameworkMessage(codec.encodeMethodCall(requestAutofill)); //No-op and without crashing. }); test('setClient, show, setEditingState, hide', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); // Editing shouldn't have started yet. expect(domDocument.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); checkInputEditingState(textEditing!.strategy.domElement, '', 0, 0); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); const MethodCall hide = MethodCall('TextInput.hide'); sendFrameworkMessage(codec.encodeMethodCall(hide)); // Text editing should've stopped. expect(domDocument.activeElement, domDocument.body); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); }); test('setClient, setEditingState, show, clearClient', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); // Editing shouldn't have started yet. expect(domDocument.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); expect(domDocument.activeElement, domDocument.body); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); }); test('setClient, setEditingState, setSizeAndTransform, show - input element is put into the DOM Safari Desktop', () async { editingStrategy = SafariDesktopTextEditingStrategy(textEditing!); textEditing!.debugTextEditingStrategyOverride = editingStrategy; final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // Editing shouldn't have started yet. expect(domDocument.activeElement, domDocument.body); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); expect(defaultTextEditingRoot.ownerDocument?.activeElement, textEditing!.strategy.domElement); }, skip: !isSafari); test('setClient, setEditingState, show, updateConfig, clearClient', () { final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[ 123, createFlutterConfig('text', readOnly: true), ]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall( 'TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }, ); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); final DomElement element = textEditing!.strategy.domElement!; expect(element.getAttribute('readonly'), 'readonly'); // Update the read-only config. final MethodCall updateConfig = MethodCall( 'TextInput.updateConfig', createFlutterConfig('text'), ); sendFrameworkMessage(codec.encodeMethodCall(updateConfig)); expect(element.hasAttribute('readonly'), isFalse); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); }); test('focus and connection with blur', () async { // In all the desktop browsers we are keeping the connection // open, keep the text editing element focused if it receives a blur // event. final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); // Editing shouldn't have started yet. expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); expect(textEditing!.isEditing, isTrue); // DOM element is blurred. textEditing!.strategy.domElement!.blur(); // No connection close message sent. expect(spy.messages, hasLength(0)); await Future<void>.delayed(Duration.zero); // DOM element still keeps the focus. expect(defaultTextEditingRoot.ownerDocument?.activeElement, textEditing!.strategy.domElement); }); test('focus and disconnection with delaying blur in iOS', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); // Editing shouldn't have started yet. expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); expect(textEditing!.isEditing, isTrue); // Delay for not to be a fast callback with blur. await Future<void>.delayed(const Duration(milliseconds: 200)); // DOM element is blurred. textEditing!.strategy.domElement!.blur(); expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect( spy.messages[0].methodName, 'TextInputClient.onConnectionClosed'); await Future<void>.delayed(Duration.zero); // DOM element loses the focus. expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); }, // Test on ios-safari only. skip: browserEngine != BrowserEngine.webkit || operatingSystem != OperatingSystem.iOs); test('finishAutofillContext closes connection no autofill element', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); // Editing shouldn't have started yet. expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); const MethodCall finishAutofillContext = MethodCall('TextInput.finishAutofillContext', false); sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext)); expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.onConnectionClosed'); expect( spy.messages[0].methodArguments, <dynamic>[ 123, // Client ID ], ); spy.messages.clear(); // Input element is removed from DOM. expect(defaultTextEditingRoot.querySelectorAll('input'), hasLength(0)); }); test('finishAutofillContext removes form from DOM', () async { // Create a configuration with an AutofillGroup of four text fields. final Map<String, dynamic> flutterMultiAutofillElementConfig = createFlutterConfig( 'text', autofillHint: 'username', autofillHintsForFields: <String>[ 'username', 'email', 'name', 'telephoneNumber' ], ); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterMultiAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The transform is changed. For example after a validation error, red // line appeared under the input field. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); // Form is added to DOM. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); // Form stays on the DOM until autofill context is finalized. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); expect(formsOnTheDom, hasLength(1)); const MethodCall finishAutofillContext = MethodCall('TextInput.finishAutofillContext', false); sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext)); // Form element is removed from DOM. expect(defaultTextEditingRoot.querySelectorAll('form'), isEmpty); expect(formsOnTheDom, hasLength(0)); }); test('finishAutofillContext with save submits forms', () async { // Create a configuration with an AutofillGroup of four text fields. final Map<String, dynamic> flutterMultiAutofillElementConfig = createFlutterConfig('text', autofillHint: 'username', autofillHintsForFields: <String>[ 'username', 'email', 'name', 'telephoneNumber' ]); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterMultiAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The transform is changed. For example after a validation error, red // line appeared under the input field. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); // Form is added to DOM. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); final DomHTMLFormElement formElement = defaultTextEditingRoot.querySelector('form')! as DomHTMLFormElement; final Completer<bool> submittedForm = Completer<bool>(); formElement.addEventListener( 'submit', createDomEventListener((DomEvent event) => submittedForm.complete(true))); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); const MethodCall finishAutofillContext = MethodCall('TextInput.finishAutofillContext', true); sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext)); // `submit` action is called on form. await expectLater(await submittedForm.future, isTrue); }); test('forms submits for focused input', () async { // Create a configuration with an AutofillGroup of four text fields. final Map<String, dynamic> flutterMultiAutofillElementConfig = createFlutterConfig('text', autofillHint: 'username', autofillHintsForFields: <String>[ 'username', 'email', 'name', 'telephoneNumber' ]); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterMultiAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The transform is changed. For example after a validation error, red // line appeared under the input field. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); // Form is added to DOM. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); final DomHTMLFormElement formElement = defaultTextEditingRoot.querySelector('form')! as DomHTMLFormElement; final Completer<bool> submittedForm = Completer<bool>(); formElement.addEventListener( 'submit', createDomEventListener((DomEvent event) => submittedForm.complete(true))); // Clear client is not called. The used requested context to be finalized. const MethodCall finishAutofillContext = MethodCall('TextInput.finishAutofillContext', true); sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext)); // Connection is closed by the engine. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.onConnectionClosed'); // `submit` action is called on form. await expectLater(await submittedForm.future, isTrue); // Form element is removed from DOM. expect(defaultTextEditingRoot.querySelectorAll('form'), hasLength(0)); expect(formsOnTheDom, hasLength(0)); }); test('form is not placed and input is not focused until after tick on Desktop Safari', () async { // Create a configuration with an AutofillGroup of four text fields. final Map<String, dynamic> flutterMultiAutofillElementConfig = createFlutterConfig('text', autofillHint: 'username', autofillHintsForFields: <String>[ 'username', 'email', 'name', 'telephoneNumber' ]); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterMultiAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); // Prior to tick, form should not exist and no elements should be focused. expect(defaultTextEditingRoot.querySelectorAll('form'), isEmpty); expect(domDocument.activeElement, domDocument.body); await waitForDesktopSafariFocus(); // Form is added to DOM. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); final DomHTMLInputElement inputElement = textEditing!.strategy.domElement! as DomHTMLInputElement; expect(domDocument.activeElement, inputElement); }, skip: !isSafari); test('setClient, setEditingState, show, setClient', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); // Editing shouldn't have started yet. expect(domDocument.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); final MethodCall setClient2 = MethodCall( 'TextInput.setClient', <dynamic>[567, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient2)); // Receiving another client via setClient should stop editing, hence // should remove the previous active element. expect(domDocument.activeElement, domDocument.body); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); hideKeyboard(); }); test('setClient, setEditingState, show, setEditingState, clearClient', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); const MethodCall setEditingState2 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'xyz', 'selectionBase': 0, 'selectionExtent': 2, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState2)); await waitForDesktopSafariFocus(); // The second [setEditingState] should override the first one. checkInputEditingState( textEditing!.strategy.domElement, 'xyz', 0, 2); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); }); test( 'singleTextField Autofill: setClient, setEditingState, show, ' 'setSizeAndTransform, setEditingState, clearClient', () async { // Create a configuration with focused element has autofil hint. final Map<String, dynamic> flutterSingleAutofillElementConfig = createFlutterConfig('text', autofillHint: 'username'); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterSingleAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); // The second [setEditingState] should override the first one. checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); final DomHTMLFormElement formElement = defaultTextEditingRoot.querySelector('form')! as DomHTMLFormElement; // The form has one input element and one submit button. expect(formElement.childNodes, hasLength(2)); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); // Form stays on the DOM until autofill context is finalized. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); expect(formsOnTheDom, hasLength(1)); }); test( 'singleTextField Autofill setEditableSizeAndTransform preserves' 'editing state', () async { // Create a configuration with focused element has autofil hint. final Map<String, dynamic> flutterSingleAutofillElementConfig = createFlutterConfig('text', autofillHint: 'username'); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterSingleAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(10, 10, Matrix4.translationValues(10.0, 10.0, 10.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); final DomHTMLInputElement inputElement = textEditing!.strategy.domElement! as DomHTMLInputElement; expect(inputElement.value, 'abcd'); if (!(browserEngine == BrowserEngine.webkit && operatingSystem == OperatingSystem.macOs)) { // In Safari Desktop Autofill menu appears as soon as an element is // focused, therefore the input element is only focused after the // location is received. expect( defaultTextEditingRoot.ownerDocument?.activeElement, inputElement); expect(inputElement.selectionStart, 2); expect(inputElement.selectionEnd, 3); } // The transform is changed. For example after a validation error, red // line appeared under the input field. final MethodCall updateSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(updateSizeAndTransform)); await waitForDesktopSafariFocus(); // Check the element still has focus. User can keep editing. expect(defaultTextEditingRoot.ownerDocument?.activeElement, textEditing!.strategy.domElement); // Check the cursor location is the same. checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); // Form stays on the DOM until autofill context is finalized. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); expect(formsOnTheDom, hasLength(1)); }); test( 'multiTextField Autofill: setClient, setEditingState, show, ' 'setSizeAndTransform setEditingState, clearClient', () async { // Create a configuration with an AutofillGroup of four text fields. final Map<String, dynamic> flutterMultiAutofillElementConfig = createFlutterConfig('text', autofillHint: 'username', autofillHintsForFields: <String>[ 'username', 'email', 'name', 'telephoneNumber' ]); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterMultiAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); // The second [setEditingState] should override the first one. checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); final DomHTMLFormElement formElement = defaultTextEditingRoot.querySelector('form')! as DomHTMLFormElement; // The form has 4 input elements and one submit button. expect(formElement.childNodes, hasLength(5)); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); // Form stays on the DOM until autofill context is finalized. expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); expect(formsOnTheDom, hasLength(1)); }); test('No capitalization: setClient, setEditingState, show', () { // Create a configuration with an AutofillGroup of four text fields. final Map<String, dynamic> capitalizeWordsConfig = createFlutterConfig( 'text'); final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, capitalizeWordsConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': '', 'selectionBase': 0, 'selectionExtent': 0, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); spy.messages.clear(); // Test for mobile Safari. `sentences` is the default attribute for // mobile browsers. Check if `off` is added to the input element. if (browserEngine == BrowserEngine.webkit && operatingSystem == OperatingSystem.iOs) { expect( textEditing!.strategy.domElement! .getAttribute('autocapitalize'), 'off'); } else { expect( textEditing!.strategy.domElement! .getAttribute('autocapitalize'), isNull); } spy.messages.clear(); hideKeyboard(); }); test('All characters capitalization: setClient, setEditingState, show', () { // Create a configuration with an AutofillGroup of four text fields. final Map<String, dynamic> capitalizeWordsConfig = createFlutterConfig( 'text', textCapitalization: 'TextCapitalization.characters'); final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, capitalizeWordsConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': '', 'selectionBase': 0, 'selectionExtent': 0, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); spy.messages.clear(); // Test for mobile Safari. if (browserEngine == BrowserEngine.webkit && operatingSystem == OperatingSystem.iOs) { expect( textEditing!.strategy.domElement! .getAttribute('autocapitalize'), 'characters'); } spy.messages.clear(); hideKeyboard(); }); test( 'setClient, setEditableSizeAndTransform, setStyle, setEditingState, show, clearClient', () { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); final MethodCall setStyle = configureSetStyleMethodCall(12, 'sans-serif', 4, 4, 1); sendFrameworkMessage(codec.encodeMethodCall(setStyle)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); final DomElement domElement = textEditing!.strategy.domElement!; checkInputEditingState(domElement, 'abcd', 2, 3); // Check if the location and styling is correct. final DomRect boundingRect = domElement.getBoundingClientRect(); expect(boundingRect.left, 10.0); expect(boundingRect.top, 20.0); expect(boundingRect.right, 160.0); expect(boundingRect.bottom, 70.0); expect(domElement.style.transform, 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1)'); expect(textEditing!.strategy.domElement!.style.font, '500 12px sans-serif'); const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); // Confirm that [HybridTextEditing] didn't send any messages. expect(spy.messages, isEmpty); }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/50590 skip: browserEngine == BrowserEngine.webkit); test( 'setClient, show, setEditableSizeAndTransform, setStyle, setEditingState, clearClient', () { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall( 150, 50, Matrix4.translationValues( 10.0, 20.0, 30.0, ).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); final MethodCall setStyle = configureSetStyleMethodCall(12, 'sans-serif', 4, 4, 1); sendFrameworkMessage(codec.encodeMethodCall(setStyle)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); final DomHTMLElement domElement = textEditing!.strategy.domElement!; checkInputEditingState(domElement, 'abcd', 2, 3); // Check if the position is correct. final DomRect boundingRect = domElement.getBoundingClientRect(); expect(boundingRect.left, 10.0); expect(boundingRect.top, 20.0); expect(boundingRect.right, 160.0); expect(boundingRect.bottom, 70.0); expect( domElement.style.transform, 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1)', ); expect( textEditing!.strategy.domElement!.style.font, '500 12px sans-serif', ); // For `blink` and `webkit` browser engines the overlay would be hidden. if (browserEngine == BrowserEngine.blink || browserEngine == BrowserEngine.webkit) { expect(textEditing!.strategy.domElement!.classList.contains('transparentTextEditing'), isTrue); } else { expect( textEditing!.strategy.domElement!.classList.contains('transparentTextEditing'), isFalse); } const MethodCall clearClient = MethodCall('TextInput.clearClient'); sendFrameworkMessage(codec.encodeMethodCall(clearClient)); }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/50590 skip: browserEngine == BrowserEngine.webkit); test('input font set successfully with null fontWeightIndex', () { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); final MethodCall setStyle = configureSetStyleMethodCall( 12, 'sans-serif', 4, null /* fontWeightIndex */, 1); sendFrameworkMessage(codec.encodeMethodCall(setStyle)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); final DomHTMLElement domElement = textEditing!.strategy.domElement!; checkInputEditingState(domElement, 'abcd', 2, 3); // Check if the location and styling is correct. final DomRect boundingRect = domElement.getBoundingClientRect(); expect(boundingRect.left, 10.0); expect(boundingRect.top, 20.0); expect(boundingRect.right, 160.0); expect(boundingRect.bottom, 70.0); expect(domElement.style.transform, 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1)'); expect( textEditing!.strategy.domElement!.style.font, '12px sans-serif'); hideKeyboard(); }, // TODO(mdebbar): https://github.com/flutter/flutter/issues/50590 skip: browserEngine == BrowserEngine.webkit); test('Canonicalizes font family', () { showKeyboard(inputType: 'text'); final DomHTMLElement input = textEditing!.strategy.domElement!; MethodCall setStyle; setStyle = configureSetStyleMethodCall(12, 'sans-serif', 4, 4, 1); sendFrameworkMessage(codec.encodeMethodCall(setStyle)); expect(input.style.fontFamily, canonicalizeFontFamily('sans-serif')); setStyle = configureSetStyleMethodCall(12, '.SF Pro Text', 4, 4, 1); sendFrameworkMessage(codec.encodeMethodCall(setStyle)); expect(input.style.fontFamily, canonicalizeFontFamily('.SF Pro Text')); setStyle = configureSetStyleMethodCall(12, 'foo bar baz', 4, 4, 1); sendFrameworkMessage(codec.encodeMethodCall(setStyle)); expect(input.style.fontFamily, canonicalizeFontFamily('foo bar baz')); hideKeyboard(); }); test( 'negative base offset and selection extent values in editing state is handled', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'xyz', 'selectionBase': 1, 'selectionExtent': 2, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); // Check if the selection range is correct. checkInputEditingState( textEditing!.strategy.domElement, 'xyz', 1, 2); const MethodCall setEditingState2 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'xyz', 'selectionBase': -1, 'selectionExtent': -1, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState2)); // The negative offset values are applied to the dom element as 0. checkInputEditingState( textEditing!.strategy.domElement, 'xyz', 0, 0); hideKeyboard(); }); test('Syncs the editing state back to Flutter', () { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); final DomHTMLInputElement input = textEditing!.strategy.domElement! as DomHTMLInputElement; input.value = 'something'; input.dispatchEvent(createDomEvent('Event', 'input')); expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.updateEditingState'); expect( spy.messages[0].methodArguments, <dynamic>[ 123, // Client ID <String, dynamic>{ 'text': 'something', 'selectionBase': 9, 'selectionExtent': 9, 'composingBase': -1, 'composingExtent': -1 } ], ); spy.messages.clear(); input.setSelectionRange(2, 5); if (browserEngine == BrowserEngine.firefox) { final DomEvent keyup = createDomEvent('Event', 'keyup'); textEditing!.strategy.domElement!.dispatchEvent(keyup); } else { domDocument.dispatchEvent(createDomEvent('Event', 'selectionchange')); } expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.updateEditingState'); expect( spy.messages[0].methodArguments, <dynamic>[ 123, // Client ID <String, dynamic>{ 'text': 'something', 'selectionBase': 2, 'selectionExtent': 5, 'composingBase': -1, 'composingExtent': -1 } ], ); spy.messages.clear(); hideKeyboard(); }); test('Syncs the editing state back to Flutter - delta model', () { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, createFlutterConfig('text', enableDeltaModel: true)]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': '', 'selectionBase': -1, 'selectionExtent': -1, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); final DomHTMLInputElement input = textEditing!.strategy.domElement! as DomHTMLInputElement; input.value = 'something'; input.dispatchEvent(createDomEvent('Event', 'input')); spy.messages.clear(); input.setSelectionRange(2, 5); if (browserEngine == BrowserEngine.firefox) { final DomEvent keyup = createDomEvent('Event', 'keyup'); textEditing!.strategy.domElement!.dispatchEvent(keyup); } else { domDocument.dispatchEvent(createDomEvent('Event', 'selectionchange')); } expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.updateEditingStateWithDeltas'); expect( spy.messages[0].methodArguments, <dynamic>[ 123, // Client ID <String, dynamic>{ 'deltas': <Map<String, dynamic>>[ <String, dynamic>{ 'oldText': 'something', 'deltaText': '', 'deltaStart': -1, 'deltaEnd': -1, 'selectionBase': 2, 'selectionExtent': 5, 'composingBase': -1, 'composingExtent': -1 } ], } ], ); spy.messages.clear(); hideKeyboard(); }); test('Supports deletion at inverted selection', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, createFlutterConfig('text', enableDeltaModel: true)]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'Hello world', 'selectionBase': 9, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); final DomHTMLInputElement input = textEditing!.strategy.domElement! as DomHTMLInputElement; final DomInputEvent testEvent = createDomInputEvent( 'beforeinput', <Object?, Object?>{ 'inputType': 'deleteContentBackward', }, ); input.dispatchEvent(testEvent); final EditingState editingState = EditingState( text: 'Helld', baseOffset: 3, extentOffset: 3, ); editingState.applyToDomElement(input); input.dispatchEvent(createDomEvent('Event', 'input')); expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.updateEditingStateWithDeltas'); expect( spy.messages[0].methodArguments, <dynamic>[ 123, // Client ID <String, dynamic>{ 'deltas': <Map<String, dynamic>>[ <String, dynamic>{ 'oldText': 'Hello world', 'deltaText': '', 'deltaStart': 3, 'deltaEnd': 9, 'selectionBase': 3, 'selectionExtent': 3, 'composingBase': -1, 'composingExtent': -1 } ], } ], ); spy.messages.clear(); hideKeyboard(); // TODO(Renzo-Olivares): https://github.com/flutter/flutter/issues/134271 }, skip: isSafari); test('Supports new line at inverted selection', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, createFlutterConfig('text', enableDeltaModel: true)]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'Hello world', 'selectionBase': 9, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); final DomHTMLInputElement input = textEditing!.strategy.domElement! as DomHTMLInputElement; final DomInputEvent testEvent = createDomInputEvent( 'beforeinput', <Object?, Object?>{ 'inputType': 'insertLineBreak', }, ); input.dispatchEvent(testEvent); final EditingState editingState = EditingState( text: 'Hel\nld', baseOffset: 3, extentOffset: 3, ); editingState.applyToDomElement(input); input.dispatchEvent(createDomEvent('Event', 'input')); expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.updateEditingStateWithDeltas'); expect( spy.messages[0].methodArguments, <dynamic>[ 123, // Client ID <String, dynamic>{ 'deltas': <Map<String, dynamic>>[ <String, dynamic>{ 'oldText': 'Hello world', 'deltaText': '\n', 'deltaStart': 3, 'deltaEnd': 9, 'selectionBase': 3, 'selectionExtent': 3, 'composingBase': -1, 'composingExtent': -1 } ], } ], ); spy.messages.clear(); hideKeyboard(); // TODO(Renzo-Olivares): https://github.com/flutter/flutter/issues/134271 }, skip: isSafari); test('multiTextField Autofill sync updates back to Flutter', () async { // Create a configuration with an AutofillGroup of four text fields. const String hintForFirstElement = 'familyName'; final Map<String, dynamic> flutterMultiAutofillElementConfig = createFlutterConfig('text', autofillHint: 'email', autofillHintsForFields: <String>[ hintForFirstElement, 'email', 'givenName', 'telephoneNumber' ]); final MethodCall setClient = MethodCall('TextInput.setClient', <dynamic>[123, flutterMultiAutofillElementConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall setEditingState1 = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'abcd', 'selectionBase': 2, 'selectionExtent': 3, }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState1)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); // The second [setEditingState] should override the first one. checkInputEditingState( textEditing!.strategy.domElement, 'abcd', 2, 3); final DomHTMLFormElement formElement = defaultTextEditingRoot.querySelector('form')! as DomHTMLFormElement; // The form has 4 input elements and one submit button. expect(formElement.childNodes, hasLength(5)); // Autofill one of the form elements. final DomHTMLInputElement element = formElement.childNodes.toList()[0] as DomHTMLInputElement; if (browserEngine == BrowserEngine.firefox) { expect(element.name, BrowserAutofillHints.instance.flutterToEngine(hintForFirstElement)); } else { expect(element.autocomplete, BrowserAutofillHints.instance.flutterToEngine(hintForFirstElement)); } element.value = 'something'; element.dispatchEvent(createDomEvent('Event', 'input')); expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.updateEditingStateWithTag'); expect( spy.messages[0].methodArguments, <dynamic>[ 0, // Client ID <String, dynamic>{ hintForFirstElement: <String, dynamic>{ 'text': 'something', 'selectionBase': 9, 'selectionExtent': 9, 'composingBase': -1, 'composingExtent': -1 } }, ], ); spy.messages.clear(); hideKeyboard(); }); test('Multi-line mode also works', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterMultilineConfig]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); // Editing shouldn't have started yet. expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); final DomHTMLTextAreaElement textarea = textEditing!.strategy.domElement! as DomHTMLTextAreaElement; checkTextAreaEditingState(textarea, '', 0, 0); // Can set editing state and preserve new lines. const MethodCall setEditingState = MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': 'foo\nbar', 'selectionBase': 2, 'selectionExtent': 3, 'composingBase': null, 'composingExtent': null }); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); checkTextAreaEditingState(textarea, 'foo\nbar', 2, 3); textarea.value = 'something\nelse'; textarea.dispatchEvent(createDomEvent('Event', 'input')); textarea.setSelectionRange(2, 5); if (browserEngine == BrowserEngine.firefox) { textEditing!.strategy.domElement! .dispatchEvent(createDomEvent('Event', 'keyup')); } else { domDocument.dispatchEvent(createDomEvent('Event', 'selectionchange')); } // Two messages should've been sent. One for the 'input' event and one for // the 'selectionchange' event. expect(spy.messages, hasLength(2)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.updateEditingState'); expect( spy.messages[0].methodArguments, <dynamic>[ 123, // Client ID <String, dynamic>{ 'text': 'something\nelse', 'selectionBase': 14, 'selectionExtent': 14, 'composingBase': -1, 'composingExtent': -1 } ], ); expect(spy.messages[1].channel, 'flutter/textinput'); expect(spy.messages[1].methodName, 'TextInputClient.updateEditingState'); expect( spy.messages[1].methodArguments, <dynamic>[ 123, // Client ID <String, dynamic>{ 'text': 'something\nelse', 'selectionBase': 2, 'selectionExtent': 5, 'composingBase': -1, 'composingExtent': -1 } ], ); spy.messages.clear(); const MethodCall hide = MethodCall('TextInput.hide'); sendFrameworkMessage(codec.encodeMethodCall(hide)); // Text editing should've stopped. expect(domDocument.activeElement, domDocument.body); // Confirm that [HybridTextEditing] didn't send any more messages. expect(spy.messages, isEmpty); }); test('none mode works', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, createFlutterConfig('none')]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); expect(textEditing!.strategy.domElement!.tagName, 'INPUT'); expect(getEditingInputMode(), 'none'); }); test('none multiline mode works', () async { final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, createFlutterConfig('none', isMultiline: true)]); sendFrameworkMessage(codec.encodeMethodCall(setClient)); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList()); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); await waitForDesktopSafariFocus(); expect(textEditing!.strategy.domElement!.tagName, 'TEXTAREA'); expect(getEditingInputMode(), 'none'); }); test('sets correct input type in Android', () { debugOperatingSystemOverride = OperatingSystem.android; debugBrowserEngineOverride = BrowserEngine.blink; /// During initialization [HybridTextEditing] will pick the correct /// text editing strategy for [OperatingSystem.android]. textEditing = HybridTextEditing(); showKeyboard(inputType: 'text'); expect(getEditingInputMode(), null); showKeyboard(inputType: 'number'); expect(getEditingInputMode(), 'numeric'); showKeyboard(inputType: 'number'); expect(getEditingInputMode(), 'numeric'); showKeyboard(inputType: 'number', decimal: true); expect(getEditingInputMode(), 'decimal'); showKeyboard(inputType: 'phone'); expect(getEditingInputMode(), 'tel'); showKeyboard(inputType: 'emailAddress'); expect(getEditingInputMode(), 'email'); showKeyboard(inputType: 'url'); expect(getEditingInputMode(), 'url'); showKeyboard(inputType: 'none'); expect(getEditingInputMode(), 'none'); expect(textEditing!.strategy.domElement!.tagName, 'INPUT'); showKeyboard(inputType: 'none', isMultiline: true); expect(getEditingInputMode(), 'none'); expect(textEditing!.strategy.domElement!.tagName, 'TEXTAREA'); hideKeyboard(); }); test('sets correct input type for Firefox on Android', () { debugOperatingSystemOverride = OperatingSystem.android; debugBrowserEngineOverride = BrowserEngine.firefox; /// During initialization [HybridTextEditing] will pick the correct /// text editing strategy for [OperatingSystem.android]. textEditing = HybridTextEditing(); showKeyboard(inputType: 'text'); expect(getEditingInputMode(), null); showKeyboard(inputType: 'number'); expect(getEditingInputMode(), 'numeric'); showKeyboard(inputType: 'number'); expect(getEditingInputMode(), 'numeric'); showKeyboard(inputType: 'number', decimal: true); expect(getEditingInputMode(), 'decimal'); showKeyboard(inputType: 'phone'); expect(getEditingInputMode(), 'tel'); showKeyboard(inputType: 'emailAddress'); expect(getEditingInputMode(), 'email'); showKeyboard(inputType: 'url'); expect(getEditingInputMode(), 'url'); showKeyboard(inputType: 'none'); expect(getEditingInputMode(), 'none'); hideKeyboard(); }); test('prevent mouse events on Android', () { // Regression test for https://github.com/flutter/flutter/issues/124483. debugOperatingSystemOverride = OperatingSystem.android; debugBrowserEngineOverride = BrowserEngine.blink; /// During initialization [HybridTextEditing] will pick the correct /// text editing strategy for [OperatingSystem.android]. textEditing = HybridTextEditing(); final MethodCall setClient = MethodCall( 'TextInput.setClient', <dynamic>[123, flutterMultilineConfig], ); sendFrameworkMessage(codec.encodeMethodCall(setClient)); // Editing shouldn't have started yet. expect(defaultTextEditingRoot.ownerDocument?.activeElement, domDocument.body); const MethodCall show = MethodCall('TextInput.show'); sendFrameworkMessage(codec.encodeMethodCall(show)); // The "setSizeAndTransform" message has to be here before we call // checkInputEditingState, since on some platforms (e.g. Desktop Safari) // we don't put the input element into the DOM until we get its correct // dimensions from the framework. final List<double> transform = Matrix4.translationValues(10.0, 20.0, 30.0).storage.toList(); final MethodCall setSizeAndTransform = configureSetSizeAndTransformMethodCall(150, 50, transform); sendFrameworkMessage(codec.encodeMethodCall(setSizeAndTransform)); final DomHTMLTextAreaElement textarea = textEditing!.strategy.domElement! as DomHTMLTextAreaElement; checkTextAreaEditingState(textarea, '', 0, 0); // Can set editing state and preserve new lines. const MethodCall setEditingState = MethodCall( 'TextInput.setEditingState', <String, dynamic>{ 'text': '1\n2\n3\n4\n', 'selectionBase': 8, 'selectionExtent': 8, 'composingBase': null, 'composingExtent': null, }, ); sendFrameworkMessage(codec.encodeMethodCall(setEditingState)); checkTextAreaEditingState(textarea, '1\n2\n3\n4\n', 8, 8); // 'mousedown' event should be prevented. final DomEvent event = createDomEvent('Event', 'mousedown'); textarea.dispatchEvent(event); expect(event.defaultPrevented, isTrue); hideKeyboard(); }); test('sets correct input type in iOS', () { // Test on ios-safari only. if (browserEngine == BrowserEngine.webkit && operatingSystem == OperatingSystem.iOs) { /// During initialization [HybridTextEditing] will pick the correct /// text editing strategy for [OperatingSystem.iOs]. textEditing = HybridTextEditing(); showKeyboard(inputType: 'text'); expect(getEditingInputMode(), null); showKeyboard(inputType: 'number'); expect(getEditingInputMode(), 'numeric'); showKeyboard(inputType: 'number'); expect(getEditingInputMode(), 'numeric'); showKeyboard(inputType: 'number', decimal: true); expect(getEditingInputMode(), 'decimal'); showKeyboard(inputType: 'phone'); expect(getEditingInputMode(), 'tel'); showKeyboard(inputType: 'emailAddress'); expect(getEditingInputMode(), 'email'); showKeyboard(inputType: 'url'); expect(getEditingInputMode(), 'url'); showKeyboard(inputType: 'none'); expect(getEditingInputMode(), 'none'); expect(textEditing!.strategy.domElement!.tagName, 'INPUT'); showKeyboard(inputType: 'none', isMultiline: true); expect(getEditingInputMode(), 'none'); expect(textEditing!.strategy.domElement!.tagName, 'TEXTAREA'); hideKeyboard(); } }); test('sends the correct input action as a platform message', () { final int clientId = showKeyboard( inputType: 'text', inputAction: 'TextInputAction.next', ); // There should be no input action yet. expect(lastInputAction, isNull); dispatchKeyboardEvent( textEditing!.strategy.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.performAction'); expect( spy.messages[0].methodArguments, <dynamic>[clientId, 'TextInputAction.next'], ); }); test('sends input action in multi-line mode', () { showKeyboard( inputType: 'multiline', inputAction: 'TextInputAction.next', ); final DomKeyboardEvent event = dispatchKeyboardEvent( textEditing!.strategy.domElement!, 'keydown', keyCode: _kReturnKeyCode, ); // Input action is sent as a platform message. expect(spy.messages, hasLength(1)); expect(spy.messages[0].channel, 'flutter/textinput'); expect(spy.messages[0].methodName, 'TextInputClient.performAction'); expect( spy.messages[0].methodArguments, <dynamic>[clientId, 'TextInputAction.next'], ); // And default behavior of keyboard event shouldn't have been prevented. expect(event.defaultPrevented, isFalse); }); tearDown(() { clearForms(); }); }); group('EngineAutofillForm', () { test('validate multi element form', () { final List<dynamic> fields = createFieldValues( <String>['username', 'password', 'newPassword'], <String>['field1', 'field2', 'field3']); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('username', 'field1'), fields)!; // Number of elements if number of fields sent to the constructor minus // one (for the focused text element). expect(autofillForm.elements, hasLength(2)); expect(autofillForm.items, hasLength(2)); expect(autofillForm.formElement, isNotNull); expect(autofillForm.formIdentifier, 'field1*field2*field3'); final DomHTMLFormElement form = autofillForm.formElement; // Note that we also add a submit button. Therefore the form element has // 3 child nodes. expect(form.childNodes, hasLength(3)); final DomHTMLInputElement firstElement = form.childNodes.toList()[0] as DomHTMLInputElement; // Autofill value is applied to the element. expect(firstElement.name, BrowserAutofillHints.instance.flutterToEngine('password')); expect(firstElement.id, BrowserAutofillHints.instance.flutterToEngine('password')); expect(firstElement.type, 'password'); if (browserEngine == BrowserEngine.firefox) { expect(firstElement.name, BrowserAutofillHints.instance.flutterToEngine('password')); } else { expect(firstElement.autocomplete, BrowserAutofillHints.instance.flutterToEngine('password')); } // Editing state is applied to the element. expect(firstElement.value, 'Test'); expect(firstElement.selectionStart, 0); expect(firstElement.selectionEnd, 0); // Element is hidden. final DomCSSStyleDeclaration css = firstElement.style; expect(css.color, 'transparent'); expect(css.backgroundColor, 'transparent'); // For `blink` and `webkit` browser engines the overlay would be hidden. if (browserEngine == BrowserEngine.blink || browserEngine == BrowserEngine.webkit) { expect(firstElement.classList.contains('transparentTextEditing'), isTrue); } else { expect(firstElement.classList.contains('transparentTextEditing'), isFalse); } }); test('validate multi element form ids sorted for form id', () { final List<dynamic> fields = createFieldValues( <String>['username', 'password', 'newPassword'], <String>['zzyyxx', 'aabbcc', 'jjkkll']); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('username', 'field1'), fields)!; expect(autofillForm.formIdentifier, 'aabbcc*jjkkll*zzyyxx'); }); test('place and store form', () { expect(defaultTextEditingRoot.querySelectorAll('form'), isEmpty); final List<dynamic> fields = createFieldValues( <String>['username', 'password', 'newPassword'], <String>['field1', 'fields2', 'field3']); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('username', 'field1'), fields)!; final DomHTMLInputElement testInputElement = createDomHTMLInputElement(); autofillForm.placeForm(testInputElement); // The focused element is appended to the form, form also has the button // so in total it shoould have 4 elements. final DomHTMLFormElement form = autofillForm.formElement; expect(form.childNodes, hasLength(4)); final DomHTMLFormElement formOnDom = defaultTextEditingRoot.querySelector('form')! as DomHTMLFormElement; // Form is attached to the DOM. expect(form, equals(formOnDom)); autofillForm.storeForm(); expect(defaultTextEditingRoot.querySelectorAll('form'), isNotEmpty); expect(formsOnTheDom, hasLength(1)); }); test('Validate single element form', () { final List<dynamic> fields = createFieldValues( <String>['username'], <String>['field1'], ); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('username', 'field1'), fields)!; // The focused element is the only field. Form should be empty after // the initialization (focus element is appended later). expect(autofillForm.elements, isEmpty); expect(autofillForm.items, isEmpty); expect(autofillForm.formElement, isNotNull); final DomHTMLFormElement form = autofillForm.formElement; // Submit button is added to the form. expect(form.childNodes, isNotEmpty); final DomHTMLInputElement inputElement = form.childNodes.toList()[0] as DomHTMLInputElement; expect(inputElement.type, 'submit'); // The submit button should have class `submitBtn`. expect(inputElement.className, 'submitBtn'); }); test('Return null if no focused element', () { final List<dynamic> fields = createFieldValues( <String>['username'], <String>['field1'], ); final EngineAutofillForm? autofillForm = EngineAutofillForm.fromFrameworkMessage(null, fields); expect(autofillForm, isNull); }); test('placeForm() should place element in correct position', () { final List<dynamic> fields = createFieldValues(<String>[ 'email', 'username', 'password', ], <String>[ 'field1', 'field2', 'field3' ]); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('email', 'field1'), fields)!; expect(autofillForm.elements, hasLength(2)); List<DomHTMLInputElement> formChildNodes = autofillForm.formElement.childNodes.toList() as List<DomHTMLInputElement>; // Only username, password, submit nodes are created expect(formChildNodes, hasLength(3)); expect(formChildNodes[0].name, 'username'); expect(formChildNodes[1].name, 'current-password'); expect(formChildNodes[2].type, 'submit'); // insertion point for email should be before username expect(autofillForm.insertionReferenceNode, formChildNodes[0]); final DomHTMLInputElement testInputElement = createDomHTMLInputElement(); testInputElement.name = 'email'; autofillForm.placeForm(testInputElement); formChildNodes = autofillForm.formElement.childNodes.toList() as List<DomHTMLInputElement>; // email node should be placed before username expect(formChildNodes, hasLength(4)); expect(formChildNodes[0].name, 'email'); expect(formChildNodes[1].name, 'username'); expect(formChildNodes[2].name, 'current-password'); expect(formChildNodes[3].type, 'submit'); }); test( 'hidden autofill elements should have a width and height of 0 on non-Safari browsers', () { final List<dynamic> fields = createFieldValues(<String>[ 'email', 'username', 'password', ], <String>[ 'field1', 'field2', 'field3' ]); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('email', 'field1'), fields)!; final List<DomHTMLInputElement> formChildNodes = autofillForm.formElement.childNodes.toList() as List<DomHTMLInputElement>; final DomHTMLInputElement username = formChildNodes[0]; final DomHTMLInputElement password = formChildNodes[1]; expect(username.name, 'username'); expect(password.name, 'current-password'); expect(username.style.width, '0px'); expect(username.style.height, '0px'); expect(username.style.pointerEvents, isNot('none')); expect(password.style.width, '0px'); expect(password.style.height, '0px'); expect(password.style.pointerEvents, isNot('none')); expect(autofillForm.formElement.style.pointerEvents, isNot('none')); }, skip: isSafari); test( 'hidden autofill elements should not have a width and height of 0 on Safari', () { final List<dynamic> fields = createFieldValues(<String>[ 'email', 'username', 'password', ], <String>[ 'field1', 'field2', 'field3' ]); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('email', 'field1'), fields)!; final List<DomHTMLInputElement> formChildNodes = autofillForm.formElement.childNodes.toList() as List<DomHTMLInputElement>; final DomHTMLInputElement username = formChildNodes[0]; final DomHTMLInputElement password = formChildNodes[1]; expect(username.name, 'username'); expect(password.name, 'current-password'); expect(username.style.width, isNot('0px')); expect(username.style.height, isNot('0px')); expect(username.style.pointerEvents, 'none'); expect(password.style.width, isNot('0px')); expect(password.style.height, isNot('0px')); expect(password.style.pointerEvents, 'none'); expect(autofillForm.formElement.style.pointerEvents, 'none'); }, skip: !isSafari); test( 'the focused element within a form should explicitly set pointer events on Safari', () { final List<dynamic> fields = createFieldValues(<String>[ 'email', 'username', 'password', ], <String>[ 'field1', 'field2', 'field3' ]); final EngineAutofillForm autofillForm = EngineAutofillForm.fromFrameworkMessage( createAutofillInfo('email', 'field1'), fields)!; final DomHTMLInputElement testInputElement = createDomHTMLInputElement(); testInputElement.name = 'email'; autofillForm.placeForm(testInputElement); final List<DomHTMLInputElement> formChildNodes = autofillForm.formElement.childNodes.toList() as List<DomHTMLInputElement>; final DomHTMLInputElement email = formChildNodes[0]; final DomHTMLInputElement username = formChildNodes[1]; final DomHTMLInputElement password = formChildNodes[2]; expect(email.name, 'email'); expect(username.name, 'username'); expect(password.name, 'current-password'); // pointer events are none on the form and all non-focused elements expect(autofillForm.formElement.style.pointerEvents, 'none'); expect(username.style.pointerEvents, 'none'); expect(password.style.pointerEvents, 'none'); // pointer events are set to all on the activeDomElement expect(email.style.pointerEvents, 'all'); }, skip: !isSafari); tearDown(() { clearForms(); }); }); group('AutofillInfo', () { const String testHint = 'streetAddressLine2'; const String testId = 'EditableText-659836579'; const String testPasswordHint = 'password'; test('autofill has correct value', () { final AutofillInfo autofillInfo = AutofillInfo.fromFrameworkMessage( createAutofillInfo(testHint, testId)); // Hint sent from the framework is converted to the hint compatible with // browsers. expect(autofillInfo.autofillHint, BrowserAutofillHints.instance.flutterToEngine(testHint)); expect(autofillInfo.uniqueIdentifier, testId); }); test('input with autofill hint', () { final AutofillInfo autofillInfo = AutofillInfo.fromFrameworkMessage( createAutofillInfo(testHint, testId)); final DomHTMLInputElement testInputElement = createDomHTMLInputElement(); autofillInfo.applyToDomElement(testInputElement); // Hint sent from the framework is converted to the hint compatible with // browsers. expect(testInputElement.name, BrowserAutofillHints.instance.flutterToEngine(testHint)); expect(testInputElement.id, BrowserAutofillHints.instance.flutterToEngine(testHint)); expect(testInputElement.type, 'text'); if (browserEngine == BrowserEngine.firefox) { expect(testInputElement.name, BrowserAutofillHints.instance.flutterToEngine(testHint)); } else { expect(testInputElement.autocomplete, BrowserAutofillHints.instance.flutterToEngine(testHint)); } }); test('textarea with autofill hint', () { final AutofillInfo autofillInfo = AutofillInfo.fromFrameworkMessage( createAutofillInfo(testHint, testId)); final DomHTMLTextAreaElement testInputElement = createDomHTMLTextAreaElement(); autofillInfo.applyToDomElement(testInputElement); // Hint sent from the framework is converted to the hint compatible with // browsers. expect(testInputElement.name, BrowserAutofillHints.instance.flutterToEngine(testHint)); expect(testInputElement.id, BrowserAutofillHints.instance.flutterToEngine(testHint)); expect(testInputElement.getAttribute('autocomplete'), BrowserAutofillHints.instance.flutterToEngine(testHint)); }); test('password autofill hint', () { final AutofillInfo autofillInfo = AutofillInfo.fromFrameworkMessage( createAutofillInfo(testPasswordHint, testId)); final DomHTMLInputElement testInputElement = createDomHTMLInputElement(); autofillInfo.applyToDomElement(testInputElement); // Hint sent from the framework is converted to the hint compatible with // browsers. expect(testInputElement.name, BrowserAutofillHints.instance.flutterToEngine(testPasswordHint)); expect(testInputElement.id, BrowserAutofillHints.instance.flutterToEngine(testPasswordHint)); expect(testInputElement.type, 'password'); expect(testInputElement.getAttribute('autocomplete'), BrowserAutofillHints.instance.flutterToEngine(testPasswordHint)); }); test('autofill with no hints', () { final AutofillInfo autofillInfo = AutofillInfo.fromFrameworkMessage( createAutofillInfo(null, testId)); final DomHTMLInputElement testInputElement = createDomHTMLInputElement(); autofillInfo.applyToDomElement(testInputElement); expect(testInputElement.autocomplete,'on'); expect(testInputElement.placeholder, isEmpty); }); test('TextArea autofill with no hints', () { final AutofillInfo autofillInfo = AutofillInfo.fromFrameworkMessage( createAutofillInfo(null, testId)); final DomHTMLTextAreaElement testInputElement = createDomHTMLTextAreaElement(); autofillInfo.applyToDomElement(testInputElement); expect(testInputElement.getAttribute('autocomplete'),'on'); expect(testInputElement.placeholder, isEmpty); }); test('autofill with only placeholder', () { final AutofillInfo autofillInfo = AutofillInfo.fromFrameworkMessage( createAutofillInfo(null, testId, placeholder: 'enter your password')); final DomHTMLTextAreaElement testInputElement = createDomHTMLTextAreaElement(); autofillInfo.applyToDomElement(testInputElement); expect(testInputElement.getAttribute('autocomplete'),'on'); expect(testInputElement.placeholder, 'enter your password'); }); // Regression test for https://github.com/flutter/flutter/issues/135542 test('autofill with middleName hint', () { expect(BrowserAutofillHints.instance.flutterToEngine('middleName'), 'additional-name'); }); }); group('EditingState', () { EditingState editingState; setUp(() { editingStrategy = GloballyPositionedTextEditingStrategy(HybridTextEditing()); editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); }); test('Fix flipped base and extent offsets', () { expect( EditingState(baseOffset: 10, extentOffset: 4), EditingState(baseOffset: 4, extentOffset: 10), ); expect( EditingState.fromFrameworkMessage(<String, dynamic>{ 'selectionBase': 10, 'selectionExtent': 4, }), EditingState.fromFrameworkMessage(<String, dynamic>{ 'selectionBase': 4, 'selectionExtent': 10, }), ); }); test('Sets default composing offsets if none given', () { final EditingState editingState = EditingState(text: 'Test', baseOffset: 2, extentOffset: 4); final EditingState editingStateFromFrameworkMsg = EditingState.fromFrameworkMessage(<String, dynamic>{ 'selectionBase': 10, 'selectionExtent': 4, }); expect(editingState.composingBaseOffset, -1); expect(editingState.composingExtentOffset, -1); expect(editingStateFromFrameworkMsg.composingBaseOffset, -1); expect(editingStateFromFrameworkMsg.composingExtentOffset, -1); }); test('Correctly identifies min and max offsets', () { final EditingState flippedEditingState = EditingState(baseOffset: 10, extentOffset: 4); final EditingState normalEditingState = EditingState(baseOffset: 2, extentOffset: 6); expect(flippedEditingState.minOffset, 4); expect(flippedEditingState.maxOffset, 10); expect(normalEditingState.minOffset, 2); expect(normalEditingState.maxOffset, 6); }); test('Configure input element from the editing state', () { final DomHTMLInputElement input = defaultTextEditingRoot.querySelector('input')! as DomHTMLInputElement; editingState = EditingState(text: 'Test', baseOffset: 1, extentOffset: 2); editingState.applyToDomElement(input); expect(input.value, 'Test'); expect(input.selectionStart, 1); expect(input.selectionEnd, 2); }); test('Configure text area element from the editing state', () { cleanTextEditingStrategy(); editingStrategy!.enable( multilineConfig, onChange: trackEditingState, onAction: trackInputAction, ); final DomHTMLTextAreaElement textArea = defaultTextEditingRoot.querySelector('textarea')! as DomHTMLTextAreaElement; editingState = EditingState(text: 'Test', baseOffset: 1, extentOffset: 2); editingState.applyToDomElement(textArea); expect(textArea.value, 'Test'); expect(textArea.selectionStart, 1); expect(textArea.selectionEnd, 2); }); test('Configure input element editing state for a flipped base and extent', () { final DomHTMLInputElement input = defaultTextEditingRoot.querySelector('input')! as DomHTMLInputElement; editingState = EditingState(text: 'Hello World', baseOffset: 10, extentOffset: 2); editingState.applyToDomElement(input); expect(input.value, 'Hello World'); expect(input.selectionStart, 2); expect(input.selectionEnd, 10); }); test('Get Editing State from input element', () { final DomHTMLInputElement input = defaultTextEditingRoot.querySelector('input')! as DomHTMLInputElement; input.value = 'Test'; input.setSelectionRange(1, 2); editingState = EditingState.fromDomElement(input); expect(editingState.text, 'Test'); expect(editingState.baseOffset, 1); expect(editingState.extentOffset, 2); input.setSelectionRange(1, 2, 'backward'); editingState = EditingState.fromDomElement(input); expect(editingState.baseOffset, 2); expect(editingState.extentOffset, 1); }); test('Get Editing State from text area element', () { cleanTextEditingStrategy(); editingStrategy!.enable( multilineConfig, onChange: trackEditingState, onAction: trackInputAction, ); final DomHTMLTextAreaElement input = defaultTextEditingRoot.querySelector('textarea')! as DomHTMLTextAreaElement; input.value = 'Test'; input.setSelectionRange(1, 2); editingState = EditingState.fromDomElement(input); expect(editingState.text, 'Test'); expect(editingState.baseOffset, 1); expect(editingState.extentOffset, 2); input.setSelectionRange(1, 2, 'backward'); editingState = EditingState.fromDomElement(input); expect(editingState.baseOffset, 2); expect(editingState.extentOffset, 1); }); group('comparing editing states', () { test('From dom element', () { final DomHTMLInputElement input = defaultTextEditingRoot.querySelector('input')! as DomHTMLInputElement; input.value = 'Test'; input.selectionStart = 1; input.selectionEnd = 2; final EditingState editingState1 = EditingState.fromDomElement(input); final EditingState editingState2 = EditingState.fromDomElement(input); input.setSelectionRange(1, 3); final EditingState editingState3 = EditingState.fromDomElement(input); expect(editingState1 == editingState2, isTrue); expect(editingState1 != editingState3, isTrue); }); test('Takes flipped base and extent offsets into account', () { final EditingState flippedEditingState = EditingState(baseOffset: 10, extentOffset: 4); final EditingState normalEditingState = EditingState(baseOffset: 4, extentOffset: 10); expect(normalEditingState, flippedEditingState); expect(normalEditingState == flippedEditingState, isTrue); }); test('takes composition range into account', () { final EditingState editingState1 = EditingState(composingBaseOffset: 1, composingExtentOffset: 2); final EditingState editingState2 = EditingState(composingBaseOffset: 1, composingExtentOffset: 2); final EditingState editingState3 = EditingState(composingBaseOffset: 4, composingExtentOffset: 8); expect(editingState1, editingState2); expect(editingState1, isNot(editingState3)); }); }); }); group('TextEditingDeltaState', () { // The selection baseOffset and extentOffset are not inferred by // TextEditingDeltaState.inferDeltaState so we do not verify them here. test('Verify correct delta is inferred - insertion', () { final EditingState newEditState = EditingState(text: 'world', baseOffset: 5, extentOffset: 5); final EditingState lastEditState = EditingState(text: 'worl', baseOffset: 4, extentOffset: 4); final TextEditingDeltaState deltaState = TextEditingDeltaState(oldText: 'worl', deltaText: 'd', deltaStart: 4, deltaEnd: 4, baseOffset: -1, extentOffset: -1, composingOffset: -1, composingExtent: -1); final TextEditingDeltaState textEditingDeltaState = TextEditingDeltaState.inferDeltaState(newEditState, lastEditState, deltaState); expect(textEditingDeltaState.oldText, 'worl'); expect(textEditingDeltaState.deltaText, 'd'); expect(textEditingDeltaState.deltaStart, 4); expect(textEditingDeltaState.deltaEnd, 4); expect(textEditingDeltaState.baseOffset, 5); expect(textEditingDeltaState.extentOffset, 5); expect(textEditingDeltaState.composingOffset, -1); expect(textEditingDeltaState.composingExtent, -1); }); test('Verify correct delta is inferred - Backward deletion - Empty selection', () { final EditingState newEditState = EditingState(text: 'worl', baseOffset: 4, extentOffset: 4); final EditingState lastEditState = EditingState(text: 'world', baseOffset: 5, extentOffset: 5); // `deltaState.deltaEnd` is initialized accordingly to what is done in `DefaultTextEditingStrategy.handleBeforeInput` final TextEditingDeltaState deltaState = TextEditingDeltaState( oldText: 'world', deltaEnd: 5, baseOffset: -1, extentOffset: -1, composingOffset: -1, composingExtent: -1, ); final TextEditingDeltaState textEditingDeltaState = TextEditingDeltaState.inferDeltaState(newEditState, lastEditState, deltaState); expect(textEditingDeltaState.oldText, 'world'); expect(textEditingDeltaState.deltaText, ''); expect(textEditingDeltaState.deltaStart, 4); expect(textEditingDeltaState.deltaEnd, 5); expect(textEditingDeltaState.baseOffset, 4); expect(textEditingDeltaState.extentOffset, 4); expect(textEditingDeltaState.composingOffset, -1); expect(textEditingDeltaState.composingExtent, -1); }); test('Verify correct delta is inferred - Forward deletion - Empty selection', () { final EditingState newEditState = EditingState(text: 'worl', baseOffset: 4, extentOffset: 4); final EditingState lastEditState = EditingState(text: 'world', baseOffset: 4, extentOffset: 4); // `deltaState.deltaEnd` is initialized accordingly to what is done in `DefaultTextEditingStrategy.handleBeforeInput` final TextEditingDeltaState deltaState = TextEditingDeltaState( oldText: 'world', deltaEnd: 4, baseOffset: -1, extentOffset: -1, composingOffset: -1, composingExtent: -1, ); final TextEditingDeltaState textEditingDeltaState = TextEditingDeltaState.inferDeltaState(newEditState, lastEditState, deltaState); expect(textEditingDeltaState.oldText, 'world'); expect(textEditingDeltaState.deltaText, ''); expect(textEditingDeltaState.deltaStart, 4); expect(textEditingDeltaState.deltaEnd, 5); expect(textEditingDeltaState.baseOffset, 4); expect(textEditingDeltaState.extentOffset, 4); expect(textEditingDeltaState.composingOffset, -1); expect(textEditingDeltaState.composingExtent, -1); }); test('Verify correct delta is inferred - Deletion - Non-empty selection', () { final EditingState newEditState = EditingState(text: 'w', baseOffset: 1, extentOffset: 1); final EditingState lastEditState = EditingState(text: 'world', baseOffset: 1, extentOffset: 5); // `deltaState.deltaEnd` is initialized accordingly to what is done in `DefaultTextEditingStrategy.handleBeforeInput` final TextEditingDeltaState deltaState = TextEditingDeltaState( oldText: 'world', deltaEnd: 5, baseOffset: -1, extentOffset: -1, composingOffset: -1, composingExtent: -1, ); final TextEditingDeltaState textEditingDeltaState = TextEditingDeltaState.inferDeltaState(newEditState, lastEditState, deltaState); expect(textEditingDeltaState.oldText, 'world'); expect(textEditingDeltaState.deltaText, ''); expect(textEditingDeltaState.deltaStart, 1); expect(textEditingDeltaState.deltaEnd, 5); expect(textEditingDeltaState.baseOffset, 1); expect(textEditingDeltaState.extentOffset, 1); expect(textEditingDeltaState.composingOffset, -1); expect(textEditingDeltaState.composingExtent, -1); }); test('Verify correct delta is inferred - composing region replacement', () { final EditingState newEditState = EditingState(text: '你好吗', baseOffset: 3, extentOffset: 3); final EditingState lastEditState = EditingState(text: 'ni hao ma', baseOffset: 9, extentOffset: 9); final TextEditingDeltaState deltaState = TextEditingDeltaState(oldText: 'ni hao ma', deltaText: '你好吗', deltaStart: 9, deltaEnd: 9, baseOffset: -1, extentOffset: -1, composingOffset: 0, composingExtent: 9); final TextEditingDeltaState textEditingDeltaState = TextEditingDeltaState.inferDeltaState(newEditState, lastEditState, deltaState); expect(textEditingDeltaState.oldText, 'ni hao ma'); expect(textEditingDeltaState.deltaText, '你好吗'); expect(textEditingDeltaState.deltaStart, 0); expect(textEditingDeltaState.deltaEnd, 9); expect(textEditingDeltaState.baseOffset, 3); expect(textEditingDeltaState.extentOffset, 3); expect(textEditingDeltaState.composingOffset, 0); expect(textEditingDeltaState.composingExtent, 9); }); test('Verify correct delta is inferred for double space to insert a period', () { final EditingState newEditState = EditingState(text: 'hello. ', baseOffset: 7, extentOffset: 7); final EditingState lastEditState = EditingState(text: 'hello ', baseOffset: 6, extentOffset: 6); final TextEditingDeltaState deltaState = TextEditingDeltaState(oldText: 'hello ', deltaText: '. ', deltaStart: 6, deltaEnd: 6, baseOffset: -1, extentOffset: -1, composingOffset: -1, composingExtent: -1); final TextEditingDeltaState textEditingDeltaState = TextEditingDeltaState.inferDeltaState(newEditState, lastEditState, deltaState); expect(textEditingDeltaState.oldText, 'hello '); expect(textEditingDeltaState.deltaText, '. '); expect(textEditingDeltaState.deltaStart, 5); expect(textEditingDeltaState.deltaEnd, 6); expect(textEditingDeltaState.baseOffset, 7); expect(textEditingDeltaState.extentOffset, 7); expect(textEditingDeltaState.composingOffset, -1); expect(textEditingDeltaState.composingExtent, -1); }); test('Verify correct delta is inferred for accent menu', () { final EditingState newEditState = EditingState(text: 'à', baseOffset: 1, extentOffset: 1); final EditingState lastEditState = EditingState(text: 'a', baseOffset: 1, extentOffset: 1); final TextEditingDeltaState deltaState = TextEditingDeltaState(oldText: 'a', deltaText: 'à', deltaStart: 1, deltaEnd: 1, baseOffset: -1, extentOffset: -1, composingOffset: -1, composingExtent: -1); final TextEditingDeltaState textEditingDeltaState = TextEditingDeltaState.inferDeltaState(newEditState, lastEditState, deltaState); expect(textEditingDeltaState.oldText, 'a'); expect(textEditingDeltaState.deltaText, 'à'); expect(textEditingDeltaState.deltaStart, 0); expect(textEditingDeltaState.deltaEnd, 1); expect(textEditingDeltaState.baseOffset, 1); expect(textEditingDeltaState.extentOffset, 1); expect(textEditingDeltaState.composingOffset, -1); expect(textEditingDeltaState.composingExtent, -1); }); test('Delta state is cleared after setting editing state', (){ editingStrategy!.enable( multilineConfig, onChange: trackEditingState, onAction: trackInputAction, ); final DomHTMLInputElement input = editingStrategy!.domElement! as DomHTMLInputElement; input.value = 'foo bar'; input.dispatchEvent(createDomEvent('Event', 'input')); expect( lastEditingState, EditingState(text: 'foo bar', baseOffset: 7, extentOffset: 7), ); expect(editingStrategy!.editingDeltaState.oldText, 'foo bar'); editingStrategy!.setEditingState(EditingState(text: 'foo bar baz', baseOffset: 11, extentOffset: 11)); input.dispatchEvent(createDomEvent('Event', 'input')); expect(editingStrategy?.editingDeltaState.oldText, 'foo bar baz'); }); }); group('text editing styles', () { test('invisible element', () { editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); final DomHTMLElement input = editingStrategy!.activeDomElement; expect(input.style.color, contains('transparent')); if (isSafari) { // macOS 13 returns different values than macOS 12. expect(input.style.background, anyOf(contains('transparent'), contains('none'))); expect(input.style.outline, anyOf(contains('none'), contains('currentcolor'))); expect(input.style.border, anyOf(contains('none'), contains('medium'))); } else { expect(input.style.background, contains('transparent')); expect(input.style.outline, contains('none')); expect(input.style.border, contains('none')); } expect(input.style.backgroundColor, contains('transparent')); expect(input.style.caretColor, contains('transparent')); expect(input.style.textShadow, contains('none')); }); test('prevents effect of (forced-colors: active)', () { editingStrategy!.enable( singlelineConfig, onChange: trackEditingState, onAction: trackInputAction, ); final DomHTMLElement input = editingStrategy!.activeDomElement; expect(input.style.getPropertyValue('forced-color-adjust'), 'none'); // TODO(hterkelsen): Firefox does not support forced-color-adjust even // though it supports forced-colors. Safari doesn't support forced-colors // so this isn't a problem there. }, skip: isFirefox || isSafari); }); } DomKeyboardEvent dispatchKeyboardEvent( DomEventTarget target, String type, { required int keyCode, }) { final Object jsKeyboardEvent = js_util.getProperty<Object>(domWindow, 'KeyboardEvent'); final List<dynamic> eventArgs = <dynamic>[ type, js_util.jsify(<String, dynamic>{ 'keyCode': keyCode, 'cancelable': true, }), ]; final DomKeyboardEvent event = js_util.callConstructor<DomKeyboardEvent>( jsKeyboardEvent, eventArgs, ); target.dispatchEvent(event); return event; } MethodCall configureSetStyleMethodCall(int fontSize, String fontFamily, int textAlignIndex, int? fontWeightIndex, int textDirectionIndex) { return MethodCall('TextInput.setStyle', <String, dynamic>{ 'fontSize': fontSize, 'fontFamily': fontFamily, 'textAlignIndex': textAlignIndex, 'fontWeightIndex': fontWeightIndex, 'textDirectionIndex': textDirectionIndex, }); } MethodCall configureSetSizeAndTransformMethodCall( int width, int height, List<double> transform) { return MethodCall('TextInput.setEditableSizeAndTransform', <String, dynamic>{ 'width': width, 'height': height, 'transform': transform }); } /// Will disable editing element which will also clean the backup DOM /// element from the page. void cleanTextEditingStrategy() { if (editingStrategy != null && editingStrategy!.isEnabled) { // Clean up all the DOM elements and event listeners. editingStrategy!.disable(); } } void cleanTestFlags() { debugBrowserEngineOverride = null; debugOperatingSystemOverride = null; } void checkInputEditingState( DomElement? element, String text, int start, int end) { expect(element, isNotNull); expect(domInstanceOfString(element, 'HTMLInputElement'), true); final DomHTMLInputElement input = element! as DomHTMLInputElement; expect(defaultTextEditingRoot.ownerDocument?.activeElement, input); expect(input.value, text); expect(input.selectionStart, start); expect(input.selectionEnd, end); } /// In case of an exception backup DOM element(s) can still stay on the DOM. void clearBackUpDomElementIfExists() { final List<DomElement> domElementsToRemove = <DomElement>[]; if (defaultTextEditingRoot.querySelectorAll('input').isNotEmpty) { domElementsToRemove.addAll(defaultTextEditingRoot.querySelectorAll('input').cast<DomElement>()); } if (defaultTextEditingRoot.querySelectorAll('textarea').isNotEmpty) { domElementsToRemove.addAll(defaultTextEditingRoot.querySelectorAll('textarea').cast<DomElement>()); } domElementsToRemove.forEach(_removeNode); } void _removeNode(DomElement n)=> n.remove(); void checkTextAreaEditingState( DomHTMLTextAreaElement textarea, String text, int start, int end, ) { expect(defaultTextEditingRoot.ownerDocument?.activeElement, textarea); expect(textarea.value, text); expect(textarea.selectionStart, start); expect(textarea.selectionEnd, end); } /// Creates an [InputConfiguration] for using in the tests. /// /// For simplicity this method is using `autofillHint` as the `uniqueId` for /// simplicity. Map<String, dynamic> createFlutterConfig( String inputType, { bool readOnly = false, bool obscureText = false, bool autocorrect = true, String textCapitalization = 'TextCapitalization.none', String? inputAction, bool autofillEnabled = true, String? autofillHint, String? placeholderText, List<String>? autofillHintsForFields, bool decimal = false, bool enableDeltaModel = false, bool isMultiline = false, }) { return <String, dynamic>{ 'inputType': <String, dynamic>{ 'name': 'TextInputType.$inputType', if (decimal) 'decimal': true, if (isMultiline) 'isMultiline': true, }, 'readOnly': readOnly, 'obscureText': obscureText, 'autocorrect': autocorrect, 'inputAction': inputAction ?? 'TextInputAction.done', 'textCapitalization': textCapitalization, if (autofillEnabled) 'autofill': createAutofillInfo(autofillHint, autofillHint ?? 'bogusId', placeholder: placeholderText), if (autofillEnabled && autofillHintsForFields != null) 'fields': createFieldValues(autofillHintsForFields, autofillHintsForFields), 'enableDeltaModel': enableDeltaModel, }; } Map<String, dynamic> createAutofillInfo(String? hint, String uniqueId, { String? placeholder }) => <String, dynamic>{ 'uniqueIdentifier': uniqueId, if (hint != null) 'hints': <String>[hint], if (placeholder != null) 'hintText': placeholder, 'editingValue': <String, dynamic>{ 'text': 'Test', 'selectionBase': 0, 'selectionExtent': 0, 'selectionAffinity': 'TextAffinity.downstream', 'selectionIsDirectional': false, 'composingBase': -1, 'composingExtent': -1, }, }; List<dynamic> createFieldValues(List<String> hints, List<String> uniqueIds) { final List<dynamic> testFields = <dynamic>[]; expect(hints.length, equals(uniqueIds.length)); for (int i = 0; i < hints.length; i++) { testFields.add(createOneFieldValue(hints[i], uniqueIds[i])); } return testFields; } Map<String, dynamic> createOneFieldValue(String hint, String uniqueId) => <String, dynamic>{ 'inputType': <String, dynamic>{ 'name': 'TextInputType.text', 'signed': null, 'decimal': null }, 'textCapitalization': 'TextCapitalization.none', 'autofill': createAutofillInfo(hint, uniqueId) }; /// In order to not leak test state, clean up the forms from dom if any remains. void clearForms() { while (defaultTextEditingRoot.querySelectorAll('form').isNotEmpty) { defaultTextEditingRoot.querySelectorAll('form').last.remove(); } formsOnTheDom.clear(); } /// On Desktop Safari, the editing element is focused after a zero-duration timer /// to prevent autofill popup flickering. We must wait a tick for this placement /// before referencing these elements. Future<void> waitForDesktopSafariFocus() async { if (textEditing.strategy is SafariDesktopTextEditingStrategy) { await Future<void>.delayed(Duration.zero); } } class GlobalTextEditingStrategySpy extends GloballyPositionedTextEditingStrategy { GlobalTextEditingStrategySpy(super.owner); int placeElementCount = 0; @override void placeElement() { placeElementCount++; super.placeElement(); } }
engine/lib/web_ui/test/engine/text_editing_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/text_editing_test.dart", "repo_id": "engine", "token_count": 50697 }
330
// 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 '../../common/matchers.dart'; void main() { internalBootstrapBrowserTest(() => doTests); } void doTests() { group('StyleManager', () { test('attachGlobalStyles hides the outline when focused', () { final DomElement flutterViewElement = createDomElement(DomManager.flutterViewTagName); domDocument.body!.append(flutterViewElement); StyleManager.attachGlobalStyles( node: flutterViewElement, styleId: 'testing', styleNonce: 'testing', cssSelectorPrefix: DomManager.flutterViewTagName, ); final String expected = browserEngine == BrowserEngine.firefox ? 'rgb(0, 0, 0) 0px' : 'rgb(0, 0, 0) none 0px'; final String got = domWindow.getComputedStyle(flutterViewElement, 'focus').outline; expect(got, expected); }); test('styleSceneHost', () { expect( () => StyleManager.styleSceneHost(createDomHTMLDivElement()), throwsAssertionError, ); final DomElement sceneHost = createDomElement('flt-scene-host'); StyleManager.styleSceneHost(sceneHost); expect(sceneHost.style.pointerEvents, 'none'); expect(sceneHost.style.opacity, isEmpty); final DomElement sceneHost2 = createDomElement('flt-scene-host'); StyleManager.styleSceneHost(sceneHost2, debugShowSemanticsNodes: true); expect(sceneHost2.style.pointerEvents, 'none'); expect(sceneHost2.style.opacity, isNotEmpty); }); test('styleSemanticsHost', () { expect( () => StyleManager.styleSemanticsHost(createDomHTMLDivElement(), 1.0), throwsAssertionError, reason: 'Only accepts a <flt-semantics-host> element.' ); final DomElement semanticsHost = createDomElement('flt-semantics-host'); StyleManager.styleSemanticsHost(semanticsHost, 4.0); expect(semanticsHost.style.transform, 'scale(0.25)'); expect(semanticsHost.style.position, 'absolute'); expect(semanticsHost.style.transformOrigin, anyOf('0px 0px 0px', '0px 0px')); }); test('scaleSemanticsHost', () { expect( () => StyleManager.scaleSemanticsHost(createDomHTMLDivElement(), 1.0), throwsAssertionError, reason: 'Only accepts a <flt-semantics-host> element.' ); final DomElement semanticsHost = createDomElement('flt-semantics-host'); StyleManager.scaleSemanticsHost(semanticsHost, 5.0); expect(semanticsHost.style.transform, 'scale(0.2)'); // Didn't set other styles. expect(semanticsHost.style.position, isEmpty); expect(semanticsHost.style.transformOrigin, isEmpty); }); }); }
engine/lib/web_ui/test/engine/view_embedder/style_manager_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/view_embedder/style_manager_test.dart", "repo_id": "engine", "token_count": 1086 }
331
// 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:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:web_engine_tester/golden_tester.dart'; import '../../common/matchers.dart'; import '../../common/test_initialization.dart'; const ui.Rect region = ui.Rect.fromLTWH(0, 0, 500, 100); void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); setUp(() async { // To debug test failures uncomment the following to visualize clipping // layers: // debugShowClipLayers = true; SurfaceSceneBuilder.debugForgetFrameScene(); for (final DomNode scene in domDocument.querySelectorAll('flt-scene')) { scene.remove(); } }); test('pushClipRect', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushClipRect( const ui.Rect.fromLTRB(10, 10, 60, 60), ); _drawTestPicture(builder); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_shifted_clip_rect.png', region: region); }); test('pushClipRect with offset and transform', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushOffset(0, 60); builder.pushTransform( Matrix4.diagonal3Values(1, -1, 1).toFloat64(), ); builder.pushClipRect( const ui.Rect.fromLTRB(10, 10, 60, 60), ); _drawTestPicture(builder); builder.pop(); builder.pop(); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_clip_rect_with_offset_and_transform.png', region: region); }); test('pushClipRect with offset and transform ClipOp none should not clip', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushOffset(0, 80); builder.pushTransform( Matrix4.diagonal3Values(1, -1, 1).toFloat64(), ); builder.pushClipRect(const ui.Rect.fromLTRB(10, 10, 60, 60), clipBehavior: ui.Clip.none); _drawTestPicture(builder); builder.pop(); builder.pop(); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_clip_rect_clipop_none.png', region: region); }); test('pushClipRRect with offset and transform ClipOp none should not clip', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushOffset(0, 80); builder.pushTransform( Matrix4.diagonal3Values(1, -1, 1).toFloat64(), ); builder.pushClipRRect( ui.RRect.fromRectAndRadius( const ui.Rect.fromLTRB(10, 10, 60, 60), const ui.Radius.circular(1), ), clipBehavior: ui.Clip.none); _drawTestPicture(builder); builder.pop(); builder.pop(); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_clip_rrect_clipop_none.png', region: region); }); test('pushClipRRect', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushClipRRect( ui.RRect.fromLTRBR(10, 10, 60, 60, const ui.Radius.circular(5)), ); _drawTestPicture(builder); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_shifted_clip_rrect.png', region: region); }); test('pushImageFilter blur', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushImageFilter( ui.ImageFilter.blur(sigmaX: 1, sigmaY: 3), ); _drawTestPicture(builder); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_image_filter.png', region: region); }); test('pushImageFilter matrix', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushImageFilter( ui.ImageFilter.matrix( ( Matrix4.identity() ..translate(40, 10) ..rotateZ(math.pi / 6) ..scale(0.75, 0.75) ).toFloat64()), ); _drawTestPicture(builder); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_image_filter_matrix.png', region: region); }); test('pushImageFilter using mode ColorFilter', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); // Applying the colorFilter should turn all the circles red. builder.pushImageFilter( const ui.ColorFilter.mode( ui.Color(0xFFFF0000), ui.BlendMode.srcIn, )); _drawTestPicture(builder); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_image_filter_using_mode_color_filter.png', region: region); }); test('pushImageFilter using matrix ColorFilter', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); // Apply a "greyscale" color filter. final List<double> colorMatrix = <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, // ]; builder.pushImageFilter(ui.ColorFilter.matrix(colorMatrix)); _drawTestPicture(builder); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_image_filter_using_matrix_color_filter.png', region: region); }); group('Cull rect computation', () { _testCullRectComputation(); }); } void _testCullRectComputation() { // Draw a picture larger that screen. Verify that cull rect is equal to screen // bounds. test('fills screen bounds', () async { final ui.SceneBuilder builder = ui.SceneBuilder(); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle( ui.Offset.zero, 10000, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.build(); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(0, 0, 500, 100)); }, skip: ''' TODO(https://github.com/flutter/flutter/issues/40395) Needs ability to set iframe to 500,100 size. Current screen seems to be 500,500'''); // Draw a picture that overflows the screen. Verify that cull rect is the // intersection of screen bounds and paint bounds. test('intersects with screen bounds', () async { final ui.SceneBuilder builder = ui.SceneBuilder(); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle(ui.Offset.zero, 20, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.build(); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(0, 0, 20, 20)); }); // Draw a picture that's fully outside the screen bounds. Verify the cull rect // is zero. test('fully outside screen bounds', () async { final ui.SceneBuilder builder = ui.SceneBuilder(); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle( const ui.Offset(-100, -100), 20, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.build(); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, ui.Rect.zero); expect(picture.debugExactGlobalCullRect, ui.Rect.zero); }); // Draw a picture that's fully inside the screen. Verify that cull rect is // equal to the paint bounds. test('limits to paint bounds if no clip layers', () async { final ui.SceneBuilder builder = ui.SceneBuilder(); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle( const ui.Offset(50, 50), 10, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.build(); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(40, 40, 60, 60)); }); // Draw a picture smaller than the screen. Offset it such that it remains // fully inside the screen bounds. Verify that cull rect is still just the // paint bounds. test('offset does not affect paint bounds', () async { final ui.SceneBuilder builder = ui.SceneBuilder(); builder.pushOffset(10, 10); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle( const ui.Offset(50, 50), 10, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.pop(); builder.build(); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(40, 40, 60, 60)); }); // Draw a picture smaller than the screen. Offset it such that the picture // overflows screen bounds. Verify that the cull rect is the intersection // between screen bounds and paint bounds. test('offset overflows paint bounds', () async { final ui.SceneBuilder builder = ui.SceneBuilder(); builder.pushOffset(0, 90); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle(ui.Offset.zero, 20, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.pop(); builder.build(); final PersistedPicture picture = enumeratePictures().single; expect( picture.debugExactGlobalCullRect, const ui.Rect.fromLTRB(0, 70, 20, 100)); expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(0, -20, 20, 10)); }, skip: ''' TODO(https://github.com/flutter/flutter/issues/40395) Needs ability to set iframe to 500,100 size. Current screen seems to be 500,500'''); // Draw a picture inside a layer clip but fill all available space inside it. // Verify that the cull rect is equal to the layer clip. test('fills layer clip rect', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushClipRect( const ui.Rect.fromLTWH(10, 10, 60, 60), ); builder.pushClipRect( const ui.Rect.fromLTWH(40, 40, 60, 60), ); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle( ui.Offset.zero, 10000, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.pop(); // pushClipRect builder.pop(); // pushClipRect domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_cull_rect_fills_layer_clip.png', region: region); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(40, 40, 70, 70)); }); // Draw a picture inside a layer clip but position the picture such that its // paint bounds overflow the layer clip. Verify that the cull rect is the // intersection between the layer clip and paint bounds. test('intersects layer clip rect and paint bounds', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushClipRect( const ui.Rect.fromLTWH(10, 10, 60, 60), ); builder.pushClipRect( const ui.Rect.fromLTWH(40, 40, 60, 60), ); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle( const ui.Offset(80, 55), 30, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.pop(); // pushClipRect builder.pop(); // pushClipRect domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile( 'compositing_cull_rect_intersects_clip_and_paint_bounds.png', region: region); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(50, 40, 70, 70)); }); // Draw a picture inside a layer clip that's positioned inside the clip using // an offset layer. Verify that the cull rect is the intersection between the // layer clip and the offset paint bounds. test('offsets picture inside layer clip rect', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushClipRect( const ui.Rect.fromLTWH(10, 10, 60, 60), ); builder.pushClipRect( const ui.Rect.fromLTWH(40, 40, 60, 60), ); builder.pushOffset(55, 70); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle(ui.Offset.zero, 20, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.pop(); // pushOffset builder.pop(); // pushClipRect builder.pop(); // pushClipRect domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_cull_rect_offset_inside_layer_clip.png', region: region); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, const ui.Rect.fromLTRB(-15.0, -20.0, 15.0, 0.0)); }); // Draw a picture inside a layer clip that's positioned an offset layer such // that the picture is push completely outside the clip area. Verify that the // cull rect is zero. test('zero intersection with clip', () async { final ui.SceneBuilder builder = ui.SceneBuilder(); builder.pushClipRect( const ui.Rect.fromLTWH(10, 10, 60, 60), ); builder.pushClipRect( const ui.Rect.fromLTWH(40, 40, 60, 60), ); builder.pushOffset(100, 50); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawCircle(ui.Offset.zero, 20, SurfacePaint()..style = ui.PaintingStyle.fill); }); builder.pop(); // pushOffset builder.pop(); // pushClipRect builder.pop(); // pushClipRect builder.build(); final PersistedPicture picture = enumeratePictures().single; expect(picture.optimalLocalCullRect, ui.Rect.zero); expect(picture.debugExactGlobalCullRect, ui.Rect.zero); }); // Draw a picture inside a rotated clip. Verify that the cull rect is big // enough to fit the rotated clip. test('rotates clip and the picture', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushOffset(80, 50); builder.pushTransform( Matrix4.rotationZ(-math.pi / 4).toFloat64(), ); builder.pushClipRect( const ui.Rect.fromLTRB(-10, -10, 10, 10), ); builder.pushTransform( Matrix4.rotationZ(math.pi / 4).toFloat64(), ); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawPaint(SurfacePaint() ..color = const ui.Color.fromRGBO(0, 0, 255, 0.6) ..style = ui.PaintingStyle.fill); canvas.drawRect( const ui.Rect.fromLTRB(-5, -5, 5, 5), SurfacePaint() ..color = const ui.Color.fromRGBO(0, 255, 0, 1.0) ..style = ui.PaintingStyle.fill, ); }); builder.pop(); // pushTransform builder.pop(); // pushClipRect builder.pop(); // pushTransform builder.pop(); // pushOffset domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_cull_rect_rotated.png', region: region); final PersistedPicture picture = enumeratePictures().single; expect( picture.optimalLocalCullRect, within( distance: 0.05, from: const ui.Rect.fromLTRB(-14.1, -14.1, 14.1, 14.1)), ); }); test('pushClipPath', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); final ui.Path path = ui.Path(); path.addRect(const ui.Rect.fromLTRB(10, 10, 60, 60)); builder.pushClipPath( path, ); _drawTestPicture(builder); builder.pop(); domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_clip_path.png', region: region); }); // Draw a picture inside a rotated clip. Verify that the cull rect is big // enough to fit the rotated clip. test('clips correctly when using 3d transforms', () async { final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushTransform(Matrix4.diagonal3Values( EngineFlutterDisplay.instance.browserDevicePixelRatio, EngineFlutterDisplay.instance.browserDevicePixelRatio, 1.0) .toFloat64()); // TODO(yjbanov): see the TODO below. // final double screenWidth = domWindow.innerWidth.toDouble(); // final double screenHeight = domWindow.innerHeight.toDouble(); final Matrix4 scaleTransform = Matrix4.identity().scaled(0.5, 0.2); builder.pushTransform( scaleTransform.toFloat64(), ); builder.pushOffset(400, 200); builder.pushClipRect( const ui.Rect.fromLTRB(-200, -200, 200, 200), ); builder .pushTransform(Matrix4.rotationY(45.0 * math.pi / 180.0).toFloat64()); builder.pushClipRect( const ui.Rect.fromLTRB(-140, -140, 140, 140), ); builder.pushTransform(Matrix4.translationValues(0, 0, -50).toFloat64()); drawWithBitmapCanvas(builder, (RecordingCanvas canvas) { canvas.drawPaint(SurfacePaint() ..color = const ui.Color.fromRGBO(0, 0, 255, 0.6) ..style = ui.PaintingStyle.fill); // ui.Rect will be clipped. canvas.drawRect( const ui.Rect.fromLTRB(-150, -150, 150, 150), SurfacePaint() ..color = const ui.Color.fromRGBO(0, 255, 0, 1.0) ..style = ui.PaintingStyle.fill, ); // Should be outside the clip range. canvas.drawRect( const ui.Rect.fromLTRB(-150, -150, -140, -140), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 255, 0, 0) ..style = ui.PaintingStyle.fill, ); canvas.drawRect( const ui.Rect.fromLTRB(140, -150, 150, -140), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 255, 0, 0) ..style = ui.PaintingStyle.fill, ); canvas.drawRect( const ui.Rect.fromLTRB(-150, 140, -140, 150), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 255, 0, 0) ..style = ui.PaintingStyle.fill, ); canvas.drawRect( const ui.Rect.fromLTRB(140, 140, 150, 150), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 255, 0, 0) ..style = ui.PaintingStyle.fill, ); // Should be inside clip range canvas.drawRect( const ui.Rect.fromLTRB(-100, -100, -90, -90), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 0, 0, 0x80) ..style = ui.PaintingStyle.fill, ); canvas.drawRect( const ui.Rect.fromLTRB(90, -100, 100, -90), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 0, 0, 0x80) ..style = ui.PaintingStyle.fill, ); canvas.drawRect( const ui.Rect.fromLTRB(-100, 90, -90, 100), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 0, 0, 0x80) ..style = ui.PaintingStyle.fill, ); canvas.drawRect( const ui.Rect.fromLTRB(90, 90, 100, 100), SurfacePaint() ..color = const ui.Color.fromARGB(0xE0, 0, 0, 0x80) ..style = ui.PaintingStyle.fill, ); }); builder.pop(); // pushTransform Z-50 builder.pop(); // pushClipRect builder.pop(); // pushTransform 3D rotate builder.pop(); // pushClipRect builder.pop(); // pushOffset builder.pop(); // pushTransform scale builder.pop(); // pushTransform scale devicepixelratio domDocument.body!.append(builder.build().webOnlyRootElement!); await matchGoldenFile('compositing_3d_rotate1.png', region: region); // ignore: unused_local_variable final PersistedPicture picture = enumeratePictures().single; // TODO(yjbanov): https://github.com/flutter/flutter/issues/40395) // Needs ability to set iframe to 500,100 size. Current screen seems to be 500,500. // expect( // picture.optimalLocalCullRect, // within( // distance: 0.05, // from: ui.Rect.fromLTRB( // -140, -140, screenWidth - 360.0, screenHeight + 40.0)), // ); }); // This test reproduces text blurriness when two pieces of text appear inside // two nested clips: // // ┌───────────────────────┐ // │ text in outer clip │ // │ ┌────────────────────┐│ // │ │ text in inner clip ││ // │ └────────────────────┘│ // └───────────────────────┘ // // This test clips using layers. See a similar test in `bitmap_canvas_golden_test.dart`, // which clips using canvas. // // More details: https://github.com/flutter/flutter/issues/32274 test( 'renders clipped text with high quality', () async { // To reproduce blurriness we need real clipping. final CanvasParagraph paragraph = (ui.ParagraphBuilder(ui.ParagraphStyle(fontFamily: 'Roboto')) // Use a decoration to force rendering in DOM mode. ..pushStyle(ui.TextStyle(decoration: ui.TextDecoration.lineThrough, decorationColor: const ui.Color(0x00000000))) ..addText('Am I blurry?')) .build() as CanvasParagraph; paragraph.layout(const ui.ParagraphConstraints(width: 1000)); final ui.Rect canvasSize = ui.Rect.fromLTRB( 0, 0, paragraph.maxIntrinsicWidth + 16, 2 * paragraph.height + 32, ); final ui.Rect outerClip = ui.Rect.fromLTRB(0.5, 0.5, canvasSize.right, canvasSize.bottom); final ui.Rect innerClip = ui.Rect.fromLTRB(0.5, canvasSize.bottom / 2 + 0.5, canvasSize.right, canvasSize.bottom); final SurfaceSceneBuilder builder = SurfaceSceneBuilder(); builder.pushClipRect(outerClip); { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(outerClip); canvas.drawParagraph(paragraph, const ui.Offset(8.5, 8.5)); final ui.Picture picture = recorder.endRecording(); expect(paragraph.canDrawOnCanvas, isFalse); builder.addPicture( ui.Offset.zero, picture, ); } builder.pushClipRect(innerClip); { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(innerClip); canvas.drawParagraph(paragraph, ui.Offset(8.5, 8.5 + innerClip.top)); final ui.Picture picture = recorder.endRecording(); expect(paragraph.canDrawOnCanvas, isFalse); builder.addPicture( ui.Offset.zero, picture, ); } builder.pop(); // inner clip builder.pop(); // outer clip final DomElement sceneElement = builder.build().webOnlyRootElement!; expect( sceneElement .querySelectorAll('flt-paragraph') .map<String>((DomElement e) => e.innerText) .toList(), <String>['Am I blurry?', 'Am I blurry?'], reason: 'Expected to render text using HTML', ); domDocument.body!.append(sceneElement); await matchGoldenFile( 'compositing_draw_high_quality_text.png', region: canvasSize, ); }, testOn: 'chrome', ); } void _drawTestPicture(ui.SceneBuilder builder) { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 100, 100)); canvas.drawCircle( const ui.Offset(10, 10), 10, SurfacePaint()..style = ui.PaintingStyle.fill); canvas.drawCircle( const ui.Offset(60, 10), 10, SurfacePaint() ..style = ui.PaintingStyle.fill ..color = const ui.Color.fromRGBO(255, 0, 0, 1)); canvas.drawCircle( const ui.Offset(10, 60), 10, SurfacePaint() ..style = ui.PaintingStyle.fill ..color = const ui.Color.fromRGBO(0, 255, 0, 1)); canvas.drawCircle( const ui.Offset(60, 60), 10, SurfacePaint() ..style = ui.PaintingStyle.fill ..color = const ui.Color.fromRGBO(0, 0, 255, 1)); final ui.Picture picture = recorder.endRecording(); builder.addPicture( ui.Offset.zero, picture, ); } typedef PaintCallback = void Function(RecordingCanvas canvas); void drawWithBitmapCanvas(ui.SceneBuilder builder, PaintCallback callback, {ui.Rect bounds = ui.Rect.largest}) { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(bounds); canvas.debugEnforceArbitraryPaint(); callback(canvas); final ui.Picture picture = recorder.endRecording(); builder.addPicture( ui.Offset.zero, picture, ); }
engine/lib/web_ui/test/html/compositing/compositing_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/compositing/compositing_golden_test.dart", "repo_id": "engine", "token_count": 9708 }
332
// 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' hide window; import '../../common/test_initialization.dart'; import 'helper.dart'; const String _rtlWord1 = 'واحد'; const String _rtlWord2 = 'اثنان'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); void paintBasicBidiStartingWithLtr( EngineCanvas canvas, Rect bounds, double y, TextDirection textDirection, TextAlign textAlign, ) { // The text starts with a left-to-right word. const String text = 'One 12 $_rtlWord1 $_rtlWord2 34 two 56'; final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textDirection: textDirection, textAlign: textAlign, ); final CanvasParagraph paragraph = plain( paragraphStyle, text, textStyle: EngineTextStyle.only(color: blue), ); final double maxWidth = bounds.width - 10; paragraph.layout(constrain(maxWidth)); canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5)); } test('basic bidi starting with ltr', () { const Rect bounds = Rect.fromLTWH(0, 0, 340, 600); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); const double height = 40; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintBasicBidiStartingWithLtr(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintBasicBidiStartingWithLtr(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintBasicBidiStartingWithLtr(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintBasicBidiStartingWithLtr(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintBasicBidiStartingWithLtr(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintBasicBidiStartingWithLtr(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintBasicBidiStartingWithLtr(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintBasicBidiStartingWithLtr(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintBasicBidiStartingWithLtr(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintBasicBidiStartingWithLtr(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_ltr'); }); test('basic bidi starting with ltr (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 340, 600); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); const double height = 40; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintBasicBidiStartingWithLtr(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintBasicBidiStartingWithLtr(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintBasicBidiStartingWithLtr(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintBasicBidiStartingWithLtr(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintBasicBidiStartingWithLtr(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintBasicBidiStartingWithLtr(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintBasicBidiStartingWithLtr(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintBasicBidiStartingWithLtr(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintBasicBidiStartingWithLtr(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintBasicBidiStartingWithLtr(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_ltr_dom'); }); void paintBasicBidiStartingWithRtl( EngineCanvas canvas, Rect bounds, double y, TextDirection textDirection, TextAlign textAlign, ) { // The text starts with a right-to-left word. const String text = '$_rtlWord1 12 one 34 $_rtlWord2 56 two'; final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textDirection: textDirection, textAlign: textAlign, ); final CanvasParagraph paragraph = plain( paragraphStyle, text, textStyle: EngineTextStyle.only(color: blue), ); final double maxWidth = bounds.width - 10; paragraph.layout(constrain(maxWidth)); canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5)); } test('basic bidi starting with rtl', () { const Rect bounds = Rect.fromLTWH(0, 0, 340, 600); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); const double height = 40; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintBasicBidiStartingWithRtl(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintBasicBidiStartingWithRtl(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintBasicBidiStartingWithRtl(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintBasicBidiStartingWithRtl(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintBasicBidiStartingWithRtl(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintBasicBidiStartingWithRtl(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintBasicBidiStartingWithRtl(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintBasicBidiStartingWithRtl(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintBasicBidiStartingWithRtl(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintBasicBidiStartingWithRtl(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_rtl'); }); test('basic bidi starting with rtl (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 340, 600); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); const double height = 40; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintBasicBidiStartingWithRtl(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintBasicBidiStartingWithRtl(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintBasicBidiStartingWithRtl(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintBasicBidiStartingWithRtl(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintBasicBidiStartingWithRtl(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintBasicBidiStartingWithRtl(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintBasicBidiStartingWithRtl(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintBasicBidiStartingWithRtl(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintBasicBidiStartingWithRtl(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintBasicBidiStartingWithRtl(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_rtl_dom'); }); void paintMultilineBidi( EngineCanvas canvas, Rect bounds, double y, TextDirection textDirection, TextAlign textAlign, ) { // ''' // Lorem 12 $_rtlWord1 // $_rtlWord2 34 ipsum // dolor 56 // ''' const String text = 'Lorem 12 $_rtlWord1 $_rtlWord2 34 ipsum dolor 56'; final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textDirection: textDirection, textAlign: textAlign, ); final CanvasParagraph paragraph = plain( paragraphStyle, text, textStyle: EngineTextStyle.only(color: blue), ); final double maxWidth = bounds.width - 10; paragraph.layout(constrain(maxWidth)); canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5)); } test('multiline bidi', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 500); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); const double height = 95; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintMultilineBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintMultilineBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintMultilineBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintMultilineBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintMultilineBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintMultilineBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintMultilineBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintMultilineBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintMultilineBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintMultilineBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multiline'); }); test('multiline bidi (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 500); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); const double height = 95; final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintMultilineBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintMultilineBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintMultilineBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintMultilineBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintMultilineBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintMultilineBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintMultilineBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintMultilineBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintMultilineBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintMultilineBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multiline_dom'); }); void paintMultSpanBidi( EngineCanvas canvas, Rect bounds, double y, TextDirection textDirection, TextAlign textAlign, ) { final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textDirection: textDirection, textAlign: textAlign, ); // ''' // Lorem 12 $_rtlWord1 // $_rtlWord2 34 ipsum // dolor 56 // ''' final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('Lorem '); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('12 '); builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('$_rtlWord1 '); builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('$_rtlWord2 '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('34 ipsum '); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('dolor 56 '); }); final double maxWidth = bounds.width - 10; paragraph.layout(constrain(maxWidth)); canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5)); } test('multi span bidi', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 900); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); const double height = 95; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintMultSpanBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintMultSpanBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintMultSpanBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintMultSpanBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintMultSpanBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintMultSpanBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintMultSpanBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintMultSpanBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintMultSpanBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintMultSpanBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multispan'); }); test('multi span bidi (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 900); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); const double height = 95; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintMultSpanBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintMultSpanBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintMultSpanBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintMultSpanBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintMultSpanBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintMultSpanBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintMultSpanBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintMultSpanBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintMultSpanBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintMultSpanBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multispan_dom'); }); void paintBidiWithSelection( EngineCanvas canvas, Rect bounds, double y, TextDirection textDirection, TextAlign textAlign, ) { // ''' // Lorem 12 $_rtlWord1 // $_rtlWord2 34 ipsum // dolor 56 // ''' const String text = 'Lorem 12 $_rtlWord1 $_rtlWord2 34 ipsum dolor 56'; final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textDirection: textDirection, textAlign: textAlign, ); final CanvasParagraph paragraph = plain( paragraphStyle, text, textStyle: EngineTextStyle.only(color: blue), ); final double maxWidth = bounds.width - 10; paragraph.layout(constrain(maxWidth)); final Offset offset = Offset(bounds.left + 5, bounds.top + y + 5); // Range for "em 12 " and the first character of `_rtlWord1`. fillBoxes(canvas, offset, paragraph.getBoxesForRange(3, 10), lightBlue); // Range for the second half of `_rtlWord1` and all of `_rtlWord2` and " 3". fillBoxes(canvas, offset, paragraph.getBoxesForRange(11, 21), lightPurple); // Range for "psum dolo". fillBoxes(canvas, offset, paragraph.getBoxesForRange(24, 33), green); canvas.drawParagraph(paragraph, offset); } test('bidi with selection', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 500); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); const double height = 95; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintBidiWithSelection(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintBidiWithSelection(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintBidiWithSelection(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintBidiWithSelection(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintBidiWithSelection(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintBidiWithSelection(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintBidiWithSelection(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintBidiWithSelection(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintBidiWithSelection(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintBidiWithSelection(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_selection'); }); test('bidi with selection (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 500); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); const double height = 95; // Border for ltr paragraphs. final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10); canvas.drawRect( ltrBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // LTR with different text align values: paintBidiWithSelection(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left); paintBidiWithSelection(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right); paintBidiWithSelection(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center); paintBidiWithSelection(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start); paintBidiWithSelection(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end); // Border for rtl paragraphs. final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0); canvas.drawRect( rtlBox, SurfacePaintData() ..color = black.value ..style = PaintingStyle.stroke, ); // RTL with different text align values: paintBidiWithSelection(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left); paintBidiWithSelection(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right); paintBidiWithSelection(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center); paintBidiWithSelection(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start); paintBidiWithSelection(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end); return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_selection_dom'); }); }
engine/lib/web_ui/test/html/paragraph/bidi_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/paragraph/bidi_golden_test.dart", "repo_id": "engine", "token_count": 9179 }
333
// 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:web_engine_tester/golden_tester.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('Picture', () { test('toImage produces an image', () async { final EnginePictureRecorder recorder = EnginePictureRecorder(); final RecordingCanvas canvas = recorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 200, 100)); canvas.drawCircle( const ui.Offset(100, 50), 40, SurfacePaint() ..color = const ui.Color.fromARGB(255, 255, 100, 100), ); final ui.Picture picture = recorder.endRecording(); final HtmlImage image = await picture.toImage(200, 100) as HtmlImage; expect(image, isNotNull); domDocument.body! ..style.margin = '0' ..append(image.imgElement); try { await matchGoldenFile( 'picture_to_image.png', region: const ui.Rect.fromLTRB(0, 0, 200, 100), ); } finally { image.imgElement.remove(); } }); }); }
engine/lib/web_ui/test/html/picture_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/picture_golden_test.dart", "repo_id": "engine", "token_count": 541 }
334
// 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/test.dart'; import 'package:ui/src/engine.dart'; TestLine l( String? displayText, int? startIndex, int? endIndex, { bool? hardBreak, double? height, double? width, double? widthWithTrailingSpaces, double? left, double? baseline, }) { return TestLine( displayText: displayText, startIndex: startIndex, endIndex: endIndex, hardBreak: hardBreak, height: height, width: width, widthWithTrailingSpaces: widthWithTrailingSpaces, left: left, baseline: baseline, ); } void expectLines(CanvasParagraph paragraph, List<TestLine> expectedLines) { final List<ParagraphLine> lines = paragraph.lines; expect(lines, hasLength(expectedLines.length)); for (int i = 0; i < lines.length; i++) { final ParagraphLine line = lines[i]; final TestLine expectedLine = expectedLines[i]; expect( line.lineNumber, i, reason: 'line #$i had the wrong `lineNumber`. Expected: $i. Actual: ${line.lineNumber}', ); if (expectedLine.displayText != null) { final String displayText = line.getText(paragraph); expect( displayText, expectedLine.displayText, reason: 'line #$i had a different `displayText` value: "$displayText" vs. "${expectedLine.displayText}"', ); } if (expectedLine.startIndex != null) { expect( line.startIndex, expectedLine.startIndex, reason: 'line #$i had a different `startIndex` value: "${line.startIndex}" vs. "${expectedLine.startIndex}"', ); } if (expectedLine.endIndex != null) { expect( line.endIndex, expectedLine.endIndex, reason: 'line #$i had a different `endIndex` value: "${line.endIndex}" vs. "${expectedLine.endIndex}"', ); } if (expectedLine.hardBreak != null) { expect( line.hardBreak, expectedLine.hardBreak, reason: 'line #$i had a different `hardBreak` value: "${line.hardBreak}" vs. "${expectedLine.hardBreak}"', ); } if (expectedLine.height != null) { expect( line.height, expectedLine.height, reason: 'line #$i had a different `height` value: "${line.height}" vs. "${expectedLine.height}"', ); } if (expectedLine.width != null) { expect( line.width, expectedLine.width, reason: 'line #$i had a different `width` value: "${line.width}" vs. "${expectedLine.width}"', ); } if (expectedLine.widthWithTrailingSpaces != null) { expect( line.widthWithTrailingSpaces, expectedLine.widthWithTrailingSpaces, reason: 'line #$i had a different `widthWithTrailingSpaces` value: "${line.widthWithTrailingSpaces}" vs. "${expectedLine.widthWithTrailingSpaces}"', ); } if (expectedLine.left != null) { expect( line.left, expectedLine.left, reason: 'line #$i had a different `left` value: "${line.left}" vs. "${expectedLine.left}"', ); } if (expectedLine.baseline != null) { expect( line.baseline, expectedLine.baseline, reason: 'line #$i had a different `baseline` value: "${line.baseline}" vs. "${expectedLine.baseline}"', ); } } } class TestLine { TestLine({ this.displayText, this.startIndex, this.endIndex, this.hardBreak, this.height, this.width, this.widthWithTrailingSpaces, this.left, this.baseline, }); final String? displayText; final int? startIndex; final int? endIndex; final bool? hardBreak; final double? height; final double? width; final double? widthWithTrailingSpaces; final double? left; final double? baseline; }
engine/lib/web_ui/test/html/text/layout_service_helper.dart/0
{ "file_path": "engine/lib/web_ui/test/html/text/layout_service_helper.dart", "repo_id": "engine", "token_count": 1628 }
335
// 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:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:web_engine_tester/golden_tester.dart'; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } const ui.Rect kDefaultRegion = ui.Rect.fromLTRB(0, 0, 100, 100); void testMain() { group('Font fallbacks', () { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); setUp(() { debugDisableFontFallbacks = false; }); /// Used to save and restore [ui.PlatformDispatcher.onPlatformMessage] after each test. ui.PlatformMessageCallback? savedCallback; final List<String> downloadedFontFamilies = <String>[]; setUp(() { renderer.fontCollection.debugResetFallbackFonts(); renderer.fontCollection.fontFallbackManager!.downloadQueue.fallbackFontUrlPrefixOverride = 'assets/fallback_fonts/'; renderer.fontCollection.fontFallbackManager!.downloadQueue.debugOnLoadFontFamily = (String family) => downloadedFontFamilies.add(family); savedCallback = ui.PlatformDispatcher.instance.onPlatformMessage; }); tearDown(() { downloadedFontFamilies.clear(); ui.PlatformDispatcher.instance.onPlatformMessage = savedCallback; }); test('Roboto is always a fallback font', () { expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, contains('Roboto')); }); test('will download Noto Sans Arabic if Arabic text is added', () async { expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, <String>['Roboto']); // Creating this paragraph should cause us to start to download the // fallback font. ui.ParagraphBuilder pb = ui.ParagraphBuilder( ui.ParagraphStyle(), ); pb.addText('مرحبا'); pb.build().layout(const ui.ParagraphConstraints(width: 1000)); await renderer.fontCollection.fontFallbackManager!.debugWhenIdle(); expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, contains('Noto Sans Arabic')); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); pb = ui.ParagraphBuilder( ui.ParagraphStyle(), ); pb.pushStyle(ui.TextStyle(fontSize: 32)); pb.addText('مرحبا'); pb.pop(); final ui.Paragraph paragraph = pb.build(); paragraph.layout(const ui.ParagraphConstraints(width: 1000)); canvas.drawParagraph(paragraph, ui.Offset.zero); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile( 'ui_font_fallback_arabic.png', region: kDefaultRegion, ); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520 }); test('will put the Noto Color Emoji font before other fallback fonts in the list', () async { expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, <String>['Roboto']); // Creating this paragraph should cause us to start to download the // Arabic fallback font. ui.ParagraphBuilder pb = ui.ParagraphBuilder( ui.ParagraphStyle(), ); pb.addText('مرحبا'); pb.build().layout(const ui.ParagraphConstraints(width: 1000)); await renderer.fontCollection.fontFallbackManager!.debugWhenIdle(); expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, <String>['Roboto', 'Noto Sans Arabic']); pb = ui.ParagraphBuilder( ui.ParagraphStyle(), ); pb.pushStyle(ui.TextStyle(fontSize: 26)); pb.addText('Hello 😊 مرحبا'); pb.pop(); final ui.Paragraph paragraph = pb.build(); paragraph.layout(const ui.ParagraphConstraints(width: 1000)); await renderer.fontCollection.fontFallbackManager!.debugWhenIdle(); expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, <String>[ 'Roboto', 'Noto Color Emoji', 'Noto Sans Arabic', ]); }); test('will download Noto Color Emojis and Noto Symbols if no matching Noto Font', () async { expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, <String>['Roboto']); // Creating this paragraph should cause us to start to download the // fallback font. ui.ParagraphBuilder pb = ui.ParagraphBuilder( ui.ParagraphStyle(), ); pb.addText('Hello 😊'); pb.build().layout(const ui.ParagraphConstraints(width: 1000)); await renderer.fontCollection.fontFallbackManager!.debugWhenIdle(); expect(renderer.fontCollection.fontFallbackManager!.globalFontFallbacks, contains('Noto Color Emoji')); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); pb = ui.ParagraphBuilder( ui.ParagraphStyle(), ); pb.pushStyle(ui.TextStyle(fontSize: 26)); pb.addText('Hello 😊'); pb.pop(); final ui.Paragraph paragraph = pb.build(); paragraph.layout(const ui.ParagraphConstraints(width: 1000)); canvas.drawParagraph(paragraph, ui.Offset.zero); await drawPictureUsingCurrentRenderer(recorder.endRecording()); await matchGoldenFile( 'ui_font_fallback_emoji.png', region: kDefaultRegion, ); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520 }); /// Attempts to render [text] and verifies that [expectedFamilies] are downloaded. /// /// Then it does the same, but asserts that the families aren't downloaded again /// (because they already exist in memory). Future<void> checkDownloadedFamiliesForString(String text, List<String> expectedFamilies) async { // Try rendering text that requires fallback fonts, initially before the fonts are loaded. ui.ParagraphBuilder pb = ui.ParagraphBuilder(ui.ParagraphStyle()); pb.addText(text); pb.build().layout(const ui.ParagraphConstraints(width: 1000)); await renderer.fontCollection.fontFallbackManager!.debugWhenIdle(); expect( downloadedFontFamilies, expectedFamilies, ); // Do the same thing but this time with loaded fonts. downloadedFontFamilies.clear(); pb = ui.ParagraphBuilder(ui.ParagraphStyle()); pb.addText(text); pb.build().layout(const ui.ParagraphConstraints(width: 1000)); await renderer.fontCollection.fontFallbackManager!.debugWhenIdle(); expect(downloadedFontFamilies, isEmpty); } // Regression test for https://github.com/flutter/flutter/issues/75836 // When we had this bug our font fallback resolution logic would end up in an // infinite loop and this test would freeze and time out. test( 'can find fonts for two adjacent unmatched code points from different fonts', () async { await checkDownloadedFamiliesForString('ヽಠ', <String>[ 'Noto Sans SC', 'Noto Sans Kannada', ]); }); test('can find glyph for 2/3 symbol', () async { await checkDownloadedFamiliesForString('⅔', <String>[ 'Noto Sans', ]); }); // https://github.com/flutter/devtools/issues/6149 test('can find glyph for treble clef', () async { await checkDownloadedFamiliesForString('𝄞', <String>[ 'Noto Music', ]); }); test('findMinimumFontsForCodePoints for all supported code points', () async { // Collect all supported code points from all fallback fonts in the Noto // font tree. final Set<String> testedFonts = <String>{}; final Set<int> supportedUniqueCodePoints = <int>{}; renderer.fontCollection.fontFallbackManager!.codePointToComponents .forEachRange((int start, int end, FallbackFontComponent component) { if (component.fonts.isNotEmpty) { bool componentHasEnabledFont = false; for (final NotoFont font in component.fonts) { if (font.enabled) { testedFonts.add(font.name); componentHasEnabledFont = true; } } if (componentHasEnabledFont) { for (int codePoint = start; codePoint <= end; codePoint++) { supportedUniqueCodePoints.add(codePoint); } } } }); expect( supportedUniqueCodePoints.length, greaterThan(10000)); // sanity check expect( testedFonts, unorderedEquals(<String>{ 'Noto Color Emoji', 'Noto Music', 'Noto Sans', 'Noto Sans Symbols', 'Noto Sans Symbols 2', 'Noto Sans Adlam', 'Noto Sans Anatolian Hieroglyphs', 'Noto Sans Arabic', 'Noto Sans Armenian', 'Noto Sans Avestan', 'Noto Sans Balinese', 'Noto Sans Bamum', 'Noto Sans Bassa Vah', 'Noto Sans Batak', 'Noto Sans Bengali', 'Noto Sans Bhaiksuki', 'Noto Sans Brahmi', 'Noto Sans Buginese', 'Noto Sans Buhid', 'Noto Sans Canadian Aboriginal', 'Noto Sans Carian', 'Noto Sans Caucasian Albanian', 'Noto Sans Chakma', 'Noto Sans Cham', 'Noto Sans Cherokee', 'Noto Sans Coptic', 'Noto Sans Cuneiform', 'Noto Sans Cypriot', 'Noto Sans Deseret', 'Noto Sans Devanagari', 'Noto Sans Duployan', 'Noto Sans Egyptian Hieroglyphs', 'Noto Sans Elbasan', 'Noto Sans Elymaic', 'Noto Sans Georgian', 'Noto Sans Glagolitic', 'Noto Sans Gothic', 'Noto Sans Grantha', 'Noto Sans Gujarati', 'Noto Sans Gunjala Gondi', 'Noto Sans Gurmukhi', 'Noto Sans HK', 'Noto Sans Hanunoo', 'Noto Sans Hatran', 'Noto Sans Hebrew', 'Noto Sans Imperial Aramaic', 'Noto Sans Indic Siyaq Numbers', 'Noto Sans Inscriptional Pahlavi', 'Noto Sans Inscriptional Parthian', 'Noto Sans JP', 'Noto Sans Javanese', 'Noto Sans KR', 'Noto Sans Kaithi', 'Noto Sans Kannada', 'Noto Sans Kayah Li', 'Noto Sans Kharoshthi', 'Noto Sans Khmer', 'Noto Sans Khojki', 'Noto Sans Khudawadi', 'Noto Sans Lao', 'Noto Sans Lepcha', 'Noto Sans Limbu', 'Noto Sans Linear A', 'Noto Sans Linear B', 'Noto Sans Lisu', 'Noto Sans Lycian', 'Noto Sans Lydian', 'Noto Sans Mahajani', 'Noto Sans Malayalam', 'Noto Sans Mandaic', 'Noto Sans Manichaean', 'Noto Sans Marchen', 'Noto Sans Masaram Gondi', 'Noto Sans Math', 'Noto Sans Mayan Numerals', 'Noto Sans Medefaidrin', 'Noto Sans Meetei Mayek', 'Noto Sans Meroitic', 'Noto Sans Miao', 'Noto Sans Modi', 'Noto Sans Mongolian', 'Noto Sans Mro', 'Noto Sans Multani', 'Noto Sans Myanmar', 'Noto Sans NKo', 'Noto Sans Nabataean', 'Noto Sans New Tai Lue', 'Noto Sans Newa', 'Noto Sans Nushu', 'Noto Sans Ogham', 'Noto Sans Ol Chiki', 'Noto Sans Old Hungarian', 'Noto Sans Old Italic', 'Noto Sans Old North Arabian', 'Noto Sans Old Permic', 'Noto Sans Old Persian', 'Noto Sans Old Sogdian', 'Noto Sans Old South Arabian', 'Noto Sans Old Turkic', 'Noto Sans Oriya', 'Noto Sans Osage', 'Noto Sans Osmanya', 'Noto Sans Pahawh Hmong', 'Noto Sans Palmyrene', 'Noto Sans Pau Cin Hau', 'Noto Sans Phags Pa', 'Noto Sans Phoenician', 'Noto Sans Psalter Pahlavi', 'Noto Sans Rejang', 'Noto Sans Runic', 'Noto Sans SC', 'Noto Sans Saurashtra', 'Noto Sans Sharada', 'Noto Sans Shavian', 'Noto Sans Siddham', 'Noto Sans Sinhala', 'Noto Sans Sogdian', 'Noto Sans Sora Sompeng', 'Noto Sans Soyombo', 'Noto Sans Sundanese', 'Noto Sans Syloti Nagri', 'Noto Sans Syriac', 'Noto Sans TC', 'Noto Sans Tagalog', 'Noto Sans Tagbanwa', 'Noto Sans Tai Le', 'Noto Sans Tai Tham', 'Noto Sans Tai Viet', 'Noto Sans Takri', 'Noto Sans Tamil', 'Noto Sans Tamil Supplement', 'Noto Sans Telugu', 'Noto Sans Thaana', 'Noto Sans Thai', 'Noto Sans Tifinagh', 'Noto Sans Tirhuta', 'Noto Sans Ugaritic', 'Noto Sans Vai', 'Noto Sans Wancho', 'Noto Sans Warang Citi', 'Noto Sans Yi', 'Noto Sans Zanabazar Square', })); // Construct random paragraphs out of supported code points. final math.Random random = math.Random(0); final List<int> supportedCodePoints = supportedUniqueCodePoints.toList() ..shuffle(random); const int paragraphLength = 3; const int totalTestSize = 1000; for (int batchStart = 0; batchStart < totalTestSize; batchStart += paragraphLength) { final int batchEnd = math.min(batchStart + paragraphLength, supportedCodePoints.length); final Set<int> codePoints = <int>{}; for (int i = batchStart; i < batchEnd; i += 1) { codePoints.add(supportedCodePoints[i]); } final Set<NotoFont> fonts = <NotoFont>{}; for (final int codePoint in codePoints) { final List<NotoFont> fontsForPoint = renderer .fontCollection.fontFallbackManager!.codePointToComponents .lookup(codePoint) .fonts; // All code points are extracted from the same tree, so there must // be at least one font supporting each code point expect(fontsForPoint, isNotEmpty); fonts.addAll(fontsForPoint); } try { renderer.fontCollection.fontFallbackManager! .findFontsForMissingCodePoints(codePoints.toList()); } catch (e) { print( 'findFontsForMissingCodePoints failed:\n' ' Code points: ${codePoints.join(', ')}\n' ' Fonts: ${fonts.map((NotoFont f) => f.name).join(', ')}', ); rethrow; } } }); }, // HTML renderer doesn't use the fallback font manager. skip: isHtml, timeout: const Timeout.factor(4)); }
engine/lib/web_ui/test/ui/fallback_fonts_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/fallback_fonts_golden_test.dart", "repo_id": "engine", "token_count": 6980 }
336
// 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'; import '../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests(); test('rect accessors', () { const Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0); expect(r.left, equals(1.0)); expect(r.top, equals(3.0)); expect(r.right, equals(5.0)); expect(r.bottom, equals(7.0)); }); test('rect created by width and height', () { const Rect r = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); expect(r.left, equals(1.0)); expect(r.top, equals(3.0)); expect(r.right, equals(6.0)); expect(r.bottom, equals(10.0)); expect(r.shortestSide, equals(5.0)); expect(r.longestSide, equals(7.0)); }); test('rect intersection', () { const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); final Rect r3 = r1.intersect(r2); expect(r3.left, equals(50.0)); expect(r3.top, equals(50.0)); expect(r3.right, equals(100.0)); expect(r3.bottom, equals(100.0)); final Rect r4 = r2.intersect(r1); expect(r4, equals(r3)); }); test('rect expandToInclude overlapping rects', () { const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); final Rect r3 = r1.expandToInclude(r2); expect(r3.left, equals(0.0)); expect(r3.top, equals(0.0)); expect(r3.right, equals(200.0)); expect(r3.bottom, equals(200.0)); final Rect r4 = r2.expandToInclude(r1); expect(r4, equals(r3)); }); test('rect expandToInclude crossing rects', () { const Rect r1 = Rect.fromLTRB(50.0, 0.0, 50.0, 200.0); const Rect r2 = Rect.fromLTRB(0.0, 50.0, 200.0, 50.0); final Rect r3 = r1.expandToInclude(r2); expect(r3.left, equals(0.0)); expect(r3.top, equals(0.0)); expect(r3.right, equals(200.0)); expect(r3.bottom, equals(200.0)); final Rect r4 = r2.expandToInclude(r1); expect(r4, equals(r3)); }); test('size created from doubles', () { const Size size = Size(5.0, 7.0); expect(size.width, equals(5.0)); expect(size.height, equals(7.0)); expect(size.shortestSide, equals(5.0)); expect(size.longestSide, equals(7.0)); }); test('rounded rect created from rect and radii', () { const Rect baseRect = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); final RRect r = RRect.fromRectXY(baseRect, 1.0, 1.0); expect(r.left, equals(1.0)); expect(r.top, equals(3.0)); expect(r.right, equals(6.0)); expect(r.bottom, equals(10.0)); expect(r.shortestSide, equals(5.0)); expect(r.longestSide, equals(7.0)); }); }
engine/lib/web_ui/test/ui/rect_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/rect_test.dart", "repo_id": "engine", "token_count": 1274 }
337
// 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/fml/mapping.h" #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/lib/ui/window/platform_message.h" #include "flutter/runtime/dart_isolate.h" #include "flutter/runtime/dart_vm.h" #include "flutter/runtime/dart_vm_lifecycle.h" #include "flutter/runtime/isolate_configuration.h" #include "flutter/runtime/platform_isolate_manager.h" #include "flutter/testing/dart_isolate_runner.h" #include "flutter/testing/fixture_test.h" #include "flutter/testing/testing.h" #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/scopes/dart_isolate_scope.h" // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace flutter { namespace testing { class DartIsolateTest : public FixtureTest { public: DartIsolateTest() {} void Wait() { latch_.Wait(); } void Signal() { latch_.Signal(); } private: fml::AutoResetWaitableEvent latch_; FML_DISALLOW_COPY_AND_ASSIGN(DartIsolateTest); }; TEST_F(DartIsolateTest, RootIsolateCreationAndShutdown) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate_configuration = IsolateConfiguration::InferFromSettings(settings); UIDartState::Context context(task_runners); context.advisory_script_uri = "main.dart"; context.advisory_script_entrypoint = "main"; auto weak_isolate = DartIsolate::CreateRunningRootIsolate( vm_data->GetSettings(), // settings vm_data->GetIsolateSnapshot(), // isolate snapshot nullptr, // platform configuration DartIsolate::Flags{}, // flags nullptr, // root_isolate_create_callback settings.isolate_create_callback, // isolate create callback settings.isolate_shutdown_callback, // isolate shutdown callback "main", // dart entrypoint std::nullopt, // dart entrypoint library {}, // dart entrypoint arguments std::move(isolate_configuration), // isolate configuration context // engine context ); auto root_isolate = weak_isolate.lock(); ASSERT_TRUE(root_isolate); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); ASSERT_TRUE(root_isolate->Shutdown()); } TEST_F(DartIsolateTest, IsolateShutdownCallbackIsInIsolateScope) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate_configuration = IsolateConfiguration::InferFromSettings(settings); UIDartState::Context context(task_runners); context.advisory_script_uri = "main.dart"; context.advisory_script_entrypoint = "main"; auto weak_isolate = DartIsolate::CreateRunningRootIsolate( vm_data->GetSettings(), // settings vm_data->GetIsolateSnapshot(), // isolate snapshot nullptr, // platform configuration DartIsolate::Flags{}, // flags nullptr, // root_isolate_create_callback settings.isolate_create_callback, // isolate create callback settings.isolate_shutdown_callback, // isolate shutdown callback "main", // dart entrypoint std::nullopt, // dart entrypoint library {}, // dart entrypoint arguments std::move(isolate_configuration), // isolate configuration context // engine context ); auto root_isolate = weak_isolate.lock(); ASSERT_TRUE(root_isolate); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); size_t destruction_callback_count = 0; root_isolate->AddIsolateShutdownCallback([&destruction_callback_count]() { ASSERT_NE(Dart_CurrentIsolate(), nullptr); destruction_callback_count++; }); ASSERT_TRUE(root_isolate->Shutdown()); ASSERT_EQ(destruction_callback_count, 1u); } TEST_F(DartIsolateTest, IsolateCanLoadAndRunDartCode) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); const auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "main", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); } TEST_F(DartIsolateTest, IsolateCannotLoadAndRunUnknownDartEntrypoint) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); const auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "thisShouldNotExist", {}, GetDefaultKernelFilePath()); ASSERT_FALSE(isolate); } TEST_F(DartIsolateTest, CanRunDartCodeCodeSynchronously) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); const auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "main", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); ASSERT_TRUE(isolate->RunInIsolateScope([]() -> bool { if (tonic::CheckAndHandleError(::Dart_Invoke( Dart_RootLibrary(), tonic::ToDart("sayHi"), 0, nullptr))) { return false; } return true; })); } TEST_F(DartIsolateTest, ImpellerFlagIsCorrectWhenTrue) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); settings.enable_impeller = true; auto vm_ref = DartVMRef::Create(settings); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "main", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); ASSERT_TRUE(isolate->RunInIsolateScope([settings]() -> bool { Dart_Handle dart_ui = ::Dart_LookupLibrary(tonic::ToDart("dart:ui")); if (tonic::CheckAndHandleError(dart_ui)) { return false; } Dart_Handle impeller_enabled = ::Dart_GetField(dart_ui, tonic::ToDart("_impellerEnabled")); if (tonic::CheckAndHandleError(impeller_enabled)) { return false; } bool result; if (tonic::CheckAndHandleError( Dart_BooleanValue(impeller_enabled, &result))) { return false; } return result == settings.enable_impeller; })); } TEST_F(DartIsolateTest, ImpellerFlagIsCorrectWhenFalse) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); settings.enable_impeller = false; auto vm_ref = DartVMRef::Create(settings); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "main", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); ASSERT_TRUE(isolate->RunInIsolateScope([settings]() -> bool { Dart_Handle dart_ui = ::Dart_LookupLibrary(tonic::ToDart("dart:ui")); if (tonic::CheckAndHandleError(dart_ui)) { return false; } Dart_Handle impeller_enabled = ::Dart_GetField(dart_ui, tonic::ToDart("_impellerEnabled")); if (tonic::CheckAndHandleError(impeller_enabled)) { return false; } bool result; if (tonic::CheckAndHandleError( Dart_BooleanValue(impeller_enabled, &result))) { return false; } return result == settings.enable_impeller; })); } TEST_F(DartIsolateTest, CanRegisterNativeCallback) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); AddNativeCallback( "NotifyNative", CREATE_NATIVE_ENTRY(([this](Dart_NativeArguments args) { Signal(); }))); const auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); auto thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // thread, // thread, // thread, // thread // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "canRegisterNativeCallback", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); Wait(); } class DartSecondaryIsolateTest : public FixtureTest { public: DartSecondaryIsolateTest() : latch_(3) {} void LatchCountDown() { latch_.CountDown(); } void LatchWait() { latch_.Wait(); } void ChildShutdownSignal() { child_shutdown_latch_.Signal(); } void ChildShutdownWait() { child_shutdown_latch_.Wait(); } void RootIsolateShutdownSignal() { root_isolate_shutdown_latch_.Signal(); } bool RootIsolateIsSignaled() { return root_isolate_shutdown_latch_.IsSignaledForTest(); } private: fml::CountDownLatch latch_; fml::AutoResetWaitableEvent child_shutdown_latch_; fml::AutoResetWaitableEvent root_isolate_shutdown_latch_; FML_DISALLOW_COPY_AND_ASSIGN(DartSecondaryIsolateTest); }; TEST_F(DartSecondaryIsolateTest, CanLaunchSecondaryIsolates) { AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY(([this](Dart_NativeArguments args) { LatchCountDown(); }))); AddNativeCallback( "PassMessage", CREATE_NATIVE_ENTRY(([this](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("Hello from code is secondary isolate.", message); LatchCountDown(); }))); auto settings = CreateSettingsForFixture(); settings.root_isolate_shutdown_callback = [this]() { RootIsolateShutdownSignal(); }; settings.isolate_shutdown_callback = [this]() { ChildShutdownSignal(); }; auto vm_ref = DartVMRef::Create(settings); auto thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // thread, // thread, // thread, // thread // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "testCanLaunchSecondaryIsolate", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); ChildShutdownWait(); // wait for child isolate to shutdown first ASSERT_FALSE(RootIsolateIsSignaled()); LatchWait(); // wait for last NotifyNative called by main isolate // root isolate will be auto-shutdown } /// Tests error handling path of `Isolate.spawn()` in the engine. class IsolateStartupFailureTest : public FixtureTest { public: IsolateStartupFailureTest() : latch_(1) {} void NotifyDone() { latch_.CountDown(); } void WaitForDone() { latch_.Wait(); } private: fml::CountDownLatch latch_; FML_DISALLOW_COPY_AND_ASSIGN(IsolateStartupFailureTest); }; TEST_F(IsolateStartupFailureTest, HandlesIsolateInitializationFailureCorrectly) { AddNativeCallback("MakeNextIsolateSpawnFail", CREATE_NATIVE_ENTRY(([](Dart_NativeArguments args) { Dart_SetRootLibrary(Dart_Null()); }))); AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY( ([this](Dart_NativeArguments args) { NotifyDone(); }))); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); auto thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // thread, // thread, // thread, // thread // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "testIsolateStartupFailure", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); WaitForDone(); } TEST_F(DartIsolateTest, CanReceiveArguments) { AddNativeCallback("NotifyNative", CREATE_NATIVE_ENTRY(([this](Dart_NativeArguments args) { ASSERT_TRUE(tonic::DartConverter<bool>::FromDart( Dart_GetNativeArgument(args, 0))); Signal(); }))); const auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); auto thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // thread, // thread, // thread, // thread // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "testCanReceiveArguments", {"arg1"}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); Wait(); } TEST_F(DartIsolateTest, CanCreateServiceIsolate) { #if (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DEBUG) && \ (FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_PROFILE) GTEST_SKIP(); #endif ASSERT_FALSE(DartVMRef::IsInstanceRunning()); fml::AutoResetWaitableEvent service_isolate_latch; auto settings = CreateSettingsForFixture(); settings.enable_vm_service = true; settings.vm_service_port = 0; settings.vm_service_host = "127.0.0.1"; settings.enable_service_port_fallback = true; settings.service_isolate_create_callback = [&service_isolate_latch]() { service_isolate_latch.Signal(); }; auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate_configuration = IsolateConfiguration::InferFromSettings(settings); UIDartState::Context context(task_runners); context.advisory_script_uri = "main.dart"; context.advisory_script_entrypoint = "main"; auto weak_isolate = DartIsolate::CreateRunningRootIsolate( vm_data->GetSettings(), // settings vm_data->GetIsolateSnapshot(), // isolate snapshot nullptr, // platform configuration DartIsolate::Flags{}, // flags nullptr, // root_isolate_create_callback settings.isolate_create_callback, // isolate create callback settings.isolate_shutdown_callback, // isolate shutdown callback "main", // dart entrypoint std::nullopt, // dart entrypoint library {}, // dart entrypoint arguments std::move(isolate_configuration), // isolate configuration context // engine context ); auto root_isolate = weak_isolate.lock(); ASSERT_TRUE(root_isolate); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); service_isolate_latch.Wait(); ASSERT_TRUE(root_isolate->Shutdown()); } TEST_F(DartIsolateTest, RootIsolateCreateCallbackIsMadeOnceAndBeforeIsolateRunning) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); size_t create_callback_count = 0u; settings.root_isolate_create_callback = [&create_callback_count](const auto& isolate) { ASSERT_EQ(isolate.GetPhase(), DartIsolate::Phase::Ready); create_callback_count++; ASSERT_NE(::Dart_CurrentIsolate(), nullptr); }; auto vm_ref = DartVMRef::Create(settings); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); { auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "main", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); } ASSERT_EQ(create_callback_count, 1u); } TEST_F(DartIsolateTest, IsolateCreateCallbacksTakeInstanceSettingsInsteadOfVMSettings) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto vm_settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(vm_settings); auto instance_settings = vm_settings; size_t create_callback_count = 0u; instance_settings.root_isolate_create_callback = [&create_callback_count](const auto& isolate) { ASSERT_EQ(isolate.GetPhase(), DartIsolate::Phase::Ready); create_callback_count++; ASSERT_NE(::Dart_CurrentIsolate(), nullptr); }; TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); { auto isolate = RunDartCodeInIsolate(vm_ref, instance_settings, task_runners, "main", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); } ASSERT_EQ(create_callback_count, 1u); } TEST_F(DartIsolateTest, InvalidLoadingUnitFails) { if (!DartVM::IsRunningPrecompiledCode()) { FML_LOG(INFO) << "Split AOT does not work in JIT mode"; return; } ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); auto isolate_configuration = IsolateConfiguration::InferFromSettings(settings); UIDartState::Context context(task_runners); context.advisory_script_uri = "main.dart"; context.advisory_script_entrypoint = "main"; auto weak_isolate = DartIsolate::CreateRunningRootIsolate( vm_data->GetSettings(), // settings vm_data->GetIsolateSnapshot(), // isolate snapshot nullptr, // platform configuration DartIsolate::Flags{}, // flags nullptr, // root_isolate_create_callback settings.isolate_create_callback, // isolate create callback settings.isolate_shutdown_callback, // isolate shutdown callback "main", // dart entrypoint std::nullopt, // dart entrypoint library {}, // dart entrypoint arguments std::move(isolate_configuration), // isolate configuration context // engine context ); auto root_isolate = weak_isolate.lock(); ASSERT_TRUE(root_isolate); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); auto isolate_data = std::make_unique<const fml::NonOwnedMapping>( split_aot_symbols_.vm_isolate_data, 0); auto isolate_instructions = std::make_unique<const fml::NonOwnedMapping>( split_aot_symbols_.vm_isolate_instrs, 0); // Invalid loading unit should fail gracefully with error message. ASSERT_FALSE(root_isolate->LoadLoadingUnit(3, std::move(isolate_data), std::move(isolate_instructions))); ASSERT_TRUE(root_isolate->Shutdown()); } TEST_F(DartIsolateTest, DartPluginRegistrantIsCalled) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); std::vector<std::string> messages; fml::AutoResetWaitableEvent latch; AddNativeCallback( "PassMessage", CREATE_NATIVE_ENTRY(([&latch, &messages](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); messages.push_back(message); latch.Signal(); }))); const auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); auto thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // thread, // thread, // thread, // thread // ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "mainForPluginRegistrantTest", {}, GetDefaultKernelFilePath()); ASSERT_TRUE(isolate); ASSERT_EQ(isolate->get()->GetPhase(), DartIsolate::Phase::Running); latch.Wait(); ASSERT_EQ(messages.size(), 1u); ASSERT_EQ(messages[0], "_PluginRegistrant.register() was called"); } TEST_F(DartIsolateTest, SpawningAnIsolateDoesNotReloadKernel) { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); TaskRunners task_runners(GetCurrentTestName(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner(), // GetCurrentTaskRunner() // ); size_t get_kernel_count = 0u; if (!DartVM::IsRunningPrecompiledCode()) { ASSERT_TRUE(settings.application_kernels); auto mappings = settings.application_kernels(); ASSERT_EQ(mappings.size(), 1u); // This feels a little brittle, but the alternative seems to be making // DartIsolate have virtual methods so it can be mocked or exposing weird // test-only API on IsolateConfiguration. settings.application_kernels = fml::MakeCopyable( [&get_kernel_count, mapping = std::move(mappings.front())]() mutable -> Mappings { get_kernel_count++; EXPECT_EQ(get_kernel_count, 1u) << "Unexpectedly got more than one call for the kernel mapping."; EXPECT_TRUE(mapping); std::vector<std::unique_ptr<const fml::Mapping>> kernel_mappings; if (mapping) { kernel_mappings.emplace_back(std::move(mapping)); } return kernel_mappings; }); } std::shared_ptr<DartIsolate> root_isolate; { auto isolate_configuration = IsolateConfiguration::InferFromSettings(settings); UIDartState::Context context(task_runners); context.advisory_script_uri = "main.dart"; context.advisory_script_entrypoint = "main"; auto weak_isolate = DartIsolate::CreateRunningRootIsolate( /*settings=*/vm_data->GetSettings(), /*isolate_snapshot=*/vm_data->GetIsolateSnapshot(), /*platform_configuration=*/nullptr, /*flags=*/DartIsolate::Flags{}, /*root_isolate_create_callback=*/nullptr, /*isolate_create_callback=*/settings.isolate_create_callback, /*isolate_shutdown_callback=*/settings.isolate_shutdown_callback, /*dart_entrypoint=*/"main", /*dart_entrypoint_library=*/std::nullopt, /*dart_entrypoint_args=*/{}, /*isolate_configuration=*/std::move(isolate_configuration), /*context=*/context); root_isolate = weak_isolate.lock(); } ASSERT_TRUE(root_isolate); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); if (!DartVM::IsRunningPrecompiledCode()) { ASSERT_EQ(get_kernel_count, 1u); } { auto isolate_configuration = IsolateConfiguration::InferFromSettings( /*settings=*/settings, /*asset_manager=*/nullptr, /*io_worker=*/nullptr, /*launch_type=*/IsolateLaunchType::kExistingGroup); UIDartState::Context context(task_runners); context.advisory_script_uri = "main.dart"; context.advisory_script_entrypoint = "main"; auto weak_isolate = DartIsolate::CreateRunningRootIsolate( /*settings=*/vm_data->GetSettings(), /*isolate_snapshot=*/vm_data->GetIsolateSnapshot(), /*platform_configuration=*/nullptr, /*flags=*/DartIsolate::Flags{}, /*root_isolate_create_callback=*/nullptr, /*isolate_create_callback=*/settings.isolate_create_callback, /*isolate_shutdown_callback=*/settings.isolate_shutdown_callback, /*dart_entrypoint=*/"main", /*dart_entrypoint_library=*/std::nullopt, /*dart_entrypoint_args=*/{}, /*isolate_configuration=*/std::move(isolate_configuration), /*context=*/context, /*spawning_isolate=*/root_isolate.get()); auto spawned_isolate = weak_isolate.lock(); ASSERT_TRUE(spawned_isolate); ASSERT_EQ(spawned_isolate->GetPhase(), DartIsolate::Phase::Running); if (!DartVM::IsRunningPrecompiledCode()) { ASSERT_EQ(get_kernel_count, 1u); } ASSERT_TRUE(spawned_isolate->Shutdown()); } ASSERT_TRUE(root_isolate->Shutdown()); } class FakePlatformConfigurationClient : public PlatformConfigurationClient { public: std::shared_ptr<PlatformIsolateManager> mgr = std::shared_ptr<PlatformIsolateManager>(new PlatformIsolateManager()); std::shared_ptr<PlatformIsolateManager> GetPlatformIsolateManager() override { return mgr; } std::string DefaultRouteName() override { return ""; } void ScheduleFrame() override {} void EndWarmUpFrame() override {} void Render(int64_t view_id, Scene* scene, double width, double height) override {} void UpdateSemantics(SemanticsUpdate* update) override {} void HandlePlatformMessage( std::unique_ptr<PlatformMessage> message) override {} FontCollection& GetFontCollection() override { FML_UNREACHABLE(); return *(FontCollection*)(this); } std::shared_ptr<AssetManager> GetAssetManager() override { return nullptr; } void UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) override {} void SetNeedsReportTimings(bool value) override {} std::shared_ptr<const fml::Mapping> GetPersistentIsolateData() override { return nullptr; } std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale( const std::vector<std::string>& supported_locale_data) override { return nullptr; } void RequestDartDeferredLibrary(intptr_t loading_unit_id) override {} void SendChannelUpdate(std::string name, bool listening) override {} double GetScaledFontSize(double unscaled_font_size, int configuration_id) const override { return 0; } }; TEST_F(DartIsolateTest, PlatformIsolateCreationAndShutdown) { fml::AutoResetWaitableEvent message_latch; AddNativeCallback( "PassMessage", CREATE_NATIVE_ENTRY(([&message_latch](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("Platform isolate is ready", message); message_latch.Signal(); }))); FakePlatformConfigurationClient client; auto platform_configuration = std::make_unique<PlatformConfiguration>(&client); Dart_Isolate platform_isolate = nullptr; { ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); auto platform_thread = CreateNewThread(); auto ui_thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // label platform_thread, // platform ui_thread, // raster ui_thread, // ui ui_thread // io ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {}, GetDefaultKernelFilePath(), {}, nullptr, std::move(platform_configuration)); ASSERT_TRUE(isolate); auto root_isolate = isolate->get(); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); EXPECT_FALSE( client.mgr->IsRegisteredForTestingOnly(root_isolate->isolate())); // Post a task to the platform_thread that just waits, to delay execution of // the platform isolate until we're ready. fml::AutoResetWaitableEvent platform_thread_latch; fml::TaskRunner::RunNowOrPostTask( platform_thread, fml::MakeCopyable([&platform_thread_latch]() mutable { platform_thread_latch.Wait(); })); fml::AutoResetWaitableEvent ui_thread_latch; fml::TaskRunner::RunNowOrPostTask( ui_thread, fml::MakeCopyable([&]() mutable { ASSERT_TRUE( isolate->RunInIsolateScope([root_isolate, &platform_isolate]() { Dart_Handle lib = Dart_RootLibrary(); Dart_Handle entry_point = Dart_GetField( lib, tonic::ToDart("mainForPlatformIsolates")); char* error = nullptr; platform_isolate = root_isolate->CreatePlatformIsolate(entry_point, &error); EXPECT_FALSE(error); EXPECT_TRUE(platform_isolate); EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate()); return true; })); ui_thread_latch.Signal(); })); ui_thread_latch.Wait(); ASSERT_TRUE(platform_isolate); EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate)); // Allow the platform isolate to run. platform_thread_latch.Signal(); // Wait for a message from the platform isolate. message_latch.Wait(); // root isolate will be auto-shutdown } EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(platform_isolate)); } TEST_F(DartIsolateTest, PlatformIsolateEarlyShutdown) { FakePlatformConfigurationClient client; auto platform_configuration = std::make_unique<PlatformConfiguration>(&client); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); auto platform_thread = CreateNewThread(); auto ui_thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // label platform_thread, // platform ui_thread, // raster ui_thread, // ui ui_thread // io ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {}, GetDefaultKernelFilePath(), {}, nullptr, std::move(platform_configuration)); ASSERT_TRUE(isolate); auto root_isolate = isolate->get(); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(root_isolate->isolate())); fml::AutoResetWaitableEvent ui_thread_latch; Dart_Isolate platform_isolate = nullptr; fml::TaskRunner::RunNowOrPostTask( ui_thread, fml::MakeCopyable([&]() mutable { ASSERT_TRUE( isolate->RunInIsolateScope([root_isolate, &platform_isolate]() { Dart_Handle lib = Dart_RootLibrary(); Dart_Handle entry_point = Dart_GetField(lib, tonic::ToDart("emptyMain")); char* error = nullptr; platform_isolate = root_isolate->CreatePlatformIsolate(entry_point, &error); EXPECT_FALSE(error); EXPECT_TRUE(platform_isolate); EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate()); return true; })); ui_thread_latch.Signal(); })); ui_thread_latch.Wait(); ASSERT_TRUE(platform_isolate); EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate)); // Post a task to the platform thread to shut down the platform isolate. fml::AutoResetWaitableEvent platform_thread_latch; fml::TaskRunner::RunNowOrPostTask( platform_thread, fml::MakeCopyable([&platform_thread_latch, platform_isolate]() mutable { Dart_EnterIsolate(platform_isolate); Dart_ShutdownIsolate(); platform_thread_latch.Signal(); })); platform_thread_latch.Wait(); // The platform isolate should be shut down. EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(platform_isolate)); // root isolate will be auto-shutdown } TEST_F(DartIsolateTest, PlatformIsolateSendAndReceive) { fml::AutoResetWaitableEvent message_latch; AddNativeCallback( "PassMessage", CREATE_NATIVE_ENTRY(([&message_latch](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("Platform isolate received: Hello from root isolate!", message); message_latch.Signal(); }))); FakePlatformConfigurationClient client; auto platform_configuration = std::make_unique<PlatformConfiguration>(&client); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); auto platform_thread = CreateNewThread(); auto ui_thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // label platform_thread, // platform ui_thread, // raster ui_thread, // ui ui_thread // io ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {}, GetDefaultKernelFilePath(), {}, nullptr, std::move(platform_configuration)); ASSERT_TRUE(isolate); auto root_isolate = isolate->get(); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); fml::AutoResetWaitableEvent ui_thread_latch; Dart_Isolate platform_isolate = nullptr; fml::TaskRunner::RunNowOrPostTask( ui_thread, fml::MakeCopyable([&]() mutable { ASSERT_TRUE(isolate->RunInIsolateScope([root_isolate, &platform_isolate]() { Dart_Handle lib = Dart_RootLibrary(); Dart_Handle entry_point = Dart_Invoke( lib, tonic::ToDart("createEntryPointForPlatIsoSendAndRecvTest"), 0, nullptr); char* error = nullptr; platform_isolate = root_isolate->CreatePlatformIsolate(entry_point, &error); EXPECT_FALSE(error); return true; })); ui_thread_latch.Signal(); })); ui_thread_latch.Wait(); // Wait for a message from the platform isolate. message_latch.Wait(); // Post a task to the platform_thread that runs after the platform isolate's // entry point and all messages, and wait for it to run. fml::AutoResetWaitableEvent epilogue_latch; fml::TaskRunner::RunNowOrPostTask( platform_thread, fml::MakeCopyable([&epilogue_latch]() mutable { epilogue_latch.Signal(); })); epilogue_latch.Wait(); // root isolate will be auto-shutdown } TEST_F(DartIsolateTest, PlatformIsolateCreationAfterManagerShutdown) { AddNativeCallback("PassMessage", CREATE_NATIVE_ENTRY(( [](Dart_NativeArguments args) { FML_UNREACHABLE(); }))); FakePlatformConfigurationClient client; auto platform_configuration = std::make_unique<PlatformConfiguration>(&client); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); auto platform_thread = CreateNewThread(); auto ui_thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // label platform_thread, // platform ui_thread, // raster ui_thread, // ui ui_thread // io ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {}, GetDefaultKernelFilePath(), {}, nullptr, std::move(platform_configuration)); ASSERT_TRUE(isolate); auto root_isolate = isolate->get(); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); // Shut down the manager on the platform thread. fml::AutoResetWaitableEvent manager_shutdown_latch; fml::TaskRunner::RunNowOrPostTask( platform_thread, fml::MakeCopyable([&manager_shutdown_latch, &client]() mutable { client.mgr->ShutdownPlatformIsolates(); manager_shutdown_latch.Signal(); })); manager_shutdown_latch.Wait(); fml::AutoResetWaitableEvent ui_thread_latch; fml::TaskRunner::RunNowOrPostTask( ui_thread, fml::MakeCopyable([&]() mutable { ASSERT_TRUE(isolate->RunInIsolateScope([root_isolate]() { Dart_Handle lib = Dart_RootLibrary(); Dart_Handle entry_point = Dart_GetField(lib, tonic::ToDart("mainForPlatformIsolates")); char* error = nullptr; Dart_Isolate platform_isolate = root_isolate->CreatePlatformIsolate(entry_point, &error); // Failed to create a platform isolate, but we've still re-entered the // root isolate. EXPECT_FALSE(error); EXPECT_FALSE(platform_isolate); EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate()); return true; })); ui_thread_latch.Signal(); })); ui_thread_latch.Wait(); // root isolate will be auto-shutdown } TEST_F(DartIsolateTest, PlatformIsolateManagerShutdownBeforeMainRuns) { AddNativeCallback("PassMessage", CREATE_NATIVE_ENTRY(( [](Dart_NativeArguments args) { FML_UNREACHABLE(); }))); FakePlatformConfigurationClient client; auto platform_configuration = std::make_unique<PlatformConfiguration>(&client); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); auto platform_thread = CreateNewThread(); auto ui_thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // label platform_thread, // platform ui_thread, // raster ui_thread, // ui ui_thread // io ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {}, GetDefaultKernelFilePath(), {}, nullptr, std::move(platform_configuration)); ASSERT_TRUE(isolate); auto root_isolate = isolate->get(); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); Dart_Isolate platform_isolate = nullptr; // Post a task to the platform_thread that just waits, to delay execution of // the platform isolate until we're ready, and shutdown the manager just // before it runs. fml::AutoResetWaitableEvent platform_thread_latch; fml::TaskRunner::RunNowOrPostTask( platform_thread, fml::MakeCopyable([&platform_thread_latch, &client, &platform_isolate]() mutable { platform_thread_latch.Wait(); client.mgr->ShutdownPlatformIsolates(); EXPECT_TRUE(platform_isolate); EXPECT_FALSE(client.mgr->IsRegisteredForTestingOnly(platform_isolate)); })); fml::AutoResetWaitableEvent ui_thread_latch; fml::TaskRunner::RunNowOrPostTask( ui_thread, fml::MakeCopyable([&]() mutable { ASSERT_TRUE( isolate->RunInIsolateScope([root_isolate, &platform_isolate]() { Dart_Handle lib = Dart_RootLibrary(); Dart_Handle entry_point = Dart_GetField(lib, tonic::ToDart("mainForPlatformIsolates")); char* error = nullptr; platform_isolate = root_isolate->CreatePlatformIsolate(entry_point, &error); EXPECT_FALSE(error); EXPECT_TRUE(platform_isolate); EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate()); return true; })); ui_thread_latch.Signal(); })); ui_thread_latch.Wait(); ASSERT_TRUE(platform_isolate); EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate)); // Allow the platform isolate to run, but its main is never run. platform_thread_latch.Signal(); // Post a task to the platform_thread that runs after the platform isolate's // entry point, and wait for it to run. fml::AutoResetWaitableEvent epilogue_latch; fml::TaskRunner::RunNowOrPostTask( platform_thread, fml::MakeCopyable([&epilogue_latch]() mutable { epilogue_latch.Signal(); })); epilogue_latch.Wait(); // root isolate will be auto-shutdown } TEST_F(DartIsolateTest, PlatformIsolateMainThrowsError) { AddNativeCallback("PassMessage", CREATE_NATIVE_ENTRY(( [](Dart_NativeArguments args) { FML_UNREACHABLE(); }))); FakePlatformConfigurationClient client; auto platform_configuration = std::make_unique<PlatformConfiguration>(&client); ASSERT_FALSE(DartVMRef::IsInstanceRunning()); auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); ASSERT_TRUE(vm_ref); auto vm_data = vm_ref.GetVMData(); ASSERT_TRUE(vm_data); auto platform_thread = CreateNewThread(); auto ui_thread = CreateNewThread(); TaskRunners task_runners(GetCurrentTestName(), // label platform_thread, // platform ui_thread, // raster ui_thread, // ui ui_thread // io ); auto isolate = RunDartCodeInIsolate(vm_ref, settings, task_runners, "emptyMain", {}, GetDefaultKernelFilePath(), {}, nullptr, std::move(platform_configuration)); ASSERT_TRUE(isolate); auto root_isolate = isolate->get(); ASSERT_EQ(root_isolate->GetPhase(), DartIsolate::Phase::Running); Dart_Isolate platform_isolate = nullptr; fml::AutoResetWaitableEvent ui_thread_latch; fml::TaskRunner::RunNowOrPostTask( ui_thread, fml::MakeCopyable([&]() mutable { ASSERT_TRUE( isolate->RunInIsolateScope([root_isolate, &platform_isolate]() { Dart_Handle lib = Dart_RootLibrary(); Dart_Handle entry_point = Dart_GetField( lib, tonic::ToDart("mainForPlatformIsolatesThrowError")); char* error = nullptr; platform_isolate = root_isolate->CreatePlatformIsolate(entry_point, &error); EXPECT_FALSE(error); EXPECT_TRUE(platform_isolate); EXPECT_EQ(Dart_CurrentIsolate(), root_isolate->isolate()); return true; })); ui_thread_latch.Signal(); })); ui_thread_latch.Wait(); ASSERT_TRUE(platform_isolate); EXPECT_TRUE(client.mgr->IsRegisteredForTestingOnly(platform_isolate)); // Post a task to the platform_thread that runs after the platform isolate's // entry point, and wait for it to run. fml::AutoResetWaitableEvent epilogue_latch; fml::TaskRunner::RunNowOrPostTask( platform_thread, fml::MakeCopyable([&epilogue_latch]() mutable { epilogue_latch.Signal(); })); epilogue_latch.Wait(); // root isolate will be auto-shutdown } } // namespace testing } // namespace flutter // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/runtime/dart_isolate_unittests.cc/0
{ "file_path": "engine/runtime/dart_isolate_unittests.cc", "repo_id": "engine", "token_count": 21203 }
338