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.
import("../tools/impeller.gni")
config("impeller_canvas_recorder_config") {
defines = [ "IMPELLER_TRACE_CANVAS" ]
}
impeller_component("aiks") {
sources = [
"aiks_context.cc",
"aiks_context.h",
"canvas.cc",
"canvas.h",
"canvas_recorder.h",
"canvas_type.h",
"color_filter.cc",
"color_filter.h",
"color_source.cc",
"color_source.h",
"image.cc",
"image.h",
"image_filter.cc",
"image_filter.h",
"paint.cc",
"paint.h",
"paint_pass_delegate.cc",
"paint_pass_delegate.h",
"picture.cc",
"picture.h",
"picture_recorder.cc",
"picture_recorder.h",
"trace_serializer.h",
]
public_deps = [
"../base",
"../entity",
"../geometry",
]
deps = [ "//flutter/fml" ]
if (impeller_trace_canvas) {
sources += [ "trace_serializer.cc" ]
public_configs = [ ":impeller_canvas_recorder_config" ]
}
}
impeller_component("aiks_playground") {
testonly = true
sources = [
"aiks_playground.cc",
"aiks_playground.h",
"aiks_playground_inspector.cc",
"aiks_playground_inspector.h",
]
deps = [
":aiks",
"../playground:playground_test",
]
public_deps = [
"//flutter/impeller/typographer/backends/skia:typographer_skia_backend",
]
}
impeller_component("context_spy") {
testonly = true
sources = [
"testing/context_mock.h",
"testing/context_spy.cc",
"testing/context_spy.h",
]
deps = [
"//flutter/impeller/entity:entity_test_helpers",
"//flutter/impeller/renderer",
"//flutter/testing:testing_lib",
]
}
template("aiks_unittests_component") {
target_name = invoker.target_name
predefined_sources = [
"aiks_blur_unittests.cc",
"aiks_gradient_unittests.cc",
"aiks_path_unittests.cc",
"aiks_unittests.cc",
"aiks_unittests.h",
]
additional_sources = []
if (defined(invoker.sources)) {
additional_sources = invoker.sources
}
impeller_component(target_name) {
testonly = true
if (defined(invoker.defines)) {
defines = invoker.defines
} else {
defines = []
}
defines += [ "_USE_MATH_DEFINES" ]
sources = predefined_sources + additional_sources
deps = [
":aiks",
":aiks_playground",
":context_spy",
"//flutter/impeller/geometry:geometry_asserts",
"//flutter/impeller/golden_tests:golden_playground_test",
"//flutter/impeller/playground:playground_test",
"//flutter/impeller/scene",
"//flutter/impeller/typographer/backends/stb:typographer_stb_backend",
"//flutter/testing:testing_lib",
"//flutter/third_party/txt",
]
if (defined(invoker.public_configs)) {
public_configs = invoker.public_configs
}
}
}
aiks_unittests_component("aiks_unittests") {
sources = [
"canvas_recorder_unittests.cc",
"canvas_unittests.cc",
"trace_serializer_unittests.cc",
]
if (!impeller_trace_canvas) {
sources += [ "trace_serializer.cc" ]
public_configs = [ ":impeller_canvas_recorder_config" ]
}
}
aiks_unittests_component("aiks_unittests_golden") {
defines = [
"IMPELLER_GOLDEN_TESTS",
"IMPELLER_ENABLE_VALIDATION=1",
]
}
executable("canvas_benchmarks") {
testonly = true
sources = [ "canvas_benchmarks.cc" ]
deps = [
":aiks",
"//flutter/benchmarking",
]
}
| engine/impeller/aiks/BUILD.gn/0 | {
"file_path": "engine/impeller/aiks/BUILD.gn",
"repo_id": "engine",
"token_count": 1559
} | 212 |
// 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/testing/testing.h"
#include "impeller/aiks/canvas_recorder.h"
namespace impeller {
namespace testing {
namespace {
class Serializer {
public:
void Write(CanvasRecorderOp op) { last_op_ = op; }
void Write(const Paint& paint) {}
void Write(const std::optional<Rect> optional_rect) {}
void Write(const std::shared_ptr<ImageFilter>& image_filter) {}
void Write(size_t size) {}
void Write(const Matrix& matrix) {}
void Write(const Vector3& vec3) {}
void Write(const Vector2& vec2) {}
void Write(const Radians& vec2) {}
void Write(const Path& path) {}
void Write(const std::vector<Point>& points) {}
void Write(const PointStyle& point_style) {}
void Write(const std::shared_ptr<Image>& image) {}
void Write(const SamplerDescriptor& sampler) {}
void Write(const Entity::ClipOperation& clip_op) {}
void Write(const Picture& clip_op) {}
void Write(const std::shared_ptr<TextFrame>& text_frame) {}
void Write(const std::shared_ptr<VerticesGeometry>& vertices) {}
void Write(const BlendMode& blend_mode) {}
void Write(const std::vector<Matrix>& matrices) {}
void Write(const std::vector<Rect>& matrices) {}
void Write(const std::vector<Color>& matrices) {}
void Write(const SourceRectConstraint& src_rect_constraint) {}
void Write(const ContentBoundsPromise& promise) {}
CanvasRecorderOp last_op_;
};
} // namespace
TEST(CanvasRecorder, Save) {
CanvasRecorder<Serializer> recorder;
recorder.Save();
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kSave);
}
TEST(CanvasRecorder, SaveLayer) {
CanvasRecorder<Serializer> recorder;
Paint paint;
recorder.SaveLayer(paint);
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kSaveLayer);
}
TEST(CanvasRecorder, Restore) {
CanvasRecorder<Serializer> recorder;
recorder.Restore();
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kRestore);
}
TEST(CanvasRecorder, RestoreToCount) {
CanvasRecorder<Serializer> recorder;
recorder.Save();
recorder.RestoreToCount(0);
ASSERT_EQ(recorder.GetSerializer().last_op_,
CanvasRecorderOp::kRestoreToCount);
}
TEST(CanvasRecorder, ResetTransform) {
CanvasRecorder<Serializer> recorder;
recorder.ResetTransform();
ASSERT_EQ(recorder.GetSerializer().last_op_,
CanvasRecorderOp::kResetTransform);
}
TEST(CanvasRecorder, Transform) {
CanvasRecorder<Serializer> recorder;
recorder.Transform(Matrix());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kTransform);
}
TEST(CanvasRecorder, Concat) {
CanvasRecorder<Serializer> recorder;
recorder.Concat(Matrix());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kConcat);
}
TEST(CanvasRecorder, PreConcat) {
CanvasRecorder<Serializer> recorder;
recorder.PreConcat(Matrix());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kPreConcat);
}
TEST(CanvasRecorder, Translate) {
CanvasRecorder<Serializer> recorder;
recorder.Translate(Vector3());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kTranslate);
}
TEST(CanvasRecorder, Scale2) {
CanvasRecorder<Serializer> recorder;
recorder.Scale(Vector2());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kScale2);
}
TEST(CanvasRecorder, Scale3) {
CanvasRecorder<Serializer> recorder;
recorder.Scale(Vector3());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kScale3);
}
TEST(CanvasRecorder, Skew) {
CanvasRecorder<Serializer> recorder;
recorder.Skew(0, 0);
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kSkew);
}
TEST(CanvasRecorder, Rotate) {
CanvasRecorder<Serializer> recorder;
recorder.Rotate(Radians(0));
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kRotate);
}
TEST(CanvasRecorder, DrawPath) {
CanvasRecorder<Serializer> recorder;
recorder.DrawPath(Path(), Paint());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawPath);
}
TEST(CanvasRecorder, DrawPaint) {
CanvasRecorder<Serializer> recorder;
recorder.DrawPaint(Paint());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawPaint);
}
TEST(CanvasRecorder, DrawLine) {
CanvasRecorder<Serializer> recorder;
recorder.DrawLine(Point(), Point(), Paint());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawLine);
}
TEST(CanvasRecorder, DrawRect) {
CanvasRecorder<Serializer> recorder;
recorder.DrawRect(Rect(), Paint());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawRect);
}
TEST(CanvasRecorder, DrawOval) {
CanvasRecorder<Serializer> recorder;
recorder.DrawOval(Rect(), Paint());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawOval);
}
TEST(CanvasRecorder, DrawRRect) {
CanvasRecorder<Serializer> recorder;
recorder.DrawRRect(Rect(), {}, Paint());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawRRect);
}
TEST(CanvasRecorder, DrawCircle) {
CanvasRecorder<Serializer> recorder;
recorder.DrawCircle(Point(), 0, Paint());
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawCircle);
}
TEST(CanvasRecorder, DrawPoints) {
CanvasRecorder<Serializer> recorder;
recorder.DrawPoints(std::vector<Point>{}, 0, Paint(), PointStyle::kRound);
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawPoints);
}
TEST(CanvasRecorder, DrawImage) {
CanvasRecorder<Serializer> recorder;
recorder.DrawImage({}, {}, {}, {});
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawImage);
}
TEST(CanvasRecorder, DrawImageRect) {
CanvasRecorder<Serializer> recorder;
recorder.DrawImageRect({}, {}, {}, {}, {}, SourceRectConstraint::kFast);
ASSERT_EQ(recorder.GetSerializer().last_op_,
CanvasRecorderOp::kDrawImageRect);
}
TEST(CanvasRecorder, ClipPath) {
CanvasRecorder<Serializer> recorder;
recorder.ClipPath({});
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kClipPath);
}
TEST(CanvasRecorder, ClipRect) {
CanvasRecorder<Serializer> recorder;
recorder.ClipRect({});
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kClipRect);
}
TEST(CanvasRecorder, ClipOval) {
CanvasRecorder<Serializer> recorder;
recorder.ClipOval({});
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kClipOval);
}
TEST(CanvasRecorder, ClipRRect) {
CanvasRecorder<Serializer> recorder;
recorder.ClipRRect({}, {});
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kClipRRect);
}
TEST(CanvasRecorder, DrawTextFrame) {
CanvasRecorder<Serializer> recorder;
recorder.DrawTextFrame({}, {}, {});
ASSERT_EQ(recorder.GetSerializer().last_op_,
CanvasRecorderOp::kDrawTextFrame);
}
TEST(CanvasRecorder, DrawVertices) {
CanvasRecorder<Serializer> recorder;
auto geometry = std::shared_ptr<VerticesGeometry>(
new VerticesGeometry({}, {}, {}, {}, {}, {}));
recorder.DrawVertices(geometry, {}, {});
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawVertices);
}
TEST(CanvasRecorder, DrawAtlas) {
CanvasRecorder<Serializer> recorder;
recorder.DrawAtlas({}, {}, {}, {}, {}, {}, {}, {});
ASSERT_EQ(recorder.GetSerializer().last_op_, CanvasRecorderOp::kDrawAtlas);
}
} // namespace testing
} // namespace impeller
| engine/impeller/aiks/canvas_recorder_unittests.cc/0 | {
"file_path": "engine/impeller/aiks/canvas_recorder_unittests.cc",
"repo_id": "engine",
"token_count": 2738
} | 213 |
// 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_AIKS_PICTURE_H_
#define FLUTTER_IMPELLER_AIKS_PICTURE_H_
#include <deque>
#include <memory>
#include <optional>
#include "flutter/fml/macros.h"
#include "impeller/aiks/aiks_context.h"
#include "impeller/aiks/image.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/entity_pass.h"
namespace impeller {
struct Picture {
std::unique_ptr<EntityPass> pass;
std::optional<Snapshot> Snapshot(AiksContext& context);
std::shared_ptr<Image> ToImage(AiksContext& context, ISize size) const;
private:
std::shared_ptr<Texture> RenderToTexture(
AiksContext& context,
ISize size,
std::optional<const Matrix> translate = std::nullopt) const;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_PICTURE_H_
| engine/impeller/aiks/picture.h/0 | {
"file_path": "engine/impeller/aiks/picture.h",
"repo_id": "engine",
"token_count": 352
} | 214 |
// 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_BASE_COMPARABLE_H_
#define FLUTTER_IMPELLER_BASE_COMPARABLE_H_
#include <cstddef>
#include <functional>
#include <map>
#include <memory>
#include <type_traits>
namespace impeller {
struct UniqueID {
size_t id;
UniqueID();
constexpr bool operator==(const UniqueID& other) const {
return id == other.id;
}
};
class ComparableBase {};
template <class Type>
class Comparable : ComparableBase {
public:
virtual std::size_t GetHash() const = 0;
virtual bool IsEqual(const Type& other) const = 0;
};
template <
class ComparableType,
class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>
struct ComparableHash {
std::size_t operator()(const ComparableType& object) const {
return object.GetHash();
}
};
template <
class ComparableType,
class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>
struct ComparableEqual {
bool operator()(const ComparableType& lhs, const ComparableType& rhs) const {
return lhs.IsEqual(rhs);
}
};
template <
class ComparableType,
class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>
bool DeepComparePointer(const std::shared_ptr<ComparableType>& lhs,
const std::shared_ptr<ComparableType>& rhs) {
if (lhs == rhs) {
return true;
}
if (lhs && rhs) {
return lhs->IsEqual(*rhs);
}
return false;
}
template <
class Key,
class ComparableType,
class = std::enable_if_t<std::is_base_of_v<ComparableBase, ComparableType>>>
bool DeepCompareMap(const std::map<Key, std::shared_ptr<ComparableType>>& lhs,
const std::map<Key, std::shared_ptr<ComparableType>>& rhs) {
if (lhs.size() != rhs.size()) {
return false;
}
for (auto i = lhs.begin(), j = rhs.begin(); i != lhs.end(); i++, j++) {
if (i->first != j->first) {
return false;
}
if (!DeepComparePointer(i->second, j->second)) {
return false;
}
}
return true;
}
} // namespace impeller
namespace std {
template <>
struct hash<impeller::UniqueID> {
constexpr std::size_t operator()(const impeller::UniqueID& id) {
return id.id;
}
};
template <>
struct less<impeller::UniqueID> {
constexpr bool operator()(const impeller::UniqueID& lhs,
const impeller::UniqueID& rhs) const {
return lhs.id < rhs.id;
}
};
} // namespace std
#endif // FLUTTER_IMPELLER_BASE_COMPARABLE_H_
| engine/impeller/base/comparable.h/0 | {
"file_path": "engine/impeller/base/comparable.h",
"repo_id": "engine",
"token_count": 1031
} | 215 |
# 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/shell/version/version.gni")
impeller_component("utilities") {
# Current versions of libcxx have deprecated some of the UTF-16 string
# conversion APIs.
defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ]
sources = [
"utilities.cc",
"utilities.h",
]
public_deps = [
"../base",
"../geometry",
"../runtime_stage",
"//flutter/fml",
]
}
impeller_component("compiler_lib") {
include_dirs = [ "//flutter/third_party/vulkan-deps/spirv-cross/src/" ]
# Current versions of libcxx have deprecated some of the UTF-16 string
# conversion APIs.
defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ]
sources = [
"code_gen_template.h",
"compiler.cc",
"compiler.h",
"compiler_backend.cc",
"compiler_backend.h",
"constants.cc",
"constants.h",
"include_dir.h",
"includer.cc",
"includer.h",
"logger.h",
"reflector.cc",
"reflector.h",
"runtime_stage_data.cc",
"runtime_stage_data.h",
"shader_bundle.cc",
"shader_bundle.h",
"shader_bundle_data.cc",
"shader_bundle_data.h",
"source_options.cc",
"source_options.h",
"spirv_compiler.cc",
"spirv_compiler.h",
"spirv_sksl.cc",
"spirv_sksl.h",
"switches.cc",
"switches.h",
"types.cc",
"types.h",
"uniform_sorter.cc",
"uniform_sorter.h",
]
public_deps = [
":utilities",
"../base",
"../geometry",
"../runtime_stage",
"//flutter/fml",
"//flutter/impeller/shader_bundle:shader_bundle_flatbuffers",
# All third_party deps must be included by the global license script.
"//third_party/inja",
"//third_party/shaderc_flutter",
"//third_party/spirv_cross_flutter",
]
}
impeller_component("impellerc") {
target_type = "executable"
sources = [ "impellerc_main.cc" ]
deps = [
":compiler_lib",
"shader_lib",
]
metadata = {
entitlement_file_path = [ "impellerc" ]
}
}
group("compiler") {
deps = [ ":impellerc" ]
}
impeller_component("compiler_unittests") {
testonly = true
output_name = "impellerc_unittests"
sources = [
"compiler_test.cc",
"compiler_test.h",
"compiler_unittests.cc",
"shader_bundle_unittests.cc",
"switches_unittests.cc",
]
deps = [
":compiler_lib",
"//flutter/testing:testing_lib",
]
}
| engine/impeller/compiler/BUILD.gn/0 | {
"file_path": "engine/impeller/compiler/BUILD.gn",
"repo_id": "engine",
"token_count": 1102
} | 216 |
// 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_COMPILER_LOGGER_H_
#define FLUTTER_IMPELLER_COMPILER_LOGGER_H_
#include <sstream>
#include <string>
#include "flutter/fml/logging.h"
namespace impeller {
namespace compiler {
class AutoLogger {
public:
explicit AutoLogger(std::stringstream& logger) : logger_(logger) {}
~AutoLogger() {
logger_ << std::endl;
logger_.flush();
}
template <class T>
AutoLogger& operator<<(const T& object) {
logger_ << object;
return *this;
}
private:
std::stringstream& logger_;
AutoLogger(const AutoLogger&) = delete;
AutoLogger& operator=(const AutoLogger&) = delete;
};
#define COMPILER_ERROR(stream) \
::impeller::compiler::AutoLogger(stream) << GetSourcePrefix()
#define COMPILER_ERROR_NO_PREFIX(stream) \
::impeller::compiler::AutoLogger(stream)
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_LOGGER_H_
| engine/impeller/compiler/logger.h/0 | {
"file_path": "engine/impeller/compiler/logger.h",
"repo_id": "engine",
"token_count": 389
} | 217 |
// 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 COLOR_GLSL_
#define COLOR_GLSL_
#include <impeller/branching.glsl>
#include <impeller/types.glsl>
/// Convert a premultiplied color (a color which has its color components
/// multiplied with its alpha value) to an unpremultiplied color.
///
/// Returns (0, 0, 0, 0) if the alpha component is 0.
vec4 IPUnpremultiply(vec4 color) {
if (color.a == 0) {
return vec4(0);
}
return vec4(color.rgb / color.a, color.a);
}
/// Convert a premultiplied color (a color which has its color components
/// multiplied with its alpha value) to an unpremultiplied color.
///
/// Returns (0, 0, 0, 0) if the alpha component is 0.
f16vec4 IPHalfUnpremultiply(f16vec4 color) {
if (color.a == 0.0hf) {
return f16vec4(0.0hf);
}
return f16vec4(color.rgb / color.a, color.a);
}
/// Convert an unpremultiplied color (a color which has its color components
/// separated from its alpha value) to a premultiplied color.
///
/// Returns (0, 0, 0, 0) if the alpha component is 0.
vec4 IPPremultiply(vec4 color) {
return vec4(color.rgb * color.a, color.a);
}
/// Convert an unpremultiplied color (a color which has its color components
/// separated from its alpha value) to a premultiplied color.
///
/// Returns (0, 0, 0, 0) if the alpha component is 0.
f16vec4 IPHalfPremultiply(f16vec4 color) {
return f16vec4(color.rgb * color.a, color.a);
}
#endif
| engine/impeller/compiler/shader_lib/impeller/color.glsl/0 | {
"file_path": "engine/impeller/compiler/shader_lib/impeller/color.glsl",
"repo_id": "engine",
"token_count": 535
} | 218 |
// 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_COMPILER_SPIRV_COMPILER_H_
#define FLUTTER_IMPELLER_COMPILER_SPIRV_COMPILER_H_
#include <cstdint>
#include <vector>
#include "flutter/fml/mapping.h"
#include "impeller/compiler/includer.h"
#include "impeller/compiler/source_options.h"
#include "shaderc/shaderc.hpp"
namespace impeller {
namespace compiler {
struct SPIRVCompilerSourceProfile {
shaderc_profile profile = shaderc_profile_core;
uint32_t version = 460;
};
struct SPIRVCompilerTargetEnv {
shaderc_target_env env = shaderc_target_env::shaderc_target_env_vulkan;
shaderc_env_version version =
shaderc_env_version::shaderc_env_version_vulkan_1_1;
shaderc_spirv_version spirv_version =
shaderc_spirv_version::shaderc_spirv_version_1_3;
};
struct SPIRVCompilerOptions {
bool generate_debug_info = true;
//----------------------------------------------------------------------------
// Source Options.
//----------------------------------------------------------------------------
std::optional<shaderc_source_language> source_langauge;
std::optional<SPIRVCompilerSourceProfile> source_profile;
shaderc_optimization_level optimization_level =
shaderc_optimization_level::shaderc_optimization_level_performance;
//----------------------------------------------------------------------------
// Target Options.
//----------------------------------------------------------------------------
std::optional<SPIRVCompilerTargetEnv> target;
std::vector<std::string> macro_definitions;
std::shared_ptr<Includer> includer;
bool relaxed_vulkan_rules = false;
shaderc::CompileOptions BuildShadercOptions() const;
};
class SPIRVCompiler {
public:
SPIRVCompiler(const SourceOptions& options,
std::shared_ptr<const fml::Mapping> sources);
~SPIRVCompiler();
std::shared_ptr<fml::Mapping> CompileToSPV(
std::stringstream& error_stream,
const shaderc::CompileOptions& spirv_options) const;
private:
SourceOptions options_;
const std::shared_ptr<const fml::Mapping> sources_;
std::string GetSourcePrefix() const;
SPIRVCompiler(const SPIRVCompiler&) = delete;
SPIRVCompiler& operator=(const SPIRVCompiler&) = delete;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_SPIRV_COMPILER_H_
| engine/impeller/compiler/spirv_compiler.h/0 | {
"file_path": "engine/impeller/compiler/spirv_compiler.h",
"repo_id": "engine",
"token_count": 817
} | 219 |
// 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/buffer_view.h"
namespace impeller {
//
} // namespace impeller
| engine/impeller/core/buffer_view.cc/0 | {
"file_path": "engine/impeller/core/buffer_view.cc",
"repo_id": "engine",
"token_count": 76
} | 220 |
# 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")
impeller_component("skia_conversions") {
sources = [
"skia_conversions.cc",
"skia_conversions.h",
]
public_deps = [
"../core",
"../geometry",
"//flutter/display_list",
"//flutter/fml",
"//flutter/skia",
"//flutter/skia/modules/skparagraph",
]
}
impeller_component("display_list") {
sources = [
"dl_dispatcher.cc",
"dl_dispatcher.h",
"dl_image_impeller.cc",
"dl_image_impeller.h",
"dl_vertices_geometry.cc",
"dl_vertices_geometry.h",
"nine_patch_converter.cc",
"nine_patch_converter.h",
]
public_deps = [
":skia_conversions",
"../aiks",
"//flutter/display_list",
"//flutter/fml",
"//flutter/impeller/typographer/backends/skia:typographer_skia_backend",
"//flutter/skia",
]
if (!defined(defines)) {
defines = []
}
if (impeller_enable_3d) {
defines += [ "IMPELLER_ENABLE_3D" ]
}
}
impeller_component("display_list_unittests") {
testonly = true
sources = [
"dl_playground.cc",
"dl_playground.h",
"dl_unittests.cc",
]
deps = [
":display_list",
"../playground:playground_test",
"//flutter/impeller/scene",
"//flutter/impeller/typographer/backends/stb:typographer_stb_backend",
"//flutter/third_party/txt",
]
if (!defined(defines)) {
defines = []
}
if (impeller_enable_3d) {
defines += [ "IMPELLER_ENABLE_3D" ]
}
}
impeller_component("skia_conversions_unittests") {
testonly = true
sources = [ "skia_conversions_unittests.cc" ]
deps = [
":skia_conversions",
"//flutter/testing:testing_lib",
]
}
| engine/impeller/display_list/BUILD.gn/0 | {
"file_path": "engine/impeller/display_list/BUILD.gn",
"repo_id": "engine",
"token_count": 792
} | 221 |
# Android CPU Profiling
Android devices have different performance characteristics than iOS devices, CPU traces frequently reveal surprising performance issues, such as https://github.com/flutter/engine/pull/48303 . This document describes the steps to capture an equivalent [flame graph](https://cacm.acm.org/magazines/2016/6/202665-the-flame-graph/abstract) on your local Android device.
1. Build Local Engine with Symbols
Add the `--no-stripped` flag to the gn config when building the android engine.
Example config:
`gn --no-lto --no-goma --runtime-mode=profile --android --android-cpu=arm64 --no-stripped`
2. Configure Gradle to not remove strip sources
In the flutter project file `android/app/build.gradle` , add the following line under the `android` block:
```
packagingOptions{
doNotStrip "**/*.so"
}
```
3. `flutter run` the app with the local engine flags (`--local-engine`, `--local-engine-host`, `--local-engine-src-path`).
4. Open Android Studio.
You can create a new blank project if you don't have one already. You do not need to open the application project nor do you need to run the App through Android Studio. In fact, it's much easier if you do not do those things.
5. Open the Profiler Tab
Note: this may be in a different location depending on the exact version of Android Studio that you have installed.

6. Start a New Session.
Click the plus button to start a new session, then look for the attached devices, then finally the name of the application to profile. It usually takes a few seconds for the drop downs to populate. The IDE will warn about the build not being a release build, but this doesn't impact the C++ engine so ignore it.

7. Take a CPU Profile
Click on the CPU section of the chart highlighted below. This will open a side panel that allows you to select the type of profile. Choose "Callstack Sample Recording" and then hit "Record" to start the profile and "Stop" to end the profile

8. Analyze Raster performance
Samples will be collected from all threads, but for analyzing the engine performance we really only care about the raster thread. Note that if you are benchmarking an application that uses platform views, _and_ that platform view uses Hybrid Composition, then the raster thread will be merged with the platform thread.
Select the raster thread by clicking on that area and then choose flame graph (or any of the other options). The flame graph can be navigated using `WASD` and the chart area expanded to make inspection easier.

| engine/impeller/docs/android_cpu_profile.md/0 | {
"file_path": "engine/impeller/docs/android_cpu_profile.md",
"repo_id": "engine",
"token_count": 726
} | 222 |
# Impeller's Coordinate System
**TL;DR, Impeller uses the Metal coordinate system.**
This document describes the Impeller coordinate system. This is the coordinate
system assumed by all Impeller sub-subsystems and users of Impeller itself.
All sub-systems that deal with interacting with backend client rendering APIs
(like OpenGL, Metal, Direct3D, Dawn, etc..) must reconcile with Impellers
coordinate system.
While the readers familiarity with a particular coordinate system might make
them think otherwise, there is no right or wrong coordinate system. However,
having a consist notion of a coordinate system is essential. Since the Metal
backend was the first Impeller backend, the Metal coordinate system was picked
as the Impeller coordinate system with very little consideration of
alternatives.
The following table describes the Impeller coordinate system along with how it
differs with that of popular client rendering APIs and backends.
| API | Normalized Device Coordinate | Viewport / Framebuffer Coordinate | Texture Coordinate |
|---------------|-------------------------------------------------------|---------------------------------------|--------------------------------------|
| **Impeller** | `(-1,-1)` Bottom-Left, `(+1,+1)` Top-Right, `+Y` up. | `(0,0)` Top-Left Origin, `+Y` down. | `(0,0)` Top-Left Origin, `+Y` down. |
| **Metal** | `(-1,-1)` Bottom-Left, `(+1,+1)` Top-Right, `+Y` up. | `(0,0)` Top-Left Origin, `+Y` down. | `(0,0)` Top-Left Origin, `+Y` down. |
| **OpenGL** | `(-1,-1)` Bottom-Left, `(+1,+1)` Top-Right, `+Y` up. | `(0,0)` Bottom-Left Origin, `+Y` up. | `(0,0)` Bottom-Left Origin, `+Y` up. |
| **OpenGL ES** | `(-1,-1)` Bottom-Left, `(+1,+1)` Top-Right, `+Y` up. | `(0,0)` Bottom-Left Origin, `+Y` up. | `(0,0)` Bottom-Left Origin, `+Y` up. |
| **WebGL** | `(-1,-1)` Bottom-Left, `(+1,+1)` Top-Right, `+Y` up. | `(0,0)` Bottom-Left Origin, `+Y` up. | `(0,0)` Bottom-Left Origin, `+Y` up. |
| **Direct 3D** | `(-1,-1)` Bottom-Left, `(+1,+1)` Top-Right, `+Y` up. | `(0,0)` Top-Left Origin, `+Y` down. | `(0,0)` Top-Left Origin, `+Y` down. |
| **Vulkan** | `(-1,-1)` Top-Left, `(+1,+1)` Bottom-Right, `+Y` down.| `(0,0)` Top-Left Origin, `+Y` down. | `(0,0)` Top-Left Origin, `+Y` down. |
| **WebGPU** | `(-1,-1)` Bottom-Left, `(+1,+1)` Top-Right, `+Y` up. | `(0,0)` Top-Left Origin, `+Y` down. | `(0,0)` Top-Left Origin, `+Y` down. |
| engine/impeller/docs/coordinate_system.md/0 | {
"file_path": "engine/impeller/docs/coordinate_system.md",
"repo_id": "engine",
"token_count": 961
} | 223 |
// 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/checkerboard_contents.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_buffer_builder.h"
namespace impeller {
CheckerboardContents::CheckerboardContents() = default;
CheckerboardContents::~CheckerboardContents() = default;
bool CheckerboardContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
auto& host_buffer = renderer.GetTransientsBuffer();
using VS = CheckerboardPipeline::VertexShader;
using FS = CheckerboardPipeline::FragmentShader;
auto options = OptionsFromPass(pass);
options.blend_mode = BlendMode::kSourceOver;
options.stencil_mode = ContentContextOptions::StencilMode::kIgnore;
options.primitive_type = PrimitiveType::kTriangleStrip;
VertexBufferBuilder<typename VS::PerVertexData> vtx_builder;
vtx_builder.AddVertices({
{Point(-1, -1)},
{Point(1, -1)},
{Point(-1, 1)},
{Point(1, 1)},
});
pass.SetCommandLabel("Checkerboard");
pass.SetPipeline(renderer.GetCheckerboardPipeline(options));
pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer));
FS::FragInfo frag_info;
frag_info.color = color_;
frag_info.square_size = square_size_;
FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info));
return pass.Draw().ok();
}
std::optional<Rect> CheckerboardContents::GetCoverage(
const Entity& entity) const {
return std::nullopt;
}
void CheckerboardContents::SetColor(Color color) {
color_ = color;
}
void CheckerboardContents::SetSquareSize(Scalar square_size) {
square_size_ = square_size;
}
} // namespace impeller
| engine/impeller/entity/contents/checkerboard_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/checkerboard_contents.cc",
"repo_id": "engine",
"token_count": 714
} | 224 |
// 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/border_mask_blur_filter_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/anonymous_contents.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_buffer_builder.h"
namespace impeller {
BorderMaskBlurFilterContents::BorderMaskBlurFilterContents() = default;
BorderMaskBlurFilterContents::~BorderMaskBlurFilterContents() = default;
void BorderMaskBlurFilterContents::SetSigma(Sigma sigma_x, Sigma sigma_y) {
sigma_x_ = sigma_x;
sigma_y_ = sigma_y;
}
void BorderMaskBlurFilterContents::SetBlurStyle(BlurStyle blur_style) {
blur_style_ = blur_style;
switch (blur_style) {
case FilterContents::BlurStyle::kNormal:
src_color_factor_ = false;
inner_blur_factor_ = true;
outer_blur_factor_ = true;
break;
case FilterContents::BlurStyle::kSolid:
src_color_factor_ = true;
inner_blur_factor_ = false;
outer_blur_factor_ = true;
break;
case FilterContents::BlurStyle::kOuter:
src_color_factor_ = false;
inner_blur_factor_ = false;
outer_blur_factor_ = true;
break;
case FilterContents::BlurStyle::kInner:
src_color_factor_ = false;
inner_blur_factor_ = true;
outer_blur_factor_ = false;
break;
}
}
std::optional<Entity> BorderMaskBlurFilterContents::RenderFilter(
const FilterInput::Vector& inputs,
const ContentContext& renderer,
const Entity& entity,
const Matrix& effect_transform,
const Rect& coverage,
const std::optional<Rect>& coverage_hint) const {
using VS = BorderMaskBlurPipeline::VertexShader;
using FS = BorderMaskBlurPipeline::FragmentShader;
//----------------------------------------------------------------------------
/// Handle inputs.
///
if (inputs.empty()) {
return std::nullopt;
}
auto input_snapshot =
inputs[0]->GetSnapshot("BorderMaskBlur", renderer, entity);
if (!input_snapshot.has_value()) {
return std::nullopt;
}
auto maybe_input_uvs = input_snapshot->GetCoverageUVs(coverage);
if (!maybe_input_uvs.has_value()) {
return std::nullopt;
}
auto input_uvs = maybe_input_uvs.value();
//----------------------------------------------------------------------------
/// Create AnonymousContents for rendering.
///
auto sigma = effect_transform * Vector2(sigma_x_.sigma, sigma_y_.sigma);
RenderProc render_proc = [coverage, input_snapshot, input_uvs = input_uvs,
src_color_factor = src_color_factor_,
inner_blur_factor = inner_blur_factor_,
outer_blur_factor = outer_blur_factor_, sigma](
const ContentContext& renderer,
const Entity& entity, RenderPass& pass) -> bool {
auto& host_buffer = renderer.GetTransientsBuffer();
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
auto origin = coverage.GetOrigin();
auto size = coverage.GetSize();
vtx_builder.AddVertices({
{origin, input_uvs[0]},
{{origin.x + size.width, origin.y}, input_uvs[1]},
{{origin.x, origin.y + size.height}, input_uvs[2]},
{{origin.x + size.width, origin.y + size.height}, input_uvs[3]},
});
auto options = OptionsFromPassAndEntity(pass, entity);
options.primitive_type = PrimitiveType::kTriangleStrip;
VS::FrameInfo frame_info;
frame_info.depth = entity.GetShaderClipDepth();
frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform();
frame_info.texture_sampler_y_coord_scale =
input_snapshot->texture->GetYCoordScale();
FS::FragInfo frag_info;
frag_info.sigma_uv = sigma.Abs() / input_snapshot->texture->GetSize();
frag_info.src_factor = src_color_factor;
frag_info.inner_blur_factor = inner_blur_factor;
frag_info.outer_blur_factor = outer_blur_factor;
pass.SetCommandLabel("Border Mask Blur Filter");
pass.SetPipeline(renderer.GetBorderMaskBlurPipeline(options));
pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer));
pass.SetStencilReference(entity.GetClipDepth());
FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info));
VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info));
const std::unique_ptr<const Sampler>& sampler =
renderer.GetContext()->GetSamplerLibrary()->GetSampler({});
FS::BindTextureSampler(pass, input_snapshot->texture, sampler);
return pass.Draw().ok();
};
CoverageProc coverage_proc =
[coverage](const Entity& entity) -> std::optional<Rect> {
return coverage.TransformBounds(entity.GetTransform());
};
auto contents = AnonymousContents::Make(render_proc, coverage_proc);
Entity sub_entity;
sub_entity.SetContents(std::move(contents));
sub_entity.SetClipDepth(entity.GetClipDepth());
sub_entity.SetBlendMode(entity.GetBlendMode());
return sub_entity;
}
std::optional<Rect> BorderMaskBlurFilterContents::GetFilterCoverage(
const FilterInput::Vector& inputs,
const Entity& entity,
const Matrix& effect_transform) const {
if (inputs.empty()) {
return std::nullopt;
}
auto coverage = inputs[0]->GetCoverage(entity);
if (!coverage.has_value()) {
return std::nullopt;
}
auto transform = inputs[0]->GetTransform(entity) * effect_transform;
auto transformed_blur_vector =
transform.TransformDirection(Vector2(Radius{sigma_x_}.radius, 0)).Abs() +
transform.TransformDirection(Vector2(0, Radius{sigma_y_}.radius)).Abs();
return coverage->Expand(transformed_blur_vector);
}
std::optional<Rect> BorderMaskBlurFilterContents::GetFilterSourceCoverage(
const Matrix& effect_transform,
const Rect& output_limit) const {
auto transformed_blur_vector =
effect_transform.TransformDirection(Vector2(Radius{sigma_x_}.radius, 0))
.Abs() +
effect_transform.TransformDirection(Vector2(0, Radius{sigma_y_}.radius))
.Abs();
return output_limit.Expand(transformed_blur_vector);
}
} // namespace impeller
| engine/impeller/entity/contents/filters/border_mask_blur_filter_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/border_mask_blur_filter_contents.cc",
"repo_id": "engine",
"token_count": 2357
} | 225 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_INPUT_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_INPUT_H_
#include <memory>
#include <optional>
#include <variant>
#include <vector>
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/entity.h"
#include "impeller/geometry/rect.h"
namespace impeller {
class ContentContext;
class FilterContents;
/// `FilterInput` is a lazy/single eval `Snapshot` which may be shared across
/// filter parameters and used to evaluate input coverage.
///
/// A `FilterInput` can be re-used for any filter inputs across an entity's
/// filter graph without repeating subpasses unnecessarily.
///
/// Filters may decide to not evaluate inputs in situations where they won't
/// contribute to the filter's output texture.
class FilterInput {
public:
using Ref = std::shared_ptr<FilterInput>;
using Vector = std::vector<FilterInput::Ref>;
using Variant = std::variant<std::shared_ptr<FilterContents>,
std::shared_ptr<Contents>,
std::shared_ptr<Texture>,
Rect>;
virtual ~FilterInput();
static FilterInput::Ref Make(Variant input, bool msaa_enabled = true);
static FilterInput::Ref Make(std::shared_ptr<Texture> input,
Matrix local_transform);
static FilterInput::Vector Make(std::initializer_list<Variant> inputs);
virtual Variant GetInput() const = 0;
virtual std::optional<Snapshot> GetSnapshot(
const std::string& label,
const ContentContext& renderer,
const Entity& entity,
std::optional<Rect> coverage_limit = std::nullopt,
int32_t mip_count = 1) const = 0;
std::optional<Rect> GetLocalCoverage(const Entity& entity) const;
virtual std::optional<Rect> GetCoverage(const Entity& entity) const = 0;
virtual std::optional<Rect> GetSourceCoverage(const Matrix& effect_transform,
const Rect& output_limit) const;
/// @brief Get the local transform of this filter input. This transform is
/// relative to the `Entity` transform space.
virtual Matrix GetLocalTransform(const Entity& entity) const;
/// @brief Get the transform of this `FilterInput`. This is equivalent to
/// calling `entity.GetTransform() * GetLocalTransform()`.
virtual Matrix GetTransform(const Entity& entity) const;
/// @see `Contents::PopulateGlyphAtlas`
virtual void PopulateGlyphAtlas(
const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas,
Scalar scale);
/// @see `FilterContents::HasBasisTransforms`
virtual bool IsTranslationOnly() const;
/// @brief Returns `true` unless this input is a `FilterInput`, which may
/// take other inputs.
virtual bool IsLeaf() const;
/// @brief Replaces the inputs of all leaf `FilterContents` with a new set
/// of `inputs`.
/// @see `FilterInput::IsLeaf`
virtual void SetLeafInputs(const FilterInput::Vector& inputs);
/// @brief Sets the effect transform of filter inputs.
virtual void SetEffectTransform(const Matrix& matrix);
/// @brief Turns on subpass mode for filter inputs.
virtual void SetRenderingMode(Entity::RenderingMode rendering_mode);
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_INPUT_H_
| engine/impeller/entity/contents/filters/inputs/filter_input.h/0 | {
"file_path": "engine/impeller/entity/contents/filters/inputs/filter_input.h",
"repo_id": "engine",
"token_count": 1234
} | 226 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/contents/filters/yuv_to_rgb_filter_contents.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/anonymous_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/geometry/matrix.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_buffer_builder.h"
namespace impeller {
// clang-format off
constexpr Matrix kMatrixBT601LimitedRange = {
1.164, 1.164, 1.164, 0.0,
0.0, -0.392, 2.017, 0.0,
1.596, -0.813, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0
};
constexpr Matrix kMatrixBT601FullRange = {
1.0, 1.0, 1.0, 0.0,
0.0, -0.344, 1.772, 0.0,
1.402, -0.714, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0
};
// clang-format on
YUVToRGBFilterContents::YUVToRGBFilterContents() = default;
YUVToRGBFilterContents::~YUVToRGBFilterContents() = default;
void YUVToRGBFilterContents::SetYUVColorSpace(YUVColorSpace yuv_color_space) {
yuv_color_space_ = yuv_color_space;
}
std::optional<Entity> YUVToRGBFilterContents::RenderFilter(
const FilterInput::Vector& inputs,
const ContentContext& renderer,
const Entity& entity,
const Matrix& effect_transform,
const Rect& coverage,
const std::optional<Rect>& coverage_hint) const {
if (inputs.size() < 2) {
return std::nullopt;
}
using VS = YUVToRGBFilterPipeline::VertexShader;
using FS = YUVToRGBFilterPipeline::FragmentShader;
auto y_input_snapshot =
inputs[0]->GetSnapshot("YUVToRGB(Y)", renderer, entity);
auto uv_input_snapshot =
inputs[1]->GetSnapshot("YUVToRGB(UV)", renderer, entity);
if (!y_input_snapshot.has_value() || !uv_input_snapshot.has_value()) {
return std::nullopt;
}
if (y_input_snapshot->texture->GetTextureDescriptor().format !=
PixelFormat::kR8UNormInt ||
uv_input_snapshot->texture->GetTextureDescriptor().format !=
PixelFormat::kR8G8UNormInt) {
return std::nullopt;
}
//----------------------------------------------------------------------------
/// Create AnonymousContents for rendering.
///
RenderProc render_proc = [y_input_snapshot, uv_input_snapshot,
yuv_color_space = yuv_color_space_](
const ContentContext& renderer,
const Entity& entity, RenderPass& pass) -> bool {
pass.SetCommandLabel("YUV to RGB Filter");
pass.SetStencilReference(entity.GetClipDepth());
auto options = OptionsFromPassAndEntity(pass, entity);
options.primitive_type = PrimitiveType::kTriangleStrip;
pass.SetPipeline(renderer.GetYUVToRGBFilterPipeline(options));
auto size = y_input_snapshot->texture->GetSize();
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
vtx_builder.AddVertices({
{Point(0, 0)},
{Point(1, 0)},
{Point(0, 1)},
{Point(1, 1)},
});
auto& host_buffer = renderer.GetTransientsBuffer();
pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer));
VS::FrameInfo frame_info;
frame_info.depth = entity.GetShaderClipDepth();
frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform() *
y_input_snapshot->transform *
Matrix::MakeScale(Vector2(size));
frame_info.texture_sampler_y_coord_scale =
y_input_snapshot->texture->GetYCoordScale();
FS::FragInfo frag_info;
frag_info.yuv_color_space = static_cast<Scalar>(yuv_color_space);
switch (yuv_color_space) {
case YUVColorSpace::kBT601LimitedRange:
frag_info.matrix = kMatrixBT601LimitedRange;
break;
case YUVColorSpace::kBT601FullRange:
frag_info.matrix = kMatrixBT601FullRange;
break;
}
const std::unique_ptr<const Sampler>& sampler =
renderer.GetContext()->GetSamplerLibrary()->GetSampler({});
FS::BindYTexture(pass, y_input_snapshot->texture, sampler);
FS::BindUvTexture(pass, uv_input_snapshot->texture, sampler);
FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info));
VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info));
return pass.Draw().ok();
};
CoverageProc coverage_proc =
[coverage](const Entity& entity) -> std::optional<Rect> {
return coverage.TransformBounds(entity.GetTransform());
};
auto contents = AnonymousContents::Make(render_proc, coverage_proc);
Entity sub_entity;
sub_entity.SetContents(std::move(contents));
sub_entity.SetClipDepth(entity.GetClipDepth());
sub_entity.SetBlendMode(entity.GetBlendMode());
return sub_entity;
}
std::optional<Rect> YUVToRGBFilterContents::GetFilterSourceCoverage(
const Matrix& effect_transform,
const Rect& output_limit) const {
return output_limit;
}
} // namespace impeller
| engine/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.cc",
"repo_id": "engine",
"token_count": 1994
} | 227 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_COLOR_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_COLOR_CONTENTS_H_
#include <memory>
#include "impeller/entity/contents/color_source_contents.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/path.h"
namespace impeller {
class Path;
class HostBuffer;
struct VertexBuffer;
class SolidColorContents final : public ColorSourceContents {
public:
SolidColorContents();
~SolidColorContents() override;
static std::unique_ptr<SolidColorContents> Make(const Path& path,
Color color);
void SetColor(Color color);
Color GetColor() const;
// |ColorSourceContents|
bool IsSolidColor() const override;
// |Contents|
bool IsOpaque() const override;
// |Contents|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
std::optional<Color> AsBackgroundColor(const Entity& entity,
ISize target_size) const override;
// |Contents|
[[nodiscard]] bool ApplyColorFilter(
const ColorFilterProc& color_filter_proc) override;
private:
Color color_;
SolidColorContents(const SolidColorContents&) = delete;
SolidColorContents& operator=(const SolidColorContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_COLOR_CONTENTS_H_
| engine/impeller/entity/contents/solid_color_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/solid_color_contents.h",
"repo_id": "engine",
"token_count": 633
} | 228 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vertices_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/entity/geometry/geometry.h"
#include "impeller/entity/geometry/vertices_geometry.h"
#include "impeller/entity/position_color.vert.h"
#include "impeller/entity/vertices.frag.h"
#include "impeller/geometry/color.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
VerticesContents::VerticesContents() = default;
VerticesContents::~VerticesContents() = default;
std::optional<Rect> VerticesContents::GetCoverage(const Entity& entity) const {
return geometry_->GetCoverage(entity.GetTransform());
};
void VerticesContents::SetGeometry(std::shared_ptr<VerticesGeometry> geometry) {
geometry_ = std::move(geometry);
}
void VerticesContents::SetSourceContents(std::shared_ptr<Contents> contents) {
src_contents_ = std::move(contents);
}
std::shared_ptr<VerticesGeometry> VerticesContents::GetGeometry() const {
return geometry_;
}
void VerticesContents::SetAlpha(Scalar alpha) {
alpha_ = alpha;
}
void VerticesContents::SetBlendMode(BlendMode blend_mode) {
blend_mode_ = blend_mode;
}
const std::shared_ptr<Contents>& VerticesContents::GetSourceContents() const {
return src_contents_;
}
bool VerticesContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (blend_mode_ == BlendMode::kClear) {
return true;
}
std::shared_ptr<Contents> src_contents = src_contents_;
src_contents->SetCoverageHint(GetCoverageHint());
if (geometry_->HasTextureCoordinates()) {
auto contents = std::make_shared<VerticesUVContents>(*this);
contents->SetCoverageHint(GetCoverageHint());
if (!geometry_->HasVertexColors()) {
contents->SetAlpha(alpha_);
return contents->Render(renderer, entity, pass);
}
src_contents = contents;
}
auto dst_contents = std::make_shared<VerticesColorContents>(*this);
dst_contents->SetCoverageHint(GetCoverageHint());
std::shared_ptr<Contents> contents;
if (blend_mode_ == BlendMode::kDestination) {
dst_contents->SetAlpha(alpha_);
contents = dst_contents;
} else {
auto color_filter_contents = ColorFilterContents::MakeBlend(
blend_mode_, {FilterInput::Make(dst_contents, false),
FilterInput::Make(src_contents, false)});
color_filter_contents->SetAlpha(alpha_);
color_filter_contents->SetCoverageHint(GetCoverageHint());
contents = color_filter_contents;
}
FML_DCHECK(contents->GetCoverageHint() == GetCoverageHint());
return contents->Render(renderer, entity, pass);
}
//------------------------------------------------------
// VerticesUVContents
VerticesUVContents::VerticesUVContents(const VerticesContents& parent)
: parent_(parent) {}
VerticesUVContents::~VerticesUVContents() {}
std::optional<Rect> VerticesUVContents::GetCoverage(
const Entity& entity) const {
return parent_.GetCoverage(entity);
}
void VerticesUVContents::SetAlpha(Scalar alpha) {
alpha_ = alpha;
}
bool VerticesUVContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = TexturePipeline::VertexShader;
using FS = TexturePipeline::FragmentShader;
auto src_contents = parent_.GetSourceContents();
auto snapshot =
src_contents->RenderToSnapshot(renderer, // renderer
entity, // entity
GetCoverageHint(), // coverage_limit
std::nullopt, // sampler_descriptor
true, // msaa_enabled
/*mip_count=*/1,
"VerticesUVContents Snapshot"); // label
if (!snapshot.has_value()) {
return false;
}
pass.SetCommandLabel("VerticesUV");
auto& host_buffer = renderer.GetTransientsBuffer();
const std::shared_ptr<Geometry>& geometry = parent_.GetGeometry();
auto coverage = src_contents->GetCoverage(Entity{});
if (!coverage.has_value()) {
return false;
}
auto geometry_result = geometry->GetPositionUVBuffer(
coverage.value(), Matrix(), renderer, entity, pass);
auto opts = OptionsFromPassAndEntity(pass, entity);
opts.primitive_type = geometry_result.type;
pass.SetPipeline(renderer.GetTexturePipeline(opts));
pass.SetStencilReference(entity.GetClipDepth());
pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer));
VS::FrameInfo frame_info;
frame_info.depth = entity.GetShaderClipDepth();
frame_info.mvp = geometry_result.transform;
frame_info.texture_sampler_y_coord_scale =
snapshot->texture->GetYCoordScale();
frame_info.alpha = alpha_ * snapshot->opacity;
VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info));
FS::BindTextureSampler(pass, snapshot->texture,
renderer.GetContext()->GetSamplerLibrary()->GetSampler(
snapshot->sampler_descriptor));
return pass.Draw().ok();
}
//------------------------------------------------------
// VerticesColorContents
VerticesColorContents::VerticesColorContents(const VerticesContents& parent)
: parent_(parent) {}
VerticesColorContents::~VerticesColorContents() {}
std::optional<Rect> VerticesColorContents::GetCoverage(
const Entity& entity) const {
return parent_.GetCoverage(entity);
}
void VerticesColorContents::SetAlpha(Scalar alpha) {
alpha_ = alpha;
}
bool VerticesColorContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = GeometryColorPipeline::VertexShader;
using FS = GeometryColorPipeline::FragmentShader;
pass.SetCommandLabel("VerticesColors");
auto& host_buffer = renderer.GetTransientsBuffer();
const std::shared_ptr<VerticesGeometry>& geometry = parent_.GetGeometry();
auto geometry_result =
geometry->GetPositionColorBuffer(renderer, entity, pass);
auto opts = OptionsFromPassAndEntity(pass, entity);
opts.primitive_type = geometry_result.type;
pass.SetPipeline(renderer.GetGeometryColorPipeline(opts));
pass.SetStencilReference(entity.GetClipDepth());
pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer));
VS::FrameInfo frame_info;
frame_info.depth = entity.GetShaderClipDepth();
frame_info.mvp = geometry_result.transform;
VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info));
FS::FragInfo frag_info;
frag_info.alpha = alpha_;
FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info));
return pass.Draw().ok();
}
} // namespace impeller
| engine/impeller/entity/contents/vertices_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/vertices_contents.cc",
"repo_id": "engine",
"token_count": 2654
} | 229 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_CIRCLE_GEOMETRY_H_
#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_CIRCLE_GEOMETRY_H_
#include "impeller/entity/geometry/geometry.h"
namespace impeller {
// Geometry class that can generate vertices (with or without texture
// coordinates) for either filled or stroked circles
class CircleGeometry final : public Geometry {
public:
explicit CircleGeometry(const Point& center, Scalar radius);
explicit CircleGeometry(const Point& center,
Scalar radius,
Scalar stroke_width);
~CircleGeometry() = default;
// |Geometry|
bool CoversArea(const Matrix& transform, const Rect& rect) const override;
// |Geometry|
bool IsAxisAlignedRect() const override;
private:
// |Geometry|
GeometryResult GetPositionBuffer(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;
// |Geometry|
GeometryResult GetPositionUVBuffer(Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
Point center_;
Scalar radius_;
Scalar stroke_width_;
CircleGeometry(const CircleGeometry&) = delete;
CircleGeometry& operator=(const CircleGeometry&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_CIRCLE_GEOMETRY_H_
| engine/impeller/entity/geometry/circle_geometry.h/0 | {
"file_path": "engine/impeller/entity/geometry/circle_geometry.h",
"repo_id": "engine",
"token_count": 773
} | 230 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/impeller/entity/geometry/round_rect_geometry.h"
namespace impeller {
RoundRectGeometry::RoundRectGeometry(const Rect& bounds, const Size& radii)
: bounds_(bounds), radii_(radii) {}
GeometryResult RoundRectGeometry::GetPositionBuffer(
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
return ComputePositionGeometry(renderer,
renderer.GetTessellator()->FilledRoundRect(
entity.GetTransform(), bounds_, radii_),
entity, pass);
}
// |Geometry|
GeometryResult RoundRectGeometry::GetPositionUVBuffer(
Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
return ComputePositionUVGeometry(
renderer,
renderer.GetTessellator()->FilledRoundRect(entity.GetTransform(), bounds_,
radii_),
texture_coverage.GetNormalizingTransform() * effect_transform, entity,
pass);
}
GeometryVertexType RoundRectGeometry::GetVertexType() const {
return GeometryVertexType::kPosition;
}
std::optional<Rect> RoundRectGeometry::GetCoverage(
const Matrix& transform) const {
return bounds_.TransformBounds(transform);
}
bool RoundRectGeometry::CoversArea(const Matrix& transform,
const Rect& rect) const {
if (!transform.IsTranslationScaleOnly()) {
return false;
}
bool flat_on_tb = bounds_.GetWidth() > radii_.width * 2;
bool flat_on_lr = bounds_.GetHeight() > radii_.height * 2;
if (!flat_on_tb && !flat_on_lr) {
return false;
}
// We either transform the bounds and delta-transform the radii,
// or we compute the vertical and horizontal bounds and then
// transform each. Either way there are 2 transform operations.
// We could also get a weaker answer by computing just the
// "inner rect" and only doing a coverage analysis on that,
// but this process will produce more culling results.
if (flat_on_tb) {
Rect vertical_bounds = bounds_.Expand(Size{-radii_.width, 0});
Rect coverage = vertical_bounds.TransformBounds(transform);
if (coverage.Contains(rect)) {
return true;
}
}
if (flat_on_lr) {
Rect horizontal_bounds = bounds_.Expand(Size{0, -radii_.height});
Rect coverage = horizontal_bounds.TransformBounds(transform);
if (coverage.Contains(rect)) {
return true;
}
}
return false;
}
bool RoundRectGeometry::IsAxisAlignedRect() const {
return false;
}
} // namespace impeller
| engine/impeller/entity/geometry/round_rect_geometry.cc/0 | {
"file_path": "engine/impeller/entity/geometry/round_rect_geometry.cc",
"repo_id": "engine",
"token_count": 1037
} | 231 |
#version 450
// 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/blending.glsl>
#include <impeller/color.glsl>
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
#include "blend_select.glsl"
// Warning: if any of the constant values or layouts are changed in this
// file, then the hard-coded constant value in
// impeller/renderer/backend/vulkan/binding_helpers_vk.cc
layout(constant_id = 0) const float blend_type = 0;
layout(constant_id = 1) const float supports_decal = 1;
layout(input_attachment_index = 0) uniform subpassInputMS uSub;
vec4 ReadDestination() {
return (subpassLoad(uSub, 0) + subpassLoad(uSub, 1) + subpassLoad(uSub, 2) +
subpassLoad(uSub, 3)) /
vec4(4.0);
}
uniform sampler2D texture_sampler_src;
uniform FragInfo {
float16_t src_input_alpha;
}
frag_info;
in vec2 v_src_texture_coords;
out vec4 frag_color;
vec4 Sample(sampler2D texture_sampler, vec2 texture_coords) {
if (supports_decal > 1) {
return texture(texture_sampler, texture_coords);
}
return IPSampleDecal(texture_sampler, texture_coords);
}
void main() {
f16vec4 dst = IPHalfUnpremultiply(f16vec4(ReadDestination()));
f16vec4 src = IPHalfUnpremultiply(
f16vec4(Sample(texture_sampler_src, // sampler
v_src_texture_coords // texture coordinates
)));
src.a *= frag_info.src_input_alpha;
f16vec3 blend_result = AdvancedBlend(dst.rgb, src.rgb, int(blend_type));
frag_color = IPApplyBlendedColor(dst, src, blend_result);
}
| engine/impeller/entity/shaders/blending/framebuffer_blend.frag/0 | {
"file_path": "engine/impeller/entity/shaders/blending/framebuffer_blend.frag",
"repo_id": "engine",
"token_count": 645
} | 232 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <impeller/conversions.glsl>
#include <impeller/types.glsl>
uniform FrameInfo {
mat4 mvp;
float texture_sampler_y_coord_scale;
}
frame_info;
in vec2 position;
in vec2 texture_coords;
out vec2 v_texture_coords;
void main() {
gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0);
v_texture_coords =
IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale);
}
| engine/impeller/entity/shaders/morphology_filter.vert/0 | {
"file_path": "engine/impeller/entity/shaders/morphology_filter.vert",
"repo_id": "engine",
"token_count": 208
} | 233 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision mediump float;
#include <impeller/constants.glsl>
#include <impeller/types.glsl>
uniform f16sampler2D texture_sampler;
uniform FragInfo {
vec4 source_rect;
}
frag_info;
in highp vec2 v_texture_coords;
IMPELLER_MAYBE_FLAT in float16_t v_alpha;
out f16vec4 frag_color;
void main() {
vec2 texture_coords = vec2(clamp(v_texture_coords.x, frag_info.source_rect.x,
frag_info.source_rect.z),
clamp(v_texture_coords.y, frag_info.source_rect.y,
frag_info.source_rect.w));
f16vec4 sampled =
texture(texture_sampler, texture_coords, kDefaultMipBiasHalf);
frag_color = sampled * v_alpha;
}
| engine/impeller/entity/shaders/texture_fill_strict_src.frag/0 | {
"file_path": "engine/impeller/entity/shaders/texture_fill_strict_src.frag",
"repo_id": "engine",
"token_count": 389
} | 234 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform FrameInfo {
float current_time;
vec2 cursor_position;
vec2 window_size;
}
frame_info;
in vec2 interpolated_texture_coordinates;
out vec4 frag_color;
uniform sampler2D contents1;
uniform sampler2D contents2;
void main() {
vec4 tex1 = texture(contents1, interpolated_texture_coordinates);
vec4 tex2 = texture(contents2, interpolated_texture_coordinates);
frag_color = mix(
tex1, tex2,
clamp(frame_info.cursor_position.x / frame_info.window_size.x, 0.0, 1.0));
}
| engine/impeller/fixtures/box_fade.frag/0 | {
"file_path": "engine/impeller/fixtures/box_fade.frag",
"repo_id": "engine",
"token_count": 228
} | 235 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform FragInfo {
vec4 unused_color;
vec4 color;
}
frag_info;
in vec2 v_position;
out vec4 frag_color;
float SphereDistance(vec2 position, float radius) {
return length(v_position - position) - radius;
}
void main() {
frag_color = frag_info.color;
}
| engine/impeller/fixtures/inactive_uniforms.frag/0 | {
"file_path": "engine/impeller/fixtures/inactive_uniforms.frag",
"repo_id": "engine",
"token_count": 138
} | 236 |
// 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.
uniform FragInfo {
vec4 color;
}
frag_info;
out vec4 frag_color;
void main() {
frag_color = frag_info.color;
}
| engine/impeller/fixtures/sample.frag/0 | {
"file_path": "engine/impeller/fixtures/sample.frag",
"repo_id": "engine",
"token_count": 91
} | 237 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_GEOMETRY_GEOMETRY_ASSERTS_H_
#define FLUTTER_IMPELLER_GEOMETRY_GEOMETRY_ASSERTS_H_
#include <array>
#include <iostream>
#include "gtest/gtest.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/rect.h"
#include "impeller/geometry/size.h"
#include "impeller/geometry/vector.h"
inline bool NumberNear(double a, double b) {
static const double epsilon = 1e-3;
return (a > (b - epsilon)) && (a < (b + epsilon));
}
inline ::testing::AssertionResult MatrixNear(impeller::Matrix a,
impeller::Matrix b) {
auto equal = NumberNear(a.m[0], b.m[0]) //
&& NumberNear(a.m[1], b.m[1]) //
&& NumberNear(a.m[2], b.m[2]) //
&& NumberNear(a.m[3], b.m[3]) //
&& NumberNear(a.m[4], b.m[4]) //
&& NumberNear(a.m[5], b.m[5]) //
&& NumberNear(a.m[6], b.m[6]) //
&& NumberNear(a.m[7], b.m[7]) //
&& NumberNear(a.m[8], b.m[8]) //
&& NumberNear(a.m[9], b.m[9]) //
&& NumberNear(a.m[10], b.m[10]) //
&& NumberNear(a.m[11], b.m[11]) //
&& NumberNear(a.m[12], b.m[12]) //
&& NumberNear(a.m[13], b.m[13]) //
&& NumberNear(a.m[14], b.m[14]) //
&& NumberNear(a.m[15], b.m[15]);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure()
<< "Matrixes are not equal " << a << " " << b;
}
inline ::testing::AssertionResult QuaternionNear(impeller::Quaternion a,
impeller::Quaternion b) {
auto equal = NumberNear(a.x, b.x) && NumberNear(a.y, b.y) &&
NumberNear(a.z, b.z) && NumberNear(a.w, b.w);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure() << "Quaternions are not equal.";
}
inline ::testing::AssertionResult RectNear(impeller::Rect a, impeller::Rect b) {
auto equal = NumberNear(a.GetLeft(), b.GetLeft()) &&
NumberNear(a.GetTop(), b.GetTop()) &&
NumberNear(a.GetRight(), b.GetRight()) &&
NumberNear(a.GetBottom(), b.GetBottom());
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure()
<< "Rects are not equal (" << a << " " << b << ")";
}
inline ::testing::AssertionResult ColorNear(impeller::Color a,
impeller::Color b) {
auto equal = NumberNear(a.red, b.red) && NumberNear(a.green, b.green) &&
NumberNear(a.blue, b.blue) && NumberNear(a.alpha, b.alpha);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure() << "Colors are not equal.";
}
inline ::testing::AssertionResult PointNear(impeller::Point a,
impeller::Point b) {
auto equal = NumberNear(a.x, b.x) && NumberNear(a.y, b.y);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure()
<< "Points are not equal (" << a << " " << b << ").";
}
inline ::testing::AssertionResult Vector3Near(impeller::Vector3 a,
impeller::Vector3 b) {
auto equal =
NumberNear(a.x, b.x) && NumberNear(a.y, b.y) && NumberNear(a.z, b.z);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure() << "Vector3s are not equal.";
}
inline ::testing::AssertionResult Vector4Near(impeller::Vector4 a,
impeller::Vector4 b) {
auto equal = NumberNear(a.x, b.x) && NumberNear(a.y, b.y) &&
NumberNear(a.z, b.z) && NumberNear(a.w, b.w);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure() << "Vector4s are not equal.";
}
inline ::testing::AssertionResult SizeNear(impeller::Size a, impeller::Size b) {
auto equal = NumberNear(a.width, b.width) && NumberNear(a.height, b.height);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure() << "Sizes are not equal.";
}
inline ::testing::AssertionResult Array4Near(std::array<uint8_t, 4> a,
std::array<uint8_t, 4> b) {
auto equal = NumberNear(a[0], b[0]) && NumberNear(a[1], b[1]) &&
NumberNear(a[2], b[2]) && NumberNear(a[3], b[3]);
return equal ? ::testing::AssertionSuccess()
: ::testing::AssertionFailure() << "Arrays are not equal.";
}
inline ::testing::AssertionResult ColorBufferNear(
std::vector<uint8_t> a,
std::vector<impeller::Color> b) {
if (a.size() != b.size() * 4) {
return ::testing::AssertionFailure()
<< "Color buffer length does not match";
}
for (auto i = 0u; i < b.size(); i++) {
auto right = b[i].Premultiply().ToR8G8B8A8();
auto j = i * 4;
auto equal = NumberNear(a[j], right[0]) && NumberNear(a[j + 1], right[1]) &&
NumberNear(a[j + 2], right[2]) &&
NumberNear(a[j + 3], right[3]);
if (!equal) {
::testing::AssertionFailure() << "Color buffers are not equal.";
}
}
return ::testing::AssertionSuccess();
}
inline ::testing::AssertionResult ColorsNear(std::vector<impeller::Color> a,
std::vector<impeller::Color> b) {
if (a.size() != b.size()) {
return ::testing::AssertionFailure() << "Colors length does not match";
}
for (auto i = 0u; i < b.size(); i++) {
auto equal =
NumberNear(a[i].red, b[i].red) && NumberNear(a[i].green, b[i].green) &&
NumberNear(a[i].blue, b[i].blue) && NumberNear(a[i].alpha, b[i].alpha);
if (!equal) {
::testing::AssertionFailure() << "Colors are not equal.";
}
}
return ::testing::AssertionSuccess();
}
#define ASSERT_MATRIX_NEAR(a, b) ASSERT_PRED2(&::MatrixNear, a, b)
#define ASSERT_QUATERNION_NEAR(a, b) ASSERT_PRED2(&::QuaternionNear, a, b)
#define ASSERT_RECT_NEAR(a, b) ASSERT_PRED2(&::RectNear, a, b)
#define ASSERT_COLOR_NEAR(a, b) ASSERT_PRED2(&::ColorNear, a, b)
#define ASSERT_POINT_NEAR(a, b) ASSERT_PRED2(&::PointNear, a, b)
#define ASSERT_VECTOR3_NEAR(a, b) ASSERT_PRED2(&::Vector3Near, a, b)
#define ASSERT_VECTOR4_NEAR(a, b) ASSERT_PRED2(&::Vector4Near, a, b)
#define ASSERT_SIZE_NEAR(a, b) ASSERT_PRED2(&::SizeNear, a, b)
#define ASSERT_ARRAY_4_NEAR(a, b) ASSERT_PRED2(&::Array4Near, a, b)
#define ASSERT_COLOR_BUFFER_NEAR(a, b) ASSERT_PRED2(&::ColorBufferNear, a, b)
#define ASSERT_COLORS_NEAR(a, b) ASSERT_PRED2(&::ColorsNear, a, b)
#define EXPECT_MATRIX_NEAR(a, b) EXPECT_PRED2(&::MatrixNear, a, b)
#define EXPECT_QUATERNION_NEAR(a, b) EXPECT_PRED2(&::QuaternionNear, a, b)
#define EXPECT_RECT_NEAR(a, b) EXPECT_PRED2(&::RectNear, a, b)
#define EXPECT_COLOR_NEAR(a, b) EXPECT_PRED2(&::ColorNear, a, b)
#define EXPECT_POINT_NEAR(a, b) EXPECT_PRED2(&::PointNear, a, b)
#define EXPECT_VECTOR3_NEAR(a, b) EXPECT_PRED2(&::Vector3Near, a, b)
#define EXPECT_VECTOR4_NEAR(a, b) EXPECT_PRED2(&::Vector4Near, a, b)
#define EXPECT_SIZE_NEAR(a, b) EXPECT_PRED2(&::SizeNear, a, b)
#define EXPECT_ARRAY_4_NEAR(a, b) EXPECT_PRED2(&::Array4Near, a, b)
#define EXPECT_COLOR_BUFFER_NEAR(a, b) EXPECT_PRED2(&::ColorBufferNear, a, b)
#define EXPECT_COLORS_NEAR(a, b) EXPECT_PRED2(&::ColorsNear, a, b)
#endif // FLUTTER_IMPELLER_GEOMETRY_GEOMETRY_ASSERTS_H_
| engine/impeller/geometry/geometry_asserts.h/0 | {
"file_path": "engine/impeller/geometry/geometry_asserts.h",
"repo_id": "engine",
"token_count": 3710
} | 238 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_GEOMETRY_PATH_COMPONENT_H_
#define FLUTTER_IMPELLER_GEOMETRY_PATH_COMPONENT_H_
#include <functional>
#include <type_traits>
#include <variant>
#include <vector>
#include "impeller/geometry/point.h"
#include "impeller/geometry/rect.h"
#include "impeller/geometry/scalar.h"
namespace impeller {
// The default tolerance value for QuadraticCurveComponent::AppendPolylinePoints
// and CubicCurveComponent::AppendPolylinePoints. It also impacts the number of
// quadratics created when flattening a cubic curve to a polyline.
//
// Smaller numbers mean more points. This number seems suitable for particularly
// curvy curves at scales close to 1.0. As the scale increases, this number
// should be divided by Matrix::GetMaxBasisLength to avoid generating too few
// points for the given scale.
static constexpr Scalar kDefaultCurveTolerance = .1f;
struct LinearPathComponent {
Point p1;
Point p2;
LinearPathComponent() {}
LinearPathComponent(Point ap1, Point ap2) : p1(ap1), p2(ap2) {}
Point Solve(Scalar time) const;
void AppendPolylinePoints(std::vector<Point>& points) const;
std::vector<Point> Extrema() const;
bool operator==(const LinearPathComponent& other) const {
return p1 == other.p1 && p2 == other.p2;
}
std::optional<Vector2> GetStartDirection() const;
std::optional<Vector2> GetEndDirection() const;
};
// A component that represets a Quadratic Bézier curve.
struct QuadraticPathComponent {
// Start point.
Point p1;
// Control point.
Point cp;
// End point.
Point p2;
QuadraticPathComponent() {}
QuadraticPathComponent(Point ap1, Point acp, Point ap2)
: p1(ap1), cp(acp), p2(ap2) {}
Point Solve(Scalar time) const;
Point SolveDerivative(Scalar time) const;
// Uses the algorithm described by Raph Levien in
// https://raphlinus.github.io/graphics/curves/2019/12/23/flatten-quadbez.html.
//
// The algorithm has several benefits:
// - It does not require elevation to cubics for processing.
// - It generates fewer and more accurate points than recursive subdivision.
// - Each turn of the core iteration loop has no dependencies on other turns,
// making it trivially parallelizable.
//
// See also the implementation in kurbo: https://github.com/linebender/kurbo.
void AppendPolylinePoints(Scalar scale_factor,
std::vector<Point>& points) const;
using PointProc = std::function<void(const Point& point)>;
void ToLinearPathComponents(Scalar scale_factor, const PointProc& proc) const;
std::vector<Point> Extrema() const;
bool operator==(const QuadraticPathComponent& other) const {
return p1 == other.p1 && cp == other.cp && p2 == other.p2;
}
std::optional<Vector2> GetStartDirection() const;
std::optional<Vector2> GetEndDirection() const;
};
// A component that represets a Cubic Bézier curve.
struct CubicPathComponent {
// Start point.
Point p1;
// The first control point.
Point cp1;
// The second control point.
Point cp2;
// End point.
Point p2;
CubicPathComponent() {}
explicit CubicPathComponent(const QuadraticPathComponent& q)
: p1(q.p1),
cp1(q.p1 + (q.cp - q.p1) * (2.0 / 3.0)),
cp2(q.p2 + (q.cp - q.p2) * (2.0 / 3.0)),
p2(q.p2) {}
CubicPathComponent(Point ap1, Point acp1, Point acp2, Point ap2)
: p1(ap1), cp1(acp1), cp2(acp2), p2(ap2) {}
Point Solve(Scalar time) const;
Point SolveDerivative(Scalar time) const;
// This method approximates the cubic component with quadratics, and then
// generates a polyline from those quadratics.
//
// See the note on QuadraticPathComponent::AppendPolylinePoints for
// references.
void AppendPolylinePoints(Scalar scale, std::vector<Point>& points) const;
std::vector<Point> Extrema() const;
using PointProc = std::function<void(const Point& point)>;
void ToLinearPathComponents(Scalar scale, const PointProc& proc) const;
CubicPathComponent Subsegment(Scalar t0, Scalar t1) const;
bool operator==(const CubicPathComponent& other) const {
return p1 == other.p1 && cp1 == other.cp1 && cp2 == other.cp2 &&
p2 == other.p2;
}
std::optional<Vector2> GetStartDirection() const;
std::optional<Vector2> GetEndDirection() const;
private:
QuadraticPathComponent Lower() const;
};
struct ContourComponent {
Point destination;
bool is_closed = false;
ContourComponent() {}
explicit ContourComponent(Point p, bool is_closed = false)
: destination(p), is_closed(is_closed) {}
bool operator==(const ContourComponent& other) const {
return destination == other.destination && is_closed == other.is_closed;
}
};
using PathComponentVariant = std::variant<std::monostate,
const LinearPathComponent*,
const QuadraticPathComponent*,
const CubicPathComponent*>;
struct PathComponentStartDirectionVisitor {
std::optional<Vector2> operator()(const LinearPathComponent* component);
std::optional<Vector2> operator()(const QuadraticPathComponent* component);
std::optional<Vector2> operator()(const CubicPathComponent* component);
std::optional<Vector2> operator()(std::monostate monostate) {
return std::nullopt;
}
};
struct PathComponentEndDirectionVisitor {
std::optional<Vector2> operator()(const LinearPathComponent* component);
std::optional<Vector2> operator()(const QuadraticPathComponent* component);
std::optional<Vector2> operator()(const CubicPathComponent* component);
std::optional<Vector2> operator()(std::monostate monostate) {
return std::nullopt;
}
};
static_assert(!std::is_polymorphic<LinearPathComponent>::value);
static_assert(!std::is_polymorphic<QuadraticPathComponent>::value);
static_assert(!std::is_polymorphic<CubicPathComponent>::value);
} // namespace impeller
#endif // FLUTTER_IMPELLER_GEOMETRY_PATH_COMPONENT_H_
| engine/impeller/geometry/path_component.h/0 | {
"file_path": "engine/impeller/geometry/path_component.h",
"repo_id": "engine",
"token_count": 2145
} | 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.
#include "flutter/impeller/golden_tests/golden_playground_test.h"
#include "impeller/aiks/picture.h"
namespace impeller {
GoldenPlaygroundTest::GoldenPlaygroundTest() = default;
GoldenPlaygroundTest::~GoldenPlaygroundTest() = default;
void GoldenPlaygroundTest::SetTypographerContext(
std::shared_ptr<TypographerContext> typographer_context) {
typographer_context_ = std::move(typographer_context);
};
void GoldenPlaygroundTest::TearDown() {}
void GoldenPlaygroundTest::SetUp() {
GTEST_SKIP_("GoldenPlaygroundTest doesn't support this backend type.");
}
PlaygroundBackend GoldenPlaygroundTest::GetBackend() const {
return GetParam();
}
bool GoldenPlaygroundTest::OpenPlaygroundHere(Picture picture) {
return false;
}
bool GoldenPlaygroundTest::OpenPlaygroundHere(
AiksPlaygroundCallback
callback) { // NOLINT(performance-unnecessary-value-param)
return false;
}
std::shared_ptr<Texture> GoldenPlaygroundTest::CreateTextureForFixture(
const char* fixture_name,
bool enable_mipmapping) const {
return nullptr;
}
RuntimeStage::Map GoldenPlaygroundTest::OpenAssetAsRuntimeStage(
const char* asset_name) const {
return {};
}
std::shared_ptr<Context> GoldenPlaygroundTest::GetContext() const {
return nullptr;
}
Point GoldenPlaygroundTest::GetContentScale() const {
return Point();
}
Scalar GoldenPlaygroundTest::GetSecondsElapsed() const {
return Scalar();
}
ISize GoldenPlaygroundTest::GetWindowSize() const {
return ISize();
}
void GoldenPlaygroundTest::SetWindowSize(ISize size) {}
fml::Status GoldenPlaygroundTest::SetCapabilities(
const std::shared_ptr<Capabilities>& capabilities) {
return fml::Status(
fml::StatusCode::kUnimplemented,
"GoldenPlaygroundTest-Stub doesn't support SetCapabilities.");
}
} // namespace impeller
| engine/impeller/golden_tests/golden_playground_test_stub.cc/0 | {
"file_path": "engine/impeller/golden_tests/golden_playground_test_stub.cc",
"repo_id": "engine",
"token_count": 621
} | 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_PLAYGROUND_BACKEND_GLES_PLAYGROUND_IMPL_GLES_H_
#define FLUTTER_IMPELLER_PLAYGROUND_BACKEND_GLES_PLAYGROUND_IMPL_GLES_H_
#include "flutter/fml/macros.h"
#include "impeller/playground/playground_impl.h"
namespace impeller {
class PlaygroundImplGLES final : public PlaygroundImpl {
public:
explicit PlaygroundImplGLES(PlaygroundSwitches switches);
~PlaygroundImplGLES();
fml::Status SetCapabilities(
const std::shared_ptr<Capabilities>& capabilities) override;
private:
class ReactorWorker;
static void DestroyWindowHandle(WindowHandle handle);
using UniqueHandle = std::unique_ptr<void, decltype(&DestroyWindowHandle)>;
UniqueHandle handle_;
std::shared_ptr<ReactorWorker> worker_;
const bool use_angle_;
void* angle_glesv2_;
// |PlaygroundImpl|
std::shared_ptr<Context> GetContext() const override;
// |PlaygroundImpl|
WindowHandle GetWindowHandle() const override;
// |PlaygroundImpl|
std::unique_ptr<Surface> AcquireSurfaceFrame(
std::shared_ptr<Context> context) override;
PlaygroundImplGLES(const PlaygroundImplGLES&) = delete;
PlaygroundImplGLES& operator=(const PlaygroundImplGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_PLAYGROUND_BACKEND_GLES_PLAYGROUND_IMPL_GLES_H_
| engine/impeller/playground/backend/gles/playground_impl_gles.h/0 | {
"file_path": "engine/impeller/playground/backend/gles/playground_impl_gles.h",
"repo_id": "engine",
"token_count": 482
} | 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_PLAYGROUND_IMAGE_DECOMPRESSED_IMAGE_H_
#define FLUTTER_IMPELLER_PLAYGROUND_IMAGE_DECOMPRESSED_IMAGE_H_
#include <memory>
#include <optional>
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "impeller/geometry/size.h"
namespace impeller {
class DecompressedImage {
public:
enum class Format {
kInvalid,
kGrey,
kGreyAlpha,
kRGB,
kRGBA,
};
DecompressedImage();
DecompressedImage(ISize size,
Format format,
std::shared_ptr<const fml::Mapping> allocation);
~DecompressedImage();
const ISize& GetSize() const;
bool IsValid() const;
Format GetFormat() const;
const std::shared_ptr<const fml::Mapping>& GetAllocation() const;
DecompressedImage ConvertToRGBA() const;
private:
ISize size_;
Format format_ = Format::kInvalid;
std::shared_ptr<const fml::Mapping> allocation_;
bool is_valid_ = false;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_PLAYGROUND_IMAGE_DECOMPRESSED_IMAGE_H_
| engine/impeller/playground/image/decompressed_image.h/0 | {
"file_path": "engine/impeller/playground/image/decompressed_image.h",
"repo_id": "engine",
"token_count": 458
} | 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.
import("//flutter/impeller/tools/impeller.gni")
if (impeller_enable_compute) {
impeller_shaders("compute_shaders") {
name = "compute"
enable_opengles = false
if (impeller_enable_vulkan) {
vulkan_language_version = 130
}
if (is_ios) {
metal_version = "2.4"
} else if (is_mac) {
metal_version = "2.1"
}
shaders = [
"stroke.comp",
"path_polyline.comp",
"prefix_sum_test.comp",
"threadgroup_sizing_test.comp",
]
}
impeller_component("compute_tessellation_unittests") {
testonly = true
sources = [ "compute_subgroup_unittests.cc" ]
deps = [
":compute_shaders",
":renderer",
"../display_list:skia_conversions",
"../entity",
"../fixtures",
"../playground:playground_test",
"//flutter/testing:testing_lib",
]
}
}
impeller_component("renderer") {
sources = [
"blit_command.cc",
"blit_command.h",
"blit_pass.cc",
"blit_pass.h",
"capabilities.cc",
"capabilities.h",
"command.cc",
"command.h",
"command_buffer.cc",
"command_buffer.h",
"command_queue.cc",
"command_queue.h",
"compute_pass.cc",
"compute_pass.h",
"compute_pipeline_builder.cc",
"compute_pipeline_builder.h",
"compute_pipeline_descriptor.cc",
"compute_pipeline_descriptor.h",
"context.cc",
"context.h",
"pipeline.cc",
"pipeline.h",
"pipeline_builder.cc",
"pipeline_builder.h",
"pipeline_descriptor.cc",
"pipeline_descriptor.h",
"pipeline_library.cc",
"pipeline_library.h",
"pool.h",
"render_pass.cc",
"render_pass.h",
"render_target.cc",
"render_target.h",
"renderer.cc",
"renderer.h",
"sampler_library.cc",
"sampler_library.h",
"shader_function.cc",
"shader_function.h",
"shader_key.cc",
"shader_key.h",
"shader_library.cc",
"shader_library.h",
"snapshot.cc",
"snapshot.h",
"surface.cc",
"surface.h",
"texture_mipmap.cc",
"texture_mipmap.h",
"vertex_buffer_builder.cc",
"vertex_buffer_builder.h",
"vertex_descriptor.cc",
"vertex_descriptor.h",
]
public_deps = [
"../base",
"../core",
"../geometry",
"../runtime_stage",
"../tessellator",
]
if (impeller_enable_compute) {
sources += [
"compute_tessellator.cc",
"compute_tessellator.h",
]
public_deps += [ ":compute_shaders" ]
}
deps = [ "//flutter/fml" ]
}
impeller_component("renderer_unittests") {
testonly = true
sources = [
"blit_pass_unittests.cc",
"capabilities_unittests.cc",
"device_buffer_unittests.cc",
"pipeline_descriptor_unittests.cc",
"pool_unittests.cc",
"renderer_unittests.cc",
]
deps = [
":renderer",
"../fixtures",
"../playground:playground_test",
"//flutter/testing:testing_lib",
]
if (impeller_enable_compute) {
sources += [ "compute_unittests.cc" ]
}
}
impeller_component("renderer_dart_unittests") {
testonly = true
sources = [ "renderer_dart_unittests.cc" ]
public_configs = [ "//flutter:export_dynamic_symbols" ]
deps = [
":renderer",
"../fixtures:flutter_gpu_fixtures",
"../fixtures:flutter_gpu_shaders",
"../playground:playground_test",
"//flutter/lib/gpu",
"//flutter/lib/snapshot",
"//flutter/runtime:runtime",
"//flutter/testing:fixture_test",
"//flutter/testing:testing",
]
}
| engine/impeller/renderer/BUILD.gn/0 | {
"file_path": "engine/impeller/renderer/BUILD.gn",
"repo_id": "engine",
"token_count": 1665
} | 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_RENDERER_BACKEND_GLES_CONTEXT_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CONTEXT_GLES_H_
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/backend/gles/allocator_gles.h"
#include "impeller/renderer/backend/gles/capabilities_gles.h"
#include "impeller/renderer/backend/gles/gpu_tracer_gles.h"
#include "impeller/renderer/backend/gles/pipeline_library_gles.h"
#include "impeller/renderer/backend/gles/reactor_gles.h"
#include "impeller/renderer/backend/gles/sampler_library_gles.h"
#include "impeller/renderer/backend/gles/shader_library_gles.h"
#include "impeller/renderer/capabilities.h"
#include "impeller/renderer/command_queue.h"
#include "impeller/renderer/context.h"
namespace impeller {
class ContextGLES final : public Context,
public BackendCast<ContextGLES, Context>,
public std::enable_shared_from_this<ContextGLES> {
public:
static std::shared_ptr<ContextGLES> Create(
std::unique_ptr<ProcTableGLES> gl,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries,
bool enable_gpu_tracing);
// |Context|
~ContextGLES() override;
// |Context|
BackendType GetBackendType() const override;
const ReactorGLES::Ref& GetReactor() const;
std::optional<ReactorGLES::WorkerID> AddReactorWorker(
const std::shared_ptr<ReactorGLES::Worker>& worker);
bool RemoveReactorWorker(ReactorGLES::WorkerID id);
std::shared_ptr<GPUTracerGLES> GetGPUTracer() const { return gpu_tracer_; }
private:
ReactorGLES::Ref reactor_;
std::shared_ptr<ShaderLibraryGLES> shader_library_;
std::shared_ptr<PipelineLibraryGLES> pipeline_library_;
std::shared_ptr<SamplerLibraryGLES> sampler_library_;
std::shared_ptr<AllocatorGLES> resource_allocator_;
std::shared_ptr<CommandQueue> command_queue_;
std::shared_ptr<GPUTracerGLES> gpu_tracer_;
// Note: This is stored separately from the ProcTableGLES CapabilitiesGLES
// in order to satisfy the Context::GetCapabilities signature which returns
// a reference.
std::shared_ptr<const Capabilities> device_capabilities_;
bool is_valid_ = false;
ContextGLES(
std::unique_ptr<ProcTableGLES> gl,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries,
bool enable_gpu_tracing);
// |Context|
std::string DescribeGpuModel() const override;
// |Context|
bool IsValid() const override;
// |Context|
std::shared_ptr<Allocator> GetResourceAllocator() const override;
// |Context|
std::shared_ptr<ShaderLibrary> GetShaderLibrary() const override;
// |Context|
std::shared_ptr<SamplerLibrary> GetSamplerLibrary() const override;
// |Context|
std::shared_ptr<PipelineLibrary> GetPipelineLibrary() const override;
// |Context|
std::shared_ptr<CommandBuffer> CreateCommandBuffer() const override;
// |Context|
const std::shared_ptr<const Capabilities>& GetCapabilities() const override;
// |Context|
std::shared_ptr<CommandQueue> GetCommandQueue() const override;
// |Context|
void Shutdown() override;
ContextGLES(const ContextGLES&) = delete;
ContextGLES& operator=(const ContextGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CONTEXT_GLES_H_
| engine/impeller/renderer/backend/gles/context_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/context_gles.h",
"repo_id": "engine",
"token_count": 1250
} | 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/renderer/backend/gles/proc_table_gles.h"
#include <sstream>
#include "fml/closure.h"
#include "impeller/base/allocation.h"
#include "impeller/base/comparable.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/gles/capabilities_gles.h"
#include "impeller/renderer/capabilities.h"
namespace impeller {
const char* GLErrorToString(GLenum value) {
switch (value) {
case GL_NO_ERROR:
return "GL_NO_ERROR";
case GL_INVALID_ENUM:
return "GL_INVALID_ENUM";
case GL_INVALID_VALUE:
return "GL_INVALID_VALUE";
case GL_INVALID_OPERATION:
return "GL_INVALID_OPERATION";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "GL_INVALID_FRAMEBUFFER_OPERATION";
case GL_FRAMEBUFFER_COMPLETE:
return "GL_FRAMEBUFFER_COMPLETE";
case GL_OUT_OF_MEMORY:
return "GL_OUT_OF_MEMORY";
}
return "Unknown.";
}
bool GLErrorIsFatal(GLenum value) {
switch (value) {
case GL_NO_ERROR:
return false;
case GL_INVALID_ENUM:
case GL_INVALID_VALUE:
case GL_INVALID_OPERATION:
case GL_INVALID_FRAMEBUFFER_OPERATION:
case GL_OUT_OF_MEMORY:
return true;
}
return false;
}
ProcTableGLES::Resolver WrappedResolver(
const ProcTableGLES::Resolver& resolver) {
return [resolver](const char* function_name) -> void* {
auto resolved = resolver(function_name);
if (resolved) {
return resolved;
}
// If there are certain known suffixes (usually for extensions), strip them
// out and try to resolve the same proc addresses again.
auto function = std::string{function_name};
if (function.find("KHR", function.size() - 3) != std::string::npos) {
auto truncated = function.substr(0u, function.size() - 3);
return resolver(truncated.c_str());
}
if (function.find("EXT", function.size() - 3) != std::string::npos) {
auto truncated = function.substr(0u, function.size() - 3);
return resolver(truncated.c_str());
}
return nullptr;
};
}
ProcTableGLES::ProcTableGLES( // NOLINT(google-readability-function-size)
Resolver resolver) {
// The reason this constructor has anywhere near enough code to tip off
// `google-readability-function-size` is the proc macros, so ignore the lint.
if (!resolver) {
return;
}
resolver = WrappedResolver(resolver);
auto error_fn = reinterpret_cast<PFNGLGETERRORPROC>(resolver("glGetError"));
if (!error_fn) {
VALIDATION_LOG << "Could not resolve " << "glGetError";
return;
}
#define IMPELLER_PROC(proc_ivar) \
if (auto fn_ptr = resolver(proc_ivar.name)) { \
proc_ivar.function = \
reinterpret_cast<decltype(proc_ivar.function)>(fn_ptr); \
proc_ivar.error_fn = error_fn; \
} else { \
VALIDATION_LOG << "Could not resolve " << proc_ivar.name; \
return; \
}
FOR_EACH_IMPELLER_PROC(IMPELLER_PROC);
description_ = std::make_unique<DescriptionGLES>(*this);
if (!description_->IsValid()) {
return;
}
if (description_->IsES()) {
FOR_EACH_IMPELLER_ES_ONLY_PROC(IMPELLER_PROC);
} else {
FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(IMPELLER_PROC);
}
#undef IMPELLER_PROC
#define IMPELLER_PROC(proc_ivar) \
if (auto fn_ptr = resolver(proc_ivar.name)) { \
proc_ivar.function = \
reinterpret_cast<decltype(proc_ivar.function)>(fn_ptr); \
proc_ivar.error_fn = error_fn; \
}
FOR_EACH_IMPELLER_GLES3_PROC(IMPELLER_PROC);
FOR_EACH_IMPELLER_EXT_PROC(IMPELLER_PROC);
#undef IMPELLER_PROC
if (!description_->HasDebugExtension()) {
PushDebugGroupKHR.Reset();
PopDebugGroupKHR.Reset();
ObjectLabelKHR.Reset();
} else {
GetIntegerv(GL_MAX_LABEL_LENGTH_KHR, &debug_label_max_length_);
}
if (!description_->HasExtension("GL_EXT_discard_framebuffer")) {
DiscardFramebufferEXT.Reset();
}
capabilities_ = std::make_shared<CapabilitiesGLES>(*this);
is_valid_ = true;
}
ProcTableGLES::~ProcTableGLES() = default;
bool ProcTableGLES::IsValid() const {
return is_valid_;
}
void ProcTableGLES::ShaderSourceMapping(
GLuint shader,
const fml::Mapping& mapping,
const std::vector<Scalar>& defines) const {
if (defines.empty()) {
const GLchar* sources[] = {
reinterpret_cast<const GLchar*>(mapping.GetMapping())};
const GLint lengths[] = {static_cast<GLint>(mapping.GetSize())};
ShaderSource(shader, 1u, sources, lengths);
return;
}
const auto& shader_source = ComputeShaderWithDefines(mapping, defines);
if (!shader_source.has_value()) {
VALIDATION_LOG << "Failed to append constant data to shader";
return;
}
const GLchar* sources[] = {
reinterpret_cast<const GLchar*>(shader_source->c_str())};
const GLint lengths[] = {static_cast<GLint>(shader_source->size())};
ShaderSource(shader, 1u, sources, lengths);
}
// Visible For testing.
std::optional<std::string> ProcTableGLES::ComputeShaderWithDefines(
const fml::Mapping& mapping,
const std::vector<Scalar>& defines) const {
auto shader_source = std::string{
reinterpret_cast<const char*>(mapping.GetMapping()), mapping.GetSize()};
// Look for the first newline after the '#version' header, which impellerc
// will always emit as the first line of a compiled shader.
auto index = shader_source.find('\n');
if (index == std::string::npos) {
VALIDATION_LOG << "Failed to append constant data to shader";
return std::nullopt;
}
std::stringstream ss;
ss << std::fixed;
for (auto i = 0u; i < defines.size(); i++) {
ss << "#define SPIRV_CROSS_CONSTANT_ID_" << i << " " << defines[i] << '\n';
}
auto define_string = ss.str();
shader_source.insert(index + 1, define_string);
return shader_source;
}
const DescriptionGLES* ProcTableGLES::GetDescription() const {
return description_.get();
}
const std::shared_ptr<const CapabilitiesGLES>& ProcTableGLES::GetCapabilities()
const {
return capabilities_;
}
static const char* FramebufferStatusToString(GLenum status) {
switch (status) {
case GL_FRAMEBUFFER_COMPLETE:
return "GL_FRAMEBUFFER_COMPLETE";
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
#if GL_ES_VERSION_2_0
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
return "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
#endif
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case GL_FRAMEBUFFER_UNSUPPORTED:
return "GL_FRAMEBUFFER_UNSUPPORTED";
case GL_INVALID_ENUM:
return "GL_INVALID_ENUM";
}
return "Unknown FBO Error Status";
}
static const char* AttachmentTypeString(GLint type) {
switch (type) {
case GL_RENDERBUFFER:
return "GL_RENDERBUFFER";
case GL_TEXTURE:
return "GL_TEXTURE";
case GL_NONE:
return "GL_NONE";
}
return "Unknown Type";
}
static std::string DescribeFramebufferAttachment(const ProcTableGLES& gl,
GLenum attachment) {
GLint param = GL_NONE;
gl.GetFramebufferAttachmentParameteriv(
GL_FRAMEBUFFER, // target
attachment, // attachment
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, // parameter name
¶m // parameter
);
if (param != GL_NONE) {
param = GL_NONE;
gl.GetFramebufferAttachmentParameteriv(
GL_FRAMEBUFFER, // target
attachment, // attachment
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, // parameter name
¶m // parameter
);
std::stringstream stream;
stream << AttachmentTypeString(param) << "(" << param << ")";
return stream.str();
}
return "No Attachment";
}
std::string ProcTableGLES::DescribeCurrentFramebuffer() const {
GLint framebuffer = GL_NONE;
GetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer);
if (IsFramebuffer(framebuffer) == GL_FALSE) {
return "No framebuffer or the default window framebuffer is bound.";
}
GLenum status = CheckFramebufferStatus(framebuffer);
std::stringstream stream;
stream << "FBO "
<< ((framebuffer == GL_NONE) ? "(Default)"
: std::to_string(framebuffer))
<< ": " << FramebufferStatusToString(status) << std::endl;
if (IsCurrentFramebufferComplete()) {
stream << "Framebuffer is complete." << std::endl;
} else {
stream << "Framebuffer is incomplete." << std::endl;
}
stream << "Description: " << std::endl;
stream << "Color Attachment: "
<< DescribeFramebufferAttachment(*this, GL_COLOR_ATTACHMENT0)
<< std::endl;
stream << "Color Attachment: "
<< DescribeFramebufferAttachment(*this, GL_DEPTH_ATTACHMENT)
<< std::endl;
stream << "Color Attachment: "
<< DescribeFramebufferAttachment(*this, GL_STENCIL_ATTACHMENT)
<< std::endl;
return stream.str();
}
bool ProcTableGLES::IsCurrentFramebufferComplete() const {
GLint framebuffer = GL_NONE;
GetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer);
if (IsFramebuffer(framebuffer) == GL_FALSE) {
// The default framebuffer is always complete.
return true;
}
GLenum status = CheckFramebufferStatus(framebuffer);
return status == GL_FRAMEBUFFER_COMPLETE;
}
static std::optional<GLenum> ToDebugIdentifier(DebugResourceType type) {
switch (type) {
case DebugResourceType::kTexture:
return GL_TEXTURE;
case DebugResourceType::kBuffer:
return GL_BUFFER_KHR;
case DebugResourceType::kProgram:
return GL_PROGRAM_KHR;
case DebugResourceType::kShader:
return GL_SHADER_KHR;
case DebugResourceType::kRenderBuffer:
return GL_RENDERBUFFER;
case DebugResourceType::kFrameBuffer:
return GL_FRAMEBUFFER;
}
FML_UNREACHABLE();
}
static bool ResourceIsLive(const ProcTableGLES& gl,
DebugResourceType type,
GLint name) {
switch (type) {
case DebugResourceType::kTexture:
return gl.IsTexture(name);
case DebugResourceType::kBuffer:
return gl.IsBuffer(name);
case DebugResourceType::kProgram:
return gl.IsProgram(name);
case DebugResourceType::kShader:
return gl.IsShader(name);
case DebugResourceType::kRenderBuffer:
return gl.IsRenderbuffer(name);
case DebugResourceType::kFrameBuffer:
return gl.IsFramebuffer(name);
}
FML_UNREACHABLE();
}
bool ProcTableGLES::SetDebugLabel(DebugResourceType type,
GLint name,
const std::string& label) const {
if (debug_label_max_length_ <= 0) {
return true;
}
if (!ObjectLabelKHR.IsAvailable()) {
return true;
}
if (!ResourceIsLive(*this, type, name)) {
return false;
}
const auto identifier = ToDebugIdentifier(type);
const auto label_length =
std::min<GLsizei>(debug_label_max_length_ - 1, label.size());
if (!identifier.has_value()) {
return true;
}
ObjectLabelKHR(identifier.value(), // identifier
name, // name
label_length, // length
label.data() // label
);
return true;
}
void ProcTableGLES::PushDebugGroup(const std::string& label) const {
#ifdef IMPELLER_DEBUG
if (debug_label_max_length_ <= 0) {
return;
}
UniqueID id;
const auto label_length =
std::min<GLsizei>(debug_label_max_length_ - 1, label.size());
PushDebugGroupKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, // source
static_cast<GLuint>(id.id), // id
label_length, // length
label.data() // message
);
#endif // IMPELLER_DEBUG
}
void ProcTableGLES::PopDebugGroup() const {
#ifdef IMPELLER_DEBUG
if (debug_label_max_length_ <= 0) {
return;
}
PopDebugGroupKHR();
#endif // IMPELLER_DEBUG
}
std::string ProcTableGLES::GetProgramInfoLogString(GLuint program) const {
GLint length = 0;
GetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
if (length <= 0) {
return "";
}
length = std::min<GLint>(length, 1024);
Allocation allocation;
if (!allocation.Truncate(length, false)) {
return "";
}
GetProgramInfoLog(program, // program
length, // max length
&length, // length written (excluding NULL terminator)
reinterpret_cast<GLchar*>(allocation.GetBuffer()) // buffer
);
if (length <= 0) {
return "";
}
return std::string{reinterpret_cast<const char*>(allocation.GetBuffer()),
static_cast<size_t>(length)};
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/proc_table_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/proc_table_gles.cc",
"repo_id": "engine",
"token_count": 5675
} | 245 |
# `MockGLES`
This directory contains a mock implementation of the GLES backend.
Most functions are implemented as no-ops, have a default implementation that is not configurable, or just record the call. The latter is useful for testing:
```cc
TEST(MockGLES, Example) {
// Creates a mock GLES implementation and sets it as the current one.
auto mock_gles = MockGLES::Init();
auto& gl = mock_gles->GetProcTable();
// Call the proc table methods as usual, or pass the proc table to a class
// that needs it.
gl.PushDebugGroupKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, 0, -1, "test");
gl.PopDebugGroupKHR();
// Method names are recorded and can be inspected.
//
// Note that many built-ins, like glGetString, are not recorded (otherwise the // logs would be much bigger and less useful).
auto calls = mock_gles->GetCapturedCalls();
EXPECT_EQ(calls, std::vector<std::string>(
{"PushDebugGroupKHR", "PopDebugGroupKHR"}));
}
```
To add a new function, do the following:
1. Add a new top-level method to [`mock_gles.cc`](mock_gles.cc):
```cc
void glFooBar() {
recordCall("glFooBar");
}
```
2. Edit the `kMockResolver`, and add a new `else if` clause:
```diff
+ else if (strcmp(name, "glFooBar") == 0) {
+ return reinterpret_cast<void*>(&glFooBar);
} else {
return reinterpret_cast<void*>(&glDoNothing);
}
```
It's possible we'll want to add a more sophisticated mechanism for mocking
besides capturing calls, but this is a good start. PRs welcome!
| engine/impeller/renderer/backend/gles/test/README.md/0 | {
"file_path": "engine/impeller/renderer/backend/gles/test/README.md",
"repo_id": "engine",
"token_count": 537
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_PASS_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_PASS_MTL_H_
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/blit_command_mtl.h"
#include "impeller/renderer/blit_pass.h"
namespace impeller {
class BlitPassMTL final : public BlitPass {
public:
// |RenderPass|
~BlitPassMTL() override;
private:
friend class CommandBufferMTL;
std::vector<std::unique_ptr<BlitEncodeMTL>> commands_;
id<MTLCommandBuffer> buffer_ = nil;
std::string label_;
bool is_valid_ = false;
explicit BlitPassMTL(id<MTLCommandBuffer> buffer);
// |BlitPass|
bool IsValid() const override;
// |BlitPass|
void OnSetLabel(std::string label) override;
// |BlitPass|
bool EncodeCommands(
const std::shared_ptr<Allocator>& transients_allocator) const override;
bool EncodeCommands(id<MTLBlitCommandEncoder> pass) const;
// |BlitPass|
bool OnCopyTextureToTextureCommand(std::shared_ptr<Texture> source,
std::shared_ptr<Texture> destination,
IRect source_region,
IPoint destination_origin,
std::string label) override;
// |BlitPass|
bool OnCopyTextureToBufferCommand(std::shared_ptr<Texture> source,
std::shared_ptr<DeviceBuffer> destination,
IRect source_region,
size_t destination_offset,
std::string label) override;
// |BlitPass|
bool OnCopyBufferToTextureCommand(BufferView source,
std::shared_ptr<Texture> destination,
IPoint destination_origin,
std::string label) override;
// |BlitPass|
bool OnGenerateMipmapCommand(std::shared_ptr<Texture> texture,
std::string label) override;
BlitPassMTL(const BlitPassMTL&) = delete;
BlitPassMTL& operator=(const BlitPassMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_PASS_MTL_H_
| engine/impeller/renderer/backend/metal/blit_pass_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/blit_pass_mtl.h",
"repo_id": "engine",
"token_count": 1127
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_GPU_TRACER_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_GPU_TRACER_MTL_H_
#include <Metal/Metal.h>
#include <memory>
#include <optional>
#include "impeller/base/thread.h"
#include "impeller/base/thread_safety.h"
#include "impeller/geometry/scalar.h"
namespace impeller {
class ContextMTL;
/// @brief Approximate the GPU frame time by computing a difference between the
/// smallest GPUStartTime and largest GPUEndTime for all command buffers
/// submitted in a frame workload.
class GPUTracerMTL : public std::enable_shared_from_this<GPUTracerMTL> {
public:
GPUTracerMTL() = default;
~GPUTracerMTL() = default;
/// @brief Record that the current frame has ended. Any additional cmd buffers
/// will be attributed to the "next" frame.
void MarkFrameEnd();
/// @brief Record the current cmd buffer GPU execution timestamps into an
/// aggregate frame workload metric.
void RecordCmdBuffer(id<MTLCommandBuffer> buffer);
private:
struct GPUTraceState {
Scalar smallest_timestamp = std::numeric_limits<float>::max();
Scalar largest_timestamp = 0;
size_t pending_buffers = 0;
};
mutable Mutex trace_state_mutex_;
GPUTraceState trace_states_[16] IPLR_GUARDED_BY(trace_state_mutex_);
size_t current_state_ IPLR_GUARDED_BY(trace_state_mutex_) = 0u;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_GPU_TRACER_MTL_H_
| engine/impeller/renderer/backend/metal/gpu_tracer_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/gpu_tracer_mtl.h",
"repo_id": "engine",
"token_count": 585
} | 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_RENDERER_BACKEND_METAL_SHADER_FUNCTION_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_FUNCTION_MTL_H_
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/shader_function.h"
namespace impeller {
class ShaderFunctionMTL final
: public ShaderFunction,
public BackendCast<ShaderFunctionMTL, ShaderFunction> {
public:
// |ShaderFunction|
~ShaderFunctionMTL() override;
id<MTLFunction> GetMTLFunction() const;
using CompileCallback = std::function<void(id<MTLFunction>)>;
void GetMTLFunctionSpecialized(const std::vector<Scalar>& constants,
const CompileCallback& callback) const;
private:
friend class ShaderLibraryMTL;
id<MTLFunction> function_ = nullptr;
id<MTLLibrary> library_ = nullptr;
ShaderFunctionMTL(UniqueID parent_library_id,
id<MTLFunction> function,
id<MTLLibrary> library,
std::string name,
ShaderStage stage);
ShaderFunctionMTL(const ShaderFunctionMTL&) = delete;
ShaderFunctionMTL& operator=(const ShaderFunctionMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_FUNCTION_MTL_H_
| engine/impeller/renderer/backend/metal/shader_function_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/shader_function_mtl.h",
"repo_id": "engine",
"token_count": 599
} | 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.
#include "flutter/testing/testing.h" // IWYU pragma: keep
#include "gtest/gtest.h"
#include "impeller/core/device_buffer_descriptor.h"
#include "impeller/core/formats.h"
#include "impeller/renderer/backend/vulkan/allocator_vk.h"
#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h"
#include "vulkan/vulkan_enums.hpp"
namespace impeller {
namespace testing {
TEST(AllocatorVKTest, ToVKImageUsageFlags) {
EXPECT_EQ(AllocatorVK::ToVKImageUsageFlags(
PixelFormat::kR8G8B8A8UNormInt,
static_cast<TextureUsageMask>(TextureUsage::kRenderTarget),
StorageMode::kDeviceTransient,
/*supports_memoryless_textures=*/true),
vk::ImageUsageFlagBits::eInputAttachment |
vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransientAttachment);
EXPECT_EQ(AllocatorVK::ToVKImageUsageFlags(
PixelFormat::kD24UnormS8Uint,
static_cast<TextureUsageMask>(TextureUsage::kRenderTarget),
StorageMode::kDeviceTransient,
/*supports_memoryless_textures=*/true),
vk::ImageUsageFlagBits::eDepthStencilAttachment |
vk::ImageUsageFlagBits::eTransientAttachment);
}
TEST(AllocatorVKTest, MemoryTypeSelectionSingleHeap) {
vk::PhysicalDeviceMemoryProperties properties;
properties.memoryTypeCount = 1;
properties.memoryHeapCount = 1;
properties.memoryTypes[0].heapIndex = 0;
properties.memoryTypes[0].propertyFlags =
vk::MemoryPropertyFlagBits::eDeviceLocal;
properties.memoryHeaps[0].size = 1024 * 1024 * 1024;
properties.memoryHeaps[0].flags = vk::MemoryHeapFlagBits::eDeviceLocal;
EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(1, properties), 0);
EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(2, properties), -1);
EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(3, properties), 0);
}
TEST(AllocatorVKTest, MemoryTypeSelectionTwoHeap) {
vk::PhysicalDeviceMemoryProperties properties;
properties.memoryTypeCount = 2;
properties.memoryHeapCount = 2;
properties.memoryTypes[0].heapIndex = 0;
properties.memoryTypes[0].propertyFlags =
vk::MemoryPropertyFlagBits::eHostVisible;
properties.memoryHeaps[0].size = 1024 * 1024 * 1024;
properties.memoryHeaps[0].flags = vk::MemoryHeapFlagBits::eDeviceLocal;
properties.memoryTypes[1].heapIndex = 1;
properties.memoryTypes[1].propertyFlags =
vk::MemoryPropertyFlagBits::eDeviceLocal;
properties.memoryHeaps[1].size = 1024 * 1024 * 1024;
properties.memoryHeaps[1].flags = vk::MemoryHeapFlagBits::eDeviceLocal;
// First fails because this only looks for eDeviceLocal.
EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(1, properties), -1);
EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(2, properties), 1);
EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(3, properties), 1);
EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(4, properties), -1);
}
#ifdef IMPELLER_DEBUG
TEST(AllocatorVKTest, RecreateSwapchainWhenSizeChanges) {
auto const context = MockVulkanContextBuilder().Build();
auto allocator = context->GetResourceAllocator();
EXPECT_EQ(
reinterpret_cast<AllocatorVK*>(allocator.get())->DebugGetHeapUsage(), 0u);
allocator->CreateBuffer(DeviceBufferDescriptor{
.storage_mode = StorageMode::kDevicePrivate,
.size = 1024,
});
// Usage increases beyond the size of the allocated buffer since VMA will
// first allocate large blocks of memory and then suballocate small memory
// allocations.
EXPECT_EQ(
reinterpret_cast<AllocatorVK*>(allocator.get())->DebugGetHeapUsage(),
16u);
}
#endif // IMPELLER_DEBUG
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/allocator_vk_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/allocator_vk_unittests.cc",
"repo_id": "engine",
"token_count": 1447
} | 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.
#include <thread>
#include "flutter/testing/testing.h" // IWYU pragma: keep
#include "fml/synchronization/waitable_event.h"
#include "impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h"
#include "impeller/renderer/command_buffer.h"
namespace impeller {
namespace testing {
TEST(CommandEncoderVKTest, DeleteEncoderAfterThreadDies) {
// Tests that when a CommandEncoderVK is deleted that it will clean up its
// command buffers before it cleans up its command pool.
std::shared_ptr<std::vector<std::string>> called_functions;
{
auto context = MockVulkanContextBuilder().Build();
called_functions = GetMockVulkanFunctions(context->GetDevice());
std::shared_ptr<CommandEncoderVK> encoder;
std::thread thread([&] {
CommandEncoderFactoryVK factory(context);
encoder = factory.Create();
});
thread.join();
context->Shutdown();
}
auto destroy_pool =
std::find(called_functions->begin(), called_functions->end(),
"vkDestroyCommandPool");
auto free_buffers =
std::find(called_functions->begin(), called_functions->end(),
"vkFreeCommandBuffers");
EXPECT_TRUE(destroy_pool != called_functions->end());
EXPECT_TRUE(free_buffers != called_functions->end());
EXPECT_TRUE(free_buffers < destroy_pool);
}
TEST(CommandEncoderVKTest, CleanupAfterSubmit) {
// This tests deleting the TrackedObjects where the thread is killed before
// the fence waiter has disposed of them, making sure the command buffer and
// its pools are deleted in that order.
std::shared_ptr<std::vector<std::string>> called_functions;
{
fml::AutoResetWaitableEvent wait_for_submit;
fml::AutoResetWaitableEvent wait_for_thread_join;
auto context = MockVulkanContextBuilder().Build();
std::thread thread([&] {
auto buffer = context->CreateCommandBuffer();
context->GetCommandQueue()->Submit(
{buffer}, [&](CommandBuffer::Status status) {
ASSERT_EQ(status, CommandBuffer::Status::kCompleted);
wait_for_thread_join.Wait();
wait_for_submit.Signal();
});
});
thread.join();
wait_for_thread_join.Signal();
wait_for_submit.Wait();
called_functions = GetMockVulkanFunctions(context->GetDevice());
context->Shutdown();
}
auto destroy_pool =
std::find(called_functions->begin(), called_functions->end(),
"vkDestroyCommandPool");
auto free_buffers =
std::find(called_functions->begin(), called_functions->end(),
"vkFreeCommandBuffers");
EXPECT_TRUE(destroy_pool != called_functions->end());
EXPECT_TRUE(free_buffers != called_functions->end());
EXPECT_TRUE(free_buffers < destroy_pool);
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/command_encoder_vk_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/command_encoder_vk_unittests.cc",
"repo_id": "engine",
"token_count": 1079
} | 251 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DESCRIPTOR_POOL_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DESCRIPTOR_POOL_VK_H_
#include <cstdint>
#include "fml/status_or.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "vulkan/vulkan_handles.hpp"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief A per-frame descriptor pool. Descriptors
/// from this pool don't need to be freed individually. Instead, the
/// pool must be collected after all the descriptors allocated from
/// it are done being used.
///
/// The pool or it's descriptors may not be accessed from multiple
/// threads.
///
/// Encoders create pools as necessary as they have the same
/// threading and lifecycle restrictions.
class DescriptorPoolVK {
public:
explicit DescriptorPoolVK(std::weak_ptr<const ContextVK> context);
~DescriptorPoolVK();
fml::StatusOr<vk::DescriptorSet> AllocateDescriptorSets(
const vk::DescriptorSetLayout& layout,
const ContextVK& context_vk);
private:
std::weak_ptr<const ContextVK> context_;
std::vector<vk::UniqueDescriptorPool> pools_;
fml::Status CreateNewPool(const ContextVK& context_vk);
DescriptorPoolVK(const DescriptorPoolVK&) = delete;
DescriptorPoolVK& operator=(const DescriptorPoolVK&) = delete;
};
//------------------------------------------------------------------------------
/// @brief Creates and manages the lifecycle of |vk::DescriptorPoolVK|
/// objects.
class DescriptorPoolRecyclerVK final
: public std::enable_shared_from_this<DescriptorPoolRecyclerVK> {
public:
~DescriptorPoolRecyclerVK() = default;
/// The maximum number of descriptor pools this recycler will hold onto.
static constexpr size_t kMaxRecycledPools = 32u;
/// @brief Creates a recycler for the given |ContextVK|.
///
/// @param[in] context The context to create the recycler for.
explicit DescriptorPoolRecyclerVK(std::weak_ptr<ContextVK> context)
: context_(std::move(context)) {}
/// @brief Gets a descriptor pool.
///
/// This may create a new descriptor pool if no existing pools had
/// the necessary capacity.
vk::UniqueDescriptorPool Get();
/// @brief Returns the descriptor pool to be reset on a background
/// thread.
///
/// @param[in] pool The pool to recycler.
void Reclaim(vk::UniqueDescriptorPool&& pool);
private:
std::weak_ptr<ContextVK> context_;
Mutex recycled_mutex_;
std::vector<vk::UniqueDescriptorPool> recycled_ IPLR_GUARDED_BY(
recycled_mutex_);
/// @brief Creates a new |vk::CommandPool|.
///
/// @returns Returns a |std::nullopt| if a pool could not be created.
vk::UniqueDescriptorPool Create();
/// @brief Reuses a recycled |vk::CommandPool|, if available.
///
/// @returns Returns a |std::nullopt| if a pool was not available.
std::optional<vk::UniqueDescriptorPool> Reuse();
DescriptorPoolRecyclerVK(const DescriptorPoolRecyclerVK&) = delete;
DescriptorPoolRecyclerVK& operator=(const DescriptorPoolRecyclerVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DESCRIPTOR_POOL_VK_H_
| engine/impeller/renderer/backend/vulkan/descriptor_pool_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/descriptor_pool_vk.h",
"repo_id": "engine",
"token_count": 1247
} | 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.
// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/123467
#include "impeller/renderer/backend/vulkan/pipeline_cache_vk.h"
#include <sstream>
#include "flutter/fml/mapping.h"
#include "impeller/base/validation.h"
namespace impeller {
static constexpr const char* kPipelineCacheFileName =
"flutter.impeller.vkcache";
static bool VerifyExistingCache(const fml::Mapping& mapping,
const CapabilitiesVK& caps) {
return true;
}
static std::shared_ptr<fml::Mapping> DecorateCacheWithMetadata(
std::shared_ptr<fml::Mapping> data) {
return data;
}
static std::unique_ptr<fml::Mapping> RemoveMetadataFromCache(
std::unique_ptr<fml::Mapping> data) {
return data;
}
static std::unique_ptr<fml::Mapping> OpenCacheFile(
const fml::UniqueFD& base_directory,
const std::string& cache_file_name,
const CapabilitiesVK& caps) {
if (!base_directory.is_valid()) {
return nullptr;
}
std::unique_ptr<fml::Mapping> mapping =
fml::FileMapping::CreateReadOnly(base_directory, cache_file_name);
if (!mapping) {
return nullptr;
}
if (!VerifyExistingCache(*mapping, caps)) {
return nullptr;
}
mapping = RemoveMetadataFromCache(std::move(mapping));
if (!mapping) {
return nullptr;
}
return mapping;
}
PipelineCacheVK::PipelineCacheVK(std::shared_ptr<const Capabilities> caps,
std::shared_ptr<DeviceHolderVK> device_holder,
fml::UniqueFD cache_directory)
: caps_(std::move(caps)),
device_holder_(device_holder),
cache_directory_(std::move(cache_directory)) {
if (!caps_ || !device_holder->GetDevice()) {
return;
}
const auto& vk_caps = CapabilitiesVK::Cast(*caps_);
auto existing_cache_data =
OpenCacheFile(cache_directory_, kPipelineCacheFileName, vk_caps);
vk::PipelineCacheCreateInfo cache_info;
if (existing_cache_data) {
cache_info.initialDataSize = existing_cache_data->GetSize();
cache_info.pInitialData = existing_cache_data->GetMapping();
}
auto [result, existing_cache] =
device_holder->GetDevice().createPipelineCacheUnique(cache_info);
if (result == vk::Result::eSuccess) {
cache_ = std::move(existing_cache);
} else {
// Even though we perform consistency checks because we don't trust the
// driver, the driver may have additional information that may cause it to
// reject the cache too.
FML_LOG(INFO) << "Existing pipeline cache was invalid: "
<< vk::to_string(result) << ". Starting with a fresh cache.";
cache_info.pInitialData = nullptr;
cache_info.initialDataSize = 0u;
auto [result2, new_cache] =
device_holder->GetDevice().createPipelineCacheUnique(cache_info);
if (result2 == vk::Result::eSuccess) {
cache_ = std::move(new_cache);
} else {
VALIDATION_LOG << "Could not create new pipeline cache: "
<< vk::to_string(result2);
}
}
is_valid_ = !!cache_;
}
PipelineCacheVK::~PipelineCacheVK() {
std::shared_ptr<DeviceHolderVK> device_holder = device_holder_.lock();
if (device_holder) {
cache_.reset();
} else {
cache_.release();
}
}
bool PipelineCacheVK::IsValid() const {
return is_valid_;
}
vk::UniquePipeline PipelineCacheVK::CreatePipeline(
const vk::GraphicsPipelineCreateInfo& info) {
std::shared_ptr<DeviceHolderVK> strong_device = device_holder_.lock();
if (!strong_device) {
return {};
}
auto [result, pipeline] =
strong_device->GetDevice().createGraphicsPipelineUnique(*cache_, info);
if (result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create graphics pipeline: "
<< vk::to_string(result);
}
return std::move(pipeline);
}
vk::UniquePipeline PipelineCacheVK::CreatePipeline(
const vk::ComputePipelineCreateInfo& info) {
std::shared_ptr<DeviceHolderVK> strong_device = device_holder_.lock();
if (!strong_device) {
return {};
}
auto [result, pipeline] =
strong_device->GetDevice().createComputePipelineUnique(*cache_, info);
if (result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create compute pipeline: "
<< vk::to_string(result);
}
return std::move(pipeline);
}
std::shared_ptr<fml::Mapping> PipelineCacheVK::CopyPipelineCacheData() const {
std::shared_ptr<DeviceHolderVK> strong_device = device_holder_.lock();
if (!strong_device) {
return nullptr;
}
if (!IsValid()) {
return nullptr;
}
auto [result, data] =
strong_device->GetDevice().getPipelineCacheData(*cache_);
if (result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not get pipeline cache data to persist.";
return nullptr;
}
auto shared_data = std::make_shared<std::vector<uint8_t>>();
std::swap(*shared_data, data);
return std::make_shared<fml::NonOwnedMapping>(
shared_data->data(), shared_data->size(), [shared_data](auto, auto) {});
}
void PipelineCacheVK::PersistCacheToDisk() const {
if (!cache_directory_.is_valid()) {
return;
}
auto data = CopyPipelineCacheData();
if (!data) {
VALIDATION_LOG << "Could not copy pipeline cache data.";
return;
}
data = DecorateCacheWithMetadata(std::move(data));
if (!data) {
VALIDATION_LOG
<< "Could not decorate pipeline cache with additional metadata.";
return;
}
if (!fml::WriteAtomically(cache_directory_, kPipelineCacheFileName, *data)) {
VALIDATION_LOG << "Could not persist pipeline cache to disk.";
return;
}
}
const CapabilitiesVK* PipelineCacheVK::GetCapabilities() const {
return CapabilitiesVK::Cast(caps_.get());
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/pipeline_cache_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/pipeline_cache_vk.cc",
"repo_id": "engine",
"token_count": 2194
} | 253 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/sampler_library_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/sampler_vk.h"
namespace impeller {
SamplerLibraryVK::SamplerLibraryVK(
const std::weak_ptr<DeviceHolderVK>& device_holder)
: device_holder_(device_holder) {}
SamplerLibraryVK::~SamplerLibraryVK() = default;
static const std::unique_ptr<const Sampler> kNullSampler = nullptr;
const std::unique_ptr<const Sampler>& SamplerLibraryVK::GetSampler(
SamplerDescriptor desc) {
auto found = samplers_.find(desc);
if (found != samplers_.end()) {
return found->second;
}
auto device_holder = device_holder_.lock();
if (!device_holder || !device_holder->GetDevice()) {
return kNullSampler;
}
return (samplers_[desc] =
std::make_unique<SamplerVK>(device_holder->GetDevice(), desc));
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/sampler_library_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/sampler_library_vk.cc",
"repo_id": "engine",
"token_count": 407
} | 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.
#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h"
namespace impeller {
KHRSwapchainImageVK::KHRSwapchainImageVK(TextureDescriptor desc,
const vk::Device& device,
vk::Image image)
: TextureSourceVK(desc), image_(image) {
vk::ImageViewCreateInfo view_info;
view_info.image = image_;
view_info.viewType = vk::ImageViewType::e2D;
view_info.format = ToVKImageFormat(desc.format);
view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
view_info.subresourceRange.baseMipLevel = 0u;
view_info.subresourceRange.baseArrayLayer = 0u;
view_info.subresourceRange.levelCount = desc.mip_count;
view_info.subresourceRange.layerCount = ToArrayLayerCount(desc.type);
auto [view_result, view] = device.createImageViewUnique(view_info);
if (view_result != vk::Result::eSuccess) {
return;
}
image_view_ = std::move(view);
is_valid_ = true;
}
KHRSwapchainImageVK::~KHRSwapchainImageVK() = default;
bool KHRSwapchainImageVK::IsValid() const {
return is_valid_;
}
std::shared_ptr<Texture> KHRSwapchainImageVK::GetMSAATexture() const {
return msaa_texture_;
}
std::shared_ptr<Texture> KHRSwapchainImageVK::GetDepthStencilTexture() const {
return depth_stencil_texture_;
}
void KHRSwapchainImageVK::SetMSAATexture(std::shared_ptr<Texture> texture) {
msaa_texture_ = std::move(texture);
}
void KHRSwapchainImageVK::SetDepthStencilTexture(
std::shared_ptr<Texture> texture) {
depth_stencil_texture_ = std::move(texture);
}
PixelFormat KHRSwapchainImageVK::GetPixelFormat() const {
return desc_.format;
}
ISize KHRSwapchainImageVK::GetSize() const {
return desc_.size;
}
// |TextureSourceVK|
vk::Image KHRSwapchainImageVK::GetImage() const {
return image_;
}
// |TextureSourceVK|
vk::ImageView KHRSwapchainImageVK::GetImageView() const {
return image_view_.get();
}
// |TextureSourceVK|
vk::ImageView KHRSwapchainImageVK::GetRenderTargetView() const {
return image_view_.get();
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.cc",
"repo_id": "engine",
"token_count": 860
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TRACKED_OBJECTS_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TRACKED_OBJECTS_VK_H_
#include <memory>
#include "impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
namespace impeller {
/// @brief A per-frame object used to track resource lifetimes and allocate
/// command buffers and descriptor sets.
class TrackedObjectsVK {
public:
explicit TrackedObjectsVK(const std::weak_ptr<const ContextVK>& context,
const std::shared_ptr<CommandPoolVK>& pool,
std::unique_ptr<GPUProbe> probe);
~TrackedObjectsVK();
bool IsValid() const;
void Track(std::shared_ptr<SharedObjectVK> object);
void Track(std::shared_ptr<const DeviceBuffer> buffer);
bool IsTracking(const std::shared_ptr<const DeviceBuffer>& buffer) const;
void Track(std::shared_ptr<const TextureSourceVK> texture);
bool IsTracking(const std::shared_ptr<const TextureSourceVK>& texture) const;
vk::CommandBuffer GetCommandBuffer() const;
DescriptorPoolVK& GetDescriptorPool();
GPUProbe& GetGPUProbe() const;
private:
DescriptorPoolVK desc_pool_;
// `shared_ptr` since command buffers have a link to the command pool.
std::shared_ptr<CommandPoolVK> pool_;
vk::UniqueCommandBuffer buffer_;
std::set<std::shared_ptr<SharedObjectVK>> tracked_objects_;
std::set<std::shared_ptr<const DeviceBuffer>> tracked_buffers_;
std::set<std::shared_ptr<const TextureSourceVK>> tracked_textures_;
std::unique_ptr<GPUProbe> probe_;
bool is_valid_ = false;
TrackedObjectsVK(const TrackedObjectsVK&) = delete;
TrackedObjectsVK& operator=(const TrackedObjectsVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TRACKED_OBJECTS_VK_H_
| engine/impeller/renderer/backend/vulkan/tracked_objects_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/tracked_objects_vk.h",
"repo_id": "engine",
"token_count": 736
} | 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_RENDERER_CAPABILITIES_H_
#define FLUTTER_IMPELLER_RENDERER_CAPABILITIES_H_
#include <memory>
#include "flutter/fml/macros.h"
#include "impeller/core/formats.h"
namespace impeller {
class Capabilities {
public:
virtual ~Capabilities();
/// @brief Whether the context backend supports attaching offscreen MSAA
/// color/stencil textures.
virtual bool SupportsOffscreenMSAA() const = 0;
/// @brief Whether the context backend supports multisampled rendering to
/// the on-screen surface without requiring an explicit resolve of
/// the MSAA color attachment.
virtual bool SupportsImplicitResolvingMSAA() const = 0;
/// @brief Whether the context backend supports binding Shader Storage Buffer
/// Objects (SSBOs) to pipelines.
virtual bool SupportsSSBO() const = 0;
/// @brief Whether the context backend supports blitting from a given
/// `DeviceBuffer` view to a texture region (via the relevant
/// `BlitPass::AddCopy` overloads).
virtual bool SupportsBufferToTextureBlits() const = 0;
/// @brief Whether the context backend supports blitting from one texture
/// region to another texture region (via the relevant
/// `BlitPass::AddCopy` overloads).
virtual bool SupportsTextureToTextureBlits() const = 0;
/// @brief Whether the context backend is able to support pipelines with
/// shaders that read from the framebuffer (i.e. pixels that have been
/// written by previous draw calls in the current render pass).
///
/// Example of reading from the first color attachment in a GLSL
/// shader:
/// ```
/// uniform subpassInput subpass_input;
///
/// out vec4 frag_color;
///
/// void main() {
/// vec4 color = subpassLoad(subpass_input);
/// // Invert the colors drawn to the framebuffer.
/// frag_color = vec4(vec3(1) - color.rgb, color.a);
/// }
/// ```
virtual bool SupportsFramebufferFetch() const = 0;
/// @brief Whether the context backend supports `ComputePass`.
virtual bool SupportsCompute() const = 0;
/// @brief Whether the context backend supports configuring `ComputePass`
/// command subgroups.
virtual bool SupportsComputeSubgroups() const = 0;
/// @brief Whether the context backend supports binding the current
/// `RenderPass` attachments. This is supported if the backend can
/// guarantee that attachment textures will not be mutated until the
/// render pass has fully completed.
///
/// This is possible because many mobile graphics cards track
/// `RenderPass` attachment state in intermediary tile memory prior to
/// Storing the pass in the heap allocated attachments on DRAM.
/// Metal's hazard tracking and Vulkan's barriers are granular enough
/// to allow for safely accessing attachment textures prior to storage
/// in the same `RenderPass`.
virtual bool SupportsReadFromResolve() const = 0;
/// @brief Whether the context backend supports `SamplerAddressMode::Decal`.
virtual bool SupportsDecalSamplerAddressMode() const = 0;
/// @brief Whether the context backend supports allocating
/// `StorageMode::kDeviceTransient` (aka "memoryless") textures, which
/// are temporary textures kept in tile memory for the duration of the
/// `RenderPass` it's attached to.
///
/// This feature is especially useful for MSAA and stencils.
virtual bool SupportsDeviceTransientTextures() const = 0;
/// @brief Returns a supported `PixelFormat` for textures that store
/// 4-channel colors (red/green/blue/alpha).
virtual PixelFormat GetDefaultColorFormat() const = 0;
/// @brief Returns a supported `PixelFormat` for textures that store stencil
/// information. May include a depth channel if a stencil-only format
/// is not available.
virtual PixelFormat GetDefaultStencilFormat() const = 0;
/// @brief Returns a supported `PixelFormat` for textures that store both a
/// stencil and depth component. This will never return a depth-only
/// or stencil-only texture.
/// Returns `PixelFormat::kUnknown` if no suitable depth+stencil
/// format was found.
virtual PixelFormat GetDefaultDepthStencilFormat() const = 0;
/// @brief Returns the default pixel format for the alpha bitmap glyph atlas.
///
/// Some backends may use Red channel while others use grey. This
/// should not have any impact
virtual PixelFormat GetDefaultGlyphAtlasFormat() const = 0;
protected:
Capabilities();
Capabilities(const Capabilities&) = delete;
Capabilities& operator=(const Capabilities&) = delete;
};
class CapabilitiesBuilder {
public:
CapabilitiesBuilder();
~CapabilitiesBuilder();
CapabilitiesBuilder& SetSupportsOffscreenMSAA(bool value);
CapabilitiesBuilder& SetSupportsSSBO(bool value);
CapabilitiesBuilder& SetSupportsBufferToTextureBlits(bool value);
CapabilitiesBuilder& SetSupportsTextureToTextureBlits(bool value);
CapabilitiesBuilder& SetSupportsFramebufferFetch(bool value);
CapabilitiesBuilder& SetSupportsCompute(bool value);
CapabilitiesBuilder& SetSupportsComputeSubgroups(bool value);
CapabilitiesBuilder& SetSupportsReadFromResolve(bool value);
CapabilitiesBuilder& SetDefaultColorFormat(PixelFormat value);
CapabilitiesBuilder& SetDefaultStencilFormat(PixelFormat value);
CapabilitiesBuilder& SetDefaultDepthStencilFormat(PixelFormat value);
CapabilitiesBuilder& SetSupportsDecalSamplerAddressMode(bool value);
CapabilitiesBuilder& SetSupportsDeviceTransientTextures(bool value);
CapabilitiesBuilder& SetDefaultGlyphAtlasFormat(PixelFormat value);
std::unique_ptr<Capabilities> Build();
private:
bool supports_offscreen_msaa_ = false;
bool supports_ssbo_ = false;
bool supports_buffer_to_texture_blits_ = false;
bool supports_texture_to_texture_blits_ = false;
bool supports_framebuffer_fetch_ = false;
bool supports_compute_ = false;
bool supports_compute_subgroups_ = false;
bool supports_read_from_resolve_ = false;
bool supports_decal_sampler_address_mode_ = false;
bool supports_device_transient_textures_ = false;
std::optional<PixelFormat> default_color_format_ = std::nullopt;
std::optional<PixelFormat> default_stencil_format_ = std::nullopt;
std::optional<PixelFormat> default_depth_stencil_format_ = std::nullopt;
std::optional<PixelFormat> default_glyph_atlas_format_ = std::nullopt;
CapabilitiesBuilder(const CapabilitiesBuilder&) = delete;
CapabilitiesBuilder& operator=(const CapabilitiesBuilder&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_CAPABILITIES_H_
| engine/impeller/renderer/capabilities.h/0 | {
"file_path": "engine/impeller/renderer/capabilities.h",
"repo_id": "engine",
"token_count": 2194
} | 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_RENDERER_COMPUTE_TESSELLATOR_H_
#define FLUTTER_IMPELLER_RENDERER_COMPUTE_TESSELLATOR_H_
#include "flutter/fml/macros.h"
#include "impeller/core/buffer_view.h"
#include "impeller/geometry/path.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/context.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief A utility that generates triangles of the specified fill type
/// given a path.
///
class ComputeTessellator {
public:
ComputeTessellator();
~ComputeTessellator();
static constexpr size_t kMaxCubicCount = 512;
static constexpr size_t kMaxQuadCount = 2048;
static constexpr size_t kMaxLineCount = 4096;
static constexpr size_t kMaxComponentCount =
kMaxCubicCount + kMaxQuadCount + kMaxLineCount;
enum class Status {
kCommandInvalid,
kTooManyComponents,
kOk,
};
enum class Style {
kStroke,
// TODO(dnfield): Implement kFill.
};
ComputeTessellator& SetStyle(Style value);
ComputeTessellator& SetStrokeWidth(Scalar value);
ComputeTessellator& SetStrokeJoin(Join value);
ComputeTessellator& SetStrokeCap(Cap value);
ComputeTessellator& SetMiterLimit(Scalar value);
ComputeTessellator& SetCubicAccuracy(Scalar value);
ComputeTessellator& SetQuadraticTolerance(Scalar value);
//----------------------------------------------------------------------------
/// @brief Generates triangles from the path.
/// If the data needs to be synchronized back to the CPU, e.g.
/// because one of the buffer views are host visible and will be
/// used without creating a blit pass to copy them back, the
/// callback is used to determine when the GPU calculation is
/// complete and its status.
/// On Metal, no additional synchronization is needed as long as
/// the buffers are not heap allocated, so no additional
/// synchronization mechanism is provided.
///
/// @return A |Status| value indicating success or failure of the submission.
///
// TODO(dnfield): Provide additional synchronization methods here for Vulkan
// and heap allocated buffers on Metal.
Status Tessellate(
const Path& path,
HostBuffer& host_buffer,
const std::shared_ptr<Context>& context,
BufferView vertex_buffer,
BufferView vertex_buffer_count,
const CommandBuffer::CompletionCallback& callback = nullptr) const;
private:
Style style_ = Style::kStroke;
Scalar stroke_width_ = 1.0f;
Cap stroke_cap_ = Cap::kButt;
Join stroke_join_ = Join::kMiter;
Scalar miter_limit_ = 4.0f;
Scalar cubic_accuracy_ = kDefaultCurveTolerance;
Scalar quad_tolerance_ = .1f;
ComputeTessellator(const ComputeTessellator&) = delete;
ComputeTessellator& operator=(const ComputeTessellator&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_COMPUTE_TESSELLATOR_H_
| engine/impeller/renderer/compute_tessellator.h/0 | {
"file_path": "engine/impeller/renderer/compute_tessellator.h",
"repo_id": "engine",
"token_count": 1092
} | 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.
#include "gtest/gtest.h"
#include "impeller/renderer/pool.h"
namespace impeller {
namespace testing {
namespace {
class Foobar {
public:
static std::shared_ptr<Foobar> Create() { return std::make_shared<Foobar>(); }
size_t GetSize() const { return size_; }
void SetSize(size_t size) { size_ = size; }
void Reset() { is_reset_ = true; }
bool GetIsReset() const { return is_reset_; }
void SetIsReset(bool is_reset) { is_reset_ = is_reset; }
private:
size_t size_;
bool is_reset_ = false;
};
} // namespace
TEST(PoolTest, Simple) {
Pool<Foobar> pool(1'000);
{
auto grabbed = pool.Grab();
grabbed->SetSize(123);
pool.Recycle(grabbed);
EXPECT_EQ(pool.GetSize(), 123u);
}
auto grabbed = pool.Grab();
EXPECT_EQ(grabbed->GetSize(), 123u);
EXPECT_TRUE(grabbed->GetIsReset());
EXPECT_EQ(pool.GetSize(), 0u);
}
TEST(PoolTest, Overload) {
Pool<Foobar> pool(1'000);
{
std::vector<std::shared_ptr<Foobar>> values;
values.reserve(20);
for (int i = 0; i < 20; i++) {
values.push_back(pool.Grab());
}
for (const auto& value : values) {
value->SetSize(100);
pool.Recycle(value);
}
}
EXPECT_EQ(pool.GetSize(), 1'000u);
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/pool_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/pool_unittests.cc",
"repo_id": "engine",
"token_count": 564
} | 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/renderer/shader_library.h"
namespace impeller {
ShaderLibrary::ShaderLibrary() = default;
ShaderLibrary::~ShaderLibrary() = default;
void ShaderLibrary::RegisterFunction(
std::string name, // NOLINT(performance-unnecessary-value-param)
ShaderStage stage,
std::shared_ptr<fml::Mapping>
code, // NOLINT(performance-unnecessary-value-param)
RegistrationCallback
callback) { // NOLINT(performance-unnecessary-value-param)
if (callback) {
callback(false);
}
}
} // namespace impeller
| engine/impeller/renderer/shader_library.cc/0 | {
"file_path": "engine/impeller/renderer/shader_library.cc",
"repo_id": "engine",
"token_count": 237
} | 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.
#include "impeller/runtime_stage/runtime_stage.h"
#include <array>
#include <memory>
#include "fml/mapping.h"
#include "impeller/base/validation.h"
#include "impeller/core/runtime_types.h"
#include "impeller/runtime_stage/runtime_stage_flatbuffers.h"
#include "runtime_stage_types_flatbuffers.h"
namespace impeller {
static RuntimeUniformType ToType(fb::UniformDataType type) {
switch (type) {
case fb::UniformDataType::kFloat:
return RuntimeUniformType::kFloat;
case fb::UniformDataType::kSampledImage:
return RuntimeUniformType::kSampledImage;
case fb::UniformDataType::kStruct:
return RuntimeUniformType::kStruct;
}
FML_UNREACHABLE();
}
static RuntimeShaderStage ToShaderStage(fb::Stage stage) {
switch (stage) {
case fb::Stage::kVertex:
return RuntimeShaderStage::kVertex;
case fb::Stage::kFragment:
return RuntimeShaderStage::kFragment;
case fb::Stage::kCompute:
return RuntimeShaderStage::kCompute;
}
FML_UNREACHABLE();
}
/// The generated name from GLSLang/shaderc for the UBO containing non-opaque
/// uniforms specified in the user-written runtime effect shader.
///
/// Vulkan does not allow non-opaque uniforms outside of a UBO.
const char* RuntimeStage::kVulkanUBOName =
"_RESERVED_IDENTIFIER_FIXUP_gl_DefaultUniformBlock";
std::unique_ptr<RuntimeStage> RuntimeStage::RuntimeStageIfPresent(
const fb::RuntimeStage* runtime_stage,
const std::shared_ptr<fml::Mapping>& payload) {
if (!runtime_stage) {
return nullptr;
}
return std::unique_ptr<RuntimeStage>(
new RuntimeStage(runtime_stage, payload));
}
RuntimeStage::Map RuntimeStage::DecodeRuntimeStages(
const std::shared_ptr<fml::Mapping>& payload) {
if (payload == nullptr || !payload->GetMapping()) {
return {};
}
if (!fb::RuntimeStagesBufferHasIdentifier(payload->GetMapping())) {
return {};
}
auto raw_stages = fb::GetRuntimeStages(payload->GetMapping());
return {
{RuntimeStageBackend::kSkSL,
RuntimeStageIfPresent(raw_stages->sksl(), payload)},
{RuntimeStageBackend::kMetal,
RuntimeStageIfPresent(raw_stages->metal(), payload)},
{RuntimeStageBackend::kOpenGLES,
RuntimeStageIfPresent(raw_stages->opengles(), payload)},
{RuntimeStageBackend::kVulkan,
RuntimeStageIfPresent(raw_stages->vulkan(), payload)},
};
}
RuntimeStage::RuntimeStage(const fb::RuntimeStage* runtime_stage,
const std::shared_ptr<fml::Mapping>& payload)
: payload_(payload) {
FML_DCHECK(runtime_stage);
stage_ = ToShaderStage(runtime_stage->stage());
entrypoint_ = runtime_stage->entrypoint()->str();
auto* uniforms = runtime_stage->uniforms();
if (uniforms) {
for (auto i = uniforms->begin(), end = uniforms->end(); i != end; i++) {
RuntimeUniformDescription desc;
desc.name = i->name()->str();
desc.location = i->location();
desc.type = ToType(i->type());
desc.dimensions = RuntimeUniformDimensions{
static_cast<size_t>(i->rows()), static_cast<size_t>(i->columns())};
desc.bit_width = i->bit_width();
desc.array_elements = i->array_elements();
if (i->struct_layout()) {
for (const auto& byte_type : *i->struct_layout()) {
desc.struct_layout.push_back(static_cast<uint8_t>(byte_type));
}
}
desc.struct_float_count = i->struct_float_count();
uniforms_.emplace_back(std::move(desc));
}
}
code_mapping_ = std::make_shared<fml::NonOwnedMapping>(
runtime_stage->shader()->data(), //
runtime_stage->shader()->size(), //
[payload = payload_](auto, auto) {} //
);
is_valid_ = true;
}
RuntimeStage::~RuntimeStage() = default;
RuntimeStage::RuntimeStage(RuntimeStage&&) = default;
RuntimeStage& RuntimeStage::operator=(RuntimeStage&&) = default;
bool RuntimeStage::IsValid() const {
return is_valid_;
}
const std::shared_ptr<fml::Mapping>& RuntimeStage::GetCodeMapping() const {
return code_mapping_;
}
const std::vector<RuntimeUniformDescription>& RuntimeStage::GetUniforms()
const {
return uniforms_;
}
const RuntimeUniformDescription* RuntimeStage::GetUniform(
const std::string& name) const {
for (const auto& uniform : uniforms_) {
if (uniform.name == name) {
return &uniform;
}
}
return nullptr;
}
const std::string& RuntimeStage::GetEntrypoint() const {
return entrypoint_;
}
RuntimeShaderStage RuntimeStage::GetShaderStage() const {
return stage_;
}
bool RuntimeStage::IsDirty() const {
return is_dirty_;
}
void RuntimeStage::SetClean() {
is_dirty_ = false;
}
} // namespace impeller
| engine/impeller/runtime_stage/runtime_stage.cc/0 | {
"file_path": "engine/impeller/runtime_stage/runtime_stage.cc",
"repo_id": "engine",
"token_count": 1779
} | 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/scene/animation/property_resolver.h"
#include <algorithm>
#include <iterator>
#include <memory>
#include "impeller/geometry/matrix_decomposition.h"
#include "impeller/geometry/point.h"
#include "impeller/scene/node.h"
namespace impeller {
namespace scene {
std::unique_ptr<TranslationTimelineResolver>
PropertyResolver::MakeTranslationTimeline(std::vector<Scalar> times,
std::vector<Vector3> values) {
FML_DCHECK(times.size() == values.size());
auto result = std::unique_ptr<TranslationTimelineResolver>(
new TranslationTimelineResolver());
result->times_ = std::move(times);
result->values_ = std::move(values);
return result;
}
std::unique_ptr<RotationTimelineResolver>
PropertyResolver::MakeRotationTimeline(std::vector<Scalar> times,
std::vector<Quaternion> values) {
FML_DCHECK(times.size() == values.size());
auto result =
std::unique_ptr<RotationTimelineResolver>(new RotationTimelineResolver());
result->times_ = std::move(times);
result->values_ = std::move(values);
return result;
}
std::unique_ptr<ScaleTimelineResolver> PropertyResolver::MakeScaleTimeline(
std::vector<Scalar> times,
std::vector<Vector3> values) {
FML_DCHECK(times.size() == values.size());
auto result =
std::unique_ptr<ScaleTimelineResolver>(new ScaleTimelineResolver());
result->times_ = std::move(times);
result->values_ = std::move(values);
return result;
}
PropertyResolver::~PropertyResolver() = default;
TimelineResolver::~TimelineResolver() = default;
SecondsF TimelineResolver::GetEndTime() {
if (times_.empty()) {
return SecondsF::zero();
}
return SecondsF(times_.back());
}
TimelineResolver::TimelineKey TimelineResolver::GetTimelineKey(SecondsF time) {
if (times_.size() <= 1 || time.count() <= times_.front()) {
return {.index = 0, .lerp = 1};
}
if (time.count() >= times_.back()) {
return {.index = times_.size() - 1, .lerp = 1};
}
auto it = std::lower_bound(times_.begin(), times_.end(), time.count());
size_t index = std::distance(times_.begin(), it);
Scalar previous_time = *(it - 1);
Scalar next_time = *it;
return {.index = index,
.lerp = (time.count() - previous_time) / (next_time - previous_time)};
}
TranslationTimelineResolver::TranslationTimelineResolver() = default;
TranslationTimelineResolver::~TranslationTimelineResolver() = default;
void TranslationTimelineResolver::Apply(AnimationTransforms& target,
SecondsF time,
Scalar weight) {
if (values_.empty()) {
return;
}
auto key = GetTimelineKey(time);
auto value = values_[key.index];
if (key.lerp < 1) {
value = values_[key.index - 1].Lerp(value, key.lerp);
}
target.animated_pose.translation +=
(value - target.bind_pose.translation) * weight;
}
RotationTimelineResolver::RotationTimelineResolver() = default;
RotationTimelineResolver::~RotationTimelineResolver() = default;
void RotationTimelineResolver::Apply(AnimationTransforms& target,
SecondsF time,
Scalar weight) {
if (values_.empty()) {
return;
}
auto key = GetTimelineKey(time);
auto value = values_[key.index];
if (key.lerp < 1) {
value = values_[key.index - 1].Slerp(value, key.lerp);
}
target.animated_pose.rotation =
target.animated_pose.rotation *
Quaternion().Slerp(target.bind_pose.rotation.Invert() * value, weight);
}
ScaleTimelineResolver::ScaleTimelineResolver() = default;
ScaleTimelineResolver::~ScaleTimelineResolver() = default;
void ScaleTimelineResolver::Apply(AnimationTransforms& target,
SecondsF time,
Scalar weight) {
if (values_.empty()) {
return;
}
auto key = GetTimelineKey(time);
auto value = values_[key.index];
if (key.lerp < 1) {
value = values_[key.index - 1].Lerp(value, key.lerp);
}
target.animated_pose.scale *=
Vector3(1, 1, 1).Lerp(value / target.bind_pose.scale, weight);
}
} // namespace scene
} // namespace impeller
| engine/impeller/scene/animation/property_resolver.cc/0 | {
"file_path": "engine/impeller/scene/animation/property_resolver.cc",
"repo_id": "engine",
"token_count": 1712
} | 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_SCENE_IMPORTER_TYPES_H_
#define FLUTTER_IMPELLER_SCENE_IMPORTER_TYPES_H_
namespace impeller {
namespace scene {
namespace importer {
enum class SourceType {
kUnknown,
kGLTF,
};
} // namespace importer
} // namespace scene
} // namespace impeller
#endif // FLUTTER_IMPELLER_SCENE_IMPORTER_TYPES_H_
| engine/impeller/scene/importer/types.h/0 | {
"file_path": "engine/impeller/scene/importer/types.h",
"repo_id": "engine",
"token_count": 181
} | 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.
#include <cmath>
#include <memory>
#include <vector>
#include "flutter/fml/mapping.h"
#include "flutter/testing/testing.h"
#include "impeller/core/formats.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/constants.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/quaternion.h"
#include "impeller/geometry/vector.h"
#include "impeller/playground/image/decompressed_image.h"
#include "impeller/playground/playground.h"
#include "impeller/playground/playground_test.h"
#include "impeller/scene/animation/animation_clip.h"
#include "impeller/scene/camera.h"
#include "impeller/scene/geometry.h"
#include "impeller/scene/importer/scene_flatbuffers.h"
#include "impeller/scene/material.h"
#include "impeller/scene/mesh.h"
#include "impeller/scene/scene.h"
#include "third_party/flatbuffers/include/flatbuffers/verifier.h"
#include "third_party/imgui/imgui.h"
namespace impeller {
namespace scene {
namespace testing {
using SceneTest = PlaygroundTest;
INSTANTIATE_PLAYGROUND_SUITE(SceneTest);
TEST_P(SceneTest, CuboidUnlit) {
auto scene_context = std::make_shared<SceneContext>(GetContext());
Renderer::RenderCallback callback = [&](RenderTarget& render_target) {
auto allocator = GetContext()->GetResourceAllocator();
auto scene = Scene(scene_context);
{
Mesh mesh;
auto material = Material::MakeUnlit();
material->SetColor(Color::Red());
Vector3 size(1, 1, 0);
mesh.AddPrimitive({Geometry::MakeCuboid(size), std::move(material)});
Node& root = scene.GetRoot();
root.SetLocalTransform(Matrix::MakeTranslation(-size / 2));
root.SetMesh(std::move(mesh));
}
// Face towards the +Z direction (+X right, +Y up).
auto camera = Camera::MakePerspective(
/* fov */ Radians(kPiOver4),
/* position */ {2, 2, -5})
.LookAt(
/* target */ Vector3(),
/* up */ {0, 1, 0});
scene.Render(render_target, camera);
return true;
};
OpenPlaygroundHere(callback);
}
TEST_P(SceneTest, FlutterLogo) {
auto allocator = GetContext()->GetResourceAllocator();
auto mapping =
flutter::testing::OpenFixtureAsMapping("flutter_logo_baked.glb.ipscene");
ASSERT_NE(mapping, nullptr);
flatbuffers::Verifier verifier(mapping->GetMapping(), mapping->GetSize());
ASSERT_TRUE(fb::VerifySceneBuffer(verifier));
std::shared_ptr<Node> gltf_scene =
Node::MakeFromFlatbuffer(*mapping, *allocator);
ASSERT_NE(gltf_scene, nullptr);
ASSERT_EQ(gltf_scene->GetChildren().size(), 1u);
ASSERT_EQ(gltf_scene->GetChildren()[0]->GetMesh().GetPrimitives().size(), 1u);
auto scene_context = std::make_shared<SceneContext>(GetContext());
auto scene = Scene(scene_context);
scene.GetRoot().AddChild(std::move(gltf_scene));
scene.GetRoot().SetLocalTransform(Matrix::MakeScale({3, 3, 3}));
Renderer::RenderCallback callback = [&](RenderTarget& render_target) {
Quaternion rotation({0, 1, 0}, -GetSecondsElapsed() * 0.5);
Vector3 start_position(-1, -1.5, -5);
// Face towards the +Z direction (+X right, +Y up).
auto camera = Camera::MakePerspective(
/* fov */ Degrees(60),
/* position */ rotation * start_position)
.LookAt(
/* target */ Vector3(),
/* up */ {0, 1, 0});
scene.Render(render_target, camera);
return true;
};
OpenPlaygroundHere(callback);
}
TEST_P(SceneTest, TwoTriangles) {
if (GetBackend() == PlaygroundBackend::kVulkan) {
GTEST_SKIP_("Temporarily disabled.");
}
auto allocator = GetContext()->GetResourceAllocator();
auto mapping =
flutter::testing::OpenFixtureAsMapping("two_triangles.glb.ipscene");
ASSERT_NE(mapping, nullptr);
std::shared_ptr<Node> gltf_scene =
Node::MakeFromFlatbuffer(*mapping, *allocator);
ASSERT_NE(gltf_scene, nullptr);
auto animation = gltf_scene->FindAnimationByName("Metronome");
ASSERT_NE(animation, nullptr);
AnimationClip* metronome_clip = gltf_scene->AddAnimation(animation);
ASSERT_NE(metronome_clip, nullptr);
metronome_clip->SetLoop(true);
metronome_clip->Play();
auto scene_context = std::make_shared<SceneContext>(GetContext());
auto scene = Scene(scene_context);
scene.GetRoot().AddChild(std::move(gltf_scene));
Renderer::RenderCallback callback = [&](RenderTarget& render_target) {
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
{
static Scalar playback_time_scale = 1;
static Scalar weight = 1;
static bool loop = true;
ImGui::SliderFloat("Playback time scale", &playback_time_scale, -5, 5);
ImGui::SliderFloat("Weight", &weight, -2, 2);
ImGui::Checkbox("Loop", &loop);
if (ImGui::Button("Play")) {
metronome_clip->Play();
}
if (ImGui::Button("Pause")) {
metronome_clip->Pause();
}
if (ImGui::Button("Stop")) {
metronome_clip->Stop();
}
metronome_clip->SetPlaybackTimeScale(playback_time_scale);
metronome_clip->SetWeight(weight);
metronome_clip->SetLoop(loop);
}
ImGui::End();
Node& node = *scene.GetRoot().GetChildren()[0];
node.SetLocalTransform(node.GetLocalTransform() *
Matrix::MakeRotation(0.02, {0, 1, 0, 0}));
static ImVec2 mouse_pos_prev = ImGui::GetMousePos();
ImVec2 mouse_pos = ImGui::GetMousePos();
Vector2 mouse_diff =
Vector2(mouse_pos.x - mouse_pos_prev.x, mouse_pos.y - mouse_pos_prev.y);
static Vector3 position(0, 1, -5);
static Vector3 cam_position = position;
auto strafe =
Vector3(ImGui::IsKeyDown(ImGuiKey_D) - ImGui::IsKeyDown(ImGuiKey_A),
ImGui::IsKeyDown(ImGuiKey_E) - ImGui::IsKeyDown(ImGuiKey_Q),
ImGui::IsKeyDown(ImGuiKey_W) - ImGui::IsKeyDown(ImGuiKey_S));
position += strafe * 0.5;
cam_position = cam_position.Lerp(position, 0.02);
// Face towards the +Z direction (+X right, +Y up).
auto camera = Camera::MakePerspective(
/* fov */ Degrees(60),
/* position */ cam_position)
.LookAt(
/* target */ cam_position + Vector3(0, 0, 1),
/* up */ {0, 1, 0});
scene.Render(render_target, camera);
return true;
};
OpenPlaygroundHere(callback);
}
TEST_P(SceneTest, Dash) {
auto allocator = GetContext()->GetResourceAllocator();
auto mapping = flutter::testing::OpenFixtureAsMapping("dash.glb.ipscene");
if (!mapping) {
// TODO(bdero): Just skip this playground is the dash asset isn't found. I
// haven't checked it in because it's way too big right now,
// but this is still useful to keep around for debugging
// purposes.
return;
}
ASSERT_NE(mapping, nullptr);
std::shared_ptr<Node> gltf_scene =
Node::MakeFromFlatbuffer(*mapping, *allocator);
ASSERT_NE(gltf_scene, nullptr);
auto walk_anim = gltf_scene->FindAnimationByName("Walk");
ASSERT_NE(walk_anim, nullptr);
AnimationClip* walk_clip = gltf_scene->AddAnimation(walk_anim);
ASSERT_NE(walk_clip, nullptr);
walk_clip->SetLoop(true);
walk_clip->Play();
auto run_anim = gltf_scene->FindAnimationByName("Run");
ASSERT_NE(walk_anim, nullptr);
AnimationClip* run_clip = gltf_scene->AddAnimation(run_anim);
ASSERT_NE(run_clip, nullptr);
run_clip->SetLoop(true);
run_clip->Play();
auto scene_context = std::make_shared<SceneContext>(GetContext());
auto scene = Scene(scene_context);
scene.GetRoot().AddChild(std::move(gltf_scene));
Renderer::RenderCallback callback = [&](RenderTarget& render_target) {
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
{
static Scalar playback_time_scale = 1;
static Scalar walk = 0.5;
static Scalar run = 0.5;
static bool loop = true;
ImGui::SliderFloat("Playback time scale", &playback_time_scale, -5, 5);
ImGui::SliderFloat("Walk weight", &walk, 0, 1);
ImGui::SliderFloat("Run weight", &run, 0, 1);
ImGui::Checkbox("Loop", &loop);
if (ImGui::Button("Play")) {
walk_clip->Play();
run_clip->Play();
}
if (ImGui::Button("Pause")) {
walk_clip->Pause();
run_clip->Pause();
}
if (ImGui::Button("Stop")) {
walk_clip->Stop();
run_clip->Stop();
}
walk_clip->SetPlaybackTimeScale(playback_time_scale);
walk_clip->SetWeight(walk);
walk_clip->SetLoop(loop);
run_clip->SetPlaybackTimeScale(playback_time_scale);
run_clip->SetWeight(run);
run_clip->SetLoop(loop);
}
ImGui::End();
Node& node = *scene.GetRoot().GetChildren()[0];
node.SetLocalTransform(node.GetLocalTransform() *
Matrix::MakeRotation(0.02, {0, 1, 0, 0}));
static ImVec2 mouse_pos_prev = ImGui::GetMousePos();
ImVec2 mouse_pos = ImGui::GetMousePos();
Vector2 mouse_diff =
Vector2(mouse_pos.x - mouse_pos_prev.x, mouse_pos.y - mouse_pos_prev.y);
static Vector3 position(0, 1, -5);
static Vector3 cam_position = position;
auto strafe =
Vector3(ImGui::IsKeyDown(ImGuiKey_D) - ImGui::IsKeyDown(ImGuiKey_A),
ImGui::IsKeyDown(ImGuiKey_E) - ImGui::IsKeyDown(ImGuiKey_Q),
ImGui::IsKeyDown(ImGuiKey_W) - ImGui::IsKeyDown(ImGuiKey_S));
position += strafe * 0.5;
cam_position = cam_position.Lerp(position, 0.02);
// Face towards the +Z direction (+X right, +Y up).
auto camera = Camera::MakePerspective(
/* fov */ Degrees(60),
/* position */ cam_position)
.LookAt(
/* target */ cam_position + Vector3(0, 0, 1),
/* up */ {0, 1, 0});
scene.Render(render_target, camera);
return true;
};
OpenPlaygroundHere(callback);
}
} // namespace testing
} // namespace scene
} // namespace impeller
| engine/impeller/scene/scene_unittests.cc/0 | {
"file_path": "engine/impeller/scene/scene_unittests.cc",
"repo_id": "engine",
"token_count": 4365
} | 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 <filesystem>
#include <iostream>
#include "flutter/fml/command_line.h"
#include "impeller/shader_archive/shader_archive_writer.h"
namespace impeller {
bool Main(const fml::CommandLine& command_line) {
ShaderArchiveWriter writer;
std::string output;
if (!command_line.GetOptionValue("output", &output)) {
std::cerr << "Output path not specified." << std::endl;
return false;
}
for (const auto& input : command_line.GetOptionValues("input")) {
if (!writer.AddShaderAtPath(std::string{input})) {
std::cerr << "Could not add shader at path: " << input << std::endl;
return false;
}
}
auto archive = writer.CreateMapping();
if (!archive) {
std::cerr << "Could not create shader archive." << std::endl;
return false;
}
auto current_directory =
fml::OpenDirectory(std::filesystem::current_path().string().c_str(),
false, fml::FilePermission::kReadWrite);
auto output_path =
std::filesystem::absolute(std::filesystem::current_path() / output);
if (!fml::WriteAtomically(current_directory, output_path.string().c_str(),
*archive)) {
std::cerr << "Could not write shader archive to path " << output
<< std::endl;
return false;
}
return true;
}
} // namespace impeller
int main(int argc, char const* argv[]) {
return impeller::Main(fml::CommandLineFromPlatformOrArgcArgv(argc, argv))
? EXIT_SUCCESS
: EXIT_FAILURE;
}
| engine/impeller/shader_archive/shader_archive_main.cc/0 | {
"file_path": "engine/impeller/shader_archive/shader_archive_main.cc",
"repo_id": "engine",
"token_count": 633
} | 265 |
Android Toolkit
===============
Type-safe managed wrappers around Android objects vended by the NDK. Does not
require linking to libandroid.so. The symbols are resolved via dynamic runtime
lookup so that the toolkit can be built with an older NDK but still run on
modern Android versions and use the latest features.
| engine/impeller/toolkit/android/README.md/0 | {
"file_path": "engine/impeller/toolkit/android/README.md",
"repo_id": "engine",
"token_count": 73
} | 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.
#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_CONFIG_H_
#define FLUTTER_IMPELLER_TOOLKIT_EGL_CONFIG_H_
#include "flutter/fml/macros.h"
#include "impeller/toolkit/egl/egl.h"
namespace impeller {
namespace egl {
enum class API {
kOpenGL,
kOpenGLES2,
kOpenGLES3,
};
enum class Samples {
kOne = 1,
kTwo = 2,
kFour = 4,
};
enum class ColorFormat {
kRGBA8888,
kRGB565,
};
enum class StencilBits {
kZero = 0,
kEight = 8,
};
enum class DepthBits {
kZero = 0,
kEight = 8,
};
enum class SurfaceType {
kWindow,
kPBuffer,
};
struct ConfigDescriptor {
API api = API::kOpenGLES2;
Samples samples = Samples::kOne;
ColorFormat color_format = ColorFormat::kRGB565;
StencilBits stencil_bits = StencilBits::kZero;
DepthBits depth_bits = DepthBits::kZero;
SurfaceType surface_type = SurfaceType::kPBuffer;
};
class Config {
public:
Config(ConfigDescriptor descriptor, EGLConfig config);
~Config();
bool IsValid() const;
const ConfigDescriptor& GetDescriptor() const;
const EGLConfig& GetHandle() const;
private:
const ConfigDescriptor desc_;
EGLConfig config_ = nullptr;
Config(const Config&) = delete;
Config& operator=(const Config&) = delete;
};
} // namespace egl
} // namespace impeller
#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_CONFIG_H_
| engine/impeller/toolkit/egl/config.h/0 | {
"file_path": "engine/impeller/toolkit/egl/config.h",
"repo_id": "engine",
"token_count": 552
} | 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 sys
import argparse
import errno
import os
import subprocess
def make_directories(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--output', type=str, required=True, help='The location to generate the Metal library to.'
)
parser.add_argument('--depfile', type=str, required=True, help='The location of the depfile.')
parser.add_argument(
'--source',
type=str,
action='append',
required=True,
help='The source file to compile. Can be specified multiple times.'
)
parser.add_argument(
'--platform',
required=True,
choices=['mac', 'ios', 'ios-simulator'],
help='Select the platform.'
)
parser.add_argument(
'--metal-version', required=True, help='The language standard version to compile for.'
)
args = parser.parse_args()
make_directories(os.path.dirname(args.depfile))
command = [
'xcrun',
]
# Select the SDK.
command += ['-sdk']
if args.platform == 'mac':
command += [
'macosx',
]
elif args.platform == 'ios':
command += [
'iphoneos',
]
elif args.platform == 'ios-simulator':
command += [
'iphonesimulator',
]
else:
raise 'Unknown target platform'
command += [
'metal',
# These warnings are from generated code and would make no sense to the
# GLSL author.
'-Wno-unused-variable',
# Both user and system header will be tracked.
'-MMD',
# Like -Os (and thus -O2), but reduces code size further.
'-Oz',
# Allow aggressive, lossy floating-point optimizations.
'-ffast-math',
# Record symbols in a separate *.metallibsym file.
'-frecord-sources=flat',
'-MF',
args.depfile,
'-o',
args.output,
]
# Select the Metal standard and the minimum supported OS versions.
# The Metal standard must match the specification in impellerc.
if args.platform == 'mac':
command += [
'--std=macos-metal%s' % args.metal_version,
'-mmacos-version-min=10.14',
]
elif args.platform == 'ios':
command += [
'--std=ios-metal%s' % args.metal_version,
'-mios-version-min=11.0',
]
elif args.platform == 'ios-simulator':
command += [
'--std=ios-metal%s' % args.metal_version,
'-miphonesimulator-version-min=11.0',
]
else:
raise 'Unknown target platform'
command += args.source
try:
subprocess.check_output(command, stderr=subprocess.STDOUT, text=True)
except subprocess.CalledProcessError as cpe:
print(cpe.output)
return cpe.returncode
return 0
if __name__ == '__main__':
if sys.platform != 'darwin':
raise Exception('This script only runs on Mac')
sys.exit(main())
| engine/impeller/tools/build_metal_library.py/0 | {
"file_path": "engine/impeller/tools/build_metal_library.py",
"repo_id": "engine",
"token_count": 1199
} | 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.
#include "impeller/typographer/backends/skia/typographer_context_skia.h"
#include <numeric>
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/allocation.h"
#include "impeller/core/allocator.h"
#include "impeller/typographer/backends/skia/glyph_atlas_context_skia.h"
#include "impeller/typographer/backends/skia/typeface_skia.h"
#include "impeller/typographer/rectangle_packer.h"
#include "impeller/typographer/typographer_context.h"
#include "include/core/SkColor.h"
#include "include/core/SkSize.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkFont.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace impeller {
// TODO(bdero): We might be able to remove this per-glyph padding if we fix
// the underlying causes of the overlap.
// https://github.com/flutter/flutter/issues/114563
constexpr auto kPadding = 2;
std::shared_ptr<TypographerContext> TypographerContextSkia::Make() {
return std::make_shared<TypographerContextSkia>();
}
TypographerContextSkia::TypographerContextSkia() = default;
TypographerContextSkia::~TypographerContextSkia() = default;
std::shared_ptr<GlyphAtlasContext>
TypographerContextSkia::CreateGlyphAtlasContext() const {
return std::make_shared<GlyphAtlasContextSkia>();
}
static size_t PairsFitInAtlasOfSize(
const std::vector<FontGlyphPair>& pairs,
const ISize& atlas_size,
std::vector<Rect>& glyph_positions,
const std::shared_ptr<RectanglePacker>& rect_packer) {
if (atlas_size.IsEmpty()) {
return false;
}
glyph_positions.clear();
glyph_positions.reserve(pairs.size());
size_t i = 0;
for (auto it = pairs.begin(); it != pairs.end(); ++i, ++it) {
const auto& pair = *it;
const auto glyph_size =
ISize::Ceil(pair.glyph.bounds.GetSize() * pair.scaled_font.scale);
IPoint16 location_in_atlas;
if (!rect_packer->addRect(glyph_size.width + kPadding, //
glyph_size.height + kPadding, //
&location_in_atlas //
)) {
return pairs.size() - i;
}
glyph_positions.emplace_back(Rect::MakeXYWH(location_in_atlas.x(), //
location_in_atlas.y(), //
glyph_size.width, //
glyph_size.height //
));
}
return 0;
}
static bool CanAppendToExistingAtlas(
const std::shared_ptr<GlyphAtlas>& atlas,
const std::vector<FontGlyphPair>& extra_pairs,
std::vector<Rect>& glyph_positions,
ISize atlas_size,
const std::shared_ptr<RectanglePacker>& rect_packer) {
TRACE_EVENT0("impeller", __FUNCTION__);
if (!rect_packer || atlas_size.IsEmpty()) {
return false;
}
// We assume that all existing glyphs will fit. After all, they fit before.
// The glyph_positions only contains the values for the additional glyphs
// from extra_pairs.
FML_DCHECK(glyph_positions.size() == 0);
glyph_positions.reserve(extra_pairs.size());
for (size_t i = 0; i < extra_pairs.size(); i++) {
const FontGlyphPair& pair = extra_pairs[i];
const auto glyph_size =
ISize::Ceil(pair.glyph.bounds.GetSize() * pair.scaled_font.scale);
IPoint16 location_in_atlas;
if (!rect_packer->addRect(glyph_size.width + kPadding, //
glyph_size.height + kPadding, //
&location_in_atlas //
)) {
return false;
}
glyph_positions.emplace_back(Rect::MakeXYWH(location_in_atlas.x(), //
location_in_atlas.y(), //
glyph_size.width, //
glyph_size.height //
));
}
return true;
}
static ISize OptimumAtlasSizeForFontGlyphPairs(
const std::vector<FontGlyphPair>& pairs,
std::vector<Rect>& glyph_positions,
const std::shared_ptr<GlyphAtlasContext>& atlas_context,
GlyphAtlas::Type type,
const ISize& max_texture_size) {
static constexpr auto kMinAtlasSize = 8u;
static constexpr auto kMinAlphaBitmapSize = 1024u;
TRACE_EVENT0("impeller", __FUNCTION__);
ISize current_size = type == GlyphAtlas::Type::kAlphaBitmap
? ISize(kMinAlphaBitmapSize, kMinAlphaBitmapSize)
: ISize(kMinAtlasSize, kMinAtlasSize);
size_t total_pairs = pairs.size() + 1;
do {
auto rect_packer = std::shared_ptr<RectanglePacker>(
RectanglePacker::Factory(current_size.width, current_size.height));
auto remaining_pairs = PairsFitInAtlasOfSize(pairs, current_size,
glyph_positions, rect_packer);
if (remaining_pairs == 0) {
atlas_context->UpdateRectPacker(rect_packer);
return current_size;
} else if (remaining_pairs < std::ceil(total_pairs / 2)) {
current_size = ISize::MakeWH(
std::max(current_size.width, current_size.height),
Allocation::NextPowerOfTwoSize(
std::min(current_size.width, current_size.height) + 1));
} else {
current_size = ISize::MakeWH(
Allocation::NextPowerOfTwoSize(current_size.width + 1),
Allocation::NextPowerOfTwoSize(current_size.height + 1));
}
} while (current_size.width <= max_texture_size.width &&
current_size.height <= max_texture_size.height);
return ISize{0, 0};
}
static void DrawGlyph(SkCanvas* canvas,
const ScaledFont& scaled_font,
const Glyph& glyph,
const Rect& location,
bool has_color) {
const auto& metrics = scaled_font.font.GetMetrics();
const auto position = SkPoint::Make(location.GetX() / scaled_font.scale,
location.GetY() / scaled_font.scale);
SkGlyphID glyph_id = glyph.index;
SkFont sk_font(
TypefaceSkia::Cast(*scaled_font.font.GetTypeface()).GetSkiaTypeface(),
metrics.point_size, metrics.scaleX, metrics.skewX);
sk_font.setEdging(SkFont::Edging::kAntiAlias);
sk_font.setHinting(SkFontHinting::kSlight);
sk_font.setEmbolden(metrics.embolden);
auto glyph_color = has_color ? SK_ColorWHITE : SK_ColorBLACK;
SkPaint glyph_paint;
glyph_paint.setColor(glyph_color);
canvas->resetMatrix();
canvas->scale(scaled_font.scale, scaled_font.scale);
canvas->drawGlyphs(1u, // count
&glyph_id, // glyphs
&position, // positions
SkPoint::Make(-glyph.bounds.GetLeft(),
-glyph.bounds.GetTop()), // origin
sk_font, // font
glyph_paint // paint
);
}
static bool UpdateAtlasBitmap(const GlyphAtlas& atlas,
const std::shared_ptr<SkBitmap>& bitmap,
const std::vector<FontGlyphPair>& new_pairs) {
TRACE_EVENT0("impeller", __FUNCTION__);
FML_DCHECK(bitmap != nullptr);
auto surface = SkSurfaces::WrapPixels(bitmap->pixmap());
if (!surface) {
return false;
}
auto canvas = surface->getCanvas();
if (!canvas) {
return false;
}
bool has_color = atlas.GetType() == GlyphAtlas::Type::kColorBitmap;
for (const FontGlyphPair& pair : new_pairs) {
auto pos = atlas.FindFontGlyphBounds(pair);
if (!pos.has_value()) {
continue;
}
DrawGlyph(canvas, pair.scaled_font, pair.glyph, pos.value(), has_color);
}
return true;
}
static std::shared_ptr<SkBitmap> CreateAtlasBitmap(const GlyphAtlas& atlas,
const ISize& atlas_size) {
TRACE_EVENT0("impeller", __FUNCTION__);
auto bitmap = std::make_shared<SkBitmap>();
SkImageInfo image_info;
switch (atlas.GetType()) {
case GlyphAtlas::Type::kAlphaBitmap:
image_info =
SkImageInfo::MakeA8(SkISize{static_cast<int32_t>(atlas_size.width),
static_cast<int32_t>(atlas_size.height)});
break;
case GlyphAtlas::Type::kColorBitmap:
image_info =
SkImageInfo::MakeN32Premul(atlas_size.width, atlas_size.height);
break;
}
if (!bitmap->tryAllocPixels(image_info)) {
return nullptr;
}
auto surface = SkSurfaces::WrapPixels(bitmap->pixmap());
if (!surface) {
return nullptr;
}
auto canvas = surface->getCanvas();
if (!canvas) {
return nullptr;
}
bool has_color = atlas.GetType() == GlyphAtlas::Type::kColorBitmap;
atlas.IterateGlyphs([canvas, has_color](const ScaledFont& scaled_font,
const Glyph& glyph,
const Rect& location) -> bool {
DrawGlyph(canvas, scaled_font, glyph, location, has_color);
return true;
});
return bitmap;
}
static bool UpdateGlyphTextureAtlas(std::shared_ptr<SkBitmap> bitmap,
const std::shared_ptr<Texture>& texture) {
TRACE_EVENT0("impeller", __FUNCTION__);
FML_DCHECK(bitmap != nullptr);
auto texture_descriptor = texture->GetTextureDescriptor();
auto mapping = std::make_shared<fml::NonOwnedMapping>(
reinterpret_cast<const uint8_t*>(bitmap->getAddr(0, 0)), // data
texture_descriptor.GetByteSizeOfBaseMipLevel(), // size
[bitmap](auto, auto) mutable { bitmap.reset(); } // proc
);
return texture->SetContents(mapping);
}
static std::shared_ptr<Texture> UploadGlyphTextureAtlas(
const std::shared_ptr<Allocator>& allocator,
std::shared_ptr<SkBitmap> bitmap,
const ISize& atlas_size,
PixelFormat format) {
TRACE_EVENT0("impeller", __FUNCTION__);
if (!allocator) {
return nullptr;
}
FML_DCHECK(bitmap != nullptr);
const auto& pixmap = bitmap->pixmap();
TextureDescriptor texture_descriptor;
texture_descriptor.storage_mode = StorageMode::kHostVisible;
texture_descriptor.format = format;
texture_descriptor.size = atlas_size;
if (pixmap.rowBytes() * pixmap.height() !=
texture_descriptor.GetByteSizeOfBaseMipLevel()) {
return nullptr;
}
auto texture = allocator->CreateTexture(texture_descriptor);
if (!texture || !texture->IsValid()) {
return nullptr;
}
texture->SetLabel("GlyphAtlas");
auto mapping = std::make_shared<fml::NonOwnedMapping>(
reinterpret_cast<const uint8_t*>(bitmap->getAddr(0, 0)), // data
texture_descriptor.GetByteSizeOfBaseMipLevel(), // size
[bitmap](auto, auto) mutable { bitmap.reset(); } // proc
);
if (!texture->SetContents(mapping)) {
return nullptr;
}
return texture;
}
std::shared_ptr<GlyphAtlas> TypographerContextSkia::CreateGlyphAtlas(
Context& context,
GlyphAtlas::Type type,
const std::shared_ptr<GlyphAtlasContext>& atlas_context,
const FontGlyphMap& font_glyph_map) const {
TRACE_EVENT0("impeller", __FUNCTION__);
if (!IsValid()) {
return nullptr;
}
auto& atlas_context_skia = GlyphAtlasContextSkia::Cast(*atlas_context);
std::shared_ptr<GlyphAtlas> last_atlas = atlas_context->GetGlyphAtlas();
if (font_glyph_map.empty()) {
return last_atlas;
}
// ---------------------------------------------------------------------------
// Step 1: Determine if the atlas type and font glyph pairs are compatible
// with the current atlas and reuse if possible.
// ---------------------------------------------------------------------------
std::vector<FontGlyphPair> new_glyphs;
for (const auto& font_value : font_glyph_map) {
const ScaledFont& scaled_font = font_value.first;
const FontGlyphAtlas* font_glyph_atlas =
last_atlas->GetFontGlyphAtlas(scaled_font.font, scaled_font.scale);
if (font_glyph_atlas) {
for (const Glyph& glyph : font_value.second) {
if (!font_glyph_atlas->FindGlyphBounds(glyph)) {
new_glyphs.emplace_back(scaled_font, glyph);
}
}
} else {
for (const Glyph& glyph : font_value.second) {
new_glyphs.emplace_back(scaled_font, glyph);
}
}
}
if (last_atlas->GetType() == type && new_glyphs.size() == 0) {
return last_atlas;
}
// ---------------------------------------------------------------------------
// Step 2: Determine if the additional missing glyphs can be appended to the
// existing bitmap without recreating the atlas. This requires that
// the type is identical.
// ---------------------------------------------------------------------------
std::vector<Rect> glyph_positions;
if (last_atlas->GetType() == type &&
CanAppendToExistingAtlas(last_atlas, new_glyphs, glyph_positions,
atlas_context->GetAtlasSize(),
atlas_context->GetRectPacker())) {
// The old bitmap will be reused and only the additional glyphs will be
// added.
// ---------------------------------------------------------------------------
// Step 3a: Record the positions in the glyph atlas of the newly added
// glyphs.
// ---------------------------------------------------------------------------
for (size_t i = 0, count = glyph_positions.size(); i < count; i++) {
last_atlas->AddTypefaceGlyphPosition(new_glyphs[i], glyph_positions[i]);
}
// ---------------------------------------------------------------------------
// Step 4a: Draw new font-glyph pairs into the existing bitmap.
// ---------------------------------------------------------------------------
auto bitmap = atlas_context_skia.GetBitmap();
if (!UpdateAtlasBitmap(*last_atlas, bitmap, new_glyphs)) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 5a: Update the existing texture with the updated bitmap.
// ---------------------------------------------------------------------------
if (!UpdateGlyphTextureAtlas(bitmap, last_atlas->GetTexture())) {
return nullptr;
}
return last_atlas;
}
// A new glyph atlas must be created.
// ---------------------------------------------------------------------------
// Step 3b: Get the optimum size of the texture atlas.
// ---------------------------------------------------------------------------
std::vector<FontGlyphPair> font_glyph_pairs;
font_glyph_pairs.reserve(std::accumulate(
font_glyph_map.begin(), font_glyph_map.end(), 0,
[](const int a, const auto& b) { return a + b.second.size(); }));
for (const auto& font_value : font_glyph_map) {
const ScaledFont& scaled_font = font_value.first;
for (const Glyph& glyph : font_value.second) {
font_glyph_pairs.push_back({scaled_font, glyph});
}
}
auto glyph_atlas = std::make_shared<GlyphAtlas>(type);
auto atlas_size = OptimumAtlasSizeForFontGlyphPairs(
font_glyph_pairs, //
glyph_positions, //
atlas_context, //
type, //
context.GetResourceAllocator()->GetMaxTextureSizeSupported() //
);
atlas_context->UpdateGlyphAtlas(glyph_atlas, atlas_size);
if (atlas_size.IsEmpty()) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 4b: Find location of font-glyph pairs in the atlas. We have this from
// the last step. So no need to do create another rect packer. But just do a
// sanity check of counts. This could also be just an assertion as only a
// construction issue would cause such a failure.
// ---------------------------------------------------------------------------
if (glyph_positions.size() != font_glyph_pairs.size()) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 5b: Record the positions in the glyph atlas.
// ---------------------------------------------------------------------------
{
size_t i = 0;
for (auto it = font_glyph_pairs.begin(); it != font_glyph_pairs.end();
++i, ++it) {
glyph_atlas->AddTypefaceGlyphPosition(*it, glyph_positions[i]);
}
}
// ---------------------------------------------------------------------------
// Step 6b: Draw font-glyph pairs in the correct spot in the atlas.
// ---------------------------------------------------------------------------
auto bitmap = CreateAtlasBitmap(*glyph_atlas, atlas_size);
if (!bitmap) {
return nullptr;
}
atlas_context_skia.UpdateBitmap(bitmap);
// ---------------------------------------------------------------------------
// Step 7b: Upload the atlas as a texture.
// ---------------------------------------------------------------------------
PixelFormat format;
switch (type) {
case GlyphAtlas::Type::kAlphaBitmap:
format = context.GetCapabilities()->GetDefaultGlyphAtlasFormat();
break;
case GlyphAtlas::Type::kColorBitmap:
format = PixelFormat::kR8G8B8A8UNormInt;
break;
}
auto texture = UploadGlyphTextureAtlas(context.GetResourceAllocator(), bitmap,
atlas_size, format);
if (!texture) {
return nullptr;
}
// ---------------------------------------------------------------------------
// Step 8b: Record the texture in the glyph atlas.
// ---------------------------------------------------------------------------
glyph_atlas->SetTexture(std::move(texture));
return glyph_atlas;
}
} // namespace impeller
| engine/impeller/typographer/backends/skia/typographer_context_skia.cc/0 | {
"file_path": "engine/impeller/typographer/backends/skia/typographer_context_skia.cc",
"repo_id": "engine",
"token_count": 7502
} | 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.
#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_H_
#define FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_H_
#include <cstdint>
#include <functional>
#include "flutter/fml/hash_combine.h"
#include "flutter/fml/macros.h"
#include "impeller/geometry/rect.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief The glyph index in the typeface.
///
struct Glyph {
enum class Type : uint8_t {
kPath,
kBitmap,
};
uint16_t index = 0;
//------------------------------------------------------------------------------
/// @brief Whether the glyph is a path or a bitmap.
///
Type type = Type::kPath;
//------------------------------------------------------------------------------
/// @brief Visibility coverage of the glyph in text run space (relative to
/// the baseline, no scaling applied).
///
Rect bounds;
Glyph(uint16_t p_index, Type p_type, Rect p_bounds)
: index(p_index), type(p_type), bounds(p_bounds) {}
};
// Many Glyph instances are instantiated, so care should be taken when
// increasing the size.
static_assert(sizeof(Glyph) == 20);
} // namespace impeller
template <>
struct std::hash<impeller::Glyph> {
constexpr std::size_t operator()(const impeller::Glyph& g) const {
static_assert(sizeof(g.index) == 2);
static_assert(sizeof(g.type) == 1);
return (static_cast<size_t>(g.type) << 16) | g.index;
}
};
template <>
struct std::equal_to<impeller::Glyph> {
constexpr bool operator()(const impeller::Glyph& lhs,
const impeller::Glyph& rhs) const {
return lhs.index == rhs.index && lhs.type == rhs.type;
}
};
template <>
struct std::less<impeller::Glyph> {
constexpr bool operator()(const impeller::Glyph& lhs,
const impeller::Glyph& rhs) const {
return lhs.index < rhs.index;
}
};
#endif // FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_H_
| engine/impeller/typographer/glyph.h/0 | {
"file_path": "engine/impeller/typographer/glyph.h",
"repo_id": "engine",
"token_count": 765
} | 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.
import("//flutter/common/config.gni")
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/testing/testing.gni")
source_set("gpu") {
cflags = [
# Dart gives us doubles. Skia and Impeller work in floats.
# If Dart gives us a double > FLT_MAX or < -FLT_MAX, implicit conversion
# will convert it to either inf/-inf or FLT_MAX/-FLT_MAX (undefined
# behavior). This can result in surprising and difficult to debug behavior
# for Flutter application developers, so it should be explicitly handled
# via SafeNarrow.
"-Wimplicit-float-conversion",
]
if (is_win) {
# This causes build failures in third_party dependencies on Windows.
cflags += [ "-Wno-implicit-int-float-conversion" ]
}
public_configs = [ "//flutter:config" ]
public_deps = []
if (!defined(defines)) {
defines = []
}
if (!is_fuchsia) {
sources = [
"command_buffer.cc",
"command_buffer.h",
"context.cc",
"context.h",
"device_buffer.cc",
"device_buffer.h",
"export.cc",
"export.h",
"fixtures.cc",
"fixtures.h",
"formats.cc",
"formats.h",
"host_buffer.cc",
"host_buffer.h",
"render_pass.cc",
"render_pass.h",
"render_pipeline.cc",
"render_pipeline.h",
"shader.cc",
"shader.h",
"shader_library.cc",
"shader_library.h",
"smoketest.cc",
"smoketest.h",
"texture.cc",
"texture.h",
]
}
deps = [
"//flutter/assets",
"//flutter/impeller",
"//flutter/impeller/display_list:skia_conversions",
"//flutter/impeller/shader_bundle:shader_bundle_flatbuffers",
"//flutter/lib/ui",
"//flutter/third_party/tonic",
]
if (is_win) {
# Required for M_PI and others.
defines += [ "_USE_MATH_DEFINES" ]
}
}
if (enable_unittests) {
}
| engine/lib/gpu/BUILD.gn/0 | {
"file_path": "engine/lib/gpu/BUILD.gn",
"repo_id": "engine",
"token_count": 860
} | 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.
/// The Flutter GPU library.
///
/// To use, import `package:flutter_gpu/gpu.dart`.
///
/// See also:
///
/// * [Flutter GPU Wiki page](https://github.com/flutter/flutter/wiki/Flutter-GPU).
library flutter_gpu;
import 'dart:ffi';
import 'dart:nativewrappers';
import 'dart:typed_data';
// ignore: uri_does_not_exist
import 'dart:ui' as ui;
export 'src/smoketest.dart';
part 'src/buffer.dart';
part 'src/command_buffer.dart';
part 'src/context.dart';
part 'src/formats.dart';
part 'src/texture.dart';
part 'src/render_pass.dart';
part 'src/render_pipeline.dart';
part 'src/shader.dart';
part 'src/shader_library.dart';
| engine/lib/gpu/lib/gpu.dart/0 | {
"file_path": "engine/lib/gpu/lib/gpu.dart",
"repo_id": "engine",
"token_count": 290
} | 272 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/gpu/shader.h"
#include <utility>
#include "flutter/lib/gpu/formats.h"
#include "fml/make_copyable.h"
#include "impeller/core/runtime_types.h"
#include "impeller/renderer/shader_function.h"
#include "impeller/renderer/shader_library.h"
#include "tonic/converter/dart_converter.h"
namespace flutter {
namespace gpu {
const impeller::ShaderStructMemberMetadata*
Shader::UniformBinding::GetMemberMetadata(const std::string& name) const {
auto result =
std::find_if(metadata.members.begin(), metadata.members.end(),
[&name](const impeller::ShaderStructMemberMetadata& member) {
return member.name == name;
});
if (result == metadata.members.end()) {
return nullptr;
}
return &(*result);
}
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, Shader);
Shader::Shader() = default;
Shader::~Shader() = default;
fml::RefPtr<Shader> Shader::Make(
std::string entrypoint,
impeller::ShaderStage stage,
std::shared_ptr<fml::Mapping> code_mapping,
std::shared_ptr<impeller::VertexDescriptor> vertex_desc,
std::unordered_map<std::string, UniformBinding> uniform_structs,
std::unordered_map<std::string, impeller::SampledImageSlot>
uniform_textures) {
auto shader = fml::MakeRefCounted<Shader>();
shader->entrypoint_ = std::move(entrypoint);
shader->stage_ = stage;
shader->code_mapping_ = std::move(code_mapping);
shader->vertex_desc_ = std::move(vertex_desc);
shader->uniform_structs_ = std::move(uniform_structs);
shader->uniform_textures_ = std::move(uniform_textures);
return shader;
}
std::shared_ptr<const impeller::ShaderFunction> Shader::GetFunctionFromLibrary(
impeller::ShaderLibrary& library) {
return library.GetFunction(entrypoint_, stage_);
}
bool Shader::IsRegistered(Context& context) {
auto& lib = *context.GetContext()->GetShaderLibrary();
return GetFunctionFromLibrary(lib) != nullptr;
}
bool Shader::RegisterSync(Context& context) {
if (IsRegistered(context)) {
return true; // Already registered.
}
auto& lib = *context.GetContext()->GetShaderLibrary();
std::promise<bool> promise;
auto future = promise.get_future();
lib.RegisterFunction(
entrypoint_, stage_, code_mapping_,
fml::MakeCopyable([promise = std::move(promise)](bool result) mutable {
promise.set_value(result);
}));
if (!future.get()) {
return false; // Registration failed.
}
return true;
}
std::shared_ptr<impeller::VertexDescriptor> Shader::GetVertexDescriptor()
const {
return vertex_desc_;
}
impeller::ShaderStage Shader::GetShaderStage() const {
return stage_;
}
const Shader::UniformBinding* Shader::GetUniformStruct(
const std::string& name) const {
auto uniform = uniform_structs_.find(name);
if (uniform == uniform_structs_.end()) {
return nullptr;
}
return &uniform->second;
}
const impeller::SampledImageSlot* Shader::GetUniformTexture(
const std::string& name) const {
auto uniform = uniform_textures_.find(name);
if (uniform == uniform_textures_.end()) {
return nullptr;
}
return &uniform->second;
}
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
int InternalFlutterGpu_Shader_GetUniformStructSize(
flutter::gpu::Shader* wrapper,
Dart_Handle struct_name_handle) {
auto name = tonic::StdStringFromDart(struct_name_handle);
const auto* uniform = wrapper->GetUniformStruct(name);
if (uniform == nullptr) {
return -1;
}
return uniform->size_in_bytes;
}
int InternalFlutterGpu_Shader_GetUniformMemberOffset(
flutter::gpu::Shader* wrapper,
Dart_Handle struct_name_handle,
Dart_Handle member_name_handle) {
auto struct_name = tonic::StdStringFromDart(struct_name_handle);
const auto* uniform = wrapper->GetUniformStruct(struct_name);
if (uniform == nullptr) {
return -1;
}
auto member_name = tonic::StdStringFromDart(member_name_handle);
const auto* member = uniform->GetMemberMetadata(member_name);
if (member == nullptr) {
return -1;
}
return member->offset;
}
| engine/lib/gpu/shader.cc/0 | {
"file_path": "engine/lib/gpu/shader.cc",
"repo_id": "engine",
"token_count": 1543
} | 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.
#ifndef FLUTTER_LIB_SNAPSHOT_SNAPSHOT_H_
#define FLUTTER_LIB_SNAPSHOT_SNAPSHOT_H_
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
extern "C" {
extern const uint8_t kDartVmSnapshotData[];
extern const uint8_t kDartVmSnapshotInstructions[];
extern const uint8_t kDartIsolateSnapshotData[];
extern const uint8_t kDartIsolateSnapshotInstructions[];
}
#endif // FLUTTER_LIB_SNAPSHOT_SNAPSHOT_H_
| engine/lib/snapshot/snapshot.h/0 | {
"file_path": "engine/lib/snapshot/snapshot.h",
"repo_id": "engine",
"token_count": 223
} | 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_LIB_UI_DART_WRAPPER_H_
#define FLUTTER_LIB_UI_DART_WRAPPER_H_
#include "flutter/fml/memory/ref_counted.h"
#include "third_party/tonic/dart_wrappable.h"
namespace flutter {
template <typename T>
class RefCountedDartWrappable : public fml::RefCountedThreadSafe<T>,
public tonic::DartWrappable {
public:
virtual void RetainDartWrappableReference() const override {
fml::RefCountedThreadSafe<T>::AddRef();
}
virtual void ReleaseDartWrappableReference() const override {
fml::RefCountedThreadSafe<T>::Release();
}
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_DART_WRAPPER_H_
| engine/lib/ui/dart_wrapper.h/0 | {
"file_path": "engine/lib/ui/dart_wrapper.h",
"repo_id": "engine",
"token_count": 314
} | 275 |
#version 320 es
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 oColor;
layout(location = 0) uniform sampler2D iChild;
void main() {
// iChild1 is an image that is half blue, half green,
// so oColor should be set to vec2(0, 1, 0, 1)
oColor = texture(iChild, vec2(1, 0));
oColor.a = 1.0;
}
| engine/lib/ui/fixtures/shaders/general_shaders/blue_green_sampler.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/general_shaders/blue_green_sampler.frag",
"repo_id": "engine",
"token_count": 159
} | 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.
#ifndef FLUTTER_LIB_UI_IO_MANAGER_H_
#define FLUTTER_LIB_UI_IO_MANAGER_H_
#include "flutter/flow/skia_gpu_object.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/synchronization/sync_switch.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
namespace impeller {
class Context;
} // namespace impeller
namespace flutter {
// Interface for methods that manage access to the resource GrDirectContext and
// Skia unref queue. Meant to be implemented by the owner of the resource
// GrDirectContext, i.e. the shell's IOManager.
class IOManager {
public:
virtual ~IOManager() = default;
virtual fml::WeakPtr<IOManager> GetWeakIOManager() const = 0;
virtual fml::WeakPtr<GrDirectContext> GetResourceContext() const = 0;
virtual fml::RefPtr<flutter::SkiaUnrefQueue> GetSkiaUnrefQueue() const = 0;
virtual std::shared_ptr<const fml::SyncSwitch>
GetIsGpuDisabledSyncSwitch() = 0;
virtual std::shared_ptr<impeller::Context> GetImpellerContext() const;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_IO_MANAGER_H_
| engine/lib/ui/io_manager.h/0 | {
"file_path": "engine/lib/ui/io_manager.h",
"repo_id": "engine",
"token_count": 418
} | 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_LIB_UI_PAINTING_COLOR_FILTER_H_
#define FLUTTER_LIB_UI_PAINTING_COLOR_FILTER_H_
#include "flutter/display_list/effects/dl_color_filter.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace flutter {
// A handle to an SkCodec object.
//
// Doesn't mirror SkCodec's API but provides a simple sequential access API.
class ColorFilter : public RefCountedDartWrappable<ColorFilter> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(ColorFilter);
public:
static void Create(Dart_Handle wrapper);
void initMode(int color, int blend_mode);
void initMatrix(const tonic::Float32List& color_matrix);
void initSrgbToLinearGamma();
void initLinearToSrgbGamma();
~ColorFilter() override;
const std::shared_ptr<const DlColorFilter> filter() const { return filter_; }
private:
std::shared_ptr<const DlColorFilter> filter_;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_COLOR_FILTER_H_
| engine/lib/ui/painting/color_filter.h/0 | {
"file_path": "engine/lib/ui/painting/color_filter.h",
"repo_id": "engine",
"token_count": 401
} | 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.
#ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_H_
#define FLUTTER_LIB_UI_PAINTING_IMAGE_H_
#include "flutter/display_list/image/dl_image.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/skia/include/core/SkImage.h"
namespace flutter {
// Must be kept in sync with painting.dart.
enum ColorSpace {
kSRGB,
kExtendedSRGB,
};
class CanvasImage final : public RefCountedDartWrappable<CanvasImage> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(CanvasImage);
public:
~CanvasImage() override;
static fml::RefPtr<CanvasImage> Create() {
return fml::MakeRefCounted<CanvasImage>();
}
Dart_Handle CreateOuterWrapping();
int width() { return image_ ? image_->width() : 0; }
int height() { return image_ ? image_->height() : 0; }
Dart_Handle toByteData(int format, Dart_Handle callback);
void dispose();
sk_sp<DlImage> image() const { return image_; }
void set_image(const sk_sp<DlImage>& image) {
FML_DCHECK(image->isUIThreadSafe());
image_ = image;
}
int colorSpace();
private:
CanvasImage();
sk_sp<DlImage> image_;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_H_
| engine/lib/ui/painting/image.h/0 | {
"file_path": "engine/lib/ui/painting/image.h",
"repo_id": "engine",
"token_count": 507
} | 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.
#ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_ENCODING_IMPELLER_H_
#define FLUTTER_LIB_UI_PAINTING_IMAGE_ENCODING_IMPELLER_H_
#include "flutter/common/task_runners.h"
#include "flutter/display_list/image/dl_image.h"
#include "flutter/fml/status_or.h"
#include "flutter/fml/synchronization/sync_switch.h"
namespace impeller {
class Context;
} // namespace impeller
namespace flutter {
class ImageEncodingImpeller {
public:
static int GetColorSpace(const std::shared_ptr<impeller::Texture>& texture);
/// Converts a DlImage to a SkImage.
/// This should be called from the thread that corresponds to
/// `dl_image->owning_context()` when gpu access is guaranteed.
/// See also: `ConvertImageToRaster`.
/// Visible for testing.
static void ConvertDlImageToSkImage(
const sk_sp<DlImage>& dl_image,
std::function<void(fml::StatusOr<sk_sp<SkImage>>)> encode_task,
const std::shared_ptr<impeller::Context>& impeller_context);
/// Converts a DlImage to a SkImage.
/// `encode_task` is executed with the resulting `SkImage`.
static void ConvertImageToRaster(
const sk_sp<DlImage>& dl_image,
std::function<void(fml::StatusOr<sk_sp<SkImage>>)> encode_task,
const fml::RefPtr<fml::TaskRunner>& raster_task_runner,
const fml::RefPtr<fml::TaskRunner>& io_task_runner,
const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch,
const std::shared_ptr<impeller::Context>& impeller_context);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_ENCODING_IMPELLER_H_
| engine/lib/ui/painting/image_encoding_impeller.h/0 | {
"file_path": "engine/lib/ui/painting/image_encoding_impeller.h",
"repo_id": "engine",
"token_count": 632
} | 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 "flutter/lib/ui/painting/immutable_buffer.h"
#include <cstring>
#include "flutter/fml/file.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_persistent_value.h"
#if FML_OS_ANDROID
#include <sys/mman.h>
#endif
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, ImmutableBuffer);
ImmutableBuffer::~ImmutableBuffer() {}
Dart_Handle ImmutableBuffer::init(Dart_Handle buffer_handle,
Dart_Handle data,
Dart_Handle callback_handle) {
if (!Dart_IsClosure(callback_handle)) {
return tonic::ToDart("Callback must be a function");
}
tonic::Uint8List dataList = tonic::Uint8List(data);
auto sk_data = MakeSkDataWithCopy(dataList.data(), dataList.num_elements());
dataList.Release();
auto buffer = fml::MakeRefCounted<ImmutableBuffer>(sk_data);
buffer->AssociateWithDartWrapper(buffer_handle);
tonic::DartInvoke(callback_handle, {Dart_TypeVoid()});
return Dart_Null();
}
Dart_Handle ImmutableBuffer::initFromAsset(Dart_Handle raw_buffer_handle,
Dart_Handle asset_name_handle,
Dart_Handle callback_handle) {
UIDartState::ThrowIfUIOperationsProhibited();
if (!Dart_IsClosure(callback_handle)) {
return tonic::ToDart("Callback must be a function");
}
uint8_t* chars = nullptr;
intptr_t asset_length = 0;
Dart_Handle result =
Dart_StringToUTF8(asset_name_handle, &chars, &asset_length);
if (Dart_IsError(result)) {
return tonic::ToDart("Asset name must be valid UTF8");
}
std::string asset_name = std::string{reinterpret_cast<const char*>(chars),
static_cast<size_t>(asset_length)};
auto* dart_state = UIDartState::Current();
auto ui_task_runner = dart_state->GetTaskRunners().GetUITaskRunner();
auto* buffer_callback_ptr =
new tonic::DartPersistentValue(dart_state, callback_handle);
auto* buffer_handle_ptr =
new tonic::DartPersistentValue(dart_state, raw_buffer_handle);
auto asset_manager = UIDartState::Current()
->platform_configuration()
->client()
->GetAssetManager();
auto ui_task = fml::MakeCopyable(
[buffer_callback_ptr, buffer_handle_ptr](const sk_sp<SkData>& sk_data,
size_t buffer_size) mutable {
std::unique_ptr<tonic::DartPersistentValue> buffer_handle(
buffer_handle_ptr);
std::unique_ptr<tonic::DartPersistentValue> buffer_callback(
buffer_callback_ptr);
auto dart_state = buffer_callback->dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
if (!sk_data) {
// -1 is used as a sentinel that the file could not be opened.
tonic::DartInvoke(buffer_callback->Get(), {tonic::ToDart(-1)});
return;
}
auto buffer = fml::MakeRefCounted<ImmutableBuffer>(sk_data);
buffer->AssociateWithDartWrapper(buffer_handle->Get());
tonic::DartInvoke(buffer_callback->Get(), {tonic::ToDart(buffer_size)});
});
dart_state->GetConcurrentTaskRunner()->PostTask(
[asset_name = std::move(asset_name),
asset_manager = std::move(asset_manager),
ui_task_runner = std::move(ui_task_runner), ui_task] {
std::unique_ptr<fml::Mapping> mapping =
asset_manager->GetAsMapping(asset_name);
sk_sp<SkData> sk_data;
size_t buffer_size = 0;
if (mapping != nullptr) {
buffer_size = mapping->GetSize();
const void* bytes = static_cast<const void*>(mapping->GetMapping());
sk_data = MakeSkDataWithCopy(bytes, buffer_size);
}
ui_task_runner->PostTask(
[sk_data = std::move(sk_data), ui_task = ui_task, buffer_size]() {
ui_task(sk_data, buffer_size);
});
});
return Dart_Null();
}
Dart_Handle ImmutableBuffer::initFromFile(Dart_Handle raw_buffer_handle,
Dart_Handle file_path_handle,
Dart_Handle callback_handle) {
UIDartState::ThrowIfUIOperationsProhibited();
if (!Dart_IsClosure(callback_handle)) {
return tonic::ToDart("Callback must be a function");
}
uint8_t* chars = nullptr;
intptr_t file_path_length = 0;
Dart_Handle result =
Dart_StringToUTF8(file_path_handle, &chars, &file_path_length);
if (Dart_IsError(result)) {
return tonic::ToDart("File path must be valid UTF8");
}
std::string file_path = std::string{reinterpret_cast<const char*>(chars),
static_cast<size_t>(file_path_length)};
auto* dart_state = UIDartState::Current();
auto ui_task_runner = dart_state->GetTaskRunners().GetUITaskRunner();
auto* buffer_callback_ptr =
new tonic::DartPersistentValue(dart_state, callback_handle);
auto* buffer_handle_ptr =
new tonic::DartPersistentValue(dart_state, raw_buffer_handle);
auto ui_task = fml::MakeCopyable(
[buffer_callback_ptr, buffer_handle_ptr](const sk_sp<SkData>& sk_data,
size_t buffer_size) mutable {
std::unique_ptr<tonic::DartPersistentValue> buffer_handle(
buffer_handle_ptr);
std::unique_ptr<tonic::DartPersistentValue> buffer_callback(
buffer_callback_ptr);
auto dart_state = buffer_callback->dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
if (!sk_data) {
// -1 is used as a sentinel that the file could not be opened.
tonic::DartInvoke(buffer_callback->Get(), {tonic::ToDart(-1)});
return;
}
auto buffer = fml::MakeRefCounted<ImmutableBuffer>(sk_data);
buffer->AssociateWithDartWrapper(buffer_handle->Get());
tonic::DartInvoke(buffer_callback->Get(), {tonic::ToDart(buffer_size)});
});
dart_state->GetConcurrentTaskRunner()->PostTask(
[file_path = std::move(file_path),
ui_task_runner = std::move(ui_task_runner), ui_task] {
auto mapping = std::make_unique<fml::FileMapping>(fml::OpenFile(
file_path.c_str(), false, fml::FilePermission::kRead));
sk_sp<SkData> sk_data;
size_t buffer_size = 0;
if (mapping->IsValid()) {
buffer_size = mapping->GetSize();
const void* bytes = static_cast<const void*>(mapping->GetMapping());
sk_data = MakeSkDataWithCopy(bytes, buffer_size);
}
ui_task_runner->PostTask(
[sk_data = std::move(sk_data), ui_task = ui_task, buffer_size]() {
ui_task(sk_data, buffer_size);
});
});
return Dart_Null();
}
#if FML_OS_ANDROID
// Compressed image buffers are allocated on the UI thread but are deleted on a
// decoder worker thread. Android's implementation of malloc appears to
// continue growing the native heap size when the allocating thread is
// different from the freeing thread. To work around this, create an SkData
// backed by an anonymous mapping.
sk_sp<SkData> ImmutableBuffer::MakeSkDataWithCopy(const void* data,
size_t length) {
if (length == 0) {
return SkData::MakeEmpty();
}
size_t mapping_length = length + sizeof(size_t);
void* mapping = ::mmap(nullptr, mapping_length, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (mapping == MAP_FAILED) {
return SkData::MakeEmpty();
}
*reinterpret_cast<size_t*>(mapping) = mapping_length;
void* mapping_data = reinterpret_cast<char*>(mapping) + sizeof(size_t);
::memcpy(mapping_data, data, length);
SkData::ReleaseProc proc = [](const void* ptr, void* context) {
size_t* size_ptr = reinterpret_cast<size_t*>(context);
FML_DCHECK(ptr == size_ptr + 1);
if (::munmap(const_cast<void*>(context), *size_ptr) == -1) {
FML_LOG(ERROR) << "munmap of codec SkData failed";
}
};
return SkData::MakeWithProc(mapping_data, length, proc, mapping);
}
#else
sk_sp<SkData> ImmutableBuffer::MakeSkDataWithCopy(const void* data,
size_t length) {
return SkData::MakeWithCopy(data, length);
}
#endif // FML_OS_ANDROID
} // namespace flutter
| engine/lib/ui/painting/immutable_buffer.cc/0 | {
"file_path": "engine/lib/ui/painting/immutable_buffer.cc",
"repo_id": "engine",
"token_count": 3916
} | 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.
#include "flutter/lib/ui/painting/picture_recorder.h"
#include "flutter/lib/ui/painting/canvas.h"
#include "flutter/lib/ui/painting/picture.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, PictureRecorder);
void PictureRecorder::Create(Dart_Handle wrapper) {
UIDartState::ThrowIfUIOperationsProhibited();
auto res = fml::MakeRefCounted<PictureRecorder>();
res->AssociateWithDartWrapper(wrapper);
}
PictureRecorder::PictureRecorder() {}
PictureRecorder::~PictureRecorder() {}
sk_sp<DisplayListBuilder> PictureRecorder::BeginRecording(SkRect bounds) {
display_list_builder_ =
sk_make_sp<DisplayListBuilder>(bounds, /*prepare_rtree=*/true);
return display_list_builder_;
}
void PictureRecorder::endRecording(Dart_Handle dart_picture) {
if (!canvas_) {
return;
}
auto display_list = display_list_builder_->Build();
display_list_builder_ = nullptr;
FML_DCHECK(display_list->has_rtree());
Picture::CreateAndAssociateWithDartWrapper(dart_picture, display_list);
canvas_->Invalidate();
canvas_ = nullptr;
ClearDartWrapper();
}
} // namespace flutter
| engine/lib/ui/painting/picture_recorder.cc/0 | {
"file_path": "engine/lib/ui/painting/picture_recorder.cc",
"repo_id": "engine",
"token_count": 510
} | 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.
part of dart.ui;
/// Runs [computation] on the platform thread and returns the result.
///
/// This may run the computation on a separate isolate. That isolate will be
/// reused for subsequent [runOnPlatformThread] calls. This means that global
/// state is maintained in that isolate between calls.
///
/// The [computation] and any state it captures may be sent to that isolate.
/// See [SendPort.send] for information about what types can be sent.
///
/// If [computation] is asynchronous (returns a `Future<R>`) then
/// that future is awaited in the new isolate, completing the entire
/// asynchronous computation, before returning the result.
///
/// If [computation] throws, the `Future` returned by this function completes
/// with that error.
///
/// The [computation] function and its result (or error) must be
/// sendable between isolates. Objects that cannot be sent include open
/// files and sockets (see [SendPort.send] for details).
///
/// This method can only be invoked from the main isolate.
///
/// This API is currently experimental.
Future<R> runOnPlatformThread<R>(FutureOr<R> Function() computation) {
if (isRunningOnPlatformThread) {
return Future<R>(computation);
}
final SendPort? sendPort = _platformRunnerSendPort;
if (sendPort != null) {
return _sendComputation(sendPort, computation);
} else {
return (_platformRunnerSendPortFuture ??= _spawnPlatformIsolate())
.then((SendPort port) => _sendComputation(port, computation));
}
}
SendPort? _platformRunnerSendPort;
Future<SendPort>? _platformRunnerSendPortFuture;
final Map<int, Completer<Object?>> _pending = <int, Completer<Object?>>{};
int _nextId = 0;
Future<SendPort> _spawnPlatformIsolate() {
final Completer<SendPort> sendPortCompleter = Completer<SendPort>();
final RawReceivePort receiver = RawReceivePort()..keepIsolateAlive = false;
receiver.handler = (Object? message) {
if (message == null) {
// This is the platform isolate's onExit handler.
// This shouldn't really happen, since Isolate.exit is disabled, the
// pause and terminate capabilities aren't provided to the parent
// isolate, and errors are fatal is false. But if the isolate does
// shutdown unexpectedly, clear the singleton so we can create another.
for (final Completer<Object?> completer in _pending.values) {
completer.completeError(RemoteError(
'PlatformIsolate shutdown unexpectedly',
StackTrace.empty.toString()));
}
_pending.clear();
_platformRunnerSendPort = null;
_platformRunnerSendPortFuture = null;
} else if (message is _PlatformIsolateReadyMessage) {
_platformRunnerSendPort = message.computationPort;
sendPortCompleter.complete(message.computationPort);
} else if (message is _ComputationResult) {
final Completer<Object?> resultCompleter = _pending.remove(message.id)!;
final Object? remoteStack = message.remoteStack;
final Object? remoteError = message.remoteError;
if (remoteStack != null) {
if (remoteStack is StackTrace) {
// Typed error.
resultCompleter.completeError(remoteError!, remoteStack);
} else {
// onError handler message, uncaught async error.
// Both values are strings, so calling `toString` is efficient.
final RemoteError error =
RemoteError(remoteError!.toString(), remoteStack.toString());
resultCompleter.completeError(error, error.stackTrace);
}
} else {
resultCompleter.complete(message.result);
}
} else {
// We encountered an error while starting the new isolate.
if (!sendPortCompleter.isCompleted) {
sendPortCompleter.completeError(
IsolateSpawnException('Unable to spawn isolate: $message'));
return;
}
// This shouldn't happen.
throw IsolateSpawnException(
"Internal error: unexpected message: '$message'");
}
};
final Isolate parentIsolate = Isolate.current;
final SendPort sendPort = receiver.sendPort;
try {
_nativeSpawn(() => _platformIsolateMain(parentIsolate, sendPort));
} on Object {
receiver.close();
rethrow;
}
return sendPortCompleter.future;
}
Future<R> _sendComputation<R>(
SendPort port, FutureOr<R> Function() computation) {
final int id = ++_nextId;
final Completer<R> resultCompleter = Completer<R>();
_pending[id] = resultCompleter;
port.send(_ComputationRequest(id, computation));
return resultCompleter.future;
}
void _safeSend(SendPort sendPort, int id, Object? result, Object? error,
Object? stackTrace) {
try {
sendPort.send(_ComputationResult(id, result, error, stackTrace));
} catch (sendError, sendStack) {
sendPort.send(_ComputationResult(id, null, sendError, sendStack));
}
}
void _platformIsolateMain(Isolate parentIsolate, SendPort sendPort) {
final RawReceivePort computationPort = RawReceivePort();
computationPort.handler = (_ComputationRequest? message) {
if (message == null) {
// The parent isolate has shutdown. Allow this isolate to shutdown.
computationPort.keepIsolateAlive = false;
return;
}
late final FutureOr<Object?> potentiallyAsyncResult;
try {
potentiallyAsyncResult = message.computation();
} catch (e, s) {
_safeSend(sendPort, message.id, null, e, s);
return;
}
if (potentiallyAsyncResult is Future<Object?>) {
potentiallyAsyncResult.then((Object? result) {
_safeSend(sendPort, message.id, result, null, null);
}, onError: (Object? e, Object? s) {
_safeSend(sendPort, message.id, null, e, s ?? StackTrace.empty);
});
} else {
_safeSend(sendPort, message.id, potentiallyAsyncResult, null, null);
}
};
Isolate.current.addOnExitListener(sendPort);
parentIsolate.addOnExitListener(computationPort.sendPort);
sendPort.send(_PlatformIsolateReadyMessage(computationPort.sendPort));
}
@Native<Void Function(Handle)>(symbol: 'PlatformIsolateNativeApi::Spawn')
external void _nativeSpawn(Function entryPoint);
/// Whether the current isolate is running on the platform thread.
final bool isRunningOnPlatformThread = _isRunningOnPlatformThread();
@Native<Bool Function()>(
symbol: 'PlatformIsolateNativeApi::IsRunningOnPlatformThread', isLeaf: true)
external bool _isRunningOnPlatformThread();
class _PlatformIsolateReadyMessage {
_PlatformIsolateReadyMessage(this.computationPort);
final SendPort computationPort;
}
class _ComputationRequest {
_ComputationRequest(this.id, this.computation);
final int id;
final FutureOr<Object?> Function() computation;
}
class _ComputationResult {
_ComputationResult(this.id, this.result, this.remoteError, this.remoteStack);
final int id;
final Object? result;
final Object? remoteError;
final Object? remoteStack;
}
| engine/lib/ui/platform_isolate.dart/0 | {
"file_path": "engine/lib/ui/platform_isolate.dart",
"repo_id": "engine",
"token_count": 2334
} | 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_LIB_UI_SEMANTICS_STRING_ATTRIBUTE_H_
#define FLUTTER_LIB_UI_SEMANTICS_STRING_ATTRIBUTE_H_
#include "flutter/lib/ui/dart_wrapper.h"
#include "third_party/tonic/dart_library_natives.h"
namespace flutter {
struct StringAttribute;
using StringAttributePtr = std::shared_ptr<flutter::StringAttribute>;
using StringAttributes = std::vector<StringAttributePtr>;
// When adding a new StringAttributeType, the classes in these file must be
// updated as well.
// * engine/src/flutter/lib/ui/semantics.dart
// * engine/src/flutter/lib/web_ui/lib/semantics.dart
// * engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java
// * engine/src/flutter/shell/platform/embedder/embedder.h
// * engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_api_test.dart
// * engine/src/flutter/testing/dart/semantics_test.dart
enum class StringAttributeType : int32_t {
kSpellOut,
kLocale,
};
//------------------------------------------------------------------------------
/// The c++ representation of the StringAttribute, this struct serves as an
/// abstract interface for the subclasses and should not be used directly.
struct StringAttribute {
virtual ~StringAttribute() = default;
int32_t start = -1;
int32_t end = -1;
StringAttributeType type;
};
//------------------------------------------------------------------------------
/// Indicates the string needs to be spelled out character by character when the
/// assistive technologies announce the string.
struct SpellOutStringAttribute : StringAttribute {};
//------------------------------------------------------------------------------
/// Indicates the string needs to be treated as a specific language when the
/// assistive technologies announce the string.
struct LocaleStringAttribute : StringAttribute {
std::string locale;
};
//------------------------------------------------------------------------------
/// The peer class for all of the StringAttribute subclasses in semantics.dart.
class NativeStringAttribute
: public RefCountedDartWrappable<NativeStringAttribute> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(NativeStringAttribute);
public:
~NativeStringAttribute() override;
//----------------------------------------------------------------------------
/// The init method for SpellOutStringAttribute constructor
static void initSpellOutStringAttribute(Dart_Handle string_attribute_handle,
int32_t start,
int32_t end);
//----------------------------------------------------------------------------
/// The init method for LocaleStringAttribute constructor
static void initLocaleStringAttribute(Dart_Handle string_attribute_handle,
int32_t start,
int32_t end,
std::string locale);
//----------------------------------------------------------------------------
/// Returns the c++ representataion of StringAttribute.
const StringAttributePtr GetAttribute() const;
private:
NativeStringAttribute();
StringAttributePtr attribute_;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_SEMANTICS_STRING_ATTRIBUTE_H_
| engine/lib/ui/semantics/string_attribute.h/0 | {
"file_path": "engine/lib/ui/semantics/string_attribute.h",
"repo_id": "engine",
"token_count": 1043
} | 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/lib/ui/volatile_path_tracker.h"
#include <utility>
namespace flutter {
VolatilePathTracker::VolatilePathTracker(
fml::RefPtr<fml::TaskRunner> ui_task_runner,
bool enabled)
: ui_task_runner_(std::move(ui_task_runner)), enabled_(enabled) {}
void VolatilePathTracker::Track(const std::shared_ptr<TrackedPath>& path) {
FML_DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
FML_DCHECK(path);
FML_DCHECK(path->path.isVolatile());
if (!enabled_) {
path->path.setIsVolatile(false);
return;
}
paths_.push_back(path);
}
void VolatilePathTracker::OnFrame() {
FML_DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
if (!enabled_) {
return;
}
paths_.erase(std::remove_if(paths_.begin(), paths_.end(),
[](const std::weak_ptr<TrackedPath>& weak_path) {
auto path = weak_path.lock();
if (!path) {
return true;
}
path->frame_count++;
if (path->frame_count >= kFramesOfVolatility) {
path->path.setIsVolatile(false);
path->tracking_volatility = false;
return true;
}
return false;
}),
paths_.end());
}
} // namespace flutter
| engine/lib/ui/volatile_path_tracker.cc/0 | {
"file_path": "engine/lib/ui/volatile_path_tracker.cc",
"repo_id": "engine",
"token_count": 870
} | 285 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/window/platform_message_response_dart.h"
#include <utility>
#include "flutter/common/task_runners.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/trace_event.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
static std::atomic<uint64_t> platform_message_counter = 1;
namespace flutter {
namespace {
void MappingFinalizer(void* isolate_callback_data, void* peer) {
delete static_cast<fml::Mapping*>(peer);
}
template <typename Callback, typename TaskRunner, typename Result>
void PostCompletion(Callback&& callback,
const TaskRunner& ui_task_runner,
bool* is_complete,
const std::string& channel,
Result&& result) {
if (callback.is_empty()) {
return;
}
FML_DCHECK(!*is_complete);
*is_complete = true;
uint64_t platform_message_id = platform_message_counter.fetch_add(1);
TRACE_EVENT_ASYNC_BEGIN1("flutter", "PlatformChannel ScheduleResult",
platform_message_id, "channel", channel.c_str());
ui_task_runner->PostTask(fml::MakeCopyable(
[callback = std::move(callback), platform_message_id,
result = std::move(result), channel = channel]() mutable {
TRACE_EVENT_ASYNC_END0("flutter", "PlatformChannel ScheduleResult",
platform_message_id);
std::shared_ptr<tonic::DartState> dart_state =
callback.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::DartInvoke(callback.Release(), {result()});
}));
}
} // namespace
PlatformMessageResponseDart::PlatformMessageResponseDart(
tonic::DartPersistentValue callback,
fml::RefPtr<fml::TaskRunner> ui_task_runner,
const std::string& channel)
: callback_(std::move(callback)),
ui_task_runner_(std::move(ui_task_runner)),
channel_(channel) {}
PlatformMessageResponseDart::~PlatformMessageResponseDart() {
if (!callback_.is_empty()) {
ui_task_runner_->PostTask(fml::MakeCopyable(
[callback = std::move(callback_)]() mutable { callback.Clear(); }));
}
}
void PlatformMessageResponseDart::Complete(std::unique_ptr<fml::Mapping> data) {
PostCompletion(
std::move(callback_), ui_task_runner_, &is_complete_, channel_,
[data = std::move(data)]() mutable {
Dart_Handle byte_buffer;
intptr_t size = data->GetSize();
if (data->GetSize() > tonic::DartByteData::kExternalSizeThreshold) {
const void* mapping = data->GetMapping();
byte_buffer = Dart_NewUnmodifiableExternalTypedDataWithFinalizer(
/*type=*/Dart_TypedData_kByteData,
/*data=*/mapping,
/*length=*/size,
/*peer=*/data.release(),
/*external_allocation_size=*/size,
/*callback=*/MappingFinalizer);
} else {
Dart_Handle mutable_byte_buffer =
tonic::DartByteData::Create(data->GetMapping(), data->GetSize());
Dart_Handle ui_lib = Dart_LookupLibrary(
tonic::DartConverter<std::string>().ToDart("dart:ui"));
FML_DCHECK(!(Dart_IsNull(ui_lib) || Dart_IsError(ui_lib)));
byte_buffer = Dart_Invoke(ui_lib,
tonic::DartConverter<std::string>().ToDart(
"_wrapUnmodifiableByteData"),
1, &mutable_byte_buffer);
FML_DCHECK(!(Dart_IsNull(byte_buffer) || Dart_IsError(byte_buffer)));
}
return byte_buffer;
});
}
void PlatformMessageResponseDart::CompleteEmpty() {
PostCompletion(std::move(callback_), ui_task_runner_, &is_complete_, channel_,
[] { return Dart_Null(); });
}
} // namespace flutter
| engine/lib/ui/window/platform_message_response_dart.cc/0 | {
"file_path": "engine/lib/ui/window/platform_message_response_dart.cc",
"repo_id": "engine",
"token_count": 1805
} | 286 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:path/path.dart' as path;
import 'browser.dart';
import 'chrome.dart';
import 'edge.dart';
import 'environment.dart';
import 'felt_config.dart';
import 'firefox.dart';
import 'safari_macos.dart';
/// The port number for debugging.
const int kDevtoolsPort = 12345;
const int kMaxScreenshotWidth = 1024;
const int kMaxScreenshotHeight = 1024;
abstract class PlatformBinding {
static PlatformBinding get instance {
return _instance ??= _createInstance();
}
static PlatformBinding? _instance;
static PlatformBinding _createInstance() {
if (io.Platform.isLinux) {
return LinuxPlatformBinding();
}
if (io.Platform.isMacOS) {
if (environment.isMacosArm) {
return MacArmPlatformBinding();
}
return Macx64PlatformBinding();
}
if (io.Platform.isWindows) {
return WindowsPlatformBinding();
}
throw UnsupportedError('${io.Platform.operatingSystem} is not supported');
}
String get chromePlatformString;
String getChromeDownloadUrl(String version) =>
'https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/$version/$chromePlatformString/chrome-$chromePlatformString.zip';
String getChromeDriverDownloadUrl(String version) =>
'https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/$version/$chromePlatformString/chromedriver-$chromePlatformString.zip';
String getFirefoxDownloadUrl(String version);
String getFirefoxDownloadFilename(String version);
String getChromeExecutablePath(io.Directory versionDir);
String getFirefoxExecutablePath(io.Directory versionDir);
String getFirefoxLatestVersionUrl();
String getMacApplicationLauncher();
String getCommandToRunEdge();
String getEsbuildDownloadUrl(String version) =>
'https://registry.npmjs.org/@esbuild/$esbuildPlatformName/-/$esbuildPlatformName-$version.tgz';
String get esbuildPlatformName;
}
class WindowsPlatformBinding extends PlatformBinding {
@override
String get chromePlatformString => 'win64';
@override
String getChromeExecutablePath(io.Directory versionDir) =>
path.join(versionDir.path, 'chrome.exe');
@override
String getFirefoxDownloadUrl(String version) =>
'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/win64/en-US/'
'${getFirefoxDownloadFilename(version)}';
@override
String getFirefoxDownloadFilename(String version) => 'firefox-$version.exe';
@override
String getFirefoxExecutablePath(io.Directory versionDir) =>
path.join(versionDir.path, 'firefox', 'firefox');
@override
String getFirefoxLatestVersionUrl() =>
'https://download.mozilla.org/?product=firefox-latest&os=win&lang=en-US';
@override
String getMacApplicationLauncher() =>
throw UnsupportedError('Safari is not supported on Windows');
@override
String getCommandToRunEdge() => 'MicrosoftEdgeLauncher';
@override
String get esbuildPlatformName => 'win32-x64';
}
class LinuxPlatformBinding extends PlatformBinding {
@override
String get chromePlatformString => 'linux64';
@override
String getChromeExecutablePath(io.Directory versionDir) =>
path.join(versionDir.path, 'chrome');
@override
String getFirefoxDownloadUrl(String version) =>
'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/linux-x86_64/en-US/'
'${getFirefoxDownloadFilename(version)}';
@override
String getFirefoxDownloadFilename(String version) =>
'firefox-$version.tar.bz2';
@override
String getFirefoxExecutablePath(io.Directory versionDir) =>
path.join(versionDir.path, 'firefox', 'firefox');
@override
String getFirefoxLatestVersionUrl() =>
'https://download.mozilla.org/?product=firefox-latest&os=linux64&lang=en-US';
@override
String getMacApplicationLauncher() =>
throw UnsupportedError('Safari is not supported on Linux');
@override
String getCommandToRunEdge() =>
throw UnsupportedError('Edge is not supported on Linux');
@override
String get esbuildPlatformName => 'linux-x64';
}
abstract class MacPlatformBinding extends PlatformBinding {
@override
String getChromeExecutablePath(io.Directory versionDir) => path.join(
versionDir.path,
'Google Chrome for Testing.app',
'Contents',
'MacOS',
'Google Chrome for Testing',
);
@override
String getFirefoxDownloadUrl(String version) =>
'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/mac/en-US/'
'${getFirefoxDownloadFilename(version)}';
@override
String getFirefoxDownloadFilename(String version) => 'Firefox $version.dmg';
@override
String getFirefoxExecutablePath(io.Directory versionDir) =>
path.join(versionDir.path, 'Firefox.app', 'Contents', 'MacOS', 'firefox');
@override
String getFirefoxLatestVersionUrl() =>
'https://download.mozilla.org/?product=firefox-latest&os=osx&lang=en-US';
@override
String getMacApplicationLauncher() => 'open';
@override
String getCommandToRunEdge() =>
throw UnimplementedError('Tests for Edge are not implemented for MacOS.');
}
class MacArmPlatformBinding extends MacPlatformBinding {
@override
String get chromePlatformString => 'mac-arm64';
@override
String get esbuildPlatformName => 'darwin-arm64';
}
class Macx64PlatformBinding extends MacPlatformBinding {
@override
String get chromePlatformString => 'mac-x64';
@override
String get esbuildPlatformName => 'darwin-x64';
}
class BrowserInstallation {
const BrowserInstallation({
required this.version,
required this.executable,
});
/// Browser version.
final String version;
/// Path the browser executable.
final String executable;
}
/// A string sink that swallows all input.
class DevNull implements StringSink {
@override
void write(Object? obj) {}
@override
void writeAll(Iterable<dynamic> objects, [String separator = '']) {}
@override
void writeCharCode(int charCode) {}
@override
void writeln([Object? obj = '']) {}
}
/// Whether the felt command is running on LUCI.
bool get isLuci => io.Platform.environment['LUCI_CONTEXT'] != null;
/// Whether the felt command is running on one of the Continuous Integration
/// environements.
bool get isCi => isLuci;
const String kChrome = 'chrome';
const String kEdge = 'edge';
const String kFirefox = 'firefox';
const String kSafari = 'safari';
const List<String> kAllBrowserNames = <String>[
kChrome,
kEdge,
kFirefox,
kSafari,
];
/// Creates an environment for a browser.
///
/// The [browserName] matches the browser name passed as the `--browser` option.
BrowserEnvironment getBrowserEnvironment(
BrowserName browserName, {
required bool useDwarf,
}) {
switch (browserName) {
case BrowserName.chrome:
return ChromeEnvironment(useDwarf: useDwarf);
case BrowserName.edge:
return EdgeEnvironment();
case BrowserName.firefox:
return FirefoxEnvironment();
case BrowserName.safari:
return SafariMacOsEnvironment();
}
}
| engine/lib/web_ui/dev/common.dart/0 | {
"file_path": "engine/lib/web_ui/dev/common.dart",
"repo_id": "engine",
"token_count": 2344
} | 287 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart' as path;
import 'package:watcher/watcher.dart';
import 'exceptions.dart';
import 'utils.dart';
/// Describes what [Pipeline] is currently doing.
enum PipelineStatus {
/// The pipeline has not started yet.
///
/// This is the initial state of the pipeline.
idle,
/// The pipeline is running build steps.
started,
/// The pipeline is stopping.
stopping,
/// The pipeline is not running anything because it has been interrupted.
interrupted,
/// The pipeline is not running anything because it encountered an error.
error,
/// The pipeline is not running anything because it finished all build steps successfully.
done,
}
/// A step in the build pipeline.
abstract class PipelineStep {
/// The name of this step.
///
/// This value appears in logs, so it should be descriptive and human-readable.
String get description;
/// Whether it is safe to interrupt this step while it's running.
bool get isSafeToInterrupt;
/// Runs this step.
///
/// The returned future is completed when the step is finished. The future
/// completes with an error if the step failed.
Future<void> run();
/// Interrupts this step, if it's already running.
///
/// [Pipeline] only calls this if [isSafeToInterrupt] returns true.
Future<void> interrupt();
}
/// A helper class for implementing [PipelineStep] in terms of a process.
abstract class ProcessStep implements PipelineStep {
ProcessManager? _process;
bool _isInterrupted = false;
/// Starts and returns the process that implements the logic of this pipeline
/// step.
Future<ProcessManager> createProcess();
@override
Future<void> interrupt() async {
_isInterrupted = true;
_process?.kill();
}
@override
Future<void> run() async {
final ProcessManager process = await createProcess();
if (_isInterrupted) {
// If the step was interrupted while creating the process, the
// `interrupt` won't kill the process; it must be done here.
process.kill();
return;
}
_process = process;
await process.wait();
_process = null;
}
}
class _PipelineStepFailure {
_PipelineStepFailure(this.step, this.error);
final PipelineStep step;
final Object error;
}
/// Executes a sequence of asynchronous tasks, typically as part of a build/test
/// process.
///
/// The pipeline can be executed by calling [start] and stopped by calling
/// [stop].
///
/// When a pipeline is stopped, it switches to the [PipelineStatus.stopping]
/// state. If [PipelineStep.isSafeToInterrupt] is true, interrupts the currently
/// running step and skips the rest. Otherwise, waits until the current task
/// finishes and skips the rest.
class Pipeline {
Pipeline({required this.steps});
final Iterable<PipelineStep> steps;
PipelineStep? _currentStep;
Future<void>? _currentStepFuture;
PipelineStatus get status => _status;
PipelineStatus _status = PipelineStatus.idle;
/// Runs the steps of the pipeline.
///
/// Returns a future that resolves after all steps have been performed.
///
/// If any steps fail, the pipeline attempts to continue to subsequent steps,
/// but will fail at the end.
///
/// The pipeline may be interrupted by calling [stop] before the future
/// resolves.
Future<void> run() async {
_status = PipelineStatus.started;
final List<_PipelineStepFailure> failures = <_PipelineStepFailure>[];
for (final PipelineStep step in steps) {
_currentStep = step;
_currentStepFuture = step.run();
try {
await _currentStepFuture;
} catch (e) {
failures.add(_PipelineStepFailure(step, e));
} finally {
_currentStep = null;
}
}
if (failures.isEmpty) {
_status = PipelineStatus.done;
} else {
_status = PipelineStatus.error;
print('Pipeline experienced the following failures:');
for (final _PipelineStepFailure failure in failures) {
print(' "${failure.step.description}": ${failure.error}');
}
throw ToolExit('Test pipeline failed.');
}
}
/// Stops executing any more tasks in the pipeline.
///
/// Tasks that are safe to interrupt (according to [PipelineStep.isSafeToInterrupt]),
/// are interrupted. Otherwise, waits for the current step to finish before
/// interrupting the pipeline.
Future<void> stop() async {
_status = PipelineStatus.stopping;
final PipelineStep? step = _currentStep;
if (step == null) {
_status = PipelineStatus.interrupted;
return;
}
if (step.isSafeToInterrupt) {
print('Interrupting ${step.description}');
await step.interrupt();
_status = PipelineStatus.interrupted;
return;
}
print('${step.description} cannot be interrupted. Waiting for it to complete.');
await _currentStepFuture;
_status = PipelineStatus.interrupted;
}
}
/// Signature of functions to be called when a [WatchEvent] is received.
typedef WatchEventPredicate = bool Function(WatchEvent event);
/// Responsible for watching a directory [dir] and executing the given
/// [pipeline] whenever a change occurs in the directory.
///
/// The [ignore] callback can be used to customize the watching behavior to
/// ignore certain files.
class PipelineWatcher {
PipelineWatcher({
required this.dir,
required this.pipeline,
this.ignore,
}) : watcher = DirectoryWatcher(dir);
/// The path of the directory to watch for changes.
final String dir;
/// The pipeline to be executed when an event is fired by the watcher.
final Pipeline pipeline;
/// Used to watch a directory for any file system changes.
final DirectoryWatcher watcher;
/// A callback that determines whether to rerun the pipeline or not for a
/// given [WatchEvent] instance.
final WatchEventPredicate? ignore;
/// Activates the watcher.
Future<void> start() async {
watcher.events.listen(_onEvent);
// Listen to the `q` key stroke to stop the pipeline.
print("Press 'q' to exit felt");
// Key strokes should be reported immediately and one at a time rather than
// wait for the user to hit ENTER and report the whole line. To achieve
// that, echo mode and line mode must be disabled.
io.stdin.echoMode = false;
io.stdin.lineMode = false;
// Reset these settings when the felt command is done.
cleanupCallbacks.add(() async {
io.stdin.echoMode = true;
io.stdin.lineMode = true;
});
await io.stdin.firstWhere((List<int> event) {
const int qKeyCode = 113;
final bool qEntered = event.isNotEmpty && event.first == qKeyCode;
return qEntered;
});
print('Stopping felt');
await pipeline.stop();
}
int _pipelineRunCount = 0;
Timer? _scheduledPipeline;
void _onEvent(WatchEvent event) {
if (ignore?.call(event) ?? false) {
return;
}
final String relativePath = path.relative(event.path, from: dir);
print('- [${event.type}] $relativePath');
_pipelineRunCount++;
_scheduledPipeline?.cancel();
_scheduledPipeline = Timer(const Duration(milliseconds: 100), () {
_scheduledPipeline = null;
_runPipeline();
});
}
Future<void> _runPipeline() async {
if (pipeline.status == PipelineStatus.stopping) {
// We are already trying to stop the pipeline. No need to do anything.
return;
}
if (pipeline.status == PipelineStatus.started) {
// If the pipeline already running, stop it before starting it again.
await pipeline.stop();
}
final int runCount = _pipelineRunCount;
try {
await pipeline.run();
_pipelineSucceeded(runCount);
} catch(error, stackTrace) {
// The error is printed but not rethrown. This is because in watch mode
// failures are expected. The idea is that the developer corrects the
// error, saves the file, and the pipeline reruns.
_pipelineFailed(error, stackTrace);
}
}
void _pipelineSucceeded(int pipelineRunCount) {
if (pipelineRunCount == _pipelineRunCount) {
print('*** Done! ***');
print("Press 'q' to exit felt");
}
}
void _pipelineFailed(Object error, StackTrace stackTrace) {
print('felt command failed: $error');
print(stackTrace);
}
}
| engine/lib/web_ui/dev/pipeline.dart/0 | {
"file_path": "engine/lib/web_ui/dev/pipeline.dart",
"repo_id": "engine",
"token_count": 2719
} | 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.
import { createWasmInstantiator } from "./instantiate_wasm.js";
export const loadCanvasKit = (deps, config, browserEnvironment, engineRevision) => {
if (window.flutterCanvasKit) {
// The user has set this global variable ahead of time, so we just return that.
return Promise.resolve(window.flutterCanvasKit);
}
window.flutterCanvasKitLoaded = new Promise((resolve, reject) => {
const supportsChromiumCanvasKit = browserEnvironment.hasChromiumBreakIterators && browserEnvironment.hasImageCodecs;
if (!supportsChromiumCanvasKit && config.canvasKitVariant == "chromium") {
throw "Chromium CanvasKit variant specifically requested, but unsupported in this browser";
}
const useChromiumCanvasKit = supportsChromiumCanvasKit && (config.canvasKitVariant !== "full");
let baseUrl = config.canvasKitBaseUrl ?? `https://www.gstatic.com/flutter-canvaskit/${engineRevision}/`;
if (useChromiumCanvasKit) {
baseUrl = `${baseUrl}chromium/`;
}
let canvasKitUrl = `${baseUrl}canvaskit.js`;
if (deps.flutterTT.policy) {
canvasKitUrl = deps.flutterTT.policy.createScriptURL(canvasKitUrl);
}
const wasmInstantiator = createWasmInstantiator(`${baseUrl}canvaskit.wasm`);
const script = document.createElement("script");
script.src = canvasKitUrl;
if (config.nonce) {
script.nonce = config.nonce;
}
script.addEventListener('load', async () => {
try {
const canvasKit = await CanvasKitInit({
instantiateWasm: wasmInstantiator,
});
window.flutterCanvasKit = canvasKit;
resolve(canvasKit);
} catch (e) {
reject(e);
}
});
script.addEventListener('error', reject);
document.head.appendChild(script);
});
return window.flutterCanvasKitLoaded;
}
| engine/lib/web_ui/flutter_js/src/canvaskit_loader.js/0 | {
"file_path": "engine/lib/web_ui/flutter_js/src/canvaskit_loader.js",
"repo_id": "engine",
"token_count": 721
} | 289 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of ui;
/// The type of a key event.
// Must match the KeyEventType enum in ui/window/key_data.h.
enum KeyEventType {
/// The key is pressed.
down,
/// The key is released.
up,
/// The key is held, causing a repeated key input.
repeat;
String get label {
return switch (this) {
down => 'Key Down',
up => 'Key Up',
repeat => 'Key Repeat',
};
}
}
/// The source device for the key event.
///
/// Not all platforms supply an accurate type.
// Must match the KeyEventDeviceType enum in ui/window/key_data.h.
enum KeyEventDeviceType {
/// The device is a keyboard.
keyboard,
/// The device is a directional pad on something like a television remote
/// control or similar.
directionalPad,
/// The device is a gamepad button
gamepad,
/// The device is a joystick button
joystick,
/// The device is a device connected to an HDMI bus.
hdmi;
String get label {
return switch (this) {
keyboard => 'Keyboard',
directionalPad => 'Directional Pad',
gamepad => 'Gamepad',
joystick => 'Joystick',
hdmi => 'HDMI',
};
}
}
/// Information about a key event.
class KeyData {
/// Creates an object that represents a key event.
const KeyData({
required this.timeStamp,
required this.type,
required this.physical,
required this.logical,
required this.character,
required this.synthesized,
this.deviceType = KeyEventDeviceType.keyboard,
});
/// Time of event dispatch, relative to an arbitrary timeline.
///
/// For synthesized events, the [timeStamp] might not be the actual time that
/// the key press or release happens.
final Duration timeStamp;
/// The type of the event.
final KeyEventType type;
/// Describes what type of device (keyboard, directional pad, etc.) this event
/// originated from.
final KeyEventDeviceType deviceType;
/// The key code for the physical key that has changed.
final int physical;
/// The key code for the logical key that has changed.
final int logical;
/// Character input from the event.
///
/// Ignored for up events.
final String? character;
/// If [synthesized] is true, this event does not correspond to a native
/// event.
///
/// Although most of Flutter's keyboard events are transformed from native
/// events, some events are not based on native events, and are synthesized
/// only to conform Flutter's key event model (as documented in the
/// `HardwareKeyboard` class in the framework).
///
/// For example, some key downs or ups might be lost when the window loses
/// focus. Some platforms provide ways to query whether a key is being held.
/// If the embedder detects an inconsistency between its internal record and
/// the state returned by the system, the embedder will synthesize a
/// corresponding event to synchronize the state without breaking the event
/// model.
///
/// As another example, macOS treats CapsLock in a special way by sending down
/// and up events at the down of alternate presses to indicate the direction
/// in which the lock is toggled instead of that the physical key is going. A
/// macOS embedder should normalize the behavior by converting a native down
/// event into a down event followed immediately by a synthesized up event,
/// and the native up event also into a down event followed immediately by a
/// synthesized up event.
///
/// Synthesized events do not have a trustworthy [timeStamp], and should not
/// be processed as if the key actually went down or up at the time of the
/// callback.
///
/// [KeyRepeatEvent] is never synthesized.
final bool synthesized;
String _logicalToString() {
final String result = '0x${logical.toRadixString(16)}';
// Find the bits that are not included in `valueMask`, shifted to the right.
// For example, if [logical] is 0x12abcdabcd, then the result is 0x12.
//
// This is mostly equivalent to a right shift, resolving the problem that
// JavaScript only support 32-bit bitwise operations and needs to use
// division instead.
final int planeNum = (logical / 0x100000000).floor();
final String planeDescription = (() {
switch (planeNum) {
case 0x000:
return ' (Unicode)';
case 0x001:
return ' (Unprintable)';
case 0x002:
return ' (Flutter)';
case 0x011:
return ' (Android)';
case 0x012:
return ' (Fuchsia)';
case 0x013:
return ' (iOS)';
case 0x014:
return ' (macOS)';
case 0x015:
return ' (GTK)';
case 0x016:
return ' (Windows)';
case 0x017:
return ' (Web)';
case 0x018:
return ' (GLFW)';
}
return '';
})();
return '$result$planeDescription';
}
String? _escapeCharacter() {
if (character == null) {
return '<none>';
}
switch (character!) {
case '\n':
return r'"\n"';
case '\t':
return r'"\t"';
case '\r':
return r'"\r"';
case '\b':
return r'"\b"';
case '\f':
return r'"\f"';
default:
return '"$character"';
}
}
String? _quotedCharCode() {
if (character == null) {
return '';
}
final Iterable<String> hexChars = character!.codeUnits
.map((int code) => code.toRadixString(16).padLeft(2, '0'));
return ' (0x${hexChars.join(' ')})';
}
@override
String toString() {
return 'KeyData(${type.label}, '
'physical: 0x${physical.toRadixString(16)}, '
'logical: ${_logicalToString()}, '
'character: ${_escapeCharacter()}${_quotedCharCode()}'
'${synthesized ? ', synthesized' : ''})';
}
/// Returns a complete textual description of the information in this object.
String toStringFull() {
return '$runtimeType('
'type: ${type.label}, '
'deviceType: ${deviceType.label}, '
'timeStamp: $timeStamp, '
'physical: 0x${physical.toRadixString(16)}, '
'logical: 0x${logical.toRadixString(16)}, '
'character: ${_escapeCharacter()}, '
'synthesized: $synthesized'
')';
}
}
| engine/lib/web_ui/lib/key.dart/0 | {
"file_path": "engine/lib/web_ui/lib/key.dart",
"repo_id": "engine",
"token_count": 2297
} | 290 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../color_filter.dart';
import '../display.dart';
import 'canvaskit_api.dart';
import 'color_filter.dart';
import 'image.dart';
import 'image_filter.dart';
import 'painting.dart';
import 'path.dart';
import 'picture.dart';
import 'text.dart';
import 'util.dart';
import 'vertices.dart';
/// Memoized value for ClipOp.Intersect, so we don't have to hit JS-interop
/// every time we need it.
final SkClipOp _clipOpIntersect = canvasKit.ClipOp.Intersect;
/// A Dart wrapper around Skia's [SkCanvas].
///
/// This is intentionally not memory-managing the underlying [SkCanvas]. See
/// the docs on [SkCanvas], which explain the reason.
class CkCanvas {
CkCanvas(this.skCanvas);
// Cubic equation coefficients recommended by Mitchell & Netravali
// in their paper on cubic interpolation.
static const double _kMitchellNetravali_B = 1.0 / 3.0;
static const double _kMitchellNetravali_C = 1.0 / 3.0;
final SkCanvas skCanvas;
int? get saveCount => skCanvas.getSaveCount().toInt();
void clear(ui.Color color) {
skCanvas.clear(toSharedSkColor1(color));
}
void clipPath(CkPath path, bool doAntiAlias) {
skCanvas.clipPath(
path.skiaObject,
_clipOpIntersect,
doAntiAlias,
);
}
void clipRRect(ui.RRect rrect, bool doAntiAlias) {
skCanvas.clipRRect(
toSkRRect(rrect),
_clipOpIntersect,
doAntiAlias,
);
}
void clipRect(ui.Rect rect, ui.ClipOp clipOp, bool doAntiAlias) {
skCanvas.clipRect(
toSkRect(rect),
toSkClipOp(clipOp),
doAntiAlias,
);
}
ui.Rect getDeviceClipBounds() {
return rectFromSkIRect(skCanvas.getDeviceClipBounds());
}
void drawArc(
ui.Rect oval,
double startAngle,
double sweepAngle,
bool useCenter,
CkPaint paint,
) {
const double toDegrees = 180 / math.pi;
skCanvas.drawArc(
toSkRect(oval),
startAngle * toDegrees,
sweepAngle * toDegrees,
useCenter,
paint.skiaObject,
);
}
// TODO(flar): CanvasKit does not expose sampling options available on SkCanvas.drawAtlas
void drawAtlasRaw(
CkPaint paint,
CkImage atlas,
Float32List rstTransforms,
Float32List rects,
Uint32List? colors,
ui.BlendMode blendMode,
) {
skCanvas.drawAtlas(
atlas.skImage,
rects,
rstTransforms,
paint.skiaObject,
toSkBlendMode(blendMode),
colors,
);
}
void drawCircle(ui.Offset c, double radius, CkPaint paint) {
skCanvas.drawCircle(
c.dx,
c.dy,
radius,
paint.skiaObject,
);
}
void drawColor(ui.Color color, ui.BlendMode blendMode) {
skCanvas.drawColorInt(
color.value.toDouble(),
toSkBlendMode(blendMode),
);
}
void drawDRRect(ui.RRect outer, ui.RRect inner, CkPaint paint) {
skCanvas.drawDRRect(
toSkRRect(outer),
toSkRRect(inner),
paint.skiaObject,
);
}
void drawImage(CkImage image, ui.Offset offset, CkPaint paint) {
final ui.FilterQuality filterQuality = paint.filterQuality;
if (filterQuality == ui.FilterQuality.high) {
skCanvas.drawImageCubic(
image.skImage,
offset.dx,
offset.dy,
_kMitchellNetravali_B,
_kMitchellNetravali_C,
paint.skiaObject,
);
} else {
skCanvas.drawImageOptions(
image.skImage,
offset.dx,
offset.dy,
toSkFilterMode(filterQuality),
toSkMipmapMode(filterQuality),
paint.skiaObject,
);
}
}
void drawImageRect(CkImage image, ui.Rect src, ui.Rect dst, CkPaint paint) {
final ui.FilterQuality filterQuality = paint.filterQuality;
if (filterQuality == ui.FilterQuality.high) {
skCanvas.drawImageRectCubic(
image.skImage,
toSkRect(src),
toSkRect(dst),
_kMitchellNetravali_B,
_kMitchellNetravali_C,
paint.skiaObject,
);
} else {
skCanvas.drawImageRectOptions(
image.skImage,
toSkRect(src),
toSkRect(dst),
toSkFilterMode(filterQuality),
toSkMipmapMode(filterQuality),
paint.skiaObject,
);
}
}
void drawImageNine(
CkImage image, ui.Rect center, ui.Rect dst, CkPaint paint) {
skCanvas.drawImageNine(
image.skImage,
toSkRect(center),
toSkRect(dst),
toSkFilterMode(paint.filterQuality),
paint.skiaObject,
);
}
void drawLine(ui.Offset p1, ui.Offset p2, CkPaint paint) {
skCanvas.drawLine(
p1.dx,
p1.dy,
p2.dx,
p2.dy,
paint.skiaObject,
);
}
void drawOval(ui.Rect rect, CkPaint paint) {
skCanvas.drawOval(
toSkRect(rect),
paint.skiaObject,
);
}
void drawPaint(CkPaint paint) {
skCanvas.drawPaint(paint.skiaObject);
}
void drawParagraph(CkParagraph paragraph, ui.Offset offset) {
skCanvas.drawParagraph(
paragraph.skiaObject,
offset.dx,
offset.dy,
);
}
void drawPath(CkPath path, CkPaint paint) {
skCanvas.drawPath(path.skiaObject, paint.skiaObject);
}
void drawPicture(CkPicture picture) {
assert(picture.debugCheckNotDisposed('Failed to draw picture.'));
skCanvas.drawPicture(picture.skiaObject);
}
void drawPoints(CkPaint paint, ui.PointMode pointMode, Float32List points) {
skCanvas.drawPoints(
toSkPointMode(pointMode),
points,
paint.skiaObject,
);
}
void drawRRect(ui.RRect rrect, CkPaint paint) {
skCanvas.drawRRect(
toSkRRect(rrect),
paint.skiaObject,
);
}
void drawRect(ui.Rect rect, CkPaint paint) {
skCanvas.drawRect(toSkRect(rect), paint.skiaObject);
}
void drawShadow(
CkPath path, ui.Color color, double elevation, bool transparentOccluder) {
drawSkShadow(skCanvas, path, color, elevation, transparentOccluder,
EngineFlutterDisplay.instance.devicePixelRatio);
}
void drawVertices(
CkVertices vertices, ui.BlendMode blendMode, CkPaint paint) {
skCanvas.drawVertices(
vertices.skiaObject,
toSkBlendMode(blendMode),
paint.skiaObject,
);
}
void restore() {
skCanvas.restore();
}
void restoreToCount(int count) {
skCanvas.restoreToCount(count.toDouble());
}
void rotate(double radians) {
skCanvas.rotate(radians * 180.0 / math.pi, 0.0, 0.0);
}
int save() {
return skCanvas.save().toInt();
}
void saveLayer(ui.Rect bounds, CkPaint? paint) {
skCanvas.saveLayer(
paint?.skiaObject,
toSkRect(bounds),
null,
null,
);
}
void saveLayerWithoutBounds(CkPaint? paint) {
skCanvas.saveLayer(paint?.skiaObject, null, null, null);
}
void saveLayerWithFilter(ui.Rect bounds, ui.ImageFilter filter,
[CkPaint? paint]) {
final CkManagedSkImageFilterConvertible convertible;
if (filter is ui.ColorFilter) {
convertible = createCkColorFilter(filter as EngineColorFilter)!;
} else {
convertible = filter as CkManagedSkImageFilterConvertible;
}
convertible.imageFilter((SkImageFilter filter) {
skCanvas.saveLayer(
paint?.skiaObject,
toSkRect(bounds),
filter,
0,
);
});
}
void scale(double sx, double sy) {
skCanvas.scale(sx, sy);
}
void skew(double sx, double sy) {
skCanvas.skew(sx, sy);
}
void transform(Float32List matrix4) {
skCanvas.concat(toSkM44FromFloat32(matrix4));
}
void translate(double dx, double dy) {
skCanvas.translate(dx, dy);
}
Float32List getLocalToDevice() {
final List<dynamic> list = skCanvas.getLocalToDevice();
final Float32List matrix4 = Float32List(16);
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++) {
matrix4[c * 4 + r] = (list[r * 4 + c] as num).toDouble();
}
}
return matrix4;
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/canvas.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/canvas.dart",
"repo_id": "engine",
"token_count": 3499
} | 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.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'canvas.dart';
import 'painting.dart';
import 'path.dart';
/// A virtual canvas that applies operations to multiple canvases at once.
class CkNWayCanvas {
final List<CkCanvas> _canvases = <CkCanvas>[];
void addCanvas(CkCanvas canvas) {
_canvases.add(canvas);
}
/// Calls [save] on all canvases.
int save() {
int saveCount = 0;
for (int i = 0; i < _canvases.length; i++) {
saveCount = _canvases[i].save();
}
return saveCount;
}
/// Calls [saveLayer] on all canvases.
void saveLayer(ui.Rect bounds, CkPaint? paint) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].saveLayer(bounds, paint);
}
}
/// Calls [saveLayerWithFilter] on all canvases.
void saveLayerWithFilter(ui.Rect bounds, ui.ImageFilter filter,
[CkPaint? paint]) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].saveLayerWithFilter(bounds, filter, paint);
}
}
/// Calls [restore] on all canvases.
void restore() {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].restore();
}
}
/// Calls [restoreToCount] on all canvases.
void restoreToCount(int count) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].restoreToCount(count);
}
}
/// Calls [translate] on all canvases.
void translate(double dx, double dy) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].translate(dx, dy);
}
}
/// Calls [transform] on all canvases.
void transform(Float32List matrix) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].transform(matrix);
}
}
/// Calls [clear] on all canvases.
void clear(ui.Color color) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].clear(color);
}
}
/// Calls [clipPath] on all canvases.
void clipPath(CkPath path, bool doAntiAlias) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].clipPath(path, doAntiAlias);
}
}
/// Calls [clipRect] on all canvases.
void clipRect(ui.Rect rect, ui.ClipOp clipOp, bool doAntiAlias) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].clipRect(rect, clipOp, doAntiAlias);
}
}
/// Calls [clipRRect] on all canvases.
void clipRRect(ui.RRect rrect, bool doAntiAlias) {
for (int i = 0; i < _canvases.length; i++) {
_canvases[i].clipRRect(rrect, doAntiAlias);
}
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/n_way_canvas.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/n_way_canvas.dart",
"repo_id": "engine",
"token_count": 1081
} | 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.
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
final bool _ckRequiresClientICU = canvasKit.ParagraphBuilder.RequiresClientICU();
final List<String> _testFonts = <String>['FlutterTest', 'Ahem'];
String? _computeEffectiveFontFamily(String? fontFamily) {
return ui_web.debugEmulateFlutterTesterEnvironment && !_testFonts.contains(fontFamily)
? _testFonts.first
: fontFamily;
}
@immutable
class CkParagraphStyle implements ui.ParagraphStyle {
CkParagraphStyle({
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,
}) : skParagraphStyle = toSkParagraphStyle(
textAlign,
textDirection,
maxLines,
_computeEffectiveFontFamily(fontFamily),
fontSize,
height,
textHeightBehavior,
fontWeight,
fontStyle,
strutStyle,
ellipsis,
locale,
),
_textAlign = textAlign,
_textDirection = textDirection,
_fontWeight = fontWeight,
_fontStyle = fontStyle,
_maxLines = maxLines,
_originalFontFamily = fontFamily,
_effectiveFontFamily = _computeEffectiveFontFamily(fontFamily),
_fontSize = fontSize,
_height = height,
_textHeightBehavior = textHeightBehavior,
_strutStyle = strutStyle,
_ellipsis = ellipsis,
_locale = locale;
final SkParagraphStyle skParagraphStyle;
final ui.TextAlign? _textAlign;
final ui.TextDirection? _textDirection;
final ui.FontWeight? _fontWeight;
final ui.FontStyle? _fontStyle;
final int? _maxLines;
final String? _originalFontFamily;
final String? _effectiveFontFamily;
final double? _fontSize;
final double? _height;
final ui.TextHeightBehavior? _textHeightBehavior;
final ui.StrutStyle? _strutStyle;
final String? _ellipsis;
final ui.Locale? _locale;
static SkTextStyleProperties toSkTextStyleProperties(
String? fontFamily,
double? fontSize,
double? height,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
) {
final SkTextStyleProperties skTextStyle = SkTextStyleProperties();
if (fontWeight != null || fontStyle != null) {
skTextStyle.fontStyle = toSkFontStyle(fontWeight, fontStyle);
}
if (fontSize != null) {
skTextStyle.fontSize = fontSize;
}
if (height != null) {
skTextStyle.heightMultiplier = height;
}
skTextStyle.fontFamilies = _computeCombinedFontFamilies(fontFamily);
return skTextStyle;
}
static SkStrutStyleProperties toSkStrutStyleProperties(
ui.StrutStyle value, ui.TextHeightBehavior? paragraphHeightBehavior) {
final CkStrutStyle style = value as CkStrutStyle;
final SkStrutStyleProperties skStrutStyle = SkStrutStyleProperties();
skStrutStyle.fontFamilies =
_computeCombinedFontFamilies(style._fontFamily, style._fontFamilyFallback);
if (style._fontSize != null) {
skStrutStyle.fontSize = style._fontSize;
}
if (style._height != null) {
skStrutStyle.heightMultiplier = style._height;
}
final ui.TextLeadingDistribution? effectiveLeadingDistribution =
style._leadingDistribution ??
paragraphHeightBehavior?.leadingDistribution;
switch (effectiveLeadingDistribution) {
case null:
break;
case ui.TextLeadingDistribution.even:
skStrutStyle.halfLeading = true;
case ui.TextLeadingDistribution.proportional:
skStrutStyle.halfLeading = false;
}
if (style._leading != null) {
skStrutStyle.leading = style._leading;
}
if (style._fontWeight != null || style._fontStyle != null) {
skStrutStyle.fontStyle =
toSkFontStyle(style._fontWeight, style._fontStyle);
}
if (style._forceStrutHeight != null) {
skStrutStyle.forceStrutHeight = style._forceStrutHeight;
}
skStrutStyle.strutEnabled = true;
return skStrutStyle;
}
static SkParagraphStyle toSkParagraphStyle(
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,
) {
final SkParagraphStyleProperties properties = SkParagraphStyleProperties();
if (textAlign != null) {
properties.textAlign = toSkTextAlign(textAlign);
}
if (textDirection != null) {
properties.textDirection = toSkTextDirection(textDirection);
}
if (maxLines != null) {
properties.maxLines = maxLines;
}
if (height != null) {
properties.heightMultiplier = height;
}
if (textHeightBehavior != null) {
properties.textHeightBehavior =
toSkTextHeightBehavior(textHeightBehavior);
}
if (ellipsis != null) {
properties.ellipsis = ellipsis;
}
if (strutStyle != null) {
properties.strutStyle =
toSkStrutStyleProperties(strutStyle, textHeightBehavior);
}
properties.replaceTabCharacters = true;
properties.textStyle = toSkTextStyleProperties(
fontFamily, fontSize, height, fontWeight, fontStyle);
properties.applyRoundingHack = false;
return canvasKit.ParagraphStyle(properties);
}
CkTextStyle getTextStyle() {
return CkTextStyle._(
originalFontFamily: _originalFontFamily,
effectiveFontFamily: _effectiveFontFamily,
fontSize: _fontSize,
height: _height,
leadingDistribution: _textHeightBehavior?.leadingDistribution,
fontWeight: _fontWeight,
fontStyle: _fontStyle,
// Use defaults for everything else.
color: null,
decoration: null,
decorationColor: null,
decorationStyle: null,
decorationThickness: null,
textBaseline: null,
originalFontFamilyFallback: null,
effectiveFontFamilyFallback: null,
letterSpacing: null,
wordSpacing: null,
locale: null,
background: null,
foreground: null,
shadows: null,
fontFeatures: null,
fontVariations: null,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is CkParagraphStyle &&
other._textAlign == _textAlign &&
other._textDirection == _textDirection &&
other._fontWeight == _fontWeight &&
other._fontStyle == _fontStyle &&
other._maxLines == _maxLines &&
other._originalFontFamily == _originalFontFamily &&
// effectiveFontFamily is not compared as it's a computed value.
other._fontSize == _fontSize &&
other._height == _height &&
other._textHeightBehavior == _textHeightBehavior &&
other._strutStyle == _strutStyle &&
other._ellipsis == _ellipsis &&
other._locale == _locale;
}
@override
int get hashCode {
return Object.hash(
_textAlign,
_textDirection,
_fontWeight,
_fontStyle,
_maxLines,
_originalFontFamily,
// effectiveFontFamily is not included as it's a computed value.
_fontSize,
_height,
_textHeightBehavior,
_strutStyle,
_ellipsis,
_locale,
);
}
@override
String toString() {
String result = super.toString();
assert(() {
final double? fontSize = _fontSize;
final double? height = _height;
result = 'ParagraphStyle('
'textAlign: ${_textAlign ?? "unspecified"}, '
'textDirection: ${_textDirection ?? "unspecified"}, '
'fontWeight: ${_fontWeight ?? "unspecified"}, '
'fontStyle: ${_fontStyle ?? "unspecified"}, '
'maxLines: ${_maxLines ?? "unspecified"}, '
'textHeightBehavior: ${_textHeightBehavior ?? "unspecified"}, '
'fontFamily: ${_originalFontFamily ?? "unspecified"}, '
'fontSize: ${fontSize != null ? fontSize.toStringAsFixed(1) : "unspecified"}, '
'height: ${height != null ? "${height.toStringAsFixed(1)}x" : "unspecified"}, '
'strutStyle: ${_strutStyle ?? "unspecified"}, '
'ellipsis: ${_ellipsis != null ? '"$_ellipsis"' : "unspecified"}, '
'locale: ${_locale ?? "unspecified"}'
')';
return true;
}());
return result;
}
}
@immutable
class CkTextStyle implements ui.TextStyle {
factory CkTextStyle({
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,
CkPaint? background,
CkPaint? foreground,
List<ui.Shadow>? shadows,
List<ui.FontFeature>? fontFeatures,
List<ui.FontVariation>? fontVariations,
}) {
assert(
color == null || foreground == null,
'Cannot provide both a color and a foreground\n'
'The color argument is just a shorthand for "foreground: Paint()..color = color".',
);
return CkTextStyle._(
color: color,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
decorationThickness: decorationThickness,
fontWeight: fontWeight,
fontStyle: fontStyle,
textBaseline: textBaseline,
originalFontFamily: fontFamily,
effectiveFontFamily: _computeEffectiveFontFamily(fontFamily),
originalFontFamilyFallback: fontFamilyFallback,
effectiveFontFamilyFallback: ui_web.debugEmulateFlutterTesterEnvironment ? null : fontFamilyFallback,
fontSize: fontSize,
letterSpacing: letterSpacing,
wordSpacing: wordSpacing,
height: height,
leadingDistribution: leadingDistribution,
locale: locale,
background: background,
foreground: foreground,
shadows: shadows,
fontFeatures: fontFeatures,
fontVariations: fontVariations,
);
}
CkTextStyle._({
required this.color,
required this.decoration,
required this.decorationColor,
required this.decorationStyle,
required this.decorationThickness,
required this.fontWeight,
required this.fontStyle,
required this.textBaseline,
required this.originalFontFamily,
required this.effectiveFontFamily,
required this.originalFontFamilyFallback,
required this.effectiveFontFamilyFallback,
required this.fontSize,
required this.letterSpacing,
required this.wordSpacing,
required this.height,
required this.leadingDistribution,
required this.locale,
required this.background,
required this.foreground,
required this.shadows,
required this.fontFeatures,
required this.fontVariations,
});
final ui.Color? color;
final ui.TextDecoration? decoration;
final ui.Color? decorationColor;
final ui.TextDecorationStyle? decorationStyle;
final double? decorationThickness;
final ui.FontWeight? fontWeight;
final ui.FontStyle? fontStyle;
final ui.TextBaseline? textBaseline;
final String? originalFontFamily;
final String? effectiveFontFamily;
final List<String>? originalFontFamilyFallback;
final List<String>? effectiveFontFamilyFallback;
final double? fontSize;
final double? letterSpacing;
final double? wordSpacing;
final double? height;
final ui.TextLeadingDistribution? leadingDistribution;
final ui.Locale? locale;
final CkPaint? background;
final CkPaint? foreground;
final List<ui.Shadow>? shadows;
final List<ui.FontFeature>? fontFeatures;
final List<ui.FontVariation>? fontVariations;
/// Merges this text style with [other] and returns the new text style.
///
/// The values in this text style are used unless [other] specifically
/// overrides it.
CkTextStyle mergeWith(CkTextStyle other) {
return CkTextStyle._(
color: other.color ?? color,
decoration: other.decoration ?? decoration,
decorationColor: other.decorationColor ?? decorationColor,
decorationStyle: other.decorationStyle ?? decorationStyle,
decorationThickness: other.decorationThickness ?? decorationThickness,
fontWeight: other.fontWeight ?? fontWeight,
fontStyle: other.fontStyle ?? fontStyle,
textBaseline: other.textBaseline ?? textBaseline,
originalFontFamily: other.originalFontFamily ?? originalFontFamily,
effectiveFontFamily: other.effectiveFontFamily ?? effectiveFontFamily,
originalFontFamilyFallback: other.originalFontFamilyFallback ?? originalFontFamilyFallback,
effectiveFontFamilyFallback: other.effectiveFontFamilyFallback ?? effectiveFontFamilyFallback,
fontSize: other.fontSize ?? fontSize,
letterSpacing: other.letterSpacing ?? letterSpacing,
wordSpacing: other.wordSpacing ?? wordSpacing,
height: other.height ?? height,
leadingDistribution: other.leadingDistribution ?? leadingDistribution,
locale: other.locale ?? locale,
background: other.background ?? background,
foreground: other.foreground ?? foreground,
shadows: other.shadows ?? shadows,
fontFeatures: other.fontFeatures ?? fontFeatures,
fontVariations: other.fontVariations ?? fontVariations,
);
}
/// Lazy-initialized combination of font family and font family fallback sent to Skia.
late final List<String> combinedFontFamilies =
_computeCombinedFontFamilies(effectiveFontFamily, effectiveFontFamilyFallback);
/// Lazy-initialized Skia style used to pass the style to Skia.
///
/// This is lazy because not every style ends up being passed to Skia, so the
/// conversion would be wasteful.
late final SkTextStyle skTextStyle = () {
// Write field values to locals so null checks promote types to non-null.
final ui.Color? color = this.color;
final ui.TextDecoration? decoration = this.decoration;
final ui.Color? decorationColor = this.decorationColor;
final ui.TextDecorationStyle? decorationStyle = this.decorationStyle;
final double? decorationThickness = this.decorationThickness;
final ui.FontWeight? fontWeight = this.fontWeight;
final ui.FontStyle? fontStyle = this.fontStyle;
final ui.TextBaseline? textBaseline = this.textBaseline;
final double? fontSize = this.fontSize;
final double? letterSpacing = this.letterSpacing;
final double? wordSpacing = this.wordSpacing;
final double? height = this.height;
final ui.Locale? locale = this.locale;
final CkPaint? background = this.background;
final CkPaint? foreground = this.foreground;
final List<ui.Shadow>? shadows = this.shadows;
final List<ui.FontFeature>? fontFeatures = this.fontFeatures;
final List<ui.FontVariation>? fontVariations = this.fontVariations;
final SkTextStyleProperties properties = SkTextStyleProperties();
if (background != null) {
properties.backgroundColor = makeFreshSkColor(background.color);
}
if (color != null) {
properties.color = makeFreshSkColor(color);
}
if (decoration != null) {
int decorationValue = canvasKit.NoDecoration.toInt();
if (decoration.contains(ui.TextDecoration.underline)) {
decorationValue |= canvasKit.UnderlineDecoration.toInt();
}
if (decoration.contains(ui.TextDecoration.overline)) {
decorationValue |= canvasKit.OverlineDecoration.toInt();
}
if (decoration.contains(ui.TextDecoration.lineThrough)) {
decorationValue |= canvasKit.LineThroughDecoration.toInt();
}
properties.decoration = decorationValue;
}
if (decorationThickness != null) {
properties.decorationThickness = decorationThickness;
}
if (decorationColor != null) {
properties.decorationColor = makeFreshSkColor(decorationColor);
}
if (decorationStyle != null) {
properties.decorationStyle = toSkTextDecorationStyle(decorationStyle);
}
if (textBaseline != null) {
properties.textBaseline = toSkTextBaseline(textBaseline);
}
if (fontSize != null) {
properties.fontSize = fontSize;
}
if (letterSpacing != null) {
properties.letterSpacing = letterSpacing;
}
if (wordSpacing != null) {
properties.wordSpacing = wordSpacing;
}
if (height != null) {
properties.heightMultiplier = height;
}
switch (leadingDistribution) {
case null:
break;
case ui.TextLeadingDistribution.even:
properties.halfLeading = true;
case ui.TextLeadingDistribution.proportional:
properties.halfLeading = false;
}
if (locale != null) {
properties.locale = locale.toLanguageTag();
}
properties.fontFamilies = combinedFontFamilies;
if (fontWeight != null || fontStyle != null) {
properties.fontStyle = toSkFontStyle(fontWeight, fontStyle);
}
if (foreground != null) {
properties.foregroundColor = makeFreshSkColor(foreground.color);
}
if (shadows != null) {
final List<SkTextShadow> ckShadows = <SkTextShadow>[];
for (final ui.Shadow shadow in shadows) {
final SkTextShadow ckShadow = SkTextShadow();
ckShadow.color = makeFreshSkColor(shadow.color);
ckShadow.offset = toSkPoint(shadow.offset);
ckShadow.blurRadius = shadow.blurRadius;
ckShadows.add(ckShadow);
}
properties.shadows = ckShadows;
}
if (fontFeatures != null) {
final List<SkFontFeature> skFontFeatures = <SkFontFeature>[];
for (final ui.FontFeature fontFeature in fontFeatures) {
final SkFontFeature skFontFeature = SkFontFeature();
skFontFeature.name = fontFeature.feature;
skFontFeature.value = fontFeature.value;
skFontFeatures.add(skFontFeature);
}
properties.fontFeatures = skFontFeatures;
}
if (fontVariations != null) {
final List<SkFontVariation> skFontVariations = <SkFontVariation>[];
for (final ui.FontVariation fontVariation in fontVariations) {
final SkFontVariation skFontVariation = SkFontVariation();
skFontVariation.axis = fontVariation.axis;
skFontVariation.value = fontVariation.value;
skFontVariations.add(skFontVariation);
}
properties.fontVariations = skFontVariations;
}
return canvasKit.TextStyle(properties);
}();
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is CkTextStyle
&& other.color == color
&& other.decoration == decoration
&& other.decorationColor == decorationColor
&& other.decorationStyle == decorationStyle
&& other.fontWeight == fontWeight
&& other.fontStyle == fontStyle
&& other.textBaseline == textBaseline
&& other.leadingDistribution == leadingDistribution
&& other.originalFontFamily == originalFontFamily
&& other.fontSize == fontSize
&& other.letterSpacing == letterSpacing
&& other.wordSpacing == wordSpacing
&& other.height == height
&& other.decorationThickness == decorationThickness
&& other.locale == locale
&& other.background == background
&& other.foreground == foreground
&& listEquals<ui.Shadow>(other.shadows, shadows)
&& listEquals<String>(other.originalFontFamilyFallback, originalFontFamilyFallback)
&& listEquals<ui.FontFeature>(other.fontFeatures, fontFeatures)
&& listEquals<ui.FontVariation>(other.fontVariations, fontVariations);
}
@override
int get hashCode {
final List<ui.Shadow>? shadows = this.shadows;
final List<ui.FontFeature>? fontFeatures = this.fontFeatures;
final List<ui.FontVariation>? fontVariations = this.fontVariations;
final List<String>? fontFamilyFallback = originalFontFamilyFallback;
return Object.hash(
color,
decoration,
decorationColor,
decorationStyle,
fontWeight,
fontStyle,
textBaseline,
leadingDistribution,
originalFontFamily,
fontFamilyFallback == null ? null : Object.hashAll(fontFamilyFallback),
fontSize,
letterSpacing,
wordSpacing,
height,
locale,
background,
foreground,
shadows == null ? null : Object.hashAll(shadows),
decorationThickness,
// Object.hash goes up to 20 arguments, but we have 21
Object.hash(
fontFeatures == null ? null : Object.hashAll(fontFeatures),
fontVariations == null ? null : Object.hashAll(fontVariations),
)
);
}
@override
String toString() {
String result = super.toString();
assert(() {
final List<String>? fontFamilyFallback = originalFontFamilyFallback;
final double? fontSize = this.fontSize;
final double? height = this.height;
result = 'TextStyle('
'color: ${color ?? "unspecified"}, '
'decoration: ${decoration ?? "unspecified"}, '
'decorationColor: ${decorationColor ?? "unspecified"}, '
'decorationStyle: ${decorationStyle ?? "unspecified"}, '
'decorationThickness: ${decorationThickness ?? "unspecified"}, '
'fontWeight: ${fontWeight ?? "unspecified"}, '
'fontStyle: ${fontStyle ?? "unspecified"}, '
'textBaseline: ${textBaseline ?? "unspecified"}, '
'fontFamily: ${originalFontFamily ?? "unspecified"}, '
'fontFamilyFallback: ${fontFamilyFallback != null && fontFamilyFallback.isNotEmpty ? fontFamilyFallback : "unspecified"}, '
'fontSize: ${fontSize != null ? fontSize.toStringAsFixed(1) : "unspecified"}, '
'letterSpacing: ${letterSpacing != null ? "${letterSpacing}x" : "unspecified"}, '
'wordSpacing: ${wordSpacing != null ? "${wordSpacing}x" : "unspecified"}, '
'height: ${height != null ? "${height.toStringAsFixed(1)}x" : "unspecified"}, '
'leadingDistribution: ${leadingDistribution ?? "unspecified"}, '
'locale: ${locale ?? "unspecified"}, '
'background: ${background ?? "unspecified"}, '
'foreground: ${foreground ?? "unspecified"}, '
'shadows: ${shadows ?? "unspecified"}, '
'fontFeatures: ${fontFeatures ?? "unspecified"}, '
'fontVariations: ${fontVariations ?? "unspecified"}'
')';
return true;
}());
return result;
}
}
class CkStrutStyle implements ui.StrutStyle {
CkStrutStyle({
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? height,
// TODO(mdebbar): implement leadingDistribution.
ui.TextLeadingDistribution? leadingDistribution,
double? leading,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
bool? forceStrutHeight,
}) : _fontFamily = _computeEffectiveFontFamily(fontFamily),
_fontFamilyFallback = ui_web.debugEmulateFlutterTesterEnvironment ? null : fontFamilyFallback,
_fontSize = fontSize,
_height = height,
_leadingDistribution = leadingDistribution,
_leading = leading,
_fontWeight = fontWeight,
_fontStyle = fontStyle,
_forceStrutHeight = forceStrutHeight;
final String? _fontFamily;
final List<String>? _fontFamilyFallback;
final double? _fontSize;
final double? _height;
final double? _leading;
final ui.FontWeight? _fontWeight;
final ui.FontStyle? _fontStyle;
final bool? _forceStrutHeight;
final ui.TextLeadingDistribution? _leadingDistribution;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is CkStrutStyle &&
other._fontFamily == _fontFamily &&
other._fontSize == _fontSize &&
other._height == _height &&
other._leading == _leading &&
other._leadingDistribution == _leadingDistribution &&
other._fontWeight == _fontWeight &&
other._fontStyle == _fontStyle &&
other._forceStrutHeight == _forceStrutHeight &&
listEquals<String>(other._fontFamilyFallback, _fontFamilyFallback);
}
@override
int get hashCode {
final List<String>? fontFamilyFallback = _fontFamilyFallback;
return Object.hash(
_fontFamily,
fontFamilyFallback != null ? Object.hashAll(fontFamilyFallback) : null,
_fontSize,
_height,
_leading,
_leadingDistribution,
_fontWeight,
_fontStyle,
_forceStrutHeight,
);
}
}
SkFontStyle toSkFontStyle(ui.FontWeight? fontWeight, ui.FontStyle? fontStyle) {
final SkFontStyle style = SkFontStyle();
if (fontWeight != null) {
style.weight = toSkFontWeight(fontWeight);
}
if (fontStyle != null) {
style.slant = toSkFontSlant(fontStyle);
}
return style;
}
/// The CanvasKit implementation of [ui.Paragraph].
class CkParagraph implements ui.Paragraph {
CkParagraph(SkParagraph skParagraph, this._paragraphStyle) {
_ref = UniqueRef<SkParagraph>(this, skParagraph, 'Paragraph');
}
late final UniqueRef<SkParagraph> _ref;
SkParagraph get skiaObject => _ref.nativeObject;
/// The constraints from the last time we laid the paragraph out.
///
/// This is used to resurrect the paragraph if the initial paragraph
/// is deleted.
double _lastLayoutConstraints = double.negativeInfinity;
/// The paragraph style used to build this paragraph.
///
/// This is used to resurrect the paragraph if the initial paragraph
/// is deleted.
final CkParagraphStyle _paragraphStyle;
@override
double get alphabeticBaseline => _alphabeticBaseline;
double _alphabeticBaseline = 0;
@override
bool get didExceedMaxLines => _didExceedMaxLines;
bool _didExceedMaxLines = false;
@override
double get height => _height;
double _height = 0;
@override
double get ideographicBaseline => _ideographicBaseline;
double _ideographicBaseline = 0;
@override
double get longestLine => _longestLine;
double _longestLine = 0;
@override
double get maxIntrinsicWidth => _maxIntrinsicWidth;
double _maxIntrinsicWidth = 0;
@override
double get minIntrinsicWidth => _minIntrinsicWidth;
double _minIntrinsicWidth = 0;
@override
double get width => _width;
double _width = 0;
@override
List<ui.TextBox> getBoxesForPlaceholders() => _boxesForPlaceholders;
late List<ui.TextBox> _boxesForPlaceholders;
@override
List<ui.TextBox> getBoxesForRange(
int start,
int end, {
ui.BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight,
ui.BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight,
}) {
assert(!_disposed, 'Paragraph has been disposed.');
if (start < 0 || end < 0) {
return const <ui.TextBox>[];
}
final List<SkRectWithDirection> skRects = skiaObject.getRectsForRange(
start.toDouble(),
end.toDouble(),
toSkRectHeightStyle(boxHeightStyle),
toSkRectWidthStyle(boxWidthStyle),
);
return skRectsToTextBoxes(skRects);
}
List<ui.TextBox> skRectsToTextBoxes(List<SkRectWithDirection> skRects) {
assert(!_disposed, 'Paragraph has been disposed.');
final List<ui.TextBox> result = <ui.TextBox>[];
for (int i = 0; i < skRects.length; i++) {
final SkRectWithDirection skRect = skRects[i];
final Float32List rect = skRect.rect;
final int skTextDirection = skRect.dir.value.toInt();
result.add(ui.TextBox.fromLTRBD(
rect[0],
rect[1],
rect[2],
rect[3],
ui.TextDirection.values[skTextDirection],
));
}
return result;
}
@override
ui.TextPosition getPositionForOffset(ui.Offset offset) {
assert(!_disposed, 'Paragraph has been disposed.');
final SkTextPosition positionWithAffinity = skiaObject.getGlyphPositionAtCoordinate(
offset.dx,
offset.dy,
);
return fromPositionWithAffinity(positionWithAffinity);
}
@override
ui.GlyphInfo? getClosestGlyphInfoForOffset(ui.Offset offset) {
assert(!_disposed, 'Paragraph has been disposed.');
return skiaObject.getClosestGlyphInfoAt(offset.dx, offset.dy);
}
@override
ui.GlyphInfo? getGlyphInfoAt(int codeUnitOffset) {
assert(!_disposed, 'Paragraph has been disposed.');
return skiaObject.getGlyphInfoAt(codeUnitOffset.toDouble());
}
@override
ui.TextRange getWordBoundary(ui.TextPosition position) {
assert(!_disposed, 'Paragraph has been disposed.');
final int characterPosition;
switch (position.affinity) {
case ui.TextAffinity.upstream:
characterPosition = position.offset - 1;
case ui.TextAffinity.downstream:
characterPosition = position.offset;
}
final SkTextRange skRange = skiaObject.getWordBoundary(characterPosition.toDouble());
return ui.TextRange(start: skRange.start.toInt(), end: skRange.end.toInt());
}
@override
void layout(ui.ParagraphConstraints constraints) {
assert(!_disposed, 'Paragraph has been disposed.');
if (_lastLayoutConstraints == constraints.width) {
return;
}
_lastLayoutConstraints = constraints.width;
// TODO(het): CanvasKit throws an exception when laid out with
// a font that wasn't registered.
try {
final SkParagraph paragraph = skiaObject;
paragraph.layout(constraints.width);
_alphabeticBaseline = paragraph.getAlphabeticBaseline();
_didExceedMaxLines = paragraph.didExceedMaxLines();
_height = paragraph.getHeight();
_ideographicBaseline = paragraph.getIdeographicBaseline();
_longestLine = paragraph.getLongestLine();
_maxIntrinsicWidth = paragraph.getMaxIntrinsicWidth();
_minIntrinsicWidth = paragraph.getMinIntrinsicWidth();
_width = paragraph.getMaxWidth();
_boxesForPlaceholders =
skRectsToTextBoxes(paragraph.getRectsForPlaceholders());
} catch (e) {
printWarning(
'CanvasKit threw an exception while laying '
'out the paragraph. The font was "${_paragraphStyle._originalFontFamily}". '
'Exception:\n$e',
);
rethrow;
}
}
@override
ui.TextRange getLineBoundary(ui.TextPosition position) {
assert(!_disposed, 'Paragraph has been disposed.');
final List<SkLineMetrics> metrics = skiaObject.getLineMetrics();
final int offset = position.offset;
for (final SkLineMetrics metric in metrics) {
if (offset >= metric.startIndex && offset <= metric.endIndex) {
return ui.TextRange(start: metric.startIndex.toInt(), end: metric.endIndex.toInt());
}
}
return ui.TextRange.empty;
}
@override
List<ui.LineMetrics> computeLineMetrics() {
assert(!_disposed, 'Paragraph has been disposed.');
final List<SkLineMetrics> skLineMetrics = skiaObject.getLineMetrics();
final List<ui.LineMetrics> result = <ui.LineMetrics>[];
for (final SkLineMetrics metric in skLineMetrics) {
result.add(CkLineMetrics._(metric));
}
return result;
}
@override
ui.LineMetrics? getLineMetricsAt(int lineNumber) {
assert(!_disposed, 'Paragraph has been disposed.');
final SkLineMetrics? metrics = skiaObject.getLineMetricsAt(lineNumber.toDouble());
return metrics == null ? null : CkLineMetrics._(metrics);
}
@override
int get numberOfLines {
assert(!_disposed, 'Paragraph has been disposed.');
return skiaObject.getNumberOfLines().toInt();
}
@override
int? getLineNumberAt(int codeUnitOffset) {
assert(!_disposed, 'Paragraph has been disposed.');
final int lineNumber = skiaObject.getLineNumberAt(codeUnitOffset.toDouble()).toInt();
return lineNumber >= 0 ? lineNumber : null;
}
bool _disposed = false;
@override
void dispose() {
assert(!_disposed, 'Paragraph has been disposed.');
_ref.dispose();
_disposed = true;
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError('Paragraph.debugDisposed is only available when asserts are enabled.');
}
}
class CkLineMetrics implements ui.LineMetrics {
CkLineMetrics._(this.skLineMetrics);
final SkLineMetrics skLineMetrics;
@override
double get ascent => skLineMetrics.ascent;
@override
double get descent => skLineMetrics.descent;
// TODO(hterkelsen): Implement this correctly once SkParagraph does.
@override
double get unscaledAscent => skLineMetrics.ascent;
@override
bool get hardBreak => skLineMetrics.isHardBreak;
@override
double get baseline => skLineMetrics.baseline;
@override
double get height =>
(skLineMetrics.ascent + skLineMetrics.descent).round().toDouble();
@override
double get left => skLineMetrics.left;
@override
double get width => skLineMetrics.width;
@override
int get lineNumber => skLineMetrics.lineNumber.toInt();
}
class CkParagraphBuilder implements ui.ParagraphBuilder {
CkParagraphBuilder(ui.ParagraphStyle style)
: _style = style as CkParagraphStyle,
_placeholderCount = 0,
_placeholderScales = <double>[],
_styleStack = <CkTextStyle>[],
_paragraphBuilder = canvasKit.ParagraphBuilder.MakeFromFontCollection(
style.skParagraphStyle,
CanvasKitRenderer.instance.fontCollection.skFontCollection,
) {
_styleStack.add(_style.getTextStyle());
}
final SkParagraphBuilder _paragraphBuilder;
final CkParagraphStyle _style;
int _placeholderCount;
final List<double> _placeholderScales;
final List<CkTextStyle> _styleStack;
@override
void addPlaceholder(
double width,
double height,
ui.PlaceholderAlignment alignment, {
double scale = 1.0,
double? baselineOffset,
ui.TextBaseline? baseline,
}) {
// Require a baseline to be specified if using a baseline-based alignment.
assert(!(alignment == ui.PlaceholderAlignment.aboveBaseline ||
alignment == ui.PlaceholderAlignment.belowBaseline ||
alignment == ui.PlaceholderAlignment.baseline) || baseline != null);
_placeholderCount++;
_placeholderScales.add(scale);
final _CkParagraphPlaceholder placeholderStyle = toSkPlaceholderStyle(
width * scale,
height * scale,
alignment,
(baselineOffset ?? height) * scale,
baseline ?? ui.TextBaseline.alphabetic,
);
_addPlaceholder(placeholderStyle);
}
void _addPlaceholder(_CkParagraphPlaceholder placeholderStyle) {
_paragraphBuilder.addPlaceholder(
placeholderStyle.width,
placeholderStyle.height,
placeholderStyle.alignment,
placeholderStyle.baseline,
placeholderStyle.offset,
);
}
static _CkParagraphPlaceholder toSkPlaceholderStyle(
double width,
double height,
ui.PlaceholderAlignment alignment,
double baselineOffset,
ui.TextBaseline baseline,
) {
final _CkParagraphPlaceholder properties = _CkParagraphPlaceholder(
width: width,
height: height,
alignment: toSkPlaceholderAlignment(alignment),
offset: baselineOffset,
baseline: toSkTextBaseline(baseline),
);
return properties;
}
@override
void addText(String text) {
final List<String> fontFamilies = <String>[];
final CkTextStyle style = _peekStyle();
if (style.effectiveFontFamily != null) {
fontFamilies.add(style.effectiveFontFamily!);
}
if (style.effectiveFontFamilyFallback != null) {
fontFamilies.addAll(style.effectiveFontFamilyFallback!);
}
renderer.fontCollection.fontFallbackManager!.ensureFontsSupportText(text, fontFamilies);
_paragraphBuilder.addText(text);
}
@override
CkParagraph build() {
final SkParagraph builtParagraph = _buildSkParagraph();
return CkParagraph(builtParagraph, _style);
}
/// Builds the CkParagraph with the builder and deletes the builder.
SkParagraph _buildSkParagraph() {
if (_ckRequiresClientICU) {
injectClientICU(_paragraphBuilder);
}
final SkParagraph result = _paragraphBuilder.build();
_paragraphBuilder.delete();
return result;
}
@override
int get placeholderCount => _placeholderCount;
@override
List<double> get placeholderScales => _placeholderScales;
@override
void pop() {
if (_styleStack.length <= 1) {
// The top-level text style is paragraph-level. We don't pop it off.
assert(() {
printWarning(
'Cannot pop text style in ParagraphBuilder. '
'Already popped all text styles from the style stack.',
);
return true;
}());
return;
}
_styleStack.removeLast();
_paragraphBuilder.pop();
}
CkTextStyle _peekStyle() {
assert(_styleStack.isNotEmpty);
return _styleStack.last;
}
// Used as the paint for background or foreground in the text style when
// the other one is not specified. CanvasKit either both background and
// foreground paints specified, or neither, but Flutter allows one of them
// to go unspecified.
//
// This object is never deleted. It is effectively a static global constant.
// Therefore it doesn't need to be wrapped in CkPaint.
static final SkPaint _defaultTextForeground = SkPaint();
static final SkPaint _defaultTextBackground = SkPaint()
..setColorInt(0x00000000);
@override
void pushStyle(ui.TextStyle style) {
final CkTextStyle baseStyle = _peekStyle();
final CkTextStyle ckStyle = style as CkTextStyle;
final CkTextStyle skStyle = baseStyle.mergeWith(ckStyle);
_styleStack.add(skStyle);
if (skStyle.foreground != null || skStyle.background != null) {
SkPaint? foreground = skStyle.foreground?.skiaObject;
if (foreground == null) {
_defaultTextForeground.setColorInt(
(skStyle.color?.value ?? 0xFF000000).toDouble(),
);
foreground = _defaultTextForeground;
}
final SkPaint background =
skStyle.background?.skiaObject ?? _defaultTextBackground;
_paragraphBuilder.pushPaintStyle(
skStyle.skTextStyle, foreground, background);
} else {
_paragraphBuilder.pushStyle(skStyle.skTextStyle);
}
}
}
class _CkParagraphPlaceholder {
_CkParagraphPlaceholder({
required this.width,
required this.height,
required this.alignment,
required this.baseline,
required this.offset,
});
final double width;
final double height;
final SkPlaceholderAlignment alignment;
final SkTextBaseline baseline;
final double offset;
}
List<String> _computeCombinedFontFamilies(String? fontFamily,
[List<String>? fontFamilyFallback]) {
final List<String> fontFamilies = <String>[];
if (fontFamily != null) {
fontFamilies.add(fontFamily);
}
if (fontFamilyFallback != null &&
!fontFamilyFallback.every((String font) => fontFamily == font)) {
fontFamilies.addAll(fontFamilyFallback);
}
fontFamilies.addAll(
renderer.fontCollection.fontFallbackManager!.globalFontFallbacks
);
return fontFamilies;
}
| engine/lib/web_ui/lib/src/engine/canvaskit/text.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/text.dart",
"repo_id": "engine",
"token_count": 14729
} | 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.
import 'package:ui/ui.dart' as ui;
import '../browser_detection.dart';
import '../color_filter.dart';
import '../dom.dart';
import '../util.dart';
import '../vector_math.dart';
import 'resource_manager.dart';
import 'shaders/shader.dart';
import 'surface.dart';
import 'surface_stats.dart';
/// A surface that applies an image filter to background.
class PersistedBackdropFilter extends PersistedContainerSurface
implements ui.BackdropFilterEngineLayer {
PersistedBackdropFilter(PersistedBackdropFilter? super.oldLayer, this.filter);
final ui.ImageFilter filter;
/// The dedicated child container element that's separate from the
/// [rootElement] is used to host child in front of [filterElement] that
/// is transformed to cover background.
@override
DomElement? get childContainer => _childContainer;
DomElement? _childContainer;
DomElement? _filterElement;
DomElement? _svgFilter;
ui.Rect? _activeClipBounds;
// Cached inverted transform for [transform].
late Matrix4 _invertedTransform;
// Reference to transform last used to cache [_invertedTransform].
Matrix4? _previousTransform;
@override
void adoptElements(PersistedBackdropFilter oldSurface) {
super.adoptElements(oldSurface);
_childContainer = oldSurface._childContainer;
_filterElement = oldSurface._filterElement;
_svgFilter = oldSurface._svgFilter;
oldSurface._childContainer = null;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-backdrop');
element.style.transformOrigin = '0 0 0';
_childContainer = createDomElement('flt-backdrop-interior');
_childContainer!.style.position = 'absolute';
if (debugExplainSurfaceStats) {
// This creates an additional interior element. Count it too.
surfaceStatsFor(this).allocatedDomNodeCount++;
}
_filterElement = defaultCreateElement('flt-backdrop-filter');
_filterElement!.style.transformOrigin = '0 0 0';
element..append(_filterElement!)..append(_childContainer!);
return element;
}
@override
void discard() {
super.discard();
// Do not detach the child container from the root. It is permanently
// attached. The elements are reused together and are detached from the DOM
// together.
ResourceManager.instance.removeResource(_svgFilter);
_svgFilter = null;
_childContainer = null;
_filterElement = null;
}
@override
void apply() {
EngineImageFilter backendFilter;
if (filter is ui.ColorFilter) {
backendFilter = createHtmlColorFilter(filter as EngineColorFilter)!;
} else {
backendFilter = filter as EngineImageFilter;
}
ResourceManager.instance.removeResource(_svgFilter);
_svgFilter = null;
if (_previousTransform != transform) {
_invertedTransform = Matrix4.inverted(transform!);
_previousTransform = transform;
}
// https://api.flutter.dev/flutter/widgets/BackdropFilter-class.html
// Defines the effective area as the parent/ancestor clip or if not
// available, the whole screen.
//
// The CSS backdrop-filter will use isolation boundary defined in
// https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty
// Therefore we need to use parent clip element bounds for
// backdrop boundary.
final double dpr = ui.window.devicePixelRatio;
final ui.Rect rect = _invertedTransform.transformRect(ui.Rect.fromLTRB(0, 0,
ui.window.physicalSize.width * dpr,
ui.window.physicalSize.height * dpr));
double left = rect.left;
double top = rect.top;
double width = rect.width;
double height = rect.height;
PersistedContainerSurface? parentSurface = parent;
while (parentSurface != null) {
if (parentSurface.isClipping) {
final ui.Rect activeClipBounds = (_activeClipBounds = parentSurface.localClipBounds)!;
left = activeClipBounds.left;
top = activeClipBounds.top;
width = activeClipBounds.width;
height = activeClipBounds.height;
break;
}
parentSurface = parentSurface.parent;
}
final DomCSSStyleDeclaration filterElementStyle = _filterElement!.style;
filterElementStyle
..position = 'absolute'
..left = '${left}px'
..top = '${top}px'
..width = '${width}px'
..height = '${height}px';
if (browserEngine == BrowserEngine.firefox) {
// For FireFox for now render transparent black background.
// TODO(ferhat): Switch code to use filter when
// See https://caniuse.com/#feat=css-backdrop-filter.
filterElementStyle
..backgroundColor = '#000'
..opacity = '0.2';
} else {
if (backendFilter is ModeHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(_filterElement);
/// Some blendModes do not make an svgFilter. See [EngineHtmlColorFilter.makeSvgFilter()]
if (_svgFilter == null) {
return;
}
} else if (backendFilter is MatrixHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(_filterElement);
}
// CSS uses pixel radius for blur. Flutter & SVG use sigma parameters. For
// Gaussian blur with standard deviation (normal distribution),
// the blur will fall within 2 * sigma pixels.
if (browserEngine == BrowserEngine.webkit) {
setElementStyle(_filterElement!, '-webkit-backdrop-filter',
backendFilter.filterAttribute);
}
setElementStyle(_filterElement!, 'backdrop-filter', backendFilter.filterAttribute);
}
}
@override
void update(PersistedBackdropFilter oldSurface) {
super.update(oldSurface);
if (filter != oldSurface.filter) {
apply();
} else {
_checkForUpdatedAncestorClipElement();
}
}
void _checkForUpdatedAncestorClipElement() {
// If parent clip element has moved, adjust bounds.
PersistedContainerSurface? parentSurface = parent;
while (parentSurface != null) {
if (parentSurface.isClipping) {
if (parentSurface.localClipBounds != _activeClipBounds) {
apply();
}
break;
}
parentSurface = parentSurface.parent;
}
}
@override
void retain() {
super.retain();
_checkForUpdatedAncestorClipElement();
}
}
| engine/lib/web_ui/lib/src/engine/html/backdrop_filter.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/backdrop_filter.dart",
"repo_id": "engine",
"token_count": 2259
} | 294 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'path_utils.dart';
/// Stores the path verbs, points and conic weights.
///
/// This is a Dart port of Skia SkPathRef class.
/// For reference Flutter Gallery average points array size is 5.9, max 25
/// we start with [_pointsCapacity] 10 to reduce allocations during growth.
///
/// Unlike native skia GenID is not supported since we don't have requirement
/// to update caches due to content changes.
class PathRef {
PathRef()
: fPoints = Float32List(kInitialPointsCapacity * 2),
_fVerbs = Uint8List(kInitialVerbsCapacity) {
_fPointsCapacity = kInitialPointsCapacity;
_fVerbsCapacity = kInitialVerbsCapacity;
_resetFields();
}
/// Creates a copy of the path by pointing new path to a current
/// points,verbs and weights arrays. If original path is mutated by adding
/// more verbs, this copy only returns path at the time of copy and shares
/// typed arrays of original path.
PathRef.shallowCopy(PathRef ref)
: fPoints = ref.fPoints,
_fVerbs = ref._fVerbs {
_fVerbsCapacity = ref._fVerbsCapacity;
_fVerbsLength = ref._fVerbsLength;
_fPointsCapacity = ref._fPointsCapacity;
_fPointsLength = ref._fPointsLength;
_conicWeightsCapacity = ref._conicWeightsCapacity;
_conicWeightsLength = ref._conicWeightsLength;
_conicWeights = ref._conicWeights;
fBoundsIsDirty = ref.fBoundsIsDirty;
if (!fBoundsIsDirty) {
fBounds = ref.fBounds;
cachedBounds = ref.cachedBounds;
fIsFinite = ref.fIsFinite;
}
fSegmentMask = ref.fSegmentMask;
fIsOval = ref.fIsOval;
fIsRRect = ref.fIsRRect;
fIsRect = ref.fIsRect;
fRRectOrOvalIsCCW = ref.fRRectOrOvalIsCCW;
fRRectOrOvalStartIdx = ref.fRRectOrOvalStartIdx;
debugValidate();
}
/// Returns a new path by translating [source] by [offsetX], [offsetY].
PathRef.shiftedFrom(PathRef source, double offsetX, double offsetY)
: fPoints = _fPointsFromSource(source, offsetX, offsetY),
_fVerbs = _fVerbsFromSource(source) {
_conicWeightsCapacity = source._conicWeightsCapacity;
_conicWeightsLength = source._conicWeightsLength;
if (source._conicWeights != null) {
_conicWeights = Float32List(_conicWeightsCapacity);
_conicWeights!.setAll(0, source._conicWeights!);
}
_fVerbsCapacity = source._fVerbsCapacity;
_fVerbsLength = source._fVerbsLength;
_fPointsCapacity = source._fPointsCapacity;
_fPointsLength = source._fPointsLength;
fBoundsIsDirty = source.fBoundsIsDirty;
if (!fBoundsIsDirty) {
fBounds = source.fBounds!.translate(offsetX, offsetY);
cachedBounds = source.cachedBounds?.translate(offsetX, offsetY);
fIsFinite = source.fIsFinite;
}
fSegmentMask = source.fSegmentMask;
fIsOval = source.fIsOval;
fIsRRect = source.fIsRRect;
fIsRect = source.fIsRect;
fRRectOrOvalIsCCW = source.fRRectOrOvalIsCCW;
fRRectOrOvalStartIdx = source.fRRectOrOvalStartIdx;
debugValidate();
}
// Value to use to check against to insert move(0,0) when a command
// is added without moveTo.
static const int kInitialLastMoveToIndex = -1;
// SerializationOffsets
static const int kLegacyRRectOrOvalStartIdx_SerializationShift =
28; // requires 3 bits, ignored.
static const int kLegacyRRectOrOvalIsCCW_SerializationShift =
27; // requires 1 bit, ignored.
static const int kLegacyIsRRect_SerializationShift =
26; // requires 1 bit, ignored.
static const int kIsFinite_SerializationShift = 25; // requires 1 bit
static const int kLegacyIsOval_SerializationShift =
24; // requires 1 bit, ignored.
static const int kSegmentMask_SerializationShift =
0; // requires 4 bits (deprecated)
static const int kInitialPointsCapacity = 8;
static const int kInitialVerbsCapacity = 8;
/// Bounds of points that define path.
ui.Rect? fBounds;
/// Computed tight bounds of path (may exclude curve control points).
ui.Rect? cachedBounds;
int _fPointsCapacity = 0;
int _fPointsLength = 0;
int _fVerbsCapacity = 0;
Float32List fPoints;
Uint8List _fVerbs;
int _fVerbsLength = 0;
int _conicWeightsCapacity = 0;
Float32List? _conicWeights;
int _conicWeightsLength = 0;
// Resets state to initial except points and verbs storage.
void _resetFields() {
fBoundsIsDirty = true; // this also invalidates fIsFinite
fSegmentMask = 0;
fIsOval = false;
fIsRRect = false;
fIsRect = false;
// The next two values don't matter unless fIsOval or fIsRRect are true.
fRRectOrOvalIsCCW = false;
fRRectOrOvalStartIdx = 0xAC;
assert(() {
debugValidate();
return true;
}());
}
/// Given a point index stores [x],[y].
void setPoint(int pointIndex, double x, double y) {
assert(pointIndex < _fPointsLength);
final int index = pointIndex * 2;
fPoints[index] = x;
fPoints[index + 1] = y;
}
Float32List get points => fPoints;
Float32List? get conicWeights => _conicWeights;
int countPoints() => _fPointsLength;
int countVerbs() => _fVerbsLength;
int countWeights() => _conicWeightsLength;
/// Convenience method for reading verb at index.
int atVerb(int index) {
return _fVerbs[index];
}
ui.Offset atPoint(int index) {
return ui.Offset(fPoints[index * 2], fPoints[index * 2 + 1]);
}
double pointXAt(int index) => fPoints[index * 2];
double pointYAt(int index) => fPoints[index * 2 + 1];
double atWeight(int index) {
return _conicWeights![index];
}
/// Returns true if all of the points in this path are finite, meaning
/// there are no infinities and no NaNs.
bool get isFinite {
if (fBoundsIsDirty) {
_computeBounds();
}
return fIsFinite;
}
/// Returns a mask, where each bit corresponding to a SegmentMask is
/// set if the path contains 1 or more segments of that type.
/// Returns 0 for an empty path (no segments).
int get segmentMasks => fSegmentMask;
/// Returns start index if the path is an oval or -1 if not.
///
/// Tracking whether a path is an oval is considered an
/// optimization for performance and so some paths that are in
/// fact ovals can report false.
int get isOval => fIsOval ? fRRectOrOvalStartIdx : -1;
bool get isOvalCCW => fRRectOrOvalIsCCW;
int get isRRect => fIsRRect ? fRRectOrOvalStartIdx : -1;
int get isRect => fIsRect ? fRRectOrOvalStartIdx : -1;
ui.RRect? getRRect() => fIsRRect ? _getRRect() : null;
ui.Rect? getRect() {
/// Use _detectRect() for detection if explicitly addRect was used (fIsRect) or
/// it is a potential due to moveTo + 3 lineTo verbs.
if (fIsRect) {
return ui.Rect.fromLTRB(
atPoint(0).dx, atPoint(0).dy, atPoint(1).dx, atPoint(2).dy);
} else {
return _fVerbsLength == 4 ? _detectRect() : null;
}
}
bool get isRectCCW => fRRectOrOvalIsCCW;
bool get hasComputedBounds => !fBoundsIsDirty;
/// Returns the bounds of the path's points. If the path contains 0 or 1
/// points, the bounds is set to (0,0,0,0), and isEmpty() will return true.
/// Note: this bounds may be larger than the actual shape, since curves
/// do not extend as far as their control points.
ui.Rect getBounds() {
if (fBoundsIsDirty) {
_computeBounds();
}
return fBounds!;
}
/// Reconstructs Rect from path commands.
///
/// Detects clockwise starting with horizontal line.
ui.Rect? _detectRect() {
assert(_fVerbs[0] == SPath.kMoveVerb);
final double x0 = atPoint(0).dx;
final double y0 = atPoint(0).dy;
final double x1 = atPoint(1).dx;
final double y1 = atPoint(1).dy;
if (_fVerbs[1] != SPath.kLineVerb || y1 != y0) {
return null;
}
final double width = x1 - x0;
final double x2 = atPoint(2).dx;
final double y2 = atPoint(2).dy;
if (_fVerbs[2] != SPath.kLineVerb || x2 != x1) {
return null;
}
final double height = y2 - y1;
final double x3 = atPoint(3).dx;
final double y3 = atPoint(3).dy;
if (_fVerbs[3] != SPath.kLineVerb || y3 != y2) {
return null;
}
if ((x2 - x3) != width || (y3 - y0) != height) {
return null;
}
final double x = math.min(x0, x1);
final double y = math.min(y0, y2);
return ui.Rect.fromLTWH(x, y, width.abs(), height.abs());
}
/// Returns horizontal/vertical line bounds or null if not a line.
ui.Rect? getStraightLine() {
if (_fVerbsLength != 2 || _fVerbs[0] != SPath.kMoveVerb ||
_fVerbs[1] != SPath.kLineVerb) {
return null;
}
final double x0 = fPoints[0];
final double y0 = fPoints[1];
final double x1 = fPoints[2];
final double y1 = fPoints[3];
if (y0 == y1 || x0 == x1) {
return ui.Rect.fromLTRB(x0, y0, x1, y1);
}
return null;
}
/// Reconstructs RRect from path commands.
///
/// Expect 4 Conics and lines between.
/// Use conic points to calculate corner radius.
ui.RRect _getRRect() {
final ui.Rect bounds = getBounds();
// Radii x,y of 4 corners
final List<ui.Radius> radii = <ui.Radius>[];
final PathRefIterator iter = PathRefIterator(this);
final Float32List pts = Float32List(PathRefIterator.kMaxBufferSize);
int verb = iter.next(pts);
assert(SPath.kMoveVerb == verb);
int cornerIndex = 0;
while ((verb = iter.next(pts)) != SPath.kDoneVerb) {
if (SPath.kConicVerb == verb) {
final double controlPx = pts[2];
final double controlPy = pts[3];
final double vector1_0x = controlPx - pts[0];
final double vector1_0y = controlPy - pts[1];
final double vector2_1x = pts[4] - pts[2];
final double vector2_1y = pts[5] - pts[3];
double dx, dy;
// Depending on the corner we have control point at same
// horizontal position as startpoint or same vertical position.
// The location delta of control point specifies corner radius.
if (vector1_0x != 0.0) {
// For CW : Top right or bottom left corners.
dx = vector1_0x.abs();
dy = vector2_1y.abs();
} else if (vector1_0y != 0.0) {
dx = vector2_1x.abs();
dy = vector1_0y.abs();
} else {
dx = vector1_0x.abs();
dy = vector1_0y.abs();
}
assert(() {
final int checkCornerIndex = SPath.nearlyEqual(controlPx, bounds.left)
? (SPath.nearlyEqual(controlPy, bounds.top)
? _Corner.kUpperLeft
: _Corner.kLowerLeft)
: (SPath.nearlyEqual(controlPy, bounds.top)
? _Corner.kUpperRight
: _Corner.kLowerRight);
return checkCornerIndex == cornerIndex;
}());
radii.add(ui.Radius.elliptical(dx, dy));
++cornerIndex;
} else {
assert(() {
if (verb == SPath.kLineVerb) {
final bool isVerticalOrHorizontal =
SPath.nearlyEqual(pts[2], pts[0]) ||
SPath.nearlyEqual(pts[3], pts[1]);
assert(
isVerticalOrHorizontal,
'An RRect path must only contain vertical and horizontal lines.'
);
} else {
assert(verb == SPath.kCloseVerb);
}
return true;
}());
}
}
return ui.RRect.fromRectAndCorners(bounds,
topLeft: radii[_Corner.kUpperLeft],
topRight: radii[_Corner.kUpperRight],
bottomRight: radii[_Corner.kLowerRight],
bottomLeft: radii[_Corner.kLowerLeft]);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is PathRef && equals(other);
}
@override
int get hashCode => Object.hash(fSegmentMask,
fPoints, _conicWeights, _fVerbs);
bool equals(PathRef ref) {
// We explicitly check fSegmentMask as a quick-reject. We could skip it,
// since it is only a cache of info in the fVerbs, but its a fast way to
// notice a difference
if (fSegmentMask != ref.fSegmentMask) {
return false;
}
final int pointCount = countPoints();
if (pointCount != ref.countPoints()) {
return false;
}
final int len = pointCount * 2;
for (int i = 0; i < len; i++) {
if (fPoints[i] != ref.fPoints[i]) {
return false;
}
}
if (_conicWeights == null) {
if (ref._conicWeights != null) {
return false;
}
} else {
if (ref._conicWeights == null) {
return false;
}
final int weightCount = _conicWeights!.length;
if (ref._conicWeights!.length != weightCount) {
return false;
}
for (int i = 0; i < weightCount; i++) {
if (_conicWeights![i] != ref._conicWeights![i]) {
return false;
}
}
}
final int verbCount = countVerbs();
if (verbCount != ref.countVerbs()) {
return false;
}
for (int i = 0; i < verbCount; i++) {
if (_fVerbs[i] != ref._fVerbs[i]) {
return false;
}
}
if (ref.countVerbs() == 0) {
assert(ref.countPoints() == 0);
}
return true;
}
static Float32List _fPointsFromSource(
PathRef source, double offsetX, double offsetY) {
final int sourceLength = source._fPointsLength;
final int sourceCapacity = source._fPointsCapacity;
final Float32List dest = Float32List(sourceCapacity * 2);
final Float32List sourcePoints = source.points;
final int len = sourceLength * 2;
for (int i = 0; i < len; i += 2) {
dest[i] = sourcePoints[i] + offsetX;
dest[i + 1] = sourcePoints[i + 1] + offsetY;
}
return dest;
}
static Uint8List _fVerbsFromSource(PathRef source) {
final Uint8List verbs = Uint8List(source._fVerbsCapacity);
verbs.setAll(0, source._fVerbs);
return verbs;
}
/// Copies contents from a source path [ref].
void copy(
PathRef ref, int additionalReserveVerbs, int additionalReservePoints) {
ref.debugValidate();
final int verbCount = ref.countVerbs();
final int pointCount = ref.countPoints();
final int weightCount = ref.countWeights();
resetToSize(verbCount, pointCount, weightCount, additionalReserveVerbs,
additionalReservePoints);
_fVerbs.setAll(0, ref._fVerbs);
fPoints.setAll(0, ref.fPoints);
if (ref._conicWeights == null) {
_conicWeights = null;
} else {
_conicWeights!.setAll(0, ref._conicWeights!);
}
assert(verbCount == 0 || _fVerbs[0] == ref._fVerbs[0]);
fBoundsIsDirty = ref.fBoundsIsDirty;
if (!fBoundsIsDirty) {
fBounds = ref.fBounds;
cachedBounds = ref.cachedBounds;
fIsFinite = ref.fIsFinite;
}
fSegmentMask = ref.fSegmentMask;
fIsOval = ref.fIsOval;
fIsRRect = ref.fIsRRect;
fIsRect = ref.fIsRect;
fRRectOrOvalIsCCW = ref.fRRectOrOvalIsCCW;
fRRectOrOvalStartIdx = ref.fRRectOrOvalStartIdx;
debugValidate();
}
void _resizePoints(int newLength) {
if (newLength > _fPointsCapacity) {
_fPointsCapacity = newLength + 10;
final Float32List newPoints = Float32List(_fPointsCapacity * 2);
newPoints.setAll(0, fPoints);
fPoints = newPoints;
}
_fPointsLength = newLength;
}
void _resizeVerbs(int newLength) {
if (newLength > _fVerbsCapacity) {
_fVerbsCapacity = newLength + 8;
final Uint8List newVerbs = Uint8List(_fVerbsCapacity);
newVerbs.setAll(0, _fVerbs);
_fVerbs = newVerbs;
}
_fVerbsLength = newLength;
}
void _resizeConicWeights(int newLength) {
if (newLength > _conicWeightsCapacity) {
_conicWeightsCapacity = newLength + 4;
final Float32List newWeights = Float32List(_conicWeightsCapacity);
if (_conicWeights != null) {
newWeights.setAll(0, _conicWeights!);
}
_conicWeights = newWeights;
}
_conicWeightsLength = newLength;
}
void append(PathRef source) {
final int pointCount = source.countPoints();
final int curLength = _fPointsLength;
final int newPointCount = curLength + pointCount;
startEdit();
_resizePoints(newPointCount);
final Float32List sourcePoints = source.points;
for (int source = pointCount * 2 - 1, dst = newPointCount * 2 - 1;
source >= 0;
source--, dst--) {
fPoints[dst] = sourcePoints[source];
}
final int verbCount = countVerbs();
final int newVerbCount = source.countVerbs();
_resizeVerbs(verbCount + newVerbCount);
for (int i = 0; i < newVerbCount; i++) {
_fVerbs[verbCount + i] = source._fVerbs[i];
}
if (source._conicWeights != null) {
final int weightCount = countWeights();
final int newWeightCount = source.countWeights();
_resizeConicWeights(weightCount + newWeightCount);
final Float32List sourceWeights = source._conicWeights!;
final Float32List dest = _conicWeights!;
for (int i = 0; i < newWeightCount; i++) {
dest[weightCount + i] = sourceWeights[i];
}
}
fBoundsIsDirty = true;
}
/// Doesn't read fSegmentMask, but (re)computes it from the verbs array
int computeSegmentMask() {
final Uint8List verbs = _fVerbs;
int mask = 0;
final int verbCount = countVerbs();
for (int i = 0; i < verbCount; ++i) {
switch (verbs[i]) {
case SPath.kLineVerb:
mask |= SPath.kLineSegmentMask;
case SPath.kQuadVerb:
mask |= SPath.kQuadSegmentMask;
case SPath.kConicVerb:
mask |= SPath.kConicSegmentMask;
case SPath.kCubicVerb:
mask |= SPath.kCubicSegmentMask;
default:
break;
}
}
return mask;
}
/// This is incorrectly defined as instance method on SkPathRef although
/// SkPath instance method first makes a copy of itself into out and
/// then interpolates based on weight.
static void interpolate(PathRef ending, double weight, PathRef out) {
assert(out.countPoints() == ending.countPoints());
final int count = out.countPoints() * 2;
final Float32List outValues = out.points;
final Float32List inValues = ending.points;
for (int index = 0; index < count; ++index) {
outValues[index] =
outValues[index] * weight + inValues[index] * (1.0 - weight);
}
out.fBoundsIsDirty = true;
out.startEdit();
}
/// Computes bounds and fIsFinite based on points.
///
/// Used by getBounds() and cached.
void _computeBounds() {
debugValidate();
assert(fBoundsIsDirty);
final int pointCount = countPoints();
fBoundsIsDirty = false;
cachedBounds = null;
double accum = 0;
if (pointCount == 0) {
fBounds = ui.Rect.zero;
fIsFinite = true;
} else {
double minX, maxX, minY, maxY;
minX = maxX = fPoints[0];
accum *= minX;
minY = maxY = fPoints[1];
accum *= minY;
final int len = 2 * pointCount;
for (int i = 2; i < len; i += 2) {
final double x = fPoints[i];
accum *= x;
final double y = fPoints[i + 1];
accum *= y;
minX = math.min(minX, x);
minY = math.min(minY, y);
maxX = math.max(maxX, x);
maxY = math.max(maxY, y);
}
final bool allFinite = accum * 0 == 0;
if (allFinite) {
fBounds = ui.Rect.fromLTRB(minX, minY, maxX, maxY);
fIsFinite = true;
} else {
fBounds = ui.Rect.zero;
fIsFinite = false;
}
}
}
/// Sets to initial state preserving internal storage.
void rewind() {
_fPointsLength = 0;
_fVerbsLength = 0;
_conicWeightsLength = 0;
_resetFields();
}
/// Resets the path ref with verbCount verbs and pointCount points, all
/// uninitialized. Also allocates space for reserveVerb additional verbs
/// and reservePoints additional points.
void resetToSize(int verbCount, int pointCount, int conicCount,
[int reserveVerbs = 0, int reservePoints = 0]) {
debugValidate();
fBoundsIsDirty = true; // this also invalidates fIsFinite
fSegmentMask = 0;
startEdit();
_resizePoints(pointCount + reservePoints);
_resizeVerbs(verbCount + reserveVerbs);
_resizeConicWeights(conicCount);
debugValidate();
}
/// Increases the verb count 1, records the new verb, and creates room for
/// the requisite number of additional points. A pointer to the first point
/// is returned. Any new points are uninitialized.
int growForVerb(int verb, double weight) {
debugValidate();
int pCnt;
int mask = 0;
String? throwError;
switch (verb) {
case SPath.kMoveVerb:
pCnt = 1;
case SPath.kLineVerb:
mask = SPath.kLineSegmentMask;
pCnt = 1;
case SPath.kQuadVerb:
mask = SPath.kQuadSegmentMask;
pCnt = 2;
case SPath.kConicVerb:
mask = SPath.kConicSegmentMask;
pCnt = 2;
case SPath.kCubicVerb:
mask = SPath.kCubicSegmentMask;
pCnt = 3;
case SPath.kCloseVerb:
pCnt = 0;
case SPath.kDoneVerb:
assert(() {
throwError = 'growForVerb called for kDone';
return true;
}());
pCnt = 0;
default:
assert(() {
throwError = 'growForVerb called for unknown verb';
return true;
}());
pCnt = 0;
}
if (throwError != null) {
throw Exception(throwError);
}
fSegmentMask |= mask;
fBoundsIsDirty = true; // this also invalidates fIsFinite
startEdit();
final int verbCount = countVerbs();
_resizeVerbs(verbCount + 1);
_fVerbs[verbCount] = verb;
if (SPath.kConicVerb == verb) {
final int weightCount = countWeights();
_resizeConicWeights(weightCount + 1);
_conicWeights![weightCount] = weight;
}
final int ptsIndex = _fPointsLength;
_resizePoints(ptsIndex + pCnt);
debugValidate();
return ptsIndex;
}
/// Increases the verb count by numVbs and point count by the required amount.
/// The new points are uninitialized. All the new verbs are set to the
/// specified verb. If 'verb' is kConic_Verb, 'weights' will return a
/// pointer to the uninitialized conic weights.
///
/// This is an optimized version for [SPath.addPolygon].
int growForRepeatedVerb(int /*SkPath::Verb*/ verb, int numVbs) {
debugValidate();
startEdit();
int pCnt;
int mask = 0;
String? throwError;
switch (verb) {
case SPath.kMoveVerb:
pCnt = numVbs;
case SPath.kLineVerb:
mask = SPath.kLineSegmentMask;
pCnt = numVbs;
case SPath.kQuadVerb:
mask = SPath.kQuadSegmentMask;
pCnt = 2 * numVbs;
case SPath.kConicVerb:
mask = SPath.kConicSegmentMask;
pCnt = 2 * numVbs;
case SPath.kCubicVerb:
mask = SPath.kCubicSegmentMask;
pCnt = 3 * numVbs;
case SPath.kCloseVerb:
pCnt = 0;
case SPath.kDoneVerb:
assert(() {
throwError = 'growForVerb called for kDone';
return true;
}());
pCnt = 0;
default:
assert(() {
throwError = 'growForVerb called for unknown verb';
return true;
}());
pCnt = 0;
}
if (throwError != null) {
throw Exception(throwError);
}
fSegmentMask |= mask;
fBoundsIsDirty = true; // this also invalidates fIsFinite
startEdit();
if (SPath.kConicVerb == verb) {
_resizeConicWeights(countWeights() + numVbs);
}
final int verbCount = countVerbs();
_resizeVerbs(verbCount + numVbs);
for (int i = 0; i < numVbs; i++) {
_fVerbs[verbCount + i] = verb;
}
final int ptsIndex = _fPointsLength;
_resizePoints(ptsIndex + pCnt);
debugValidate();
return ptsIndex;
}
/// Concatenates all verbs from 'path' onto our own verbs array. Increases the point count by the
/// number of points in 'path', and the conic weight count by the number of conics in 'path'.
///
/// Returns pointers to the uninitialized points and conic weights data.
void growForVerbsInPath(PathRef path) {
debugValidate();
startEdit();
fSegmentMask |= path.fSegmentMask;
fBoundsIsDirty = true; // this also invalidates fIsFinite
final int numVerbs = path.countVerbs();
if (numVerbs != 0) {
final int curLength = countVerbs();
_resizePoints(curLength + numVerbs);
_fVerbs.setAll(curLength, path._fVerbs);
}
final int numPts = path.countPoints();
if (numPts != 0) {
final int curLength = countPoints();
_resizePoints(curLength + numPts);
fPoints.setAll(curLength * 2, path.fPoints);
}
final int numConics = path.countWeights();
if (numConics != 0) {
final int curLength = countWeights();
_resizeConicWeights(curLength + numConics);
final Float32List sourceWeights = path._conicWeights!;
final Float32List destWeights = _conicWeights!;
for (int i = 0; i < numConics; i++) {
destWeights[curLength + i] = sourceWeights[i];
}
}
debugValidate();
}
/// Resets higher level curve detection before a new edit is started.
///
/// SurfacePath.addOval, addRRect will set these flags after the verbs and
/// points are added.
void startEdit() {
fIsOval = false;
fIsRRect = false;
fIsRect = false;
cachedBounds = null;
fBoundsIsDirty = true;
}
void setIsOval(bool isOval, bool isCCW, int start) {
fIsOval = isOval;
fRRectOrOvalIsCCW = isCCW;
fRRectOrOvalStartIdx = start;
}
void setIsRRect(bool isRRect, bool isCCW, int start, ui.RRect rrect) {
fIsRRect = isRRect;
fRRectOrOvalIsCCW = isCCW;
fRRectOrOvalStartIdx = start;
}
void setIsRect(bool isRect, bool isCCW, int start) {
fIsRect = isRect;
fRRectOrOvalIsCCW = isCCW;
fRRectOrOvalStartIdx = start;
}
Float32List getPoints() {
debugValidate();
return fPoints;
}
static const int kMinSize = 256;
bool fBoundsIsDirty = true;
bool fIsFinite = true; // only meaningful if bounds are valid
bool fIsOval = false;
bool fIsRRect = false;
bool fIsRect = false;
// Both the circle and rrect special cases have a notion of direction and starting point
// The next two variables store that information for either.
bool fRRectOrOvalIsCCW = false;
int fRRectOrOvalStartIdx = -1;
int fSegmentMask = 0;
bool get isValid {
if (fIsOval || fIsRRect) {
// Currently we don't allow both of these to be set.
if (fIsOval == fIsRRect) {
return false;
}
if (fIsOval) {
if (fRRectOrOvalStartIdx >= 4) {
return false;
}
} else {
if (fRRectOrOvalStartIdx >= 8) {
return false;
}
}
}
if (fIsRect) {
if (fIsOval || fIsRRect) {
return false;
}
if (fRRectOrOvalStartIdx >= 4) {
return false;
}
}
if (!fBoundsIsDirty && !fBounds!.isEmpty) {
bool isFinite = true;
final ui.Rect bounds = fBounds!;
final double boundsLeft = bounds.left;
final double boundsTop = bounds.top;
final double boundsRight = bounds.right;
final double boundsBottom = bounds.bottom;
final int len = _fPointsLength * 2;
for (int i = 0; i < len; i += 2) {
final double pointX = fPoints[i];
final double pointY = fPoints[i + 1];
const double tolerance = 0.0001;
final bool pointIsFinite = pointX.isFinite && pointY.isFinite;
if (pointIsFinite &&
(pointX + tolerance < boundsLeft ||
pointY + tolerance < boundsTop ||
pointX - tolerance > boundsRight ||
pointY - tolerance > boundsBottom)) {
return false;
}
if (!pointIsFinite) {
isFinite = false;
}
}
if (fIsFinite != isFinite) {
// Inconsistent state. Cached [fIsFinite] doesn't match what we found.
return false;
}
}
return true;
}
bool get isEmpty => countVerbs() == 0;
void debugValidate() {
assert(isValid);
}
/// Returns point index of maximum y in path points.
int findMaxY(int pointIndex, int count) {
assert(count > 0);
// move to y component.
double max = fPoints[pointIndex * 2 + 1];
int firstIndex = pointIndex;
for (int i = 1; i < count; i++) {
final double y = fPoints[(pointIndex + i) * 2];
if (y > max) {
max = y;
firstIndex = pointIndex + i;
}
}
return firstIndex;
}
/// Returns index of point that is different from point at [index].
///
/// Used to get previous/next points that dont coincide for calculating
/// cross product at a point.
int findDiffPoint(int index, int n, int inc) {
int i = index;
for (;;) {
i = (i + inc) % n;
if (i == index) {
// we wrapped around, so abort
break;
}
if (fPoints[index * 2] != fPoints[i * 2] ||
fPoints[index * 2 + 1] != fPoints[i * 2 + 1]) {
// found a different point, success!
break;
}
}
return i;
}
}
class PathRefIterator {
PathRefIterator(this.pathRef) {
_pointIndex = 0;
if (!pathRef.isFinite) {
// Don't allow iteration through non-finite points, prepare to return
// done verb.
_verbIndex = pathRef.countVerbs();
}
}
final PathRef pathRef;
int _conicWeightIndex = -1;
int _verbIndex = 0;
int _pointIndex = 0;
/// Maximum buffer size required for points in [next] calls.
static const int kMaxBufferSize = 8;
int iterIndex = 0;
/// Returns current point index.
int get pointIndex => _pointIndex ~/ 2;
/// Advances to start of next contour (move verb).
///
/// Usage:
/// int startPointIndex = PathRefIterator._pointIndex;
/// int nextContourPointIndex = iter.skipToNextContour();
/// int pointCountInContour = nextContourPointIndex - startPointIndex;
int skipToNextContour() {
int verb = -1;
int curPointIndex = _pointIndex;
do {
curPointIndex = _pointIndex;
verb = nextIndex();
} while (
verb != SPath.kDoneVerb && (iterIndex == 0 || verb != SPath.kMoveVerb));
return (verb == SPath.kDoneVerb ? _pointIndex : curPointIndex) ~/ 2;
}
/// Returns next verb and [iterIndex] with location of first point.
int nextIndex() {
if (_verbIndex == pathRef.countVerbs()) {
return SPath.kDoneVerb;
}
final int verb = pathRef._fVerbs[_verbIndex++];
switch (verb) {
case SPath.kMoveVerb:
iterIndex = _pointIndex;
_pointIndex += 2;
case SPath.kLineVerb:
iterIndex = _pointIndex - 2;
_pointIndex += 2;
case SPath.kConicVerb:
_conicWeightIndex++;
iterIndex = _pointIndex - 2;
_pointIndex += 4;
case SPath.kQuadVerb:
iterIndex = _pointIndex - 2;
_pointIndex += 4;
case SPath.kCubicVerb:
iterIndex = _pointIndex - 2;
_pointIndex += 6;
case SPath.kCloseVerb:
break;
case SPath.kDoneVerb:
assert(_verbIndex == pathRef.countVerbs());
default:
throw FormatException('Unsupport Path verb $verb');
}
return verb;
}
// Returns next verb and reads associated points into [outPts].
int next(Float32List outPts) {
if (_verbIndex == pathRef.countVerbs()) {
return SPath.kDoneVerb;
}
final int verb = pathRef._fVerbs[_verbIndex++];
final Float32List points = pathRef.points;
int pointIndex = _pointIndex;
switch (verb) {
case SPath.kMoveVerb:
outPts[0] = points[pointIndex++];
outPts[1] = points[pointIndex++];
case SPath.kLineVerb:
outPts[0] = points[pointIndex - 2];
outPts[1] = points[pointIndex - 1];
outPts[2] = points[pointIndex++];
outPts[3] = points[pointIndex++];
case SPath.kConicVerb:
_conicWeightIndex++;
outPts[0] = points[pointIndex - 2];
outPts[1] = points[pointIndex - 1];
outPts[2] = points[pointIndex++];
outPts[3] = points[pointIndex++];
outPts[4] = points[pointIndex++];
outPts[5] = points[pointIndex++];
case SPath.kQuadVerb:
outPts[0] = points[pointIndex - 2];
outPts[1] = points[pointIndex - 1];
outPts[2] = points[pointIndex++];
outPts[3] = points[pointIndex++];
outPts[4] = points[pointIndex++];
outPts[5] = points[pointIndex++];
case SPath.kCubicVerb:
outPts[0] = points[pointIndex - 2];
outPts[1] = points[pointIndex - 1];
outPts[2] = points[pointIndex++];
outPts[3] = points[pointIndex++];
outPts[4] = points[pointIndex++];
outPts[5] = points[pointIndex++];
outPts[6] = points[pointIndex++];
outPts[7] = points[pointIndex++];
case SPath.kCloseVerb:
break;
case SPath.kDoneVerb:
assert(_verbIndex == pathRef.countVerbs());
default:
throw FormatException('Unsupport Path verb $verb');
}
_pointIndex = pointIndex;
return verb;
}
double get conicWeight => pathRef._conicWeights![_conicWeightIndex];
int peek() => _verbIndex < pathRef.countVerbs()
? pathRef._fVerbs[_verbIndex]
: SPath.kDoneVerb;
}
class _Corner {
static const int kUpperLeft = 0;
static const int kUpperRight = 1;
static const int kLowerRight = 2;
static const int kLowerLeft = 3;
}
| engine/lib/web_ui/lib/src/engine/html/path/path_ref.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/path/path_ref.dart",
"repo_id": "engine",
"token_count": 14161
} | 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.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../../safe_browser_api.dart';
import 'shader_builder.dart';
/// Converts colors and stops to typed array of bias, scale and threshold to use
/// in shaders.
///
/// A color is generated by taking a t value [0..1] and computing
/// t * scale + bias.
///
/// Example: For stops 0.0 t1, t2, 1.0 and colors c0, c1, c2, c3
/// Given t1<t<t2 outputColor = t * scale + bias.
/// = c1 + (t - t1)/(t2 - t1) * (c2 - c1)
/// = t * (c2 - c1)/(t2 - t1) + c1 - t1/(t2 - t1) * (c2 - c1)
/// scale = (c2 - c1) / (t2 - t1)
/// bias = c1 - t1 / (t2 - t1) * (c2 - c1)
class NormalizedGradient {
factory NormalizedGradient(List<ui.Color> colors, {List<double>? stops}) {
// If colorStops is not provided, then only two stops, at 0.0 and 1.0,
// are implied (and colors must therefore only have two entries).
assert(stops != null || colors.length == 2);
stops ??= const <double>[0.0, 1.0];
final int colorCount = colors.length;
int normalizedCount = colorCount;
final bool isOpaque = !colors.any((ui.Color c) => c.alpha < 1.0);
final bool addFirst = stops[0] != 0.0;
final bool addLast = stops.last != 1.0;
if (addFirst) {
normalizedCount++;
}
if (addLast) {
normalizedCount++;
}
final Float32List bias = Float32List(normalizedCount * 4);
final Float32List scale = Float32List(normalizedCount * 4);
final Float32List thresholds =
Float32List(4 * ((normalizedCount - 1) ~/ 4 + 1));
int targetIndex = 0;
int thresholdIndex = 0;
if (addFirst) {
final ui.Color c = colors[0];
bias[targetIndex++] = c.red / 255.0;
bias[targetIndex++] = c.green / 255.0;
bias[targetIndex++] = c.blue / 255.0;
bias[targetIndex++] = c.alpha / 255.0;
thresholds[thresholdIndex++] = 0.0;
}
for (final ui.Color c in colors) {
bias[targetIndex++] = c.red / 255.0;
bias[targetIndex++] = c.green / 255.0;
bias[targetIndex++] = c.blue / 255.0;
bias[targetIndex++] = c.alpha / 255.0;
}
for (final double stop in stops) {
thresholds[thresholdIndex++] = stop;
}
if (addLast) {
final ui.Color c = colors.last;
bias[targetIndex++] = c.red / 255.0;
bias[targetIndex++] = c.green / 255.0;
bias[targetIndex++] = c.blue / 255.0;
bias[targetIndex++] = c.alpha / 255.0;
thresholds[thresholdIndex++] = 1.0;
}
// Now that we have bias for each color stop, we can compute scale based
// on delta between colors.
final int lastColorIndex = 4 * (normalizedCount - 1);
for (int i = 0; i < lastColorIndex; i++) {
final int thresholdIndex = i >> 2;
scale[i] = (bias[i + 4] - bias[i]) /
(thresholds[thresholdIndex + 1] - thresholds[thresholdIndex]);
}
scale[lastColorIndex] = 0.0;
scale[lastColorIndex + 1] = 0.0;
scale[lastColorIndex + 2] = 0.0;
scale[lastColorIndex + 3] = 0.0;
// Compute bias = colorAtStop - stopValue * (scale).
for (int i = 0; i < normalizedCount; i++) {
final double t = thresholds[i];
final int colorIndex = i * 4;
bias[colorIndex] -= t * scale[colorIndex];
bias[colorIndex + 1] -= t * scale[colorIndex + 1];
bias[colorIndex + 2] -= t * scale[colorIndex + 2];
bias[colorIndex + 3] -= t * scale[colorIndex + 3];
}
return NormalizedGradient._(normalizedCount, thresholds, scale, bias, isOpaque);
}
NormalizedGradient._(
this.thresholdCount, this._thresholds, this._scale, this._bias, this.isOpaque);
final Float32List _thresholds;
final Float32List _bias;
final Float32List _scale;
final int thresholdCount;
final bool isOpaque;
/// Sets uniforms for threshold, bias and scale for program.
void setupUniforms(GlContext gl, GlProgram glProgram) {
for (int i = 0; i < thresholdCount; i++) {
final Object biasId = gl.getUniformLocation(glProgram.program, 'bias_$i');
gl.setUniform4f(biasId, _bias[i * 4], _bias[i * 4 + 1], _bias[i * 4 + 2],
_bias[i * 4 + 3]);
final Object scaleId = gl.getUniformLocation(glProgram.program, 'scale_$i');
gl.setUniform4f(scaleId, _scale[i * 4], _scale[i * 4 + 1],
_scale[i * 4 + 2], _scale[i * 4 + 3]);
}
for (int i = 0; i < _thresholds.length; i += 4) {
final Object thresId =
gl.getUniformLocation(glProgram.program, 'threshold_${i ~/ 4}');
gl.setUniform4f(thresId, _thresholds[i], _thresholds[i + 1],
_thresholds[i + 2], _thresholds[i + 3]);
}
}
/// Returns bias component at index.
double biasAt(int index) => _bias[index];
/// Returns scale component at index.
double scaleAt(int index) => _scale[index];
/// Returns threshold at index.
double thresholdAt(int index) => _thresholds[index];
}
/// Writes fragment shader code to search for probe value in source data and set
/// bias and scale to be used for computation.
///
/// Source data for thresholds is provided using ceil(count/4) packed vec4
/// uniforms.
///
/// Bias and scale data are vec4 uniforms that hold color data.
void writeUnrolledBinarySearch(ShaderMethod method, int start, int end,
{required String probe,
required String sourcePrefix,
required String biasName,
required String scaleName}) {
if (start == end) {
final String biasSource = '${biasName}_$start';
method.addStatement('$biasName = $biasSource;');
final String scaleSource = '${scaleName}_$start';
method.addStatement('$scaleName = $scaleSource;');
} else {
// Add probe check.
final int mid = (start + end) ~/ 2;
String thresholdAtMid = '${sourcePrefix}_${(mid + 1) ~/ 4}';
thresholdAtMid += '.${vectorComponentIndexToName((mid + 1) % 4)}';
method.addStatement('if ($probe < $thresholdAtMid) {');
method.indent();
writeUnrolledBinarySearch(method, start, mid,
probe: probe,
sourcePrefix: sourcePrefix,
biasName: biasName,
scaleName: scaleName);
method.unindent();
method.addStatement('} else {');
method.indent();
writeUnrolledBinarySearch(method, mid + 1, end,
probe: probe,
sourcePrefix: sourcePrefix,
biasName: biasName,
scaleName: scaleName);
method.unindent();
method.addStatement('}');
}
}
String vectorComponentIndexToName(int index) {
assert(index >= 0 && index <= 4);
return 'xyzw'[index];
}
| engine/lib/web_ui/lib/src/engine/html/shaders/normalized_gradient.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/shaders/normalized_gradient.dart",
"repo_id": "engine",
"token_count": 2637
} | 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.
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:ui/src/engine/scene_painting.dart';
import 'package:ui/src/engine/vector_math.dart';
import 'package:ui/ui.dart' as ui;
class EngineRootLayer with PictureEngineLayer {}
class BackdropFilterLayer
with PictureEngineLayer
implements ui.BackdropFilterEngineLayer {}
class BackdropFilterOperation implements LayerOperation {
BackdropFilterOperation(this.filter, this.mode);
final ui.ImageFilter filter;
final ui.BlendMode mode;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect;
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect contentRect) {
canvas.saveLayerWithFilter(contentRect, ui.Paint()..blendMode = mode, filter);
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() => const PlatformViewStyling();
}
class ClipPathLayer
with PictureEngineLayer
implements ui.ClipPathEngineLayer {}
class ClipPathOperation implements LayerOperation {
ClipPathOperation(this.path, this.clip);
final ui.Path path;
final ui.Clip clip;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect.intersect(path.getBounds());
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect contentRect) {
canvas.save();
canvas.clipPath(path, doAntiAlias: clip != ui.Clip.hardEdge);
if (clip == ui.Clip.antiAliasWithSaveLayer) {
canvas.saveLayer(path.getBounds(), ui.Paint());
}
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
if (clip == ui.Clip.antiAliasWithSaveLayer) {
canvas.restore();
}
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() {
// TODO(jacksongardner): implement clip styling for platform views
return const PlatformViewStyling();
}
}
class ClipRectLayer
with PictureEngineLayer
implements ui.ClipRectEngineLayer {}
class ClipRectOperation implements LayerOperation {
const ClipRectOperation(this.rect, this.clip);
final ui.Rect rect;
final ui.Clip clip;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect.intersect(rect);
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect contentRect) {
canvas.save();
canvas.clipRect(rect, doAntiAlias: clip != ui.Clip.hardEdge);
if (clip == ui.Clip.antiAliasWithSaveLayer) {
canvas.saveLayer(rect, ui.Paint());
}
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
if (clip == ui.Clip.antiAliasWithSaveLayer) {
canvas.restore();
}
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() {
// TODO(jacksongardner): implement clip styling for platform views
return const PlatformViewStyling();
}
}
class ClipRRectLayer
with PictureEngineLayer
implements ui.ClipRRectEngineLayer {}
class ClipRRectOperation implements LayerOperation {
const ClipRRectOperation(this.rrect, this.clip);
final ui.RRect rrect;
final ui.Clip clip;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect.intersect(rrect.outerRect);
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect contentRect) {
canvas.save();
canvas.clipRRect(rrect, doAntiAlias: clip != ui.Clip.hardEdge);
if (clip == ui.Clip.antiAliasWithSaveLayer) {
canvas.saveLayer(rrect.outerRect, ui.Paint());
}
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
if (clip == ui.Clip.antiAliasWithSaveLayer) {
canvas.restore();
}
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() {
// TODO(jacksongardner): implement clip styling for platform views
return const PlatformViewStyling();
}
}
class ColorFilterLayer
with PictureEngineLayer
implements ui.ColorFilterEngineLayer {}
class ColorFilterOperation implements LayerOperation {
ColorFilterOperation(this.filter);
final ui.ColorFilter filter;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect;
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect contentRect) {
canvas.saveLayer(contentRect, ui.Paint()..colorFilter = filter);
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() => const PlatformViewStyling();
}
class ImageFilterLayer
with PictureEngineLayer
implements ui.ImageFilterEngineLayer {}
class ImageFilterOperation implements LayerOperation {
ImageFilterOperation(this.filter, this.offset);
final ui.ImageFilter filter;
final ui.Offset offset;
@override
ui.Rect cullRect(ui.Rect contentRect) => (filter as SceneImageFilter).filterBounds(contentRect);
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect contentRect) {
if (offset != ui.Offset.zero) {
canvas.save();
canvas.translate(offset.dx, offset.dy);
}
final ui.Rect adjustedContentRect =
(filter as SceneImageFilter).filterBounds(contentRect);
canvas.saveLayer(adjustedContentRect, ui.Paint()..imageFilter = filter);
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
if (offset != ui.Offset.zero) {
canvas.restore();
}
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() {
if (offset != ui.Offset.zero) {
return PlatformViewStyling(
position: PlatformViewPosition.offset(offset)
);
} else {
return const PlatformViewStyling();
}
}
}
class OffsetLayer
with PictureEngineLayer
implements ui.OffsetEngineLayer {}
class OffsetOperation implements LayerOperation {
OffsetOperation(this.dx, this.dy);
final double dx;
final double dy;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect.shift(ui.Offset(dx, dy));
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect.shift(ui.Offset(-dx, -dy));
@override
void pre(SceneCanvas canvas, ui.Rect cullRect) {
canvas.save();
canvas.translate(dx, dy);
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() => PlatformViewStyling(
position: PlatformViewPosition.offset(ui.Offset(dx, dy))
);
}
class OpacityLayer
with PictureEngineLayer
implements ui.OpacityEngineLayer {}
class OpacityOperation implements LayerOperation {
OpacityOperation(this.alpha, this.offset);
final int alpha;
final ui.Offset offset;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect.shift(offset);
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect cullRect) {
if (offset != ui.Offset.zero) {
canvas.save();
canvas.translate(offset.dx, offset.dy);
cullRect = cullRect.shift(-offset);
}
canvas.saveLayer(
cullRect,
ui.Paint()..color = ui.Color.fromARGB(alpha, 0, 0, 0)
);
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
canvas.restore();
if (offset != ui.Offset.zero) {
canvas.restore();
}
}
@override
PlatformViewStyling createPlatformViewStyling() => PlatformViewStyling(
position: offset != ui.Offset.zero ? PlatformViewPosition.offset(offset) : const PlatformViewPosition.zero(),
opacity: alpha.toDouble() / 255.0,
);
}
class TransformLayer
with PictureEngineLayer
implements ui.TransformEngineLayer {}
class TransformOperation implements LayerOperation {
TransformOperation(this.transform);
final Float64List transform;
Matrix4 getMatrix() => Matrix4.fromFloat32List(toMatrix32(transform));
@override
ui.Rect cullRect(ui.Rect contentRect) => getMatrix().transformRect(contentRect);
@override
ui.Rect inverseMapRect(ui.Rect rect) {
final Matrix4 matrix = getMatrix()..invert();
return matrix.transformRect(rect);
}
@override
void pre(SceneCanvas canvas, ui.Rect cullRect) {
canvas.save();
canvas.transform(transform);
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() => PlatformViewStyling(
position: PlatformViewPosition.transform(getMatrix()),
);
}
class ShaderMaskLayer
with PictureEngineLayer
implements ui.ShaderMaskEngineLayer {}
class ShaderMaskOperation implements LayerOperation {
ShaderMaskOperation(this.shader, this.maskRect, this.blendMode);
final ui.Shader shader;
final ui.Rect maskRect;
final ui.BlendMode blendMode;
@override
ui.Rect cullRect(ui.Rect contentRect) => contentRect;
@override
ui.Rect inverseMapRect(ui.Rect rect) => rect;
@override
void pre(SceneCanvas canvas, ui.Rect contentRect) {
canvas.saveLayer(
contentRect,
ui.Paint(),
);
}
@override
void post(SceneCanvas canvas, ui.Rect contentRect) {
canvas.save();
canvas.translate(maskRect.left, maskRect.top);
canvas.drawRect(
ui.Rect.fromLTWH(0, 0, maskRect.width, maskRect.height),
ui.Paint()
..blendMode = blendMode
..shader = shader
);
canvas.restore();
canvas.restore();
}
@override
PlatformViewStyling createPlatformViewStyling() => const PlatformViewStyling();
}
class PlatformView {
PlatformView(this.viewId, this.size, this.styling);
int viewId;
// The bounds of this platform view, in the layer's local coordinate space.
ui.Size size;
PlatformViewStyling styling;
}
sealed class LayerSlice {
void dispose();
}
// A slice that contains one or more platform views to be rendered.
class PlatformViewSlice implements LayerSlice {
PlatformViewSlice(this.views, this.occlusionRect);
List<PlatformView> views;
// A conservative estimate of what area platform views in this slice may cover.
// This is expressed in the coordinate space of the parent.
ui.Rect? occlusionRect;
@override
void dispose() {}
}
// A slice that contains flutter content to be rendered int he form of a single
// ScenePicture.
class PictureSlice implements LayerSlice {
PictureSlice(this.picture);
ScenePicture picture;
@override
void dispose() => picture.dispose();
}
mixin PictureEngineLayer implements ui.EngineLayer {
// Each layer is represented as a series of "slices" which contain either
// flutter content or platform views. Slices in this list are ordered from
// bottom to top.
List<LayerSlice> slices = <LayerSlice>[];
@override
void dispose() {
for (final LayerSlice slice in slices) {
slice.dispose();
}
}
}
abstract class LayerOperation {
const LayerOperation();
// Given an input content rectangle, this returns a conservative estimate of
// the covering rectangle of the content after it has been processed by the
// layer operation.
ui.Rect cullRect(ui.Rect contentRect);
// Takes a rectangle in the layer's coordinate space and maps it to the parent
// coordinate space.
ui.Rect inverseMapRect(ui.Rect rect);
void pre(SceneCanvas canvas, ui.Rect contentRect);
void post(SceneCanvas canvas, ui.Rect contentRect);
PlatformViewStyling createPlatformViewStyling();
}
class PictureDrawCommand {
PictureDrawCommand(this.offset, this.picture);
ui.Offset offset;
ui.Picture picture;
}
// Represents how a platform view should be positioned in the scene.
// This object is immutable, so it can be reused across different platform
// views that have the same positioning.
class PlatformViewPosition {
// No transformation at all. We leave both fields null.
const PlatformViewPosition.zero() : offset = null, transform = null;
// A simple offset is the most common scenario. In those cases, we only
// store the offset and leave the transform as null
const PlatformViewPosition.offset(this.offset) : transform = null;
// In more complex cases, we store the transform. In those cases, the offset
// is left as null.
const PlatformViewPosition.transform(this.transform) : offset = null;
bool get isZero => (offset == null) && (transform == null);
final ui.Offset? offset;
final Matrix4? transform;
static PlatformViewPosition combine(PlatformViewPosition outer, PlatformViewPosition inner) {
// We try to reuse existing objects if possible, if they are immutable.
if (outer.isZero) {
return inner;
}
if (inner.isZero) {
return outer;
}
final ui.Offset? outerOffset = outer.offset;
final ui.Offset? innerOffset = inner.offset;
if (outerOffset != null && innerOffset != null) {
// Both positions are simple offsets, so they can be combined cheaply
// into another offset.
return PlatformViewPosition.offset(outerOffset + innerOffset);
}
// Otherwise, at least one of the positions involves a matrix transform.
final Matrix4 newTransform;
if (outerOffset != null) {
newTransform = Matrix4.translationValues(outerOffset.dx, outerOffset.dy, 0);
} else {
newTransform = outer.transform!.clone();
}
if (innerOffset != null) {
newTransform.translate(innerOffset.dx, innerOffset.dy);
} else {
newTransform.multiply(inner.transform!);
}
return PlatformViewPosition.transform(newTransform);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! PlatformViewPosition) {
return false;
}
return (offset == other.offset) && (transform == other.transform);
}
@override
int get hashCode {
return Object.hash(offset, transform);
}
}
// Represents the styling to be performed on a platform view when it is
// composited. This object is immutable so that it can be reused with different
// platform views that have the same styling.
class PlatformViewStyling {
const PlatformViewStyling({
this.position = const PlatformViewPosition.zero(),
this.opacity = 1.0
});
bool get isDefault => position.isZero && (opacity == 1.0);
final PlatformViewPosition position;
final double opacity;
static PlatformViewStyling combine(PlatformViewStyling outer, PlatformViewStyling inner) {
// Attempt to reuse one of the existing immutable objects.
if (outer.isDefault) {
return inner;
}
if (inner.isDefault) {
return outer;
}
return PlatformViewStyling(
position: PlatformViewPosition.combine(outer.position, inner.position),
opacity: outer.opacity * inner.opacity,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! PlatformViewStyling) {
return false;
}
return (position == other.position) && (opacity == other.opacity);
}
@override
int get hashCode {
return Object.hash(position, opacity);
}
}
class LayerBuilder {
factory LayerBuilder.rootLayer() {
return LayerBuilder._(null, EngineRootLayer(), null);
}
factory LayerBuilder.childLayer({
required LayerBuilder parent,
required PictureEngineLayer layer,
required LayerOperation operation
}) {
return LayerBuilder._(parent, layer, operation);
}
LayerBuilder._(
this.parent,
this.layer,
this.operation);
@visibleForTesting
static (ui.PictureRecorder, SceneCanvas) Function(ui.Rect)? debugRecorderFactory;
final LayerBuilder? parent;
final PictureEngineLayer layer;
final LayerOperation? operation;
final List<PictureDrawCommand> pendingPictures = <PictureDrawCommand>[];
List<PlatformView> pendingPlatformViews = <PlatformView>[];
ui.Rect? picturesRect;
ui.Rect? platformViewRect;
PlatformViewStyling? _memoizedPlatformViewStyling;
PlatformViewStyling _createPlatformViewStyling() {
final PlatformViewStyling? innerStyling = operation?.createPlatformViewStyling();
final PlatformViewStyling? outerStyling = parent?.platformViewStyling;
if (innerStyling == null) {
return outerStyling ?? const PlatformViewStyling();
}
if (outerStyling == null) {
return innerStyling;
}
return PlatformViewStyling.combine(outerStyling, innerStyling);
}
PlatformViewStyling get platformViewStyling {
return _memoizedPlatformViewStyling ??= _createPlatformViewStyling();
}
(ui.PictureRecorder, SceneCanvas) _createRecorder(ui.Rect rect) {
if (debugRecorderFactory != null) {
return debugRecorderFactory!(rect);
}
final ui.PictureRecorder recorder = ui.PictureRecorder();
final SceneCanvas canvas = ui.Canvas(recorder, rect) as SceneCanvas;
return (recorder, canvas);
}
void flushSlices() {
if (pendingPictures.isNotEmpty) {
// Merge the existing draw commands into a single picture and add a slice
// with that picture to the slice list.
final ui.Rect drawnRect = picturesRect ?? ui.Rect.zero;
final ui.Rect rect = operation?.cullRect(drawnRect) ?? drawnRect;
final (ui.PictureRecorder recorder, SceneCanvas canvas) = _createRecorder(rect);
operation?.pre(canvas, rect);
for (final PictureDrawCommand command in pendingPictures) {
if (command.offset != ui.Offset.zero) {
canvas.save();
canvas.translate(command.offset.dx, command.offset.dy);
canvas.drawPicture(command.picture);
canvas.restore();
} else {
canvas.drawPicture(command.picture);
}
}
operation?.post(canvas, rect);
final ui.Picture picture = recorder.endRecording();
layer.slices.add(PictureSlice(picture as ScenePicture));
}
if (pendingPlatformViews.isNotEmpty) {
// Take any pending platform views and lower them into a platform view
// slice.
ui.Rect? occlusionRect = platformViewRect;
if (occlusionRect != null && operation != null) {
occlusionRect = operation!.inverseMapRect(occlusionRect);
}
layer.slices.add(PlatformViewSlice(pendingPlatformViews, occlusionRect));
}
pendingPictures.clear();
pendingPlatformViews = <PlatformView>[];
// All the pictures and platform views have been lowered into slices. Clear
// our occlusion rectangles.
picturesRect = null;
platformViewRect = null;
}
void addPicture(
ui.Offset offset,
ui.Picture picture, {
bool isComplexHint = false,
bool willChangeHint = false
}) {
final ui.Rect cullRect = (picture as ScenePicture).cullRect;
final ui.Rect shiftedRect = cullRect.shift(offset);
final ui.Rect? currentPlatformViewRect = platformViewRect;
if (currentPlatformViewRect != null) {
// Whenever we add a picture to our layer, we try to see if the picture
// will overlap with any platform views that are currently on top of our
// drawing surface. If they don't overlap with the platform views, they
// can be grouped with the existing pending pictures.
if (pendingPictures.isEmpty || currentPlatformViewRect.overlaps(shiftedRect)) {
// If they do overlap with the platform views, however, we should flush
// all the current content into slices and start anew with a fresh
// group of pictures and platform views that will be rendered on top of
// the previous content. Note that we also flush if we have no pending
// pictures to group with. This is the case when platform views are
// the first thing in our stack of objects to composite, and it doesn't
// make sense to try to put a picture slice below the first platform
// view slice, even if the picture doesn't overlap.
flushSlices();
}
}
pendingPictures.add(PictureDrawCommand(offset, picture));
picturesRect = picturesRect?.expandToInclude(shiftedRect) ?? shiftedRect;
}
void addPlatformView(
int viewId, {
ui.Offset offset = ui.Offset.zero,
double width = 0.0,
double height = 0.0
}) {
final ui.Rect bounds = ui.Rect.fromLTWH(offset.dx, offset.dy, width, height);
platformViewRect = platformViewRect?.expandToInclude(bounds) ?? bounds;
final PlatformViewStyling layerStyling = platformViewStyling;
final PlatformViewStyling viewStyling = offset == ui.Offset.zero
? layerStyling
: PlatformViewStyling.combine(
layerStyling,
PlatformViewStyling(
position: PlatformViewPosition.offset(offset),
),
);
pendingPlatformViews.add(PlatformView(viewId, ui.Size(width, height), viewStyling));
}
void mergeLayer(PictureEngineLayer layer) {
// When we merge layers, we attempt to merge slices as much as possible as
// well, based on ordering of pictures and platform views and reusing the
// occlusion logic for determining where we can lower each picture.
for (final LayerSlice slice in layer.slices) {
switch (slice) {
case PictureSlice():
addPicture(ui.Offset.zero, slice.picture);
case PlatformViewSlice():
final ui.Rect? occlusionRect = slice.occlusionRect;
if (occlusionRect != null) {
platformViewRect = platformViewRect?.expandToInclude(occlusionRect) ?? occlusionRect;
}
pendingPlatformViews.addAll(slice.views);
}
}
}
PictureEngineLayer build() {
// Lower any pending pictures or platform views to their respective slices.
flushSlices();
return layer;
}
}
| engine/lib/web_ui/lib/src/engine/layers.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/layers.dart",
"repo_id": "engine",
"token_count": 7299
} | 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.
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../platform_dispatcher.dart';
import '../util.dart';
import 'semantics.dart';
/// Supplies generic accessibility focus features to semantics nodes that have
/// [ui.SemanticsFlag.isFocusable] set.
///
/// Assumes that the element being focused on is [SemanticsObject.element]. Role
/// managers with special needs can implement custom focus management and
/// exclude this role manager.
///
/// `"tab-index=0"` is used because `<flt-semantics>` is not intrinsically
/// focusable. Examples of intrinsically focusable elements include:
///
/// * <button>
/// * <input> (of any type)
/// * <a>
/// * <textarea>
///
/// See also:
///
/// * https://developer.mozilla.org/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets
class Focusable extends RoleManager {
Focusable(SemanticsObject semanticsObject, PrimaryRoleManager owner)
: _focusManager = AccessibilityFocusManager(semanticsObject.owner),
super(Role.focusable, semanticsObject, owner);
final AccessibilityFocusManager _focusManager;
/// Requests focus as a result of a route (e.g. dialog) deciding that the node
/// managed by this class should be focused by default when nothing requests
/// focus explicitly.
///
/// This method of taking focus is different from the regular method of using
/// the [SemanticsObject.hasFocus] flag, as in this case the framework did not
/// explicitly request focus. Instead, the DOM element is being focus directly
/// programmatically, simulating the screen reader choosing a default element
/// to focus on.
///
/// Returns `true` if the role manager took the focus. Returns `false` if
/// this role manager did not take the focus. The return value can be used to
/// decide whether to stop searching for a node that should take focus.
bool focusAsRouteDefault() {
owner.element.focus();
return true;
}
@override
void update() {
if (semanticsObject.isFocusable) {
if (!_focusManager.isManaging) {
_focusManager.manage(semanticsObject.id, owner.element);
}
_focusManager.changeFocus(semanticsObject.hasFocus && (!semanticsObject.hasEnabledState || semanticsObject.isEnabled));
} else {
_focusManager.stopManaging();
}
}
@override
void dispose() {
super.dispose();
_focusManager.stopManaging();
}
}
/// Objects associated with the element whose focus is being managed.
typedef _FocusTarget = ({
/// [SemanticsObject.id] of the semantics node being managed.
int semanticsNodeId,
/// The element whose focus is being managed.
DomElement element,
/// The listener for the "focus" DOM event.
DomEventListener domFocusListener,
/// The listener for the "blur" DOM event.
DomEventListener domBlurListener,
});
/// Implements accessibility focus management for arbitrary elements.
///
/// Unlike [Focusable], which implements focus features on [SemanticsObject]s
/// whose [SemanticsObject.element] is directly focusable, this class can help
/// implementing focus features on custom elements. For example, [Incrementable]
/// uses a custom `<input>` tag internally while its root-level element is not
/// focusable. However, it can still use this class to manage the focus of the
/// internal element.
class AccessibilityFocusManager {
/// Creates a focus manager tied to a specific [EngineSemanticsOwner].
AccessibilityFocusManager(this._owner);
final EngineSemanticsOwner _owner;
_FocusTarget? _target;
// The last focus value set by this focus manager, used to prevent requesting
// focus on the same element repeatedly. Requesting focus on DOM elements is
// not an idempotent operation. If the element is already focused and focus is
// requested the browser will scroll to that element. However, scrolling is
// not this class' concern and so this class should avoid doing anything that
// would affect scrolling.
bool? _lastSetValue;
/// Whether this focus manager is managing a focusable target.
bool get isManaging => _target != null;
/// Starts managing the focus of the given [element].
///
/// The "focus" and "blur" DOM events are forwarded to the framework-side
/// semantics node with ID [semanticsNodeId] as [ui.SemanticsAction]s.
///
/// If this manage was already managing a different element, stops managing
/// the old element and starts managing the new one.
///
/// Calling this with the same element but a different [semanticsNodeId] will
/// cause any future focus/blur events to be forwarded to the new ID.
void manage(int semanticsNodeId, DomElement element) {
if (identical(element, _target?.element)) {
final _FocusTarget previousTarget = _target!;
if (semanticsNodeId == previousTarget.semanticsNodeId) {
return;
}
// No need to hook up new DOM listeners. The existing ones are good enough.
_target = (
semanticsNodeId: semanticsNodeId,
element: previousTarget.element,
domFocusListener: previousTarget.domFocusListener,
domBlurListener: previousTarget.domBlurListener,
);
return;
}
if (_target != null) {
// The element changed. Clear the old element before initializing the new one.
stopManaging();
}
final _FocusTarget newTarget = (
semanticsNodeId: semanticsNodeId,
element: element,
domFocusListener: createDomEventListener((_) => _setFocusFromDom(true)),
domBlurListener: createDomEventListener((_) => _setFocusFromDom(false)),
);
_target = newTarget;
element.tabIndex = 0;
element.addEventListener('focus', newTarget.domFocusListener);
element.addEventListener('blur', newTarget.domBlurListener);
}
/// Stops managing the focus of the current element, if any.
void stopManaging() {
final _FocusTarget? target = _target;
_target = null;
_lastSetValue = null;
if (target == null) {
/// Nothing is being managed. Just return.
return;
}
target.element.removeEventListener('focus', target.domFocusListener);
target.element.removeEventListener('blur', target.domBlurListener);
}
void _setFocusFromDom(bool acquireFocus) {
final _FocusTarget? target = _target;
if (target == null) {
// DOM events can be asynchronous. By the time the event reaches here, the
// focus manager may have been disposed of.
return;
}
EnginePlatformDispatcher.instance.invokeOnSemanticsAction(
target.semanticsNodeId,
acquireFocus
? ui.SemanticsAction.didGainAccessibilityFocus
: ui.SemanticsAction.didLoseAccessibilityFocus,
null,
);
}
/// Requests focus or blur on the DOM element.
void changeFocus(bool value) {
final _FocusTarget? target = _target;
if (target == null) {
// If this branch is being executed, there's a bug somewhere already, but
// it doesn't hurt to clean up old values anyway.
_lastSetValue = null;
// Nothing is being managed right now.
assert(() {
printWarning(
'Cannot change focus to $value. No element is being managed by this '
'AccessibilityFocusManager.'
);
return true;
}());
return;
}
if (value == _lastSetValue) {
// The focus is being changed to a value that's already been requested in
// the past. Do nothing.
return;
}
_lastSetValue = value;
if (value) {
_owner.willRequestFocus();
} else {
// Do not blur elements. Instead let the element be blurred by requesting
// focus elsewhere. Blurring elements is a very error-prone thing to do,
// as it is subject to non-local effects. Let's say the framework decides
// that a semantics node is currently not focused. That would lead to
// changeFocus(false) to be called. However, what if this node is inside
// a dialog, and nothing else in the dialog is focused. The Flutter
// framework expects that the screen reader will focus on the first (in
// traversal order) focusable element inside the dialog and send a
// didGainAccessibilityFocus action. Screen readers on the web do not do
// that, and so the web engine has to implement this behavior directly. So
// the dialog will look for a focusable element and request focus on it,
// but now there may be a race between this method unsetting the focus and
// the dialog requesting focus on the same element.
return;
}
// Delay the focus request until the final DOM structure is established
// because the element may not yet be attached to the DOM, or it may be
// reparented and lose focus again.
_owner.addOneTimePostUpdateCallback(() {
if (_target != target) {
// The element may have been swapped or the manager may have been disposed
// of between the focus change request and the post update callback
// invocation. So check again that the element is still the same and is
// not null.
return;
}
target.element.focus();
});
}
}
| engine/lib/web_ui/lib/src/engine/semantics/focusable.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/semantics/focusable.dart",
"repo_id": "engine",
"token_count": 2857
} | 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.
import 'dart:typed_data';
import 'buffers.dart';
/// Write-only buffer for incrementally building a [ByteData] instance.
///
/// A WriteBuffer instance can be used only once. Attempts to reuse will result
/// in [NoSuchMethodError]s being thrown.
///
/// The byte order used is [Endian.host] throughout.
class WriteBuffer {
/// Creates an interface for incrementally building a [ByteData] instance.
factory WriteBuffer() {
final Uint8Buffer buffer = Uint8Buffer();
final ByteData eightBytes = ByteData(8);
final Uint8List eightBytesAsList = eightBytes.buffer.asUint8List();
return WriteBuffer._(buffer, eightBytes, eightBytesAsList);
}
WriteBuffer._(this._buffer, this._eightBytes, this._eightBytesAsList);
bool _debugFinalized = false;
final Uint8Buffer _buffer;
final ByteData _eightBytes;
final Uint8List _eightBytesAsList;
/// Write a Uint8 into the buffer.
void putUint8(int byte) {
assert(!_debugFinalized);
_buffer.add(byte);
}
/// Write a Uint16 into the buffer.
void putUint16(int value) {
assert(!_debugFinalized);
_eightBytes.setUint16(0, value, Endian.host);
_buffer.addAll(_eightBytesAsList, 0, 2);
}
/// Write a Uint32 into the buffer.
void putUint32(int value) {
assert(!_debugFinalized);
_eightBytes.setUint32(0, value, Endian.host);
_buffer.addAll(_eightBytesAsList, 0, 4);
}
/// Write an Int32 into the buffer.
void putInt32(int value) {
assert(!_debugFinalized);
_eightBytes.setInt32(0, value, Endian.host);
_buffer.addAll(_eightBytesAsList, 0, 4);
}
/// Write an Int64 into the buffer.
void putInt64(int value) {
assert(!_debugFinalized);
_eightBytes.setInt64(0, value, Endian.host);
_buffer.addAll(_eightBytesAsList, 0, 8);
}
/// Write an Float64 into the buffer.
void putFloat64(double value) {
assert(!_debugFinalized);
_alignTo(8);
_eightBytes.setFloat64(0, value, Endian.host);
_buffer.addAll(_eightBytesAsList);
}
/// Write all the values from a [Uint8List] into the buffer.
void putUint8List(Uint8List list) {
assert(!_debugFinalized);
_buffer.addAll(list);
}
/// Write all the values from a [Int32List] into the buffer.
void putInt32List(Int32List list) {
assert(!_debugFinalized);
_alignTo(4);
_buffer
.addAll(list.buffer.asUint8List(list.offsetInBytes, 4 * list.length));
}
/// Write all the values from an [Int64List] into the buffer.
void putInt64List(Int64List list) {
assert(!_debugFinalized);
_alignTo(8);
_buffer
.addAll(list.buffer.asUint8List(list.offsetInBytes, 8 * list.length));
}
/// Write all the values from a [Float64List] into the buffer.
void putFloat64List(Float64List list) {
assert(!_debugFinalized);
_alignTo(8);
_buffer
.addAll(list.buffer.asUint8List(list.offsetInBytes, 8 * list.length));
}
void _alignTo(int alignment) {
final int mod = _buffer.length % alignment;
if (mod != 0) {
for (int i = 0; i < alignment - mod; i++) {
_buffer.add(0);
}
}
}
/// Finalize and return the written [ByteData].
ByteData done() {
_debugFinalized = true;
final ByteData result = _buffer.buffer.asByteData(0, _buffer.lengthInBytes);
return result;
}
}
/// Read-only buffer for reading sequentially from a [ByteData] instance.
///
/// The byte order used is [Endian.host] throughout.
class ReadBuffer {
/// Creates a [ReadBuffer] for reading from the specified [data].
ReadBuffer(this.data);
/// The underlying data being read.
final ByteData data;
/// The position to read next.
int _position = 0;
/// Whether the buffer has data remaining to read.
bool get hasRemaining => _position < data.lengthInBytes;
/// Reads a Uint8 from the buffer.
int getUint8() {
return data.getUint8(_position++);
}
/// Reads a Uint16 from the buffer.
int getUint16() {
final int value = data.getUint16(_position, Endian.host);
_position += 2;
return value;
}
/// Reads a Uint32 from the buffer.
int getUint32() {
final int value = data.getUint32(_position, Endian.host);
_position += 4;
return value;
}
/// Reads an Int32 from the buffer.
int getInt32() {
final int value = data.getInt32(_position, Endian.host);
_position += 4;
return value;
}
/// Reads an Int64 from the buffer.
int getInt64() {
final int value = data.getInt64(_position, Endian.host);
_position += 8;
return value;
}
/// Reads a Float64 from the buffer.
double getFloat64() {
_alignTo(8);
final double value = data.getFloat64(_position, Endian.host);
_position += 8;
return value;
}
/// Reads the given number of Uint8s from the buffer.
Uint8List getUint8List(int length) {
final Uint8List list =
data.buffer.asUint8List(data.offsetInBytes + _position, length);
_position += length;
return list;
}
/// Reads the given number of Int32s from the buffer.
Int32List getInt32List(int length) {
_alignTo(4);
final Int32List list =
data.buffer.asInt32List(data.offsetInBytes + _position, length);
_position += 4 * length;
return list;
}
/// Reads the given number of Int64s from the buffer.
Int64List getInt64List(int length) {
_alignTo(8);
final Int64List list =
data.buffer.asInt64List(data.offsetInBytes + _position, length);
_position += 8 * length;
return list;
}
/// Reads the given number of Float64s from the buffer.
Float64List getFloat64List(int length) {
_alignTo(8);
final Float64List list =
data.buffer.asFloat64List(data.offsetInBytes + _position, length);
_position += 8 * length;
return list;
}
void _alignTo(int alignment) {
final int mod = _position % alignment;
if (mod != 0) {
_position += alignment - mod;
}
}
}
| engine/lib/web_ui/lib/src/engine/services/serialization.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/services/serialization.dart",
"repo_id": "engine",
"token_count": 2195
} | 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.
@DefaultAsset('skwasm')
library skwasm_impl;
import 'dart:ffi';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
final class RawCanvas extends Opaque {}
typedef CanvasHandle = Pointer<RawCanvas>;
@Native<Void Function(CanvasHandle)>(symbol: 'canvas_save', isLeaf: true)
external void canvasSave(CanvasHandle canvas);
@Native<Void Function(
CanvasHandle,
RawRect,
PaintHandle,
ImageFilterHandle,
)>(symbol: 'canvas_saveLayer', isLeaf: true)
external void canvasSaveLayer(
CanvasHandle canvas,
RawRect rect,
PaintHandle paint,
ImageFilterHandle handle,
);
@Native<Void Function(CanvasHandle)>(symbol: 'canvas_restore', isLeaf: true)
external void canvasRestore(CanvasHandle canvas);
@Native<Void Function(CanvasHandle, Int)>(
symbol: 'canvas_restoreToCount', isLeaf: true)
external void canvasRestoreToCount(CanvasHandle canvas, int count);
@Native<Int Function(CanvasHandle)>(symbol: 'canvas_getSaveCount', isLeaf: true)
external int canvasGetSaveCount(CanvasHandle canvas);
@Native<Void Function(CanvasHandle, Float, Float)>(
symbol: 'canvas_translate', isLeaf: true)
external void canvasTranslate(CanvasHandle canvas, double dx, double dy);
@Native<Void Function(CanvasHandle, Float, Float)>(
symbol: 'canvas_scale', isLeaf: true)
external void canvasScale(CanvasHandle canvas, double sx, double sy);
@Native<Void Function(CanvasHandle, Float)>(
symbol: 'canvas_rotate', isLeaf: true)
external void canvasRotate(CanvasHandle canvas, double degrees);
@Native<Void Function(CanvasHandle, Float, Float)>(
symbol: 'canvas_skew', isLeaf: true)
external void canvasSkew(CanvasHandle canvas, double sx, double sy);
@Native<Void Function(CanvasHandle, RawMatrix44)>(
symbol: 'canvas_transform', isLeaf: true)
external void canvasTransform(CanvasHandle canvas, RawMatrix44 matrix);
@Native<Void Function(CanvasHandle, RawRect, Int, Bool)>(
symbol: 'canvas_clipRect', isLeaf: true)
external void canvasClipRect(
CanvasHandle canvas, RawRect rect, int op, bool antialias);
@Native<Void Function(CanvasHandle, RawRRect, Bool)>(
symbol: 'canvas_clipRRect', isLeaf: true)
external void canvasClipRRect(
CanvasHandle canvas, RawRRect rrect, bool antialias);
@Native<Void Function(CanvasHandle, PathHandle, Bool)>(
symbol: 'canvas_clipPath', isLeaf: true)
external void canvasClipPath(
CanvasHandle canvas, PathHandle path, bool antialias);
@Native<Void Function(CanvasHandle, Int32, Int)>(
symbol: 'canvas_drawColor', isLeaf: true)
external void canvasDrawColor(CanvasHandle canvas, int color, int blendMode);
@Native<Void Function(CanvasHandle, Float, Float, Float, Float, PaintHandle)>(
symbol: 'canvas_drawLine', isLeaf: true)
external void canvasDrawLine(CanvasHandle canvas, double x1, double y1,
double x2, double y2, PaintHandle paint);
@Native<Void Function(CanvasHandle, PaintHandle)>(
symbol: 'canvas_drawPaint', isLeaf: true)
external void canvasDrawPaint(CanvasHandle canvas, PaintHandle paint);
@Native<Void Function(CanvasHandle, RawRect, PaintHandle)>(
symbol: 'canvas_drawRect', isLeaf: true)
external void canvasDrawRect(
CanvasHandle canvas, RawRect rect, PaintHandle paint);
@Native<Void Function(CanvasHandle, RawRRect, PaintHandle)>(
symbol: 'canvas_drawRRect', isLeaf: true)
external void canvasDrawRRect(
CanvasHandle canvas, RawRRect rrect, PaintHandle paint);
@Native<Void Function(CanvasHandle, RawRRect, RawRRect, PaintHandle)>(
symbol: 'canvas_drawDRRect', isLeaf: true)
external void canvasDrawDRRect(
CanvasHandle canvas, RawRRect outer, RawRRect inner, PaintHandle paint);
@Native<Void Function(CanvasHandle, RawRect, PaintHandle)>(
symbol: 'canvas_drawOval', isLeaf: true)
external void canvasDrawOval(
CanvasHandle canvas, RawRect oval, PaintHandle paint);
@Native<Void Function(CanvasHandle, Float, Float, Float, PaintHandle)>(
symbol: 'canvas_drawCircle', isLeaf: true)
external void canvasDrawCircle(
CanvasHandle canvas, double x, double y, double radius, PaintHandle paint);
@Native<Void Function(CanvasHandle, RawRect, Float, Float, Bool, PaintHandle)>(
symbol: 'canvas_drawArc', isLeaf: true)
external void canvasDrawArc(
CanvasHandle canvas,
RawRect rect,
double startAngleDegrees,
double sweepAngleDegrees,
bool useCenter,
PaintHandle paint);
@Native<Void Function(CanvasHandle, PathHandle, PaintHandle)>(
symbol: 'canvas_drawPath', isLeaf: true)
external void canvasDrawPath(
CanvasHandle canvas, PathHandle path, PaintHandle paint);
@Native<Void Function(CanvasHandle, PictureHandle)>(
symbol: 'canvas_drawPicture', isLeaf: true)
external void canvasDrawPicture(CanvasHandle canvas, PictureHandle picture);
@Native<Void Function(
CanvasHandle,
ImageHandle,
Float,
Float,
PaintHandle,
Int
)>(symbol: 'canvas_drawImage', isLeaf: true)
external void canvasDrawImage(
CanvasHandle handle,
ImageHandle image,
double offsetX,
double offsetY,
PaintHandle paint,
int filterQuality,
);
@Native<Void Function(
CanvasHandle,
ImageHandle,
Pointer<Float>,
Pointer<Float>,
PaintHandle,
Int,
)>(symbol: 'canvas_drawImageRect', isLeaf: true)
external void canvasDrawImageRect(
CanvasHandle handle,
ImageHandle image,
Pointer<Float> sourceRect,
Pointer<Float> destRect,
PaintHandle paint,
int filterQuality,
);
@Native<Void Function(
CanvasHandle,
ImageHandle,
Pointer<Int32>,
Pointer<Float>,
PaintHandle,
Int,
)>(symbol: 'canvas_drawImageNine', isLeaf: true)
external void canvasDrawImageNine(
CanvasHandle handle,
ImageHandle image,
Pointer<Int32> centerRect,
Pointer<Float> destRect,
PaintHandle paint,
int filterQuality,
);
@Native<Void Function(CanvasHandle, PathHandle, Float, Float, Int32, Bool)>(
symbol: 'canvas_drawShadow', isLeaf: true)
external void canvasDrawShadow(
CanvasHandle canvas,
PathHandle path,
double elevation,
double devicePixelRatio,
int color,
bool transparentOccluder,
);
@Native<Void Function(
CanvasHandle,
ParagraphHandle,
Float,
Float,
)>(symbol: 'canvas_drawParagraph', isLeaf: true)
external void canvasDrawParagraph(
CanvasHandle handle,
ParagraphHandle paragraphHandle,
double x,
double y,
);
@Native<Void Function(
CanvasHandle,
VerticesHandle,
Int,
PaintHandle,
)>(symbol: 'canvas_drawVertices', isLeaf: true)
external void canvasDrawVertices(
CanvasHandle handle,
VerticesHandle vertices,
int blendMode,
PaintHandle paint,
);
@Native<Void Function(
CanvasHandle,
Int,
RawPointArray,
Int,
PaintHandle,
)>(symbol: 'canvas_drawPoints', isLeaf: true)
external void canvasDrawPoints(
CanvasHandle handle,
int pointMode,
RawPointArray points,
int pointCount,
PaintHandle paint,
);
@Native<Void Function(
CanvasHandle,
ImageHandle,
RawRSTransformArray,
RawRect,
RawColorArray,
Int,
Int,
RawRect,
PaintHandle,
)>(symbol: 'canvas_drawAtlas', isLeaf: true)
external void canvasDrawAtlas(
CanvasHandle handle,
ImageHandle atlas,
RawRSTransformArray transforms,
RawRect rects,
RawColorArray colors,
int spriteCount,
int blendMode,
RawRect cullRect,
PaintHandle paint,
);
@Native<Void Function(CanvasHandle, RawMatrix44)>(
symbol: 'canvas_getTransform', isLeaf: true)
external void canvasGetTransform(CanvasHandle canvas, RawMatrix44 outMatrix);
@Native<Void Function(CanvasHandle, RawRect)>(
symbol: 'canvas_getLocalClipBounds', isLeaf: true)
external void canvasGetLocalClipBounds(CanvasHandle canvas, RawRect outRect);
@Native<Void Function(CanvasHandle, RawIRect)>(
symbol: 'canvas_getDeviceClipBounds', isLeaf: true)
external void canvasGetDeviceClipBounds(CanvasHandle canvas, RawIRect outRect);
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_canvas.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_canvas.dart",
"repo_id": "engine",
"token_count": 2649
} | 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.
@DefaultAsset('skwasm')
library skwasm_impl;
import 'dart:ffi';
final class RawLineMetrics extends Opaque {}
typedef LineMetricsHandle = Pointer<RawLineMetrics>;
@Native<LineMetricsHandle Function(
Bool,
Double,
Double,
Double,
Double,
Double,
Double,
Double,
Size,
)>(symbol: 'lineMetrics_create', isLeaf: true)
external LineMetricsHandle lineMetricsCreate(
bool hardBreak,
double ascent,
double descent,
double unscaledAscent,
double height,
double width,
double left,
double baseline,
int lineNumber
);
@Native<Void Function(LineMetricsHandle)>(symbol: 'lineMetrics_dispose', isLeaf: true)
external void lineMetricsDispose(LineMetricsHandle handle);
@Native<Bool Function(LineMetricsHandle)>(symbol: 'lineMetrics_getHardBreak', isLeaf: true)
external bool lineMetricsGetHardBreak(LineMetricsHandle handle);
@Native<Float Function(LineMetricsHandle)>(symbol: 'lineMetrics_getAscent', isLeaf: true)
external double lineMetricsGetAscent(LineMetricsHandle handle);
@Native<Float Function(LineMetricsHandle)>(symbol: 'lineMetrics_getDescent', isLeaf: true)
external double lineMetricsGetDescent(LineMetricsHandle handle);
@Native<Float Function(LineMetricsHandle)>(symbol: 'lineMetrics_getUnscaledAscent', isLeaf: true)
external double lineMetricsGetUnscaledAscent(LineMetricsHandle handle);
@Native<Float Function(LineMetricsHandle)>(symbol: 'lineMetrics_getHeight', isLeaf: true)
external double lineMetricsGetHeight(LineMetricsHandle handle);
@Native<Float Function(LineMetricsHandle)>(symbol: 'lineMetrics_getWidth', isLeaf: true)
external double lineMetricsGetWidth(LineMetricsHandle handle);
@Native<Float Function(LineMetricsHandle)>(symbol: 'lineMetrics_getLeft', isLeaf: true)
external double lineMetricsGetLeft(LineMetricsHandle handle);
@Native<Float Function(LineMetricsHandle)>(symbol: 'lineMetrics_getBaseline', isLeaf: true)
external double lineMetricsGetBaseline(LineMetricsHandle handle);
@Native<Int Function(LineMetricsHandle)>(symbol: 'lineMetrics_getLineNumber', isLeaf: true)
external int lineMetricsGetLineNumber(LineMetricsHandle handle);
@Native<Size Function(LineMetricsHandle)>(symbol: 'lineMetrics_getStartIndex', isLeaf: true)
external int lineMetricsGetStartIndex(LineMetricsHandle handle);
@Native<Size Function(LineMetricsHandle)>(symbol: 'lineMetrics_getEndIndex', isLeaf: true)
external int lineMetricsGetEndIndex(LineMetricsHandle handle);
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/text/raw_line_metrics.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/text/raw_line_metrics.dart",
"repo_id": "engine",
"token_count": 804
} | 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.
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
/// This class is responsible for registering and loading fonts.
///
/// Once an asset manager has been set in the framework, call
/// [downloadAssetFonts] with it to register fonts declared in the
/// font manifest. If test fonts are enabled, then call
/// [debugDownloadTestFonts] as well.
class HtmlFontCollection implements FlutterFontCollection {
/// Reads the font manifest using the [ui_web.assetManager] and downloads all of the
/// fonts declared within.
@override
Future<AssetFontsResult> loadAssetFonts(FontManifest manifest) async {
final List<Future<(String, FontLoadError?)>> pendingFonts = <Future<(String, FontLoadError?)>>[];
for (final FontFamily family in manifest.families) {
for (final FontAsset fontAsset in family.fontAssets) {
pendingFonts.add(() async {
return (
fontAsset.asset,
await _loadFontAsset(family.name, fontAsset.asset, fontAsset.descriptors)
);
}());
}
}
final List<String> loadedFonts = <String>[];
final Map<String, FontLoadError> fontFailures = <String, FontLoadError>{};
for (final (String asset, FontLoadError? error) in await Future.wait(pendingFonts)) {
if (error == null) {
loadedFonts.add(asset);
} else {
fontFailures[asset] = error;
}
}
return AssetFontsResult(loadedFonts, fontFailures);
}
@override
Future<bool> loadFontFromList(Uint8List list, {String? fontFamily}) async {
if (fontFamily == null) {
printWarning('Font family must be provided to HtmlFontCollection.');
return false;
}
return _loadFontFaceBytes(fontFamily, list);
}
@override
Null get fontFallbackManager => null;
/// Unregister all fonts that have been registered.
@override
void clear() {
domDocument.fonts!.clear();
}
// Regular expression to detect a string with no punctuations.
// For example font family 'Ahem!' does not fall into this category
// so the family name will be wrapped in quotes.
static final RegExp notPunctuation =
RegExp(r'[a-z0-9\s]+', caseSensitive: false);
// Regular expression to detect tokens starting with a digit.
// For example font family 'Goudy Bookletter 1911' falls into this
// category.
static final RegExp startWithDigit = RegExp(r'\b\d');
/// Registers assets to Flutter Web Engine.
///
/// Browsers and browsers versions differ significantly on how a valid font
/// family name should be formatted. Notable issues are:
///
/// Safari 12 and Firefox crash if you create a [DomFontFace] with a font
/// family that is not correct CSS syntax. Font family names with invalid
/// characters are accepted on these browsers, when wrapped it in
/// quotes.
///
/// Additionally, for Safari 12 to work [DomFontFace] name should be
/// loaded correctly on the first try.
///
/// A font in Chrome is not usable other than inside a '<p>' tag, if a
/// [DomFontFace] is loaded wrapped with quotes. Unlike Safari 12 if a
/// valid version of the font is also loaded afterwards it will show
/// that font normally.
///
/// In Safari 13 the [DomFontFace] should be loaded with unquoted family
/// names.
///
/// In order to avoid all these browser compatibility issues this method:
/// * Detects the family names that might cause a conflict.
/// * Loads it with the quotes.
/// * Loads it again without the quotes.
/// * For all the other family names [DomFontFace] is loaded only once.
///
/// See also:
///
/// * https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#Valid_family_names
/// * https://drafts.csswg.org/css-fonts-3/#font-family-prop
Future<FontLoadError?> _loadFontAsset(
String family,
String asset,
Map<String, String> descriptors,
) async {
final List<DomFontFace> fontFaces = <DomFontFace>[];
final List<FontLoadError> errors = <FontLoadError>[];
try {
if (startWithDigit.hasMatch(family) ||
notPunctuation.stringMatch(family) != family) {
// Load a font family name with special characters once here wrapped in
// quotes.
fontFaces.add(await _loadFontFace("'$family'", asset, descriptors));
}
} on FontLoadError catch (error) {
errors.add(error);
}
try {
// Load all fonts, without quoted family names.
fontFaces.add(await _loadFontFace(family, asset, descriptors));
} on FontLoadError catch (error) {
errors.add(error);
}
if (fontFaces.isEmpty) {
// We failed to load either font face. Return the first error.
return errors.first;
}
try {
// Since we can't use tear-offs for interop members, this code is faster
// and easier to read with a for loop instead of forEach.
// ignore: prefer_foreach
for (final DomFontFace font in fontFaces) {
domDocument.fonts!.add(font);
}
} catch (e) {
return FontInvalidDataError(asset);
}
return null;
}
Future<DomFontFace> _loadFontFace(
String family,
String asset,
Map<String, String> descriptors,
) async {
// try/catch because `new FontFace` can crash with an improper font family.
try {
final DomFontFace fontFace = createDomFontFace(family, 'url(${ui_web.assetManager.getAssetUrl(asset)})', descriptors);
return await fontFace.load();
} catch (e) {
printWarning('Error while loading font family "$family":\n$e');
throw FontDownloadError(asset, e);
}
}
// Loads a font from bytes, surfacing errors through the future.
Future<bool> _loadFontFaceBytes(String family, Uint8List list) async {
// Since these fonts are loaded by user code, surface the error
// through the returned future.
try {
final DomFontFace fontFace = createDomFontFace(family, list);
if (fontFace.status == 'error') {
// Font failed to load.
return false;
}
domDocument.fonts!.add(fontFace);
// There might be paragraph measurements for this new font before it is
// loaded. They were measured using fallback font, so we should clear the
// cache.
Spanometer.clearRulersCache();
} catch (exception) {
// Failures here will throw an DomException. Return false.
return false;
}
return true;
}
@override
void debugResetFallbackFonts() {
}
}
| engine/lib/web_ui/lib/src/engine/text/font_collection.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/text/font_collection.dart",
"repo_id": "engine",
"token_count": 2262
} | 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 '../browser_detection.dart';
import '../dom.dart';
/// Various input action types used in text fields.
///
/// These types are coming from Flutter's [TextInputAction]. Currently, the web doesn't
/// support all the types. We fallback to [EngineInputAction.none] when Flutter
/// sends a type that isn't supported.
abstract class EngineInputAction {
const EngineInputAction();
static EngineInputAction fromName(String name) {
switch (name) {
case 'TextInputAction.continueAction':
case 'TextInputAction.next':
return next;
case 'TextInputAction.previous':
return previous;
case 'TextInputAction.done':
return done;
case 'TextInputAction.go':
return go;
case 'TextInputAction.newline':
return enter;
case 'TextInputAction.search':
return search;
case 'TextInputAction.send':
return send;
case 'TextInputAction.emergencyCall':
case 'TextInputAction.join':
case 'TextInputAction.none':
case 'TextInputAction.route':
case 'TextInputAction.unspecified':
default:
return none;
}
}
/// No input action
static const NoInputAction none = NoInputAction();
/// Action to go to next
static const NextInputAction next = NextInputAction();
/// Action to go to previous
static const PreviousInputAction previous = PreviousInputAction();
/// Action to be finished
static const DoneInputAction done = DoneInputAction();
/// Action to Go
static const GoInputAction go = GoInputAction();
/// Action to insert newline
static const EnterInputAction enter = EnterInputAction();
/// Action to search
static const SearchInputAction search = SearchInputAction();
/// Action to send
static const SendInputAction send = SendInputAction();
/// The HTML `enterkeyhint` attribute to be set on the DOM element.
///
/// This HTML attribute helps the browser decide what kind of keyboard action
/// to use for this text field
///
/// For various `enterkeyhint` values supported by browsers, see:
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/enterkeyhint>.
String? get enterkeyhintAttribute;
/// Given a [domElement], set attributes that are specific to this input action.
void configureInputAction(DomHTMLElement domElement) {
if (enterkeyhintAttribute == null) {
return;
}
// Only apply `enterkeyhint` in mobile browsers so that the right virtual
// keyboard shows up.
if (operatingSystem == OperatingSystem.iOs ||
operatingSystem == OperatingSystem.android ||
enterkeyhintAttribute == EngineInputAction.none.enterkeyhintAttribute) {
domElement.setAttribute('enterkeyhint', enterkeyhintAttribute!);
}
}
}
/// No action specified
class NoInputAction extends EngineInputAction {
const NoInputAction();
@override
String? get enterkeyhintAttribute => null;
}
/// Typically inserting a new line.
class EnterInputAction extends EngineInputAction {
const EnterInputAction();
@override
String? get enterkeyhintAttribute => 'enter';
}
/// Typically meaning there is nothing more to input and the input method editor (IME) will be closed.
class DoneInputAction extends EngineInputAction {
const DoneInputAction();
@override
String? get enterkeyhintAttribute => 'done';
}
/// Typically meaning to take the user to the target of the text they typed.
class GoInputAction extends EngineInputAction {
const GoInputAction();
@override
String? get enterkeyhintAttribute => 'go';
}
/// Typically taking the user to the next field that will accept text.
class NextInputAction extends EngineInputAction {
const NextInputAction();
@override
String? get enterkeyhintAttribute => 'next';
}
/// Typically taking the user to the previous field that will accept text.
class PreviousInputAction extends EngineInputAction {
const PreviousInputAction();
@override
String? get enterkeyhintAttribute => 'previous';
}
/// Typically taking the user to the results of searching for the text they have typed.
class SearchInputAction extends EngineInputAction {
const SearchInputAction();
@override
String? get enterkeyhintAttribute => 'search';
}
/// Typically delivering the text to its target.
class SendInputAction extends EngineInputAction {
const SendInputAction();
@override
String? get enterkeyhintAttribute => 'send';
}
| engine/lib/web_ui/lib/src/engine/text_editing/input_action.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/text_editing/input_action.dart",
"repo_id": "engine",
"token_count": 1339
} | 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 '../dom.dart';
/// Sets global attributes for a Flutter View.
///
/// The global attributes are set on the [rootElement] of the Flutter View, as
/// well as the on [hostElement] where the Flutter View is inserted.
///
/// The [hostElement] corresponds to the <body> element in full-page mode.
///
/// The global attributes provide quick and general information about the
/// Flutter app. They are set on a global element (e.g. the body element) to
/// make it easily accessible to the user.
class GlobalHtmlAttributes {
GlobalHtmlAttributes({required this.rootElement, required this.hostElement});
/// The [FlutterView.viewId] attribute name.
static const String flutterViewIdAttributeName = 'flt-view-id';
final DomElement rootElement;
final DomElement hostElement;
void applyAttributes({
required int viewId,
required bool autoDetectRenderer,
required String rendererTag,
required String buildMode,
}) {
// This `flt-view-id` attribute does not serve a function in the engine's
// operation, but it's useful for debugging, test automation, and DOM
// interop use-cases. It allows one to use CSS selectors to find views by
// their identifiers.
//
// Example:
//
// document.querySelector('flutter-view[flt-view-id="$viewId"]')
rootElement.setAttribute(flutterViewIdAttributeName, viewId);
// How was the current renderer selected?
final String rendererSelection = autoDetectRenderer
? 'auto-selected'
: 'requested explicitly';
hostElement.setAttribute('flt-renderer', '$rendererTag ($rendererSelection)');
hostElement.setAttribute('flt-build-mode', buildMode);
// TODO(mdebbar): Disable spellcheck until changes in the framework and
// engine are complete.
hostElement.setAttribute('spellcheck', 'false');
}
}
| engine/lib/web_ui/lib/src/engine/view_embedder/global_html_attributes.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/view_embedder/global_html_attributes.dart",
"repo_id": "engine",
"token_count": 598
} | 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.
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
/// Sets the handler that forwards platform messages to web plugins.
///
/// This function exists because unlike mobile, on the web plugins are also
/// implemented using Dart code, and that code needs a way to receive messages.
void setPluginHandler(ui.PlatformMessageCallback handler) {
pluginMessageCallHandler = handler;
}
| engine/lib/web_ui/lib/ui_web/src/ui_web/plugins.dart/0 | {
"file_path": "engine/lib/web_ui/lib/ui_web/src/ui_web/plugins.dart",
"repo_id": "engine",
"token_count": 145
} | 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.
#include "export.h"
#include "helpers.h"
#include "third_party/skia/include/core/SkBBHFactory.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "wrappers.h"
using namespace Skwasm;
SkRTreeFactory bbhFactory;
SKWASM_EXPORT SkPictureRecorder* pictureRecorder_create() {
return new SkPictureRecorder();
}
SKWASM_EXPORT void pictureRecorder_dispose(SkPictureRecorder* recorder) {
delete recorder;
}
SKWASM_EXPORT SkCanvas* pictureRecorder_beginRecording(
SkPictureRecorder* recorder,
const SkRect* cullRect) {
return recorder->beginRecording(*cullRect, &bbhFactory);
}
SKWASM_EXPORT SkPicture* pictureRecorder_endRecording(
SkPictureRecorder* recorder) {
return recorder->finishRecordingAsPicture().release();
}
SKWASM_EXPORT void picture_getCullRect(SkPicture* picture, SkRect* outRect) {
*outRect = picture->cullRect();
}
SKWASM_EXPORT void picture_dispose(SkPicture* picture) {
picture->unref();
}
SKWASM_EXPORT uint32_t picture_approximateBytesUsed(SkPicture* picture) {
return static_cast<uint32_t>(picture->approximateBytesUsed());
}
| engine/lib/web_ui/skwasm/picture.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/picture.cpp",
"repo_id": "engine",
"token_count": 448
} | 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 'dart:math' as math;
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
const ui.Rect kDefaultRegion = ui.Rect.fromLTRB(0, 0, 500, 250);
void testMain() {
group('CkCanvas', () {
setUpCanvasKitTest(withImplicitView: true);
setUp(() {
renderer.fontCollection.debugResetFallbackFonts();
renderer.fontCollection.fontFallbackManager!.downloadQueue.fallbackFontUrlPrefixOverride = 'assets/fallback_fonts/';
});
test('renders using non-recording canvas if weak refs are supported',
() async {
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(kDefaultRegion);
expect(canvas.runtimeType, CkCanvas);
drawTestPicture(canvas);
await matchPictureGolden(
'canvaskit_picture.png',
recorder.endRecording(),
region: kDefaultRegion,
);
});
test(
'text style - foreground/background/color do not leak across paragraphs',
() async {
const double testWidth = 440;
const double middle = testWidth / 2;
CkParagraph createTestParagraph(
{ui.Color? color, CkPaint? foreground, CkPaint? background}) {
final CkParagraphBuilder builder =
CkParagraphBuilder(CkParagraphStyle());
builder.pushStyle(CkTextStyle(
fontSize: 16,
color: color,
foreground: foreground,
background: background,
));
final StringBuffer text = StringBuffer();
if (color == null && foreground == null && background == null) {
text.write('Default');
} else {
if (color != null) {
text.write('Color');
}
if (foreground != null) {
if (text.isNotEmpty) {
text.write('+');
}
text.write('Foreground');
}
if (background != null) {
if (text.isNotEmpty) {
text.write('+');
}
text.write('Background');
}
}
builder.addText(text.toString());
final CkParagraph paragraph = builder.build();
paragraph.layout(const ui.ParagraphConstraints(width: testWidth));
return paragraph;
}
final List<ParagraphFactory> variations = <ParagraphFactory>[
() => createTestParagraph(),
() => createTestParagraph(color: const ui.Color(0xFF009900)),
() => createTestParagraph(
foreground: CkPaint()..color = const ui.Color(0xFF990000)),
() => createTestParagraph(
background: CkPaint()..color = const ui.Color(0xFF7777FF)),
() => createTestParagraph(
color: const ui.Color(0xFFFF00FF),
background: CkPaint()..color = const ui.Color(0xFF0000FF),
),
() => createTestParagraph(
foreground: CkPaint()..color = const ui.Color(0xFF00FFFF),
background: CkPaint()..color = const ui.Color(0xFF0000FF),
),
];
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.translate(10, 10);
for (final ParagraphFactory from in variations) {
for (final ParagraphFactory to in variations) {
canvas.save();
final CkParagraph fromParagraph = from();
canvas.drawParagraph(fromParagraph, ui.Offset.zero);
final ui.Offset leftEnd = ui.Offset(
fromParagraph.maxIntrinsicWidth + 10, fromParagraph.height / 2);
final ui.Offset rightEnd = ui.Offset(middle - 10, leftEnd.dy);
const ui.Offset tipOffset = ui.Offset(-5, -5);
canvas.drawLine(leftEnd, rightEnd, CkPaint());
canvas.drawLine(rightEnd, rightEnd + tipOffset, CkPaint());
canvas.drawLine(
rightEnd, rightEnd + tipOffset.scale(1, -1), CkPaint());
canvas.translate(middle, 0);
canvas.drawParagraph(to(), ui.Offset.zero);
canvas.restore();
canvas.translate(0, 22);
}
}
final CkPicture picture = recorder.endRecording();
await matchPictureGolden(
'canvaskit_text_styles_do_not_leak.png',
picture,
region: const ui.Rect.fromLTRB(0, 0, testWidth, 850),
);
});
// Make sure we clear the canvas in between frames.
test('empty frame after contentful frame', () async {
// First draw a frame with a red rectangle
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawRect(const ui.Rect.fromLTRB(20, 20, 100, 100),
CkPaint()..color = const ui.Color(0xffff0000));
final CkPicture picture = recorder.endRecording();
final LayerSceneBuilder builder = LayerSceneBuilder();
builder.pushOffset(0, 0);
builder.addPicture(ui.Offset.zero, picture);
final LayerScene scene = builder.build();
await renderScene(scene);
// Now draw an empty layer tree and confirm that the red rectangle is
// no longer drawn.
final LayerSceneBuilder emptySceneBuilder = LayerSceneBuilder();
emptySceneBuilder.pushOffset(0, 0);
final LayerScene emptyScene = emptySceneBuilder.build();
await matchSceneGolden('canvaskit_empty_scene.png', emptyScene,
region: const ui.Rect.fromLTRB(0, 0, 100, 100));
});
// Regression test for https://github.com/flutter/flutter/issues/121758
test(
'resources used in temporary surfaces for Image.toByteData can cross to rendering overlays',
() async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
CkPicture makeTextPicture(String text, ui.Offset offset) {
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
final CkParagraphBuilder builder = CkParagraphBuilder(CkParagraphStyle());
builder.addText(text);
final CkParagraph paragraph = builder.build();
paragraph.layout(const ui.ParagraphConstraints(width: 100));
canvas.drawRect(
ui.Rect.fromLTWH(offset.dx, offset.dy, paragraph.width, paragraph.height).inflate(10),
CkPaint()..color = const ui.Color(0xFF00FF00)
);
canvas.drawParagraph(paragraph, offset);
return recorder.endRecording();
}
CkPicture imageToPicture(CkImage image, ui.Offset offset) {
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawImage(image, offset, CkPaint());
return recorder.endRecording();
}
final CkPicture helloPicture = makeTextPicture('Hello', ui.Offset.zero);
final CkImage helloImage = helloPicture.toImageSync(100, 100);
// Calling toByteData is essential to hit the bug.
await helloImage.toByteData(format: ui.ImageByteFormat.png);
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, helloPicture);
sb.addPlatformView(0, width: 10, height: 10);
// The image is rendered after the platform view so that it's rendered into
// a separate surface, which is what triggers the bug. If the bug is present
// the image will not appear on the UI.
sb.addPicture(const ui.Offset(0, 50), imageToPicture(helloImage, ui.Offset.zero));
sb.pop();
// The below line should not throw an error.
await matchSceneGolden('cross_overlay_resources.png', sb.build(),
region: const ui.Rect.fromLTRB(0, 0, 100, 100));
});
});
}
typedef ParagraphFactory = CkParagraph Function();
void drawTestPicture(CkCanvas canvas) {
canvas.clear(const ui.Color(0xFFFFFFF));
canvas.translate(10, 10);
// Row 1
canvas.save();
canvas.save();
canvas.clipRect(
const ui.Rect.fromLTRB(0, 0, 45, 45),
ui.ClipOp.intersect,
true,
);
canvas.clipRRect(
ui.RRect.fromLTRBR(5, 5, 50, 50, const ui.Radius.circular(8)),
true,
);
canvas.clipPath(
CkPath()
..moveTo(5, 5)
..lineTo(25, 5)
..lineTo(45, 45)
..lineTo(5, 45)
..close(),
true,
);
canvas.drawColor(const ui.Color.fromARGB(255, 100, 100, 0), ui.BlendMode.srcOver);
canvas.restore(); // remove clips
canvas.translate(60, 0);
canvas.drawCircle(
const ui.Offset(30, 25),
15,
CkPaint()..color = const ui.Color(0xFF0000AA),
);
canvas.translate(60, 0);
canvas.drawArc(
const ui.Rect.fromLTRB(10, 20, 50, 40),
math.pi / 4,
3 * math.pi / 2,
true,
CkPaint()..color = const ui.Color(0xFF00AA00),
);
canvas.translate(60, 0);
canvas.drawImage(
generateTestImage(),
const ui.Offset(20, 20),
CkPaint(),
);
canvas.translate(60, 0);
final ui.RSTransform transform = ui.RSTransform.fromComponents(
rotation: 0,
scale: 1,
anchorX: 0,
anchorY: 0,
translateX: 0,
translateY: 0,
);
canvas.drawAtlasRaw(
CkPaint(),
generateTestImage(),
Float32List(4)
..[0] = transform.scos
..[1] = transform.ssin
..[2] = transform.tx + 20
..[3] = transform.ty + 20,
Float32List(4)
..[0] = 0
..[1] = 0
..[2] = 15
..[3] = 15,
Uint32List.fromList(<int>[0x00000000]),
ui.BlendMode.srcOver,
);
canvas.translate(60, 0);
canvas.drawDRRect(
ui.RRect.fromLTRBR(0, 0, 40, 30, const ui.Radius.elliptical(16, 8)),
ui.RRect.fromLTRBR(10, 10, 30, 20, const ui.Radius.elliptical(4, 8)),
CkPaint(),
);
canvas.translate(60, 0);
canvas.drawImageRect(
generateTestImage(),
const ui.Rect.fromLTRB(0, 0, 15, 15),
const ui.Rect.fromLTRB(10, 10, 40, 40),
CkPaint(),
);
canvas.translate(60, 0);
canvas.drawImageNine(
generateTestImage(),
const ui.Rect.fromLTRB(5, 5, 15, 15),
const ui.Rect.fromLTRB(10, 10, 50, 40),
CkPaint(),
);
canvas.restore();
// Row 2
canvas.translate(0, 60);
canvas.save();
canvas.drawLine(ui.Offset.zero, const ui.Offset(40, 30), CkPaint());
canvas.translate(60, 0);
canvas.drawOval(
const ui.Rect.fromLTRB(0, 0, 40, 30),
CkPaint(),
);
canvas.translate(60, 0);
canvas.save();
canvas.clipRect(const ui.Rect.fromLTRB(0, 0, 50, 30), ui.ClipOp.intersect, true);
canvas.drawPaint(CkPaint()..color = const ui.Color(0xFF6688AA));
canvas.restore();
canvas.translate(60, 0);
{
final CkPictureRecorder otherRecorder = CkPictureRecorder();
final CkCanvas otherCanvas =
otherRecorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 40, 20));
otherCanvas.drawCircle(
const ui.Offset(30, 15),
10,
CkPaint()..color = const ui.Color(0xFFAABBCC),
);
canvas.drawPicture(otherRecorder.endRecording());
}
canvas.translate(60, 0);
// TODO(yjbanov): CanvasKit.drawPoints is currently broken
// https://github.com/flutter/flutter/issues/71489
// But keeping this anyway as it's a good test-case that
// will ensure it's fixed when we have the fix.
canvas.drawPoints(
CkPaint()
..color = const ui.Color(0xFF0000FF)
..strokeWidth = 5
..strokeCap = ui.StrokeCap.round,
ui.PointMode.polygon,
offsetListToFloat32List(const <ui.Offset>[
ui.Offset(10, 10),
ui.Offset(20, 10),
ui.Offset(30, 20),
ui.Offset(40, 20)
]),
);
canvas.translate(60, 0);
canvas.drawRRect(
ui.RRect.fromLTRBR(0, 0, 40, 30, const ui.Radius.circular(10)),
CkPaint(),
);
canvas.translate(60, 0);
canvas.drawRect(
const ui.Rect.fromLTRB(0, 0, 40, 30),
CkPaint(),
);
canvas.translate(60, 0);
canvas.drawShadow(
CkPath()..addRect(const ui.Rect.fromLTRB(0, 0, 40, 30)),
const ui.Color(0xFF00FF00),
4,
true,
);
canvas.restore();
// Row 3
canvas.translate(0, 60);
canvas.save();
canvas.drawVertices(
CkVertices(
ui.VertexMode.triangleFan,
const <ui.Offset>[
ui.Offset(10, 30),
ui.Offset(30, 50),
ui.Offset(10, 60),
],
),
ui.BlendMode.srcOver,
CkPaint(),
);
canvas.translate(60, 0);
final int restorePoint = canvas.save();
for (int i = 0; i < 5; i++) {
canvas.save();
canvas.translate(10, 10);
canvas.drawCircle(ui.Offset.zero, 5, CkPaint());
}
canvas.restoreToCount(restorePoint);
canvas.drawCircle(ui.Offset.zero, 7, CkPaint()..color = const ui.Color(0xFFFF0000));
canvas.translate(60, 0);
canvas.drawLine(ui.Offset.zero, const ui.Offset(30, 30), CkPaint());
canvas.save();
canvas.rotate(-math.pi / 8);
canvas.drawLine(ui.Offset.zero, const ui.Offset(30, 30), CkPaint());
canvas.drawCircle(
const ui.Offset(30, 30), 7, CkPaint()..color = const ui.Color(0xFF00AA00));
canvas.restore();
canvas.translate(60, 0);
final CkPaint thickStroke = CkPaint()
..style = ui.PaintingStyle.stroke
..strokeWidth = 20;
final CkPaint semitransparent = CkPaint()..color = const ui.Color(0x66000000);
canvas.saveLayer(kDefaultRegion, semitransparent);
canvas.drawLine(const ui.Offset(10, 10), const ui.Offset(50, 50), thickStroke);
canvas.drawLine(const ui.Offset(50, 10), const ui.Offset(10, 50), thickStroke);
canvas.restore();
canvas.translate(60, 0);
canvas.saveLayerWithoutBounds(semitransparent);
canvas.drawLine(const ui.Offset(10, 10), const ui.Offset(50, 50), thickStroke);
canvas.drawLine(const ui.Offset(50, 10), const ui.Offset(10, 50), thickStroke);
canvas.restore();
// To test saveLayerWithFilter we draw three circles with only the middle one
// blurred using the layer image filter.
canvas.translate(60, 0);
canvas.saveLayer(kDefaultRegion, CkPaint());
canvas.drawCircle(const ui.Offset(30, 30), 10, CkPaint());
{
canvas.saveLayerWithFilter(
kDefaultRegion, ui.ImageFilter.blur(sigmaX: 5, sigmaY: 10));
canvas.drawCircle(const ui.Offset(10, 10), 10, CkPaint());
canvas.drawCircle(const ui.Offset(50, 50), 10, CkPaint());
canvas.restore();
}
canvas.restore();
canvas.translate(60, 0);
canvas.save();
canvas.translate(30, 30);
canvas.scale(2, 1.5);
canvas.drawCircle(ui.Offset.zero, 10, CkPaint());
canvas.restore();
canvas.translate(60, 0);
canvas.save();
canvas.translate(30, 30);
canvas.skew(2, 1.5);
canvas.drawRect(const ui.Rect.fromLTRB(-10, -10, 10, 10), CkPaint());
canvas.restore();
canvas.restore();
// Row 4
canvas.translate(0, 60);
canvas.save();
canvas.save();
final Matrix4 matrix = Matrix4.identity();
matrix.translate(30, 30);
matrix.scale(2, 1.5);
canvas.transform(matrix.storage);
canvas.drawCircle(ui.Offset.zero, 10, CkPaint());
canvas.restore();
canvas.translate(60, 0);
final CkParagraph p = makeSimpleText('Hello', fontSize: 18, color: const ui.Color(0xFF0000AA));
canvas.drawParagraph(
p,
const ui.Offset(10, 20),
);
canvas.translate(60, 0);
canvas.drawPath(
CkPath()
..moveTo(30, 20)
..lineTo(50, 50)
..lineTo(10, 50)
..close(),
CkPaint()..color = const ui.Color(0xFF0000AA),
);
canvas.restore();
}
CkImage generateTestImage() {
final DomCanvasElement canvas = createDomCanvasElement(width: 20, height: 20);
final DomCanvasRenderingContext2D ctx = canvas.context2D;
ctx.fillStyle = '#FF0000';
ctx.fillRect(0, 0, 10, 10);
ctx.fillStyle = '#00FF00';
ctx.fillRect(0, 10, 10, 10);
ctx.fillStyle = '#0000FF';
ctx.fillRect(10, 0, 10, 10);
ctx.fillStyle = '#FF00FF';
ctx.fillRect(10, 10, 10, 10);
final Uint8List imageData =
ctx.getImageData(0, 0, 20, 20).data.buffer.asUint8List();
final SkImage skImage = canvasKit.MakeImage(
SkImageInfo(
width: 20,
height: 20,
alphaType: canvasKit.AlphaType.Premul,
colorType: canvasKit.ColorType.RGBA_8888,
colorSpace: SkColorSpaceSRGB,
),
imageData,
4 * 20)!;
return CkImage(skImage);
}
| engine/lib/web_ui/test/canvaskit/canvas_golden_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/canvas_golden_test.dart",
"repo_id": "engine",
"token_count": 7069
} | 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 'package:js/js_util.dart' as js_util;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('initializeEngineServices', () {
test('stores user configuration', () async {
final JsFlutterConfiguration config = JsFlutterConfiguration();
// `canvasKitBaseUrl` is required for the test to actually run.
js_util.setProperty(config, 'canvasKitBaseUrl', '/canvaskit/');
// A property under test, that we'll try to read later.
js_util.setProperty(config, 'nonce', 'some_nonce');
// A non-existing property to verify our js-interop doesn't crash.
js_util.setProperty(config, 'canvasKitMaximumSurfaces', 32.0);
// Remove window.flutterConfiguration (if it's there)
js_util.setProperty(domWindow, 'flutterConfiguration', null);
// TODO(web): Replace the above nullification by the following assertion
// when wasm and JS tests initialize their config the same way:
// assert(js_util.getProperty<Object?>(domWindow, 'flutterConfiguration') == null);
await initializeEngineServices(jsConfiguration: config);
expect(configuration.nonce, 'some_nonce');
});
});
}
| engine/lib/web_ui/test/canvaskit/initialization/stores_config_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/initialization/stores_config_test.dart",
"repo_id": "engine",
"token_count": 480
} | 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:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import '../common/fake_asset_manager.dart';
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$SkiaFontCollection', () {
setUpUnitTests();
final List<String> warnings = <String>[];
late void Function(String) oldPrintWarning;
late FakeAssetScope testAssetScope;
setUpAll(() async {
oldPrintWarning = printWarning;
printWarning = (String warning) {
warnings.add(warning);
};
});
tearDownAll(() {
printWarning = oldPrintWarning;
});
setUp(() {
testAssetScope = fakeAssetManager.pushAssetScope();
mockHttpFetchResponseFactory = null;
warnings.clear();
});
tearDown(() {
fakeAssetManager.popAssetScope(testAssetScope);
mockHttpFetchResponseFactory = null;
});
test('logs no warnings with the default mock asset manager', () async {
final SkiaFontCollection fontCollection = SkiaFontCollection();
await fontCollection.loadAssetFonts(await fetchFontManifest(fakeAssetManager));
expect(warnings, isEmpty);
});
test('logs a warning if one of the registered fonts is invalid', () async {
mockHttpFetchResponseFactory = (String url) async {
final ByteBuffer bogusData = Uint8List.fromList('this is not valid font data'.codeUnits).buffer;
return MockHttpFetchResponse(
status: 200,
url: url,
contentLength: bogusData.lengthInBytes,
payload: MockHttpFetchPayload(byteBuffer: bogusData),
);
};
final SkiaFontCollection fontCollection = SkiaFontCollection();
testAssetScope.setAsset('FontManifest.json', stringAsUtf8Data('''
[
{
"family":"Roboto",
"fonts":[{"asset":"/fonts/Roboto-Regular.ttf"}]
},
{
"family": "BrokenFont",
"fonts":[{"asset":"packages/bogus/BrokenFont.ttf"}]
}
]
'''));
// It should complete without error, but emit a warning about BrokenFont.
await fontCollection.loadAssetFonts(await fetchFontManifest(fakeAssetManager));
expect(
warnings,
containsAllInOrder(
<String>[
'Failed to load font BrokenFont at packages/bogus/BrokenFont.ttf',
'Verify that packages/bogus/BrokenFont.ttf contains a valid font.',
],
),
);
});
test('logs an HTTP warning if one of the registered fonts is missing (404 file not found)', () async {
final SkiaFontCollection fontCollection = SkiaFontCollection();
testAssetScope.setAsset('FontManifest.json', stringAsUtf8Data('''
[
{
"family":"Roboto",
"fonts":[{"asset":"/fonts/Roboto-Regular.ttf"}]
},
{
"family": "ThisFontDoesNotExist",
"fonts":[{"asset":"packages/bogus/ThisFontDoesNotExist.ttf"}]
}
]
'''));
// It should complete without error, but emit a warning about ThisFontDoesNotExist.
await fontCollection.loadAssetFonts(await fetchFontManifest(fakeAssetManager));
expect(
warnings,
containsAllInOrder(<String>[
'Font family ThisFontDoesNotExist not found (404) at packages/bogus/ThisFontDoesNotExist.ttf'
]),
);
});
test('prioritizes Ahem loaded via FontManifest.json', () async {
final SkiaFontCollection fontCollection = SkiaFontCollection();
testAssetScope.setAsset('FontManifest.json', stringAsUtf8Data('''
[
{
"family":"Ahem",
"fonts":[{"asset":"/assets/fonts/Roboto-Regular.ttf"}]
}
]
'''.trim()));
final ByteBuffer robotoData = await httpFetchByteBuffer('/assets/fonts/Roboto-Regular.ttf');
await fontCollection.loadAssetFonts(await fetchFontManifest(fakeAssetManager));
expect(warnings, isEmpty);
// Use `singleWhere` to make sure only one version of 'Ahem' is loaded.
final RegisteredFont ahem = fontCollection.debugRegisteredFonts!
.singleWhere((RegisteredFont font) => font.family == 'Ahem');
// Check that the contents of 'Ahem' is actually Roboto, because that's
// what's specified in the manifest, and the manifest takes precedence.
expect(ahem.bytes.length, robotoData.lengthInBytes);
});
test('falls back to default Ahem URL', () async {
final SkiaFontCollection fontCollection = renderer.fontCollection as SkiaFontCollection;
final ByteBuffer ahemData = await httpFetchByteBuffer('/assets/fonts/ahem.ttf');
// Use `singleWhere` to make sure only one version of 'Ahem' is loaded.
final RegisteredFont ahem = fontCollection.debugRegisteredFonts!
.singleWhere((RegisteredFont font) => font.family == 'Ahem');
// Check that the contents of 'Ahem' is actually Roboto, because that's
// what's specified in the manifest, and the manifest takes precedence.
expect(ahem.bytes.length, ahemData.lengthInBytes);
});
test('FlutterTest is the default test font', () async {
final SkiaFontCollection fontCollection = renderer.fontCollection as SkiaFontCollection;
expect(fontCollection.debugRegisteredFonts, isNotEmpty);
expect(fontCollection.debugRegisteredFonts!.first.family, 'FlutterTest');
});
});
}
| engine/lib/web_ui/test/canvaskit/skia_font_collection_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/skia_font_collection_test.dart",
"repo_id": "engine",
"token_count": 2067
} | 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:js_interop';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine/browser_detection.dart';
import 'package:ui/src/engine/safe_browser_api.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('detectBrowserEngineByVendorAgent', () {
test('Should detect Blink', () {
// Chrome Version 89.0.4389.90 (Official Build) (x86_64) / MacOS
final BrowserEngine browserEngine = detectBrowserEngineByVendorAgent(
'Google Inc.',
'mozilla/5.0 (macintosh; intel mac os x 11_2_3) applewebkit/537.36 '
'(khtml, like gecko) chrome/89.0.4389.90 safari/537.36');
expect(browserEngine, BrowserEngine.blink);
});
test('Should detect Firefox', () {
// 85.0.2 (64-bit) / MacOS
final BrowserEngine browserEngine = detectBrowserEngineByVendorAgent(
'',
'mozilla/5.0 (macintosh; intel mac os x 10.16; rv:85.0) '
'gecko/20100101 firefox/85.0');
expect(browserEngine, BrowserEngine.firefox);
});
test('Should detect Safari', () {
final BrowserEngine browserEngine = detectBrowserEngineByVendorAgent(
'Apple Computer, Inc.',
'mozilla/5.0 (macintosh; intel mac os x 10_15_6) applewebkit/605.1.15 '
'(khtml, like gecko) version/14.0.3 safari/605.1.15');
expect(browserEngine, BrowserEngine.webkit);
});
});
group('detectOperatingSystem', () {
void expectOs(
OperatingSystem expectedOs, {
String platform = 'any',
String ua = 'any',
int touchPoints = 0,
}) {
try {
getUserAgent = () => ua;
expect(
detectOperatingSystem(
overridePlatform: platform,
overrideMaxTouchPoints: touchPoints,
),
expectedOs,
);
} finally {
getUserAgent = defaultGetUserAgent;
}
}
test('Determine unknown for weird values of platform/ua', () {
expectOs(OperatingSystem.unknown);
});
test('Determine MacOS if platform starts by Mac', () {
expectOs(
OperatingSystem.macOs,
platform: 'MacIntel',
);
expectOs(
OperatingSystem.macOs,
platform: 'MacAnythingElse',
);
});
test('Determine iOS if platform contains iPhone/iPad/iPod', () {
expectOs(
OperatingSystem.iOs,
platform: 'iPhone',
);
expectOs(
OperatingSystem.iOs,
platform: 'iPhone Simulator',
);
expectOs(
OperatingSystem.iOs,
platform: 'iPad',
);
expectOs(
OperatingSystem.iOs,
platform: 'iPad Simulator',
);
expectOs(
OperatingSystem.iOs,
platform: 'iPod',
);
expectOs(
OperatingSystem.iOs,
platform: 'iPod Simulator',
);
});
// See https://github.com/flutter/flutter/issues/81918
test('Tell apart MacOS from iOS requesting a desktop site.', () {
expectOs(
OperatingSystem.macOs,
platform: 'MacARM',
);
expectOs(
OperatingSystem.iOs,
platform: 'MacARM',
touchPoints: 5,
);
});
test('Determine Android if user agent contains Android', () {
expectOs(
OperatingSystem.android,
ua: 'Mozilla/5.0 (Linux; U; Android 2.2) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',
);
});
test('Determine Linux if the platform begins with Linux', () {
expectOs(
OperatingSystem.linux,
platform: 'Linux',
);
expectOs(
OperatingSystem.linux,
platform: 'Linux armv8l',
);
expectOs(
OperatingSystem.linux,
platform: 'Linux x86_64',
);
});
test('Determine Windows if the platform begins with Win', () {
expectOs(
OperatingSystem.windows,
platform: 'Windows',
);
expectOs(
OperatingSystem.windows,
platform: 'Win32',
);
expectOs(
OperatingSystem.windows,
platform: 'Win16',
);
expectOs(
OperatingSystem.windows,
platform: 'WinCE',
);
});
});
group('browserSupportsCanvasKitChromium', () {
JSAny? oldV8BreakIterator = v8BreakIterator;
JSAny? oldIntlSegmenter = intlSegmenter;
setUp(() {
oldV8BreakIterator = v8BreakIterator;
oldIntlSegmenter = intlSegmenter;
});
tearDown(() {
v8BreakIterator = oldV8BreakIterator;
intlSegmenter = oldIntlSegmenter;
debugResetBrowserSupportsImageDecoder();
});
test('Detect browsers that support CanvasKit Chromium', () {
v8BreakIterator = Object().toJSBox; // Any non-null value.
intlSegmenter = Object().toJSBox; // Any non-null value.
browserSupportsImageDecoder = true;
expect(browserSupportsCanvaskitChromium, isTrue);
});
test('Detect browsers that do not support image codecs', () {
v8BreakIterator = Object().toJSBox; // Any non-null value.
intlSegmenter = Object().toJSBox; // Any non-null value.
browserSupportsImageDecoder = false;
// TODO(mdebbar): we don't check image codecs for now.
// https://github.com/flutter/flutter/issues/122331
expect(browserSupportsCanvaskitChromium, isTrue);
});
test('Detect browsers that do not support v8BreakIterator', () {
v8BreakIterator = null;
intlSegmenter = Object().toJSBox; // Any non-null value.
browserSupportsImageDecoder = true;
expect(browserSupportsCanvaskitChromium, isFalse);
});
test('Detect browsers that support neither', () {
v8BreakIterator = null;
intlSegmenter = Object().toJSBox; // Any non-null value.
browserSupportsImageDecoder = false;
expect(browserSupportsCanvaskitChromium, isFalse);
});
test('Detect browsers that support v8BreakIterator but no Intl.Segmenter', () {
v8BreakIterator = Object().toJSBox; // Any non-null value.
intlSegmenter = null;
expect(browserSupportsCanvaskitChromium, isFalse);
});
});
group('OffscreenCanvas', () {
test('OffscreenCanvas is detected as unsupported in Safari', () {
debugBrowserEngineOverride = BrowserEngine.webkit;
expect(OffScreenCanvas.supported, isFalse);
debugBrowserEngineOverride = null;
});
});
}
@JS('window.Intl.v8BreakIterator')
external JSAny? get v8BreakIterator;
@JS('window.Intl.v8BreakIterator')
external set v8BreakIterator(JSAny? x);
@JS('window.Intl.Segmenter')
external JSAny? get intlSegmenter;
@JS('window.Intl.Segmenter')
external set intlSegmenter(JSAny? x);
| engine/lib/web_ui/test/engine/browser_detect_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/browser_detect_test.dart",
"repo_id": "engine",
"token_count": 2850
} | 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 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('PlatformViewManager', () {
const int viewId = 6;
group('createPlatformViewSlot', () {
test(
'can render slot, even for views that might have never been rendered before',
() async {
final DomElement slot = createPlatformViewSlot(viewId);
expect(slot, isNotNull);
expect(slot.querySelector('slot'), isNotNull);
});
test('rendered markup contains required attributes', () async {
final DomElement slot = createPlatformViewSlot(viewId);
expect(slot.style.pointerEvents, 'auto',
reason:
'Should re-enable pointer events for the contents of the view.');
final DomElement innerSlot = slot.querySelector('slot')!;
expect(innerSlot.getAttribute('name'), contains('$viewId'),
reason:
'The name attribute of the inner SLOT tag must refer to the viewId.');
});
});
});
test('getPlatformViewSlotName', () {
expect(getPlatformViewSlotName(42), 'flt-pv-slot-42');
});
test('getPlatformViewDomId', () {
expect(getPlatformViewDomId(42), 'flt-pv-42');
});
}
| engine/lib/web_ui/test/engine/platform_views/slots_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/platform_views/slots_test.dart",
"repo_id": "engine",
"token_count": 552
} | 311 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.