text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/synchronization/semaphore.h"
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
#if FML_OS_MACOSX
#include <dispatch/dispatch.h>
namespace fml {
class PlatformSemaphore {
public:
explicit PlatformSemaphore(uint32_t count)
: sem_(dispatch_semaphore_create(count)), initial_(count) {}
~PlatformSemaphore() {
for (uint32_t i = 0; i < initial_; ++i) {
Signal();
}
if (sem_ != nullptr) {
dispatch_release(reinterpret_cast<dispatch_object_t>(sem_));
sem_ = nullptr;
}
}
bool IsValid() const { return sem_ != nullptr; }
bool Wait() {
if (sem_ == nullptr) {
return false;
}
return dispatch_semaphore_wait(sem_, DISPATCH_TIME_FOREVER) == 0;
}
bool TryWait() {
if (sem_ == nullptr) {
return false;
}
return dispatch_semaphore_wait(sem_, DISPATCH_TIME_NOW) == 0;
}
void Signal() {
if (sem_ != nullptr) {
dispatch_semaphore_signal(sem_);
}
}
private:
dispatch_semaphore_t sem_;
const uint32_t initial_;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore);
};
} // namespace fml
#elif FML_OS_WIN
#include <windows.h>
namespace fml {
class PlatformSemaphore {
public:
explicit PlatformSemaphore(uint32_t count)
: _sem(CreateSemaphore(NULL, count, LONG_MAX, NULL)) {}
~PlatformSemaphore() {
if (_sem != nullptr) {
CloseHandle(_sem);
_sem = nullptr;
}
}
bool IsValid() const { return _sem != nullptr; }
bool Wait() {
if (_sem == nullptr) {
return false;
}
return WaitForSingleObject(_sem, INFINITE) == WAIT_OBJECT_0;
}
bool TryWait() {
if (_sem == nullptr) {
return false;
}
return WaitForSingleObject(_sem, 0) == WAIT_OBJECT_0;
}
void Signal() {
if (_sem != nullptr) {
ReleaseSemaphore(_sem, 1, NULL);
}
}
private:
HANDLE _sem;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore);
};
} // namespace fml
#else
#include <semaphore.h>
#include "flutter/fml/eintr_wrapper.h"
namespace fml {
class PlatformSemaphore {
public:
explicit PlatformSemaphore(uint32_t count)
: valid_(::sem_init(&sem_, 0 /* not shared */, count) == 0) {}
~PlatformSemaphore() {
if (valid_) {
int result = ::sem_destroy(&sem_);
(void)result;
// Can only be EINVAL which should not be possible since we checked for
// validity.
FML_DCHECK(result == 0);
}
}
bool IsValid() const { return valid_; }
bool Wait() {
if (!valid_) {
return false;
}
return FML_HANDLE_EINTR(::sem_wait(&sem_)) == 0;
}
bool TryWait() {
if (!valid_) {
return false;
}
return FML_HANDLE_EINTR(::sem_trywait(&sem_)) == 0;
}
void Signal() {
if (!valid_) {
return;
}
::sem_post(&sem_);
return;
}
private:
bool valid_;
sem_t sem_;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore);
};
} // namespace fml
#endif
namespace fml {
Semaphore::Semaphore(uint32_t count) : impl_(new PlatformSemaphore(count)) {}
Semaphore::~Semaphore() = default;
bool Semaphore::IsValid() const {
return impl_->IsValid();
}
bool Semaphore::Wait() {
return impl_->Wait();
}
bool Semaphore::TryWait() {
return impl_->TryWait();
}
void Semaphore::Signal() {
return impl_->Signal();
}
} // namespace fml
| engine/fml/synchronization/semaphore.cc/0 | {
"file_path": "engine/fml/synchronization/semaphore.cc",
"repo_id": "engine",
"token_count": 1442
} | 171 |
// Copyright 2013 The Flutter 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_FML_TASK_SOURCE_H_
#define FLUTTER_FML_TASK_SOURCE_H_
#include "flutter/fml/delayed_task.h"
#include "flutter/fml/task_queue_id.h"
#include "flutter/fml/task_source_grade.h"
namespace fml {
class MessageLoopTaskQueues;
/**
* A Source of tasks for the `MessageLoopTaskQueues` task dispatcher. This is a
* wrapper around a primary and secondary task heap with the difference between
* them being that the secondary task heap can be paused and resumed by the task
* dispatcher. `TaskSourceGrade` determines what task heap the task is assigned
* to.
*
* Registering Tasks
* -----------------
* The task dispatcher associates a task source with each `TaskQueueID`. When
* the user of the task dispatcher registers a task, the task is in-turn
* registered with the `TaskSource` corresponding to the `TaskQueueID`.
*
* Processing Tasks
* ----------------
* Task dispatcher provides the event loop a way to acquire tasks to run via
* `GetNextTaskToRun`. Task dispatcher asks the underlying `TaskSource` for the
* next task.
*/
class TaskSource {
public:
struct TopTask {
TaskQueueId task_queue_id;
const DelayedTask& task;
};
/// Construts a TaskSource with the given `task_queue_id`.
explicit TaskSource(TaskQueueId task_queue_id);
~TaskSource();
/// Drops the pending tasks from both primary and secondary task heaps.
void ShutDown();
/// Adds a task to the corresponding task heap as dictated by the
/// `TaskSourceGrade` of the `DelayedTask`.
void RegisterTask(const DelayedTask& task);
/// Pops the task heap corresponding to the `TaskSourceGrade`.
void PopTask(TaskSourceGrade grade);
/// Returns the number of pending tasks. Excludes the tasks from the secondary
/// heap if it's paused.
size_t GetNumPendingTasks() const;
/// Returns true if `GetNumPendingTasks` is zero.
bool IsEmpty() const;
/// Returns the top task based on scheduled time, taking into account whether
/// the secondary heap has been paused or not.
TopTask Top() const;
/// Pause providing tasks from secondary task heap.
void PauseSecondary();
/// Resume providing tasks from secondary task heap.
void ResumeSecondary();
private:
const fml::TaskQueueId task_queue_id_;
fml::DelayedTaskQueue primary_task_queue_;
fml::DelayedTaskQueue secondary_task_queue_;
int secondary_pause_requests_ = 0;
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(TaskSource);
};
} // namespace fml
#endif // FLUTTER_FML_TASK_SOURCE_H_
| engine/fml/task_source.h/0 | {
"file_path": "engine/fml/task_source.h",
"repo_id": "engine",
"token_count": 769
} | 172 |
// Copyright 2013 The Flutter 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_FML_TRACE_EVENT_H_
#define FLUTTER_FML_TRACE_EVENT_H_
#include <functional>
#include "flutter/fml/build_config.h"
#if defined(OS_FUCHSIA)
// Forward to the system tracing mechanism on Fuchsia.
#include <lib/trace/event.h>
// TODO(DNO-448): This is disabled because the Fuchsia counter id json parsing
// only handles ints whereas this can produce ints or strings.
#define FML_TRACE_COUNTER(a, b, c, arg1, ...) \
::fml::tracing::TraceCounterNopHACK((a), (b), (c), (arg1), __VA_ARGS__);
#define FML_TRACE_EVENT(a, b, args...) TRACE_DURATION(a, b)
// On Fuchsia, the flow_id arguments to this macro are ignored.
#define FML_TRACE_EVENT_WITH_FLOW_IDS(category_group, name, flow_id_count, \
flow_ids, ...) \
FML_TRACE_EVENT(category_group, name)
#define TRACE_EVENT0(a, b) TRACE_DURATION(a, b)
// On Fuchsia, the flow_id arguments to this macro are ignored.
#define TRACE_EVENT0_WITH_FLOW_IDS(category_group, name, flow_id_count, \
flow_ids) \
TRACE_EVENT0(category_group, name)
#define TRACE_EVENT1(a, b, c, d) TRACE_DURATION(a, b, c, d)
// On Fuchsia, the flow_id arguments to this macro are ignored.
#define TRACE_EVENT1_WITH_FLOW_IDS(category_group, name, flow_id_count, \
flow_ids, arg1_name, arg1_val) \
TRACE_EVENT1(category_group, name, arg1_name, arg1_val)
#define TRACE_EVENT2(a, b, c, d, e, f) TRACE_DURATION(a, b, c, d, e, f)
#define TRACE_EVENT_ASYNC_BEGIN0(a, b, c) TRACE_ASYNC_BEGIN(a, b, c)
// On Fuchsia, the flow_id arguments to this macro are ignored.
#define TRACE_EVENT_ASYNC_BEGIN0_WITH_FLOW_IDS(category_group, name, id, \
flow_id_count, flow_ids) \
TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id)
#define TRACE_EVENT_ASYNC_END0(a, b, c) TRACE_ASYNC_END(a, b, c)
#define TRACE_EVENT_ASYNC_BEGIN1(a, b, c, d, e) TRACE_ASYNC_BEGIN(a, b, c, d, e)
#define TRACE_EVENT_ASYNC_END1(a, b, c, d, e) TRACE_ASYNC_END(a, b, c, d, e)
#define TRACE_EVENT_INSTANT0(a, b) TRACE_INSTANT(a, b, TRACE_SCOPE_THREAD)
#define TRACE_EVENT_INSTANT1(a, b, k1, v1) \
TRACE_INSTANT(a, b, TRACE_SCOPE_THREAD, k1, v1)
#define TRACE_EVENT_INSTANT2(a, b, k1, v1, k2, v2) \
TRACE_INSTANT(a, b, TRACE_SCOPE_THREAD, k1, v1, k2, v2)
#endif // defined(OS_FUCHSIA)
#include <cstddef>
#include <cstdint>
#include <string>
#include <type_traits>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/fml/time/time_point.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
#if (FLUTTER_RELEASE && !defined(OS_FUCHSIA) && !defined(FML_OS_ANDROID))
#define FLUTTER_TIMELINE_ENABLED 0
#else
#define FLUTTER_TIMELINE_ENABLED 1
#endif
#if !defined(OS_FUCHSIA)
#ifndef TRACE_EVENT_HIDE_MACROS
#define __FML__TOKEN_CAT__(x, y) x##y
#define __FML__TOKEN_CAT__2(x, y) __FML__TOKEN_CAT__(x, y)
#define __FML__AUTO_TRACE_END(name) \
::fml::tracing::ScopedInstantEnd __FML__TOKEN_CAT__2(__trace_end_, \
__LINE__)(name);
// This macro has the FML_ prefix so that it does not collide with the macros
// from lib/trace/event.h on Fuchsia.
//
// TODO(chinmaygarde): All macros here should have the FML prefix.
#define FML_TRACE_COUNTER(category_group, name, counter_id, arg1, ...) \
::fml::tracing::TraceCounter((category_group), (name), (counter_id), (arg1), \
__VA_ARGS__);
// Avoid using the same `name` and `argX_name` for nested traces, which can
// lead to double free errors. E.g. the following code should be avoided:
//
// ```cpp
// {
// TRACE_EVENT1("flutter", "Foo::Bar", "count", "initial_count_value");
// ...
// TRACE_EVENT_INSTANT1("flutter", "Foo::Bar",
// "count", "updated_count_value");
// }
// ```
//
// Instead, either use different `name` or `arg1` parameter names.
#define FML_TRACE_EVENT_WITH_FLOW_IDS(category_group, name, flow_id_count, \
flow_ids, ...) \
::fml::tracing::TraceEvent((category_group), (name), (flow_id_count), \
(flow_ids), __VA_ARGS__); \
__FML__AUTO_TRACE_END(name)
// Avoid using the same `name` and `argX_name` for nested traces, which can
// lead to double free errors. E.g. the following code should be avoided:
//
// ```cpp
// {
// TRACE_EVENT1("flutter", "Foo::Bar", "count", "initial_count_value");
// ...
// TRACE_EVENT_INSTANT1("flutter", "Foo::Bar",
// "count", "updated_count_value");
// }
// ```
//
// Instead, either use different `name` or `arg1` parameter names.
#define FML_TRACE_EVENT(category_group, name, ...) \
FML_TRACE_EVENT_WITH_FLOW_IDS((category_group), (name), \
/*flow_id_count=*/(0), /*flow_ids=*/(nullptr), \
__VA_ARGS__)
#define TRACE_EVENT0_WITH_FLOW_IDS(category_group, name, flow_id_count, \
flow_ids) \
::fml::tracing::TraceEvent0(category_group, name, flow_id_count, flow_ids); \
__FML__AUTO_TRACE_END(name)
#define TRACE_EVENT0(category_group, name) \
TRACE_EVENT0_WITH_FLOW_IDS(category_group, name, /*flow_id_count=*/0, \
/*flow_ids=*/nullptr)
#define TRACE_EVENT1_WITH_FLOW_IDS(category_group, name, flow_id_count, \
flow_ids, arg1_name, arg1_val) \
::fml::tracing::TraceEvent1(category_group, name, flow_id_count, flow_ids, \
arg1_name, arg1_val); \
__FML__AUTO_TRACE_END(name)
#define TRACE_EVENT1(category_group, name, arg1_name, arg1_val) \
TRACE_EVENT1_WITH_FLOW_IDS(category_group, name, /*flow_id_count=*/0, \
/*flow_ids=*/nullptr, arg1_name, arg1_val)
#define TRACE_EVENT2(category_group, name, arg1_name, arg1_val, arg2_name, \
arg2_val) \
::fml::tracing::TraceEvent2(category_group, name, /*flow_id_count=*/0, \
/*flow_ids=*/nullptr, arg1_name, arg1_val, \
arg2_name, arg2_val); \
__FML__AUTO_TRACE_END(name)
#define TRACE_EVENT_ASYNC_BEGIN0_WITH_FLOW_IDS(category_group, name, id, \
flow_id_count, flow_ids) \
::fml::tracing::TraceEventAsyncBegin0(category_group, name, id, \
flow_id_count, flow_ids);
#define TRACE_EVENT_ASYNC_BEGIN0(category_group, name, id) \
TRACE_EVENT_ASYNC_BEGIN0_WITH_FLOW_IDS( \
category_group, name, id, /*flow_id_count=*/0, /*flow_ids=*/nullptr)
#define TRACE_EVENT_ASYNC_END0(category_group, name, id) \
::fml::tracing::TraceEventAsyncEnd0(category_group, name, id);
#define TRACE_EVENT_ASYNC_BEGIN1(category_group, name, id, arg1_name, \
arg1_val) \
::fml::tracing::TraceEventAsyncBegin1( \
category_group, name, id, /*flow_id_count=*/0, /*flow_ids=*/nullptr, \
arg1_name, arg1_val);
#define TRACE_EVENT_ASYNC_END1(category_group, name, id, arg1_name, arg1_val) \
::fml::tracing::TraceEventAsyncEnd1( \
category_group, name, id, /*flow_id_count=*/0, /*flow_ids=*/nullptr, \
arg1_name, arg1_val);
#define TRACE_EVENT_INSTANT0(category_group, name) \
::fml::tracing::TraceEventInstant0( \
category_group, name, /*flow_id_count=*/0, /*flow_ids=*/nullptr);
#define TRACE_EVENT_INSTANT1(category_group, name, arg1_name, arg1_val) \
::fml::tracing::TraceEventInstant1( \
category_group, name, /*flow_id_count=*/0, /*flow_ids=*/nullptr, \
arg1_name, arg1_val);
#define TRACE_EVENT_INSTANT2(category_group, name, arg1_name, arg1_val, \
arg2_name, arg2_val) \
::fml::tracing::TraceEventInstant2( \
category_group, name, /*flow_id_count=*/0, /*flow_ids=*/nullptr, \
arg1_name, arg1_val, arg2_name, arg2_val);
#define TRACE_FLOW_BEGIN(category, name, id) \
::fml::tracing::TraceEventFlowBegin0(category, name, id);
#define TRACE_FLOW_STEP(category, name, id) \
::fml::tracing::TraceEventFlowStep0(category, name, id);
#define TRACE_FLOW_END(category, name, id) \
::fml::tracing::TraceEventFlowEnd0(category, name, id);
#endif // TRACE_EVENT_HIDE_MACROS
#endif // !defined(OS_FUCHSIA)
#define TRACE_EVENT2_INT(category_group, name, arg1_name, arg1_val, arg2_name, \
arg2_val) \
const auto __arg1_val_str = std::to_string(arg1_val); \
const auto __arg2_val_str = std::to_string(arg2_val); \
TRACE_EVENT2(category_group, name, arg1_name, __arg1_val_str.c_str(), \
arg2_name, __arg2_val_str.c_str());
namespace fml {
namespace tracing {
using TraceArg = const char*;
using TraceIDArg = int64_t;
void TraceSetAllowlist(const std::vector<std::string>& allowlist);
typedef void (*TimelineEventHandler)(const char*,
int64_t,
int64_t,
intptr_t,
const int64_t*,
Dart_Timeline_Event_Type,
intptr_t,
const char**,
const char**);
using TimelineMicrosSource = int64_t (*)();
void TraceSetTimelineEventHandler(TimelineEventHandler handler);
bool TraceHasTimelineEventHandler();
void TraceSetTimelineMicrosSource(TimelineMicrosSource source);
int64_t TraceGetTimelineMicros();
void TraceTimelineEvent(TraceArg category_group,
TraceArg name,
int64_t timestamp_micros,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids,
Dart_Timeline_Event_Type type,
const std::vector<const char*>& names,
const std::vector<std::string>& values);
void TraceTimelineEvent(TraceArg category_group,
TraceArg name,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids,
Dart_Timeline_Event_Type type,
const std::vector<const char*>& names,
const std::vector<std::string>& values);
inline std::string TraceToString(const char* string) {
return std::string{string};
}
inline std::string TraceToString(std::string string) {
return string;
}
inline std::string TraceToString(TimePoint point) {
return std::to_string(point.ToEpochDelta().ToNanoseconds());
}
template <typename T, typename = std::enable_if_t<std::is_arithmetic<T>::value>>
std::string TraceToString(T string) {
return std::to_string(string);
}
inline void SplitArgumentsCollect(std::vector<const char*>& keys,
std::vector<std::string>& values) {}
template <typename Key, typename Value, typename... Args>
void SplitArgumentsCollect(std::vector<const char*>& keys,
std::vector<std::string>& values,
Key key,
Value value,
Args... args) {
keys.emplace_back(key);
values.emplace_back(TraceToString(value));
SplitArgumentsCollect(keys, values, args...);
}
inline std::pair<std::vector<const char*>, std::vector<std::string>>
SplitArguments() {
return {};
}
template <typename Key, typename Value, typename... Args>
std::pair<std::vector<const char*>, std::vector<std::string>>
SplitArguments(Key key, Value value, Args... args) {
std::vector<const char*> keys;
std::vector<std::string> values;
SplitArgumentsCollect(keys, values, key, value, args...);
return std::make_pair(std::move(keys), std::move(values));
}
size_t TraceNonce();
template <typename... Args>
void TraceCounter(TraceArg category,
TraceArg name,
TraceIDArg identifier,
Args... args) {
#if FLUTTER_TIMELINE_ENABLED
auto split = SplitArguments(args...);
TraceTimelineEvent(category, name, identifier, /*flow_id_count=*/0,
/*flow_ids=*/nullptr, Dart_Timeline_Event_Counter,
split.first, split.second);
#endif // FLUTTER_TIMELINE_ENABLED
}
// HACK: Used to NOP FML_TRACE_COUNTER macro without triggering unused var
// warnings at usage sites.
template <typename... Args>
void TraceCounterNopHACK(TraceArg category,
TraceArg name,
TraceIDArg identifier,
Args... args) {}
template <typename... Args>
void TraceEvent(TraceArg category,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
Args... args) {
#if FLUTTER_TIMELINE_ENABLED
auto split = SplitArguments(args...);
TraceTimelineEvent(category, name, 0, flow_id_count, flow_ids,
Dart_Timeline_Event_Begin, split.first, split.second);
#endif // FLUTTER_TIMELINE_ENABLED
}
void TraceEvent0(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids);
void TraceEvent1(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val);
void TraceEvent2(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val,
TraceArg arg2_name,
TraceArg arg2_val);
void TraceEventEnd(TraceArg name);
template <typename... Args>
void TraceEventAsyncComplete(TraceArg category_group,
TraceArg name,
TimePoint begin,
TimePoint end,
Args... args) {
#if FLUTTER_TIMELINE_ENABLED
auto identifier = TraceNonce();
const auto split = SplitArguments(args...);
if (begin > end) {
std::swap(begin, end);
}
const int64_t begin_micros = begin.ToEpochDelta().ToMicroseconds();
const int64_t end_micros = end.ToEpochDelta().ToMicroseconds();
TraceTimelineEvent(category_group, // group
name, // name
begin_micros, // timestamp_micros
identifier, // identifier
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Async_Begin, // type
split.first, // names
split.second // values
);
TraceTimelineEvent(category_group, // group
name, // name
end_micros, // timestamp_micros
identifier, // identifier
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Async_End, // type
split.first, // names
split.second // values
);
#endif // FLUTTER_TIMELINE_ENABLED
}
void TraceEventAsyncBegin0(TraceArg category_group,
TraceArg name,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids);
void TraceEventAsyncEnd0(TraceArg category_group, TraceArg name, TraceIDArg id);
void TraceEventAsyncBegin1(TraceArg category_group,
TraceArg name,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val);
void TraceEventAsyncEnd1(TraceArg category_group,
TraceArg name,
TraceIDArg id,
TraceArg arg1_name,
TraceArg arg1_val);
void TraceEventInstant0(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids);
void TraceEventInstant1(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val);
void TraceEventInstant2(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val,
TraceArg arg2_name,
TraceArg arg2_val);
void TraceEventFlowBegin0(TraceArg category_group,
TraceArg name,
TraceIDArg id);
void TraceEventFlowStep0(TraceArg category_group, TraceArg name, TraceIDArg id);
void TraceEventFlowEnd0(TraceArg category_group, TraceArg name, TraceIDArg id);
class ScopedInstantEnd {
public:
explicit ScopedInstantEnd(const char* str) : label_(str) {}
~ScopedInstantEnd() { TraceEventEnd(label_); }
private:
const char* label_;
FML_DISALLOW_COPY_AND_ASSIGN(ScopedInstantEnd);
};
// A move-only utility object that creates a new flow with a unique ID and
// automatically ends it when it goes out of scope. When tracing using multiple
// overlapping flows, it often gets hard to make sure to end the flow
// (especially with early returns), or, end/step on the wrong flow. This
// leads to corrupted or missing traces in the UI.
class TraceFlow {
public:
explicit TraceFlow(const char* label) : label_(label), nonce_(TraceNonce()) {
TraceEvent0("flutter", label_, /*flow_id_count=*/1,
/*flow_ids=*/&nonce_);
TraceEventFlowBegin0("flutter", label_, nonce_);
TraceEventEnd(label_);
}
~TraceFlow() { End(label_); }
TraceFlow(TraceFlow&& other) : label_(other.label_), nonce_(other.nonce_) {
other.nonce_ = 0;
}
void Step(const char* label = nullptr) const {
TraceEvent0("flutter", label ? label : label_, /*flow_id_count=*/1,
/*flow_ids=*/&nonce_);
TraceEventFlowStep0("flutter", label ? label : label_, nonce_);
TraceEventEnd(label ? label : label_);
}
void End(const char* label = nullptr) {
if (nonce_ != 0) {
TraceEvent0("flutter", label ? label : label_, /*flow_id_count=*/1,
/*flow_ids=*/&nonce_);
TraceEventFlowEnd0("flutter", label ? label : label_, nonce_);
TraceEventEnd(label ? label : label_);
nonce_ = 0;
}
}
private:
const char* label_;
uint64_t nonce_;
FML_DISALLOW_COPY_AND_ASSIGN(TraceFlow);
};
} // namespace tracing
} // namespace fml
#endif // FLUTTER_FML_TRACE_EVENT_H_
| engine/fml/trace_event.h/0 | {
"file_path": "engine/fml/trace_event.h",
"repo_id": "engine",
"token_count": 10487
} | 173 |
// Copyright 2013 The Flutter 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_AIKS_PLAYGROUND_H_
#define FLUTTER_IMPELLER_AIKS_AIKS_PLAYGROUND_H_
#include "flutter/fml/macros.h"
#include "impeller/aiks/aiks_context.h"
#include "impeller/aiks/aiks_playground_inspector.h"
#include "impeller/aiks/picture.h"
#include "impeller/playground/playground_test.h"
#include "impeller/typographer/typographer_context.h"
#include "third_party/imgui/imgui.h"
namespace impeller {
class AiksPlayground : public PlaygroundTest {
public:
using AiksPlaygroundCallback =
std::function<std::optional<Picture>(AiksContext& renderer)>;
AiksPlayground();
~AiksPlayground();
void TearDown() override;
void SetTypographerContext(
std::shared_ptr<TypographerContext> typographer_context);
bool OpenPlaygroundHere(Picture picture);
bool OpenPlaygroundHere(AiksPlaygroundCallback callback);
static bool ImGuiBegin(const char* name,
bool* p_open,
ImGuiWindowFlags flags);
private:
std::shared_ptr<TypographerContext> typographer_context_;
AiksInspector inspector_;
AiksPlayground(const AiksPlayground&) = delete;
AiksPlayground& operator=(const AiksPlayground&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_AIKS_PLAYGROUND_H_
| engine/impeller/aiks/aiks_playground.h/0 | {
"file_path": "engine/impeller/aiks/aiks_playground.h",
"repo_id": "engine",
"token_count": 538
} | 174 |
// Copyright 2013 The Flutter 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/aiks/image.h"
namespace impeller {
Image::Image(std::shared_ptr<Texture> texture) : texture_(std::move(texture)) {}
Image::~Image() = default;
ISize Image::GetSize() const {
return texture_ ? texture_->GetSize() : ISize{};
}
std::shared_ptr<Texture> Image::GetTexture() const {
return texture_;
}
} // namespace impeller
| engine/impeller/aiks/image.cc/0 | {
"file_path": "engine/impeller/aiks/image.cc",
"repo_id": "engine",
"token_count": 163
} | 175 |
// Copyright 2013 The Flutter 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_TRACE_SERIALIZER_H_
#define FLUTTER_IMPELLER_AIKS_TRACE_SERIALIZER_H_
#include <iostream>
#include "impeller/aiks/canvas_recorder.h"
namespace impeller {
class TraceSerializer {
public:
TraceSerializer();
void Write(CanvasRecorderOp 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);
private:
std::stringstream buffer_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_TRACE_SERIALIZER_H_
| engine/impeller/aiks/trace_serializer.h/0 | {
"file_path": "engine/impeller/aiks/trace_serializer.h",
"repo_id": "engine",
"token_count": 546
} | 176 |
// Copyright 2013 The Flutter 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/compiler/compiler_test.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/process.h"
#include <algorithm>
#include <filesystem>
namespace impeller {
namespace compiler {
namespace testing {
static std::string GetIntermediatesPath() {
auto test_name = flutter::testing::GetCurrentTestName();
std::replace(test_name.begin(), test_name.end(), '/', '_');
std::replace(test_name.begin(), test_name.end(), '.', '_');
std::stringstream dir_name;
dir_name << test_name << "_" << std::to_string(fml::GetCurrentProcId());
return fml::paths::JoinPaths(
{flutter::testing::GetFixturesPath(), dir_name.str()});
}
CompilerTest::CompilerTest() : intermediates_path_(GetIntermediatesPath()) {
intermediates_directory_ =
fml::OpenDirectory(intermediates_path_.c_str(),
true, // create if necessary
fml::FilePermission::kReadWrite);
FML_CHECK(intermediates_directory_.is_valid());
}
CompilerTest::~CompilerTest() {
intermediates_directory_.reset();
std::filesystem::remove_all(std::filesystem::path(intermediates_path_));
}
static std::string ReflectionHeaderName(const char* fixture_name) {
std::stringstream stream;
stream << fixture_name << ".h";
return stream.str();
}
static std::string ReflectionCCName(const char* fixture_name) {
std::stringstream stream;
stream << fixture_name << ".cc";
return stream.str();
}
static std::string ReflectionJSONName(const char* fixture_name) {
std::stringstream stream;
stream << fixture_name << ".json";
return stream.str();
}
static std::string SPIRVFileName(const char* fixture_name) {
std::stringstream stream;
stream << fixture_name << ".spv";
return stream.str();
}
static std::string SLFileName(const char* fixture_name,
TargetPlatform platform) {
std::stringstream stream;
stream << fixture_name << "." << TargetPlatformSLExtension(platform);
return stream.str();
}
std::unique_ptr<fml::FileMapping> CompilerTest::GetReflectionJson(
const char* fixture_name) const {
auto filename = ReflectionJSONName(fixture_name);
auto fd = fml::OpenFileReadOnly(intermediates_directory_, filename.c_str());
return fml::FileMapping::CreateReadOnly(fd);
}
std::unique_ptr<fml::FileMapping> CompilerTest::GetShaderFile(
const char* fixture_name,
TargetPlatform platform) const {
auto filename = SLFileName(fixture_name, platform);
auto fd = fml::OpenFileReadOnly(intermediates_directory_, filename.c_str());
return fml::FileMapping::CreateReadOnly(fd);
}
bool CompilerTest::CanCompileAndReflect(const char* fixture_name,
SourceType source_type,
SourceLanguage source_language,
const char* entry_point_name) const {
std::shared_ptr<fml::Mapping> fixture =
flutter::testing::OpenFixtureAsMapping(fixture_name);
if (!fixture || !fixture->GetMapping()) {
VALIDATION_LOG << "Could not find shader in fixtures: " << fixture_name;
return false;
}
SourceOptions source_options(fixture_name, source_type);
source_options.target_platform = GetParam();
source_options.source_language = source_language;
source_options.working_directory = std::make_shared<fml::UniqueFD>(
flutter::testing::OpenFixturesDirectory());
source_options.entry_point_name = EntryPointFunctionNameFromSourceName(
fixture_name, SourceTypeFromFileName(fixture_name), source_language,
entry_point_name);
Reflector::Options reflector_options;
reflector_options.header_file_name = ReflectionHeaderName(fixture_name);
reflector_options.shader_name = "shader_name";
Compiler compiler(fixture, source_options, reflector_options);
if (!compiler.IsValid()) {
VALIDATION_LOG << "Compilation failed: " << compiler.GetErrorMessages();
return false;
}
auto spirv_assembly = compiler.GetSPIRVAssembly();
if (!spirv_assembly) {
VALIDATION_LOG << "No spirv was generated.";
return false;
}
if (!fml::WriteAtomically(intermediates_directory_,
SPIRVFileName(fixture_name).c_str(),
*spirv_assembly)) {
VALIDATION_LOG << "Could not write SPIRV intermediates.";
return false;
}
auto sl_source = compiler.GetSLShaderSource();
if (!sl_source) {
VALIDATION_LOG << "No SL source was generated.";
return false;
}
if (!fml::WriteAtomically(intermediates_directory_,
SLFileName(fixture_name, GetParam()).c_str(),
*sl_source)) {
VALIDATION_LOG << "Could not write SL intermediates.";
return false;
}
if (TargetPlatformNeedsReflection(GetParam())) {
auto reflector = compiler.GetReflector();
if (!reflector) {
VALIDATION_LOG
<< "No reflector was found for target platform SL compiler.";
return false;
}
auto reflection_json = reflector->GetReflectionJSON();
auto reflection_header = reflector->GetReflectionHeader();
auto reflection_source = reflector->GetReflectionCC();
if (!reflection_json) {
VALIDATION_LOG << "Reflection JSON was not found.";
return false;
}
if (!reflection_header) {
VALIDATION_LOG << "Reflection header was not found.";
return false;
}
if (!reflection_source) {
VALIDATION_LOG << "Reflection source was not found.";
return false;
}
if (!fml::WriteAtomically(intermediates_directory_,
ReflectionHeaderName(fixture_name).c_str(),
*reflection_header)) {
VALIDATION_LOG << "Could not write reflection header intermediates.";
return false;
}
if (!fml::WriteAtomically(intermediates_directory_,
ReflectionCCName(fixture_name).c_str(),
*reflection_source)) {
VALIDATION_LOG << "Could not write reflection CC intermediates.";
return false;
}
if (!fml::WriteAtomically(intermediates_directory_,
ReflectionJSONName(fixture_name).c_str(),
*reflection_json)) {
VALIDATION_LOG << "Could not write reflection json intermediates.";
return false;
}
}
return true;
}
} // namespace testing
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/compiler_test.cc/0 | {
"file_path": "engine/impeller/compiler/compiler_test.cc",
"repo_id": "engine",
"token_count": 2527
} | 177 |
// Copyright 2013 The Flutter 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/compiler/shader_bundle_data.h"
#include <optional>
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
#include "impeller/base/validation.h"
namespace impeller {
namespace compiler {
ShaderBundleData::ShaderBundleData(std::string entrypoint,
spv::ExecutionModel stage,
TargetPlatform target_platform)
: entrypoint_(std::move(entrypoint)),
stage_(stage),
target_platform_(target_platform) {}
ShaderBundleData::~ShaderBundleData() = default;
void ShaderBundleData::AddUniformStruct(ShaderUniformStruct uniform_struct) {
uniform_structs_.emplace_back(std::move(uniform_struct));
}
void ShaderBundleData::AddUniformTexture(ShaderUniformTexture uniform_texture) {
uniform_textures_.emplace_back(std::move(uniform_texture));
}
void ShaderBundleData::AddInputDescription(InputDescription input) {
inputs_.emplace_back(std::move(input));
}
void ShaderBundleData::SetShaderData(std::shared_ptr<fml::Mapping> shader) {
shader_ = std::move(shader);
}
static std::optional<fb::shaderbundle::ShaderStage> ToStage(
spv::ExecutionModel stage) {
switch (stage) {
case spv::ExecutionModel::ExecutionModelVertex:
return fb::shaderbundle::ShaderStage::kVertex;
case spv::ExecutionModel::ExecutionModelFragment:
return fb::shaderbundle::ShaderStage::kFragment;
case spv::ExecutionModel::ExecutionModelGLCompute:
return fb::shaderbundle::ShaderStage::kCompute;
default:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<fb::shaderbundle::UniformDataType> ToUniformType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Boolean:
return fb::shaderbundle::UniformDataType::kBoolean;
case spirv_cross::SPIRType::SByte:
return fb::shaderbundle::UniformDataType::kSignedByte;
case spirv_cross::SPIRType::UByte:
return fb::shaderbundle::UniformDataType::kUnsignedByte;
case spirv_cross::SPIRType::Short:
return fb::shaderbundle::UniformDataType::kSignedShort;
case spirv_cross::SPIRType::UShort:
return fb::shaderbundle::UniformDataType::kUnsignedShort;
case spirv_cross::SPIRType::Int:
return fb::shaderbundle::UniformDataType::kSignedInt;
case spirv_cross::SPIRType::UInt:
return fb::shaderbundle::UniformDataType::kUnsignedInt;
case spirv_cross::SPIRType::Int64:
return fb::shaderbundle::UniformDataType::kSignedInt64;
case spirv_cross::SPIRType::UInt64:
return fb::shaderbundle::UniformDataType::kUnsignedInt64;
case spirv_cross::SPIRType::Half:
return fb::shaderbundle::UniformDataType::kHalfFloat;
case spirv_cross::SPIRType::Float:
return fb::shaderbundle::UniformDataType::kFloat;
case spirv_cross::SPIRType::Double:
return fb::shaderbundle::UniformDataType::kDouble;
case spirv_cross::SPIRType::SampledImage:
return fb::shaderbundle::UniformDataType::kSampledImage;
case spirv_cross::SPIRType::AccelerationStructure:
case spirv_cross::SPIRType::AtomicCounter:
case spirv_cross::SPIRType::Char:
case spirv_cross::SPIRType::ControlPointArray:
case spirv_cross::SPIRType::Image:
case spirv_cross::SPIRType::Interpolant:
case spirv_cross::SPIRType::RayQuery:
case spirv_cross::SPIRType::Sampler:
case spirv_cross::SPIRType::Struct:
case spirv_cross::SPIRType::Unknown:
case spirv_cross::SPIRType::Void:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<fb::shaderbundle::InputDataType> ToInputType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Boolean:
return fb::shaderbundle::InputDataType::kBoolean;
case spirv_cross::SPIRType::SByte:
return fb::shaderbundle::InputDataType::kSignedByte;
case spirv_cross::SPIRType::UByte:
return fb::shaderbundle::InputDataType::kUnsignedByte;
case spirv_cross::SPIRType::Short:
return fb::shaderbundle::InputDataType::kSignedShort;
case spirv_cross::SPIRType::UShort:
return fb::shaderbundle::InputDataType::kUnsignedShort;
case spirv_cross::SPIRType::Int:
return fb::shaderbundle::InputDataType::kSignedInt;
case spirv_cross::SPIRType::UInt:
return fb::shaderbundle::InputDataType::kUnsignedInt;
case spirv_cross::SPIRType::Int64:
return fb::shaderbundle::InputDataType::kSignedInt64;
case spirv_cross::SPIRType::UInt64:
return fb::shaderbundle::InputDataType::kUnsignedInt64;
case spirv_cross::SPIRType::Float:
return fb::shaderbundle::InputDataType::kFloat;
case spirv_cross::SPIRType::Double:
return fb::shaderbundle::InputDataType::kDouble;
case spirv_cross::SPIRType::Unknown:
case spirv_cross::SPIRType::Void:
case spirv_cross::SPIRType::Half:
case spirv_cross::SPIRType::AtomicCounter:
case spirv_cross::SPIRType::Struct:
case spirv_cross::SPIRType::Image:
case spirv_cross::SPIRType::SampledImage:
case spirv_cross::SPIRType::Sampler:
case spirv_cross::SPIRType::AccelerationStructure:
case spirv_cross::SPIRType::RayQuery:
case spirv_cross::SPIRType::ControlPointArray:
case spirv_cross::SPIRType::Interpolant:
case spirv_cross::SPIRType::Char:
return std::nullopt;
}
FML_UNREACHABLE();
}
std::unique_ptr<fb::shaderbundle::BackendShaderT>
ShaderBundleData::CreateFlatbuffer() const {
auto shader_bundle = std::make_unique<fb::shaderbundle::BackendShaderT>();
// The high level object API is used here for writing to the buffer. This is
// just a convenience.
shader_bundle->entrypoint = entrypoint_;
const auto stage = ToStage(stage_);
if (!stage.has_value()) {
VALIDATION_LOG << "Invalid shader bundle.";
return nullptr;
}
shader_bundle->stage = stage.value();
// This field is ignored, so just set it to anything.
if (!shader_) {
VALIDATION_LOG << "No shader specified for shader bundle.";
return nullptr;
}
if (shader_->GetSize() > 0u) {
shader_bundle->shader = {shader_->GetMapping(),
shader_->GetMapping() + shader_->GetSize()};
}
for (const auto& uniform : uniform_structs_) {
auto desc = std::make_unique<fb::shaderbundle::ShaderUniformStructT>();
desc->name = uniform.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Uniform name cannot be empty.";
return nullptr;
}
desc->ext_res_0 = uniform.ext_res_0;
desc->set = uniform.set;
desc->binding = uniform.binding;
desc->size_in_bytes = uniform.size_in_bytes;
for (const auto& field : uniform.fields) {
auto field_desc =
std::make_unique<fb::shaderbundle::ShaderUniformStructFieldT>();
field_desc->name = field.name;
auto type = ToUniformType(field.type);
if (!type.has_value()) {
VALIDATION_LOG << " Invalid shader type " << field.type << ".";
return nullptr;
}
field_desc->type = type.value();
field_desc->offset_in_bytes = field.offset_in_bytes;
field_desc->element_size_in_bytes = field.element_size_in_bytes;
field_desc->total_size_in_bytes = field.total_size_in_bytes;
field_desc->array_elements = field.array_elements.value_or(0);
desc->fields.push_back(std::move(field_desc));
}
shader_bundle->uniform_structs.emplace_back(std::move(desc));
}
for (const auto& texture : uniform_textures_) {
auto desc = std::make_unique<fb::shaderbundle::ShaderUniformTextureT>();
desc->name = texture.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Uniform name cannot be empty.";
return nullptr;
}
desc->ext_res_0 = texture.ext_res_0;
desc->set = texture.set;
desc->binding = texture.binding;
shader_bundle->uniform_textures.emplace_back(std::move(desc));
}
for (const auto& input : inputs_) {
auto desc = std::make_unique<fb::shaderbundle::ShaderInputT>();
desc->name = input.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Stage input name cannot be empty.";
return nullptr;
}
desc->location = input.location;
desc->set = input.set;
desc->binding = input.binding;
auto input_type = ToInputType(input.type);
if (!input_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = input_type.value();
desc->bit_width = input.bit_width;
desc->vec_size = input.vec_size;
desc->columns = input.columns;
desc->offset = input.offset;
shader_bundle->inputs.emplace_back(std::move(desc));
}
return shader_bundle;
}
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/shader_bundle_data.cc/0 | {
"file_path": "engine/impeller/compiler/shader_bundle_data.cc",
"repo_id": "engine",
"token_count": 3510
} | 178 |
// Copyright 2013 The Flutter 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 PATH_GLSL_
#define PATH_GLSL_
struct LineData {
vec2 p1;
vec2 p2;
};
struct QuadData {
vec2 p1;
vec2 cp;
vec2 p2;
};
struct CubicData {
vec2 p1;
vec2 cp1;
vec2 cp2;
vec2 p2;
};
struct QuadDecomposition {
float a0;
float a2;
float u0;
float u_scale;
uint line_count;
float steps;
};
struct PathComponent {
uint index; // Location in buffer
uint count; // Number of points. 4 = cubic, 3 = quad, 2 = line.
};
/// Solve for point on a quadratic Bezier curve defined by starting point `p1`,
/// control point `cp`, and end point `p2` at time `t`.
vec2 QuadraticSolve(QuadData quad, float t) {
return (1.0 - t) * (1.0 - t) * quad.p1 + //
2.0 * (1.0 - t) * t * quad.cp + //
t * t * quad.p2;
}
vec2 CubicSolve(CubicData cubic, float t) {
return (1. - t) * (1. - t) * (1. - t) * cubic.p1 + //
3 * (1. - t) * (1. - t) * t * cubic.cp1 + //
3 * (1. - t) * t * t * cubic.cp2 + //
t * t * t * cubic.p2;
}
/// Used to approximate quadratic curves using parabola.
///
/// See
/// https://raphlinus.github.io/graphics/curves/2019/12/23/flatten-quadbez.html
float ApproximateParabolaIntegral(float x) {
float d = 0.67;
return x / (1.0 - d + sqrt(sqrt(pow(d, 4) + 0.25 * x * x)));
}
bool isfinite(float f) {
return !isnan(f) && !isinf(f);
}
float Cross(vec2 p1, vec2 p2) {
return p1.x * p2.y - p1.y * p2.x;
}
QuadData GenerateQuadraticFromCubic(CubicData cubic,
uint index,
float quad_count) {
float t0 = index / quad_count;
float t1 = (index + 1) / quad_count;
// calculate the subsegment
vec2 sub_p1 = CubicSolve(cubic, t0);
vec2 sub_p2 = CubicSolve(cubic, t1);
QuadData quad = QuadData(3.0 * (cubic.cp1 - cubic.p1), //
3.0 * (cubic.cp2 - cubic.cp1), //
3.0 * (cubic.p2 - cubic.cp2));
float sub_scale = (t1 - t0) * (1.0 / 3.0);
vec2 sub_cp1 = sub_p1 + sub_scale * QuadraticSolve(quad, t0);
vec2 sub_cp2 = sub_p2 - sub_scale * QuadraticSolve(quad, t1);
vec2 quad_p1x2 = 3.0 * sub_cp1 - sub_p1;
vec2 quad_p2x2 = 3.0 * sub_cp2 - sub_p2;
return QuadData(sub_p1, //
((quad_p1x2 + quad_p2x2) / 4.0), //
sub_p2);
}
uint EstimateQuadraticCount(CubicData cubic, float accuracy) {
// The maximum error, as a vector from the cubic to the best approximating
// quadratic, is proportional to the third derivative, which is constant
// across the segment. Thus, the error scales down as the third power of
// the number of subdivisions. Our strategy then is to subdivide `t` evenly.
//
// This is an overestimate of the error because only the component
// perpendicular to the first derivative is important. But the simplicity is
// appealing.
// This magic number is the square of 36 / sqrt(3).
// See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html
float max_hypot2 = 432.0 * accuracy * accuracy;
vec2 err_v = (3.0 * cubic.cp2 - cubic.p2) - (3.0 * cubic.cp1 - cubic.p1);
float err = dot(err_v, err_v);
return uint(max(1., ceil(pow(err * (1.0 / max_hypot2), 1. / 6.0))));
}
QuadDecomposition DecomposeQuad(QuadData quad, float tolerance) {
float sqrt_tolerance = sqrt(tolerance);
vec2 d01 = quad.cp - quad.p1;
vec2 d12 = quad.p2 - quad.cp;
vec2 dd = d01 - d12;
// This should never happen, but if it does happen be more defensive -
// otherwise we'll get NaNs down the line.
if (dd == vec2(0.)) {
return QuadDecomposition(0., 0., 0., 0., 0, 0.);
}
float c = Cross(quad.p2 - quad.p1, dd);
float x0 = dot(d01, dd) * 1. / c;
float x2 = dot(d12, dd) * 1. / c;
float scale = abs(c / (sqrt(dd.x * dd.x + dd.y * dd.y) * (x2 - x0)));
float a0 = ApproximateParabolaIntegral(x0);
float a2 = ApproximateParabolaIntegral(x2);
float val = 0.f;
if (isfinite(scale)) {
float da = abs(a2 - a0);
float sqrt_scale = sqrt(scale);
if ((x0 < 0 && x2 < 0) || (x0 >= 0 && x2 >= 0)) {
val = da * sqrt_scale;
} else {
// cusp case
float xmin = sqrt_tolerance / sqrt_scale;
val = sqrt_tolerance * da / ApproximateParabolaIntegral(xmin);
}
}
float u0 = ApproximateParabolaIntegral(a0);
float u2 = ApproximateParabolaIntegral(a2);
float u_scale = 1. / (u2 - u0);
uint line_count = uint(max(1., ceil(0.5 * val / sqrt_tolerance)) + 1.);
float steps = 1. / line_count;
return QuadDecomposition(a0, a2, u0, u_scale, line_count, steps);
}
vec2 GenerateLineFromQuad(QuadData quad,
uint index,
QuadDecomposition decomposition) {
float u = index * decomposition.steps;
float a = decomposition.a0 + (decomposition.a2 - decomposition.a0) * u;
float t = (ApproximateParabolaIntegral(a) - decomposition.u0) *
decomposition.u_scale;
return QuadraticSolve(quad, t);
}
#endif
| engine/impeller/compiler/shader_lib/impeller/path.glsl/0 | {
"file_path": "engine/impeller/compiler/shader_lib/impeller/path.glsl",
"repo_id": "engine",
"token_count": 2279
} | 179 |
// Copyright 2013 The Flutter 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_TYPES_H_
#define FLUTTER_IMPELLER_COMPILER_TYPES_H_
#include <codecvt>
#include <locale>
#include <map>
#include <optional>
#include <string>
#include "flutter/fml/macros.h"
#include "shaderc/shaderc.hpp"
#include "spirv_cross.hpp"
#include "spirv_msl.hpp"
namespace impeller {
namespace compiler {
enum class SourceType {
kUnknown,
kVertexShader,
kFragmentShader,
kComputeShader,
};
enum class TargetPlatform {
kUnknown,
kMetalDesktop,
kMetalIOS,
kOpenGLES,
kOpenGLDesktop,
kVulkan,
kRuntimeStageMetal,
kRuntimeStageGLES,
kRuntimeStageVulkan,
kSkSL,
};
enum class SourceLanguage {
kUnknown,
kGLSL,
kHLSL,
};
struct UniformDescription {
std::string name;
size_t location = 0u;
spirv_cross::SPIRType::BaseType type = spirv_cross::SPIRType::BaseType::Float;
size_t rows = 0u;
size_t columns = 0u;
size_t bit_width = 0u;
std::optional<size_t> array_elements = std::nullopt;
std::vector<uint8_t> struct_layout = {};
size_t struct_float_count = 0u;
};
struct InputDescription {
std::string name;
size_t location;
size_t set;
size_t binding;
spirv_cross::SPIRType::BaseType type =
spirv_cross::SPIRType::BaseType::Unknown;
size_t bit_width;
size_t vec_size;
size_t columns;
size_t offset;
};
/// A shader config parsed as part of a ShaderBundleConfig.
struct ShaderConfig {
std::string source_file_name;
SourceType type;
SourceLanguage language;
std::string entry_point;
};
using ShaderBundleConfig = std::unordered_map<std::string, ShaderConfig>;
bool TargetPlatformIsMetal(TargetPlatform platform);
bool TargetPlatformIsOpenGL(TargetPlatform platform);
bool TargetPlatformIsVulkan(TargetPlatform platform);
SourceType SourceTypeFromFileName(const std::string& file_name);
SourceType SourceTypeFromString(std::string name);
std::string SourceTypeToString(SourceType type);
std::string TargetPlatformToString(TargetPlatform platform);
SourceLanguage ToSourceLanguage(const std::string& source_language);
std::string SourceLanguageToString(SourceLanguage source_language);
std::string TargetPlatformSLExtension(TargetPlatform platform);
std::string EntryPointFunctionNameFromSourceName(
const std::string& file_name,
SourceType type,
SourceLanguage source_language,
const std::string& entry_point_name);
bool TargetPlatformNeedsReflection(TargetPlatform platform);
bool TargetPlatformBundlesSkSL(TargetPlatform platform);
std::string ShaderCErrorToString(shaderc_compilation_status status);
shaderc_shader_kind ToShaderCShaderKind(SourceType type);
spv::ExecutionModel ToExecutionModel(SourceType type);
spirv_cross::CompilerMSL::Options::Platform TargetPlatformToMSLPlatform(
TargetPlatform platform);
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_TYPES_H_
| engine/impeller/compiler/types.h/0 | {
"file_path": "engine/impeller/compiler/types.h",
"repo_id": "engine",
"token_count": 1023
} | 180 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_DESCRIPTOR_H_
#define FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_DESCRIPTOR_H_
#include <cstddef>
#include "impeller/core/formats.h"
namespace impeller {
struct DeviceBufferDescriptor {
StorageMode storage_mode = StorageMode::kDeviceTransient;
size_t size = 0u;
// Perhaps we could combine this with storage mode and create appropriate
// host-write and host-read flags.
bool readback = false;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_DESCRIPTOR_H_
| engine/impeller/core/device_buffer_descriptor.h/0 | {
"file_path": "engine/impeller/core/device_buffer_descriptor.h",
"repo_id": "engine",
"token_count": 240
} | 181 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_CORE_SAMPLER_DESCRIPTOR_H_
#define FLUTTER_IMPELLER_CORE_SAMPLER_DESCRIPTOR_H_
#include "impeller/base/comparable.h"
#include "impeller/core/formats.h"
namespace impeller {
class Context;
struct SamplerDescriptor final : public Comparable<SamplerDescriptor> {
MinMagFilter min_filter = MinMagFilter::kNearest;
MinMagFilter mag_filter = MinMagFilter::kNearest;
MipFilter mip_filter = MipFilter::kNearest;
SamplerAddressMode width_address_mode = SamplerAddressMode::kClampToEdge;
SamplerAddressMode height_address_mode = SamplerAddressMode::kClampToEdge;
SamplerAddressMode depth_address_mode = SamplerAddressMode::kClampToEdge;
std::string label = "NN Clamp Sampler";
SamplerDescriptor();
SamplerDescriptor(std::string label,
MinMagFilter min_filter,
MinMagFilter mag_filter,
MipFilter mip_filter);
// Comparable<SamplerDescriptor>
std::size_t GetHash() const override {
return fml::HashCombine(min_filter, mag_filter, mip_filter,
width_address_mode, height_address_mode,
depth_address_mode);
}
// Comparable<SamplerDescriptor>
bool IsEqual(const SamplerDescriptor& o) const override {
return min_filter == o.min_filter && mag_filter == o.mag_filter &&
mip_filter == o.mip_filter &&
width_address_mode == o.width_address_mode &&
height_address_mode == o.height_address_mode &&
depth_address_mode == o.depth_address_mode;
}
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_CORE_SAMPLER_DESCRIPTOR_H_
| engine/impeller/core/sampler_descriptor.h/0 | {
"file_path": "engine/impeller/core/sampler_descriptor.h",
"repo_id": "engine",
"token_count": 718
} | 182 |
// Copyright 2013 The Flutter 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 <array>
#include <cmath>
#include <memory>
#include <vector>
#include "flutter/display_list/dl_blend_mode.h"
#include "flutter/display_list/dl_builder.h"
#include "flutter/display_list/dl_color.h"
#include "flutter/display_list/dl_paint.h"
#include "flutter/display_list/dl_tile_mode.h"
#include "flutter/display_list/effects/dl_color_filter.h"
#include "flutter/display_list/effects/dl_color_source.h"
#include "flutter/display_list/effects/dl_image_filter.h"
#include "flutter/display_list/effects/dl_mask_filter.h"
#include "flutter/testing/testing.h"
#include "gtest/gtest.h"
#include "impeller/display_list/dl_dispatcher.h"
#include "impeller/display_list/dl_image_impeller.h"
#include "impeller/display_list/dl_playground.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/solid_color_contents.h"
#include "impeller/entity/contents/solid_rrect_blur_contents.h"
#include "impeller/geometry/constants.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/scalar.h"
#include "impeller/playground/widgets.h"
#include "impeller/scene/node.h"
#include "third_party/imgui/imgui.h"
#include "third_party/skia/include/core/SkBlurTypes.h"
#include "third_party/skia/include/core/SkClipOp.h"
#include "third_party/skia/include/core/SkPathBuilder.h"
#include "third_party/skia/include/core/SkRRect.h"
namespace impeller {
namespace testing {
flutter::DlColor toColor(const float* components) {
return flutter::DlColor(Color::ToIColor(
Color(components[0], components[1], components[2], components[3])));
}
using DisplayListTest = DlPlayground;
INSTANTIATE_PLAYGROUND_SUITE(DisplayListTest);
TEST_P(DisplayListTest, CanDrawRect) {
flutter::DisplayListBuilder builder;
builder.DrawRect(SkRect::MakeXYWH(10, 10, 100, 100),
flutter::DlPaint(flutter::DlColor::kBlue()));
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawTextBlob) {
flutter::DisplayListBuilder builder;
builder.DrawTextBlob(SkTextBlob::MakeFromString("Hello", CreateTestFont()),
100, 100, flutter::DlPaint(flutter::DlColor::kBlue()));
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawTextBlobWithGradient) {
flutter::DisplayListBuilder builder;
std::vector<flutter::DlColor> colors = {flutter::DlColor::kBlue(),
flutter::DlColor::kRed()};
const float stops[2] = {0.0, 1.0};
auto linear = flutter::DlColorSource::MakeLinear({0.0, 0.0}, {300.0, 300.0},
2, colors.data(), stops,
flutter::DlTileMode::kClamp);
flutter::DlPaint paint;
paint.setColorSource(linear);
builder.DrawTextBlob(
SkTextBlob::MakeFromString("Hello World", CreateTestFont()), 100, 100,
paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawTextWithSaveLayer) {
flutter::DisplayListBuilder builder;
builder.DrawTextBlob(SkTextBlob::MakeFromString("Hello", CreateTestFont()),
100, 100, flutter::DlPaint(flutter::DlColor::kRed()));
flutter::DlPaint save_paint;
float alpha = 0.5;
save_paint.setAlpha(static_cast<uint8_t>(255 * alpha));
builder.SaveLayer(nullptr, &save_paint);
builder.DrawTextBlob(SkTextBlob::MakeFromString("Hello with half alpha",
CreateTestFontOfSize(100)),
100, 300, flutter::DlPaint(flutter::DlColor::kRed()));
builder.Restore();
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawImage) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, nullptr);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawCapsAndJoins) {
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setStrokeWidth(30);
paint.setColor(flutter::DlColor::kRed());
auto path =
SkPathBuilder{}.moveTo(-50, 0).lineTo(0, -50).lineTo(50, 0).snapshot();
builder.Translate(100, 100);
{
paint.setStrokeCap(flutter::DlStrokeCap::kButt);
paint.setStrokeJoin(flutter::DlStrokeJoin::kMiter);
paint.setStrokeMiter(4);
builder.DrawPath(path, paint);
}
{
builder.Save();
builder.Translate(0, 100);
// The joint in the path is 45 degrees. A miter length of 1 convert to a
// bevel in this case.
paint.setStrokeMiter(1);
builder.DrawPath(path, paint);
builder.Restore();
}
builder.Translate(150, 0);
{
paint.setStrokeCap(flutter::DlStrokeCap::kSquare);
paint.setStrokeJoin(flutter::DlStrokeJoin::kBevel);
builder.DrawPath(path, paint);
}
builder.Translate(150, 0);
{
paint.setStrokeCap(flutter::DlStrokeCap::kRound);
paint.setStrokeJoin(flutter::DlStrokeJoin::kRound);
builder.DrawPath(path, paint);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawArc) {
auto callback = [&]() {
static float start_angle = 45;
static float sweep_angle = 270;
static float stroke_width = 10;
static bool use_center = true;
static int selected_cap = 0;
const char* cap_names[] = {"Butt", "Round", "Square"};
flutter::DlStrokeCap cap;
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::SliderFloat("Start angle", &start_angle, -360, 360);
ImGui::SliderFloat("Sweep angle", &sweep_angle, -360, 360);
ImGui::SliderFloat("Stroke width", &stroke_width, 0, 300);
ImGui::Combo("Cap", &selected_cap, cap_names,
sizeof(cap_names) / sizeof(char*));
ImGui::Checkbox("Use center", &use_center);
ImGui::End();
switch (selected_cap) {
case 0:
cap = flutter::DlStrokeCap::kButt;
break;
case 1:
cap = flutter::DlStrokeCap::kRound;
break;
case 2:
cap = flutter::DlStrokeCap::kSquare;
break;
default:
cap = flutter::DlStrokeCap::kButt;
break;
}
static PlaygroundPoint point_a(Point(200, 200), 20, Color::White());
static PlaygroundPoint point_b(Point(400, 400), 20, Color::White());
auto [p1, p2] = DrawPlaygroundLine(point_a, point_b);
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
Vector2 scale = GetContentScale();
builder.Scale(scale.x, scale.y);
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setStrokeCap(cap);
paint.setStrokeJoin(flutter::DlStrokeJoin::kMiter);
paint.setStrokeMiter(10);
auto rect = SkRect::MakeLTRB(p1.x, p1.y, p2.x, p2.y);
paint.setColor(flutter::DlColor::kGreen());
paint.setStrokeWidth(2);
builder.DrawRect(rect, paint);
paint.setColor(flutter::DlColor::kRed());
paint.setStrokeWidth(stroke_width);
builder.DrawArc(rect, start_angle, sweep_angle, use_center, paint);
return builder.Build();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(DisplayListTest, StrokedPathsDrawCorrectly) {
auto callback = [&]() {
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kRed());
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
static float stroke_width = 10.0f;
static int selected_stroke_type = 0;
static int selected_join_type = 0;
const char* stroke_types[] = {"Butte", "Round", "Square"};
const char* join_type[] = {"kMiter", "Round", "kBevel"};
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::Combo("Cap", &selected_stroke_type, stroke_types,
sizeof(stroke_types) / sizeof(char*));
ImGui::Combo("Join", &selected_join_type, join_type,
sizeof(join_type) / sizeof(char*));
ImGui::SliderFloat("Stroke Width", &stroke_width, 10.0f, 50.0f);
ImGui::End();
flutter::DlStrokeCap cap;
flutter::DlStrokeJoin join;
switch (selected_stroke_type) {
case 0:
cap = flutter::DlStrokeCap::kButt;
break;
case 1:
cap = flutter::DlStrokeCap::kRound;
break;
case 2:
cap = flutter::DlStrokeCap::kSquare;
break;
default:
cap = flutter::DlStrokeCap::kButt;
break;
}
switch (selected_join_type) {
case 0:
join = flutter::DlStrokeJoin::kMiter;
break;
case 1:
join = flutter::DlStrokeJoin::kRound;
break;
case 2:
join = flutter::DlStrokeJoin::kBevel;
break;
default:
join = flutter::DlStrokeJoin::kMiter;
break;
}
paint.setStrokeCap(cap);
paint.setStrokeJoin(join);
paint.setStrokeWidth(stroke_width);
// Make rendering better to watch.
builder.Scale(1.5f, 1.5f);
// Rectangle
builder.Translate(100, 100);
builder.DrawRect(SkRect::MakeSize({100, 100}), paint);
// Rounded rectangle
builder.Translate(150, 0);
builder.DrawRRect(SkRRect::MakeRectXY(SkRect::MakeSize({100, 50}), 10, 10),
paint);
// Double rounded rectangle
builder.Translate(150, 0);
builder.DrawDRRect(
SkRRect::MakeRectXY(SkRect::MakeSize({100, 50}), 10, 10),
SkRRect::MakeRectXY(SkRect::MakeXYWH(10, 10, 80, 30), 10, 10), paint);
// Contour with duplicate join points
{
builder.Translate(150, 0);
SkPath path;
path.moveTo(0, 0);
path.lineTo(0, 0);
path.lineTo({100, 0});
path.lineTo({100, 0});
path.lineTo({100, 100});
builder.DrawPath(path, paint);
}
// Contour with duplicate start and end points
// Line.
builder.Translate(200, 0);
{
builder.Save();
SkPath line_path;
line_path.moveTo(0, 0);
line_path.moveTo(0, 0);
line_path.lineTo({0, 0});
line_path.lineTo({0, 0});
line_path.lineTo({50, 50});
line_path.lineTo({50, 50});
line_path.lineTo({100, 0});
line_path.lineTo({100, 0});
builder.DrawPath(line_path, paint);
builder.Translate(0, 100);
builder.DrawPath(line_path, paint);
builder.Translate(0, 100);
SkPath line_path2;
line_path2.moveTo(0, 0);
line_path2.lineTo(0, 0);
line_path2.lineTo(0, 0);
builder.DrawPath(line_path2, paint);
builder.Restore();
}
// Cubic.
builder.Translate(150, 0);
{
builder.Save();
SkPath cubic_path;
cubic_path.moveTo({0, 0});
cubic_path.cubicTo(0, 0, 140.0, 100.0, 140, 20);
builder.DrawPath(cubic_path, paint);
builder.Translate(0, 100);
SkPath cubic_path2;
cubic_path2.moveTo({0, 0});
cubic_path2.cubicTo(0, 0, 0, 0, 150, 150);
builder.DrawPath(cubic_path2, paint);
builder.Translate(0, 100);
SkPath cubic_path3;
cubic_path3.moveTo({0, 0});
cubic_path3.cubicTo(0, 0, 0, 0, 0, 0);
builder.DrawPath(cubic_path3, paint);
builder.Restore();
}
// Quad.
builder.Translate(200, 0);
{
builder.Save();
SkPath quad_path;
quad_path.moveTo(0, 0);
quad_path.moveTo(0, 0);
quad_path.quadTo({100, 40}, {50, 80});
builder.DrawPath(quad_path, paint);
builder.Translate(0, 150);
SkPath quad_path2;
quad_path2.moveTo(0, 0);
quad_path2.moveTo(0, 0);
quad_path2.quadTo({0, 0}, {100, 100});
builder.DrawPath(quad_path2, paint);
builder.Translate(0, 100);
SkPath quad_path3;
quad_path3.moveTo(0, 0);
quad_path3.quadTo({0, 0}, {0, 0});
builder.DrawPath(quad_path3, paint);
builder.Restore();
}
return builder.Build();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(DisplayListTest, CanDrawWithOddPathWinding) {
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kRed());
paint.setDrawStyle(flutter::DlDrawStyle::kFill);
builder.Translate(300, 300);
SkPath path;
path.setFillType(SkPathFillType::kEvenOdd);
path.addCircle(0, 0, 100);
path.addCircle(0, 0, 50);
builder.DrawPath(path, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
// Regression test for https://github.com/flutter/flutter/issues/134816.
//
// It should be possible to draw 3 lines, and not have an implicit close path.
TEST_P(DisplayListTest, CanDrawAnOpenPath) {
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kRed());
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setStrokeWidth(10);
builder.Translate(300, 300);
// Move to (50, 50) and draw lines from:
// 1. (50, height)
// 2. (width, height)
// 3. (width, 50)
SkPath path;
path.moveTo(50, 50);
path.lineTo(50, 100);
path.lineTo(100, 100);
path.lineTo(100, 50);
builder.DrawPath(path, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawWithMaskBlur) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
// Mask blurred image.
{
auto filter =
flutter::DlBlurMaskFilter(flutter::DlBlurStyle::kNormal, 10.0f);
paint.setMaskFilter(&filter);
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, &paint);
}
// Mask blurred filled path.
{
paint.setColor(flutter::DlColor::kYellow());
auto filter =
flutter::DlBlurMaskFilter(flutter::DlBlurStyle::kOuter, 10.0f);
paint.setMaskFilter(&filter);
builder.DrawArc(SkRect::MakeXYWH(410, 110, 100, 100), 45, 270, true, paint);
}
// Mask blurred text.
{
auto filter =
flutter::DlBlurMaskFilter(flutter::DlBlurStyle::kSolid, 10.0f);
paint.setMaskFilter(&filter);
builder.DrawTextBlob(
SkTextBlob::MakeFromString("Testing", CreateTestFont()), 220, 170,
paint);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawStrokedText) {
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setColor(flutter::DlColor::kRed());
builder.DrawTextBlob(
SkTextBlob::MakeFromString("stoked about stroked text", CreateTestFont()),
250, 250, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
// Regression test for https://github.com/flutter/flutter/issues/133157.
TEST_P(DisplayListTest, StrokedTextNotOffsetFromNormalText) {
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
auto const& text_blob = SkTextBlob::MakeFromString("00000", CreateTestFont());
// https://api.flutter.dev/flutter/material/Colors/blue-constant.html.
auto const& mat_blue = flutter::DlColor(0xFF2196f3);
// Draw a blue filled rectangle so the text is easier to see.
paint.setDrawStyle(flutter::DlDrawStyle::kFill);
paint.setColor(mat_blue);
builder.DrawRect(SkRect::MakeXYWH(0, 0, 500, 500), paint);
// Draw stacked text, with stroked text on top.
paint.setDrawStyle(flutter::DlDrawStyle::kFill);
paint.setColor(flutter::DlColor::kWhite());
builder.DrawTextBlob(text_blob, 250, 250, paint);
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setColor(flutter::DlColor::kBlack());
builder.DrawTextBlob(text_blob, 250, 250, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, IgnoreMaskFilterWhenSavingLayer) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
auto filter = flutter::DlBlurMaskFilter(flutter::DlBlurStyle::kNormal, 10.0f);
flutter::DlPaint paint;
paint.setMaskFilter(&filter);
builder.SaveLayer(nullptr, &paint);
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor);
builder.Restore();
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawWithBlendColorFilter) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
// Pipeline blended image.
{
auto filter = flutter::DlBlendColorFilter(flutter::DlColor::kYellow(),
flutter::DlBlendMode::kModulate);
paint.setColorFilter(&filter);
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, &paint);
}
// Advanced blended image.
{
auto filter = flutter::DlBlendColorFilter(flutter::DlColor::kRed(),
flutter::DlBlendMode::kScreen);
paint.setColorFilter(&filter);
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(250, 250),
flutter::DlImageSampling::kNearestNeighbor, &paint);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawWithColorFilterImageFilter) {
const float invert_color_matrix[20] = {
-1, 0, 0, 0, 1, //
0, -1, 0, 0, 1, //
0, 0, -1, 0, 1, //
0, 0, 0, 1, 0, //
};
auto texture = CreateTextureForFixture("boston.jpg");
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
auto color_filter =
std::make_shared<flutter::DlMatrixColorFilter>(invert_color_matrix);
auto image_filter =
std::make_shared<flutter::DlColorFilterImageFilter>(color_filter);
paint.setImageFilter(image_filter.get());
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, &paint);
builder.Translate(0, 700);
paint.setColorFilter(color_filter.get());
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, &paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawWithImageBlurFilter) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
auto callback = [&]() {
static float sigma[] = {10, 10};
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::SliderFloat2("Sigma", sigma, 0, 100);
ImGui::End();
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
auto filter = flutter::DlBlurImageFilter(sigma[0], sigma[1],
flutter::DlTileMode::kClamp);
paint.setImageFilter(&filter);
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(200, 200),
flutter::DlImageSampling::kNearestNeighbor, &paint);
return builder.Build();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(DisplayListTest, CanDrawWithComposeImageFilter) {
auto texture = CreateTextureForFixture("boston.jpg");
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
auto dilate = std::make_shared<flutter::DlDilateImageFilter>(10.0, 10.0);
auto erode = std::make_shared<flutter::DlErodeImageFilter>(10.0, 10.0);
auto open = std::make_shared<flutter::DlComposeImageFilter>(dilate, erode);
auto close = std::make_shared<flutter::DlComposeImageFilter>(erode, dilate);
paint.setImageFilter(open.get());
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, &paint);
builder.Translate(0, 700);
paint.setImageFilter(close.get());
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, &paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanClampTheResultingColorOfColorMatrixFilter) {
auto texture = CreateTextureForFixture("boston.jpg");
const float inner_color_matrix[20] = {
1, 0, 0, 0, 0, //
0, 1, 0, 0, 0, //
0, 0, 1, 0, 0, //
0, 0, 0, 2, 0, //
};
const float outer_color_matrix[20] = {
1, 0, 0, 0, 0, //
0, 1, 0, 0, 0, //
0, 0, 1, 0, 0, //
0, 0, 0, 0.5, 0, //
};
auto inner_color_filter =
std::make_shared<flutter::DlMatrixColorFilter>(inner_color_matrix);
auto outer_color_filter =
std::make_shared<flutter::DlMatrixColorFilter>(outer_color_matrix);
auto inner =
std::make_shared<flutter::DlColorFilterImageFilter>(inner_color_filter);
auto outer =
std::make_shared<flutter::DlColorFilterImageFilter>(outer_color_filter);
auto compose = std::make_shared<flutter::DlComposeImageFilter>(outer, inner);
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setImageFilter(compose.get());
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(100, 100),
flutter::DlImageSampling::kNearestNeighbor, &paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawBackdropFilter) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
auto callback = [&]() {
static float sigma[] = {10, 10};
static float ctm_scale = 1;
static bool use_bounds = true;
static bool draw_circle = true;
static bool add_clip = true;
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::SliderFloat2("Sigma", sigma, 0, 100);
ImGui::SliderFloat("Scale", &ctm_scale, 0, 10);
ImGui::NewLine();
ImGui::TextWrapped(
"If everything is working correctly, none of the options below should "
"impact the filter's appearance.");
ImGui::Checkbox("Use SaveLayer bounds", &use_bounds);
ImGui::Checkbox("Draw child element", &draw_circle);
ImGui::Checkbox("Add pre-clip", &add_clip);
ImGui::End();
flutter::DisplayListBuilder builder;
Vector2 scale = ctm_scale * GetContentScale();
builder.Scale(scale.x, scale.y);
auto filter = flutter::DlBlurImageFilter(sigma[0], sigma[1],
flutter::DlTileMode::kClamp);
std::optional<SkRect> bounds;
if (use_bounds) {
static PlaygroundPoint point_a(Point(350, 150), 20, Color::White());
static PlaygroundPoint point_b(Point(800, 600), 20, Color::White());
auto [p1, p2] = DrawPlaygroundLine(point_a, point_b);
bounds = SkRect::MakeLTRB(p1.x, p1.y, p2.x, p2.y);
}
// Insert a clip to test that the backdrop filter handles stencil depths > 0
// correctly.
if (add_clip) {
builder.ClipRect(SkRect::MakeLTRB(0, 0, 99999, 99999),
flutter::DlCanvas::ClipOp::kIntersect, true);
}
builder.DrawImage(DlImageImpeller::Make(texture), SkPoint::Make(200, 200),
flutter::DlImageSampling::kNearestNeighbor, nullptr);
builder.SaveLayer(bounds.has_value() ? &bounds.value() : nullptr, nullptr,
&filter);
if (draw_circle) {
static PlaygroundPoint center_point(Point(500, 400), 20, Color::Red());
auto circle_center = DrawPlaygroundPoint(center_point);
flutter::DlPaint paint;
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setStrokeCap(flutter::DlStrokeCap::kButt);
paint.setStrokeJoin(flutter::DlStrokeJoin::kBevel);
paint.setStrokeWidth(10);
paint.setColor(flutter::DlColor::kRed().withAlpha(100));
builder.DrawCircle({circle_center.x, circle_center.y}, 100, paint);
}
return builder.Build();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(DisplayListTest, CanDrawNinePatchImage) {
// Image is drawn with corners to scale and center pieces stretched to fit.
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
auto size = texture->GetSize();
builder.DrawImageNine(
DlImageImpeller::Make(texture),
SkIRect::MakeLTRB(size.width / 4, size.height / 4, size.width * 3 / 4,
size.height * 3 / 4),
SkRect::MakeLTRB(0, 0, size.width * 2, size.height * 2),
flutter::DlFilterMode::kNearest, nullptr);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawNinePatchImageCenterWidthBiggerThanDest) {
// Edge case, the width of the corners does not leave any room for the
// center slice. The center (across the vertical axis) is folded out of the
// resulting image.
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
auto size = texture->GetSize();
builder.DrawImageNine(
DlImageImpeller::Make(texture),
SkIRect::MakeLTRB(size.width / 4, size.height / 4, size.width * 3 / 4,
size.height * 3 / 4),
SkRect::MakeLTRB(0, 0, size.width / 2, size.height),
flutter::DlFilterMode::kNearest, nullptr);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawNinePatchImageCenterHeightBiggerThanDest) {
// Edge case, the height of the corners does not leave any room for the
// center slice. The center (across the horizontal axis) is folded out of the
// resulting image.
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
auto size = texture->GetSize();
builder.DrawImageNine(
DlImageImpeller::Make(texture),
SkIRect::MakeLTRB(size.width / 4, size.height / 4, size.width * 3 / 4,
size.height * 3 / 4),
SkRect::MakeLTRB(0, 0, size.width, size.height / 2),
flutter::DlFilterMode::kNearest, nullptr);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawNinePatchImageCenterBiggerThanDest) {
// Edge case, the width and height of the corners does not leave any
// room for the center slices. Only the corners are displayed.
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
auto size = texture->GetSize();
builder.DrawImageNine(
DlImageImpeller::Make(texture),
SkIRect::MakeLTRB(size.width / 4, size.height / 4, size.width * 3 / 4,
size.height * 3 / 4),
SkRect::MakeLTRB(0, 0, size.width / 2, size.height / 2),
flutter::DlFilterMode::kNearest, nullptr);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawNinePatchImageCornersScaledDown) {
// Edge case, there is not enough room for the corners to be drawn
// without scaling them down.
auto texture = CreateTextureForFixture("embarcadero.jpg");
flutter::DisplayListBuilder builder;
auto size = texture->GetSize();
builder.DrawImageNine(
DlImageImpeller::Make(texture),
SkIRect::MakeLTRB(size.width / 4, size.height / 4, size.width * 3 / 4,
size.height * 3 / 4),
SkRect::MakeLTRB(0, 0, size.width / 4, size.height / 4),
flutter::DlFilterMode::kNearest, nullptr);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, NinePatchImagePrecision) {
// Draw a nine patch image with colored corners and verify that the corner
// color does not leak outside the intended region.
auto texture = CreateTextureForFixture("nine_patch_corners.png");
flutter::DisplayListBuilder builder;
builder.DrawImageNine(DlImageImpeller::Make(texture),
SkIRect::MakeXYWH(10, 10, 1, 1),
SkRect::MakeXYWH(0, 0, 200, 100),
flutter::DlFilterMode::kNearest, nullptr);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawPoints) {
flutter::DisplayListBuilder builder;
SkPoint points[7] = {
{0, 0}, //
{100, 100}, //
{100, 0}, //
{0, 100}, //
{0, 0}, //
{48, 48}, //
{52, 52}, //
};
std::vector<flutter::DlStrokeCap> caps = {
flutter::DlStrokeCap::kButt,
flutter::DlStrokeCap::kRound,
flutter::DlStrokeCap::kSquare,
};
flutter::DlPaint paint =
flutter::DlPaint() //
.setColor(flutter::DlColor::kYellow().withAlpha(127)) //
.setStrokeWidth(20);
builder.Translate(50, 50);
for (auto cap : caps) {
paint.setStrokeCap(cap);
builder.Save();
builder.DrawPoints(flutter::DlCanvas::PointMode::kPoints, 7, points, paint);
builder.Translate(150, 0);
builder.DrawPoints(flutter::DlCanvas::PointMode::kLines, 5, points, paint);
builder.Translate(150, 0);
builder.DrawPoints(flutter::DlCanvas::PointMode::kPolygon, 5, points,
paint);
builder.Restore();
builder.Translate(0, 150);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawZeroLengthLine) {
flutter::DisplayListBuilder builder;
std::vector<flutter::DlStrokeCap> caps = {
flutter::DlStrokeCap::kButt,
flutter::DlStrokeCap::kRound,
flutter::DlStrokeCap::kSquare,
};
flutter::DlPaint paint =
flutter::DlPaint() //
.setColor(flutter::DlColor::kYellow().withAlpha(127)) //
.setDrawStyle(flutter::DlDrawStyle::kStroke) //
.setStrokeCap(flutter::DlStrokeCap::kButt) //
.setStrokeWidth(20);
SkPath path = SkPath().addPoly({{150, 50}, {150, 50}}, false);
for (auto cap : caps) {
paint.setStrokeCap(cap);
builder.DrawLine({50, 50}, {50, 50}, paint);
builder.DrawPath(path, paint);
builder.Translate(0, 150);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawShadow) {
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
auto content_scale = GetContentScale() * 0.8;
builder.Scale(content_scale.x, content_scale.y);
constexpr size_t star_spikes = 5;
constexpr SkScalar half_spike_rotation = kPi / star_spikes;
constexpr SkScalar radius = 40;
constexpr SkScalar spike_size = 10;
constexpr SkScalar outer_radius = radius + spike_size;
constexpr SkScalar inner_radius = radius - spike_size;
std::array<SkPoint, star_spikes * 2> star;
for (size_t i = 0; i < star_spikes; i++) {
const SkScalar rotation = half_spike_rotation * i * 2;
star[i * 2] = SkPoint::Make(50 + std::sin(rotation) * outer_radius,
50 - std::cos(rotation) * outer_radius);
star[i * 2 + 1] = SkPoint::Make(
50 + std::sin(rotation + half_spike_rotation) * inner_radius,
50 - std::cos(rotation + half_spike_rotation) * inner_radius);
}
std::array<SkPath, 4> paths = {
SkPath{}.addRect(SkRect::MakeXYWH(0, 0, 200, 100)),
SkPath{}.addRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(20, 0, 200, 100), 30, 30)),
SkPath{}.addCircle(100, 50, 50),
SkPath{}.addPoly(star.data(), star.size(), true),
};
paint.setColor(flutter::DlColor::kWhite());
builder.DrawPaint(paint);
paint.setColor(flutter::DlColor::kCyan());
builder.Translate(100, 50);
for (size_t x = 0; x < paths.size(); x++) {
builder.Save();
for (size_t y = 0; y < 6; y++) {
builder.DrawShadow(paths[x], flutter::DlColor::kBlack(), 3 + y * 8, false,
1);
builder.DrawPath(paths[x], paint);
builder.Translate(0, 150);
}
builder.Restore();
builder.Translate(250, 0);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest,
DispatcherDoesNotCullPerspectiveTransformedChildDisplayLists) {
// Regression test for https://github.com/flutter/flutter/issues/130613
flutter::DisplayListBuilder sub_builder(true);
sub_builder.DrawRect(SkRect::MakeXYWH(0, 0, 50, 50),
flutter::DlPaint(flutter::DlColor::kRed()));
auto display_list = sub_builder.Build();
DlDispatcher dispatcher(Rect::MakeLTRB(0, 0, 2400, 1800));
dispatcher.scale(2.0, 2.0);
dispatcher.translate(-93.0, 0.0);
// clang-format off
dispatcher.transformFullPerspective(
0.8, -0.2, -0.1, -0.0,
0.0, 1.0, 0.0, 0.0,
1.4, 1.3, 1.0, 0.0,
63.2, 65.3, 48.6, 1.1
);
// clang-format on
dispatcher.translate(35.0, 75.0);
dispatcher.drawDisplayList(display_list, 1.0f);
auto picture = dispatcher.EndRecordingAsPicture();
bool found = false;
picture.pass->IterateAllEntities([&found](Entity& entity) {
if (std::static_pointer_cast<SolidColorContents>(entity.GetContents())
->GetColor() == Color::Red()) {
found = true;
return false;
}
return true;
});
EXPECT_TRUE(found);
}
TEST_P(DisplayListTest, TransparentShadowProducesCorrectColor) {
DlDispatcher dispatcher;
dispatcher.save();
dispatcher.scale(1.618, 1.618);
SkPath path = SkPath{}.addRect(SkRect::MakeXYWH(0, 0, 200, 100));
flutter::DlOpReceiver::CacheablePath cache(path);
dispatcher.drawShadow(cache, flutter::DlColor::kTransparent(), 15, false, 1);
dispatcher.restore();
auto picture = dispatcher.EndRecordingAsPicture();
std::shared_ptr<SolidRRectBlurContents> rrect_blur;
picture.pass->IterateAllEntities([&rrect_blur](Entity& entity) {
if (ScalarNearlyEqual(entity.GetTransform().GetScale().x, 1.618f)) {
rrect_blur = std::static_pointer_cast<SolidRRectBlurContents>(
entity.GetContents());
return false;
}
return true;
});
ASSERT_NE(rrect_blur, nullptr);
ASSERT_EQ(rrect_blur->GetColor().red, 0);
ASSERT_EQ(rrect_blur->GetColor().green, 0);
ASSERT_EQ(rrect_blur->GetColor().blue, 0);
ASSERT_EQ(rrect_blur->GetColor().alpha, 0);
}
// Draw a hexagon using triangle fan
TEST_P(DisplayListTest, CanConvertTriangleFanToTriangles) {
constexpr Scalar hexagon_radius = 125;
auto hex_start = Point(200.0, -hexagon_radius + 200.0);
auto center_to_flat = 1.73 / 2 * hexagon_radius;
// clang-format off
std::vector<SkPoint> vertices = {
SkPoint::Make(hex_start.x, hex_start.y),
SkPoint::Make(hex_start.x + center_to_flat, hex_start.y + 0.5 * hexagon_radius),
SkPoint::Make(hex_start.x + center_to_flat, hex_start.y + 1.5 * hexagon_radius),
SkPoint::Make(hex_start.x + center_to_flat, hex_start.y + 1.5 * hexagon_radius),
SkPoint::Make(hex_start.x, hex_start.y + 2 * hexagon_radius),
SkPoint::Make(hex_start.x, hex_start.y + 2 * hexagon_radius),
SkPoint::Make(hex_start.x - center_to_flat, hex_start.y + 1.5 * hexagon_radius),
SkPoint::Make(hex_start.x - center_to_flat, hex_start.y + 1.5 * hexagon_radius),
SkPoint::Make(hex_start.x - center_to_flat, hex_start.y + 0.5 * hexagon_radius)
};
// clang-format on
auto paint = flutter::DlPaint(flutter::DlColor::kDarkGrey());
auto dl_vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangleFan, vertices.size(), vertices.data(),
nullptr, nullptr);
flutter::DisplayListBuilder builder;
builder.DrawVertices(dl_vertices, flutter::DlBlendMode::kSrcOver, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawZeroWidthLine) {
flutter::DisplayListBuilder builder;
std::vector<flutter::DlStrokeCap> caps = {
flutter::DlStrokeCap::kButt,
flutter::DlStrokeCap::kRound,
flutter::DlStrokeCap::kSquare,
};
flutter::DlPaint paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kWhite()) //
.setDrawStyle(flutter::DlDrawStyle::kStroke) //
.setStrokeWidth(0);
flutter::DlPaint outline_paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kYellow()) //
.setDrawStyle(flutter::DlDrawStyle::kStroke) //
.setStrokeCap(flutter::DlStrokeCap::kSquare) //
.setStrokeWidth(1);
SkPath path = SkPath().addPoly({{150, 50}, {160, 50}}, false);
for (auto cap : caps) {
paint.setStrokeCap(cap);
builder.DrawLine({50, 50}, {60, 50}, paint);
builder.DrawRect({45, 45, 65, 55}, outline_paint);
builder.DrawLine({100, 50}, {100, 50}, paint);
if (cap != flutter::DlStrokeCap::kButt) {
builder.DrawRect({95, 45, 105, 55}, outline_paint);
}
builder.DrawPath(path, paint);
builder.DrawRect(path.getBounds().makeOutset(5, 5), outline_paint);
builder.Translate(0, 150);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawWithMatrixFilter) {
auto boston = CreateTextureForFixture("boston.jpg");
auto callback = [&]() {
static int selected_matrix_type = 0;
const char* matrix_type_names[] = {"Matrix", "Local Matrix"};
static float ctm_translation[2] = {200, 200};
static float ctm_scale[2] = {0.65, 0.65};
static float ctm_skew[2] = {0, 0};
static bool enable = true;
static float translation[2] = {100, 100};
static float scale[2] = {0.8, 0.8};
static float skew[2] = {0.2, 0.2};
static bool enable_savelayer = true;
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
{
ImGui::Combo("Filter type", &selected_matrix_type, matrix_type_names,
sizeof(matrix_type_names) / sizeof(char*));
ImGui::TextWrapped("Current Transform");
ImGui::SliderFloat2("CTM Translation", ctm_translation, 0, 1000);
ImGui::SliderFloat2("CTM Scale", ctm_scale, 0, 3);
ImGui::SliderFloat2("CTM Skew", ctm_skew, -3, 3);
ImGui::TextWrapped(
"MatrixFilter and LocalMatrixFilter modify the CTM in the same way. "
"The only difference is that MatrixFilter doesn't affect the effect "
"transform, whereas LocalMatrixFilter does.");
// Note: See this behavior in:
// https://fiddle.skia.org/c/6cbb551ab36d06f163db8693972be954
ImGui::Checkbox("Enable", &enable);
ImGui::SliderFloat2("Filter Translation", translation, 0, 1000);
ImGui::SliderFloat2("Filter Scale", scale, 0, 3);
ImGui::SliderFloat2("Filter Skew", skew, -3, 3);
ImGui::TextWrapped(
"Rendering the filtered image within a layer can expose bounds "
"issues. If the rendered image gets cut off when this setting is "
"enabled, there's a coverage bug in the filter.");
ImGui::Checkbox("Render in layer", &enable_savelayer);
}
ImGui::End();
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
if (enable_savelayer) {
builder.SaveLayer(nullptr, nullptr);
}
{
auto content_scale = GetContentScale();
builder.Scale(content_scale.x, content_scale.y);
// Set the current transform
auto ctm_matrix =
SkMatrix::MakeAll(ctm_scale[0], ctm_skew[0], ctm_translation[0], //
ctm_skew[1], ctm_scale[1], ctm_translation[1], //
0, 0, 1);
builder.Transform(ctm_matrix);
// Set the matrix filter
auto filter_matrix =
SkMatrix::MakeAll(scale[0], skew[0], translation[0], //
skew[1], scale[1], translation[1], //
0, 0, 1);
if (enable) {
switch (selected_matrix_type) {
case 0: {
auto filter = flutter::DlMatrixImageFilter(
filter_matrix, flutter::DlImageSampling::kLinear);
paint.setImageFilter(&filter);
break;
}
case 1: {
auto internal_filter =
flutter::DlBlurImageFilter(10, 10, flutter::DlTileMode::kDecal)
.shared();
auto filter = flutter::DlLocalMatrixImageFilter(filter_matrix,
internal_filter);
paint.setImageFilter(&filter);
break;
}
}
}
builder.DrawImage(DlImageImpeller::Make(boston), {},
flutter::DlImageSampling::kLinear, &paint);
}
if (enable_savelayer) {
builder.Restore();
}
return builder.Build();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(DisplayListTest, CanDrawWithMatrixFilterWhenSavingLayer) {
auto callback = [&]() {
static float translation[2] = {0, 0};
static bool enable_save_layer = true;
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::SliderFloat2("Translation", translation, -130, 130);
ImGui::Checkbox("Enable save layer", &enable_save_layer);
ImGui::End();
flutter::DisplayListBuilder builder;
builder.Save();
builder.Scale(2.0, 2.0);
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kYellow());
builder.DrawRect(SkRect::MakeWH(300, 300), paint);
paint.setStrokeWidth(1.0);
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setColor(flutter::DlColor::kBlack().withAlpha(0x80));
builder.DrawLine(SkPoint::Make(150, 0), SkPoint::Make(150, 300), paint);
builder.DrawLine(SkPoint::Make(0, 150), SkPoint::Make(300, 150), paint);
flutter::DlPaint save_paint;
SkRect bounds = SkRect::MakeXYWH(100, 100, 100, 100);
SkMatrix translate_matrix =
SkMatrix::Translate(translation[0], translation[1]);
if (enable_save_layer) {
auto filter = flutter::DlMatrixImageFilter(
translate_matrix, flutter::DlImageSampling::kNearestNeighbor);
save_paint.setImageFilter(filter.shared());
builder.SaveLayer(&bounds, &save_paint);
} else {
builder.Save();
builder.Transform(translate_matrix);
}
SkMatrix filter_matrix = SkMatrix::I();
filter_matrix.postTranslate(-150, -150);
filter_matrix.postScale(0.2f, 0.2f);
filter_matrix.postTranslate(150, 150);
auto filter = flutter::DlMatrixImageFilter(
filter_matrix, flutter::DlImageSampling::kNearestNeighbor);
save_paint.setImageFilter(filter.shared());
builder.SaveLayer(&bounds, &save_paint);
flutter::DlPaint paint2;
paint2.setColor(flutter::DlColor::kBlue());
builder.DrawRect(bounds, paint2);
builder.Restore();
builder.Restore();
return builder.Build();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(DisplayListTest, CanDrawRectWithLinearToSrgbColorFilter) {
flutter::DlPaint paint;
paint.setColor(flutter::DlColor(0xFF2196F3).withAlpha(128));
flutter::DisplayListBuilder builder;
paint.setColorFilter(
flutter::DlLinearToSrgbGammaColorFilter::kInstance.get());
builder.DrawRect(SkRect::MakeXYWH(0, 0, 200, 200), paint);
builder.Translate(0, 200);
paint.setColorFilter(
flutter::DlSrgbToLinearGammaColorFilter::kInstance.get());
builder.DrawRect(SkRect::MakeXYWH(0, 0, 200, 200), paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawPaintWithColorSource) {
const flutter::DlColor colors[2] = {
flutter::DlColor(0xFFF44336),
flutter::DlColor(0xFF2196F3),
};
const float stops[2] = {0.0, 1.0};
flutter::DlPaint paint;
flutter::DisplayListBuilder builder;
auto clip_bounds = SkRect::MakeWH(300.0, 300.0);
builder.Save();
builder.Translate(100, 100);
builder.ClipRect(clip_bounds, flutter::DlCanvas::ClipOp::kIntersect, false);
auto linear =
flutter::DlColorSource::MakeLinear({0.0, 0.0}, {100.0, 100.0}, 2, colors,
stops, flutter::DlTileMode::kRepeat);
paint.setColorSource(linear);
builder.DrawPaint(paint);
builder.Restore();
builder.Save();
builder.Translate(500, 100);
builder.ClipRect(clip_bounds, flutter::DlCanvas::ClipOp::kIntersect, false);
auto radial = flutter::DlColorSource::MakeRadial(
{100.0, 100.0}, 100.0, 2, colors, stops, flutter::DlTileMode::kRepeat);
paint.setColorSource(radial);
builder.DrawPaint(paint);
builder.Restore();
builder.Save();
builder.Translate(100, 500);
builder.ClipRect(clip_bounds, flutter::DlCanvas::ClipOp::kIntersect, false);
auto sweep =
flutter::DlColorSource::MakeSweep({100.0, 100.0}, 180.0, 270.0, 2, colors,
stops, flutter::DlTileMode::kRepeat);
paint.setColorSource(sweep);
builder.DrawPaint(paint);
builder.Restore();
builder.Save();
builder.Translate(500, 500);
builder.ClipRect(clip_bounds, flutter::DlCanvas::ClipOp::kIntersect, false);
auto texture = CreateTextureForFixture("table_mountain_nx.png");
auto image = std::make_shared<flutter::DlImageColorSource>(
DlImageImpeller::Make(texture), flutter::DlTileMode::kRepeat,
flutter::DlTileMode::kRepeat);
paint.setColorSource(image);
builder.DrawPaint(paint);
builder.Restore();
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanBlendDstOverAndDstCorrectly) {
flutter::DisplayListBuilder builder;
{
builder.SaveLayer(nullptr, nullptr);
builder.Translate(100, 100);
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kRed());
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
paint.setColor(flutter::DlColor::kBlue().withAlpha(127));
paint.setBlendMode(flutter::DlBlendMode::kSrcOver);
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
builder.Restore();
}
{
builder.SaveLayer(nullptr, nullptr);
builder.Translate(300, 100);
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kBlue().withAlpha(127));
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
paint.setColor(flutter::DlColor::kRed());
paint.setBlendMode(flutter::DlBlendMode::kDstOver);
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
builder.Restore();
}
{
builder.SaveLayer(nullptr, nullptr);
builder.Translate(100, 300);
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kRed());
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
paint.setColor(flutter::DlColor::kBlue().withAlpha(127));
paint.setBlendMode(flutter::DlBlendMode::kSrc);
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
builder.Restore();
}
{
builder.SaveLayer(nullptr, nullptr);
builder.Translate(300, 300);
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kBlue().withAlpha(127));
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
paint.setColor(flutter::DlColor::kRed());
paint.setBlendMode(flutter::DlBlendMode::kDst);
builder.DrawRect(SkRect::MakeSize({200, 200}), paint);
builder.Restore();
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, CanDrawCorrectlyWithColorFilterAndImageFilter) {
flutter::DisplayListBuilder builder;
const float green_color_matrix[20] = {
0, 0, 0, 0, 0, //
0, 0, 0, 0, 1, //
0, 0, 0, 0, 0, //
0, 0, 0, 1, 0, //
};
const float blue_color_matrix[20] = {
0, 0, 0, 0, 0, //
0, 0, 0, 0, 0, //
0, 0, 0, 0, 1, //
0, 0, 0, 1, 0, //
};
auto green_color_filter =
std::make_shared<flutter::DlMatrixColorFilter>(green_color_matrix);
auto blue_color_filter =
std::make_shared<flutter::DlMatrixColorFilter>(blue_color_matrix);
auto blue_image_filter =
std::make_shared<flutter::DlColorFilterImageFilter>(blue_color_filter);
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kRed());
paint.setColorFilter(green_color_filter);
paint.setImageFilter(blue_image_filter);
builder.DrawRect(SkRect::MakeLTRB(100, 100, 500, 500), paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, MaskBlursApplyCorrectlyToColorSources) {
auto blur_filter = std::make_shared<flutter::DlBlurMaskFilter>(
flutter::DlBlurStyle::kNormal, 10);
flutter::DisplayListBuilder builder;
std::array<flutter::DlColor, 2> colors = {flutter::DlColor::kBlue(),
flutter::DlColor::kGreen()};
std::array<float, 2> stops = {0, 1};
std::array<std::shared_ptr<flutter::DlColorSource>, 2> color_sources = {
std::make_shared<flutter::DlColorColorSource>(flutter::DlColor::kWhite()),
flutter::DlColorSource::MakeLinear(
SkPoint::Make(0, 0), SkPoint::Make(100, 50), 2, colors.data(),
stops.data(), flutter::DlTileMode::kClamp)};
int offset = 100;
for (const auto& color_source : color_sources) {
flutter::DlPaint paint;
paint.setColorSource(color_source);
paint.setMaskFilter(blur_filter);
paint.setDrawStyle(flutter::DlDrawStyle::kFill);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(100, offset, 100, 50), 30, 30),
paint);
paint.setDrawStyle(flutter::DlDrawStyle::kStroke);
paint.setStrokeWidth(10);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(300, offset, 100, 50), 30, 30),
paint);
offset += 100;
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawVerticesSolidColorTrianglesWithoutIndices) {
// Use negative coordinates and then scale the transform by -1, -1 to make
// sure coverage is taking the transform into account.
std::vector<SkPoint> positions = {SkPoint::Make(-100, -300),
SkPoint::Make(-200, -100),
SkPoint::Make(-300, -300)};
std::vector<flutter::DlColor> colors = {flutter::DlColor::kWhite(),
flutter::DlColor::kGreen(),
flutter::DlColor::kWhite()};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, 3, positions.data(),
/*texture_coordinates=*/nullptr, colors.data());
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kRed().modulateOpacity(0.5));
builder.Scale(-1, -1);
builder.DrawVertices(vertices, flutter::DlBlendMode::kSrcOver, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawVerticesLinearGradientWithoutIndices) {
std::vector<SkPoint> positions = {SkPoint::Make(100, 300),
SkPoint::Make(200, 100),
SkPoint::Make(300, 300)};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, 3, positions.data(),
/*texture_coordinates=*/nullptr, /*colors=*/nullptr);
std::vector<flutter::DlColor> colors = {flutter::DlColor::kBlue(),
flutter::DlColor::kRed()};
const float stops[2] = {0.0, 1.0};
auto linear = flutter::DlColorSource::MakeLinear(
{100.0, 100.0}, {300.0, 300.0}, 2, colors.data(), stops,
flutter::DlTileMode::kRepeat);
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColorSource(linear);
builder.DrawVertices(vertices, flutter::DlBlendMode::kSrcOver, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawVerticesLinearGradientWithTextureCoordinates) {
std::vector<SkPoint> positions = {SkPoint::Make(100, 300),
SkPoint::Make(200, 100),
SkPoint::Make(300, 300)};
std::vector<SkPoint> texture_coordinates = {SkPoint::Make(300, 100),
SkPoint::Make(100, 200),
SkPoint::Make(300, 300)};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, 3, positions.data(),
texture_coordinates.data(), /*colors=*/nullptr);
std::vector<flutter::DlColor> colors = {flutter::DlColor::kBlue(),
flutter::DlColor::kRed()};
const float stops[2] = {0.0, 1.0};
auto linear = flutter::DlColorSource::MakeLinear(
{100.0, 100.0}, {300.0, 300.0}, 2, colors.data(), stops,
flutter::DlTileMode::kRepeat);
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColorSource(linear);
builder.DrawVertices(vertices, flutter::DlBlendMode::kSrcOver, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawVerticesImageSourceWithTextureCoordinates) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
auto dl_image = DlImageImpeller::Make(texture);
std::vector<SkPoint> positions = {SkPoint::Make(100, 300),
SkPoint::Make(200, 100),
SkPoint::Make(300, 300)};
std::vector<SkPoint> texture_coordinates = {
SkPoint::Make(0, 0), SkPoint::Make(100, 200), SkPoint::Make(200, 100)};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, 3, positions.data(),
texture_coordinates.data(), /*colors=*/nullptr);
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
auto image_source = flutter::DlImageColorSource(
dl_image, flutter::DlTileMode::kRepeat, flutter::DlTileMode::kRepeat);
paint.setColorSource(&image_source);
builder.DrawVertices(vertices, flutter::DlBlendMode::kSrcOver, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest,
DrawVerticesImageSourceWithTextureCoordinatesAndColorBlending) {
auto texture = CreateTextureForFixture("embarcadero.jpg");
auto dl_image = DlImageImpeller::Make(texture);
std::vector<SkPoint> positions = {SkPoint::Make(100, 300),
SkPoint::Make(200, 100),
SkPoint::Make(300, 300)};
std::vector<flutter::DlColor> colors = {flutter::DlColor::kWhite(),
flutter::DlColor::kGreen(),
flutter::DlColor::kWhite()};
std::vector<SkPoint> texture_coordinates = {
SkPoint::Make(0, 0), SkPoint::Make(100, 200), SkPoint::Make(200, 100)};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, 3, positions.data(),
texture_coordinates.data(), colors.data());
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
auto image_source = flutter::DlImageColorSource(
dl_image, flutter::DlTileMode::kRepeat, flutter::DlTileMode::kRepeat);
paint.setColorSource(&image_source);
builder.DrawVertices(vertices, flutter::DlBlendMode::kModulate, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawVerticesSolidColorTrianglesWithIndices) {
std::vector<SkPoint> positions = {
SkPoint::Make(100, 300), SkPoint::Make(200, 100), SkPoint::Make(300, 300),
SkPoint::Make(200, 500)};
std::vector<uint16_t> indices = {0, 1, 2, 0, 2, 3};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, positions.size(), positions.data(),
/*texture_coordinates=*/nullptr, /*colors=*/nullptr, indices.size(),
indices.data());
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColor(flutter::DlColor::kWhite());
builder.DrawVertices(vertices, flutter::DlBlendMode::kSrcOver, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawVerticesPremultipliesColors) {
std::vector<SkPoint> positions = {
SkPoint::Make(100, 300), SkPoint::Make(200, 100), SkPoint::Make(300, 300),
SkPoint::Make(200, 500)};
auto color = flutter::DlColor::kBlue().withAlpha(0x99);
std::vector<uint16_t> indices = {0, 1, 2, 0, 2, 3};
std::vector<flutter::DlColor> colors = {color, color, color, color};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, positions.size(), positions.data(),
/*texture_coordinates=*/nullptr, colors.data(), indices.size(),
indices.data());
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setBlendMode(flutter::DlBlendMode::kSrcOver);
paint.setColor(flutter::DlColor::kRed());
builder.DrawRect(SkRect::MakeLTRB(0, 0, 400, 400), paint);
builder.DrawVertices(vertices, flutter::DlBlendMode::kDst, paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawShapes) {
flutter::DisplayListBuilder builder;
std::vector<flutter::DlStrokeJoin> joins = {
flutter::DlStrokeJoin::kBevel,
flutter::DlStrokeJoin::kRound,
flutter::DlStrokeJoin::kMiter,
};
flutter::DlPaint paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kWhite()) //
.setDrawStyle(flutter::DlDrawStyle::kFill) //
.setStrokeWidth(10);
flutter::DlPaint stroke_paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kWhite()) //
.setDrawStyle(flutter::DlDrawStyle::kStroke) //
.setStrokeWidth(10);
SkPath path = SkPath().addPoly({{150, 50}, {160, 50}}, false);
builder.Translate(300, 50);
builder.Scale(0.8, 0.8);
for (auto join : joins) {
paint.setStrokeJoin(join);
stroke_paint.setStrokeJoin(join);
builder.DrawRect(SkRect::MakeXYWH(0, 0, 100, 100), paint);
builder.DrawRect(SkRect::MakeXYWH(0, 150, 100, 100), stroke_paint);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(150, 0, 100, 100), 30, 30), paint);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(150, 150, 100, 100), 30, 30),
stroke_paint);
builder.DrawCircle({350, 50}, 50, paint);
builder.DrawCircle({350, 200}, 50, stroke_paint);
builder.Translate(0, 300);
}
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, ClipDrawRRectWithNonCircularRadii) {
flutter::DisplayListBuilder builder;
flutter::DlPaint fill_paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kBlue()) //
.setDrawStyle(flutter::DlDrawStyle::kFill) //
.setStrokeWidth(10);
flutter::DlPaint stroke_paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kGreen()) //
.setDrawStyle(flutter::DlDrawStyle::kStroke) //
.setStrokeWidth(10);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(500, 100, 300, 300), 120, 40),
fill_paint);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(500, 100, 300, 300), 120, 40),
stroke_paint);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(100, 500, 300, 300), 40, 120),
fill_paint);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(100, 500, 300, 300), 40, 120),
stroke_paint);
flutter::DlPaint reference_paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kMidGrey()) //
.setDrawStyle(flutter::DlDrawStyle::kFill) //
.setStrokeWidth(10);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(500, 500, 300, 300), 40, 40),
reference_paint);
builder.DrawRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(100, 100, 300, 300), 120, 120),
reference_paint);
flutter::DlPaint clip_fill_paint = //
flutter::DlPaint() //
.setColor(flutter::DlColor::kCyan()) //
.setDrawStyle(flutter::DlDrawStyle::kFill) //
.setStrokeWidth(10);
builder.Save();
builder.ClipRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(900, 100, 300, 300), 120, 40));
builder.DrawPaint(clip_fill_paint);
builder.Restore();
builder.Save();
builder.ClipRRect(
SkRRect::MakeRectXY(SkRect::MakeXYWH(100, 900, 300, 300), 40, 120));
builder.DrawPaint(clip_fill_paint);
builder.Restore();
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
TEST_P(DisplayListTest, DrawVerticesBlendModes) {
std::vector<const char*> blend_mode_names;
std::vector<flutter::DlBlendMode> blend_mode_values;
{
const std::vector<std::tuple<const char*, flutter::DlBlendMode>> blends = {
// Pipeline blends (Porter-Duff alpha compositing)
{"Clear", flutter::DlBlendMode::kClear},
{"Source", flutter::DlBlendMode::kSrc},
{"Destination", flutter::DlBlendMode::kDst},
{"SourceOver", flutter::DlBlendMode::kSrcOver},
{"DestinationOver", flutter::DlBlendMode::kDstOver},
{"SourceIn", flutter::DlBlendMode::kSrcIn},
{"DestinationIn", flutter::DlBlendMode::kDstIn},
{"SourceOut", flutter::DlBlendMode::kSrcOut},
{"DestinationOut", flutter::DlBlendMode::kDstOut},
{"SourceATop", flutter::DlBlendMode::kSrcATop},
{"DestinationATop", flutter::DlBlendMode::kDstATop},
{"Xor", flutter::DlBlendMode::kXor},
{"Plus", flutter::DlBlendMode::kPlus},
{"Modulate", flutter::DlBlendMode::kModulate},
// Advanced blends (color component blends)
{"Screen", flutter::DlBlendMode::kScreen},
{"Overlay", flutter::DlBlendMode::kOverlay},
{"Darken", flutter::DlBlendMode::kDarken},
{"Lighten", flutter::DlBlendMode::kLighten},
{"ColorDodge", flutter::DlBlendMode::kColorDodge},
{"ColorBurn", flutter::DlBlendMode::kColorBurn},
{"HardLight", flutter::DlBlendMode::kHardLight},
{"SoftLight", flutter::DlBlendMode::kSoftLight},
{"Difference", flutter::DlBlendMode::kDifference},
{"Exclusion", flutter::DlBlendMode::kExclusion},
{"Multiply", flutter::DlBlendMode::kMultiply},
{"Hue", flutter::DlBlendMode::kHue},
{"Saturation", flutter::DlBlendMode::kSaturation},
{"Color", flutter::DlBlendMode::kColor},
{"Luminosity", flutter::DlBlendMode::kLuminosity},
};
assert(blends.size() ==
static_cast<size_t>(flutter::DlBlendMode::kLastMode) + 1);
for (const auto& [name, mode] : blends) {
blend_mode_names.push_back(name);
blend_mode_values.push_back(mode);
}
}
auto callback = [&]() {
static int current_blend_index = 3;
static float dst_alpha = 1;
static float src_alpha = 1;
static float color0[4] = {1.0f, 0.0f, 0.0f, 1.0f};
static float color1[4] = {0.0f, 1.0f, 0.0f, 1.0f};
static float color2[4] = {0.0f, 0.0f, 1.0f, 1.0f};
static float src_color[4] = {1.0f, 1.0f, 1.0f, 1.0f};
ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
{
ImGui::ListBox("Blending mode", ¤t_blend_index,
blend_mode_names.data(), blend_mode_names.size());
ImGui::SliderFloat("Source alpha", &src_alpha, 0, 1);
ImGui::ColorEdit4("Color A", color0);
ImGui::ColorEdit4("Color B", color1);
ImGui::ColorEdit4("Color C", color2);
ImGui::ColorEdit4("Source Color", src_color);
ImGui::SliderFloat("Destination alpha", &dst_alpha, 0, 1);
}
ImGui::End();
std::vector<SkPoint> positions = {SkPoint::Make(100, 300),
SkPoint::Make(200, 100),
SkPoint::Make(300, 300)};
std::vector<flutter::DlColor> colors = {
toColor(color0).modulateOpacity(dst_alpha),
toColor(color1).modulateOpacity(dst_alpha),
toColor(color2).modulateOpacity(dst_alpha)};
auto vertices = flutter::DlVertices::Make(
flutter::DlVertexMode::kTriangles, 3, positions.data(),
/*texture_coordinates=*/nullptr, colors.data());
flutter::DisplayListBuilder builder;
flutter::DlPaint paint;
paint.setColor(toColor(src_color).modulateOpacity(src_alpha));
builder.DrawVertices(vertices, blend_mode_values[current_blend_index],
paint);
return builder.Build();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
template <typename Contents>
static std::optional<Rect> GetCoverageOfFirstEntity(const Picture& picture) {
std::optional<Rect> coverage;
picture.pass->IterateAllEntities([&coverage](Entity& entity) {
if (std::static_pointer_cast<Contents>(entity.GetContents())) {
auto contents = std::static_pointer_cast<Contents>(entity.GetContents());
Entity entity;
coverage = contents->GetCoverage(entity);
return false;
}
return true;
});
return coverage;
}
TEST(DisplayListTest, RRectBoundsComputation) {
SkRRect rrect = SkRRect::MakeRectXY(SkRect::MakeLTRB(0, 0, 100, 100), 4, 4);
SkPath path = SkPath().addRRect(rrect);
flutter::DlPaint paint;
flutter::DisplayListBuilder builder;
builder.DrawPath(path, paint);
auto display_list = builder.Build();
DlDispatcher dispatcher;
display_list->Dispatch(dispatcher);
auto picture = dispatcher.EndRecordingAsPicture();
std::optional<Rect> coverage =
GetCoverageOfFirstEntity<SolidColorContents>(picture);
// Validate that the RRect coverage is _exactly_ the same as the input rect.
ASSERT_TRUE(coverage.has_value());
ASSERT_EQ(coverage.value_or(Rect::MakeMaximum()),
Rect::MakeLTRB(0, 0, 100, 100));
}
TEST(DisplayListTest, CircleBoundsComputation) {
SkPath path = SkPath().addCircle(0, 0, 5);
flutter::DlPaint paint;
flutter::DisplayListBuilder builder;
builder.DrawPath(path, paint);
auto display_list = builder.Build();
DlDispatcher dispatcher;
display_list->Dispatch(dispatcher);
auto picture = dispatcher.EndRecordingAsPicture();
std::optional<Rect> coverage =
GetCoverageOfFirstEntity<SolidColorContents>(picture);
ASSERT_TRUE(coverage.has_value());
ASSERT_EQ(coverage.value_or(Rect::MakeMaximum()),
Rect::MakeLTRB(-5, -5, 5, 5));
}
#ifdef IMPELLER_ENABLE_3D
TEST_P(DisplayListTest, SceneColorSource) {
// Load up the scene.
auto mapping =
flutter::testing::OpenFixtureAsMapping("flutter_logo_baked.glb.ipscene");
ASSERT_NE(mapping, nullptr);
std::shared_ptr<scene::Node> gltf_scene =
impeller::scene::Node::MakeFromFlatbuffer(
*mapping, *GetContext()->GetResourceAllocator());
ASSERT_NE(gltf_scene, nullptr);
flutter::DisplayListBuilder builder;
auto color_source = std::make_shared<flutter::DlSceneColorSource>(
gltf_scene,
Matrix::MakePerspective(Degrees(45), GetWindowSize(), 0.1, 1000) *
Matrix::MakeLookAt({3, 2, -5}, {0, 0, 0}, {0, 1, 0}));
flutter::DlPaint paint = flutter::DlPaint().setColorSource(color_source);
builder.DrawPaint(paint);
ASSERT_TRUE(OpenPlaygroundHere(builder.Build()));
}
#endif
} // namespace testing
} // namespace impeller
| engine/impeller/display_list/dl_unittests.cc/0 | {
"file_path": "engine/impeller/display_list/dl_unittests.cc",
"repo_id": "engine",
"token_count": 28565
} | 183 |
# Specialization Constants
A specialization constant is a named variable that is known to be constant at runtime but not when the shader is authored. These variables are bound to specific values when the shader is compiled on application start up and allow the backend to perform optimizations such as branch elimination and constant folding.
Specialization constants have two possible benefits when used in a shader:
* Improving performance, by removing branching and conditional code.
* Code organization/size, by removing the number of shader source files required.
These goals are related: The number of shaders can be reduce by adding runtime branching to create more generic shaders. Alternatively, branching can be reduced by adding more specialized shader variants. Specialization constants provide a happy medium where the source files can be combined with branching but done so in a way that has no runtime cost.
## Example Usage
Consider the case of the "decal" texture sampling mode. This is implement via clamp-to-border with
a border color set to transparent black. While this functionality is well supported on the Metal and
Vulkan backends, the GLES backend needs to support devices that do not have this extension. As a
result, the following code was used to conditionally decal:
```glsl
// Decal sample if necessary.
vec4 Sample(sampler2D sampler, vec2 coord) {
#ifdef GLES
return IPSampleDecal(sampler, coord)
#else
return texture(sampler, coord);
#endif
}
```
This works great as long as we know that the GLES backend can never do the decal sample mode. This is also "free" as the ifdef branch is evaluated in the compiler. But eventually, we added a runtime check for decal mode as we need to support this on GLES. So the code turned into (approximately) the following:
```glsl
#ifdef GLES
uniform float supports_decal;
#endif
// Decal sample if necessary.
vec4 Sample(sampler2D sampler, vec2 coord) {
#ifdef GLES
if (supports_decal) {
return texture(sampler, coord);
}
return IPSampleDecal(sampler, coord)
#else
return texture(sampler, coord);
#endif
}
```
Now we've got decal support, but we've also got new problems:
* The code is actually quite messy. We have to track different uniform values depending on the backend.
* The GLES backend is still paying some cost for branching, even though we "know" that decal is or isn't supported when the shader is compiled.
### Specialization constants to the rescue
Instead of using a runtime check, we can create a specialization constant that is set when compiling the
shader. This constant will be `1` if decal is supported and `0` otherwise.
```glsl
layout(constant_id = 0) const float supports_decal = 1.0;
vec4 Sample(sampler2D sampler, vec2 coord) {
if (supports_decal) {
return texture(sampler, coord);
}
return IPSampleDecal(sampler, coord)
}
```
Immediately we realize a number of benefits:
* Code is the same across all backends
* Runtime branching cost is removed as the branch is compiled out.
## Implementation
Const values are floats and can be used to represent:
* true/false via 0/1.
* function selection, such as advanced blends. The specialization value maps to a specific blend function. For example, 0 maps to screen and 1 to overlay via a giant if/else macro.
* Only fragment shaders can be specialized. This limitation could be removed with more investment.
*AVOID* adding specialization constants for color values or anything more complex.
Specialization constants are provided to the CreateDefault argument in content_context.cc and aren't a
part of variants. This is intentional: specialization constants shouldn't be used to create (potentially unlimited) runtime variants of a shader.
Backend specific information:
* In the Metal backend, the specialization constants are mapped to a MTLFunctionConstantValues. See also: https://developer.apple.com/documentation/metal/using_function_specialization_to_build_pipeline_variants?language=objc
* In the Vulkan backend, the specialization constants are mapped to VkSpecializationINfo. See also: https://blogs.igalia.com/itoral/2018/03/20/improving-shader-performance-with-vulkans-specialization-constants/
* In the GLES backend, the SPIRV Cross compiler will generate defines named `#ifdef SPIRV_CROSS_CONSTANT_i`, where i is the index of constant. The Impeller runtime will insert `#define SPIRV_CROSS_CONSTANT_i` in the header of the shader. | engine/impeller/docs/specialization_constants.md/0 | {
"file_path": "engine/impeller/docs/specialization_constants.md",
"repo_id": "engine",
"token_count": 1129
} | 184 |
// Copyright 2013 The Flutter 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 "conical_gradient_contents.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/gradient_generator.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/geometry/geometry.h"
#include "impeller/geometry/gradient.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
ConicalGradientContents::ConicalGradientContents() = default;
ConicalGradientContents::~ConicalGradientContents() = default;
void ConicalGradientContents::SetCenterAndRadius(Point center, Scalar radius) {
center_ = center;
radius_ = radius;
}
void ConicalGradientContents::SetTileMode(Entity::TileMode tile_mode) {
tile_mode_ = tile_mode;
}
void ConicalGradientContents::SetColors(std::vector<Color> colors) {
colors_ = std::move(colors);
}
void ConicalGradientContents::SetStops(std::vector<Scalar> stops) {
stops_ = std::move(stops);
}
const std::vector<Color>& ConicalGradientContents::GetColors() const {
return colors_;
}
const std::vector<Scalar>& ConicalGradientContents::GetStops() const {
return stops_;
}
void ConicalGradientContents::SetFocus(std::optional<Point> focus,
Scalar radius) {
focus_ = focus;
focus_radius_ = radius;
}
bool ConicalGradientContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (renderer.GetDeviceCapabilities().SupportsSSBO()) {
return RenderSSBO(renderer, entity, pass);
}
return RenderTexture(renderer, entity, pass);
}
bool ConicalGradientContents::RenderSSBO(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = ConicalGradientSSBOFillPipeline::VertexShader;
using FS = ConicalGradientSSBOFillPipeline::FragmentShader;
VS::FrameInfo frame_info;
frame_info.matrix = GetInverseEffectTransform();
PipelineBuilderCallback pipeline_callback =
[&renderer](ContentContextOptions options) {
return renderer.GetConicalGradientSSBOFillPipeline(options);
};
return ColorSourceContents::DrawGeometry<VS>(
renderer, entity, pass, pipeline_callback, frame_info,
[this, &renderer](RenderPass& pass) {
FS::FragInfo frag_info;
frag_info.center = center_;
frag_info.radius = radius_;
frag_info.tile_mode = static_cast<Scalar>(tile_mode_);
frag_info.decal_border_color = decal_border_color_;
frag_info.alpha = GetOpacityFactor();
if (focus_) {
frag_info.focus = focus_.value();
frag_info.focus_radius = focus_radius_;
} else {
frag_info.focus = center_;
frag_info.focus_radius = 0.0;
}
auto& host_buffer = renderer.GetTransientsBuffer();
auto colors = CreateGradientColors(colors_, stops_);
frag_info.colors_length = colors.size();
auto color_buffer =
host_buffer.Emplace(colors.data(), colors.size() * sizeof(StopData),
DefaultUniformAlignment());
FS::BindFragInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info));
FS::BindColorData(pass, color_buffer);
pass.SetCommandLabel("ConicalGradientSSBOFill");
return true;
});
}
bool ConicalGradientContents::RenderTexture(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = ConicalGradientFillPipeline::VertexShader;
using FS = ConicalGradientFillPipeline::FragmentShader;
auto gradient_data = CreateGradientBuffer(colors_, stops_);
auto gradient_texture =
CreateGradientTexture(gradient_data, renderer.GetContext());
if (gradient_texture == nullptr) {
return false;
}
auto geometry_result =
GetGeometry()->GetPositionBuffer(renderer, entity, pass);
VS::FrameInfo frame_info;
frame_info.matrix = GetInverseEffectTransform();
PipelineBuilderCallback pipeline_callback =
[&renderer](ContentContextOptions options) {
return renderer.GetConicalGradientFillPipeline(options);
};
return ColorSourceContents::DrawGeometry<VS>(
renderer, entity, pass, pipeline_callback, frame_info,
[this, &renderer, &gradient_texture](RenderPass& pass) {
FS::FragInfo frag_info;
frag_info.center = center_;
frag_info.radius = radius_;
frag_info.tile_mode = static_cast<Scalar>(tile_mode_);
frag_info.decal_border_color = decal_border_color_;
frag_info.texture_sampler_y_coord_scale =
gradient_texture->GetYCoordScale();
frag_info.alpha = GetOpacityFactor();
frag_info.half_texel =
Vector2(0.5 / gradient_texture->GetSize().width,
0.5 / gradient_texture->GetSize().height);
if (focus_) {
frag_info.focus = focus_.value();
frag_info.focus_radius = focus_radius_;
} else {
frag_info.focus = center_;
frag_info.focus_radius = 0.0;
}
pass.SetCommandLabel("ConicalGradientFill");
FS::BindFragInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info));
SamplerDescriptor sampler_desc;
sampler_desc.min_filter = MinMagFilter::kLinear;
sampler_desc.mag_filter = MinMagFilter::kLinear;
FS::BindTextureSampler(
pass, gradient_texture,
renderer.GetContext()->GetSamplerLibrary()->GetSampler(
sampler_desc));
return true;
});
}
bool ConicalGradientContents::ApplyColorFilter(
const ColorFilterProc& color_filter_proc) {
for (Color& color : colors_) {
color = color_filter_proc(color);
}
decal_border_color_ = color_filter_proc(decal_border_color_);
return true;
}
} // namespace impeller
| engine/impeller/entity/contents/conical_gradient_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/conical_gradient_contents.cc",
"repo_id": "engine",
"token_count": 2560
} | 185 |
// Copyright 2013 The Flutter 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_FILTER_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_FILTER_CONTENTS_H_
#include <memory>
#include <optional>
#include <variant>
#include <vector>
#include "impeller/core/formats.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/geometry/geometry.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/sigma.h"
namespace impeller {
class FilterContents : public Contents {
public:
static const int32_t kBlurFilterRequiredMipCount;
enum class BlurStyle {
/// Blurred inside and outside.
kNormal,
/// Solid inside, blurred outside.
kSolid,
/// Nothing inside, blurred outside.
kOuter,
/// Blurred inside, nothing outside.
kInner,
};
enum class MorphType { kDilate, kErode };
/// Creates a gaussian blur that operates in 2 dimensions.
/// See also: `MakeDirectionalGaussianBlur`
static std::shared_ptr<FilterContents> MakeGaussianBlur(
const FilterInput::Ref& input,
Sigma sigma_x,
Sigma sigma_y,
Entity::TileMode tile_mode = Entity::TileMode::kDecal,
BlurStyle mask_blur_style = BlurStyle::kNormal,
const std::shared_ptr<Geometry>& mask_geometry = nullptr);
static std::shared_ptr<FilterContents> MakeBorderMaskBlur(
FilterInput::Ref input,
Sigma sigma_x,
Sigma sigma_y,
BlurStyle blur_style = BlurStyle::kNormal);
static std::shared_ptr<FilterContents> MakeDirectionalMorphology(
FilterInput::Ref input,
Radius radius,
Vector2 direction,
MorphType morph_type);
static std::shared_ptr<FilterContents> MakeMorphology(FilterInput::Ref input,
Radius radius_x,
Radius radius_y,
MorphType morph_type);
static std::shared_ptr<FilterContents> MakeMatrixFilter(
FilterInput::Ref input,
const Matrix& matrix,
const SamplerDescriptor& desc);
static std::shared_ptr<FilterContents> MakeLocalMatrixFilter(
FilterInput::Ref input,
const Matrix& matrix);
static std::shared_ptr<FilterContents> MakeYUVToRGBFilter(
std::shared_ptr<Texture> y_texture,
std::shared_ptr<Texture> uv_texture,
YUVColorSpace yuv_color_space);
FilterContents();
~FilterContents() override;
/// @brief The input texture sources for this filter. Each input's emitted
/// texture is expected to have premultiplied alpha colors.
///
/// The number of required or optional textures depends on the
/// particular filter's implementation.
void SetInputs(FilterInput::Vector inputs);
/// @brief Sets the transform which gets appended to the effect of this
/// filter. Note that this is in addition to the entity's transform.
///
/// This is useful for subpass rendering scenarios where it's
/// difficult to encode the current transform of the layer into the
/// Entity being rendered.
void SetEffectTransform(const Matrix& effect_transform);
/// @brief Create an Entity that renders this filter's output.
std::optional<Entity> GetEntity(
const ContentContext& renderer,
const Entity& entity,
const std::optional<Rect>& coverage_hint) const;
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Contents|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |Contents|
void PopulateGlyphAtlas(
const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas,
Scalar scale) override;
// |Contents|
std::optional<Snapshot> RenderToSnapshot(
const ContentContext& renderer,
const Entity& entity,
std::optional<Rect> coverage_limit = std::nullopt,
const std::optional<SamplerDescriptor>& sampler_descriptor = std::nullopt,
bool msaa_enabled = true,
int32_t mip_count = 1,
const std::string& label = "Filter Snapshot") const override;
// |Contents|
const FilterContents* AsFilter() const override;
/// @brief Determines the coverage of source pixels that will be needed
/// to produce results for the specified |output_limit| under the
/// specified |effect_transform|. This is essentially a reverse of
/// the |GetCoverage| method computing a source coverage from
/// an intended |output_limit| coverage.
///
/// Both the |output_limit| and the return value are in the
/// transformed coordinate space, and so do not need to be
/// transformed or inverse transformed by the |effect_transform|
/// but individual parameters on the filter might be in the
/// untransformed space and should be transformed by the
/// |effect_transform| before applying them to the coverages.
///
/// The method computes a result such that if the filter is applied
/// to a set of pixels filling the computed source coverage, it
/// should produce an output that covers the entire specified
/// |output_limit|.
///
/// This is useful for subpass rendering scenarios where a filter
/// will be applied to the output of the subpass and we need to
/// determine how large of a render target to allocate in order
/// to collect all pixels that might affect the supplied output
/// coverage limit. While we might end up clipping the rendering
/// of the subpass to its destination, we want to avoid clipping
/// out any pixels that contribute to the output limit via the
/// filtering operation.
///
/// @return The coverage bounds in the transformed space of any source pixel
/// that may be needed to produce output for the indicated filter
/// that covers the indicated |output_limit|.
std::optional<Rect> GetSourceCoverage(const Matrix& effect_transform,
const Rect& output_limit) const;
virtual Matrix GetLocalTransform(const Matrix& parent_transform) const;
Matrix GetTransform(const Matrix& parent_transform) const;
/// @brief Returns true if this filter graph doesn't perform any basis
/// transforms to the filtered content. For example: Rotating,
/// scaling, and skewing are all basis transforms, but
/// translating is not.
///
/// This is useful for determining whether a filtered object's space
/// is compatible enough with the parent pass space to perform certain
/// subpass clipping optimizations.
virtual bool IsTranslationOnly() const;
/// @brief Returns `true` if this filter does not have any `FilterInput`
/// children.
bool IsLeaf() const;
/// @brief Replaces the set of all leaf `FilterContents` with a new set
/// of `FilterInput`s.
/// @see `FilterContents::IsLeaf`
void SetLeafInputs(const FilterInput::Vector& inputs);
/// @brief Marks this filter chain as applying in a subpass scenario.
///
/// Subpasses render in screenspace, and this setting informs filters
/// that the current transform matrix of the entity is not stored
/// in the Entity transform matrix. Instead, the effect transform
/// is used in this case.
virtual void SetRenderingMode(Entity::RenderingMode rendering_mode);
private:
/// @brief Internal utility method for |GetLocalCoverage| that computes
/// the output coverage of this filter across the specified inputs,
/// ignoring the coverage hint.
virtual std::optional<Rect> GetFilterCoverage(
const FilterInput::Vector& inputs,
const Entity& entity,
const Matrix& effect_transform) const;
/// @brief Internal utility method for |GetSourceCoverage| that computes
/// the inverse effect of this transform on the specified output
/// coverage, ignoring the inputs which will be accommodated by
/// the caller.
virtual std::optional<Rect> GetFilterSourceCoverage(
const Matrix& effect_transform,
const Rect& output_limit) const = 0;
/// @brief Converts zero or more filter inputs into a render instruction.
virtual std::optional<Entity> 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 = 0;
/// @brief Internal utility method to compute the coverage of this
/// filter across its internally specified inputs and subject
/// to the coverage hint.
///
/// Uses |GetFilterCoverage|.
std::optional<Rect> GetLocalCoverage(const Entity& local_entity) const;
FilterInput::Vector inputs_;
Matrix effect_transform_ = Matrix();
FilterContents(const FilterContents&) = delete;
FilterContents& operator=(const FilterContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_FILTER_CONTENTS_H_
| engine/impeller/entity/contents/filters/filter_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/filters/filter_contents.h",
"repo_id": "engine",
"token_count": 3259
} | 186 |
// Copyright 2013 The Flutter 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_LINEAR_TO_SRGB_FILTER_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LINEAR_TO_SRGB_FILTER_CONTENTS_H_
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
namespace impeller {
class LinearToSrgbFilterContents final : public ColorFilterContents {
public:
LinearToSrgbFilterContents();
~LinearToSrgbFilterContents() override;
private:
// |FilterContents|
std::optional<Entity> RenderFilter(
const FilterInput::Vector& input_textures,
const ContentContext& renderer,
const Entity& entity,
const Matrix& effect_transform,
const Rect& coverage,
const std::optional<Rect>& coverage_hint) const override;
LinearToSrgbFilterContents(const LinearToSrgbFilterContents&) = delete;
LinearToSrgbFilterContents& operator=(const LinearToSrgbFilterContents&) =
delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LINEAR_TO_SRGB_FILTER_CONTENTS_H_
| engine/impeller/entity/contents/filters/linear_to_srgb_filter_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/filters/linear_to_srgb_filter_contents.h",
"repo_id": "engine",
"token_count": 435
} | 187 |
// Copyright 2013 The Flutter 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 "linear_gradient_contents.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/gradient_generator.h"
#include "impeller/entity/entity.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
LinearGradientContents::LinearGradientContents() = default;
LinearGradientContents::~LinearGradientContents() = default;
void LinearGradientContents::SetEndPoints(Point start_point, Point end_point) {
start_point_ = start_point;
end_point_ = end_point;
}
void LinearGradientContents::SetColors(std::vector<Color> colors) {
colors_ = std::move(colors);
}
void LinearGradientContents::SetStops(std::vector<Scalar> stops) {
stops_ = std::move(stops);
}
const std::vector<Color>& LinearGradientContents::GetColors() const {
return colors_;
}
const std::vector<Scalar>& LinearGradientContents::GetStops() const {
return stops_;
}
void LinearGradientContents::SetTileMode(Entity::TileMode tile_mode) {
tile_mode_ = tile_mode;
}
bool LinearGradientContents::IsOpaque() const {
if (GetOpacityFactor() < 1 || tile_mode_ == Entity::TileMode::kDecal) {
return false;
}
for (auto color : colors_) {
if (!color.IsOpaque()) {
return false;
}
}
return true;
}
bool LinearGradientContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (renderer.GetDeviceCapabilities().SupportsSSBO()) {
return RenderSSBO(renderer, entity, pass);
}
return RenderTexture(renderer, entity, pass);
}
bool LinearGradientContents::RenderTexture(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = LinearGradientFillPipeline::VertexShader;
using FS = LinearGradientFillPipeline::FragmentShader;
VS::FrameInfo frame_info;
frame_info.matrix = GetInverseEffectTransform();
PipelineBuilderCallback pipeline_callback =
[&renderer](ContentContextOptions options) {
return renderer.GetLinearGradientFillPipeline(options);
};
return ColorSourceContents::DrawGeometry<VS>(
renderer, entity, pass, pipeline_callback, frame_info,
[this, &renderer](RenderPass& pass) {
auto gradient_data = CreateGradientBuffer(colors_, stops_);
auto gradient_texture =
CreateGradientTexture(gradient_data, renderer.GetContext());
if (gradient_texture == nullptr) {
return false;
}
FS::FragInfo frag_info;
frag_info.start_point = start_point_;
frag_info.end_point = end_point_;
frag_info.tile_mode = static_cast<Scalar>(tile_mode_);
frag_info.decal_border_color = decal_border_color_;
frag_info.texture_sampler_y_coord_scale =
gradient_texture->GetYCoordScale();
frag_info.alpha = GetOpacityFactor();
frag_info.half_texel =
Vector2(0.5 / gradient_texture->GetSize().width,
0.5 / gradient_texture->GetSize().height);
pass.SetCommandLabel("LinearGradientFill");
SamplerDescriptor sampler_desc;
sampler_desc.min_filter = MinMagFilter::kLinear;
sampler_desc.mag_filter = MinMagFilter::kLinear;
FS::BindTextureSampler(
pass, std::move(gradient_texture),
renderer.GetContext()->GetSamplerLibrary()->GetSampler(
sampler_desc));
FS::BindFragInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info));
return true;
});
}
bool LinearGradientContents::RenderSSBO(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = LinearGradientSSBOFillPipeline::VertexShader;
using FS = LinearGradientSSBOFillPipeline::FragmentShader;
VS::FrameInfo frame_info;
frame_info.matrix = GetInverseEffectTransform();
PipelineBuilderCallback pipeline_callback =
[&renderer](ContentContextOptions options) {
return renderer.GetLinearGradientSSBOFillPipeline(options);
};
return ColorSourceContents::DrawGeometry<VS>(
renderer, entity, pass, pipeline_callback, frame_info,
[this, &renderer](RenderPass& pass) {
FS::FragInfo frag_info;
frag_info.start_point = start_point_;
frag_info.end_point = end_point_;
frag_info.tile_mode = static_cast<Scalar>(tile_mode_);
frag_info.decal_border_color = decal_border_color_;
frag_info.alpha = GetOpacityFactor();
auto& host_buffer = renderer.GetTransientsBuffer();
auto colors = CreateGradientColors(colors_, stops_);
frag_info.colors_length = colors.size();
auto color_buffer =
host_buffer.Emplace(colors.data(), colors.size() * sizeof(StopData),
DefaultUniformAlignment());
pass.SetCommandLabel("LinearGradientSSBOFill");
FS::BindFragInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info));
FS::BindColorData(pass, color_buffer);
return true;
});
}
bool LinearGradientContents::ApplyColorFilter(
const ColorFilterProc& color_filter_proc) {
for (Color& color : colors_) {
color = color_filter_proc(color);
}
decal_border_color_ = color_filter_proc(decal_border_color_);
return true;
}
} // namespace impeller
| engine/impeller/entity/contents/linear_gradient_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/linear_gradient_contents.cc",
"repo_id": "engine",
"token_count": 2315
} | 188 |
// Copyright 2013 The Flutter 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/test/recording_render_pass.h"
#include <utility>
namespace impeller {
RecordingRenderPass::RecordingRenderPass(
std::shared_ptr<RenderPass> delegate,
const std::shared_ptr<const Context>& context,
const RenderTarget& render_target)
: RenderPass(context, render_target), delegate_(std::move(delegate)) {}
// |RenderPass|
void RecordingRenderPass::SetPipeline(
const std::shared_ptr<Pipeline<PipelineDescriptor>>& pipeline) {
pending_.pipeline = pipeline;
if (delegate_) {
delegate_->SetPipeline(pipeline);
}
}
void RecordingRenderPass::SetCommandLabel(std::string_view label) {
#ifdef IMPELLER_DEBUG
pending_.label = std::string(label);
#endif // IMPELLER_DEBUG
if (delegate_) {
delegate_->SetCommandLabel(label);
}
}
// |RenderPass|
void RecordingRenderPass::SetStencilReference(uint32_t value) {
pending_.stencil_reference = value;
if (delegate_) {
delegate_->SetStencilReference(value);
}
}
// |RenderPass|
void RecordingRenderPass::SetBaseVertex(uint64_t value) {
pending_.base_vertex = value;
if (delegate_) {
delegate_->SetBaseVertex(value);
}
}
// |RenderPass|
void RecordingRenderPass::SetViewport(Viewport viewport) {
pending_.viewport = viewport;
if (delegate_) {
delegate_->SetViewport(viewport);
}
}
// |RenderPass|
void RecordingRenderPass::SetScissor(IRect scissor) {
pending_.scissor = scissor;
if (delegate_) {
delegate_->SetScissor(scissor);
}
}
// |RenderPass|
void RecordingRenderPass::SetInstanceCount(size_t count) {
pending_.instance_count = count;
if (delegate_) {
delegate_->SetInstanceCount(count);
}
}
// |RenderPass|
bool RecordingRenderPass::SetVertexBuffer(VertexBuffer buffer) {
pending_.vertex_buffer = buffer;
if (delegate_) {
return delegate_->SetVertexBuffer(buffer);
}
return true;
}
// |RenderPass|
fml::Status RecordingRenderPass::Draw() {
commands_.emplace_back(std::move(pending_));
pending_ = {};
if (delegate_) {
return delegate_->Draw();
}
return fml::Status();
}
// |RenderPass|
void RecordingRenderPass::OnSetLabel(std::string label) {
return;
}
// |RenderPass|
bool RecordingRenderPass::OnEncodeCommands(const Context& context) const {
if (delegate_) {
return delegate_->EncodeCommands();
}
return true;
}
// |RenderPass|
bool RecordingRenderPass::BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) {
pending_.BindResource(stage, type, slot, metadata, view);
if (delegate_) {
return delegate_->BindResource(stage, type, slot, metadata, view);
}
return true;
}
// |RenderPass|
bool RecordingRenderPass::BindResource(
ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const std::shared_ptr<const ShaderMetadata>& metadata,
BufferView view) {
pending_.BindResource(stage, type, slot, metadata, view);
if (delegate_) {
return delegate_->BindResource(stage, type, slot, metadata, view);
}
return true;
}
// |RenderPass|
bool RecordingRenderPass::BindResource(
ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) {
pending_.BindResource(stage, type, slot, metadata, texture, sampler);
if (delegate_) {
return delegate_->BindResource(stage, type, slot, metadata, texture,
sampler);
}
return true;
}
} // namespace impeller
| engine/impeller/entity/contents/test/recording_render_pass.cc/0 | {
"file_path": "engine/impeller/entity/contents/test/recording_render_pass.cc",
"repo_id": "engine",
"token_count": 1466
} | 189 |
// Copyright 2013 The Flutter 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/entity_pass_delegate.h"
#include "impeller/entity/entity_pass.h"
namespace impeller {
EntityPassDelegate::EntityPassDelegate() = default;
EntityPassDelegate::~EntityPassDelegate() = default;
class DefaultEntityPassDelegate final : public EntityPassDelegate {
public:
DefaultEntityPassDelegate() = default;
// |EntityPassDelegate|
~DefaultEntityPassDelegate() override = default;
// |EntityPassDelegate|
bool CanElide() override { return false; }
// |EntityPassDelegate|
bool CanCollapseIntoParentPass(EntityPass* entity_pass) override {
return true;
}
// |EntityPassDelegate|
std::shared_ptr<Contents> CreateContentsForSubpassTarget(
std::shared_ptr<Texture> target,
const Matrix& effect_transform) override {
// Not possible since this pass always collapses into its parent.
FML_UNREACHABLE();
}
// |EntityPassDelgate|
std::shared_ptr<FilterContents> WithImageFilter(
const FilterInput::Variant& input,
const Matrix& effect_transform) const override {
return nullptr;
}
private:
DefaultEntityPassDelegate(const DefaultEntityPassDelegate&) = delete;
DefaultEntityPassDelegate& operator=(const DefaultEntityPassDelegate&) =
delete;
};
std::unique_ptr<EntityPassDelegate> EntityPassDelegate::MakeDefault() {
return std::make_unique<DefaultEntityPassDelegate>();
}
} // namespace impeller
| engine/impeller/entity/entity_pass_delegate.cc/0 | {
"file_path": "engine/impeller/entity/entity_pass_delegate.cc",
"repo_id": "engine",
"token_count": 480
} | 190 |
// Copyright 2013 The Flutter 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/geometry/geometry.h"
#include <memory>
#include <optional>
#include "fml/status.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/geometry/circle_geometry.h"
#include "impeller/entity/geometry/cover_geometry.h"
#include "impeller/entity/geometry/ellipse_geometry.h"
#include "impeller/entity/geometry/fill_path_geometry.h"
#include "impeller/entity/geometry/line_geometry.h"
#include "impeller/entity/geometry/point_field_geometry.h"
#include "impeller/entity/geometry/rect_geometry.h"
#include "impeller/entity/geometry/round_rect_geometry.h"
#include "impeller/entity/geometry/stroke_path_geometry.h"
#include "impeller/geometry/rect.h"
namespace impeller {
GeometryResult Geometry::ComputePositionGeometry(
const ContentContext& renderer,
const Tessellator::VertexGenerator& generator,
const Entity& entity,
RenderPass& pass) {
using VT = SolidFillVertexShader::PerVertexData;
size_t count = generator.GetVertexCount();
return GeometryResult{
.type = generator.GetTriangleType(),
.vertex_buffer =
{
.vertex_buffer = renderer.GetTransientsBuffer().Emplace(
count * sizeof(VT), alignof(VT),
[&generator](uint8_t* buffer) {
auto vertices = reinterpret_cast<VT*>(buffer);
generator.GenerateVertices([&vertices](const Point& p) {
*vertices++ = {
.position = p,
};
});
FML_DCHECK(vertices == reinterpret_cast<VT*>(buffer) +
generator.GetVertexCount());
}),
.vertex_count = count,
.index_type = IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
GeometryResult Geometry::ComputePositionUVGeometry(
const ContentContext& renderer,
const Tessellator::VertexGenerator& generator,
const Matrix& uv_transform,
const Entity& entity,
RenderPass& pass) {
using VT = TextureFillVertexShader::PerVertexData;
size_t count = generator.GetVertexCount();
return GeometryResult{
.type = generator.GetTriangleType(),
.vertex_buffer =
{
.vertex_buffer = renderer.GetTransientsBuffer().Emplace(
count * sizeof(VT), alignof(VT),
[&generator, &uv_transform](uint8_t* buffer) {
auto vertices = reinterpret_cast<VT*>(buffer);
generator.GenerateVertices(
[&vertices, &uv_transform](const Point& p) { //
*vertices++ = {
.position = p,
.texture_coords = uv_transform * p,
};
});
FML_DCHECK(vertices == reinterpret_cast<VT*>(buffer) +
generator.GetVertexCount());
}),
.vertex_count = count,
.index_type = IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
VertexBufferBuilder<TextureFillVertexShader::PerVertexData>
ComputeUVGeometryCPU(
VertexBufferBuilder<SolidFillVertexShader::PerVertexData>& input,
Point texture_origin,
Size texture_coverage,
Matrix effect_transform) {
VertexBufferBuilder<TextureFillVertexShader::PerVertexData> vertex_builder;
vertex_builder.Reserve(input.GetVertexCount());
input.IterateVertices(
[&vertex_builder, &texture_coverage, &effect_transform,
&texture_origin](SolidFillVertexShader::PerVertexData old_vtx) {
TextureFillVertexShader::PerVertexData data;
data.position = old_vtx.position;
data.texture_coords = effect_transform *
(old_vtx.position - texture_origin) /
texture_coverage;
vertex_builder.AppendVertex(data);
});
return vertex_builder;
}
GeometryResult ComputeUVGeometryForRect(Rect source_rect,
Rect texture_bounds,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) {
auto& host_buffer = renderer.GetTransientsBuffer();
// Calculate UV-specific transform based on texture coverage and effect.
// For example, if the texture is 100x100 and the effect transform is
// scaling by 2.0, texture_bounds.GetNormalizingTransform() will result in a
// Matrix that scales by 0.01, and then if the effect_transform is
// Matrix::MakeScale(Vector2{2, 2}), the resulting uv_transform will have x
// and y basis vectors with scale 0.02.
auto uv_transform = texture_bounds.GetNormalizingTransform() * //
effect_transform;
// Allocate space for vertex and UV data (4 vertices)
// 0: position
// 1: UV
// 2: position
// 3: UV
// etc.
Point data[8];
// Get the raw points from the rect and transform them into UV space.
auto points = source_rect.GetPoints();
for (auto i = 0u, j = 0u; i < 8; i += 2, j++) {
// Store original coordinates.
data[i] = points[j];
// Store transformed UV coordinates.
data[i + 1] = uv_transform * points[j];
}
return GeometryResult{
.type = PrimitiveType::kTriangleStrip,
.vertex_buffer =
{
.vertex_buffer = host_buffer.Emplace(
/*buffer=*/data,
/*length=*/16 * sizeof(float),
/*align=*/alignof(float)),
.vertex_count = 4,
.index_type = IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
GeometryResult Geometry::GetPositionUVBuffer(Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
return {};
}
GeometryResult::Mode Geometry::GetResultMode() const {
return GeometryResult::Mode::kNormal;
}
std::shared_ptr<Geometry> Geometry::MakeFillPath(
const Path& path,
std::optional<Rect> inner_rect) {
return std::make_shared<FillPathGeometry>(path, inner_rect);
}
std::shared_ptr<Geometry> Geometry::MakePointField(std::vector<Point> points,
Scalar radius,
bool round) {
return std::make_shared<PointFieldGeometry>(std::move(points), radius, round);
}
std::shared_ptr<Geometry> Geometry::MakeStrokePath(const Path& path,
Scalar stroke_width,
Scalar miter_limit,
Cap stroke_cap,
Join stroke_join) {
// Skia behaves like this.
if (miter_limit < 0) {
miter_limit = 4.0;
}
return std::make_shared<StrokePathGeometry>(path, stroke_width, miter_limit,
stroke_cap, stroke_join);
}
std::shared_ptr<Geometry> Geometry::MakeCover() {
return std::make_shared<CoverGeometry>();
}
std::shared_ptr<Geometry> Geometry::MakeRect(const Rect& rect) {
return std::make_shared<RectGeometry>(rect);
}
std::shared_ptr<Geometry> Geometry::MakeOval(const Rect& rect) {
return std::make_shared<EllipseGeometry>(rect);
}
std::shared_ptr<Geometry> Geometry::MakeLine(const Point& p0,
const Point& p1,
Scalar width,
Cap cap) {
return std::make_shared<LineGeometry>(p0, p1, width, cap);
}
std::shared_ptr<Geometry> Geometry::MakeCircle(const Point& center,
Scalar radius) {
return std::make_shared<CircleGeometry>(center, radius);
}
std::shared_ptr<Geometry> Geometry::MakeStrokedCircle(const Point& center,
Scalar radius,
Scalar stroke_width) {
return std::make_shared<CircleGeometry>(center, radius, stroke_width);
}
std::shared_ptr<Geometry> Geometry::MakeRoundRect(const Rect& rect,
const Size& radii) {
return std::make_shared<RoundRectGeometry>(rect, radii);
}
bool Geometry::CoversArea(const Matrix& transform, const Rect& rect) const {
return false;
}
bool Geometry::IsAxisAlignedRect() const {
return false;
}
} // namespace impeller
| engine/impeller/entity/geometry/geometry.cc/0 | {
"file_path": "engine/impeller/entity/geometry/geometry.cc",
"repo_id": "engine",
"token_count": 4399
} | 191 |
// Copyright 2013 The Flutter 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_INLINE_PASS_CONTEXT_H_
#define FLUTTER_IMPELLER_ENTITY_INLINE_PASS_CONTEXT_H_
#include <cstdint>
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/entity_pass_target.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
class InlinePassContext {
public:
struct RenderPassResult {
bool just_created = false;
std::shared_ptr<RenderPass> pass;
std::shared_ptr<Texture> backdrop_texture;
};
InlinePassContext(
const ContentContext& renderer,
EntityPassTarget& pass_target,
uint32_t pass_texture_reads,
uint32_t entity_count,
std::optional<RenderPassResult> collapsed_parent_pass = std::nullopt);
~InlinePassContext();
bool IsValid() const;
bool IsActive() const;
std::shared_ptr<Texture> GetTexture();
bool EndPass();
EntityPassTarget& GetPassTarget() const;
uint32_t GetPassCount() const;
RenderPassResult GetRenderPass(uint32_t pass_depth);
private:
const ContentContext& renderer_;
EntityPassTarget& pass_target_;
std::shared_ptr<CommandBuffer> command_buffer_;
std::shared_ptr<RenderPass> pass_;
uint32_t pass_count_ = 0;
uint32_t entity_count_ = 0;
// Whether this context is collapsed into a parent entity pass.
bool is_collapsed_ = false;
InlinePassContext(const InlinePassContext&) = delete;
InlinePassContext& operator=(const InlinePassContext&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_INLINE_PASS_CONTEXT_H_
| engine/impeller/entity/inline_pass_context.h/0 | {
"file_path": "engine/impeller/entity/inline_pass_context.h",
"repo_id": "engine",
"token_count": 595
} | 192 |
# The Impeller Fixtures Set
Unlike other targets in the buildroot, all Impeller unit-tests use the same
fixture set and are invoked using a single test harness (`impeller_unittest`).
This is for convenience but also to make working with shader libraries easier.
| engine/impeller/fixtures/README.md/0 | {
"file_path": "engine/impeller/fixtures/README.md",
"repo_id": "engine",
"token_count": 67
} | 193 |
layout(local_size_x = 128) in;
layout(std430) buffer;
layout(binding = 0) writeonly buffer Output {
uint count;
uint elements[];
}
output_data;
layout(binding = 1) readonly buffer Input {
uint count;
uint elements[];
}
input_data;
void main() {
uint ident = gl_GlobalInvocationID.x;
if (ident >= input_data.count) {
return;
}
uint out_slot = ident * 2;
output_data.count = input_data.count * 2;
output_data.elements[out_slot] = input_data.elements[ident] * 2;
output_data.elements[out_slot + 1] = input_data.elements[ident] * 3;
}
| engine/impeller/fixtures/stage1.comp/0 | {
"file_path": "engine/impeller/fixtures/stage1.comp",
"repo_id": "engine",
"token_count": 208
} | 194 |
// Copyright 2013 The Flutter 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_MATRIX_H_
#define FLUTTER_IMPELLER_GEOMETRY_MATRIX_H_
#include <cmath>
#include <iomanip>
#include <limits>
#include <optional>
#include <ostream>
#include <utility>
#include "impeller/geometry/matrix_decomposition.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/quaternion.h"
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/shear.h"
#include "impeller/geometry/size.h"
#include "impeller/geometry/vector.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief A 4x4 matrix using column-major storage.
///
/// Utility methods that need to make assumptions about normalized
/// device coordinates must use the following convention:
/// * Left-handed coordinate system. Positive rotation is
/// clockwise about axis of rotation.
/// * Lower left corner is -1.0f, -1.0.
/// * Upper right corner is 1.0f, 1.0.
/// * Visible z-space is from 0.0 to 1.0.
/// * This is NOT the same as OpenGL! Be careful.
/// * NDC origin is at (0.0f, 0.0f, 0.5f).
struct Matrix {
union {
Scalar m[16];
Scalar e[4][4];
Vector4 vec[4];
};
//----------------------------------------------------------------------------
/// Constructs a default identity matrix.
///
constexpr Matrix()
// clang-format off
: vec{ Vector4(1.0f, 0.0f, 0.0f, 0.0f),
Vector4(0.0f, 1.0f, 0.0f, 0.0f),
Vector4(0.0f, 0.0f, 1.0f, 0.0f),
Vector4(0.0f, 0.0f, 0.0f, 1.0f)} {}
// clang-format on
// clang-format off
constexpr Matrix(Scalar m0, Scalar m1, Scalar m2, Scalar m3,
Scalar m4, Scalar m5, Scalar m6, Scalar m7,
Scalar m8, Scalar m9, Scalar m10, Scalar m11,
Scalar m12, Scalar m13, Scalar m14, Scalar m15)
: vec{Vector4(m0, m1, m2, m3),
Vector4(m4, m5, m6, m7),
Vector4(m8, m9, m10, m11),
Vector4(m12, m13, m14, m15)} {}
// clang-format on
explicit Matrix(const MatrixDecomposition& decomposition);
// clang-format off
static constexpr Matrix MakeColumn(
Scalar m0, Scalar m1, Scalar m2, Scalar m3,
Scalar m4, Scalar m5, Scalar m6, Scalar m7,
Scalar m8, Scalar m9, Scalar m10, Scalar m11,
Scalar m12, Scalar m13, Scalar m14, Scalar m15){
return Matrix(m0, m1, m2, m3,
m4, m5, m6, m7,
m8, m9, m10, m11,
m12, m13, m14, m15);
}
// clang-format on
// clang-format off
static constexpr Matrix MakeRow(
Scalar m0, Scalar m1, Scalar m2, Scalar m3,
Scalar m4, Scalar m5, Scalar m6, Scalar m7,
Scalar m8, Scalar m9, Scalar m10, Scalar m11,
Scalar m12, Scalar m13, Scalar m14, Scalar m15){
return Matrix(m0, m4, m8, m12,
m1, m5, m9, m13,
m2, m6, m10, m14,
m3, m7, m11, m15);
}
// clang-format on
static constexpr Matrix MakeTranslation(const Vector3& t) {
// clang-format off
return Matrix(1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
t.x, t.y, t.z, 1.0f);
// clang-format on
}
static constexpr Matrix MakeScale(const Vector3& s) {
// clang-format off
return Matrix(s.x, 0.0f, 0.0f, 0.0f,
0.0f, s.y, 0.0f, 0.0f,
0.0f, 0.0f, s.z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
// clang-format on
}
static constexpr Matrix MakeScale(const Vector2& s) {
return MakeScale(Vector3(s.x, s.y, 1.0f));
}
static constexpr Matrix MakeSkew(Scalar sx, Scalar sy) {
// clang-format off
return Matrix(1.0f, sy , 0.0f, 0.0f,
sx , 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
// clang-format on
}
static Matrix MakeRotation(Quaternion q) {
// clang-format off
return Matrix(
1.0f - 2.0f * q.y * q.y - 2.0f * q.z * q.z,
2.0f * q.x * q.y + 2.0f * q.z * q.w,
2.0f * q.x * q.z - 2.0f * q.y * q.w,
0.0f,
2.0f * q.x * q.y - 2.0f * q.z * q.w,
1.0f - 2.0f * q.x * q.x - 2.0f * q.z * q.z,
2.0f * q.y * q.z + 2.0f * q.x * q.w,
0.0f,
2.0f * q.x * q.z + 2.0f * q.y * q.w,
2.0f * q.y * q.z - 2.0f * q.x * q.w,
1.0f - 2.0f * q.x * q.x - 2.0f * q.y * q.y,
0.0f,
0.0f,
0.0f,
0.0f,
1.0f);
// clang-format on
}
static Matrix MakeRotation(Scalar radians, const Vector4& r) {
const Vector4 v = r.Normalize();
const Scalar cosine = cos(radians);
const Scalar cosp = 1.0f - cosine;
const Scalar sine = sin(radians);
// clang-format off
return Matrix(
cosine + cosp * v.x * v.x,
cosp * v.x * v.y + v.z * sine,
cosp * v.x * v.z - v.y * sine,
0.0f,
cosp * v.x * v.y - v.z * sine,
cosine + cosp * v.y * v.y,
cosp * v.y * v.z + v.x * sine,
0.0f,
cosp * v.x * v.z + v.y * sine,
cosp * v.y * v.z - v.x * sine,
cosine + cosp * v.z * v.z,
0.0f,
0.0f,
0.0f,
0.0f,
1.0f);
// clang-format on
}
static Matrix MakeRotationX(Radians r) {
const Scalar cosine = cos(r.radians);
const Scalar sine = sin(r.radians);
// clang-format off
return Matrix(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, cosine, sine, 0.0f,
0.0f, -sine, cosine, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
);
// clang-format on
}
static Matrix MakeRotationY(Radians r) {
const Scalar cosine = cos(r.radians);
const Scalar sine = sin(r.radians);
// clang-format off
return Matrix(
cosine, 0.0f, -sine, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
sine, 0.0f, cosine, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
);
// clang-format on
}
static Matrix MakeRotationZ(Radians r) {
const Scalar cosine = cos(r.radians);
const Scalar sine = sin(r.radians);
// clang-format off
return Matrix (
cosine, sine, 0.0f, 0.0f,
-sine, cosine, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0
);
// clang-format on
}
/// The Matrix without its `w` components (without translation).
constexpr Matrix Basis() const {
// clang-format off
return Matrix(
m[0], m[1], m[2], 0.0f,
m[4], m[5], m[6], 0.0f,
m[8], m[9], m[10], 0.0f,
0.0f, 0.0f, 0.0f, 1.0
);
// clang-format on
}
constexpr Matrix Translate(const Vector3& t) const {
// clang-format off
return Matrix(m[0], m[1], m[2], m[3],
m[4], m[5], m[6], m[7],
m[8], m[9], m[10], m[11],
m[0] * t.x + m[4] * t.y + m[8] * t.z + m[12],
m[1] * t.x + m[5] * t.y + m[9] * t.z + m[13],
m[2] * t.x + m[6] * t.y + m[10] * t.z + m[14],
m[15]);
// clang-format on
}
constexpr Matrix Scale(const Vector3& s) const {
// clang-format off
return Matrix(m[0] * s.x, m[1] * s.x, m[2] * s.x, m[3] * s.x,
m[4] * s.y, m[5] * s.y, m[6] * s.y, m[7] * s.y,
m[8] * s.z, m[9] * s.z, m[10] * s.z, m[11] * s.z,
m[12] , m[13] , m[14] , m[15] );
// clang-format on
}
constexpr Matrix Multiply(const Matrix& o) const {
// clang-format off
return Matrix(
m[0] * o.m[0] + m[4] * o.m[1] + m[8] * o.m[2] + m[12] * o.m[3],
m[1] * o.m[0] + m[5] * o.m[1] + m[9] * o.m[2] + m[13] * o.m[3],
m[2] * o.m[0] + m[6] * o.m[1] + m[10] * o.m[2] + m[14] * o.m[3],
m[3] * o.m[0] + m[7] * o.m[1] + m[11] * o.m[2] + m[15] * o.m[3],
m[0] * o.m[4] + m[4] * o.m[5] + m[8] * o.m[6] + m[12] * o.m[7],
m[1] * o.m[4] + m[5] * o.m[5] + m[9] * o.m[6] + m[13] * o.m[7],
m[2] * o.m[4] + m[6] * o.m[5] + m[10] * o.m[6] + m[14] * o.m[7],
m[3] * o.m[4] + m[7] * o.m[5] + m[11] * o.m[6] + m[15] * o.m[7],
m[0] * o.m[8] + m[4] * o.m[9] + m[8] * o.m[10] + m[12] * o.m[11],
m[1] * o.m[8] + m[5] * o.m[9] + m[9] * o.m[10] + m[13] * o.m[11],
m[2] * o.m[8] + m[6] * o.m[9] + m[10] * o.m[10] + m[14] * o.m[11],
m[3] * o.m[8] + m[7] * o.m[9] + m[11] * o.m[10] + m[15] * o.m[11],
m[0] * o.m[12] + m[4] * o.m[13] + m[8] * o.m[14] + m[12] * o.m[15],
m[1] * o.m[12] + m[5] * o.m[13] + m[9] * o.m[14] + m[13] * o.m[15],
m[2] * o.m[12] + m[6] * o.m[13] + m[10] * o.m[14] + m[14] * o.m[15],
m[3] * o.m[12] + m[7] * o.m[13] + m[11] * o.m[14] + m[15] * o.m[15]);
// clang-format on
}
constexpr Matrix Transpose() const {
// clang-format off
return {
m[0], m[4], m[8], m[12],
m[1], m[5], m[9], m[13],
m[2], m[6], m[10], m[14],
m[3], m[7], m[11], m[15],
};
// clang-format on
}
Matrix Invert() const;
Scalar GetDeterminant() const;
Scalar GetMaxBasisLength() const;
Scalar GetMaxBasisLengthXY() const;
constexpr Vector3 GetBasisX() const { return Vector3(m[0], m[1], m[2]); }
constexpr Vector3 GetBasisY() const { return Vector3(m[4], m[5], m[6]); }
constexpr Vector3 GetBasisZ() const { return Vector3(m[8], m[9], m[10]); }
constexpr Vector3 GetScale() const {
return Vector3(GetBasisX().Length(), GetBasisY().Length(),
GetBasisZ().Length());
}
constexpr Scalar GetDirectionScale(Vector3 direction) const {
return 1.0f / (this->Basis().Invert() * direction.Normalize()).Length() *
direction.Length();
}
constexpr bool IsAffine() const {
return (m[2] == 0 && m[3] == 0 && m[6] == 0 && m[7] == 0 && m[8] == 0 &&
m[9] == 0 && m[10] == 1 && m[11] == 0 && m[14] == 0 && m[15] == 1);
}
constexpr bool HasPerspective() const {
return m[3] != 0 || m[7] != 0 || m[11] != 0 || m[15] != 1;
}
constexpr bool IsAligned(Scalar tolerance = 0) const {
int v[] = {!ScalarNearlyZero(m[0], tolerance), //
!ScalarNearlyZero(m[1], tolerance), //
!ScalarNearlyZero(m[2], tolerance), //
!ScalarNearlyZero(m[4], tolerance), //
!ScalarNearlyZero(m[5], tolerance), //
!ScalarNearlyZero(m[6], tolerance), //
!ScalarNearlyZero(m[8], tolerance), //
!ScalarNearlyZero(m[9], tolerance), //
!ScalarNearlyZero(m[10], tolerance)};
// Check if all three basis vectors are aligned to an axis.
if (v[0] + v[1] + v[2] != 1 || //
v[3] + v[4] + v[5] != 1 || //
v[6] + v[7] + v[8] != 1) {
return false;
}
// Ensure that none of the basis vectors overlap.
if (v[0] + v[3] + v[6] != 1 || //
v[1] + v[4] + v[7] != 1 || //
v[2] + v[5] + v[8] != 1) {
return false;
}
return true;
}
constexpr bool IsIdentity() const {
return (
// clang-format off
m[0] == 1.0f && m[1] == 0.0f && m[2] == 0.0f && m[3] == 0.0f &&
m[4] == 0.0f && m[5] == 1.0f && m[6] == 0.0f && m[7] == 0.0f &&
m[8] == 0.0f && m[9] == 0.0f && m[10] == 1.0f && m[11] == 0.0f &&
m[12] == 0.0f && m[13] == 0.0f && m[14] == 0.0f && m[15] == 1.0f
// clang-format on
);
}
/// @brief Returns true if the matrix has a scale-only basis and is
/// non-projective. Note that an identity matrix meets this criteria.
constexpr bool IsTranslationScaleOnly() const {
return (
// clang-format off
m[0] != 0.0 && m[1] == 0.0 && m[2] == 0.0 && m[3] == 0.0 &&
m[4] == 0.0 && m[5] != 0.0 && m[6] == 0.0 && m[7] == 0.0 &&
m[8] == 0.0 && m[9] == 0.0 && m[10] != 0.0 && m[11] == 0.0 &&
m[15] == 1.0
// clang-format on
);
}
std::optional<MatrixDecomposition> Decompose() const;
constexpr bool operator==(const Matrix& m) const {
// clang-format off
return vec[0] == m.vec[0]
&& vec[1] == m.vec[1]
&& vec[2] == m.vec[2]
&& vec[3] == m.vec[3];
// clang-format on
}
constexpr bool operator!=(const Matrix& m) const {
// clang-format off
return vec[0] != m.vec[0]
|| vec[1] != m.vec[1]
|| vec[2] != m.vec[2]
|| vec[3] != m.vec[3];
// clang-format on
}
Matrix operator+(const Vector3& t) const { return Translate(t); }
Matrix operator-(const Vector3& t) const { return Translate(-t); }
Matrix operator*(const Matrix& m) const { return Multiply(m); }
Matrix operator+(const Matrix& m) const;
constexpr Vector4 operator*(const Vector4& v) const {
return Vector4(v.x * m[0] + v.y * m[4] + v.z * m[8] + v.w * m[12],
v.x * m[1] + v.y * m[5] + v.z * m[9] + v.w * m[13],
v.x * m[2] + v.y * m[6] + v.z * m[10] + v.w * m[14],
v.x * m[3] + v.y * m[7] + v.z * m[11] + v.w * m[15]);
}
constexpr Vector3 operator*(const Vector3& v) const {
Scalar w = v.x * m[3] + v.y * m[7] + v.z * m[11] + m[15];
Vector3 result(v.x * m[0] + v.y * m[4] + v.z * m[8] + m[12],
v.x * m[1] + v.y * m[5] + v.z * m[9] + m[13],
v.x * m[2] + v.y * m[6] + v.z * m[10] + m[14]);
// This is Skia's behavior, but it may be reasonable to allow UB for the w=0
// case.
if (w) {
w = 1 / w;
}
return result * w;
}
constexpr Point operator*(const Point& v) const {
Scalar w = v.x * m[3] + v.y * m[7] + m[15];
Point result(v.x * m[0] + v.y * m[4] + m[12],
v.x * m[1] + v.y * m[5] + m[13]);
// This is Skia's behavior, but it may be reasonable to allow UB for the w=0
// case.
if (w) {
w = 1 / w;
}
return result * w;
}
constexpr Vector4 TransformDirection(const Vector4& v) const {
return Vector4(v.x * m[0] + v.y * m[4] + v.z * m[8],
v.x * m[1] + v.y * m[5] + v.z * m[9],
v.x * m[2] + v.y * m[6] + v.z * m[10], v.w);
}
constexpr Vector3 TransformDirection(const Vector3& v) const {
return Vector3(v.x * m[0] + v.y * m[4] + v.z * m[8],
v.x * m[1] + v.y * m[5] + v.z * m[9],
v.x * m[2] + v.y * m[6] + v.z * m[10]);
}
constexpr Vector2 TransformDirection(const Vector2& v) const {
return Vector2(v.x * m[0] + v.y * m[4], v.x * m[1] + v.y * m[5]);
}
constexpr Quad Transform(const Quad& quad) const {
return {
*this * quad[0],
*this * quad[1],
*this * quad[2],
*this * quad[3],
};
}
template <class T>
static constexpr Matrix MakeOrthographic(TSize<T> size) {
// Per assumptions about NDC documented above.
const auto scale =
MakeScale({2.0f / static_cast<Scalar>(size.width),
-2.0f / static_cast<Scalar>(size.height), 0.0f});
const auto translate = MakeTranslation({-1.0f, 1.0f, 0.5f});
return translate * scale;
}
static constexpr Matrix MakePerspective(Radians fov_y,
Scalar aspect_ratio,
Scalar z_near,
Scalar z_far) {
Scalar height = std::tan(fov_y.radians * 0.5f);
Scalar width = height * aspect_ratio;
// clang-format off
return {
1.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, z_far / (z_far - z_near), 1.0f,
0.0f, 0.0f, -(z_far * z_near) / (z_far - z_near), 0.0f,
};
// clang-format on
}
template <class T>
static constexpr Matrix MakePerspective(Radians fov_y,
TSize<T> size,
Scalar z_near,
Scalar z_far) {
return MakePerspective(fov_y, static_cast<Scalar>(size.width) / size.height,
z_near, z_far);
}
static constexpr Matrix MakeLookAt(Vector3 position,
Vector3 target,
Vector3 up) {
Vector3 forward = (target - position).Normalize();
Vector3 right = up.Cross(forward);
up = forward.Cross(right);
// clang-format off
return {
right.x, up.x, forward.x, 0.0f,
right.y, up.y, forward.y, 0.0f,
right.z, up.z, forward.z, 0.0f,
-right.Dot(position), -up.Dot(position), -forward.Dot(position), 1.0f
};
// clang-format on
}
};
static_assert(sizeof(struct Matrix) == sizeof(Scalar) * 16,
"The matrix must be of consistent size.");
} // namespace impeller
namespace std {
inline std::ostream& operator<<(std::ostream& out, const impeller::Matrix& m) {
out << "(" << std::endl << std::fixed;
for (size_t i = 0; i < 4u; i++) {
for (size_t j = 0; j < 4u; j++) {
out << std::setw(15) << m.e[j][i] << ",";
}
out << std::endl;
}
out << ")";
return out;
}
} // namespace std
#endif // FLUTTER_IMPELLER_GEOMETRY_MATRIX_H_
| engine/impeller/geometry/matrix.h/0 | {
"file_path": "engine/impeller/geometry/matrix.h",
"repo_id": "engine",
"token_count": 9964
} | 195 |
// Copyright 2013 The Flutter 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_RECT_H_
#define FLUTTER_IMPELLER_GEOMETRY_RECT_H_
#include <array>
#include <optional>
#include <ostream>
#include <vector>
#include "fml/logging.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/saturated_math.h"
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/size.h"
namespace impeller {
#define ONLY_ON_FLOAT_M(Modifiers, Return) \
template <typename U = T> \
Modifiers std::enable_if_t<std::is_floating_point_v<U>, Return>
#define ONLY_ON_FLOAT(Return) DL_ONLY_ON_FLOAT_M(, Return)
/// Templated struct for holding an axis-aligned rectangle.
///
/// Rectangles are defined as 4 axis-aligned edges that might contain
/// space. They can be viewed as 2 X coordinates that define the
/// left and right edges and 2 Y coordinates that define the top and
/// bottom edges; or they can be viewed as an origin and horizontal
/// and vertical dimensions (width and height).
///
/// When the left and right edges are equal or reversed (right <= left)
/// or the top and bottom edges are equal or reversed (bottom <= top),
/// the rectangle is considered empty. Considering the rectangle in XYWH
/// form, the width and/or the height would be negative or zero. Such
/// reversed/empty rectangles contain no space and act as such in the
/// methods that operate on them (Intersection, Union, IntersectsWithRect,
/// Contains, Cutout, etc.)
///
/// Rectangles cannot be modified by any method and a new value can only
/// be stored into an existing rect using assignment. This keeps the API
/// clean compared to implementations that might have similar methods
/// that produce the answer in place, or construct a new object with
/// the answer, or place the result in an indicated result object.
///
/// Methods that might fail to produce an answer will use |std::optional|
/// to indicate that success or failure (see |Intersection| and |CutOut|).
/// For convenience, |Intersection| and |Union| both have overloaded
/// variants that take |std::optional| arguments and treat them as if
/// the argument was an empty rect to allow chaining multiple such methods
/// and only needing to check the optional condition of the final result.
/// The primary methods also provide |...OrEmpty| overloaded variants that
/// translate an empty optional answer into a simple empty rectangle of the
/// same type.
///
/// Rounding instance methods are not provided as the return value might
/// be wanted as another floating point rectangle or sometimes as an integer
/// rectangle. Instead a |RoundOut| factory, defined only for floating point
/// input rectangles, is provided to provide control over the result type.
///
/// NaN and Infinity values
///
/// Constructing an LTRB rectangle using Infinity values should work as
/// expected with either 0 or +Infinity returned as dimensions depending on
/// which side the Infinity values are on and the sign.
///
/// Constructing an XYWH rectangle using Infinity values will usually
/// not work if the math requires the object to compute a right or bottom
/// edge from ([xy] -Infinity + [wh] +Infinity). Other combinations might
/// work.
///
/// The special factory |MakeMaximum| is provided to construct a rectangle
/// of the indicated coordinate type that covers all finite coordinates.
/// It does not use infinity values, but rather the largest finite values
/// to avoid math that might produce a NaN value from various getters.
///
/// Any rectangle that is constructed with, or computed to have a NaN value
/// will be considered the same as any empty rectangle.
///
/// Empty Rectangle canonical results summary:
///
/// Union will ignore any empty rects and return the other rect
/// Intersection will return nullopt if either rect is empty
/// IntersectsWithRect will return false if either rect is empty
/// Cutout will return the source rect if the argument is empty
/// Cutout will return nullopt if the source rectangle is empty
/// Contains(Point) will return false if the source rectangle is empty
/// Contains(Rect) will return false if the source rectangle is empty
/// Contains(Rect) will otherwise return true if the argument is empty
/// Specifically, EmptyRect.Contains(EmptyRect) returns false
///
/// ---------------
/// Special notes on problems using the XYWH form of specifying rectangles:
///
/// It is possible to have integer rectangles whose dimensions exceed
/// the maximum number that their coordinates can represent since
/// (MAX_INT - MIN_INT) overflows the representable positive numbers.
/// Floating point rectangles technically have a similar issue in that
/// overflow can occur, but it will be automatically converted into
/// either an infinity, or a finite-overflow value and still be
/// representable, just with little to no precision.
///
/// Secondly, specifying a rectangle using XYWH leads to cases where the
/// math for (x+w) and/or (y+h) are also beyond the maximum representable
/// coordinates. For N-bit integer rectangles declared as XYWH, the
/// maximum right coordinate will require N+1 signed bits which cannot be
/// stored in storage that uses N-bit integers.
///
/// Saturated math is used when constructing a rectangle from XYWH values
/// and when returning the dimensions of the rectangle. Constructing an
/// integer rectangle from values such that xy + wh is beyond the range
/// of the integer type will place the right or bottom edges at the maximum
/// value for the integer type. Similarly, constructing an integer rectangle
/// such that the distance from the left to the right (or top to bottom) is
/// greater than the range of the integer type will simply return the
/// maximum integer value as the dimension. Floating point rectangles are
/// naturally saturated by the rules of IEEE arithmetic.
template <class T>
struct TRect {
private:
using Type = T;
public:
constexpr TRect() : left_(0), top_(0), right_(0), bottom_(0) {}
constexpr static TRect MakeLTRB(Type left,
Type top,
Type right,
Type bottom) {
return TRect(left, top, right, bottom);
}
constexpr static TRect MakeXYWH(Type x, Type y, Type width, Type height) {
return TRect(x, y, saturated::Add(x, width), saturated::Add(y, height));
}
constexpr static TRect MakeOriginSize(const TPoint<Type>& origin,
const TSize<Type>& size) {
return MakeXYWH(origin.x, origin.y, size.width, size.height);
}
template <class U>
constexpr static TRect MakeSize(const TSize<U>& size) {
return TRect(0.0, 0.0, size.width, size.height);
}
template <typename U>
constexpr static std::optional<TRect> MakePointBounds(const U& value) {
return MakePointBounds(value.begin(), value.end());
}
template <typename PointIter>
constexpr static std::optional<TRect> MakePointBounds(const PointIter first,
const PointIter last) {
if (first == last) {
return std::nullopt;
}
auto left = first->x;
auto top = first->y;
auto right = first->x;
auto bottom = first->y;
for (auto it = first + 1; it < last; ++it) {
left = std::min(left, it->x);
top = std::min(top, it->y);
right = std::max(right, it->x);
bottom = std::max(bottom, it->y);
}
return TRect::MakeLTRB(left, top, right, bottom);
}
[[nodiscard]] constexpr static TRect MakeMaximum() {
return TRect::MakeLTRB(std::numeric_limits<Type>::lowest(),
std::numeric_limits<Type>::lowest(),
std::numeric_limits<Type>::max(),
std::numeric_limits<Type>::max());
}
[[nodiscard]] constexpr bool operator==(const TRect& r) const {
return left_ == r.left_ && //
top_ == r.top_ && //
right_ == r.right_ && //
bottom_ == r.bottom_;
}
[[nodiscard]] constexpr TRect Scale(Type scale) const {
return TRect(left_ * scale, //
top_ * scale, //
right_ * scale, //
bottom_ * scale);
}
[[nodiscard]] constexpr TRect Scale(Type scale_x, Type scale_y) const {
return TRect(left_ * scale_x, //
top_ * scale_y, //
right_ * scale_x, //
bottom_ * scale_y);
}
[[nodiscard]] constexpr TRect Scale(TPoint<T> scale) const {
return Scale(scale.x, scale.y);
}
[[nodiscard]] constexpr TRect Scale(TSize<T> scale) const {
return Scale(scale.width, scale.height);
}
/// @brief Returns true iff the provided point |p| is inside the
/// half-open interior of this rectangle.
///
/// For purposes of containment, a rectangle contains points
/// along the top and left edges but not points along the
/// right and bottom edges so that a point is only ever
/// considered inside one of two abutting rectangles.
[[nodiscard]] constexpr bool Contains(const TPoint<Type>& p) const {
return !this->IsEmpty() && //
p.x >= left_ && //
p.y >= top_ && //
p.x < right_ && //
p.y < bottom_;
}
/// @brief Returns true iff this rectangle is not empty and it also
/// contains every point considered inside the provided
/// rectangle |o| (as determined by |Contains(TPoint)|).
///
/// This is similar to a definition where the result is true iff
/// the union of the two rectangles is equal to this rectangle,
/// ignoring precision issues with performing those operations
/// and assuming that empty rectangles are never equal.
///
/// An empty rectangle can contain no other rectangle.
///
/// An empty rectangle is, however, contained within any
/// other non-empy rectangle as the set of points it contains
/// is an empty set and so there are no points to fail the
/// containment criteria.
[[nodiscard]] constexpr bool Contains(const TRect& o) const {
return !this->IsEmpty() && //
(o.IsEmpty() || (o.left_ >= left_ && //
o.top_ >= top_ && //
o.right_ <= right_ && //
o.bottom_ <= bottom_));
}
/// @brief Returns true if all of the fields of this floating point
/// rectangle are finite.
///
/// Note that the results of |GetWidth()| and |GetHeight()| may
/// still be infinite due to overflow even if the fields themselves
/// are finite.
ONLY_ON_FLOAT_M([[nodiscard]] constexpr, bool)
IsFinite() const {
return std::isfinite(left_) && //
std::isfinite(top_) && //
std::isfinite(right_) && //
std::isfinite(bottom_);
}
/// @brief Returns true if either of the width or height are 0, negative,
/// or NaN.
[[nodiscard]] constexpr bool IsEmpty() const {
// Computing the non-empty condition and negating the result causes any
// NaN value to return true - i.e. is considered empty.
return !(left_ < right_ && top_ < bottom_);
}
/// @brief Returns true if width and height are equal and neither is NaN.
[[nodiscard]] constexpr bool IsSquare() const {
// empty rectangles can technically be "square", but would be
// misleading to most callers. Using |IsEmpty| also prevents
// "non-empty and non-overflowing" computations from happening
// to be equal to "empty and overflowing" results.
// (Consider LTRB(10, 15, MAX-2, MIN+2) which is empty, but both
// w/h subtractions equal "5").
return !IsEmpty() && (right_ - left_) == (bottom_ - top_);
}
[[nodiscard]] constexpr bool IsMaximum() const {
return *this == MakeMaximum();
}
/// @brief Returns the upper left corner of the rectangle as specified
/// by the left/top or x/y values when it was constructed.
[[nodiscard]] constexpr TPoint<Type> GetOrigin() const {
return {left_, top_};
}
/// @brief Returns the size of the rectangle which may be negative in
/// either width or height and may have been clipped to the
/// maximum integer values for integer rects whose size overflows.
[[nodiscard]] constexpr TSize<Type> GetSize() const {
return {GetWidth(), GetHeight()};
}
/// @brief Returns the X coordinate of the upper left corner, equivalent
/// to |GetOrigin().x|
[[nodiscard]] constexpr Type GetX() const { return left_; }
/// @brief Returns the Y coordinate of the upper left corner, equivalent
/// to |GetOrigin().y|
[[nodiscard]] constexpr Type GetY() const { return top_; }
/// @brief Returns the width of the rectangle, equivalent to
/// |GetSize().width|
[[nodiscard]] constexpr Type GetWidth() const {
return saturated::Sub(right_, left_);
}
/// @brief Returns the height of the rectangle, equivalent to
/// |GetSize().height|
[[nodiscard]] constexpr Type GetHeight() const {
return saturated::Sub(bottom_, top_);
}
[[nodiscard]] constexpr auto GetLeft() const { return left_; }
[[nodiscard]] constexpr auto GetTop() const { return top_; }
[[nodiscard]] constexpr auto GetRight() const { return right_; }
[[nodiscard]] constexpr auto GetBottom() const { return bottom_; }
[[nodiscard]] constexpr TPoint<T> GetLeftTop() const { //
return {left_, top_};
}
[[nodiscard]] constexpr TPoint<T> GetRightTop() const {
return {right_, top_};
}
[[nodiscard]] constexpr TPoint<T> GetLeftBottom() const {
return {left_, bottom_};
}
[[nodiscard]] constexpr TPoint<T> GetRightBottom() const {
return {right_, bottom_};
}
/// @brief Get the area of the rectangle, equivalent to |GetSize().Area()|
[[nodiscard]] constexpr T Area() const {
// TODO(flutter/flutter#141710) - Use saturated math to avoid overflow
// https://github.com/flutter/flutter/issues/141710
return IsEmpty() ? 0 : (right_ - left_) * (bottom_ - top_);
}
/// @brief Get the center point as a |Point|.
[[nodiscard]] constexpr Point GetCenter() const {
return {saturated::AverageScalar(left_, right_),
saturated::AverageScalar(top_, bottom_)};
}
[[nodiscard]] constexpr std::array<T, 4> GetLTRB() const {
return {left_, top_, right_, bottom_};
}
/// @brief Get the x, y coordinates of the origin and the width and
/// height of the rectangle in an array.
[[nodiscard]] constexpr std::array<T, 4> GetXYWH() const {
return {left_, top_, GetWidth(), GetHeight()};
}
/// @brief Get a version of this rectangle that has a non-negative size.
[[nodiscard]] constexpr TRect GetPositive() const {
if (!IsEmpty()) {
return *this;
}
return {
std::min(left_, right_),
std::min(top_, bottom_),
std::max(left_, right_),
std::max(top_, bottom_),
};
}
/// @brief Get the points that represent the 4 corners of this rectangle
/// in a Z order that is compatible with triangle strips or a set
/// of all zero points if the rectangle is empty.
/// The order is: Top left, top right, bottom left, bottom right.
[[nodiscard]] constexpr std::array<TPoint<T>, 4> GetPoints() const {
if (IsEmpty()) {
return {};
}
return {
TPoint{left_, top_},
TPoint{right_, top_},
TPoint{left_, bottom_},
TPoint{right_, bottom_},
};
}
[[nodiscard]] constexpr std::array<TPoint<T>, 4> GetTransformedPoints(
const Matrix& transform) const {
auto points = GetPoints();
for (size_t i = 0; i < points.size(); i++) {
points[i] = transform * points[i];
}
return points;
}
/// @brief Creates a new bounding box that contains this transformed
/// rectangle.
[[nodiscard]] constexpr TRect TransformBounds(const Matrix& transform) const {
if (IsEmpty()) {
return {};
}
auto points = GetTransformedPoints(transform);
auto bounds = TRect::MakePointBounds(points.begin(), points.end());
if (bounds.has_value()) {
return bounds.value();
}
FML_UNREACHABLE();
}
/// @brief Constructs a Matrix that will map all points in the coordinate
/// space of the rectangle into a new normalized coordinate space
/// where the upper left corner of the rectangle maps to (0, 0)
/// and the lower right corner of the rectangle maps to (1, 1).
///
/// Empty and non-finite rectangles will return a zero-scaling
/// transform that maps all points to (0, 0).
[[nodiscard]] constexpr Matrix GetNormalizingTransform() const {
if (!IsEmpty()) {
Scalar sx = 1.0 / GetWidth();
Scalar sy = 1.0 / GetHeight();
Scalar tx = left_ * -sx;
Scalar ty = top_ * -sy;
// Exclude NaN and infinities and either scale underflowing to zero
if (sx != 0.0 && sy != 0.0 && 0.0 * sx * sy * tx * ty == 0.0) {
// clang-format off
return Matrix( sx, 0.0f, 0.0f, 0.0f,
0.0f, sy, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
tx, ty, 0.0f, 1.0f);
// clang-format on
}
}
// Map all coordinates to the origin.
return Matrix::MakeScale({0.0f, 0.0f, 1.0f});
}
[[nodiscard]] constexpr TRect Union(const TRect& o) const {
if (IsEmpty()) {
return o;
}
if (o.IsEmpty()) {
return *this;
}
return {
std::min(left_, o.left_),
std::min(top_, o.top_),
std::max(right_, o.right_),
std::max(bottom_, o.bottom_),
};
}
[[nodiscard]] constexpr std::optional<TRect> Intersection(
const TRect& o) const {
if (IntersectsWithRect(o)) {
return TRect{
std::max(left_, o.left_),
std::max(top_, o.top_),
std::min(right_, o.right_),
std::min(bottom_, o.bottom_),
};
} else {
return std::nullopt;
}
}
[[nodiscard]] constexpr bool IntersectsWithRect(const TRect& o) const {
return !IsEmpty() && //
!o.IsEmpty() && //
left_ < o.right_ && //
top_ < o.bottom_ && //
right_ > o.left_ && //
bottom_ > o.top_;
}
/// @brief Returns the new boundary rectangle that would result from this
/// rectangle being cut out by the specified rectangle.
[[nodiscard]] constexpr std::optional<TRect<T>> Cutout(const TRect& o) const {
if (IsEmpty()) {
// This test isn't just a short-circuit, it also prevents the concise
// math below from returning the wrong answer on empty rects.
// Once we know that this rectangle is not empty, the math below can
// only succeed in computing a value if o is also non-empty and non-nan.
// Otherwise, the method returns *this by default.
return std::nullopt;
}
const auto& [a_left, a_top, a_right, a_bottom] = GetLTRB(); // Source rect.
const auto& [b_left, b_top, b_right, b_bottom] = o.GetLTRB(); // Cutout.
if (b_left <= a_left && b_right >= a_right) {
if (b_top <= a_top && b_bottom >= a_bottom) {
// Full cutout.
return std::nullopt;
}
if (b_top <= a_top && b_bottom > a_top) {
// Cuts off the top.
return TRect::MakeLTRB(a_left, b_bottom, a_right, a_bottom);
}
if (b_bottom >= a_bottom && b_top < a_bottom) {
// Cuts off the bottom.
return TRect::MakeLTRB(a_left, a_top, a_right, b_top);
}
}
if (b_top <= a_top && b_bottom >= a_bottom) {
if (b_left <= a_left && b_right > a_left) {
// Cuts off the left.
return TRect::MakeLTRB(b_right, a_top, a_right, a_bottom);
}
if (b_right >= a_right && b_left < a_right) {
// Cuts off the right.
return TRect::MakeLTRB(a_left, a_top, b_left, a_bottom);
}
}
return *this;
}
[[nodiscard]] constexpr TRect CutoutOrEmpty(const TRect& o) const {
return Cutout(o).value_or(TRect());
}
/// @brief Returns a new rectangle translated by the given offset.
[[nodiscard]] constexpr TRect<T> Shift(T dx, T dy) const {
return {
saturated::Add(left_, dx), //
saturated::Add(top_, dy), //
saturated::Add(right_, dx), //
saturated::Add(bottom_, dy), //
};
}
/// @brief Returns a new rectangle translated by the given offset.
[[nodiscard]] constexpr TRect<T> Shift(TPoint<T> offset) const {
return Shift(offset.x, offset.y);
}
/// @brief Returns a rectangle with expanded edges. Negative expansion
/// results in shrinking.
[[nodiscard]] constexpr TRect<T> Expand(T left,
T top,
T right,
T bottom) const {
return {
saturated::Sub(left_, left), //
saturated::Sub(top_, top), //
saturated::Add(right_, right), //
saturated::Add(bottom_, bottom), //
};
}
/// @brief Returns a rectangle with expanded edges in all directions.
/// Negative expansion results in shrinking.
[[nodiscard]] constexpr TRect<T> Expand(T amount) const {
return {
saturated::Sub(left_, amount), //
saturated::Sub(top_, amount), //
saturated::Add(right_, amount), //
saturated::Add(bottom_, amount), //
};
}
/// @brief Returns a rectangle with expanded edges in all directions.
/// Negative expansion results in shrinking.
[[nodiscard]] constexpr TRect<T> Expand(T horizontal_amount,
T vertical_amount) const {
return {
saturated::Sub(left_, horizontal_amount), //
saturated::Sub(top_, vertical_amount), //
saturated::Add(right_, horizontal_amount), //
saturated::Add(bottom_, vertical_amount), //
};
}
/// @brief Returns a rectangle with expanded edges in all directions.
/// Negative expansion results in shrinking.
[[nodiscard]] constexpr TRect<T> Expand(TPoint<T> amount) const {
return Expand(amount.x, amount.y);
}
/// @brief Returns a rectangle with expanded edges in all directions.
/// Negative expansion results in shrinking.
[[nodiscard]] constexpr TRect<T> Expand(TSize<T> amount) const {
return Expand(amount.width, amount.height);
}
/// @brief Returns a new rectangle that represents the projection of the
/// source rectangle onto this rectangle. In other words, the source
/// rectangle is redefined in terms of the coordinate space of this
/// rectangle.
[[nodiscard]] constexpr TRect<T> Project(TRect<T> source) const {
if (IsEmpty()) {
return {};
}
return source.Shift(-left_, -top_)
.Scale(1.0 / static_cast<Scalar>(GetWidth()),
1.0 / static_cast<Scalar>(GetHeight()));
}
ONLY_ON_FLOAT_M([[nodiscard]] constexpr static, TRect)
RoundOut(const TRect<U>& r) {
return TRect::MakeLTRB(saturated::Cast<U, Type>(floor(r.GetLeft())),
saturated::Cast<U, Type>(floor(r.GetTop())),
saturated::Cast<U, Type>(ceil(r.GetRight())),
saturated::Cast<U, Type>(ceil(r.GetBottom())));
}
[[nodiscard]] constexpr static std::optional<TRect> Union(
const TRect& a,
const std::optional<TRect> b) {
return b.has_value() ? a.Union(b.value()) : a;
}
[[nodiscard]] constexpr static std::optional<TRect> Union(
const std::optional<TRect> a,
const TRect& b) {
return a.has_value() ? a->Union(b) : b;
}
[[nodiscard]] constexpr static std::optional<TRect> Union(
const std::optional<TRect> a,
const std::optional<TRect> b) {
return a.has_value() ? Union(a.value(), b) : b;
}
[[nodiscard]] constexpr static std::optional<TRect> Intersection(
const TRect& a,
const std::optional<TRect> b) {
return b.has_value() ? a.Intersection(b.value()) : a;
}
[[nodiscard]] constexpr static std::optional<TRect> Intersection(
const std::optional<TRect> a,
const TRect& b) {
return a.has_value() ? a->Intersection(b) : b;
}
[[nodiscard]] constexpr static std::optional<TRect> Intersection(
const std::optional<TRect> a,
const std::optional<TRect> b) {
return a.has_value() ? Intersection(a.value(), b) : b;
}
private:
constexpr TRect(Type left, Type top, Type right, Type bottom)
: left_(left), top_(top), right_(right), bottom_(bottom) {}
Type left_;
Type top_;
Type right_;
Type bottom_;
};
using Rect = TRect<Scalar>;
using IRect = TRect<int64_t>;
#undef ONLY_ON_FLOAT
#undef ONLY_ON_FLOAT_M
} // namespace impeller
namespace std {
template <class T>
inline std::ostream& operator<<(std::ostream& out,
const impeller::TRect<T>& r) {
out << "(" << r.GetOrigin() << ", " << r.GetSize() << ")";
return out;
}
} // namespace std
#endif // FLUTTER_IMPELLER_GEOMETRY_RECT_H_
| engine/impeller/geometry/rect.h/0 | {
"file_path": "engine/impeller/geometry/rect.h",
"repo_id": "engine",
"token_count": 9609
} | 196 |
// Copyright 2013 The Flutter 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_TYPE_TRAITS_H_
#define FLUTTER_IMPELLER_GEOMETRY_TYPE_TRAITS_H_
#include <type_traits>
namespace impeller {
template <class F,
class I,
class = std::enable_if_t<std::is_floating_point_v<F> &&
std::is_integral_v<I>>>
struct MixedOp_ : public std::true_type {};
template <class F, class I>
using MixedOp = typename MixedOp_<F, I>::type;
} // namespace impeller
#endif // FLUTTER_IMPELLER_GEOMETRY_TYPE_TRAITS_H_
| engine/impeller/geometry/type_traits.h/0 | {
"file_path": "engine/impeller/geometry/type_traits.h",
"repo_id": "engine",
"token_count": 289
} | 197 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOT_H_
#define FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOT_H_
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
namespace impeller {
namespace testing {
class Screenshot {
public:
virtual ~Screenshot() = default;
/// Access raw data of the screenshot.
virtual const uint8_t* GetBytes() const = 0;
/// Returns the height of the image in pixels.
virtual size_t GetHeight() const = 0;
/// Returns the width of the image in pixels.
virtual size_t GetWidth() const = 0;
/// Returns number of bytes required to represent one row of the raw image.
virtual size_t GetBytesPerRow() const = 0;
/// Synchronously write the screenshot to disk as a PNG at `path`. Returns
/// `true` if it succeeded.
virtual bool WriteToPNG(const std::string& path) const = 0;
};
} // namespace testing
} // namespace impeller
#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOT_H_
| engine/impeller/golden_tests/screenshot.h/0 | {
"file_path": "engine/impeller/golden_tests/screenshot.h",
"repo_id": "engine",
"token_count": 365
} | 198 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/time/time_point.h"
#include "flutter/testing/test_args.h"
#include "impeller/playground/compute_playground_test.h"
namespace impeller {
ComputePlaygroundTest::ComputePlaygroundTest()
: Playground(PlaygroundSwitches{flutter::testing::GetArgsForProcess()}) {}
ComputePlaygroundTest::~ComputePlaygroundTest() = default;
void ComputePlaygroundTest::SetUp() {
if (!Playground::SupportsBackend(GetParam())) {
GTEST_SKIP_("Playground doesn't support this backend type.");
return;
}
if (!Playground::ShouldOpenNewPlaygrounds()) {
GTEST_SKIP_("Skipping due to user action.");
return;
}
SetupContext(GetParam());
SetupWindow();
start_time_ = fml::TimePoint::Now().ToEpochDelta();
}
void ComputePlaygroundTest::TearDown() {
TeardownWindow();
}
// |Playground|
std::unique_ptr<fml::Mapping> ComputePlaygroundTest::OpenAssetAsMapping(
std::string asset_name) const {
return flutter::testing::OpenFixtureAsMapping(asset_name);
}
static std::string FormatWindowTitle(const std::string& test_name) {
std::stringstream stream;
stream << "Impeller Playground for '" << test_name << "' (Press ESC to quit)";
return stream.str();
}
// |Playground|
std::string ComputePlaygroundTest::GetWindowTitle() const {
return FormatWindowTitle(flutter::testing::GetCurrentTestName());
}
} // namespace impeller
| engine/impeller/playground/compute_playground_test.cc/0 | {
"file_path": "engine/impeller/playground/compute_playground_test.cc",
"repo_id": "engine",
"token_count": 500
} | 199 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_H_
#define FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_H_
#include <chrono>
#include <memory>
#include "flutter/fml/closure.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/status.h"
#include "flutter/fml/time/time_delta.h"
#include "impeller/core/runtime_types.h"
#include "impeller/core/texture.h"
#include "impeller/geometry/point.h"
#include "impeller/playground/image/compressed_image.h"
#include "impeller/playground/image/decompressed_image.h"
#include "impeller/playground/switches.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/renderer.h"
#include "impeller/runtime_stage/runtime_stage.h"
namespace impeller {
class PlaygroundImpl;
enum class PlaygroundBackend {
kMetal,
kOpenGLES,
kVulkan,
};
// TODO(https://github.com/flutter/flutter/issues/145039)
// clang-format off
static const std::vector<std::string> kVulkanDenyValidationTests = {
"impeller_Play_SceneTest_FlutterLogo_Vulkan",
"impeller_Play_SceneTest_CuboidUnlit_Vulkan",
"impeller_Play_RuntimeStageTest_CanCreatePipelineFromRuntimeStage_Vulkan",
"impeller_Play_RuntimeEffectSetsRightSizeWhenUniformIsStruct_Vulkan",
"impeller_Play_RuntimeEffectCanSuccessfullyRender_Vulkan",
"impeller_Play_RuntimeEffect_Vulkan",
"impeller_Play_EntityTest_RuntimeStageTest_CanCreatePipelineFromRuntimeStage_Vulkan",
"impeller_Play_EntityTest_RuntimeEffectSetsRightSizeWhenUniformIsStruct_Vulkan",
"impeller_Play_EntityTest_RuntimeEffectCanSuccessfullyRender_Vulkan",
"impeller_Play_EntityTest_RuntimeEffect_Vulkan",
};
// clang-format on
constexpr inline RuntimeStageBackend PlaygroundBackendToRuntimeStageBackend(
PlaygroundBackend backend) {
switch (backend) {
case PlaygroundBackend::kMetal:
return RuntimeStageBackend::kMetal;
case PlaygroundBackend::kOpenGLES:
return RuntimeStageBackend::kOpenGLES;
case PlaygroundBackend::kVulkan:
return RuntimeStageBackend::kVulkan;
}
FML_UNREACHABLE();
}
std::string PlaygroundBackendToString(PlaygroundBackend backend);
class Playground {
public:
using SinglePassCallback = std::function<bool(RenderPass& pass)>;
explicit Playground(PlaygroundSwitches switches);
virtual ~Playground();
static bool ShouldOpenNewPlaygrounds();
void SetupContext(PlaygroundBackend backend);
void SetupWindow();
void TeardownWindow();
Point GetCursorPosition() const;
ISize GetWindowSize() const;
Point GetContentScale() const;
/// @brief Get the amount of time elapsed from the start of the playground's
/// execution.
Scalar GetSecondsElapsed() const;
std::shared_ptr<Context> GetContext() const;
std::shared_ptr<Context> MakeContext() const;
bool OpenPlaygroundHere(const Renderer::RenderCallback& render_callback);
bool OpenPlaygroundHere(SinglePassCallback pass_callback);
static std::shared_ptr<CompressedImage> LoadFixtureImageCompressed(
std::shared_ptr<fml::Mapping> mapping);
static std::optional<DecompressedImage> DecodeImageRGBA(
const std::shared_ptr<CompressedImage>& compressed);
static std::shared_ptr<Texture> CreateTextureForMapping(
const std::shared_ptr<Context>& context,
std::shared_ptr<fml::Mapping> mapping,
bool enable_mipmapping = false);
std::shared_ptr<Texture> CreateTextureForFixture(
const char* fixture_name,
bool enable_mipmapping = false) const;
std::shared_ptr<Texture> CreateTextureCubeForFixture(
std::array<const char*, 6> fixture_names) const;
static bool SupportsBackend(PlaygroundBackend backend);
virtual std::unique_ptr<fml::Mapping> OpenAssetAsMapping(
std::string asset_name) const = 0;
virtual std::string GetWindowTitle() const = 0;
[[nodiscard]] fml::Status SetCapabilities(
const std::shared_ptr<Capabilities>& capabilities);
/// TODO(https://github.com/flutter/flutter/issues/139950): Remove this.
/// Returns true if `OpenPlaygroundHere` will actually render anything.
bool WillRenderSomething() const;
protected:
const PlaygroundSwitches switches_;
virtual bool ShouldKeepRendering() const;
void SetWindowSize(ISize size);
private:
fml::TimeDelta start_time_;
std::unique_ptr<PlaygroundImpl> impl_;
std::shared_ptr<Context> context_;
std::unique_ptr<Renderer> renderer_;
Point cursor_position_;
ISize window_size_ = ISize{1024, 768};
void SetCursorPosition(Point pos);
Playground(const Playground&) = delete;
Playground& operator=(const Playground&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_H_
| engine/impeller/playground/playground.h/0 | {
"file_path": "engine/impeller/playground/playground.h",
"repo_id": "engine",
"token_count": 1582
} | 200 |
// Copyright 2013 The Flutter 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/blit_pass_gles.h"
#include <memory>
#include "flutter/fml/trace_event.h"
#include "fml/closure.h"
#include "impeller/core/formats.h"
#include "impeller/renderer/backend/gles/blit_command_gles.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
namespace impeller {
BlitPassGLES::BlitPassGLES(ReactorGLES::Ref reactor)
: reactor_(std::move(reactor)),
is_valid_(reactor_ && reactor_->IsValid()) {}
// |BlitPass|
BlitPassGLES::~BlitPassGLES() = default;
// |BlitPass|
bool BlitPassGLES::IsValid() const {
return is_valid_;
}
// |BlitPass|
void BlitPassGLES::OnSetLabel(std::string label) {
label_ = std::move(label);
}
[[nodiscard]] bool EncodeCommandsInReactor(
const std::shared_ptr<Allocator>& transients_allocator,
const ReactorGLES& reactor,
const std::vector<std::unique_ptr<BlitEncodeGLES>>& commands,
const std::string& label) {
TRACE_EVENT0("impeller", "BlitPassGLES::EncodeCommandsInReactor");
if (commands.empty()) {
return true;
}
const auto& gl = reactor.GetProcTable();
fml::ScopedCleanupClosure pop_pass_debug_marker(
[&gl]() { gl.PopDebugGroup(); });
if (!label.empty()) {
gl.PushDebugGroup(label);
} else {
pop_pass_debug_marker.Release();
}
for (const auto& command : commands) {
fml::ScopedCleanupClosure pop_cmd_debug_marker(
[&gl]() { gl.PopDebugGroup(); });
auto label = command->GetLabel();
if (!label.empty()) {
gl.PushDebugGroup(label);
} else {
pop_cmd_debug_marker.Release();
}
if (!command->Encode(reactor)) {
return false;
}
}
return true;
}
// |BlitPass|
bool BlitPassGLES::EncodeCommands(
const std::shared_ptr<Allocator>& transients_allocator) const {
if (!IsValid()) {
return false;
}
if (commands_.empty()) {
return true;
}
std::shared_ptr<const BlitPassGLES> shared_this = shared_from_this();
return reactor_->AddOperation([transients_allocator,
blit_pass = std::move(shared_this),
label = label_](const auto& reactor) {
auto result = EncodeCommandsInReactor(transients_allocator, reactor,
blit_pass->commands_, label);
FML_CHECK(result) << "Must be able to encode GL commands without error.";
});
}
// |BlitPass|
bool BlitPassGLES::OnCopyTextureToTextureCommand(
std::shared_ptr<Texture> source,
std::shared_ptr<Texture> destination,
IRect source_region,
IPoint destination_origin,
std::string label) {
auto command = std::make_unique<BlitCopyTextureToTextureCommandGLES>();
command->label = label;
command->source = std::move(source);
command->destination = std::move(destination);
command->source_region = source_region;
command->destination_origin = destination_origin;
commands_.emplace_back(std::move(command));
return true;
}
// |BlitPass|
bool BlitPassGLES::OnCopyTextureToBufferCommand(
std::shared_ptr<Texture> source,
std::shared_ptr<DeviceBuffer> destination,
IRect source_region,
size_t destination_offset,
std::string label) {
auto command = std::make_unique<BlitCopyTextureToBufferCommandGLES>();
command->label = label;
command->source = std::move(source);
command->destination = std::move(destination);
command->source_region = source_region;
command->destination_offset = destination_offset;
commands_.emplace_back(std::move(command));
return true;
}
// |BlitPass|
bool BlitPassGLES::OnGenerateMipmapCommand(std::shared_ptr<Texture> texture,
std::string label) {
auto command = std::make_unique<BlitGenerateMipmapCommandGLES>();
command->label = label;
command->texture = std::move(texture);
commands_.emplace_back(std::move(command));
return true;
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/blit_pass_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/blit_pass_gles.cc",
"repo_id": "engine",
"token_count": 1561
} | 201 |
// Copyright 2013 The Flutter 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_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GLES_H_
// IWYU pragma: begin_exports
#include "GLES3/gl3.h"
// Defines for extension enums.
#define IMPELLER_GL_CLAMP_TO_BORDER 0x812D
#define IMPELLER_GL_TEXTURE_BORDER_COLOR 0x1004
#define GL_GLEXT_PROTOTYPES
#include "GLES2/gl2ext.h"
// IWYU pragma: end_exports
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GLES_H_
| engine/impeller/renderer/backend/gles/gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/gles.h",
"repo_id": "engine",
"token_count": 252
} | 202 |
// Copyright 2013 The Flutter 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_SAMPLER_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_GLES_H_
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/core/sampler.h"
namespace impeller {
class TextureGLES;
class SamplerLibraryGLES;
class ProcTableGLES;
class SamplerGLES final : public Sampler,
public BackendCast<SamplerGLES, Sampler> {
public:
~SamplerGLES();
bool ConfigureBoundTexture(const TextureGLES& texture,
const ProcTableGLES& gl) const;
private:
friend class SamplerLibraryGLES;
explicit SamplerGLES(SamplerDescriptor desc);
SamplerGLES(const SamplerGLES&) = delete;
SamplerGLES& operator=(const SamplerGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_GLES_H_
| engine/impeller/renderer/backend/gles/sampler_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/sampler_gles.h",
"repo_id": "engine",
"token_count": 411
} | 203 |
// Copyright 2013 The Flutter 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 <optional>
#include "flutter/testing/testing.h" // IWYU pragma: keep
#include "gtest/gtest.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
#include "impeller/renderer/backend/gles/test/mock_gles.h"
namespace impeller {
namespace testing {
#define EXPECT_AVAILABLE(proc_ivar) \
EXPECT_TRUE(mock_gles->GetProcTable().proc_ivar.IsAvailable());
#define EXPECT_UNAVAILABLE(proc_ivar) \
EXPECT_FALSE(mock_gles->GetProcTable().proc_ivar.IsAvailable());
TEST(ProcTableGLES, ResolvesCorrectClearDepthProcOnES) {
auto mock_gles = MockGLES::Init(std::nullopt, "OpenGL ES 3.0");
EXPECT_TRUE(mock_gles->GetProcTable().GetDescription()->IsES());
FOR_EACH_IMPELLER_ES_ONLY_PROC(EXPECT_AVAILABLE);
FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(EXPECT_UNAVAILABLE);
}
TEST(ProcTableGLES, ResolvesCorrectClearDepthProcOnDesktopGL) {
auto mock_gles = MockGLES::Init(std::nullopt, "OpenGL 4.0");
EXPECT_FALSE(mock_gles->GetProcTable().GetDescription()->IsES());
FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(EXPECT_AVAILABLE);
FOR_EACH_IMPELLER_ES_ONLY_PROC(EXPECT_UNAVAILABLE);
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/gles/test/proc_table_gles_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/test/proc_table_gles_unittests.cc",
"repo_id": "engine",
"token_count": 525
} | 204 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/metal/compute_pass_mtl.h"
#include <Metal/Metal.h>
#include <memory>
#include "flutter/fml/backtrace.h"
#include "flutter/fml/closure.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "fml/status.h"
#include "impeller/base/backend_cast.h"
#include "impeller/core/device_buffer.h"
#include "impeller/core/formats.h"
#include "impeller/core/host_buffer.h"
#include "impeller/core/shader_types.h"
#include "impeller/renderer/backend/metal/compute_pipeline_mtl.h"
#include "impeller/renderer/backend/metal/device_buffer_mtl.h"
#include "impeller/renderer/backend/metal/formats_mtl.h"
#include "impeller/renderer/backend/metal/sampler_mtl.h"
#include "impeller/renderer/backend/metal/texture_mtl.h"
#include "impeller/renderer/command.h"
namespace impeller {
ComputePassMTL::ComputePassMTL(std::shared_ptr<const Context> context,
id<MTLCommandBuffer> buffer)
: ComputePass(std::move(context)), buffer_(buffer) {
if (!buffer_) {
return;
}
encoder_ = [buffer_ computeCommandEncoderWithDispatchType:
MTLDispatchType::MTLDispatchTypeConcurrent];
if (!encoder_) {
return;
}
pass_bindings_cache_.SetEncoder(encoder_);
is_valid_ = true;
}
ComputePassMTL::~ComputePassMTL() = default;
bool ComputePassMTL::IsValid() const {
return is_valid_;
}
void ComputePassMTL::OnSetLabel(const std::string& label) {
#ifdef IMPELLER_DEBUG
if (label.empty()) {
return;
}
[encoder_ setLabel:@(label.c_str())];
#endif // IMPELLER_DEBUG
}
void ComputePassMTL::SetCommandLabel(std::string_view label) {
has_label_ = true;
[encoder_ pushDebugGroup:@(label.data())];
}
// |ComputePass|
void ComputePassMTL::SetPipeline(
const std::shared_ptr<Pipeline<ComputePipelineDescriptor>>& pipeline) {
pass_bindings_cache_.SetComputePipelineState(
ComputePipelineMTL::Cast(*pipeline).GetMTLComputePipelineState());
}
// |ComputePass|
void ComputePassMTL::AddBufferMemoryBarrier() {
[encoder_ memoryBarrierWithScope:MTLBarrierScopeBuffers];
}
// |ComputePass|
void ComputePassMTL::AddTextureMemoryBarrier() {
[encoder_ memoryBarrierWithScope:MTLBarrierScopeTextures];
}
// |ComputePass|
bool ComputePassMTL::BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) {
if (!view.buffer) {
return false;
}
const std::shared_ptr<const DeviceBuffer>& device_buffer = view.buffer;
if (!device_buffer) {
return false;
}
id<MTLBuffer> buffer = DeviceBufferMTL::Cast(*device_buffer).GetMTLBuffer();
// The Metal call is a void return and we don't want to make it on nil.
if (!buffer) {
return false;
}
pass_bindings_cache_.SetBuffer(slot.ext_res_0, view.range.offset, buffer);
return true;
}
// |ComputePass|
bool ComputePassMTL::BindResource(
ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) {
if (!sampler || !texture->IsValid()) {
return false;
}
pass_bindings_cache_.SetTexture(slot.texture_index,
TextureMTL::Cast(*texture).GetMTLTexture());
pass_bindings_cache_.SetSampler(
slot.texture_index, SamplerMTL::Cast(*sampler).GetMTLSamplerState());
return true;
}
fml::Status ComputePassMTL::Compute(const ISize& grid_size) {
if (grid_size.IsEmpty()) {
return fml::Status(fml::StatusCode::kUnknown,
"Invalid grid size for compute command.");
}
// TODO(dnfield): use feature detection to support non-uniform threadgroup
// sizes.
// https://github.com/flutter/flutter/issues/110619
auto width = grid_size.width;
auto height = grid_size.height;
auto max_total_threads_per_threadgroup = static_cast<int64_t>(
pass_bindings_cache_.GetPipeline().maxTotalThreadsPerThreadgroup);
// Special case for linear processing.
if (height == 1) {
int64_t thread_groups = std::max(
static_cast<int64_t>(
std::ceil(width * 1.0 / max_total_threads_per_threadgroup * 1.0)),
1LL);
[encoder_
dispatchThreadgroups:MTLSizeMake(thread_groups, 1, 1)
threadsPerThreadgroup:MTLSizeMake(max_total_threads_per_threadgroup, 1,
1)];
} else {
while (width * height > max_total_threads_per_threadgroup) {
width = std::max(1LL, width / 2);
height = std::max(1LL, height / 2);
}
auto size = MTLSizeMake(width, height, 1);
[encoder_ dispatchThreadgroups:size threadsPerThreadgroup:size];
}
#ifdef IMPELLER_DEBUG
if (has_label_) {
[encoder_ popDebugGroup];
}
has_label_ = false;
#endif // IMPELLER_DEBUG
return fml::Status();
}
bool ComputePassMTL::EncodeCommands() const {
[encoder_ endEncoding];
return true;
}
} // namespace impeller
| engine/impeller/renderer/backend/metal/compute_pass_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/compute_pass_mtl.mm",
"repo_id": "engine",
"token_count": 2155
} | 205 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/metal/pipeline_library_mtl.h"
#include <Foundation/Foundation.h>
#include <Metal/Metal.h>
#include "flutter/fml/build_config.h"
#include "flutter/fml/container.h"
#include "impeller/base/promise.h"
#include "impeller/renderer/backend/metal/compute_pipeline_mtl.h"
#include "impeller/renderer/backend/metal/formats_mtl.h"
#include "impeller/renderer/backend/metal/pipeline_mtl.h"
#include "impeller/renderer/backend/metal/shader_function_mtl.h"
#include "impeller/renderer/backend/metal/vertex_descriptor_mtl.h"
namespace impeller {
PipelineLibraryMTL::PipelineLibraryMTL(id<MTLDevice> device)
: device_(device) {}
PipelineLibraryMTL::~PipelineLibraryMTL() = default;
using Callback = std::function<void(MTLRenderPipelineDescriptor*)>;
static void GetMTLRenderPipelineDescriptor(const PipelineDescriptor& desc,
const Callback& callback) {
auto descriptor = [[MTLRenderPipelineDescriptor alloc] init];
descriptor.label = @(desc.GetLabel().c_str());
descriptor.rasterSampleCount = static_cast<NSUInteger>(desc.GetSampleCount());
bool created_specialized_function = false;
if (const auto& vertex_descriptor = desc.GetVertexDescriptor()) {
VertexDescriptorMTL vertex_descriptor_mtl;
if (vertex_descriptor_mtl.SetStageInputsAndLayout(
vertex_descriptor->GetStageInputs(),
vertex_descriptor->GetStageLayouts())) {
descriptor.vertexDescriptor =
vertex_descriptor_mtl.GetMTLVertexDescriptor();
}
}
for (const auto& item : desc.GetColorAttachmentDescriptors()) {
descriptor.colorAttachments[item.first] =
ToMTLRenderPipelineColorAttachmentDescriptor(item.second);
}
descriptor.depthAttachmentPixelFormat =
ToMTLPixelFormat(desc.GetDepthPixelFormat());
descriptor.stencilAttachmentPixelFormat =
ToMTLPixelFormat(desc.GetStencilPixelFormat());
const auto& constants = desc.GetSpecializationConstants();
for (const auto& entry : desc.GetStageEntrypoints()) {
if (entry.first == ShaderStage::kVertex) {
descriptor.vertexFunction =
ShaderFunctionMTL::Cast(*entry.second).GetMTLFunction();
}
if (entry.first == ShaderStage::kFragment) {
if (constants.empty()) {
descriptor.fragmentFunction =
ShaderFunctionMTL::Cast(*entry.second).GetMTLFunction();
} else {
// This code only expects a single specialized function per pipeline.
FML_CHECK(!created_specialized_function);
created_specialized_function = true;
ShaderFunctionMTL::Cast(*entry.second)
.GetMTLFunctionSpecialized(
constants, [callback, descriptor](id<MTLFunction> function) {
descriptor.fragmentFunction = function;
callback(descriptor);
});
}
}
}
if (!created_specialized_function) {
callback(descriptor);
}
}
static MTLComputePipelineDescriptor* GetMTLComputePipelineDescriptor(
const ComputePipelineDescriptor& desc) {
auto descriptor = [[MTLComputePipelineDescriptor alloc] init];
descriptor.label = @(desc.GetLabel().c_str());
descriptor.computeFunction =
ShaderFunctionMTL::Cast(*desc.GetStageEntrypoint()).GetMTLFunction();
return descriptor;
}
// TODO(csg): Make PipelineDescriptor a struct and move this to formats_mtl.
static id<MTLDepthStencilState> CreateDepthStencilDescriptor(
const PipelineDescriptor& desc,
id<MTLDevice> device) {
auto descriptor = ToMTLDepthStencilDescriptor(
desc.GetDepthStencilAttachmentDescriptor(), //
desc.GetFrontStencilAttachmentDescriptor(), //
desc.GetBackStencilAttachmentDescriptor() //
);
return [device newDepthStencilStateWithDescriptor:descriptor];
}
// |PipelineLibrary|
bool PipelineLibraryMTL::IsValid() const {
return device_ != nullptr;
}
// |PipelineLibrary|
PipelineFuture<PipelineDescriptor> PipelineLibraryMTL::GetPipeline(
PipelineDescriptor descriptor) {
if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) {
return found->second;
}
if (!IsValid()) {
return {
descriptor,
RealizedFuture<std::shared_ptr<Pipeline<PipelineDescriptor>>>(nullptr)};
}
auto promise = std::make_shared<
std::promise<std::shared_ptr<Pipeline<PipelineDescriptor>>>>();
auto pipeline_future =
PipelineFuture<PipelineDescriptor>{descriptor, promise->get_future()};
pipelines_[descriptor] = pipeline_future;
auto weak_this = weak_from_this();
auto completion_handler =
^(id<MTLRenderPipelineState> _Nullable render_pipeline_state,
NSError* _Nullable error) {
if (error != nil) {
VALIDATION_LOG << "Could not create render pipeline for "
<< descriptor.GetLabel() << " :"
<< error.localizedDescription.UTF8String;
promise->set_value(nullptr);
return;
}
auto strong_this = weak_this.lock();
if (!strong_this) {
promise->set_value(nullptr);
return;
}
auto new_pipeline = std::shared_ptr<PipelineMTL>(new PipelineMTL(
weak_this,
descriptor, //
render_pipeline_state, //
CreateDepthStencilDescriptor(descriptor, device_) //
));
promise->set_value(new_pipeline);
};
GetMTLRenderPipelineDescriptor(
descriptor, [device = device_, completion_handler](
MTLRenderPipelineDescriptor* descriptor) {
[device newRenderPipelineStateWithDescriptor:descriptor
completionHandler:completion_handler];
});
return pipeline_future;
}
PipelineFuture<ComputePipelineDescriptor> PipelineLibraryMTL::GetPipeline(
ComputePipelineDescriptor descriptor) {
if (auto found = compute_pipelines_.find(descriptor);
found != compute_pipelines_.end()) {
return found->second;
}
if (!IsValid()) {
return {
descriptor,
RealizedFuture<std::shared_ptr<Pipeline<ComputePipelineDescriptor>>>(
nullptr)};
}
auto promise = std::make_shared<
std::promise<std::shared_ptr<Pipeline<ComputePipelineDescriptor>>>>();
auto pipeline_future = PipelineFuture<ComputePipelineDescriptor>{
descriptor, promise->get_future()};
compute_pipelines_[descriptor] = pipeline_future;
auto weak_this = weak_from_this();
auto completion_handler =
^(id<MTLComputePipelineState> _Nullable compute_pipeline_state,
MTLComputePipelineReflection* _Nullable reflection,
NSError* _Nullable error) {
if (error != nil) {
VALIDATION_LOG << "Could not create compute pipeline: "
<< error.localizedDescription.UTF8String;
promise->set_value(nullptr);
return;
}
auto strong_this = weak_this.lock();
if (!strong_this) {
VALIDATION_LOG << "Library was collected before a pending pipeline "
"creation could finish.";
promise->set_value(nullptr);
return;
}
auto new_pipeline = std::shared_ptr<ComputePipelineMTL>(
new ComputePipelineMTL(weak_this,
descriptor, //
compute_pipeline_state //
));
promise->set_value(new_pipeline);
};
[device_
newComputePipelineStateWithDescriptor:GetMTLComputePipelineDescriptor(
descriptor)
options:MTLPipelineOptionNone
completionHandler:completion_handler];
return pipeline_future;
}
// |PipelineLibrary|
void PipelineLibraryMTL::RemovePipelinesWithEntryPoint(
std::shared_ptr<const ShaderFunction> function) {
fml::erase_if(pipelines_, [&](auto item) {
return item->first.GetEntrypointForStage(function->GetStage())
->IsEqual(*function);
});
}
} // namespace impeller
| engine/impeller/renderer/backend/metal/pipeline_library_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/pipeline_library_mtl.mm",
"repo_id": "engine",
"token_count": 3522
} | 206 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/metal/texture_mtl.h"
#include <memory>
#include "impeller/base/validation.h"
#include "impeller/core/texture_descriptor.h"
namespace impeller {
std::shared_ptr<Texture> WrapperMTL(TextureDescriptor desc,
const void* mtl_texture,
std::function<void()> deletion_proc) {
return TextureMTL::Wrapper(desc, (__bridge id<MTLTexture>)mtl_texture,
std::move(deletion_proc));
}
TextureMTL::TextureMTL(TextureDescriptor p_desc,
const AcquireTextureProc& aquire_proc,
bool wrapped,
bool drawable)
: Texture(p_desc), aquire_proc_(aquire_proc), is_drawable_(drawable) {
const auto& desc = GetTextureDescriptor();
if (!desc.IsValid() || !aquire_proc) {
return;
}
if (desc.size != GetSize()) {
VALIDATION_LOG << "The texture and its descriptor disagree about its size.";
return;
}
is_wrapped_ = wrapped;
is_valid_ = true;
}
std::shared_ptr<TextureMTL> TextureMTL::Wrapper(
TextureDescriptor desc,
id<MTLTexture> texture,
std::function<void()> deletion_proc) {
if (deletion_proc) {
return std::shared_ptr<TextureMTL>(
new TextureMTL(
desc, [texture]() { return texture; }, true),
[deletion_proc = std::move(deletion_proc)](TextureMTL* t) {
deletion_proc();
delete t;
});
}
return std::shared_ptr<TextureMTL>(
new TextureMTL(desc, [texture]() { return texture; }, true));
}
std::shared_ptr<TextureMTL> TextureMTL::Create(TextureDescriptor desc,
id<MTLTexture> texture) {
return std::make_shared<TextureMTL>(desc, [texture]() { return texture; });
}
TextureMTL::~TextureMTL() = default;
void TextureMTL::SetLabel(std::string_view label) {
if (is_drawable_) {
return;
}
[aquire_proc_() setLabel:@(label.data())];
}
// |Texture|
bool TextureMTL::OnSetContents(std::shared_ptr<const fml::Mapping> mapping,
size_t slice) {
// Metal has no threading restrictions. So we can pass this data along to the
// client rendering API immediately.
return OnSetContents(mapping->GetMapping(), mapping->GetSize(), slice);
}
// |Texture|
bool TextureMTL::OnSetContents(const uint8_t* contents,
size_t length,
size_t slice) {
if (!IsValid() || !contents || is_wrapped_ || is_drawable_) {
return false;
}
const auto& desc = GetTextureDescriptor();
// Out of bounds access.
if (length != desc.GetByteSizeOfBaseMipLevel()) {
return false;
}
const auto region =
MTLRegionMake2D(0u, 0u, desc.size.width, desc.size.height);
[aquire_proc_() replaceRegion:region //
mipmapLevel:0u //
slice:slice //
withBytes:contents //
bytesPerRow:desc.GetBytesPerRow() //
bytesPerImage:desc.GetByteSizeOfBaseMipLevel() //
];
return true;
}
ISize TextureMTL::GetSize() const {
if (is_drawable_) {
return GetTextureDescriptor().size;
}
const auto& texture = aquire_proc_();
return {static_cast<ISize::Type>(texture.width),
static_cast<ISize::Type>(texture.height)};
}
id<MTLTexture> TextureMTL::GetMTLTexture() const {
return aquire_proc_();
}
bool TextureMTL::IsValid() const {
return is_valid_;
}
bool TextureMTL::IsWrapped() const {
return is_wrapped_;
}
bool TextureMTL::IsDrawable() const {
return is_drawable_;
}
bool TextureMTL::GenerateMipmap(id<MTLBlitCommandEncoder> encoder) {
if (is_drawable_) {
return false;
}
auto texture = aquire_proc_();
if (!texture) {
return false;
}
[encoder generateMipmapsForTexture:texture];
mipmap_generated_ = true;
return true;
}
} // namespace impeller
| engine/impeller/renderer/backend/metal/texture_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/texture_mtl.mm",
"repo_id": "engine",
"token_count": 1890
} | 207 |
// Copyright 2013 The Flutter 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 "impeller/renderer/backend/vulkan/blit_command_vk.h"
#include "impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h"
namespace impeller {
namespace testing {
TEST(BlitCommandVkTest, BlitCopyTextureToTextureCommandVK) {
auto context = MockVulkanContextBuilder().Build();
auto pool = context->GetCommandPoolRecycler()->Get();
auto encoder = std::make_unique<CommandEncoderFactoryVK>(context)->Create();
BlitCopyTextureToTextureCommandVK cmd;
cmd.source = context->GetResourceAllocator()->CreateTexture({
.format = PixelFormat::kR8G8B8A8UNormInt,
.size = ISize(100, 100),
});
cmd.destination = context->GetResourceAllocator()->CreateTexture({
.format = PixelFormat::kR8G8B8A8UNormInt,
.size = ISize(100, 100),
});
bool result = cmd.Encode(*encoder.get());
EXPECT_TRUE(result);
EXPECT_TRUE(encoder->IsTracking(cmd.source));
EXPECT_TRUE(encoder->IsTracking(cmd.destination));
}
TEST(BlitCommandVkTest, BlitCopyTextureToBufferCommandVK) {
auto context = MockVulkanContextBuilder().Build();
auto encoder = std::make_unique<CommandEncoderFactoryVK>(context)->Create();
BlitCopyTextureToBufferCommandVK cmd;
cmd.source = context->GetResourceAllocator()->CreateTexture({
.format = PixelFormat::kR8G8B8A8UNormInt,
.size = ISize(100, 100),
});
cmd.destination = context->GetResourceAllocator()->CreateBuffer({
.size = 1,
});
bool result = cmd.Encode(*encoder.get());
EXPECT_TRUE(result);
EXPECT_TRUE(encoder->IsTracking(cmd.source));
EXPECT_TRUE(encoder->IsTracking(cmd.destination));
}
TEST(BlitCommandVkTest, BlitCopyBufferToTextureCommandVK) {
auto context = MockVulkanContextBuilder().Build();
auto encoder = std::make_unique<CommandEncoderFactoryVK>(context)->Create();
BlitCopyBufferToTextureCommandVK cmd;
cmd.destination = context->GetResourceAllocator()->CreateTexture({
.format = PixelFormat::kR8G8B8A8UNormInt,
.size = ISize(100, 100),
});
cmd.source =
DeviceBuffer::AsBufferView(context->GetResourceAllocator()->CreateBuffer({
.size = 1,
}));
bool result = cmd.Encode(*encoder.get());
EXPECT_TRUE(result);
EXPECT_TRUE(encoder->IsTracking(cmd.source.buffer));
EXPECT_TRUE(encoder->IsTracking(cmd.destination));
}
TEST(BlitCommandVkTest, BlitGenerateMipmapCommandVK) {
auto context = MockVulkanContextBuilder().Build();
auto encoder = std::make_unique<CommandEncoderFactoryVK>(context)->Create();
BlitGenerateMipmapCommandVK cmd;
cmd.texture = context->GetResourceAllocator()->CreateTexture({
.format = PixelFormat::kR8G8B8A8UNormInt,
.size = ISize(100, 100),
.mip_count = 2,
});
bool result = cmd.Encode(*encoder.get());
EXPECT_TRUE(result);
EXPECT_TRUE(encoder->IsTracking(cmd.texture));
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/blit_command_vk_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/blit_command_vk_unittests.cc",
"repo_id": "engine",
"token_count": 1130
} | 208 |
// Copyright 2013 The Flutter 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_COMPUTE_PASS_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PASS_VK_H_
#include "impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/compute_pass.h"
namespace impeller {
class CommandBufferVK;
class ComputePassVK final : public ComputePass {
public:
// |ComputePass|
~ComputePassVK() override;
private:
friend class CommandBufferVK;
std::shared_ptr<CommandBufferVK> command_buffer_;
std::string label_;
std::array<uint32_t, 3> max_wg_size_ = {};
bool is_valid_ = false;
// Per-command state.
std::array<vk::DescriptorImageInfo, kMaxBindings> image_workspace_;
std::array<vk::DescriptorBufferInfo, kMaxBindings> buffer_workspace_;
std::array<vk::WriteDescriptorSet, kMaxBindings + kMaxBindings>
write_workspace_;
size_t bound_image_offset_ = 0u;
size_t bound_buffer_offset_ = 0u;
size_t descriptor_write_offset_ = 0u;
bool has_label_ = false;
bool pipeline_valid_ = false;
vk::DescriptorSet descriptor_set_ = {};
vk::PipelineLayout pipeline_layout_ = {};
ComputePassVK(std::shared_ptr<const Context> context,
std::shared_ptr<CommandBufferVK> command_buffer);
// |ComputePass|
bool IsValid() const override;
// |ComputePass|
void OnSetLabel(const std::string& label) override;
// |ComputePass|
bool EncodeCommands() const override;
// |ComputePass|
void SetCommandLabel(std::string_view label) override;
// |ComputePass|
void SetPipeline(const std::shared_ptr<Pipeline<ComputePipelineDescriptor>>&
pipeline) override;
// |ComputePass|
void AddBufferMemoryBarrier() override;
// |ComputePass|
void AddTextureMemoryBarrier() override;
// |ComputePass|
fml::Status Compute(const ISize& grid_size) override;
// |ResourceBinder|
bool BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) override;
// |ResourceBinder|
bool BindResource(ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) override;
bool BindResource(size_t binding,
DescriptorType type,
const BufferView& view);
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PASS_VK_H_
| engine/impeller/renderer/backend/vulkan/compute_pass_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/compute_pass_vk.h",
"repo_id": "engine",
"token_count": 1140
} | 209 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/playground/playground_test.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/surface_context_vk.h"
namespace impeller::testing {
using DriverInfoVKTest = PlaygroundTest;
INSTANTIATE_VULKAN_PLAYGROUND_SUITE(DriverInfoVKTest);
TEST_P(DriverInfoVKTest, CanQueryDriverInfo) {
ASSERT_TRUE(GetContext());
const auto& driver_info =
SurfaceContextVK::Cast(*GetContext()).GetParent().GetDriverInfo();
ASSERT_NE(driver_info, nullptr);
// 1.1 is the base Impeller version. The driver can't be lower than that.
ASSERT_TRUE(driver_info->GetAPIVersion().IsAtLeast(Version{1, 1, 0}));
ASSERT_NE(driver_info->GetVendor(), VendorVK::kUnknown);
ASSERT_NE(driver_info->GetDeviceType(), DeviceTypeVK::kUnknown);
ASSERT_NE(driver_info->GetDriverName(), "");
}
} // namespace impeller::testing
| engine/impeller/renderer/backend/vulkan/driver_info_vk_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/driver_info_vk_unittests.cc",
"repo_id": "engine",
"token_count": 354
} | 210 |
// Copyright 2013 The Flutter 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_QUEUE_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_QUEUE_VK_H_
#include <memory>
#include "impeller/base/thread.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
struct QueueIndexVK {
size_t family = 0;
size_t index = 0;
constexpr bool operator==(const QueueIndexVK& other) const {
return family == other.family && index == other.index;
}
};
//------------------------------------------------------------------------------
/// @brief A thread safe object that can be used to access device queues.
/// If multiple objects are created with the same underlying queue,
/// then the external synchronization guarantees of Vulkan queues
/// cannot be met. So care must be taken the same device queue
/// doesn't form the basis of multiple `QueueVK`s.
///
class QueueVK {
public:
QueueVK(QueueIndexVK index, vk::Queue queue);
~QueueVK();
const QueueIndexVK& GetIndex() const;
vk::Result Submit(const vk::SubmitInfo& submit_info,
const vk::Fence& fence) const;
vk::Result Present(const vk::PresentInfoKHR& present_info);
void InsertDebugMarker(std::string_view label) const;
private:
mutable Mutex queue_mutex_;
const QueueIndexVK index_;
const vk::Queue queue_ IPLR_GUARDED_BY(queue_mutex_);
QueueVK(const QueueVK&) = delete;
QueueVK& operator=(const QueueVK&) = delete;
};
//------------------------------------------------------------------------------
/// @brief The collection of queues used by the context. The queues may all
/// be the same.
///
struct QueuesVK {
std::shared_ptr<QueueVK> graphics_queue;
std::shared_ptr<QueueVK> compute_queue;
std::shared_ptr<QueueVK> transfer_queue;
QueuesVK();
QueuesVK(const vk::Device& device,
QueueIndexVK graphics,
QueueIndexVK compute,
QueueIndexVK transfer);
bool IsValid() const;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_QUEUE_VK_H_
| engine/impeller/renderer/backend/vulkan/queue_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/queue_vk.h",
"repo_id": "engine",
"token_count": 798
} | 211 |
// Copyright 2013 The Flutter 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_SHADER_LIBRARY_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_LIBRARY_VK_H_
#include "flutter/fml/macros.h"
#include "impeller/base/comparable.h"
#include "impeller/base/thread.h"
#include "impeller/renderer/backend/vulkan/device_holder_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/shader_key.h"
#include "impeller/renderer/shader_library.h"
namespace impeller {
class ShaderLibraryVK final : public ShaderLibrary {
public:
// |ShaderLibrary|
~ShaderLibraryVK() override;
// |ShaderLibrary|
bool IsValid() const override;
private:
friend class ContextVK;
std::weak_ptr<DeviceHolderVK> device_holder_;
const UniqueID library_id_;
mutable RWMutex functions_mutex_;
ShaderFunctionMap functions_ IPLR_GUARDED_BY(functions_mutex_);
bool is_valid_ = false;
ShaderLibraryVK(
std::weak_ptr<DeviceHolderVK> device_holder,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data);
// |ShaderLibrary|
std::shared_ptr<const ShaderFunction> GetFunction(std::string_view name,
ShaderStage stage) override;
// |ShaderLibrary|
void RegisterFunction(std::string name,
ShaderStage stage,
std::shared_ptr<fml::Mapping> code,
RegistrationCallback callback) override;
bool RegisterFunction(const std::string& name,
ShaderStage stage,
const std::shared_ptr<fml::Mapping>& code);
// |ShaderLibrary|
void UnregisterFunction(std::string name, ShaderStage stage) override;
ShaderLibraryVK(const ShaderLibraryVK&) = delete;
ShaderLibraryVK& operator=(const ShaderLibraryVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_LIBRARY_VK_H_
| engine/impeller/renderer/backend/vulkan/shader_library_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/shader_library_vk.h",
"repo_id": "engine",
"token_count": 848
} | 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 "impeller/renderer/backend/vulkan/test/mock_vulkan.h"
#include <cstdint>
#include <cstring>
#include <utility>
#include <vector>
#include "impeller/base/thread_safety.h"
#include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep.
#include "third_party/swiftshader/include/vulkan/vulkan_core.h"
#include "vulkan/vulkan.hpp"
#include "vulkan/vulkan_core.h"
namespace impeller {
namespace testing {
namespace {
struct MockCommandBuffer {
explicit MockCommandBuffer(
std::shared_ptr<std::vector<std::string>> called_functions)
: called_functions_(std::move(called_functions)) {}
std::shared_ptr<std::vector<std::string>> called_functions_;
};
struct MockQueryPool {};
struct MockCommandPool {};
struct MockDescriptorPool {};
struct MockSurfaceKHR {};
struct MockImage {};
struct MockSwapchainKHR {
std::array<MockImage, 3> images;
size_t current_image = 0;
};
struct MockSemaphore {};
struct MockFramebuffer {};
static ISize currentImageSize = ISize{1, 1};
class MockDevice final {
public:
explicit MockDevice() : called_functions_(new std::vector<std::string>()) {}
MockCommandBuffer* NewCommandBuffer() {
auto buffer = std::make_unique<MockCommandBuffer>(called_functions_);
MockCommandBuffer* result = buffer.get();
Lock lock(command_buffers_mutex_);
command_buffers_.emplace_back(std::move(buffer));
return result;
}
MockCommandPool* NewCommandPool() {
auto pool = std::make_unique<MockCommandPool>();
MockCommandPool* result = pool.get();
Lock lock(commmand_pools_mutex_);
command_pools_.emplace_back(std::move(pool));
return result;
}
void DeleteCommandPool(MockCommandPool* pool) {
Lock lock(commmand_pools_mutex_);
auto it = std::find_if(command_pools_.begin(), command_pools_.end(),
[pool](const std::unique_ptr<MockCommandPool>& p) {
return p.get() == pool;
});
if (it != command_pools_.end()) {
command_pools_.erase(it);
}
}
const std::shared_ptr<std::vector<std::string>>& GetCalledFunctions() {
return called_functions_;
}
void AddCalledFunction(const std::string& function) {
Lock lock(called_functions_mutex_);
called_functions_->push_back(function);
}
private:
MockDevice(const MockDevice&) = delete;
MockDevice& operator=(const MockDevice&) = delete;
Mutex called_functions_mutex_;
std::shared_ptr<std::vector<std::string>> called_functions_ IPLR_GUARDED_BY(
called_functions_mutex_);
Mutex command_buffers_mutex_;
std::vector<std::unique_ptr<MockCommandBuffer>> command_buffers_
IPLR_GUARDED_BY(command_buffers_mutex_);
Mutex commmand_pools_mutex_;
std::vector<std::unique_ptr<MockCommandPool>> command_pools_ IPLR_GUARDED_BY(
commmand_pools_mutex_);
};
void noop() {}
static thread_local std::vector<std::string> g_instance_extensions;
VkResult vkEnumerateInstanceExtensionProperties(
const char* pLayerName,
uint32_t* pPropertyCount,
VkExtensionProperties* pProperties) {
if (!pProperties) {
*pPropertyCount = g_instance_extensions.size();
} else {
uint32_t count = 0;
for (const std::string& ext : g_instance_extensions) {
strncpy(pProperties[count].extensionName, ext.c_str(),
sizeof(VkExtensionProperties::extensionName));
pProperties[count].specVersion = 0;
count++;
}
}
return VK_SUCCESS;
}
static thread_local std::vector<std::string> g_instance_layers;
VkResult vkEnumerateInstanceLayerProperties(uint32_t* pPropertyCount,
VkLayerProperties* pProperties) {
if (!pProperties) {
*pPropertyCount = g_instance_layers.size();
} else {
uint32_t count = 0;
for (const std::string& layer : g_instance_layers) {
strncpy(pProperties[count].layerName, layer.c_str(),
sizeof(VkLayerProperties::layerName));
pProperties[count].specVersion = 0;
count++;
}
}
return VK_SUCCESS;
}
VkResult vkEnumeratePhysicalDevices(VkInstance instance,
uint32_t* pPhysicalDeviceCount,
VkPhysicalDevice* pPhysicalDevices) {
if (!pPhysicalDevices) {
*pPhysicalDeviceCount = 1;
} else {
pPhysicalDevices[0] = reinterpret_cast<VkPhysicalDevice>(0xfeedface);
}
return VK_SUCCESS;
}
static thread_local std::function<void(VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties* pFormatProperties)>
g_format_properties_callback;
void vkGetPhysicalDeviceFormatProperties(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties* pFormatProperties) {
g_format_properties_callback(physicalDevice, format, pFormatProperties);
}
void vkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties* pProperties) {
pProperties->limits.framebufferColorSampleCounts =
static_cast<VkSampleCountFlags>(VK_SAMPLE_COUNT_1_BIT |
VK_SAMPLE_COUNT_4_BIT);
pProperties->limits.maxImageDimension2D = 4096;
pProperties->limits.timestampPeriod = 1;
}
void vkGetPhysicalDeviceQueueFamilyProperties(
VkPhysicalDevice physicalDevice,
uint32_t* pQueueFamilyPropertyCount,
VkQueueFamilyProperties* pQueueFamilyProperties) {
if (!pQueueFamilyProperties) {
*pQueueFamilyPropertyCount = 1;
} else {
pQueueFamilyProperties[0].queueCount = 3;
pQueueFamilyProperties[0].queueFlags = static_cast<VkQueueFlags>(
VK_QUEUE_TRANSFER_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT);
}
}
VkResult vkEnumerateDeviceExtensionProperties(
VkPhysicalDevice physicalDevice,
const char* pLayerName,
uint32_t* pPropertyCount,
VkExtensionProperties* pProperties) {
if (!pProperties) {
*pPropertyCount = 1;
} else {
strcpy(pProperties[0].extensionName, "VK_KHR_swapchain");
pProperties[0].specVersion = 0;
}
return VK_SUCCESS;
}
VkResult vkCreateDevice(VkPhysicalDevice physicalDevice,
const VkDeviceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDevice* pDevice) {
*pDevice = reinterpret_cast<VkDevice>(new MockDevice());
return VK_SUCCESS;
}
VkResult vkCreateInstance(const VkInstanceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkInstance* pInstance) {
*pInstance = reinterpret_cast<VkInstance>(0xbaadf00d);
return VK_SUCCESS;
}
void vkGetPhysicalDeviceMemoryProperties(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties* pMemoryProperties) {
pMemoryProperties->memoryTypeCount = 2;
pMemoryProperties->memoryHeapCount = 2;
pMemoryProperties->memoryTypes[0].heapIndex = 0;
pMemoryProperties->memoryTypes[0].propertyFlags =
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
pMemoryProperties->memoryTypes[1].heapIndex = 1;
pMemoryProperties->memoryTypes[1].propertyFlags =
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
pMemoryProperties->memoryHeaps[0].size = 1024 * 1024 * 1024;
pMemoryProperties->memoryHeaps[0].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
pMemoryProperties->memoryHeaps[1].size = 1024 * 1024 * 1024;
pMemoryProperties->memoryHeaps[1].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
}
VkResult vkCreatePipelineCache(VkDevice device,
const VkPipelineCacheCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineCache* pPipelineCache) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkCreatePipelineCache");
*pPipelineCache = reinterpret_cast<VkPipelineCache>(0xb000dead);
return VK_SUCCESS;
}
VkResult vkCreateCommandPool(VkDevice device,
const VkCommandPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkCommandPool* pCommandPool) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkCreateCommandPool");
*pCommandPool =
reinterpret_cast<VkCommandPool>(mock_device->NewCommandPool());
return VK_SUCCESS;
}
VkResult vkResetCommandPool(VkDevice device,
VkCommandPool commandPool,
VkCommandPoolResetFlags flags) {
return VK_SUCCESS;
}
VkResult vkAllocateCommandBuffers(
VkDevice device,
const VkCommandBufferAllocateInfo* pAllocateInfo,
VkCommandBuffer* pCommandBuffers) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkAllocateCommandBuffers");
*pCommandBuffers =
reinterpret_cast<VkCommandBuffer>(mock_device->NewCommandBuffer());
return VK_SUCCESS;
}
VkResult vkBeginCommandBuffer(VkCommandBuffer commandBuffer,
const VkCommandBufferBeginInfo* pBeginInfo) {
return VK_SUCCESS;
}
VkResult vkCreateImage(VkDevice device,
const VkImageCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImage* pImage) {
*pImage = reinterpret_cast<VkImage>(0xD0D0CACA);
return VK_SUCCESS;
}
void vkGetImageMemoryRequirements2KHR(
VkDevice device,
const VkImageMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) {
pMemoryRequirements->memoryRequirements.size = 1024;
pMemoryRequirements->memoryRequirements.memoryTypeBits = 1;
}
VkResult vkAllocateMemory(VkDevice device,
const VkMemoryAllocateInfo* pAllocateInfo,
const VkAllocationCallbacks* pAllocator,
VkDeviceMemory* pMemory) {
*pMemory = reinterpret_cast<VkDeviceMemory>(0xCAFEB0BA);
return VK_SUCCESS;
}
VkResult vkBindImageMemory(VkDevice device,
VkImage image,
VkDeviceMemory memory,
VkDeviceSize memoryOffset) {
return VK_SUCCESS;
}
VkResult vkCreateImageView(VkDevice device,
const VkImageViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImageView* pView) {
*pView = reinterpret_cast<VkImageView>(0xFEE1DEAD);
return VK_SUCCESS;
}
VkResult vkCreateBuffer(VkDevice device,
const VkBufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBuffer* pBuffer) {
*pBuffer = reinterpret_cast<VkBuffer>(0xDEADDEAD);
return VK_SUCCESS;
}
void vkGetBufferMemoryRequirements2KHR(
VkDevice device,
const VkBufferMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) {
pMemoryRequirements->memoryRequirements.size = 1024;
pMemoryRequirements->memoryRequirements.memoryTypeBits = 1;
}
VkResult vkBindBufferMemory(VkDevice device,
VkBuffer buffer,
VkDeviceMemory memory,
VkDeviceSize memoryOffset) {
return VK_SUCCESS;
}
VkResult vkCreateRenderPass(VkDevice device,
const VkRenderPassCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass) {
*pRenderPass = reinterpret_cast<VkRenderPass>(0x12341234);
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkCreateRenderPass");
return VK_SUCCESS;
}
VkResult vkCreateDescriptorSetLayout(
VkDevice device,
const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorSetLayout* pSetLayout) {
*pSetLayout = reinterpret_cast<VkDescriptorSetLayout>(0x77777777);
return VK_SUCCESS;
}
VkResult vkCreatePipelineLayout(VkDevice device,
const VkPipelineLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineLayout* pPipelineLayout) {
*pPipelineLayout = reinterpret_cast<VkPipelineLayout>(0x88888888);
return VK_SUCCESS;
}
VkResult vkCreateGraphicsPipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkCreateGraphicsPipelines");
*pPipelines = reinterpret_cast<VkPipeline>(0x99999999);
return VK_SUCCESS;
}
void vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* pAllocator) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkDestroyDevice");
delete reinterpret_cast<MockDevice*>(device);
}
void vkDestroyPipeline(VkDevice device,
VkPipeline pipeline,
const VkAllocationCallbacks* pAllocator) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkDestroyPipeline");
}
VkResult vkCreateShaderModule(VkDevice device,
const VkShaderModuleCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkShaderModule* pShaderModule) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkCreateShaderModule");
*pShaderModule = reinterpret_cast<VkShaderModule>(0x11111111);
return VK_SUCCESS;
}
void vkDestroyShaderModule(VkDevice device,
VkShaderModule shaderModule,
const VkAllocationCallbacks* pAllocator) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkDestroyShaderModule");
}
void vkDestroyPipelineCache(VkDevice device,
VkPipelineCache pipelineCache,
const VkAllocationCallbacks* pAllocator) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkDestroyPipelineCache");
}
void vkDestroySurfaceKHR(VkInstance instance,
VkSurfaceKHR surface,
const VkAllocationCallbacks* pAllocator) {
return;
}
void vkCmdBindPipeline(VkCommandBuffer commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
VkPipeline pipeline) {
MockCommandBuffer* mock_command_buffer =
reinterpret_cast<MockCommandBuffer*>(commandBuffer);
mock_command_buffer->called_functions_->push_back("vkCmdBindPipeline");
}
void vkCmdSetStencilReference(VkCommandBuffer commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t reference) {
MockCommandBuffer* mock_command_buffer =
reinterpret_cast<MockCommandBuffer*>(commandBuffer);
mock_command_buffer->called_functions_->push_back("vkCmdSetStencilReference");
}
void vkCmdSetScissor(VkCommandBuffer commandBuffer,
uint32_t firstScissor,
uint32_t scissorCount,
const VkRect2D* pScissors) {
MockCommandBuffer* mock_command_buffer =
reinterpret_cast<MockCommandBuffer*>(commandBuffer);
mock_command_buffer->called_functions_->push_back("vkCmdSetScissor");
}
void vkCmdSetViewport(VkCommandBuffer commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const VkViewport* pViewports) {
MockCommandBuffer* mock_command_buffer =
reinterpret_cast<MockCommandBuffer*>(commandBuffer);
mock_command_buffer->called_functions_->push_back("vkCmdSetViewport");
}
void vkFreeCommandBuffers(VkDevice device,
VkCommandPool commandPool,
uint32_t commandBufferCount,
const VkCommandBuffer* pCommandBuffers) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkFreeCommandBuffers");
}
void vkDestroyCommandPool(VkDevice device,
VkCommandPool commandPool,
const VkAllocationCallbacks* pAllocator) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->DeleteCommandPool(
reinterpret_cast<MockCommandPool*>(commandPool));
mock_device->AddCalledFunction("vkDestroyCommandPool");
}
VkResult vkEndCommandBuffer(VkCommandBuffer commandBuffer) {
return VK_SUCCESS;
}
VkResult vkCreateFence(VkDevice device,
const VkFenceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
*pFence = reinterpret_cast<VkFence>(new MockFence());
return VK_SUCCESS;
}
VkResult vkDestroyFence(VkDevice device,
VkFence fence,
const VkAllocationCallbacks* pAllocator) {
delete reinterpret_cast<MockFence*>(fence);
return VK_SUCCESS;
}
VkResult vkQueueSubmit(VkQueue queue,
uint32_t submitCount,
const VkSubmitInfo* pSubmits,
VkFence fence) {
return VK_SUCCESS;
}
VkResult vkWaitForFences(VkDevice device,
uint32_t fenceCount,
const VkFence* pFences,
VkBool32 waitAll,
uint64_t timeout) {
return VK_SUCCESS;
}
VkResult vkGetFenceStatus(VkDevice device, VkFence fence) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
MockFence* mock_fence = reinterpret_cast<MockFence*>(fence);
return mock_fence->GetStatus();
}
VkResult vkResetFences(VkDevice device,
uint32_t fenceCount,
const VkFence* fences) {
return VK_SUCCESS;
}
VkResult vkCreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugUtilsMessengerEXT* pMessenger) {
return VK_SUCCESS;
}
VkResult vkSetDebugUtilsObjectNameEXT(
VkDevice device,
const VkDebugUtilsObjectNameInfoEXT* pNameInfo) {
return VK_SUCCESS;
}
VkResult vkCreateQueryPool(VkDevice device,
const VkQueryPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkQueryPool* pQueryPool) {
*pQueryPool = reinterpret_cast<VkQueryPool>(new MockQueryPool());
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkCreateQueryPool");
return VK_SUCCESS;
}
void vkDestroyQueryPool(VkDevice device,
VkQueryPool queryPool,
const VkAllocationCallbacks* pAllocator) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkDestroyQueryPool");
delete reinterpret_cast<MockQueryPool*>(queryPool);
}
VkResult vkGetQueryPoolResults(VkDevice device,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount,
size_t dataSize,
void* pData,
VkDeviceSize stride,
VkQueryResultFlags flags) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
if (dataSize == sizeof(uint32_t)) {
uint32_t* data = static_cast<uint32_t*>(pData);
for (auto i = firstQuery; i < queryCount; i++) {
data[0] = i;
}
} else if (dataSize == sizeof(int64_t)) {
uint64_t* data = static_cast<uint64_t*>(pData);
for (auto i = firstQuery; i < queryCount; i++) {
data[0] = i;
}
}
mock_device->AddCalledFunction("vkGetQueryPoolResults");
return VK_SUCCESS;
}
VkResult vkCreateDescriptorPool(VkDevice device,
const VkDescriptorPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorPool* pDescriptorPool) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
*pDescriptorPool =
reinterpret_cast<VkDescriptorPool>(new MockDescriptorPool());
mock_device->AddCalledFunction("vkCreateDescriptorPool");
return VK_SUCCESS;
}
void vkDestroyDescriptorPool(VkDevice device,
VkDescriptorPool descriptorPool,
const VkAllocationCallbacks* pAllocator) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkDestroyDescriptorPool");
delete reinterpret_cast<MockDescriptorPool*>(descriptorPool);
}
VkResult vkResetDescriptorPool(VkDevice device,
VkDescriptorPool descriptorPool,
VkDescriptorPoolResetFlags flags) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkResetDescriptorPool");
return VK_SUCCESS;
}
VkResult vkAllocateDescriptorSets(
VkDevice device,
const VkDescriptorSetAllocateInfo* pAllocateInfo,
VkDescriptorSet* pDescriptorSets) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
mock_device->AddCalledFunction("vkAllocateDescriptorSets");
return VK_SUCCESS;
}
VkResult vkGetPhysicalDeviceSurfaceFormatsKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
uint32_t* pSurfaceFormatCount,
VkSurfaceFormatKHR* pSurfaceFormats) {
*pSurfaceFormatCount = 1u;
if (pSurfaceFormats != nullptr) {
pSurfaceFormats[0] =
VkSurfaceFormatKHR{.format = VK_FORMAT_R8G8B8A8_UNORM,
.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
}
return VK_SUCCESS;
}
VkResult vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
VkSurfaceCapabilitiesKHR* pSurfaceCapabilities) {
*pSurfaceCapabilities = VkSurfaceCapabilitiesKHR{
.minImageCount = 3,
.maxImageCount = 6,
.currentExtent =
VkExtent2D{
.width = static_cast<uint32_t>(currentImageSize.width),
.height = static_cast<uint32_t>(currentImageSize.height),
},
.minImageExtent =
VkExtent2D{
.width = 0,
.height = 0,
},
.maxImageExtent =
VkExtent2D{
.width = static_cast<uint32_t>(currentImageSize.width),
.height = static_cast<uint32_t>(currentImageSize.height),
},
.maxImageArrayLayers = 1,
.supportedTransforms =
VkSurfaceTransformFlagBitsKHR::VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
.currentTransform =
VkSurfaceTransformFlagBitsKHR::VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
.supportedCompositeAlpha = VkCompositeAlphaFlagBitsKHR::
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
.supportedUsageFlags =
VkImageUsageFlagBits::VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT};
return VK_SUCCESS;
}
VkResult vkGetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
VkSurfaceKHR surface,
VkBool32* pSupported) {
*pSupported = VK_TRUE;
return VK_SUCCESS;
}
VkResult vkCreateSwapchainKHR(VkDevice device,
const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchain) {
*pSwapchain = reinterpret_cast<VkSwapchainKHR>(new MockSwapchainKHR());
return VK_SUCCESS;
}
void vkDestroySwapchainKHR(VkDevice device,
VkSwapchainKHR swapchain,
const VkAllocationCallbacks* pAllocator) {
delete reinterpret_cast<MockSwapchainKHR*>(swapchain);
}
VkResult vkGetSwapchainImagesKHR(VkDevice device,
VkSwapchainKHR swapchain,
uint32_t* pSwapchainImageCount,
VkImage* pSwapchainImages) {
MockSwapchainKHR* mock_swapchain =
reinterpret_cast<MockSwapchainKHR*>(swapchain);
auto& images = mock_swapchain->images;
*pSwapchainImageCount = images.size();
if (pSwapchainImages != nullptr) {
for (size_t i = 0; i < images.size(); i++) {
pSwapchainImages[i] = reinterpret_cast<VkImage>(&images[i]);
}
}
return VK_SUCCESS;
}
VkResult vkCreateSemaphore(VkDevice device,
const VkSemaphoreCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSemaphore* pSemaphore) {
*pSemaphore = reinterpret_cast<VkSemaphore>(new MockSemaphore());
return VK_SUCCESS;
}
void vkDestroySemaphore(VkDevice device,
VkSemaphore semaphore,
const VkAllocationCallbacks* pAllocator) {
delete reinterpret_cast<MockSemaphore*>(semaphore);
}
VkResult vkAcquireNextImageKHR(VkDevice device,
VkSwapchainKHR swapchain,
uint64_t timeout,
VkSemaphore semaphore,
VkFence fence,
uint32_t* pImageIndex) {
auto current_index =
reinterpret_cast<MockSwapchainKHR*>(swapchain)->current_image++;
*pImageIndex = (current_index + 1) % 3u;
return VK_SUCCESS;
}
VkResult vkCreateFramebuffer(VkDevice device,
const VkFramebufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFramebuffer* pFramebuffer) {
*pFramebuffer = reinterpret_cast<VkFramebuffer>(new MockFramebuffer());
return VK_SUCCESS;
}
void vkDestroyFramebuffer(VkDevice device,
VkFramebuffer framebuffer,
const VkAllocationCallbacks* pAllocator) {
delete reinterpret_cast<MockFramebuffer*>(framebuffer);
}
PFN_vkVoidFunction GetMockVulkanProcAddress(VkInstance instance,
const char* pName) {
if (strcmp("vkEnumerateInstanceExtensionProperties", pName) == 0) {
return (PFN_vkVoidFunction)vkEnumerateInstanceExtensionProperties;
} else if (strcmp("vkEnumerateInstanceLayerProperties", pName) == 0) {
return (PFN_vkVoidFunction)vkEnumerateInstanceLayerProperties;
} else if (strcmp("vkEnumeratePhysicalDevices", pName) == 0) {
return (PFN_vkVoidFunction)vkEnumeratePhysicalDevices;
} else if (strcmp("vkGetPhysicalDeviceFormatProperties", pName) == 0) {
return (PFN_vkVoidFunction)vkGetPhysicalDeviceFormatProperties;
} else if (strcmp("vkGetPhysicalDeviceProperties", pName) == 0) {
return (PFN_vkVoidFunction)vkGetPhysicalDeviceProperties;
} else if (strcmp("vkGetPhysicalDeviceQueueFamilyProperties", pName) == 0) {
return (PFN_vkVoidFunction)vkGetPhysicalDeviceQueueFamilyProperties;
} else if (strcmp("vkEnumerateDeviceExtensionProperties", pName) == 0) {
return (PFN_vkVoidFunction)vkEnumerateDeviceExtensionProperties;
} else if (strcmp("vkCreateDevice", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateDevice;
} else if (strcmp("vkCreateInstance", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateInstance;
} else if (strcmp("vkGetPhysicalDeviceMemoryProperties", pName) == 0) {
return (PFN_vkVoidFunction)vkGetPhysicalDeviceMemoryProperties;
} else if (strcmp("vkCreatePipelineCache", pName) == 0) {
return (PFN_vkVoidFunction)vkCreatePipelineCache;
} else if (strcmp("vkCreateCommandPool", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateCommandPool;
} else if (strcmp("vkResetCommandPool", pName) == 0) {
return (PFN_vkVoidFunction)vkResetCommandPool;
} else if (strcmp("vkAllocateCommandBuffers", pName) == 0) {
return (PFN_vkVoidFunction)vkAllocateCommandBuffers;
} else if (strcmp("vkBeginCommandBuffer", pName) == 0) {
return (PFN_vkVoidFunction)vkBeginCommandBuffer;
} else if (strcmp("vkCreateImage", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateImage;
} else if (strcmp("vkGetInstanceProcAddr", pName) == 0) {
return (PFN_vkVoidFunction)GetMockVulkanProcAddress;
} else if (strcmp("vkGetDeviceProcAddr", pName) == 0) {
return (PFN_vkVoidFunction)GetMockVulkanProcAddress;
} else if (strcmp("vkGetImageMemoryRequirements2KHR", pName) == 0 ||
strcmp("vkGetImageMemoryRequirements2", pName) == 0) {
return (PFN_vkVoidFunction)vkGetImageMemoryRequirements2KHR;
} else if (strcmp("vkAllocateMemory", pName) == 0) {
return (PFN_vkVoidFunction)vkAllocateMemory;
} else if (strcmp("vkBindImageMemory", pName) == 0) {
return (PFN_vkVoidFunction)vkBindImageMemory;
} else if (strcmp("vkCreateImageView", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateImageView;
} else if (strcmp("vkCreateBuffer", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateBuffer;
} else if (strcmp("vkGetBufferMemoryRequirements2KHR", pName) == 0 ||
strcmp("vkGetBufferMemoryRequirements2", pName) == 0) {
return (PFN_vkVoidFunction)vkGetBufferMemoryRequirements2KHR;
} else if (strcmp("vkBindBufferMemory", pName) == 0) {
return (PFN_vkVoidFunction)vkBindBufferMemory;
} else if (strcmp("vkCreateRenderPass", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateRenderPass;
} else if (strcmp("vkCreateDescriptorSetLayout", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateDescriptorSetLayout;
} else if (strcmp("vkCreatePipelineLayout", pName) == 0) {
return (PFN_vkVoidFunction)vkCreatePipelineLayout;
} else if (strcmp("vkCreateGraphicsPipelines", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateGraphicsPipelines;
} else if (strcmp("vkDestroyDevice", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyDevice;
} else if (strcmp("vkDestroyPipeline", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyPipeline;
} else if (strcmp("vkCreateShaderModule", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateShaderModule;
} else if (strcmp("vkDestroyShaderModule", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyShaderModule;
} else if (strcmp("vkDestroyPipelineCache", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyPipelineCache;
} else if (strcmp("vkCmdBindPipeline", pName) == 0) {
return (PFN_vkVoidFunction)vkCmdBindPipeline;
} else if (strcmp("vkCmdSetStencilReference", pName) == 0) {
return (PFN_vkVoidFunction)vkCmdSetStencilReference;
} else if (strcmp("vkCmdSetScissor", pName) == 0) {
return (PFN_vkVoidFunction)vkCmdSetScissor;
} else if (strcmp("vkCmdSetViewport", pName) == 0) {
return (PFN_vkVoidFunction)vkCmdSetViewport;
} else if (strcmp("vkDestroyCommandPool", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyCommandPool;
} else if (strcmp("vkFreeCommandBuffers", pName) == 0) {
return (PFN_vkVoidFunction)vkFreeCommandBuffers;
} else if (strcmp("vkEndCommandBuffer", pName) == 0) {
return (PFN_vkVoidFunction)vkEndCommandBuffer;
} else if (strcmp("vkCreateFence", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateFence;
} else if (strcmp("vkDestroyFence", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyFence;
} else if (strcmp("vkQueueSubmit", pName) == 0) {
return (PFN_vkVoidFunction)vkQueueSubmit;
} else if (strcmp("vkWaitForFences", pName) == 0) {
return (PFN_vkVoidFunction)vkWaitForFences;
} else if (strcmp("vkGetFenceStatus", pName) == 0) {
return (PFN_vkVoidFunction)vkGetFenceStatus;
} else if (strcmp("vkResetFences", pName) == 0) {
return (PFN_vkVoidFunction)vkResetFences;
} else if (strcmp("vkCreateDebugUtilsMessengerEXT", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateDebugUtilsMessengerEXT;
} else if (strcmp("vkSetDebugUtilsObjectNameEXT", pName) == 0) {
return (PFN_vkVoidFunction)vkSetDebugUtilsObjectNameEXT;
} else if (strcmp("vkCreateQueryPool", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateQueryPool;
} else if (strcmp("vkDestroyQueryPool", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyQueryPool;
} else if (strcmp("vkGetQueryPoolResults", pName) == 0) {
return (PFN_vkVoidFunction)vkGetQueryPoolResults;
} else if (strcmp("vkCreateDescriptorPool", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateDescriptorPool;
} else if (strcmp("vkDestroyDescriptorPool", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyDescriptorPool;
} else if (strcmp("vkResetDescriptorPool", pName) == 0) {
return (PFN_vkVoidFunction)vkResetDescriptorPool;
} else if (strcmp("vkAllocateDescriptorSets", pName) == 0) {
return (PFN_vkVoidFunction)vkAllocateDescriptorSets;
} else if (strcmp("vkGetPhysicalDeviceSurfaceFormatsKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkGetPhysicalDeviceSurfaceFormatsKHR;
} else if (strcmp("vkGetPhysicalDeviceSurfaceCapabilitiesKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkGetPhysicalDeviceSurfaceCapabilitiesKHR;
} else if (strcmp("vkGetPhysicalDeviceSurfaceSupportKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkGetPhysicalDeviceSurfaceSupportKHR;
} else if (strcmp("vkCreateSwapchainKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateSwapchainKHR;
} else if (strcmp("vkDestroySwapchainKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroySwapchainKHR;
} else if (strcmp("vkGetSwapchainImagesKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkGetSwapchainImagesKHR;
} else if (strcmp("vkCreateSemaphore", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateSemaphore;
} else if (strcmp("vkDestroySemaphore", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroySemaphore;
} else if (strcmp("vkDestroySurfaceKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroySurfaceKHR;
} else if (strcmp("vkAcquireNextImageKHR", pName) == 0) {
return (PFN_vkVoidFunction)vkAcquireNextImageKHR;
} else if (strcmp("vkCreateFramebuffer", pName) == 0) {
return (PFN_vkVoidFunction)vkCreateFramebuffer;
} else if (strcmp("vkDestroyFramebuffer", pName) == 0) {
return (PFN_vkVoidFunction)vkDestroyFramebuffer;
}
return noop;
}
} // namespace
MockVulkanContextBuilder::MockVulkanContextBuilder()
: instance_extensions_({"VK_KHR_surface", "VK_MVK_macos_surface"}),
format_properties_callback_([](VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties* pFormatProperties) {
if (format == VK_FORMAT_B8G8R8A8_UNORM) {
pFormatProperties->optimalTilingFeatures =
static_cast<VkFormatFeatureFlags>(
vk::FormatFeatureFlagBits::eColorAttachment);
} else if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
pFormatProperties->optimalTilingFeatures =
static_cast<VkFormatFeatureFlags>(
vk::FormatFeatureFlagBits::eDepthStencilAttachment);
} else if (format == VK_FORMAT_S8_UINT) {
pFormatProperties->optimalTilingFeatures =
static_cast<VkFormatFeatureFlags>(
vk::FormatFeatureFlagBits::eDepthStencilAttachment);
}
}) {}
std::shared_ptr<ContextVK> MockVulkanContextBuilder::Build() {
auto message_loop = fml::ConcurrentMessageLoop::Create();
ContextVK::Settings settings;
settings.proc_address_callback = GetMockVulkanProcAddress;
if (settings_callback_) {
settings_callback_(settings);
}
g_instance_extensions = instance_extensions_;
g_instance_layers = instance_layers_;
g_format_properties_callback = format_properties_callback_;
std::shared_ptr<ContextVK> result = ContextVK::Create(std::move(settings));
return result;
}
std::shared_ptr<std::vector<std::string>> GetMockVulkanFunctions(
VkDevice device) {
MockDevice* mock_device = reinterpret_cast<MockDevice*>(device);
return mock_device->GetCalledFunctions();
}
void SetSwapchainImageSize(ISize size) {
currentImageSize = size;
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/test/mock_vulkan.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/test/mock_vulkan.cc",
"repo_id": "engine",
"token_count": 16406
} | 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_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_LIBRARY_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_LIBRARY_VK_H_
#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h"
namespace impeller {
class DeviceHolderVK;
//------------------------------------------------------------------------------
/// @brief Due the way the Vulkan spec. treats "identically defined"
/// conversions, creating two conversion with identical descriptors,
/// using one with the image and the other with the sampler, is
/// invalid use.
///
/// A conversion library hashes and caches identical descriptors to
/// de-duplicate conversions.
///
/// There can only be one conversion library (the constructor is
/// private to force this) and it found in the context.
///
class YUVConversionLibraryVK {
public:
~YUVConversionLibraryVK();
YUVConversionLibraryVK(const YUVConversionLibraryVK&) = delete;
YUVConversionLibraryVK& operator=(const YUVConversionLibraryVK&) = delete;
//----------------------------------------------------------------------------
/// @brief Get a conversion for the given descriptor. If there is already
/// a conversion created for an equivalent descriptor, a reference
/// to that descriptor is returned instead.
///
/// @param[in] desc The descriptor.
///
/// @return The conversion. A previously created conversion if one was
/// present and a new one if not. A newly created conversion is
/// cached for subsequent accesses.
///
std::shared_ptr<YUVConversionVK> GetConversion(
const YUVConversionDescriptorVK& chain);
private:
friend class ContextVK;
using ConversionsMap = std::unordered_map<YUVConversionDescriptorVK,
std::shared_ptr<YUVConversionVK>,
YUVConversionDescriptorVKHash,
YUVConversionDescriptorVKEqual>;
std::weak_ptr<DeviceHolderVK> device_holder_;
Mutex conversions_mutex_;
ConversionsMap conversions_ IPLR_GUARDED_BY(conversions_mutex_);
explicit YUVConversionLibraryVK(std::weak_ptr<DeviceHolderVK> device_holder);
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_LIBRARY_VK_H_
| engine/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h",
"repo_id": "engine",
"token_count": 960
} | 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_RENDERER_COMMAND_QUEUE_H_
#define FLUTTER_IMPELLER_RENDERER_COMMAND_QUEUE_H_
#include <functional>
#include "fml/status.h"
#include "impeller/renderer/command_buffer.h"
namespace impeller {
/// @brief An interface for submitting command buffers to the GPU for
/// encoding and execution.
class CommandQueue {
public:
using CompletionCallback = std::function<void(CommandBuffer::Status)>;
CommandQueue();
virtual ~CommandQueue();
/// @brief Submit one or more command buffer objects to be encoded and
/// executed on the GPU.
///
/// The order of the provided buffers determines the ordering in which
/// they are submitted.
///
/// The returned status only indicates if the command buffer was
/// successfully submitted. Successful completion of the command buffer
/// can only be checked in the optional completion callback.
///
/// Only the Metal and Vulkan backends can give a status beyond
/// successful encoding. This callback may be called more than once and
/// potentially on a different thread.
virtual fml::Status Submit(
const std::vector<std::shared_ptr<CommandBuffer>>& buffers,
const CompletionCallback& completion_callback = {});
private:
CommandQueue(const CommandQueue&) = delete;
CommandQueue& operator=(const CommandQueue&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_COMMAND_QUEUE_H_
| engine/impeller/renderer/command_queue.h/0 | {
"file_path": "engine/impeller/renderer/command_queue.h",
"repo_id": "engine",
"token_count": 525
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_PIPELINE_H_
#define FLUTTER_IMPELLER_RENDERER_PIPELINE_H_
#include <future>
#include "compute_pipeline_descriptor.h"
#include "impeller/renderer/compute_pipeline_builder.h"
#include "impeller/renderer/compute_pipeline_descriptor.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/pipeline_builder.h"
#include "impeller/renderer/pipeline_descriptor.h"
namespace impeller {
class PipelineLibrary;
template <typename PipelineDescriptor_>
class Pipeline;
template <typename T>
struct PipelineFuture {
std::optional<T> descriptor;
std::shared_future<std::shared_ptr<Pipeline<T>>> future;
const std::shared_ptr<Pipeline<T>> Get() const { return future.get(); }
bool IsValid() const { return future.valid(); }
};
//------------------------------------------------------------------------------
/// @brief Describes the fixed function and programmable aspects of
/// rendering and compute operations performed by commands submitted
/// to the GPU via a command buffer.
///
/// A pipeline handle must be allocated upfront and kept alive for
/// as long as possible. Do not create a pipeline object within a
/// frame workload.
///
/// This pipeline object is almost never used directly as it is
/// untyped. Use reflected shader information generated by the
/// Impeller offline shader compiler to generate a typed pipeline
/// object.
///
template <typename T>
class Pipeline {
public:
virtual ~Pipeline();
virtual bool IsValid() const = 0;
//----------------------------------------------------------------------------
/// @brief Get the descriptor that was responsible for creating this
/// pipeline. It may be copied and modified to create a pipeline
/// variant.
///
/// @return The descriptor.
///
const T& GetDescriptor() const;
PipelineFuture<T> CreateVariant(
std::function<void(T& desc)> descriptor_callback) const;
protected:
const std::weak_ptr<PipelineLibrary> library_;
const T desc_;
Pipeline(std::weak_ptr<PipelineLibrary> library, T desc);
private:
Pipeline(const Pipeline&) = delete;
Pipeline& operator=(const Pipeline&) = delete;
};
extern template class Pipeline<PipelineDescriptor>;
extern template class Pipeline<ComputePipelineDescriptor>;
PipelineFuture<PipelineDescriptor> CreatePipelineFuture(
const Context& context,
std::optional<PipelineDescriptor> desc);
PipelineFuture<ComputePipelineDescriptor> CreatePipelineFuture(
const Context& context,
std::optional<ComputePipelineDescriptor> desc);
template <class VertexShader_, class FragmentShader_>
class RenderPipelineT {
public:
using VertexShader = VertexShader_;
using FragmentShader = FragmentShader_;
using Builder = PipelineBuilder<VertexShader, FragmentShader>;
explicit RenderPipelineT(const Context& context)
: RenderPipelineT(CreatePipelineFuture(
context,
Builder::MakeDefaultPipelineDescriptor(context))) {}
explicit RenderPipelineT(const Context& context,
std::optional<PipelineDescriptor> desc)
: RenderPipelineT(CreatePipelineFuture(context, desc)) {}
explicit RenderPipelineT(PipelineFuture<PipelineDescriptor> future)
: pipeline_future_(std::move(future)) {}
std::shared_ptr<Pipeline<PipelineDescriptor>> WaitAndGet() {
if (did_wait_) {
return pipeline_;
}
did_wait_ = true;
if (pipeline_future_.IsValid()) {
pipeline_ = pipeline_future_.Get();
}
return pipeline_;
}
std::optional<PipelineDescriptor> GetDescriptor() const {
return pipeline_future_.descriptor;
}
private:
PipelineFuture<PipelineDescriptor> pipeline_future_;
std::shared_ptr<Pipeline<PipelineDescriptor>> pipeline_;
bool did_wait_ = false;
RenderPipelineT(const RenderPipelineT&) = delete;
RenderPipelineT& operator=(const RenderPipelineT&) = delete;
};
template <class ComputeShader_>
class ComputePipelineT {
public:
using ComputeShader = ComputeShader_;
using Builder = ComputePipelineBuilder<ComputeShader>;
explicit ComputePipelineT(const Context& context)
: ComputePipelineT(CreatePipelineFuture(
context,
Builder::MakeDefaultPipelineDescriptor(context))) {}
explicit ComputePipelineT(
const Context& context,
std::optional<ComputePipelineDescriptor> compute_desc)
: ComputePipelineT(CreatePipelineFuture(context, compute_desc)) {}
explicit ComputePipelineT(PipelineFuture<ComputePipelineDescriptor> future)
: pipeline_future_(std::move(future)) {}
std::shared_ptr<Pipeline<ComputePipelineDescriptor>> WaitAndGet() {
if (did_wait_) {
return pipeline_;
}
did_wait_ = true;
if (pipeline_future_.IsValid()) {
pipeline_ = pipeline_future_.Get();
}
return pipeline_;
}
private:
PipelineFuture<ComputePipelineDescriptor> pipeline_future_;
std::shared_ptr<Pipeline<ComputePipelineDescriptor>> pipeline_;
bool did_wait_ = false;
ComputePipelineT(const ComputePipelineT&) = delete;
ComputePipelineT& operator=(const ComputePipelineT&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_PIPELINE_H_
| engine/impeller/renderer/pipeline.h/0 | {
"file_path": "engine/impeller/renderer/pipeline.h",
"repo_id": "engine",
"token_count": 1938
} | 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_RENDERER_RENDERER_H_
#define FLUTTER_IMPELLER_RENDERER_RENDERER_H_
#include <functional>
#include <memory>
#include "flutter/fml/synchronization/semaphore.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
class Surface;
class Renderer {
public:
static constexpr size_t kDefaultMaxFramesInFlight = 3u;
using RenderCallback = std::function<bool(RenderTarget& render_target)>;
explicit Renderer(std::shared_ptr<Context> context,
size_t max_frames_in_flight = kDefaultMaxFramesInFlight);
~Renderer();
bool IsValid() const;
bool Render(std::unique_ptr<Surface> surface,
const RenderCallback& callback) const;
std::shared_ptr<Context> GetContext() const;
private:
std::shared_ptr<fml::Semaphore> frames_in_flight_sema_;
std::shared_ptr<Context> context_;
bool is_valid_ = false;
Renderer(const Renderer&) = delete;
Renderer& operator=(const Renderer&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_RENDERER_H_
| engine/impeller/renderer/renderer.h/0 | {
"file_path": "engine/impeller/renderer/renderer.h",
"repo_id": "engine",
"token_count": 454
} | 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 FLUTTER_IMPELLER_RENDERER_TESTING_MOCKS_H_
#define FLUTTER_IMPELLER_RENDERER_TESTING_MOCKS_H_
#include "gmock/gmock.h"
#include "impeller/core/allocator.h"
#include "impeller/core/sampler_descriptor.h"
#include "impeller/core/texture.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/command_queue.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/render_target.h"
#include "impeller/renderer/sampler_library.h"
namespace impeller {
namespace testing {
class MockDeviceBuffer : public DeviceBuffer {
public:
explicit MockDeviceBuffer(const DeviceBufferDescriptor& desc)
: DeviceBuffer(desc) {}
MOCK_METHOD(bool, SetLabel, (const std::string& label), (override));
MOCK_METHOD(bool,
SetLabel,
(const std::string& label, Range range),
(override));
MOCK_METHOD(uint8_t*, OnGetContents, (), (const, override));
MOCK_METHOD(bool,
OnCopyHostBuffer,
(const uint8_t* source, Range source_range, size_t offset),
(override));
};
class MockAllocator : public Allocator {
public:
MOCK_METHOD(ISize, GetMaxTextureSizeSupported, (), (const, override));
MOCK_METHOD(std::shared_ptr<DeviceBuffer>,
OnCreateBuffer,
(const DeviceBufferDescriptor& desc),
(override));
MOCK_METHOD(std::shared_ptr<Texture>,
OnCreateTexture,
(const TextureDescriptor& desc),
(override));
};
class MockBlitPass : public BlitPass {
public:
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(bool,
EncodeCommands,
(const std::shared_ptr<Allocator>& transients_allocator),
(const, override));
MOCK_METHOD(void, OnSetLabel, (std::string label), (override));
MOCK_METHOD(bool,
OnCopyTextureToTextureCommand,
(std::shared_ptr<Texture> source,
std::shared_ptr<Texture> destination,
IRect source_region,
IPoint destination_origin,
std::string label),
(override));
MOCK_METHOD(bool,
OnCopyTextureToBufferCommand,
(std::shared_ptr<Texture> source,
std::shared_ptr<DeviceBuffer> destination,
IRect source_region,
size_t destination_offset,
std::string label),
(override));
MOCK_METHOD(bool,
OnCopyBufferToTextureCommand,
(BufferView source,
std::shared_ptr<Texture> destination,
IPoint destination_origin,
std::string label),
(override));
MOCK_METHOD(bool,
OnGenerateMipmapCommand,
(std::shared_ptr<Texture> texture, std::string label),
(override));
};
class MockRenderPass : public RenderPass {
public:
MockRenderPass(std::shared_ptr<const Context> context,
const RenderTarget& target)
: RenderPass(std::move(context), target) {}
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(bool,
OnEncodeCommands,
(const Context& context),
(const, override));
MOCK_METHOD(void, OnSetLabel, (std::string label), (override));
};
class MockCommandBuffer : public CommandBuffer {
public:
explicit MockCommandBuffer(std::weak_ptr<const Context> context)
: CommandBuffer(std::move(context)) {}
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(void, SetLabel, (const std::string& label), (const, override));
MOCK_METHOD(std::shared_ptr<BlitPass>, OnCreateBlitPass, (), (override));
MOCK_METHOD(bool,
OnSubmitCommands,
(CompletionCallback callback),
(override));
MOCK_METHOD(void, OnWaitUntilScheduled, (), (override));
MOCK_METHOD(std::shared_ptr<ComputePass>,
OnCreateComputePass,
(),
(override));
MOCK_METHOD(std::shared_ptr<RenderPass>,
OnCreateRenderPass,
(RenderTarget render_target),
(override));
};
class MockImpellerContext : public Context {
public:
MOCK_METHOD(Context::BackendType, GetBackendType, (), (const, override));
MOCK_METHOD(std::string, DescribeGpuModel, (), (const, override));
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(void, Shutdown, (), (override));
MOCK_METHOD(std::shared_ptr<Allocator>,
GetResourceAllocator,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<ShaderLibrary>,
GetShaderLibrary,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<SamplerLibrary>,
GetSamplerLibrary,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<PipelineLibrary>,
GetPipelineLibrary,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<CommandBuffer>,
CreateCommandBuffer,
(),
(const, override));
MOCK_METHOD(const std::shared_ptr<const Capabilities>&,
GetCapabilities,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<CommandQueue>,
GetCommandQueue,
(),
(const, override));
};
class MockTexture : public Texture {
public:
explicit MockTexture(const TextureDescriptor& desc) : Texture(desc) {}
MOCK_METHOD(void, SetLabel, (std::string_view label), (override));
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(ISize, GetSize, (), (const, override));
MOCK_METHOD(bool,
OnSetContents,
(const uint8_t* contents, size_t length, size_t slice),
(override));
MOCK_METHOD(bool,
OnSetContents,
(std::shared_ptr<const fml::Mapping> mapping, size_t slice),
(override));
};
class MockCapabilities : public Capabilities {
public:
MOCK_METHOD(bool, SupportsOffscreenMSAA, (), (const, override));
MOCK_METHOD(bool, SupportsImplicitResolvingMSAA, (), (const, override));
MOCK_METHOD(bool, SupportsSSBO, (), (const, override));
MOCK_METHOD(bool, SupportsBufferToTextureBlits, (), (const, override));
MOCK_METHOD(bool, SupportsTextureToTextureBlits, (), (const, override));
MOCK_METHOD(bool, SupportsFramebufferFetch, (), (const, override));
MOCK_METHOD(bool, SupportsCompute, (), (const, override));
MOCK_METHOD(bool, SupportsComputeSubgroups, (), (const, override));
MOCK_METHOD(bool, SupportsReadFromResolve, (), (const, override));
MOCK_METHOD(bool, SupportsDecalSamplerAddressMode, (), (const, override));
MOCK_METHOD(bool, SupportsDeviceTransientTextures, (), (const, override));
MOCK_METHOD(PixelFormat, GetDefaultColorFormat, (), (const, override));
MOCK_METHOD(PixelFormat, GetDefaultStencilFormat, (), (const, override));
MOCK_METHOD(PixelFormat, GetDefaultDepthStencilFormat, (), (const, override));
MOCK_METHOD(PixelFormat, GetDefaultGlyphAtlasFormat, (), (const, override));
};
class MockCommandQueue : public CommandQueue {
public:
MOCK_METHOD(fml::Status,
Submit,
(const std::vector<std::shared_ptr<CommandBuffer>>& buffers,
const CompletionCallback& cb),
(override));
};
class MockSamplerLibrary : public SamplerLibrary {
public:
MOCK_METHOD(const std::unique_ptr<const Sampler>&,
GetSampler,
(SamplerDescriptor descriptor),
(override));
};
class MockSampler : public Sampler {
public:
explicit MockSampler(const SamplerDescriptor& desc) : Sampler(desc) {}
};
} // namespace testing
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_TESTING_MOCKS_H_
| engine/impeller/renderer/testing/mocks.h/0 | {
"file_path": "engine/impeller/renderer/testing/mocks.h",
"repo_id": "engine",
"token_count": 3390
} | 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.
import("//flutter/impeller/tools/impeller.gni")
impeller_component("scene") {
sources = [
"animation/animation.cc",
"animation/animation.h",
"animation/animation_clip.cc",
"animation/animation_clip.h",
"animation/animation_player.cc",
"animation/animation_player.h",
"animation/animation_transforms.h",
"animation/property_resolver.cc",
"animation/property_resolver.h",
"camera.cc",
"camera.h",
"geometry.cc",
"geometry.h",
"material.cc",
"material.h",
"mesh.cc",
"mesh.h",
"node.cc",
"node.h",
"pipeline_key.h",
"scene.cc",
"scene.h",
"scene_context.cc",
"scene_context.h",
"scene_encoder.cc",
"scene_encoder.h",
"skin.cc",
"skin.h",
]
public_deps = [
"../renderer",
"importer:conversions",
"importer:importer_flatbuffers",
"shaders",
]
deps = [ "//flutter/fml" ]
}
impeller_component("scene_unittests") {
testonly = true
sources = [ "scene_unittests.cc" ]
deps = [
":scene",
"../fixtures",
"../playground:playground_test",
"//flutter/testing:testing_lib",
]
}
| engine/impeller/scene/BUILD.gn/0 | {
"file_path": "engine/impeller/scene/BUILD.gn",
"repo_id": "engine",
"token_count": 565
} | 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/scene/importer/conversions.h"
#include <cstring>
#include "impeller/scene/importer/scene_flatbuffers.h"
namespace impeller {
namespace scene {
namespace importer {
Matrix ToMatrix(const std::vector<double>& m) {
return Matrix(m[0], m[1], m[2], m[3], //
m[4], m[5], m[6], m[7], //
m[8], m[9], m[10], m[11], //
m[12], m[13], m[14], m[15]);
}
//-----------------------------------------------------------------------------
/// Flatbuffers -> Impeller
///
Matrix ToMatrix(const fb::Matrix& m) {
auto& a = *m.m();
return Matrix(a[0], a[1], a[2], a[3], //
a[4], a[5], a[6], a[7], //
a[8], a[9], a[10], a[11], //
a[12], a[13], a[14], a[15]);
}
Vector2 ToVector2(const fb::Vec2& v) {
return Vector2(v.x(), v.y());
}
Vector3 ToVector3(const fb::Vec3& v) {
return Vector3(v.x(), v.y(), v.z());
}
Vector4 ToVector4(const fb::Vec4& v) {
return Vector4(v.x(), v.y(), v.z(), v.w());
}
Color ToColor(const fb::Color& c) {
return Color(c.r(), c.g(), c.b(), c.a());
}
//-----------------------------------------------------------------------------
/// Impeller -> Flatbuffers
///
fb::Matrix ToFBMatrix(const Matrix& m) {
auto array = std::array<Scalar, 16>{m.m[0], m.m[1], m.m[2], m.m[3], //
m.m[4], m.m[5], m.m[6], m.m[7], //
m.m[8], m.m[9], m.m[10], m.m[11], //
m.m[12], m.m[13], m.m[14], m.m[15]};
return fb::Matrix(array);
}
std::unique_ptr<fb::Matrix> ToFBMatrixUniquePtr(const Matrix& m) {
auto array = std::array<Scalar, 16>{m.m[0], m.m[1], m.m[2], m.m[3], //
m.m[4], m.m[5], m.m[6], m.m[7], //
m.m[8], m.m[9], m.m[10], m.m[11], //
m.m[12], m.m[13], m.m[14], m.m[15]};
return std::make_unique<fb::Matrix>(array);
}
fb::Vec2 ToFBVec2(const Vector2 v) {
return fb::Vec2(v.x, v.y);
}
fb::Vec3 ToFBVec3(const Vector3 v) {
return fb::Vec3(v.x, v.y, v.z);
}
fb::Vec4 ToFBVec4(const Vector4 v) {
return fb::Vec4(v.x, v.y, v.z, v.w);
}
fb::Color ToFBColor(const Color c) {
return fb::Color(c.red, c.green, c.blue, c.alpha);
}
std::unique_ptr<fb::Color> ToFBColor(const std::vector<double>& c) {
auto* color = new fb::Color(c.size() > 0 ? c[0] : 1, //
c.size() > 1 ? c[1] : 1, //
c.size() > 2 ? c[2] : 1, //
c.size() > 3 ? c[3] : 1);
return std::unique_ptr<fb::Color>(color);
}
} // namespace importer
} // namespace scene
} // namespace impeller
| engine/impeller/scene/importer/conversions.cc/0 | {
"file_path": "engine/impeller/scene/importer/conversions.cc",
"repo_id": "engine",
"token_count": 1554
} | 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.
#include "impeller/scene/node.h"
#include <inttypes.h>
#include <atomic>
#include <memory>
#include <vector>
#include "flutter/fml/logging.h"
#include "impeller/base/strings.h"
#include "impeller/base/thread.h"
#include "impeller/base/validation.h"
#include "impeller/geometry/matrix.h"
#include "impeller/scene/animation/animation_player.h"
#include "impeller/scene/importer/conversions.h"
#include "impeller/scene/importer/scene_flatbuffers.h"
#include "impeller/scene/mesh.h"
#include "impeller/scene/node.h"
#include "impeller/scene/scene_encoder.h"
namespace impeller {
namespace scene {
static std::atomic_uint64_t kNextNodeID = 0;
void Node::MutationLog::Append(const Entry& entry) {
WriterLock lock(write_mutex_);
dirty_ = true;
entries_.push_back(entry);
}
std::optional<std::vector<Node::MutationLog::Entry>>
Node::MutationLog::Flush() {
WriterLock lock(write_mutex_);
if (!dirty_) {
return std::nullopt;
}
dirty_ = false;
auto result = entries_;
entries_ = {};
return result;
}
std::shared_ptr<Node> Node::MakeFromFlatbuffer(
const fml::Mapping& ipscene_mapping,
Allocator& allocator) {
flatbuffers::Verifier verifier(ipscene_mapping.GetMapping(),
ipscene_mapping.GetSize());
if (!fb::VerifySceneBuffer(verifier)) {
VALIDATION_LOG << "Failed to unpack scene: Scene flatbuffer is invalid.";
return nullptr;
}
return Node::MakeFromFlatbuffer(*fb::GetScene(ipscene_mapping.GetMapping()),
allocator);
}
static std::shared_ptr<Texture> UnpackTextureFromFlatbuffer(
const fb::Texture* iptexture,
Allocator& allocator) {
if (iptexture == nullptr || iptexture->embedded_image() == nullptr ||
iptexture->embedded_image()->bytes() == nullptr) {
return nullptr;
}
auto embedded = iptexture->embedded_image();
uint8_t bytes_per_component = 0;
switch (embedded->component_type()) {
case fb::ComponentType::k8Bit:
bytes_per_component = 1;
break;
case fb::ComponentType::k16Bit:
// bytes_per_component = 2;
FML_LOG(WARNING) << "16 bit textures not yet supported.";
return nullptr;
}
switch (embedded->component_count()) {
case 4:
// RGBA.
break;
case 1:
case 3:
default:
FML_LOG(WARNING) << "Textures with " << embedded->component_count()
<< " components are not supported." << std::endl;
return nullptr;
}
if (embedded->bytes()->size() != bytes_per_component *
embedded->component_count() *
embedded->width() * embedded->height()) {
FML_LOG(WARNING) << "Embedded texture has an unexpected size. Skipping."
<< std::endl;
return nullptr;
}
auto image_mapping = std::make_shared<fml::NonOwnedMapping>(
embedded->bytes()->Data(), embedded->bytes()->size());
auto texture_descriptor = TextureDescriptor{};
texture_descriptor.storage_mode = StorageMode::kHostVisible;
texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt;
texture_descriptor.size = ISize(embedded->width(), embedded->height());
// TODO(bdero): Generate mipmaps for embedded textures.
texture_descriptor.mip_count = 1u;
auto texture = allocator.CreateTexture(texture_descriptor);
if (!texture) {
FML_LOG(ERROR) << "Could not allocate texture.";
return nullptr;
}
auto uploaded = texture->SetContents(image_mapping);
if (!uploaded) {
FML_LOG(ERROR) << "Could not upload texture to device memory.";
return nullptr;
}
return texture;
}
std::shared_ptr<Node> Node::MakeFromFlatbuffer(const fb::Scene& scene,
Allocator& allocator) {
// Unpack textures.
std::vector<std::shared_ptr<Texture>> textures;
if (scene.textures()) {
for (const auto iptexture : *scene.textures()) {
// The elements of the unpacked texture array must correspond exactly with
// the ipscene texture array. So if a texture is empty or invalid, a
// nullptr is inserted as a placeholder.
textures.push_back(UnpackTextureFromFlatbuffer(iptexture, allocator));
}
}
auto result = std::make_shared<Node>();
result->SetLocalTransform(importer::ToMatrix(*scene.transform()));
if (!scene.nodes() || !scene.children()) {
return result; // The scene is empty.
}
// Initialize nodes for unpacking the entire scene.
std::vector<std::shared_ptr<Node>> scene_nodes;
scene_nodes.reserve(scene.nodes()->size());
for (size_t node_i = 0; node_i < scene.nodes()->size(); node_i++) {
scene_nodes.push_back(std::make_shared<Node>());
}
// Connect children to the root node.
for (int child : *scene.children()) {
if (child < 0 || static_cast<size_t>(child) >= scene_nodes.size()) {
VALIDATION_LOG << "Scene child index out of range.";
continue;
}
result->AddChild(scene_nodes[child]);
}
// Unpack each node.
for (size_t node_i = 0; node_i < scene.nodes()->size(); node_i++) {
scene_nodes[node_i]->UnpackFromFlatbuffer(*scene.nodes()->Get(node_i),
scene_nodes, textures, allocator);
}
// Unpack animations.
if (scene.animations()) {
for (const auto animation : *scene.animations()) {
if (auto out_animation =
Animation::MakeFromFlatbuffer(*animation, scene_nodes)) {
result->animations_.push_back(out_animation);
}
}
}
return result;
}
void Node::UnpackFromFlatbuffer(
const fb::Node& source_node,
const std::vector<std::shared_ptr<Node>>& scene_nodes,
const std::vector<std::shared_ptr<Texture>>& textures,
Allocator& allocator) {
name_ = source_node.name()->str();
SetLocalTransform(importer::ToMatrix(*source_node.transform()));
/// Meshes.
if (source_node.mesh_primitives()) {
Mesh mesh;
for (const auto* primitives : *source_node.mesh_primitives()) {
auto geometry = Geometry::MakeFromFlatbuffer(*primitives, allocator);
auto material =
primitives->material()
? Material::MakeFromFlatbuffer(*primitives->material(), textures)
: Material::MakeUnlit();
mesh.AddPrimitive({std::move(geometry), std::move(material)});
}
SetMesh(std::move(mesh));
}
/// Child nodes.
if (source_node.children()) {
// Wire up graph connections.
for (int child : *source_node.children()) {
if (child < 0 || static_cast<size_t>(child) >= scene_nodes.size()) {
VALIDATION_LOG << "Node child index out of range.";
continue;
}
AddChild(scene_nodes[child]);
}
}
/// Skin.
if (source_node.skin()) {
skin_ = Skin::MakeFromFlatbuffer(*source_node.skin(), scene_nodes);
}
}
Node::Node() : name_(SPrintF("__node%" PRIu64, kNextNodeID++)){};
Node::~Node() = default;
Mesh::Mesh(Mesh&& mesh) = default;
Mesh& Mesh::operator=(Mesh&& mesh) = default;
const std::string& Node::GetName() const {
return name_;
}
void Node::SetName(const std::string& new_name) {
name_ = new_name;
}
Node* Node::GetParent() const {
return parent_;
}
std::shared_ptr<Node> Node::FindChildByName(
const std::string& name,
bool exclude_animation_players) const {
for (auto& child : children_) {
if (exclude_animation_players && child->animation_player_.has_value()) {
continue;
}
if (child->GetName() == name) {
return child;
}
if (auto found = child->FindChildByName(name)) {
return found;
}
}
return nullptr;
}
std::shared_ptr<Animation> Node::FindAnimationByName(
const std::string& name) const {
for (const auto& animation : animations_) {
if (animation->GetName() == name) {
return animation;
}
}
return nullptr;
}
AnimationClip* Node::AddAnimation(const std::shared_ptr<Animation>& animation) {
if (!animation_player_.has_value()) {
animation_player_ = AnimationPlayer();
}
return animation_player_->AddAnimation(animation, this);
}
void Node::SetLocalTransform(Matrix transform) {
local_transform_ = transform;
}
Matrix Node::GetLocalTransform() const {
return local_transform_;
}
void Node::SetGlobalTransform(Matrix transform) {
Matrix inverse_global_transform =
parent_ ? parent_->GetGlobalTransform().Invert() : Matrix();
local_transform_ = inverse_global_transform * transform;
}
Matrix Node::GetGlobalTransform() const {
if (parent_) {
return parent_->GetGlobalTransform() * local_transform_;
}
return local_transform_;
}
bool Node::AddChild(std::shared_ptr<Node> node) {
if (!node) {
VALIDATION_LOG << "Cannot add null child to node.";
return false;
}
// TODO(bdero): Figure out a better paradigm/rules for nodes with multiple
// parents. We should probably disallow this, make deep
// copying of nodes cheap and easy, add mesh instancing, etc.
// Today, the parent link is only used for skin posing, and so
// it's reasonable to not have a check and allow multi-parenting.
// Even still, there should still be some kind of cycle
// prevention/detection, ideally at the protocol level.
//
// if (node->parent_ != nullptr) {
// VALIDATION_LOG
// << "Cannot add a node as a child which already has a parent.";
// return false;
// }
node->parent_ = this;
children_.push_back(std::move(node));
return true;
}
std::vector<std::shared_ptr<Node>>& Node::GetChildren() {
return children_;
}
void Node::SetMesh(Mesh mesh) {
mesh_ = std::move(mesh);
}
Mesh& Node::GetMesh() {
return mesh_;
}
void Node::SetIsJoint(bool is_joint) {
is_joint_ = is_joint;
}
bool Node::IsJoint() const {
return is_joint_;
}
bool Node::Render(SceneEncoder& encoder,
Allocator& allocator,
const Matrix& parent_transform) {
std::optional<std::vector<MutationLog::Entry>> log = mutation_log_.Flush();
if (log.has_value()) {
for (const auto& entry : log.value()) {
if (auto e = std::get_if<MutationLog::SetTransformEntry>(&entry)) {
local_transform_ = e->transform;
} else if (auto e =
std::get_if<MutationLog::SetAnimationStateEntry>(&entry)) {
AnimationClip* clip =
animation_player_.has_value()
? animation_player_->GetClip(e->animation_name)
: nullptr;
if (!clip) {
auto animation = FindAnimationByName(e->animation_name);
if (!animation) {
continue;
}
clip = AddAnimation(animation);
if (!clip) {
continue;
}
}
clip->SetPlaying(e->playing);
clip->SetLoop(e->loop);
clip->SetWeight(e->weight);
clip->SetPlaybackTimeScale(e->time_scale);
} else if (auto e =
std::get_if<MutationLog::SeekAnimationEntry>(&entry)) {
AnimationClip* clip =
animation_player_.has_value()
? animation_player_->GetClip(e->animation_name)
: nullptr;
if (!clip) {
auto animation = FindAnimationByName(e->animation_name);
if (!animation) {
continue;
}
clip = AddAnimation(animation);
if (!clip) {
continue;
}
}
clip->Seek(SecondsF(e->time));
}
}
}
if (animation_player_.has_value()) {
animation_player_->Update();
}
Matrix transform = parent_transform * local_transform_;
mesh_.Render(encoder, transform,
skin_ ? skin_->GetJointsTexture(allocator) : nullptr);
for (auto& child : children_) {
if (!child->Render(encoder, allocator, transform)) {
return false;
}
}
return true;
}
void Node::AddMutation(const MutationLog::Entry& entry) {
mutation_log_.Append(entry);
}
} // namespace scene
} // namespace impeller
| engine/impeller/scene/node.cc/0 | {
"file_path": "engine/impeller/scene/node.cc",
"repo_id": "engine",
"token_count": 4860
} | 221 |
# Copyright 2013 The Flutter 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/third_party/flatbuffers/flatbuffers.gni")
import("../tools/impeller.gni")
config("shader_archive_config") {
configs = [ "//flutter/impeller:impeller_public_config" ]
include_dirs = [ "$root_gen_dir/flutter" ]
}
flatbuffers("shader_archive_flatbuffers") {
flatbuffers = [
"shader_archive.fbs",
"multi_arch_shader_archive.fbs",
]
public_configs = [ ":shader_archive_config" ]
public_deps = [ "//flutter/third_party/flatbuffers" ]
}
impeller_component("shader_archive") {
sources = [
"multi_arch_shader_archive.cc",
"multi_arch_shader_archive.h",
"multi_arch_shader_archive_writer.cc",
"multi_arch_shader_archive_writer.h",
"shader_archive.cc",
"shader_archive.h",
"shader_archive_types.h",
"shader_archive_writer.cc",
"shader_archive_writer.h",
]
public_deps = [
":shader_archive_flatbuffers",
"../base",
"//flutter/fml",
]
}
impeller_component("shader_archiver") {
target_type = "executable"
sources = [ "shader_archive_main.cc" ]
deps = [
":shader_archive",
"../base",
"//flutter/fml",
]
}
impeller_component("shader_archive_unittests") {
testonly = true
sources = [ "shader_archive_unittests.cc" ]
deps = [
":shader_archive",
"//flutter/fml",
"//flutter/testing",
]
}
| engine/impeller/shader_archive/BUILD.gn/0 | {
"file_path": "engine/impeller/shader_archive/BUILD.gn",
"repo_id": "engine",
"token_count": 603
} | 222 |
# Copyright 2013 The Flutter 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("tessellator") {
sources = [
"tessellator.cc",
"tessellator.h",
]
public_deps = [ "../geometry" ]
deps = [
"../core",
"//flutter/fml",
"//third_party/libtess2",
]
}
impeller_component("tessellator_shared") {
target_type = "shared_library"
if (is_win) {
output_name = "libtessellator"
} else {
output_name = "tessellator"
}
sources = [
"c/tessellator.cc",
"c/tessellator.h",
"tessellator.cc",
"tessellator.h",
]
deps = [
"../core",
"../geometry",
"//flutter/fml",
"//third_party/libtess2",
]
metadata = {
entitlement_file_path = [ "libtessellator.dylib" ]
}
}
impeller_component("tessellator_unittests") {
testonly = true
sources = [ "tessellator_unittests.cc" ]
deps = [
":tessellator",
"../geometry:geometry_asserts",
"//flutter/testing",
]
}
| engine/impeller/tessellator/BUILD.gn/0 | {
"file_path": "engine/impeller/tessellator/BUILD.gn",
"repo_id": "engine",
"token_count": 459
} | 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 "flutter/impeller/toolkit/android/proc_table.h"
#include "flutter/fml/build_config.h"
#include "impeller/base/validation.h"
namespace impeller::android {
const ProcTable& GetProcTable() {
static ProcTable gProcTable;
return gProcTable;
}
template <class T>
void ResolveAndroidProc(
AndroidProc<T>& proc,
const std::vector<fml::RefPtr<fml::NativeLibrary>>& libs) {
for (const auto& lib : libs) {
proc.proc = lib->ResolveFunction<T*>(proc.proc_name).value_or(nullptr);
if (proc.proc) {
break;
}
}
}
ProcTable::ProcTable() {
auto lib_android = fml::NativeLibrary::Create("libandroid.so");
auto lib_egl = fml::NativeLibrary::Create("libEGL.so");
if (!lib_android || !lib_egl) {
VALIDATION_LOG << "Could not open Android libraries.";
return;
}
libraries_.push_back(std::move(lib_android));
libraries_.push_back(std::move(lib_egl));
#define RESOLVE_PROC(proc, api) ResolveAndroidProc(proc, libraries_);
FOR_EACH_ANDROID_PROC(RESOLVE_PROC);
#undef RESOLVE_PROC
if (AChoreographer_postFrameCallback64) {
AChoreographer_postFrameCallback.Reset();
}
#if FML_ARCH_CPU_32_BITS
// On 32-bit platforms, the nanosecond resolution timestamp causes overflow on
// the argument in the callback. Don't use it on those platforms.
AChoreographer_postFrameCallback.Reset();
#endif // FML_ARCH_CPU_32_BITS
is_valid_ = true;
}
ProcTable::~ProcTable() = default;
bool ProcTable::IsValid() const {
return is_valid_;
}
bool ProcTable::TraceIsEnabled() const {
return this->ATrace_isEnabled ? this->ATrace_isEnabled() : false;
}
} // namespace impeller::android
| engine/impeller/toolkit/android/proc_table.cc/0 | {
"file_path": "engine/impeller/toolkit/android/proc_table.cc",
"repo_id": "engine",
"token_count": 650
} | 224 |
#include "flutter/impeller/toolkit/egl/image.h"
namespace impeller {}
| engine/impeller/toolkit/egl/image.cc/0 | {
"file_path": "engine/impeller/toolkit/egl/image.cc",
"repo_id": "engine",
"token_count": 28
} | 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.
import argparse
import errno
import os
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
# Dump the bytes of file into a C translation unit.
# This can be used to embed the file contents into a binary.
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--symbol-name', type=str, required=True, help='The name of the symbol referencing the data.'
)
parser.add_argument(
'--output-header',
type=str,
required=True,
help='The header file containing the symbol reference.'
)
parser.add_argument(
'--output-source', type=str, required=True, help='The source file containing the file bytes.'
)
parser.add_argument(
'--source',
type=str,
required=True,
help='The source file whose contents to embed in the output source file.'
)
args = parser.parse_args()
assert os.path.exists(args.source)
output_header = os.path.abspath(args.output_header)
output_source = os.path.abspath(args.output_source)
output_header_basename = output_header[output_header.rfind('/') + 1:]
make_directories(os.path.dirname(output_header))
make_directories(os.path.dirname(output_source))
with open(args.source, 'rb') as source, open(output_source, 'w') as output:
data_len = 0
output.write(f'#include "{output_header_basename}"\n')
output.write('#include <cstddef>\n')
output.write(
f'alignas(std::max_align_t) const unsigned char impeller_{args.symbol_name}_data[] =\n'
)
output.write('{\n')
while True:
byte = source.read(1)
if not byte:
break
data_len += 1
output.write(f'{ord(byte)},')
output.write('};\n')
output.write(f'const unsigned long impeller_{args.symbol_name}_length = {data_len};\n')
with open(output_header, 'w') as output:
output.write('#pragma once\n')
output.write('#ifdef __cplusplus\n')
output.write('extern "C" {\n')
output.write('#endif\n\n')
output.write(f'extern const unsigned char impeller_{args.symbol_name}_data[];\n')
output.write(f'extern const unsigned long impeller_{args.symbol_name}_length;\n\n')
output.write('#ifdef __cplusplus\n')
output.write('}\n')
output.write('#endif\n')
if __name__ == '__main__':
main()
| engine/impeller/tools/xxd.py/0 | {
"file_path": "engine/impeller/tools/xxd.py",
"repo_id": "engine",
"token_count": 972
} | 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/typographer/backends/stb/typeface_stb.h"
#include <cstring>
#include "flutter/fml/logging.h"
namespace impeller {
// Instantiate a typeface based on a .ttf or other font file
TypefaceSTB::TypefaceSTB(std::unique_ptr<fml::Mapping> typeface_mapping)
: typeface_mapping_(std::move(typeface_mapping)),
font_info_(std::make_unique<stbtt_fontinfo>()) {
// We need an "offset" into the ttf file
auto offset = stbtt_GetFontOffsetForIndex(typeface_mapping_->GetMapping(), 0);
if (stbtt_InitFont(font_info_.get(), typeface_mapping_->GetMapping(),
offset) == 0) {
FML_LOG(ERROR) << "Failed to initialize stb font from binary data.";
} else {
is_valid_ = true;
}
}
TypefaceSTB::~TypefaceSTB() = default;
bool TypefaceSTB::IsValid() const {
return is_valid_;
}
std::size_t TypefaceSTB::GetHash() const {
if (!IsValid()) {
return 0u;
}
return reinterpret_cast<size_t>(typeface_mapping_->GetMapping());
}
bool TypefaceSTB::IsEqual(const Typeface& other) const {
auto stb_other = reinterpret_cast<const TypefaceSTB*>(&other);
return stb_other->GetHash() == GetHash();
}
const uint8_t* TypefaceSTB::GetTypefaceFile() const {
return typeface_mapping_->GetMapping();
}
const stbtt_fontinfo* TypefaceSTB::GetFontInfo() const {
return font_info_.get();
}
} // namespace impeller
| engine/impeller/typographer/backends/stb/typeface_stb.cc/0 | {
"file_path": "engine/impeller/typographer/backends/stb/typeface_stb.cc",
"repo_id": "engine",
"token_count": 567
} | 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.
#include "impeller/typographer/text_frame.h"
namespace impeller {
TextFrame::TextFrame() = default;
TextFrame::TextFrame(std::vector<TextRun>& runs, Rect bounds, bool has_color)
: runs_(std::move(runs)), bounds_(bounds), has_color_(has_color) {}
TextFrame::~TextFrame() = default;
Rect TextFrame::GetBounds() const {
return bounds_;
}
size_t TextFrame::GetRunCount() const {
return runs_.size();
}
const std::vector<TextRun>& TextFrame::GetRuns() const {
return runs_;
}
GlyphAtlas::Type TextFrame::GetAtlasType() const {
return has_color_ ? GlyphAtlas::Type::kColorBitmap
: GlyphAtlas::Type::kAlphaBitmap;
}
bool TextFrame::MaybeHasOverlapping() const {
if (runs_.size() > 1) {
return true;
}
auto glyph_positions = runs_[0].GetGlyphPositions();
if (glyph_positions.size() > 10) {
return true;
}
if (glyph_positions.size() == 1) {
return false;
}
// To avoid quadradic behavior the overlapping is checked against an
// accumulated bounds rect. This gives faster but less precise information
// on text runs.
auto first_position = glyph_positions[0];
auto overlapping_rect = Rect::MakeOriginSize(
first_position.position + first_position.glyph.bounds.GetOrigin(),
first_position.glyph.bounds.GetSize());
for (auto i = 1u; i < glyph_positions.size(); i++) {
auto glyph_position = glyph_positions[i];
auto glyph_rect = Rect::MakeOriginSize(
glyph_position.position + glyph_position.glyph.bounds.GetOrigin(),
glyph_position.glyph.bounds.GetSize());
auto intersection = glyph_rect.Intersection(overlapping_rect);
if (intersection.has_value()) {
return true;
}
overlapping_rect = overlapping_rect.Union(glyph_rect);
}
return false;
}
// static
Scalar TextFrame::RoundScaledFontSize(Scalar scale, Scalar point_size) {
return std::round(scale * 100) / 100;
}
void TextFrame::CollectUniqueFontGlyphPairs(FontGlyphMap& glyph_map,
Scalar scale) const {
for (const TextRun& run : GetRuns()) {
const Font& font = run.GetFont();
auto rounded_scale =
RoundScaledFontSize(scale, font.GetMetrics().point_size);
auto& set = glyph_map[{font, rounded_scale}];
for (const TextRun::GlyphPosition& glyph_position :
run.GetGlyphPositions()) {
#if false
// Glyph size error due to RoundScaledFontSize usage above.
if (rounded_scale != scale) {
auto delta = std::abs(rounded_scale - scale);
FML_LOG(ERROR) << glyph_position.glyph.bounds.size * delta;
}
#endif
set.insert(glyph_position.glyph);
}
}
}
} // namespace impeller
| engine/impeller/typographer/text_frame.cc/0 | {
"file_path": "engine/impeller/typographer/text_frame.cc",
"repo_id": "engine",
"token_count": 1027
} | 228 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_GPU_DEVICE_BUFFER_H_
#define FLUTTER_LIB_GPU_DEVICE_BUFFER_H_
#include "flutter/lib/gpu/context.h"
#include "flutter/lib/gpu/export.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
namespace flutter {
namespace gpu {
class DeviceBuffer : public RefCountedDartWrappable<DeviceBuffer> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(DeviceBuffer);
public:
explicit DeviceBuffer(std::shared_ptr<impeller::DeviceBuffer> device_buffer);
~DeviceBuffer() override;
std::shared_ptr<impeller::DeviceBuffer> GetBuffer();
bool Overwrite(const tonic::DartByteData& source_bytes,
size_t destination_offset_in_bytes);
private:
std::shared_ptr<impeller::DeviceBuffer> device_buffer_;
FML_DISALLOW_COPY_AND_ASSIGN(DeviceBuffer);
};
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
extern "C" {
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_DeviceBuffer_Initialize(
Dart_Handle wrapper,
flutter::gpu::Context* gpu_context,
int storage_mode,
int size_in_bytes);
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_DeviceBuffer_InitializeWithHostData(
Dart_Handle wrapper,
flutter::gpu::Context* gpu_context,
Dart_Handle byte_data);
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_DeviceBuffer_Overwrite(
flutter::gpu::DeviceBuffer* wrapper,
Dart_Handle source_byte_data,
int destination_offset_in_bytes);
} // extern "C"
#endif // FLUTTER_LIB_GPU_DEVICE_BUFFER_H_
| engine/lib/gpu/device_buffer.h/0 | {
"file_path": "engine/lib/gpu/device_buffer.h",
"repo_id": "engine",
"token_count": 633
} | 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.
// ignore_for_file: public_member_api_docs
part of flutter_gpu;
base class UniformSlot {
UniformSlot._(this.shader, this.uniformName);
final Shader shader;
final String uniformName;
/// The reflected total size of a shader's uniform struct by name.
///
/// Returns [null] if the shader does not contain a uniform struct with the
/// given name.
int? get sizeInBytes {
int size = shader._getUniformStructSize(uniformName);
return size < 0 ? null : size;
}
/// Get the reflected offset of a named member in the uniform struct.
///
/// Returns [null] if the shader does not contain a uniform struct with the
/// given name, or if the uniform struct does not contain a member with the
/// given name.
int? getMemberOffsetInBytes(String memberName) {
int offset = shader._getUniformMemberOffset(uniformName, memberName);
return offset < 0 ? null : offset;
}
}
base class Shader extends NativeFieldWrapperClass1 {
// [Shader] handles are instantiated when interacting with a [ShaderLibrary].
Shader._();
UniformSlot getUniformSlot(String uniformName) {
return UniformSlot._(this, uniformName);
}
@Native<Int Function(Pointer<Void>, Handle)>(
symbol: 'InternalFlutterGpu_Shader_GetUniformStructSize')
external int _getUniformStructSize(String uniformStructName);
@Native<Int Function(Pointer<Void>, Handle, Handle)>(
symbol: 'InternalFlutterGpu_Shader_GetUniformMemberOffset')
external int _getUniformMemberOffset(
String uniformStructName, String memberName);
}
| engine/lib/gpu/lib/src/shader.dart/0 | {
"file_path": "engine/lib/gpu/lib/src/shader.dart",
"repo_id": "engine",
"token_count": 506
} | 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.
#ifndef FLUTTER_LIB_GPU_TEXTURE_H_
#define FLUTTER_LIB_GPU_TEXTURE_H_
#include "flutter/lib/gpu/context.h"
#include "flutter/lib/gpu/export.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "impeller/core/formats.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
namespace flutter {
namespace gpu {
class Texture : public RefCountedDartWrappable<Texture> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(Texture);
public:
explicit Texture(std::shared_ptr<impeller::Texture> texture);
~Texture() override;
std::shared_ptr<impeller::Texture> GetTexture();
void SetCoordinateSystem(impeller::TextureCoordinateSystem coordinate_system);
bool Overwrite(const tonic::DartByteData& source_bytes);
size_t GetBytesPerTexel();
Dart_Handle AsImage() const;
private:
std::shared_ptr<impeller::Texture> texture_;
FML_DISALLOW_COPY_AND_ASSIGN(Texture);
};
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
extern "C" {
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_Texture_Initialize(
Dart_Handle wrapper,
flutter::gpu::Context* gpu_context,
int storage_mode,
int format,
int width,
int height,
int sample_count,
int coordinate_system,
bool enable_render_target_usage,
bool enable_shader_read_usage,
bool enable_shader_write_usage);
FLUTTER_GPU_EXPORT
extern void InternalFlutterGpu_Texture_SetCoordinateSystem(
flutter::gpu::Texture* wrapper,
int coordinate_system);
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_Texture_Overwrite(flutter::gpu::Texture* wrapper,
Dart_Handle source_byte_data);
FLUTTER_GPU_EXPORT
extern int InternalFlutterGpu_Texture_BytesPerTexel(
flutter::gpu::Texture* wrapper);
FLUTTER_GPU_EXPORT
extern Dart_Handle InternalFlutterGpu_Texture_AsImage(
flutter::gpu::Texture* wrapper);
} // extern "C"
#endif // FLUTTER_LIB_GPU_TEXTURE_H_
| engine/lib/gpu/texture.h/0 | {
"file_path": "engine/lib/gpu/texture.h",
"repo_id": "engine",
"token_count": 793
} | 231 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_COMPOSITING_SCENE_H_
#define FLUTTER_LIB_UI_COMPOSITING_SCENE_H_
#include <cstdint>
#include <memory>
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/lib/ui/dart_wrapper.h"
namespace flutter {
class Scene : public RefCountedDartWrappable<Scene> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(Scene);
public:
~Scene() override;
static void create(Dart_Handle scene_handle,
std::shared_ptr<flutter::Layer> rootLayer,
uint32_t rasterizerTracingThreshold,
bool checkerboardRasterCacheImages,
bool checkerboardOffscreenLayers);
std::unique_ptr<flutter::LayerTree> takeLayerTree(uint64_t width,
uint64_t height);
Dart_Handle toImageSync(uint32_t width,
uint32_t height,
Dart_Handle raw_image_handle);
Dart_Handle toImage(uint32_t width,
uint32_t height,
Dart_Handle raw_image_handle);
void dispose();
private:
Scene(std::shared_ptr<flutter::Layer> rootLayer,
uint32_t rasterizerTracingThreshold,
bool checkerboardRasterCacheImages,
bool checkerboardOffscreenLayers);
// Returns true if `dispose()` has not been called.
bool valid();
void RasterizeToImage(uint32_t width,
uint32_t height,
Dart_Handle raw_image_handle);
std::unique_ptr<LayerTree> BuildLayerTree(uint32_t width, uint32_t height);
flutter::LayerTree::Config layer_tree_config_;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_COMPOSITING_SCENE_H_
| engine/lib/ui/compositing/scene.h/0 | {
"file_path": "engine/lib/ui/compositing/scene.h",
"repo_id": "engine",
"token_count": 838
} | 232 |
#version 320 es
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
// For a given incident vector I and surface normal N reflect returns the
// reflection direction calculated as I - 2.0 * dot(N, I) * N.
void main() {
// To get [0.0, 1.0] as the output, choose [0.6, 0.8] as N, and solve for I.
// Since the reflection is symmetric:
// I’ = reflect(I)
// I’ = I - 2 dot(N, I) N
// I = I’ - 2 dot(N, I’) N
// N = [0.6, 0.8]
// I’ = [0, 1]
// I = [0, 1] - 2 * 0.8 [0.6, 0.8]
// I = [-0.96, -0.28]
fragColor =
vec4(reflect(vec2(a * -0.96, -0.28), vec2(0.6, 0.8))[0],
reflect(vec2(a * -0.96, -0.28), vec2(0.6, 0.8))[1], 0.0, 1.0);
}
| engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/71_reflect.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/71_reflect.frag",
"repo_id": "engine",
"token_count": 379
} | 233 |
#version 320 es
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
float zero() {
return 0.0;
}
float one() {
return a;
}
void main() {
fragColor = vec4(zero(), one(), zero(), one());
}
| engine/lib/ui/fixtures/shaders/supported_op_shaders/33_OpTypeFunction.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_op_shaders/33_OpTypeFunction.frag",
"repo_id": "engine",
"token_count": 133
} | 234 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/image_decoder_skia.h"
#include <algorithm>
#include "flutter/fml/logging.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/lib/ui/painting/display_list_image_gpu.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h"
namespace flutter {
ImageDecoderSkia::ImageDecoderSkia(
const TaskRunners& runners,
std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner,
fml::WeakPtr<IOManager> io_manager)
: ImageDecoder(runners,
std::move(concurrent_task_runner),
std::move(io_manager)) {}
ImageDecoderSkia::~ImageDecoderSkia() = default;
static sk_sp<SkImage> ResizeRasterImage(const sk_sp<SkImage>& image,
const SkISize& resized_dimensions,
const fml::tracing::TraceFlow& flow) {
FML_DCHECK(!image->isTextureBacked());
TRACE_EVENT0("flutter", __FUNCTION__);
flow.Step(__FUNCTION__);
if (resized_dimensions.isEmpty()) {
FML_LOG(ERROR) << "Could not resize to empty dimensions.";
return nullptr;
}
if (image->dimensions() == resized_dimensions) {
return image->makeRasterImage();
}
const auto scaled_image_info =
image->imageInfo().makeDimensions(resized_dimensions);
SkBitmap scaled_bitmap;
if (!scaled_bitmap.tryAllocPixels(scaled_image_info)) {
FML_LOG(ERROR) << "Failed to allocate memory for bitmap of size "
<< scaled_image_info.computeMinByteSize() << "B";
return nullptr;
}
if (!image->scalePixels(
scaled_bitmap.pixmap(),
SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kNone),
SkImage::kDisallow_CachingHint)) {
FML_LOG(ERROR) << "Could not scale pixels";
return nullptr;
}
// Marking this as immutable makes the MakeFromBitmap call share the pixels
// instead of copying.
scaled_bitmap.setImmutable();
auto scaled_image = SkImages::RasterFromBitmap(scaled_bitmap);
if (!scaled_image) {
FML_LOG(ERROR) << "Could not create a scaled image from a scaled bitmap.";
return nullptr;
}
return scaled_image;
}
static sk_sp<SkImage> ImageFromDecompressedData(
ImageDescriptor* descriptor,
uint32_t target_width,
uint32_t target_height,
const fml::tracing::TraceFlow& flow) {
TRACE_EVENT0("flutter", __FUNCTION__);
flow.Step(__FUNCTION__);
auto image = SkImages::RasterFromData(
descriptor->image_info(), descriptor->data(), descriptor->row_bytes());
if (!image) {
FML_LOG(ERROR) << "Could not create image from decompressed bytes.";
return nullptr;
}
if (!target_width && !target_height) {
// No resizing requested. Just rasterize the image.
return image->makeRasterImage();
}
return ResizeRasterImage(image, SkISize::Make(target_width, target_height),
flow);
}
sk_sp<SkImage> ImageDecoderSkia::ImageFromCompressedData(
ImageDescriptor* descriptor,
uint32_t target_width,
uint32_t target_height,
const fml::tracing::TraceFlow& flow) {
TRACE_EVENT0("flutter", __FUNCTION__);
flow.Step(__FUNCTION__);
if (!descriptor->should_resize(target_width, target_height)) {
// No resizing requested. Just decode & rasterize the image.
sk_sp<SkImage> image = descriptor->image();
return image ? image->makeRasterImage() : nullptr;
}
const SkISize source_dimensions = descriptor->image_info().dimensions();
const SkISize resized_dimensions = {static_cast<int32_t>(target_width),
static_cast<int32_t>(target_height)};
auto decode_dimensions = descriptor->get_scaled_dimensions(
std::max(static_cast<float>(resized_dimensions.width()) /
source_dimensions.width(),
static_cast<float>(resized_dimensions.height()) /
source_dimensions.height()));
// If the codec supports efficient sub-pixel decoding, decoded at a resolution
// close to the target resolution before resizing.
if (decode_dimensions != source_dimensions) {
auto scaled_image_info =
descriptor->image_info().makeDimensions(decode_dimensions);
SkBitmap scaled_bitmap;
if (!scaled_bitmap.tryAllocPixels(scaled_image_info)) {
FML_LOG(ERROR) << "Failed to allocate memory for bitmap of size "
<< scaled_image_info.computeMinByteSize() << "B";
return nullptr;
}
const auto& pixmap = scaled_bitmap.pixmap();
if (descriptor->get_pixels(pixmap)) {
// Marking this as immutable makes the MakeFromBitmap call share
// the pixels instead of copying.
scaled_bitmap.setImmutable();
auto decoded_image = SkImages::RasterFromBitmap(scaled_bitmap);
FML_DCHECK(decoded_image);
if (!decoded_image) {
FML_LOG(ERROR)
<< "Could not create a scaled image from a scaled bitmap.";
return nullptr;
}
return ResizeRasterImage(decoded_image, resized_dimensions, flow);
}
}
auto image = descriptor->image();
if (!image) {
return nullptr;
}
return ResizeRasterImage(image, resized_dimensions, flow);
}
static SkiaGPUObject<SkImage> UploadRasterImage(
sk_sp<SkImage> image,
const fml::WeakPtr<IOManager>& io_manager,
const fml::tracing::TraceFlow& flow) {
TRACE_EVENT0("flutter", __FUNCTION__);
flow.Step(__FUNCTION__);
// Should not already be a texture image because that is the entire point of
// the this method.
FML_DCHECK(!image->isTextureBacked());
if (!io_manager->GetResourceContext() || !io_manager->GetSkiaUnrefQueue()) {
FML_LOG(ERROR)
<< "Could not acquire context of release queue for texture upload.";
return {};
}
SkPixmap pixmap;
if (!image->peekPixels(&pixmap)) {
FML_LOG(ERROR) << "Could not peek pixels of image for texture upload.";
return {};
}
SkiaGPUObject<SkImage> result;
io_manager->GetIsGpuDisabledSyncSwitch()->Execute(
fml::SyncSwitch::Handlers()
.SetIfTrue([&result, &pixmap, &image] {
SkSafeRef(image.get());
sk_sp<SkImage> texture_image = SkImages::RasterFromPixmap(
pixmap,
[](const void* pixels, SkImages::ReleaseContext context) {
SkSafeUnref(static_cast<SkImage*>(context));
},
image.get());
result = {std::move(texture_image), nullptr};
})
.SetIfFalse([&result, context = io_manager->GetResourceContext(),
&pixmap, queue = io_manager->GetSkiaUnrefQueue()] {
TRACE_EVENT0("flutter", "MakeCrossContextImageFromPixmap");
sk_sp<SkImage> texture_image =
SkImages::CrossContextTextureFromPixmap(
context.get(), // context
pixmap, // pixmap
true, // buildMips,
true // limitToMaxTextureSize
);
if (!texture_image) {
FML_LOG(ERROR) << "Could not make x-context image.";
result = {};
} else {
result = {std::move(texture_image), queue};
}
}));
return result;
}
// |ImageDecoder|
void ImageDecoderSkia::Decode(fml::RefPtr<ImageDescriptor> descriptor_ref_ptr,
uint32_t target_width,
uint32_t target_height,
const ImageResult& callback) {
TRACE_EVENT0("flutter", __FUNCTION__);
fml::tracing::TraceFlow flow(__FUNCTION__);
// ImageDescriptors have Dart peers that must be collected on the UI thread.
// However, closures in MakeCopyable below capture the descriptor. The
// captures of copyable closures may be collected on any of the thread
// participating in task execution.
//
// To avoid this issue, we resort to manually reference counting the
// descriptor. Since all task flows invoke the `result` callback, the raw
// descriptor is retained in the beginning and released in the `result`
// callback.
//
// `ImageDecoder::Decode` itself is invoked on the UI thread, so the
// collection of the smart pointer from which we obtained the raw descriptor
// is fine in this scope.
auto raw_descriptor = descriptor_ref_ptr.get();
raw_descriptor->AddRef();
FML_DCHECK(callback);
FML_DCHECK(runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
// Always service the callback (and cleanup the descriptor) on the UI thread.
auto result =
[callback, raw_descriptor, ui_runner = runners_.GetUITaskRunner()](
SkiaGPUObject<SkImage> image, fml::tracing::TraceFlow flow) {
ui_runner->PostTask(fml::MakeCopyable(
[callback, raw_descriptor, image = std::move(image),
flow = std::move(flow)]() mutable {
// We are going to terminate the trace flow here. Flows cannot
// terminate without a base trace. Add one explicitly.
TRACE_EVENT0("flutter", "ImageDecodeCallback");
flow.End();
callback(DlImageGPU::Make(std::move(image)), {});
raw_descriptor->Release();
}));
};
if (!raw_descriptor->data() || raw_descriptor->data()->size() == 0) {
result({}, std::move(flow));
return;
}
concurrent_task_runner_->PostTask(
fml::MakeCopyable([raw_descriptor, //
io_manager = io_manager_, //
io_runner = runners_.GetIOTaskRunner(), //
result, //
target_width = target_width, //
target_height = target_height, //
flow = std::move(flow) //
]() mutable {
// Step 1: Decompress the image.
// On Worker.
auto decompressed = raw_descriptor->is_compressed()
? ImageFromCompressedData(raw_descriptor, //
target_width, //
target_height, //
flow)
: ImageFromDecompressedData(raw_descriptor, //
target_width, //
target_height, //
flow);
if (!decompressed) {
FML_DLOG(ERROR) << "Could not decompress image.";
result({}, std::move(flow));
return;
}
// Step 2: Update the image to the GPU.
// On IO Thread.
io_runner->PostTask(fml::MakeCopyable([io_manager, decompressed, result,
flow =
std::move(flow)]() mutable {
if (!io_manager) {
FML_DLOG(ERROR) << "Could not acquire IO manager.";
result({}, std::move(flow));
return;
}
// If the IO manager does not have a resource context, the caller
// might not have set one or a software backend could be in use.
// Either way, just return the image as-is.
if (!io_manager->GetResourceContext()) {
result({std::move(decompressed), io_manager->GetSkiaUnrefQueue()},
std::move(flow));
return;
}
auto uploaded =
UploadRasterImage(std::move(decompressed), io_manager, flow);
if (!uploaded.skia_object()) {
FML_DLOG(ERROR) << "Could not upload image to the GPU.";
result({}, std::move(flow));
return;
}
// Finally, all done.
result(std::move(uploaded), std::move(flow));
}));
}));
}
} // namespace flutter
| engine/lib/ui/painting/image_decoder_skia.cc/0 | {
"file_path": "engine/lib/ui/painting/image_decoder_skia.cc",
"repo_id": "engine",
"token_count": 5556
} | 235 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/image_generator.h"
#include <utility>
#include "flutter/fml/logging.h"
#include "third_party/skia/include/codec/SkEncodedOrigin.h"
#include "third_party/skia/include/codec/SkPixmapUtils.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkImage.h"
namespace flutter {
ImageGenerator::~ImageGenerator() = default;
sk_sp<SkImage> ImageGenerator::GetImage() {
SkImageInfo info = GetInfo();
SkBitmap bitmap;
if (!bitmap.tryAllocPixels(info)) {
FML_DLOG(ERROR) << "Failed to allocate memory for bitmap of size "
<< info.computeMinByteSize() << "B";
return nullptr;
}
const auto& pixmap = bitmap.pixmap();
if (!GetPixels(pixmap.info(), pixmap.writable_addr(), pixmap.rowBytes())) {
FML_DLOG(ERROR) << "Failed to get pixels for image.";
return nullptr;
}
bitmap.setImmutable();
return SkImages::RasterFromBitmap(bitmap);
}
BuiltinSkiaImageGenerator::~BuiltinSkiaImageGenerator() = default;
BuiltinSkiaImageGenerator::BuiltinSkiaImageGenerator(
std::unique_ptr<SkImageGenerator> generator)
: generator_(std::move(generator)) {}
const SkImageInfo& BuiltinSkiaImageGenerator::GetInfo() {
return generator_->getInfo();
}
unsigned int BuiltinSkiaImageGenerator::GetFrameCount() const {
return 1;
}
unsigned int BuiltinSkiaImageGenerator::GetPlayCount() const {
return 1;
}
const ImageGenerator::FrameInfo BuiltinSkiaImageGenerator::GetFrameInfo(
unsigned int frame_index) {
return {.required_frame = std::nullopt,
.duration = 0,
.disposal_method = SkCodecAnimation::DisposalMethod::kKeep};
}
SkISize BuiltinSkiaImageGenerator::GetScaledDimensions(float desired_scale) {
return generator_->getInfo().dimensions();
}
bool BuiltinSkiaImageGenerator::GetPixels(
const SkImageInfo& info,
void* pixels,
size_t row_bytes,
unsigned int frame_index,
std::optional<unsigned int> prior_frame) {
return generator_->getPixels(info, pixels, row_bytes);
}
std::unique_ptr<ImageGenerator> BuiltinSkiaImageGenerator::MakeFromGenerator(
std::unique_ptr<SkImageGenerator> generator) {
if (!generator) {
return nullptr;
}
return std::make_unique<BuiltinSkiaImageGenerator>(std::move(generator));
}
BuiltinSkiaCodecImageGenerator::~BuiltinSkiaCodecImageGenerator() = default;
static SkImageInfo getInfoIncludingExif(SkCodec* codec) {
SkImageInfo info = codec->getInfo();
if (SkEncodedOriginSwapsWidthHeight(codec->getOrigin())) {
info = SkPixmapUtils::SwapWidthHeight(info);
}
if (kUnpremul_SkAlphaType == info.alphaType()) {
// Prefer premul over unpremul (this produces better filtering in general)
info = info.makeAlphaType(kPremul_SkAlphaType);
}
return info;
}
BuiltinSkiaCodecImageGenerator::BuiltinSkiaCodecImageGenerator(
std::unique_ptr<SkCodec> codec)
: codec_(std::move(codec)) {
image_info_ = getInfoIncludingExif(codec_.get());
}
BuiltinSkiaCodecImageGenerator::BuiltinSkiaCodecImageGenerator(
sk_sp<SkData> buffer)
: codec_(SkCodec::MakeFromData(std::move(buffer)).release()) {
image_info_ = getInfoIncludingExif(codec_.get());
}
const SkImageInfo& BuiltinSkiaCodecImageGenerator::GetInfo() {
return image_info_;
}
unsigned int BuiltinSkiaCodecImageGenerator::GetFrameCount() const {
return codec_->getFrameCount();
}
unsigned int BuiltinSkiaCodecImageGenerator::GetPlayCount() const {
auto repetition_count = codec_->getRepetitionCount();
return repetition_count < 0 ? kInfinitePlayCount : repetition_count + 1;
}
const ImageGenerator::FrameInfo BuiltinSkiaCodecImageGenerator::GetFrameInfo(
unsigned int frame_index) {
SkCodec::FrameInfo info = {};
codec_->getFrameInfo(frame_index, &info);
return {
.required_frame = info.fRequiredFrame == SkCodec::kNoFrame
? std::nullopt
: std::optional<unsigned int>(info.fRequiredFrame),
.duration = static_cast<unsigned int>(info.fDuration),
.disposal_method = info.fDisposalMethod};
}
SkISize BuiltinSkiaCodecImageGenerator::GetScaledDimensions(
float desired_scale) {
SkISize size = codec_->getScaledDimensions(desired_scale);
if (SkEncodedOriginSwapsWidthHeight(codec_->getOrigin())) {
std::swap(size.fWidth, size.fHeight);
}
return size;
}
bool BuiltinSkiaCodecImageGenerator::GetPixels(
const SkImageInfo& info,
void* pixels,
size_t row_bytes,
unsigned int frame_index,
std::optional<unsigned int> prior_frame) {
SkCodec::Options options;
options.fFrameIndex = frame_index;
if (prior_frame.has_value()) {
options.fPriorFrame = prior_frame.value();
}
SkEncodedOrigin origin = codec_->getOrigin();
SkPixmap output_pixmap(info, pixels, row_bytes);
SkPixmap temp_pixmap;
SkBitmap temp_bitmap;
if (origin == kTopLeft_SkEncodedOrigin) {
// We can decode directly into the output buffer.
temp_pixmap = output_pixmap;
} else {
// We need to decode into a different buffer so we can re-orient
// the pixels later.
SkImageInfo temp_info = output_pixmap.info();
if (SkEncodedOriginSwapsWidthHeight(origin)) {
// We'll be decoding into a buffer that has height and width swapped.
temp_info = SkPixmapUtils::SwapWidthHeight(temp_info);
}
if (!temp_bitmap.tryAllocPixels(temp_info)) {
FML_DLOG(ERROR) << "Failed to allocate memory for bitmap of size "
<< temp_info.computeMinByteSize() << "B";
return false;
}
temp_pixmap = temp_bitmap.pixmap();
}
SkCodec::Result result = codec_->getPixels(temp_pixmap, &options);
if (result != SkCodec::kSuccess) {
FML_DLOG(WARNING) << "codec could not get pixels. "
<< SkCodec::ResultToString(result);
return false;
}
if (origin == kTopLeft_SkEncodedOrigin) {
return true;
}
return SkPixmapUtils::Orient(output_pixmap, temp_pixmap, origin);
}
std::unique_ptr<ImageGenerator> BuiltinSkiaCodecImageGenerator::MakeFromData(
sk_sp<SkData> data) {
auto codec = SkCodec::MakeFromData(std::move(data));
if (!codec) {
return nullptr;
}
return std::make_unique<BuiltinSkiaCodecImageGenerator>(std::move(codec));
}
} // namespace flutter
| engine/lib/ui/painting/image_generator.cc/0 | {
"file_path": "engine/lib/ui/painting/image_generator.cc",
"repo_id": "engine",
"token_count": 2384
} | 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.
#ifndef FLUTTER_LIB_UI_PAINTING_PAINT_H_
#define FLUTTER_LIB_UI_PAINTING_PAINT_H_
#include "flutter/display_list/display_list.h"
#include "flutter/display_list/dl_op_flags.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/tonic/converter/dart_converter.h"
namespace flutter {
class Paint {
public:
Paint() = default;
Paint(Dart_Handle paint_objects, Dart_Handle paint_data);
const DlPaint* paint(DlPaint& paint,
const DisplayListAttributeFlags& flags) const;
void toDlPaint(DlPaint& paint) const;
bool isNull() const { return Dart_IsNull(paint_data_); }
bool isNotNull() const { return !Dart_IsNull(paint_data_); }
private:
friend struct tonic::DartConverter<Paint>;
Dart_Handle paint_objects_;
Dart_Handle paint_data_;
};
// The PaintData argument is a placeholder to receive encoded data for Paint
// objects. The data is actually processed by DartConverter<Paint>, which reads
// both at the given index and at the next index (which it assumes is a byte
// data for a Paint object).
class PaintData {};
} // namespace flutter
namespace tonic {
template <>
struct DartConverter<flutter::Paint> {
static flutter::Paint FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception);
};
template <>
struct DartConverter<flutter::PaintData> {
static flutter::PaintData FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception);
};
} // namespace tonic
#endif // FLUTTER_LIB_UI_PAINTING_PAINT_H_
| engine/lib/ui/painting/paint.h/0 | {
"file_path": "engine/lib/ui/painting/paint.h",
"repo_id": "engine",
"token_count": 739
} | 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_LIB_UI_PAINTING_SCENE_SCENE_SHADER_H_
#define FLUTTER_LIB_UI_PAINTING_SCENE_SCENE_SHADER_H_
#include <string>
#include <vector>
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/painting/scene/scene_node.h"
#include "flutter/lib/ui/painting/shader.h"
#include "impeller/geometry/matrix.h"
#include "third_party/tonic/dart_library_natives.h"
namespace flutter {
class SceneShader : public Shader {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(SceneShader);
public:
~SceneShader() override;
static void Create(Dart_Handle wrapper, Dart_Handle scene_node_handle);
void SetCameraTransform(const tonic::Float64List& matrix4);
void Dispose();
// |Shader|
std::shared_ptr<DlColorSource> shader(DlImageSampling) override;
private:
explicit SceneShader(fml::RefPtr<SceneNode> scene_node);
impeller::Matrix camera_transform_;
fml::RefPtr<SceneNode> scene_node_;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_SCENE_SCENE_SHADER_H_
| engine/lib/ui/painting/scene/scene_shader.h/0 | {
"file_path": "engine/lib/ui/painting/scene/scene_shader.h",
"repo_id": "engine",
"token_count": 435
} | 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_LIB_UI_SEMANTICS_CUSTOM_ACCESSIBILITY_ACTION_H_
#define FLUTTER_LIB_UI_SEMANTICS_CUSTOM_ACCESSIBILITY_ACTION_H_
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_wrappable.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace flutter {
/// A custom accessibility action is used to indicate additional semantics
/// actions that a user can perform on a semantics node beyond the
/// preconfigured options.
struct CustomAccessibilityAction {
CustomAccessibilityAction();
~CustomAccessibilityAction();
int32_t id = 0;
int32_t overrideId = -1;
std::string label;
std::string hint;
};
// Contains custom accessibility actions that need to be updated.
//
// The keys in the map are stable action IDs, and the values contain
// semantic information for the action corresponding to that id.
using CustomAccessibilityActionUpdates =
std::unordered_map<int32_t, CustomAccessibilityAction>;
} // namespace flutter
#endif // FLUTTER_LIB_UI_SEMANTICS_CUSTOM_ACCESSIBILITY_ACTION_H_
| engine/lib/ui/semantics/custom_accessibility_action.h/0 | {
"file_path": "engine/lib/ui/semantics/custom_accessibility_action.h",
"repo_id": "engine",
"token_count": 382
} | 239 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_H_
#define FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_H_
#include <memory>
#include <vector>
#include "flutter/assets/asset_manager.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "third_party/tonic/typed_data/typed_list.h"
#include "txt/font_collection.h"
namespace flutter {
class FontCollection {
public:
FontCollection();
virtual ~FontCollection();
std::shared_ptr<txt::FontCollection> GetFontCollection() const;
void SetupDefaultFontManager(uint32_t font_initialization_data);
// Virtual for testing.
virtual void RegisterFonts(
const std::shared_ptr<AssetManager>& asset_manager);
void RegisterTestFonts();
static void LoadFontFromList(Dart_Handle font_data_handle,
Dart_Handle callback,
const std::string& family_name);
private:
std::shared_ptr<txt::FontCollection> collection_;
sk_sp<txt::DynamicFontManager> dynamic_font_manager_;
FML_DISALLOW_COPY_AND_ASSIGN(FontCollection);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_TEXT_FONT_COLLECTION_H_
| engine/lib/ui/text/font_collection.h/0 | {
"file_path": "engine/lib/ui/text/font_collection.h",
"repo_id": "engine",
"token_count": 482
} | 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.
#include "flutter/lib/ui/window/platform_configuration.h"
#include <cstring>
#include "flutter/common/constants.h"
#include "flutter/lib/ui/compositing/scene.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/lib/ui/window/platform_message_response_dart.h"
#include "flutter/lib/ui/window/platform_message_response_dart_port.h"
#include "flutter/lib/ui/window/viewport_metrics.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
namespace flutter {
namespace {
Dart_Handle ToByteData(const fml::Mapping& buffer) {
return tonic::DartByteData::Create(buffer.GetMapping(), buffer.GetSize());
}
} // namespace
PlatformConfigurationClient::~PlatformConfigurationClient() {}
PlatformConfiguration::PlatformConfiguration(
PlatformConfigurationClient* client)
: client_(client) {}
PlatformConfiguration::~PlatformConfiguration() {}
void PlatformConfiguration::DidCreateIsolate() {
Dart_Handle library = Dart_LookupLibrary(tonic::ToDart("dart:ui"));
on_error_.Set(tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_onError")));
add_view_.Set(tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_addView")));
remove_view_.Set(tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_removeView")));
update_window_metrics_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_updateWindowMetrics")));
update_displays_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_updateDisplays")));
update_locales_.Set(tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_updateLocales")));
update_user_settings_data_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_updateUserSettingsData")));
update_initial_lifecycle_state_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_updateInitialLifecycleState")));
update_semantics_enabled_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_updateSemanticsEnabled")));
update_accessibility_features_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_updateAccessibilityFeatures")));
dispatch_platform_message_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_dispatchPlatformMessage")));
dispatch_pointer_data_packet_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_dispatchPointerDataPacket")));
dispatch_semantics_action_.Set(
tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_dispatchSemanticsAction")));
begin_frame_.Set(tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_beginFrame")));
draw_frame_.Set(tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_drawFrame")));
report_timings_.Set(tonic::DartState::Current(),
Dart_GetField(library, tonic::ToDart("_reportTimings")));
}
void PlatformConfiguration::AddView(int64_t view_id,
const ViewportMetrics& view_metrics) {
auto [view_iterator, insertion_happened] =
metrics_.emplace(view_id, view_metrics);
FML_DCHECK(insertion_happened);
std::shared_ptr<tonic::DartState> dart_state = add_view_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(tonic::DartInvoke(
add_view_.Get(),
{
tonic::ToDart(view_id),
tonic::ToDart(view_metrics.device_pixel_ratio),
tonic::ToDart(view_metrics.physical_width),
tonic::ToDart(view_metrics.physical_height),
tonic::ToDart(view_metrics.physical_padding_top),
tonic::ToDart(view_metrics.physical_padding_right),
tonic::ToDart(view_metrics.physical_padding_bottom),
tonic::ToDart(view_metrics.physical_padding_left),
tonic::ToDart(view_metrics.physical_view_inset_top),
tonic::ToDart(view_metrics.physical_view_inset_right),
tonic::ToDart(view_metrics.physical_view_inset_bottom),
tonic::ToDart(view_metrics.physical_view_inset_left),
tonic::ToDart(view_metrics.physical_system_gesture_inset_top),
tonic::ToDart(view_metrics.physical_system_gesture_inset_right),
tonic::ToDart(view_metrics.physical_system_gesture_inset_bottom),
tonic::ToDart(view_metrics.physical_system_gesture_inset_left),
tonic::ToDart(view_metrics.physical_touch_slop),
tonic::ToDart(view_metrics.physical_display_features_bounds),
tonic::ToDart(view_metrics.physical_display_features_type),
tonic::ToDart(view_metrics.physical_display_features_state),
tonic::ToDart(view_metrics.display_id),
}));
}
bool PlatformConfiguration::RemoveView(int64_t view_id) {
if (view_id == kFlutterImplicitViewId) {
FML_LOG(FATAL) << "The implicit view #" << view_id << " cannot be removed.";
return false;
}
size_t erased_elements = metrics_.erase(view_id);
if (erased_elements == 0) {
FML_LOG(ERROR) << "View #" << view_id << " doesn't exist.";
return false;
}
std::shared_ptr<tonic::DartState> dart_state =
remove_view_.dart_state().lock();
if (!dart_state) {
return false;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(
tonic::DartInvoke(remove_view_.Get(), {
tonic::ToDart(view_id),
}));
return true;
}
bool PlatformConfiguration::UpdateViewMetrics(
int64_t view_id,
const ViewportMetrics& view_metrics) {
auto found_iter = metrics_.find(view_id);
if (found_iter == metrics_.end()) {
return false;
}
found_iter->second = view_metrics;
std::shared_ptr<tonic::DartState> dart_state =
update_window_metrics_.dart_state().lock();
if (!dart_state) {
return false;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(tonic::DartInvoke(
update_window_metrics_.Get(),
{
tonic::ToDart(view_id),
tonic::ToDart(view_metrics.device_pixel_ratio),
tonic::ToDart(view_metrics.physical_width),
tonic::ToDart(view_metrics.physical_height),
tonic::ToDart(view_metrics.physical_padding_top),
tonic::ToDart(view_metrics.physical_padding_right),
tonic::ToDart(view_metrics.physical_padding_bottom),
tonic::ToDart(view_metrics.physical_padding_left),
tonic::ToDart(view_metrics.physical_view_inset_top),
tonic::ToDart(view_metrics.physical_view_inset_right),
tonic::ToDart(view_metrics.physical_view_inset_bottom),
tonic::ToDart(view_metrics.physical_view_inset_left),
tonic::ToDart(view_metrics.physical_system_gesture_inset_top),
tonic::ToDart(view_metrics.physical_system_gesture_inset_right),
tonic::ToDart(view_metrics.physical_system_gesture_inset_bottom),
tonic::ToDart(view_metrics.physical_system_gesture_inset_left),
tonic::ToDart(view_metrics.physical_touch_slop),
tonic::ToDart(view_metrics.physical_display_features_bounds),
tonic::ToDart(view_metrics.physical_display_features_type),
tonic::ToDart(view_metrics.physical_display_features_state),
tonic::ToDart(view_metrics.display_id),
}));
return true;
}
void PlatformConfiguration::UpdateDisplays(
const std::vector<DisplayData>& displays) {
std::vector<DisplayId> ids;
std::vector<double> widths;
std::vector<double> heights;
std::vector<double> device_pixel_ratios;
std::vector<double> refresh_rates;
for (const auto& display : displays) {
ids.push_back(display.id);
widths.push_back(display.width);
heights.push_back(display.height);
device_pixel_ratios.push_back(display.pixel_ratio);
refresh_rates.push_back(display.refresh_rate);
}
std::shared_ptr<tonic::DartState> dart_state =
update_displays_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(tonic::DartInvoke(
update_displays_.Get(),
{
tonic::ToDart<std::vector<DisplayId>>(ids),
tonic::ToDart<std::vector<double>>(widths),
tonic::ToDart<std::vector<double>>(heights),
tonic::ToDart<std::vector<double>>(device_pixel_ratios),
tonic::ToDart<std::vector<double>>(refresh_rates),
}));
}
void PlatformConfiguration::UpdateLocales(
const std::vector<std::string>& locales) {
std::shared_ptr<tonic::DartState> dart_state =
update_locales_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(
tonic::DartInvoke(update_locales_.Get(),
{
tonic::ToDart<std::vector<std::string>>(locales),
}));
}
void PlatformConfiguration::UpdateUserSettingsData(const std::string& data) {
std::shared_ptr<tonic::DartState> dart_state =
update_user_settings_data_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(tonic::DartInvoke(update_user_settings_data_.Get(),
{
tonic::StdStringToDart(data),
}));
}
void PlatformConfiguration::UpdateInitialLifecycleState(
const std::string& data) {
std::shared_ptr<tonic::DartState> dart_state =
update_initial_lifecycle_state_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(tonic::DartInvoke(
update_initial_lifecycle_state_.Get(), {
tonic::StdStringToDart(data),
}));
}
void PlatformConfiguration::UpdateSemanticsEnabled(bool enabled) {
std::shared_ptr<tonic::DartState> dart_state =
update_semantics_enabled_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
UIDartState::ThrowIfUIOperationsProhibited();
tonic::CheckAndHandleError(tonic::DartInvoke(update_semantics_enabled_.Get(),
{tonic::ToDart(enabled)}));
}
void PlatformConfiguration::UpdateAccessibilityFeatures(int32_t values) {
std::shared_ptr<tonic::DartState> dart_state =
update_accessibility_features_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::CheckAndHandleError(tonic::DartInvoke(
update_accessibility_features_.Get(), {tonic::ToDart(values)}));
}
void PlatformConfiguration::DispatchPlatformMessage(
std::unique_ptr<PlatformMessage> message) {
std::shared_ptr<tonic::DartState> dart_state =
dispatch_platform_message_.dart_state().lock();
if (!dart_state) {
FML_DLOG(WARNING)
<< "Dropping platform message for lack of DartState on channel: "
<< message->channel();
return;
}
tonic::DartState::Scope scope(dart_state);
Dart_Handle data_handle =
(message->hasData()) ? ToByteData(message->data()) : Dart_Null();
if (Dart_IsError(data_handle)) {
FML_DLOG(WARNING)
<< "Dropping platform message because of a Dart error on channel: "
<< message->channel();
return;
}
int response_id = 0;
if (auto response = message->response()) {
response_id = next_response_id_++;
pending_responses_[response_id] = response;
}
tonic::CheckAndHandleError(
tonic::DartInvoke(dispatch_platform_message_.Get(),
{tonic::ToDart(message->channel()), data_handle,
tonic::ToDart(response_id)}));
}
void PlatformConfiguration::DispatchPointerDataPacket(
const PointerDataPacket& packet) {
std::shared_ptr<tonic::DartState> dart_state =
dispatch_pointer_data_packet_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
const std::vector<uint8_t>& buffer = packet.data();
Dart_Handle data_handle =
tonic::DartByteData::Create(buffer.data(), buffer.size());
if (Dart_IsError(data_handle)) {
return;
}
tonic::CheckAndHandleError(
tonic::DartInvoke(dispatch_pointer_data_packet_.Get(), {data_handle}));
}
void PlatformConfiguration::DispatchSemanticsAction(int32_t node_id,
SemanticsAction action,
fml::MallocMapping args) {
std::shared_ptr<tonic::DartState> dart_state =
dispatch_semantics_action_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
Dart_Handle args_handle =
(args.GetSize() <= 0) ? Dart_Null() : ToByteData(args);
if (Dart_IsError(args_handle)) {
return;
}
tonic::CheckAndHandleError(tonic::DartInvoke(
dispatch_semantics_action_.Get(),
{tonic::ToDart(node_id), tonic::ToDart(static_cast<int32_t>(action)),
args_handle}));
}
void PlatformConfiguration::BeginFrame(fml::TimePoint frameTime,
uint64_t frame_number) {
std::shared_ptr<tonic::DartState> dart_state =
begin_frame_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
int64_t microseconds = (frameTime - fml::TimePoint()).ToMicroseconds();
tonic::CheckAndHandleError(
tonic::DartInvoke(begin_frame_.Get(), {
Dart_NewInteger(microseconds),
Dart_NewInteger(frame_number),
}));
UIDartState::Current()->FlushMicrotasksNow();
tonic::CheckAndHandleError(tonic::DartInvokeVoid(draw_frame_.Get()));
}
void PlatformConfiguration::ReportTimings(std::vector<int64_t> timings) {
std::shared_ptr<tonic::DartState> dart_state =
report_timings_.dart_state().lock();
if (!dart_state) {
return;
}
tonic::DartState::Scope scope(dart_state);
Dart_Handle data_handle =
Dart_NewTypedData(Dart_TypedData_kInt64, timings.size());
Dart_TypedData_Type type;
void* data = nullptr;
intptr_t num_acquired = 0;
FML_CHECK(!Dart_IsError(
Dart_TypedDataAcquireData(data_handle, &type, &data, &num_acquired)));
FML_DCHECK(num_acquired == static_cast<int>(timings.size()));
memcpy(data, timings.data(), sizeof(int64_t) * timings.size());
FML_CHECK(Dart_TypedDataReleaseData(data_handle));
tonic::CheckAndHandleError(
tonic::DartInvoke(report_timings_.Get(), {
data_handle,
}));
}
const ViewportMetrics* PlatformConfiguration::GetMetrics(int view_id) {
auto found = metrics_.find(view_id);
if (found != metrics_.end()) {
return &found->second;
} else {
return nullptr;
}
}
void PlatformConfiguration::CompletePlatformMessageEmptyResponse(
int response_id) {
if (!response_id) {
return;
}
auto it = pending_responses_.find(response_id);
if (it == pending_responses_.end()) {
return;
}
auto response = std::move(it->second);
pending_responses_.erase(it);
response->CompleteEmpty();
}
void PlatformConfiguration::CompletePlatformMessageResponse(
int response_id,
std::vector<uint8_t> data) {
if (!response_id) {
return;
}
auto it = pending_responses_.find(response_id);
if (it == pending_responses_.end()) {
return;
}
auto response = std::move(it->second);
pending_responses_.erase(it);
response->Complete(std::make_unique<fml::DataMapping>(std::move(data)));
}
void PlatformConfigurationNativeApi::Render(int64_t view_id,
Scene* scene,
double width,
double height) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->Render(
view_id, scene, width, height);
}
void PlatformConfigurationNativeApi::SetNeedsReportTimings(bool value) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()
->platform_configuration()
->client()
->SetNeedsReportTimings(value);
}
namespace {
Dart_Handle HandlePlatformMessage(
UIDartState* dart_state,
const std::string& name,
Dart_Handle data_handle,
const fml::RefPtr<PlatformMessageResponse>& response) {
if (Dart_IsNull(data_handle)) {
return dart_state->HandlePlatformMessage(
std::make_unique<PlatformMessage>(name, response));
} else {
tonic::DartByteData data(data_handle);
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
return dart_state->HandlePlatformMessage(std::make_unique<PlatformMessage>(
name, fml::MallocMapping::Copy(buffer, data.length_in_bytes()),
response));
}
}
} // namespace
Dart_Handle PlatformConfigurationNativeApi::SendPlatformMessage(
const std::string& name,
Dart_Handle callback,
Dart_Handle data_handle) {
UIDartState* dart_state = UIDartState::Current();
if (!dart_state->platform_configuration()) {
return tonic::ToDart(
"SendPlatformMessage only works on the root isolate, see "
"SendPortPlatformMessage.");
}
fml::RefPtr<PlatformMessageResponse> response;
if (!Dart_IsNull(callback)) {
response = fml::MakeRefCounted<PlatformMessageResponseDart>(
tonic::DartPersistentValue(dart_state, callback),
dart_state->GetTaskRunners().GetUITaskRunner(), name);
}
return HandlePlatformMessage(dart_state, name, data_handle, response);
}
Dart_Handle PlatformConfigurationNativeApi::SendPortPlatformMessage(
const std::string& name,
Dart_Handle identifier,
Dart_Handle send_port,
Dart_Handle data_handle) {
// This can be executed on any isolate.
UIDartState* dart_state = UIDartState::Current();
int64_t c_send_port = tonic::DartConverter<int64_t>::FromDart(send_port);
if (c_send_port == ILLEGAL_PORT) {
return tonic::ToDart("Invalid port specified");
}
fml::RefPtr<PlatformMessageResponse> response =
fml::MakeRefCounted<PlatformMessageResponseDartPort>(
c_send_port, tonic::DartConverter<int64_t>::FromDart(identifier),
name);
return HandlePlatformMessage(dart_state, name, data_handle, response);
}
void PlatformConfigurationNativeApi::RespondToPlatformMessage(
int response_id,
const tonic::DartByteData& data) {
if (Dart_IsNull(data.dart_handle())) {
UIDartState::Current()
->platform_configuration()
->CompletePlatformMessageEmptyResponse(response_id);
} else {
// TODO(engine): Avoid this copy.
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
UIDartState::Current()
->platform_configuration()
->CompletePlatformMessageResponse(
response_id,
std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()));
}
}
void PlatformConfigurationNativeApi::SetIsolateDebugName(
const std::string& name) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->SetDebugName(name);
}
Dart_PerformanceMode PlatformConfigurationNativeApi::current_performance_mode_ =
Dart_PerformanceMode_Default;
Dart_PerformanceMode PlatformConfigurationNativeApi::GetDartPerformanceMode() {
return current_performance_mode_;
}
int PlatformConfigurationNativeApi::RequestDartPerformanceMode(int mode) {
UIDartState::ThrowIfUIOperationsProhibited();
current_performance_mode_ = static_cast<Dart_PerformanceMode>(mode);
return Dart_SetPerformanceMode(current_performance_mode_);
}
Dart_Handle PlatformConfigurationNativeApi::GetPersistentIsolateData() {
UIDartState::ThrowIfUIOperationsProhibited();
auto persistent_isolate_data = UIDartState::Current()
->platform_configuration()
->client()
->GetPersistentIsolateData();
if (!persistent_isolate_data) {
return Dart_Null();
}
return tonic::DartByteData::Create(persistent_isolate_data->GetMapping(),
persistent_isolate_data->GetSize());
}
void PlatformConfigurationNativeApi::ScheduleFrame() {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->ScheduleFrame();
}
void PlatformConfigurationNativeApi::EndWarmUpFrame() {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->EndWarmUpFrame();
}
void PlatformConfigurationNativeApi::UpdateSemantics(SemanticsUpdate* update) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()->platform_configuration()->client()->UpdateSemantics(
update);
}
Dart_Handle PlatformConfigurationNativeApi::ComputePlatformResolvedLocale(
Dart_Handle supportedLocalesHandle) {
UIDartState::ThrowIfUIOperationsProhibited();
std::vector<std::string> supportedLocales =
tonic::DartConverter<std::vector<std::string>>::FromDart(
supportedLocalesHandle);
std::vector<std::string> results =
*UIDartState::Current()
->platform_configuration()
->client()
->ComputePlatformResolvedLocale(supportedLocales);
return tonic::DartConverter<std::vector<std::string>>::ToDart(results);
}
std::string PlatformConfigurationNativeApi::DefaultRouteName() {
UIDartState::ThrowIfUIOperationsProhibited();
return UIDartState::Current()
->platform_configuration()
->client()
->DefaultRouteName();
}
int64_t PlatformConfigurationNativeApi::GetRootIsolateToken() {
UIDartState* dart_state = UIDartState::Current();
FML_DCHECK(dart_state);
return dart_state->GetRootIsolateToken();
}
void PlatformConfigurationNativeApi::RegisterBackgroundIsolate(
int64_t root_isolate_token) {
UIDartState* dart_state = UIDartState::Current();
FML_DCHECK(dart_state && !dart_state->IsRootIsolate());
auto platform_message_handler =
(*static_cast<std::shared_ptr<PlatformMessageHandlerStorage>*>(
Dart_CurrentIsolateGroupData()));
FML_DCHECK(platform_message_handler);
auto weak_platform_message_handler =
platform_message_handler->GetPlatformMessageHandler(root_isolate_token);
dart_state->SetPlatformMessageHandler(weak_platform_message_handler);
}
void PlatformConfigurationNativeApi::SendChannelUpdate(const std::string& name,
bool listening) {
UIDartState::Current()->platform_configuration()->client()->SendChannelUpdate(
name, listening);
}
double PlatformConfigurationNativeApi::GetScaledFontSize(
double unscaled_font_size,
int configuration_id) {
UIDartState::ThrowIfUIOperationsProhibited();
return UIDartState::Current()
->platform_configuration()
->client()
->GetScaledFontSize(unscaled_font_size, configuration_id);
}
} // namespace flutter
| engine/lib/ui/window/platform_configuration.cc/0 | {
"file_path": "engine/lib/ui/window/platform_configuration.cc",
"repo_id": "engine",
"token_count": 9817
} | 241 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_WINDOW_POINTER_DATA_H_
#define FLUTTER_LIB_UI_WINDOW_POINTER_DATA_H_
#include <cstdint>
namespace flutter {
// Must match the button constants in events.dart.
enum PointerButtonMouse : int64_t {
kPointerButtonMousePrimary = 1 << 0,
kPointerButtonMouseSecondary = 1 << 1,
kPointerButtonMouseMiddle = 1 << 2,
kPointerButtonMouseBack = 1 << 3,
kPointerButtonMouseForward = 1 << 4,
};
enum PointerButtonTouch : int64_t {
kPointerButtonTouchContact = 1 << 0,
};
enum PointerButtonStylus : int64_t {
kPointerButtonStylusContact = 1 << 0,
kPointerButtonStylusPrimary = 1 << 1,
kPointerButtonStylusSecondary = 1 << 2,
};
// This structure is unpacked by platform_dispatcher.dart.
//
// If this struct changes, update:
// * kPointerDataFieldCount in pointer_data.cc. (The pointer_data.cc also
// lists out other locations that must be kept consistent.)
// * The functions to create simulated data in
// pointer_data_packet_converter_unittests.cc.
struct alignas(8) PointerData {
// Must match the PointerChange enum in pointer.dart.
enum class Change : int64_t {
kCancel,
kAdd,
kRemove,
kHover,
kDown,
kMove,
kUp,
kPanZoomStart,
kPanZoomUpdate,
kPanZoomEnd,
};
// Must match the PointerDeviceKind enum in pointer.dart.
enum class DeviceKind : int64_t {
kTouch,
kMouse,
kStylus,
kInvertedStylus,
kTrackpad,
};
// Must match the PointerSignalKind enum in pointer.dart.
enum class SignalKind : int64_t {
kNone,
kScroll,
kScrollInertiaCancel,
kScale,
};
int64_t embedder_id;
int64_t time_stamp;
Change change;
DeviceKind kind;
SignalKind signal_kind;
int64_t device;
int64_t pointer_identifier;
double physical_x;
double physical_y;
double physical_delta_x;
double physical_delta_y;
int64_t buttons;
int64_t obscured;
int64_t synthesized;
double pressure;
double pressure_min;
double pressure_max;
double distance;
double distance_max;
double size;
double radius_major;
double radius_minor;
double radius_min;
double radius_max;
double orientation;
double tilt;
int64_t platformData;
double scroll_delta_x;
double scroll_delta_y;
double pan_x;
double pan_y;
double pan_delta_x;
double pan_delta_y;
double scale;
double rotation;
int64_t view_id;
void Clear();
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_WINDOW_POINTER_DATA_H_
| engine/lib/ui/window/pointer_data.h/0 | {
"file_path": "engine/lib/ui/window/pointer_data.h",
"repo_id": "engine",
"token_count": 961
} | 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 'dart:io' as io;
import 'package:args/command_runner.dart';
import 'analyze.dart';
import 'build.dart';
import 'clean.dart';
import 'exceptions.dart';
import 'licenses.dart';
import 'roll_fallback_fonts.dart';
import 'test_runner.dart';
import 'utils.dart';
CommandRunner<bool> runner = CommandRunner<bool>(
'felt',
'Command-line utility for building and testing Flutter web engine.',
)
..addCommand(AnalyzeCommand())
..addCommand(BuildCommand())
..addCommand(CleanCommand())
..addCommand(RollFallbackFontsCommand())
..addCommand(LicensesCommand())
..addCommand(TestCommand());
Future<void> main(List<String> rawArgs) async {
// Remove --clean from the list as that's processed by the wrapper script.
final List<String> args = rawArgs.where((String arg) => arg != '--clean').toList();
if (args.isEmpty) {
// The felt tool was invoked with no arguments. Print usage.
runner.printUsage();
io.exit(64); // Exit code 64 indicates a usage error.
}
_listenToShutdownSignals();
int exitCode = -1;
try {
final bool? result = await runner.run(args);
if (result != true) {
print('Sub-command failed: `${args.join(' ')}`');
exitCode = 1;
}
} on UsageException catch (e) {
print(e);
exitCode = 64; // Exit code 64 indicates a usage error.
} on ToolExit catch (exception) {
io.stderr.writeln(exception.message);
exitCode = exception.exitCode;
} on ProcessException catch (e) {
io.stderr.writeln('description: ${e.description}'
'executable: ${e.executable} '
'arguments: ${e.arguments} '
'exit code: ${e.exitCode}');
exitCode = e.exitCode ?? 1;
} catch (e) {
rethrow;
} finally {
await cleanup();
// The exit code is changed by one of the branches.
if (exitCode != -1) {
io.exit(exitCode);
}
}
// Sometimes the Dart VM refuses to quit.
io.exit(io.exitCode);
}
void _listenToShutdownSignals() {
io.ProcessSignal.sigint.watch().listen((_) async {
print('Received SIGINT. Shutting down.');
await cleanup();
io.exit(1);
});
// SIGTERM signals are not generated under Windows.
// See https://docs.microsoft.com/en-us/previous-versions/xdkz3x12(v%3Dvs.140)
if (!io.Platform.isWindows) {
io.ProcessSignal.sigterm.watch().listen((_) async {
await cleanup();
print('Received SIGTERM. Shutting down.');
io.exit(1);
});
}
}
| engine/lib/web_ui/dev/felt.dart/0 | {
"file_path": "engine/lib/web_ui/dev/felt.dart",
"repo_id": "engine",
"token_count": 939
} | 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.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'package:async/async.dart';
import 'package:http_multi_server/http_multi_server.dart';
import 'package:image/image.dart';
import 'package:package_config/package_config.dart';
import 'package:path/path.dart' as p;
import 'package:pool/pool.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_packages_handler/shelf_packages_handler.dart';
import 'package:shelf_static/shelf_static.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:skia_gold_client/skia_gold_client.dart';
import 'package:stream_channel/stream_channel.dart';
import 'package:test_core/backend.dart' hide Compiler;
// TODO(ditman): Fix ignores when https://github.com/flutter/flutter/issues/143599 is resolved.
import 'package:test_core/src/runner/environment.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/platform.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/plugin/platform_helpers.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/runner_suite.dart'; // ignore: implementation_imports
import 'package:test_core/src/util/io.dart'; // ignore: implementation_imports
import 'package:test_core/src/util/stack_trace_mapper.dart'; // ignore: implementation_imports
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_test_utils/image_compare.dart';
import 'browser.dart';
import 'environment.dart' as env;
import 'felt_config.dart';
import 'utils.dart';
const Map<String, String> coopCoepHeaders = <String, String>{
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
};
/// Custom test platform that serves web engine unit tests.
class BrowserPlatform extends PlatformPlugin {
BrowserPlatform._(this.suite, {
required this.browserEnvironment,
required this.server,
required this.isDebug,
required this.isVerbose,
required this.doUpdateScreenshotGoldens,
required this.packageConfig,
required this.skiaClient,
required this.overridePathToCanvasKit,
}) {
// The cascade of request handlers.
final shelf.Cascade cascade = shelf.Cascade()
// The web socket that carries the test channels for running tests and
// reporting restuls. See [_browserManagerFor] and [BrowserManager.start]
// for details on how the channels are established.
.add(_webSocketHandler.handler)
// Serves /packages/* requests; fetches files and sources from
// pubspec dependencies.
//
// Includes:
// * Requests for Dart sources from source maps
// * Assets that are part of the engine sources, such as Ahem.ttf
.add(_packageUrlHandler)
.add(_canvasKitOverrideHandler)
// Serves files from the bundle's output build directory
.add(createSimpleDirectoryHandler(getBundleBuildDirectory(suite.testBundle)))
// Serves files from the out/web_tests/artifacts directory at the root (/) URL path.
.add(createSimpleDirectoryHandler(env.environment.webTestsArtifactsDir))
// Serves files from the test set directory
.add(createSimpleDirectoryHandler(getTestSetDirectory(suite.testBundle.testSet)))
.add(_testImageListingHandler)
// Serves the initial HTML for the test.
.add(_testBootstrapHandler)
// Serves source files from the engine src root for devtools debugging.
.add(_createSourceHandler())
// Serves files from the root of web_ui. Some tests download assets that are embedded
// directly in the test folder, such as test/engine/image/sample_image1.png etc
.add(createStaticHandler(env.environment.webUiRootDir.path))
// Serves absolute package URLs (i.e. not /packages/* but /Users/user/*/hosted/pub.dartlang.org/*).
// This handler goes last, after all more specific handlers failed to handle the request.
.add(_createAbsolutePackageUrlHandler())
.add(_screenshotHandler)
// Generates and serves a test payload of given length, split into chunks
// of given size. Reponds to requests to /long_test_payload.
.add(_testPayloadGenerator)
// If none of the handlers above handled the request, return 404.
.add(_fileNotFoundCatcher);
server.mount(cascade.handler);
}
/// Starts the server.
///
/// [browserEnvironment] provides the browser environment to run the test.
///
/// If [doUpdateScreenshotGoldens] is true updates screenshot golden files
/// instead of failing the test on screenshot mismatches.
static Future<BrowserPlatform> start(TestSuite suite, {
required BrowserEnvironment browserEnvironment,
required bool doUpdateScreenshotGoldens,
required SkiaGoldClient? skiaClient,
required String? overridePathToCanvasKit,
required bool isVerbose,
}) async {
final shelf_io.IOServer server =
shelf_io.IOServer(await HttpMultiServer.loopback(0));
return BrowserPlatform._(
suite,
browserEnvironment: browserEnvironment,
server: server,
isDebug: Configuration.current.pauseAfterLoad,
isVerbose: isVerbose,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
packageConfig: await loadPackageConfigUri((await Isolate.packageConfig)!),
skiaClient: skiaClient,
overridePathToCanvasKit: overridePathToCanvasKit,
);
}
final TestSuite suite;
/// If true, runs the browser with a visible windows (i.e. not headless) and
/// pauses before running the tests to give the developer a chance to set
/// breakpoints in the code.
final bool isDebug;
final bool isVerbose;
/// The underlying server.
final shelf.Server server;
/// Provides the environment for the browser running tests.
final BrowserEnvironment browserEnvironment;
/// The URL for this server.
Uri get url => server.url.resolve('/');
bool get needsCrossOriginIsolated => suite.testBundle.compileConfigs.any(
(CompileConfiguration config) => config.renderer == Renderer.skwasm
);
/// A [OneOffHandler] for servicing WebSocket connections for
/// [BrowserManager]s.
///
/// This is one-off because each [BrowserManager] can only connect to a single
/// WebSocket,
final OneOffHandler _webSocketHandler = OneOffHandler();
/// Whether [close] has been called.
bool get _closed => _closeMemo.hasRun;
/// Whether to update screenshot golden files.
final bool doUpdateScreenshotGoldens;
late final shelf.Handler _packageUrlHandler = packagesDirHandler();
final PackageConfig packageConfig;
/// A client for communicating with the Skia Gold backend to fetch, compare
/// and update images.
final SkiaGoldClient? skiaClient;
final String? overridePathToCanvasKit;
/// If a path to a custom local build of CanvasKit was specified, serve from
/// there instead of serving the default CanvasKit in the build/ directory.
Future<shelf.Response> _canvasKitOverrideHandler(
shelf.Request request) async {
final String? pathOverride = overridePathToCanvasKit;
if (pathOverride == null || !request.url.path.startsWith('canvaskit/')) {
return shelf.Response.notFound('Not a request for CanvasKit.');
}
final File file = File(p.joinAll(<String>[
pathOverride,
...p.split(request.url.path).skip(1),
]));
if (!file.existsSync()) {
return shelf.Response.notFound('File not found: ${request.url.path}');
}
final String extension = p.extension(file.path);
final String? contentType = contentTypes[extension];
if (contentType == null) {
final String error =
'Failed to determine Content-Type for "${request.url.path}".';
stderr.writeln(error);
return shelf.Response.internalServerError(body: error);
}
return shelf.Response.ok(
file.readAsBytesSync(),
headers: <String, Object>{
HttpHeaders.contentTypeHeader: contentType,
},
);
}
/// Lists available test images under `out/web_tests/test_images`.
Future<shelf.Response> _testImageListingHandler(shelf.Request request) async {
const Map<String, String> supportedImageTypes = <String, String>{
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
};
if (request.url.path != 'test_images/') {
return shelf.Response.notFound('Not found.');
}
final Directory testImageDirectory = Directory(p.join(
env.environment.webTestsArtifactsDir.path,
'test_images',
));
final List<String> testImageFiles = testImageDirectory
.listSync(recursive: true)
.whereType<File>()
.map<String>(
(File file) => p.relative(file.path, from: testImageDirectory.path))
.where(
(String path) => supportedImageTypes.containsKey(p.extension(path)))
.toList();
return shelf.Response.ok(
json.encode(testImageFiles),
headers: <String, Object>{
HttpHeaders.contentTypeHeader: 'application/json',
},
);
}
Future<shelf.Response> _fileNotFoundCatcher(shelf.Request request) async {
if (isVerbose) {
print('HTTP 404: ${request.url}');
}
return shelf.Response.notFound('File not found');
}
shelf.Handler _createSourceHandler() => (shelf.Request request) async {
final String path = p.fromUri(request.url);
final String extension = p.extension(path);
final bool isSource =
extension == '.dart' ||
extension == '.c' ||
extension == '.cc' ||
extension == '.cpp' ||
extension == '.h';
if (isSource && p.isRelative(path)) {
final String fullPath = p.join(env.environment.engineSrcDir.path, path);
final File file = File(fullPath);
if (file.existsSync()) {
return shelf.Response.ok(file.openRead());
}
}
return shelf.Response.notFound('Not found.');
};
/// Handles URLs pointing to Dart sources using absolute URI paths.
///
/// Dart source paths that dart2js puts in source maps for pub packages are
/// relative to the source map file. Example:
///
/// ../../../../../../../../../Users/yegor/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/stack_trace-1.10.0/lib/src/frame.dart
///
/// When the browser requests the file from the source map it sends a GET
/// request like this:
///
/// GET /Users/yegor/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/stack_trace-1.10.0/lib/src/frame.dart
///
/// There's no predictable structure in this URL. It's unclear whether this
/// is a request for a source file, or someone trying to hack your
/// workstation.
///
/// This handler treats the URL as an absolute path, but instead of
/// unconditionally serving it, it first checks with `package_config.json` on
/// whether this is a request for a Dart source that's listed in pubspec
/// dependencies. For example, the `stack_trace` package would be listed in
/// `package_config.json` as:
///
/// file:///C:/Users/yegor/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/stack_trace-1.10.0
///
/// If the requested URL points into one of the packages in the package config,
/// the file is served. Otherwise, HTTP 404 is returned without file contents.
///
/// To handle drive letters (C:\) and *nix file system roots, the URL and
/// package paths are initially stripped of the root and compared to each
/// other as prefixes. To actually read the file, the file system root is
/// prepended before creating the file.
shelf.Handler _createAbsolutePackageUrlHandler() {
final Map<String, Package> urlToPackage = <String, Package>{};
for (final Package package in packageConfig.packages) {
// Turns the URI as encoded in package_config.json to a file path.
final String configPath = p.fromUri(package.root);
// Strips drive letter and root prefix, if any, for example:
//
// C:\Users\user\AppData => Users\user\AppData
// /home/user/path.dart => home/user/path.dart
final String rootRelativePath =
p.relative(configPath, from: p.rootPrefix(configPath));
urlToPackage[p.toUri(rootRelativePath).path] = package;
}
return (shelf.Request request) async {
final String requestedPath = request.url.path;
// The cast is needed because keys are non-null String, so there's no way
// to return null for a mismatch.
final String? packagePath = urlToPackage.keys.cast<String?>().firstWhere(
(String? packageUrl) => requestedPath.startsWith(packageUrl!),
orElse: () => null,
);
if (packagePath == null) {
return shelf.Response.notFound('Not a pub.dartlang.org request');
}
// Attach the root prefix, such as drive letter, and convert from URI to path.
// Examples:
//
// Users\user\AppData => C:\Users\user\AppData
// home/user/path.dart => /home/user/path.dart
final Package package = urlToPackage[packagePath]!;
final String filePath = p.join(
p.rootPrefix(p.fromUri(package.root.path)),
p.fromUri(requestedPath),
);
final File fileInPackage = File(filePath);
if (!fileInPackage.existsSync()) {
return shelf.Response.notFound('File not found: $requestedPath');
}
return shelf.Response.ok(fileInPackage.openRead());
};
}
Future<shelf.Response> _testPayloadGenerator(shelf.Request request) async {
if (!request.requestedUri.path.endsWith('/long_test_payload')) {
return shelf.Response.notFound(
'This request is not handled by the test payload generator');
}
final int payloadLength = int.parse(request.requestedUri.queryParameters['length']!);
final int chunkLength = int.parse(request.requestedUri.queryParameters['chunk']!);
final StreamController<List<int>> controller = StreamController<List<int>>();
Future<void> fillPayload() async {
int remainingByteCount = payloadLength;
int byteCounter = 0;
while (remainingByteCount > 0) {
final int currentChunkLength = min(chunkLength, remainingByteCount);
final List<int> chunk = List<int>.generate(
currentChunkLength,
(int i) => (byteCounter + i) & 0xFF,
);
byteCounter = (byteCounter + currentChunkLength) & 0xFF;
remainingByteCount -= currentChunkLength;
controller.add(chunk);
await Future<void>.delayed(const Duration(milliseconds: 100));
}
await controller.close();
}
// Kick off payload filling function but don't block on it. The stream should
// be returned immediately, and the client should receive data in chunks.
unawaited(fillPayload());
return shelf.Response.ok(
controller.stream,
headers: <String, String>{
'Content-Type': 'application/octet-stream',
'Content-Length': '$payloadLength',
},
);
}
Future<shelf.Response> _screenshotHandler(shelf.Request request) async {
if (!request.requestedUri.path.endsWith('/screenshot')) {
return shelf.Response.notFound(
'This request is not handled by the screenshot handler');
}
final String payload = await request.readAsString();
final Map<String, dynamic> requestData =
json.decode(payload) as Map<String, dynamic>;
final String filename = requestData['filename'] as String;
if (!(await browserManager).supportsScreenshots) {
if (isVerbose) {
print(
'Skipping screenshot check for $filename. Current browser/OS '
'combination does not support screenshots.',
);
}
return shelf.Response.ok(json.encode('OK'));
}
final Map<String, dynamic> region =
requestData['region'] as Map<String, dynamic>;
final bool isCanvaskitTest = requestData['isCanvaskitTest'] as bool;
final String result = await _diffScreenshot(filename, region, isCanvaskitTest);
return shelf.Response.ok(json.encode(result));
}
Future<String> _diffScreenshot(
String filename,
Map<String, dynamic> region,
bool isCanvaskitTest,
) async {
final Rectangle<num> regionAsRectange = Rectangle<num>(
region['x'] as num,
region['y'] as num,
region['width'] as num,
region['height'] as num,
);
// Take screenshot.
final Image screenshot =
await (await browserManager).captureScreenshot(regionAsRectange);
return compareImage(
screenshot,
doUpdateScreenshotGoldens,
filename,
getSkiaGoldDirectoryForSuite(suite),
skiaClient,
isCanvaskitTest: isCanvaskitTest,
verbose: isVerbose,
);
}
static const Map<String, String> contentTypes = <String, String>{
'.js': 'text/javascript',
'.mjs': 'text/javascript',
'.wasm': 'application/wasm',
'.html': 'text/html',
'.htm': 'text/html',
'.css': 'text/css',
'.ico': 'image/icon-x',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.svg': 'image/svg+xml',
'.json': 'application/json',
'.map': 'application/json',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
/// Creates a simple file handler that serves files whose URLs and paths are
/// statically known.
///
/// This is used for trivial use-cases, such as `favicon.ico`, host pages, etc.
shelf.Handler createSimpleDirectoryHandler(Directory directory) {
return (shelf.Request request) {
final File fileInDirectory = File(p.join(
directory.path,
request.url.path,
));
if (request.url.path.contains('//') || !fileInDirectory.existsSync()) {
return shelf.Response.notFound('File not found: ${request.url.path}');
}
final String extension = p.extension(fileInDirectory.path);
final String? contentType = contentTypes[extension];
if (contentType == null) {
final String error =
'Failed to determine Content-Type for "${request.url.path}".';
stderr.writeln(error);
return shelf.Response.internalServerError(body: error);
}
final bool isScript =
extension == '.js' ||
extension == '.mjs' ||
extension == '.html';
return shelf.Response.ok(
fileInDirectory.readAsBytesSync(),
headers: <String, Object>{
HttpHeaders.contentTypeHeader: contentType,
if (isScript && needsCrossOriginIsolated)
...coopCoepHeaders,
},
);
};
}
String getCanvasKitVariant() {
switch (suite.runConfig.variant) {
case CanvasKitVariant.full:
return 'full';
case CanvasKitVariant.chromium:
return 'chromium';
case null:
return 'auto';
}
}
String _makeBuildConfigString(String scriptBase, CompileConfiguration config) {
return config.compiler == Compiler.dart2wasm ? '''
{
compileTarget: "${config.compiler.name}",
renderer: "${config.renderer.name}",
mainWasmPath: "$scriptBase.browser_test.dart.wasm",
jsSupportRuntimePath: "$scriptBase.browser_test.dart.mjs",
}
''' : '''
{
compileTarget: "${config.compiler.name}",
renderer: "${config.renderer.name}",
mainJsPath: "$scriptBase.browser_test.dart.js",
}
''';
}
/// Serves the HTML file that bootstraps the test.
shelf.Response _testBootstrapHandler(shelf.Request request) {
final String path = p.fromUri(request.url);
if (path.endsWith('.html')) {
final String test = '${p.withoutExtension(path)}.dart';
final String scriptBase = htmlEscape.convert(p.basename(test));
final String buildConfigsString = suite.testBundle.compileConfigs.map(
(CompileConfiguration config) => _makeBuildConfigString(scriptBase, config)
).join(',\n');
final String bootstrapScript = '''
<script>
// Define this before loading flutter.js to test PR flutter/engine#51294
if (!window._flutter) {
window._flutter = {};
}
</script>
<script>
_flutter.buildConfig = {
builds: [
$buildConfigsString
]
};
</script>
<script src="/flutter_js/flutter.js"></script>
<script>
_flutter.loader.load({
config: {
canvasKitBaseUrl: "/canvaskit/",
// Some of our tests rely on color emoji
useColorEmoji: true,
canvasKitVariant: "${getCanvasKitVariant()}",
},
});
</script>
''';
return shelf.Response.ok('''
<!DOCTYPE html>
<html>
<head>
<meta name="assetBase" content="/">
$bootstrapScript
</head>
</html>
''', headers: <String, String>{
'Content-Type': 'text/html',
if (needsCrossOriginIsolated)
...coopCoepHeaders
});
}
return shelf.Response.notFound('Not found.');
}
void _checkNotClosed() {
if (_closed) {
throw StateError('Cannot load test suite. Test platform is closed.');
}
}
/// Loads the test suite at [path] on the platform [platform].
///
/// This will start a browser to load the suite if one isn't already running.
/// Throws an [ArgumentError] if `platform.platform` isn't a browser.
@override
Future<RunnerSuite> load(String path, SuitePlatform platform,
SuiteConfiguration suiteConfig, Object message) async {
_checkNotClosed();
if (suiteConfig.precompiledPath == null) {
throw Exception('This test platform only supports precompiled JS.');
}
final Runtime browser = platform.runtime;
assert(suiteConfig.runtimes.contains(browser.identifier));
if (!browser.isBrowser) {
throw ArgumentError('$browser is not a browser.');
}
_checkNotClosed();
final Uri suiteUrl = url.resolveUri(p.toUri('${p.withoutExtension(path)}.html'));
_checkNotClosed();
final BrowserManager? browserManager = await _startBrowserManager();
if (browserManager == null) {
throw StateError(
'Failed to initialize browser manager for ${browserEnvironment.name}');
}
_checkNotClosed();
final RunnerSuite runnerSuite =
await browserManager.load(path, suiteUrl, suiteConfig, message);
_checkNotClosed();
return runnerSuite;
}
Future<BrowserManager?>? _browserManager;
Future<BrowserManager> get browserManager async => (await _browserManager!)!;
/// Starts a browser manager for the browser provided by [browserEnvironment];
///
/// If no browser manager is running yet, starts one.
Future<BrowserManager?> _startBrowserManager() {
if (_browserManager != null) {
return _browserManager!;
}
final Completer<WebSocketChannel> completer =
Completer<WebSocketChannel>.sync();
final String path =
_webSocketHandler.create(webSocketHandler(completer.complete));
final Uri webSocketUrl = url.replace(scheme: 'ws').resolve(path);
final Uri hostUrl = url.resolve('host/index.html').replace(
queryParameters: <String, dynamic>{
'managerUrl': webSocketUrl.toString(),
'debug': isDebug.toString()
});
final bool hasSourceMaps = suite.testBundle.compileConfigs.any(
(CompileConfiguration config) => config.compiler == Compiler.dart2js
);
final Future<BrowserManager?> future = BrowserManager.start(
browserEnvironment: browserEnvironment,
url: hostUrl,
future: completer.future,
packageConfig: packageConfig,
debug: isDebug,
sourceMapDirectory: hasSourceMaps ? getBundleBuildDirectory(suite.testBundle) : null,
);
// Store null values for browsers that error out so we know not to load them
// again.
_browserManager = future.catchError((dynamic _) => null);
return future;
}
/// Close all the browsers that the server currently has open.
///
/// Note that this doesn't close the server itself. Browser tests can still be
/// loaded, they'll just spawn new browsers.
@override
Future<void> closeEphemeral() async {
if (_browserManager != null) {
final BrowserManager? result = await _browserManager;
await result?.close();
}
}
/// Closes the server and releases all its resources.
///
/// Returns a [Future] that completes once the server is closed and its
/// resources have been fully released.
@override
Future<void> close() {
return _closeMemo.runOnce(() async {
final List<Future<void>> futures = <Future<void>>[];
futures.add(Future<void>.microtask(() async {
if (_browserManager != null) {
final BrowserManager? result = await _browserManager;
await result?.close();
}
}));
futures.add(server.close());
await Future.wait(futures);
});
}
final AsyncMemoizer<dynamic> _closeMemo = AsyncMemoizer<dynamic>();
}
/// A Shelf handler that provides support for one-time handlers.
///
/// This is useful for handlers that only expect to be hit once before becoming
/// invalid and don't need to have a persistent URL.
class OneOffHandler {
/// A map from URL paths to handlers.
final Map<String, shelf.Handler> _handlers = <String, shelf.Handler>{};
/// The counter of handlers that have been activated.
int _counter = 0;
/// The actual [shelf.Handler] that dispatches requests.
shelf.Handler get handler => _onRequest;
/// Creates a new one-off handler that forwards to [handler].
///
/// Returns a string that's the URL path for hitting this handler, relative to
/// the URL for the one-off handler itself.
///
/// [handler] will be unmounted as soon as it receives a request.
String create(shelf.Handler handler) {
final String path = _counter.toString();
_handlers[path] = handler;
_counter++;
return path;
}
/// Dispatches [request] to the appropriate handler.
FutureOr<shelf.Response> _onRequest(shelf.Request request) {
final List<String> components = p.url.split(request.url.path);
if (components.isEmpty) {
return shelf.Response.notFound(null);
}
final String path = components.removeAt(0);
final shelf.Handler? handler = _handlers.remove(path);
if (handler == null) {
return shelf.Response.notFound(null);
}
return handler(request.change(path: path));
}
}
/// Manages the connection to a single running browser.
///
/// This is in charge of telling the browser which test suites to load and
/// converting its responses into [Suite] objects.
class BrowserManager {
/// Creates a new BrowserManager that communicates with the browser over
/// [webSocket].
BrowserManager._(
this.packageConfig,
this._browser,
this._browserEnvironment,
this._sourceMapDirectory,
WebSocketChannel webSocket,
) {
// The duration should be short enough that the debugging console is open as
// soon as the user is done setting breakpoints, but long enough that a test
// doing a lot of synchronous work doesn't trigger a false positive.
//
// Start this canceled because we don't want it to start ticking until we
// get some response from the iframe.
_timer = RestartableTimer(const Duration(seconds: 3), () {
for (final RunnerSuiteController controller in _controllers) {
controller.setDebugging(true);
}
})..cancel();
// Whenever we get a message, no matter which child channel it's for, we the
// know browser is still running code which means the user isn't debugging.
_channel = MultiChannel<dynamic>(webSocket
.cast<String>()
.transform(jsonDocument)
.changeStream((Stream<Object?> stream) {
return stream.map((Object? message) {
if (!_closed) {
_timer.reset();
}
for (final RunnerSuiteController controller in _controllers) {
controller.setDebugging(false);
}
return message;
});
}));
_environment = _loadBrowserEnvironment();
_channel.stream.listen(
(dynamic message) => _onMessage(message as Map<dynamic, dynamic>),
onDone: close);
}
final PackageConfig packageConfig;
/// The browser instance that this is connected to via [_channel].
final Browser _browser;
/// The browser environment for this test.
final BrowserEnvironment _browserEnvironment;
/// The directory containing sourcemaps for test files
final Directory? _sourceMapDirectory;
/// The channel used to communicate with the browser.
///
/// This is connected to a page running `static/host.dart`.
late final MultiChannel<dynamic> _channel;
/// A pool that ensures that limits the number of initial connections the
/// manager will wait for at once.
///
/// This isn't the *total* number of connections; any number of iframes may be
/// loaded in the same browser. However, the browser can only load so many at
/// once, and we want a timeout in case they fail so we only wait for so many
/// at once.
final Pool _pool = Pool(8);
/// The ID of the next suite to be loaded.
///
/// This is used to ensure that the suites can be referred to consistently
/// across the client and server.
int _suiteID = 0;
/// Whether the channel to the browser has closed.
bool _closed = false;
/// The completer for [_BrowserEnvironment.displayPause].
///
/// This will be `null` as long as the browser isn't displaying a pause
/// screen.
CancelableCompleter<void>? _pauseCompleter;
/// The controller for [_BrowserEnvironment.onRestart].
final StreamController<dynamic> _onRestartController =
StreamController<dynamic>.broadcast();
/// The environment to attach to each suite.
late final Future<_BrowserEnvironment> _environment;
/// Controllers for every suite in this browser.
///
/// These are used to mark suites as debugging or not based on the browser's
/// pings.
final Set<RunnerSuiteController> _controllers = <RunnerSuiteController>{};
// A timer that's reset whenever we receive a message from the browser.
//
// Because the browser stops running code when the user is actively debugging,
// this lets us detect whether they're debugging reasonably accurately.
late final RestartableTimer _timer;
/// Starts the browser identified by [runtime] and has it connect to [url].
///
/// [url] should serve a page that establishes a WebSocket connection with
/// this process. That connection, once established, should be emitted via
/// [future]. If [debug] is true, starts the browser in debug mode, with its
/// debugger interfaces on and detected.
///
/// The [settings] indicate how to invoke this browser's executable.
///
/// Returns the browser manager, or throws an [Exception] if a
/// connection fails to be established.
static Future<BrowserManager?> start({
required BrowserEnvironment browserEnvironment,
required Uri url,
required Future<WebSocketChannel> future,
required PackageConfig packageConfig,
Directory? sourceMapDirectory,
bool debug = false,
}) async {
final Browser browser = await _newBrowser(
url,
browserEnvironment,
debug: debug,
);
return _startBrowserManager(
browserEnvironment: browserEnvironment,
url: url,
future: future,
packageConfig: packageConfig,
browser: browser,
sourceMapDirectory: sourceMapDirectory,
debug: debug,
);
}
static Future<BrowserManager?> _startBrowserManager({
required BrowserEnvironment browserEnvironment,
required Uri url,
required Future<WebSocketChannel> future,
required PackageConfig packageConfig,
required Browser browser,
Directory? sourceMapDirectory,
bool debug = false,
}) {
final Completer<BrowserManager> completer = Completer<BrowserManager>();
// For the cases where we use a delegator such as `adb` (for Android) or
// `xcrun` (for IOS), these delegator processes can shut down before the
// websocket is available. Therefore do not throw an error if process
// exits with exitCode 0. Note that `browser` will throw and error if the
// exit code was not 0, which will be processed by the next callback.
browser.onExit.catchError((Object error, StackTrace stackTrace) {
if (completer.isCompleted) {
return;
}
completer.completeError(error, stackTrace);
});
future.then((WebSocketChannel webSocket) {
if (completer.isCompleted) {
return;
}
completer.complete(BrowserManager._(
packageConfig,
browser,
browserEnvironment,
sourceMapDirectory,
webSocket,
));
}).catchError((Object error, StackTrace stackTrace) {
browser.close();
if (completer.isCompleted) {
return null;
}
completer.completeError(error, stackTrace);
});
return completer.future;
}
/// Starts the browser and requests that it load the test page at [url].
///
/// If [debug] is true, starts the browser in debug mode.
static Future<Browser> _newBrowser(
Uri url,
BrowserEnvironment browserEnvironment, {
bool debug = false,
}) {
return browserEnvironment.launchBrowserInstance(
url,
debug: debug,
);
}
/// Loads [_BrowserEnvironment].
Future<_BrowserEnvironment> _loadBrowserEnvironment() async {
return _BrowserEnvironment(
this,
await _browser.vmServiceUrl,
await _browser.remoteDebuggerUrl,
_onRestartController.stream
);
}
/// Tells the browser the load a test suite from the URL [url].
///
/// [url] should be an HTML page with a reference to the JS-compiled test
/// suite. [path] is the path of the original test suite file, which is used
/// for reporting. [suiteConfig] is the configuration for the test suite.
Future<RunnerSuite> load(String path, Uri url, SuiteConfiguration suiteConfig,
Object message) async {
url = url.replace(
fragment: Uri.encodeFull(jsonEncode(<String, dynamic>{
'metadata': suiteConfig.metadata.serialize(),
'browser': _browserEnvironment.packageTestRuntime.identifier
})));
final int suiteID = _suiteID++;
RunnerSuiteController? controller;
void closeIframe() {
if (_closed) {
return;
}
_controllers.remove(controller);
_channel.sink
.add(<String, dynamic>{'command': 'closeSuite', 'id': suiteID});
}
// The virtual channel will be closed when the suite is closed, in which
// case we should unload the iframe.
final VirtualChannel<dynamic> virtualChannel = _channel.virtualChannel();
final int suiteChannelID = virtualChannel.id;
final StreamChannel<dynamic> suiteChannel = virtualChannel.transformStream(
StreamTransformer<dynamic, dynamic>.fromHandlers(
handleDone: (EventSink<dynamic> sink) {
closeIframe();
sink.close();
}));
if (Configuration.current.pauseAfterLoad) {
print('Browser loaded. Press enter to start tests...');
stdin.readLineSync();
}
return _pool.withResource<RunnerSuite>(() async {
_channel.sink.add(<String, dynamic>{
'command': 'loadSuite',
'url': url.toString(),
'id': suiteID,
'channel': suiteChannelID
});
try {
controller = deserializeSuite(
path,
currentPlatform(_browserEnvironment.packageTestRuntime),
suiteConfig,
await _environment,
suiteChannel,
message);
if (_sourceMapDirectory == null) {
// We don't have mapping for wasm yet. But we should send a message
// to let the host page move forward.
controller!.channel('test.browser.mapper').sink.add(null);
} else {
final String sourceMapFileName =
'${p.basename(path)}.browser_test.dart.js.map';
final String pathToTest = p.dirname(path);
final String mapPath = p.join(
_sourceMapDirectory.path,
pathToTest,
sourceMapFileName
);
final Map<String, Uri> packageMap = <String, Uri>{
for (final Package p in packageConfig.packages)
p.name: p.packageUriRoot
};
final JSStackTraceMapper mapper = JSStackTraceMapper(
await File(mapPath).readAsString(),
mapUrl: p.toUri(mapPath),
packageMap: packageMap,
sdkRoot: p.toUri(sdkDir),
);
controller!.channel('test.browser.mapper').sink.add(mapper.serialize());
}
_controllers.add(controller!);
return await controller!.suite;
} catch (_) {
closeIframe();
rethrow;
}
});
}
/// An implementation of [Environment.displayPause].
CancelableOperation<void> _displayPause() {
CancelableCompleter<void>? pauseCompleter = _pauseCompleter;
if (pauseCompleter != null) {
return pauseCompleter.operation;
}
pauseCompleter = CancelableCompleter<void>(onCancel: () {
_channel.sink.add(<String, String>{'command': 'resume'});
_pauseCompleter = null;
});
_pauseCompleter = pauseCompleter;
pauseCompleter.operation.value.whenComplete(() {
_pauseCompleter = null;
});
_channel.sink.add(<String, String>{'command': 'displayPause'});
return pauseCompleter.operation;
}
/// The callback for handling messages received from the host page.
void _onMessage(Map<dynamic, dynamic> message) {
switch (message['command'] as String) {
case 'ping':
break;
case 'restart':
_onRestartController.add(null);
case 'resume':
_pauseCompleter?.complete();
default:
// Unreachable.
assert(false);
break;
}
}
bool get supportsScreenshots => _browser.supportsScreenshots;
Future<Image> captureScreenshot(Rectangle<num> region) =>
_browser.captureScreenshot(region);
/// Closes the manager and releases any resources it owns, including closing
/// the browser.
Future<void> close() => _closeMemoizer.runOnce(() {
if (Configuration.current.pauseAfterLoad) {
print('Test run finished. Press enter to close browser...');
stdin.readLineSync();
}
_closed = true;
_timer.cancel();
_pauseCompleter?.complete();
_pauseCompleter = null;
_controllers.clear();
return _browser.close();
});
final AsyncMemoizer<dynamic> _closeMemoizer = AsyncMemoizer<dynamic>();
}
/// An implementation of [Environment] for the browser.
///
/// All methods forward directly to [BrowserManager].
class _BrowserEnvironment implements Environment {
_BrowserEnvironment(this._manager, this.observatoryUrl,
this.remoteDebuggerUrl, this.onRestart);
final BrowserManager _manager;
@override
final bool supportsDebugging = true;
@override
final Uri? observatoryUrl;
@override
final Uri? remoteDebuggerUrl;
@override
final Stream<dynamic> onRestart;
@override
CancelableOperation<void> displayPause() => _manager._displayPause();
}
| engine/lib/web_ui/dev/test_platform.dart/0 | {
"file_path": "engine/lib/web_ui/dev/test_platform.dart",
"repo_id": "engine",
"token_count": 13952
} | 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.
/**
* Handles the creation of a TrustedTypes `policy` that validates URLs based
* on an (optional) incoming array of RegExes.
*/
export class FlutterTrustedTypesPolicy {
/**
* Constructs the policy.
* @param {[RegExp]} validPatterns the patterns to test URLs
* @param {String} policyName the policy name (optional)
*/
constructor(validPatterns, policyName = "flutter-js") {
const patterns = validPatterns || [
/\.js$/,
/\.mjs$/,
];
if (window.trustedTypes) {
this.policy = trustedTypes.createPolicy(policyName, {
createScriptURL: function (url) {
// Return blob urls without manipulating them
if (url.startsWith('blob:')) {
return url;
}
// Validate other urls
const parsed = new URL(url, window.location);
const file = parsed.pathname.split("/").pop();
const matches = patterns.some((pattern) => pattern.test(file));
if (matches) {
return parsed.toString();
}
console.error(
"URL rejected by TrustedTypes policy",
policyName, ":", url, "(download prevented)");
}
});
}
}
}
| engine/lib/web_ui/flutter_js/src/trusted_types.js/0 | {
"file_path": "engine/lib/web_ui/flutter_js/src/trusted_types.js",
"repo_id": "engine",
"token_count": 535
} | 245 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of ui;
typedef VoidCallback = void Function();
typedef ViewFocusChangeCallback = void Function(ViewFocusEvent viewFocusEvent);
typedef FrameCallback = void Function(Duration duration);
typedef TimingsCallback = void Function(List<FrameTiming> timings);
typedef PointerDataPacketCallback = void Function(PointerDataPacket packet);
typedef KeyDataCallback = bool Function(KeyData data);
typedef SemanticsActionEventCallback = void Function(SemanticsActionEvent action);
typedef PlatformMessageResponseCallback = void Function(ByteData? data);
typedef PlatformMessageCallback = void Function(
String name, ByteData? data, PlatformMessageResponseCallback? callback);
typedef ErrorCallback = bool Function(Object exception, StackTrace stackTrace);
// ignore: avoid_classes_with_only_static_members
/// A token that represents a root isolate.
class RootIsolateToken {
static RootIsolateToken? get instance {
throw UnsupportedError('Root isolate not identifiable on web.');
}
}
abstract class PlatformDispatcher {
static PlatformDispatcher get instance => engine.EnginePlatformDispatcher.instance;
VoidCallback? get onPlatformConfigurationChanged;
set onPlatformConfigurationChanged(VoidCallback? callback);
Iterable<Display> get displays;
Iterable<FlutterView> get views;
FlutterView? view({required int id});
FlutterView? get implicitView;
VoidCallback? get onMetricsChanged;
set onMetricsChanged(VoidCallback? callback);
ViewFocusChangeCallback? get onViewFocusChange;
set onViewFocusChange(ViewFocusChangeCallback? callback);
void requestViewFocusChange({
required int viewId,
required ViewFocusState state,
required ViewFocusDirection direction,
});
FrameCallback? get onBeginFrame;
set onBeginFrame(FrameCallback? callback);
VoidCallback? get onDrawFrame;
set onDrawFrame(VoidCallback? callback);
PointerDataPacketCallback? get onPointerDataPacket;
set onPointerDataPacket(PointerDataPacketCallback? callback);
KeyDataCallback? get onKeyData;
set onKeyData(KeyDataCallback? callback);
TimingsCallback? get onReportTimings;
set onReportTimings(TimingsCallback? callback);
void sendPlatformMessage(
String name,
ByteData? data,
PlatformMessageResponseCallback? callback,
);
void sendPortPlatformMessage(
String name,
ByteData? data,
int identifier,
Object port);
void registerBackgroundIsolate(RootIsolateToken token);
PlatformMessageCallback? get onPlatformMessage;
set onPlatformMessage(PlatformMessageCallback? callback);
void setIsolateDebugName(String name) {}
void requestDartPerformanceMode(DartPerformanceMode mode) {}
ByteData? getPersistentIsolateData() => null;
void scheduleFrame();
void scheduleWarmUpFrame({required VoidCallback beginFrame, required VoidCallback drawFrame});
AccessibilityFeatures get accessibilityFeatures;
VoidCallback? get onAccessibilityFeaturesChanged;
set onAccessibilityFeaturesChanged(VoidCallback? callback);
@Deprecated('''
In a multi-view world, the platform dispatcher can no longer provide apis
to update semantics since each view will host its own semantics tree.
Semantics updates must be passed to an individual [FlutterView]. To update
semantics, use PlatformDispatcher.instance.views to get a [FlutterView] and
call `updateSemantics`.
''')
void updateSemantics(SemanticsUpdate update);
Locale get locale;
List<Locale> get locales;
Locale? computePlatformResolvedLocale(List<Locale> supportedLocales);
VoidCallback? get onLocaleChanged;
set onLocaleChanged(VoidCallback? callback);
String get initialLifecycleState => '';
bool get alwaysUse24HourFormat;
double get textScaleFactor;
bool get nativeSpellCheckServiceDefined => false;
bool get brieflyShowPassword => true;
VoidCallback? get onTextScaleFactorChanged;
set onTextScaleFactorChanged(VoidCallback? callback);
Brightness get platformBrightness;
VoidCallback? get onPlatformBrightnessChanged;
set onPlatformBrightnessChanged(VoidCallback? callback);
String? get systemFontFamily;
VoidCallback? get onSystemFontFamilyChanged;
set onSystemFontFamilyChanged(VoidCallback? callback);
bool get semanticsEnabled;
VoidCallback? get onSemanticsEnabledChanged;
set onSemanticsEnabledChanged(VoidCallback? callback);
SemanticsActionEventCallback? get onSemanticsActionEvent;
set onSemanticsActionEvent(SemanticsActionEventCallback? callback);
ErrorCallback? get onError;
set onError(ErrorCallback? callback);
String get defaultRouteName;
FrameData get frameData;
VoidCallback? get onFrameDataChanged => null;
set onFrameDataChanged(VoidCallback? callback) {}
double scaleFontSize(double unscaledFontSize);
}
enum FramePhase {
vsyncStart,
buildStart,
buildFinish,
rasterStart,
rasterFinish,
rasterFinishWallTime,
}
enum _FrameTimingInfo {
layerCacheCount,
layerCacheBytes,
pictureCacheCount,
pictureCacheBytes,
frameNumber,
}
class FrameTiming {
factory FrameTiming({
required int vsyncStart,
required int buildStart,
required int buildFinish,
required int rasterStart,
required int rasterFinish,
required int rasterFinishWallTime,
int layerCacheCount = 0,
int layerCacheBytes = 0,
int pictureCacheCount = 0,
int pictureCacheBytes = 0,
int frameNumber = 1,
}) {
return FrameTiming._(<int>[
vsyncStart,
buildStart,
buildFinish,
rasterStart,
rasterFinish,
rasterFinishWallTime,
layerCacheCount,
layerCacheBytes,
pictureCacheCount,
pictureCacheBytes,
frameNumber,
]);
}
FrameTiming._(this._data)
: assert(_data.length == _dataLength);
static final int _dataLength = FramePhase.values.length + _FrameTimingInfo.values.length;
int timestampInMicroseconds(FramePhase phase) => _data[phase.index];
Duration _rawDuration(FramePhase phase) => Duration(microseconds: _data[phase.index]);
int _rawInfo(_FrameTimingInfo info) => _data[FramePhase.values.length + info.index];
Duration get buildDuration =>
_rawDuration(FramePhase.buildFinish) - _rawDuration(FramePhase.buildStart);
Duration get rasterDuration =>
_rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.rasterStart);
Duration get vsyncOverhead => _rawDuration(FramePhase.buildStart) - _rawDuration(FramePhase.vsyncStart);
Duration get totalSpan =>
_rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.vsyncStart);
int get layerCacheCount => _rawInfo(_FrameTimingInfo.layerCacheCount);
int get layerCacheBytes => _rawInfo(_FrameTimingInfo.layerCacheBytes);
double get layerCacheMegabytes => layerCacheBytes / 1024.0 / 1024.0;
int get pictureCacheCount => _rawInfo(_FrameTimingInfo.pictureCacheCount);
int get pictureCacheBytes => _rawInfo(_FrameTimingInfo.pictureCacheBytes);
double get pictureCacheMegabytes => pictureCacheBytes / 1024.0 / 1024.0;
int get frameNumber => _data.last;
final List<int> _data; // some elements in microseconds, some in bytes, some are counts
String _formatMS(Duration duration) => '${duration.inMicroseconds * 0.001}ms';
@override
String toString() {
return '$runtimeType(buildDuration: ${_formatMS(buildDuration)}, '
'rasterDuration: ${_formatMS(rasterDuration)}, '
'vsyncOverhead: ${_formatMS(vsyncOverhead)}, '
'totalSpan: ${_formatMS(totalSpan)}, '
'layerCacheCount: $layerCacheCount, '
'layerCacheBytes: $layerCacheBytes, '
'pictureCacheCount: $pictureCacheCount, '
'pictureCacheBytes: $pictureCacheBytes, '
'frameNumber: ${_data.last})';
}
}
enum AppLifecycleState {
detached,
resumed,
inactive,
hidden,
paused,
}
enum AppExitResponse {
exit,
cancel,
}
enum AppExitType {
cancelable,
required,
}
abstract class ViewPadding {
const factory ViewPadding._(
{required double left,
required double top,
required double right,
required double bottom}) = engine.ViewPadding;
double get left;
double get top;
double get right;
double get bottom;
static const ViewPadding zero = ViewPadding._(left: 0.0, top: 0.0, right: 0.0, bottom: 0.0);
@override
String toString() {
return 'ViewPadding(left: $left, top: $top, right: $right, bottom: $bottom)';
}
}
abstract class ViewConstraints {
const factory ViewConstraints({
double minWidth,
double maxWidth,
double minHeight,
double maxHeight,
}) = engine.ViewConstraints;
factory ViewConstraints.tight(Size size) = engine.ViewConstraints.tight;
double get minWidth;
double get maxWidth;
double get minHeight;
double get maxHeight;
bool isSatisfiedBy(Size size);
bool get isTight;
ViewConstraints operator/(double factor);
}
@Deprecated(
'Use ViewPadding instead. '
'This feature was deprecated after v3.8.0-14.0.pre.',
)
typedef WindowPadding = ViewPadding;
class DisplayFeature {
const DisplayFeature({
required this.bounds,
required this.type,
required this.state,
});
final Rect bounds;
final DisplayFeatureType type;
final DisplayFeatureState state;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is DisplayFeature && bounds == other.bounds &&
type == other.type && state == other.state;
}
@override
int get hashCode => Object.hash(bounds, type, state);
@override
String toString() {
return 'DisplayFeature(rect: $bounds, type: $type, state: $state)';
}
}
enum DisplayFeatureType {
unknown,
fold,
hinge,
cutout,
}
enum DisplayFeatureState {
unknown,
postureFlat,
postureHalfOpened,
postureFlipped,
}
class Locale {
const Locale(
this._languageCode, [
this._countryCode,
]) : assert(_languageCode != ''),
scriptCode = null;
const Locale.fromSubtags({
String languageCode = 'und',
this.scriptCode,
String? countryCode,
}) : assert(languageCode != ''),
_languageCode = languageCode,
assert(scriptCode != ''),
assert(countryCode != ''),
_countryCode = countryCode;
String get languageCode => _deprecatedLanguageSubtagMap[_languageCode] ?? _languageCode;
final String _languageCode;
// This map is generated by //flutter/tools/gen_locale.dart
// Mappings generated for language subtag registry as of 2019-02-27.
static const Map<String, String> _deprecatedLanguageSubtagMap = <String, String>{
'in': 'id', // Indonesian; deprecated 1989-01-01
'iw': 'he', // Hebrew; deprecated 1989-01-01
'ji': 'yi', // Yiddish; deprecated 1989-01-01
'jw': 'jv', // Javanese; deprecated 2001-08-13
'mo': 'ro', // Moldavian, Moldovan; deprecated 2008-11-22
'aam': 'aas', // Aramanik; deprecated 2015-02-12
'adp': 'dz', // Adap; deprecated 2015-02-12
'aue': 'ktz', // ǂKxʼauǁʼein; deprecated 2015-02-12
'ayx': 'nun', // Ayi (China); deprecated 2011-08-16
'bgm': 'bcg', // Baga Mboteni; deprecated 2016-05-30
'bjd': 'drl', // Bandjigali; deprecated 2012-08-12
'ccq': 'rki', // Chaungtha; deprecated 2012-08-12
'cjr': 'mom', // Chorotega; deprecated 2010-03-11
'cka': 'cmr', // Khumi Awa Chin; deprecated 2012-08-12
'cmk': 'xch', // Chimakum; deprecated 2010-03-11
'coy': 'pij', // Coyaima; deprecated 2016-05-30
'cqu': 'quh', // Chilean Quechua; deprecated 2016-05-30
'drh': 'khk', // Darkhat; deprecated 2010-03-11
'drw': 'prs', // Darwazi; deprecated 2010-03-11
'gav': 'dev', // Gabutamon; deprecated 2010-03-11
'gfx': 'vaj', // Mangetti Dune ǃXung; deprecated 2015-02-12
'ggn': 'gvr', // Eastern Gurung; deprecated 2016-05-30
'gti': 'nyc', // Gbati-ri; deprecated 2015-02-12
'guv': 'duz', // Gey; deprecated 2016-05-30
'hrr': 'jal', // Horuru; deprecated 2012-08-12
'ibi': 'opa', // Ibilo; deprecated 2012-08-12
'ilw': 'gal', // Talur; deprecated 2013-09-10
'jeg': 'oyb', // Jeng; deprecated 2017-02-23
'kgc': 'tdf', // Kasseng; deprecated 2016-05-30
'kgh': 'kml', // Upper Tanudan Kalinga; deprecated 2012-08-12
'koj': 'kwv', // Sara Dunjo; deprecated 2015-02-12
'krm': 'bmf', // Krim; deprecated 2017-02-23
'ktr': 'dtp', // Kota Marudu Tinagas; deprecated 2016-05-30
'kvs': 'gdj', // Kunggara; deprecated 2016-05-30
'kwq': 'yam', // Kwak; deprecated 2015-02-12
'kxe': 'tvd', // Kakihum; deprecated 2015-02-12
'kzj': 'dtp', // Coastal Kadazan; deprecated 2016-05-30
'kzt': 'dtp', // Tambunan Dusun; deprecated 2016-05-30
'lii': 'raq', // Lingkhim; deprecated 2015-02-12
'lmm': 'rmx', // Lamam; deprecated 2014-02-28
'meg': 'cir', // Mea; deprecated 2013-09-10
'mst': 'mry', // Cataelano Mandaya; deprecated 2010-03-11
'mwj': 'vaj', // Maligo; deprecated 2015-02-12
'myt': 'mry', // Sangab Mandaya; deprecated 2010-03-11
'nad': 'xny', // Nijadali; deprecated 2016-05-30
'ncp': 'kdz', // Ndaktup; deprecated 2018-03-08
'nnx': 'ngv', // Ngong; deprecated 2015-02-12
'nts': 'pij', // Natagaimas; deprecated 2016-05-30
'oun': 'vaj', // ǃOǃung; deprecated 2015-02-12
'pcr': 'adx', // Panang; deprecated 2013-09-10
'pmc': 'huw', // Palumata; deprecated 2016-05-30
'pmu': 'phr', // Mirpur Panjabi; deprecated 2015-02-12
'ppa': 'bfy', // Pao; deprecated 2016-05-30
'ppr': 'lcq', // Piru; deprecated 2013-09-10
'pry': 'prt', // Pray 3; deprecated 2016-05-30
'puz': 'pub', // Purum Naga; deprecated 2014-02-28
'sca': 'hle', // Sansu; deprecated 2012-08-12
'skk': 'oyb', // Sok; deprecated 2017-02-23
'tdu': 'dtp', // Tempasuk Dusun; deprecated 2016-05-30
'thc': 'tpo', // Tai Hang Tong; deprecated 2016-05-30
'thx': 'oyb', // The; deprecated 2015-02-12
'tie': 'ras', // Tingal; deprecated 2011-08-16
'tkk': 'twm', // Takpa; deprecated 2011-08-16
'tlw': 'weo', // South Wemale; deprecated 2012-08-12
'tmp': 'tyj', // Tai Mène; deprecated 2016-05-30
'tne': 'kak', // Tinoc Kallahan; deprecated 2016-05-30
'tnf': 'prs', // Tangshewi; deprecated 2010-03-11
'tsf': 'taj', // Southwestern Tamang; deprecated 2015-02-12
'uok': 'ema', // Uokha; deprecated 2015-02-12
'xba': 'cax', // Kamba (Brazil); deprecated 2016-05-30
'xia': 'acn', // Xiandao; deprecated 2013-09-10
'xkh': 'waw', // Karahawyana; deprecated 2016-05-30
'xsj': 'suj', // Subi; deprecated 2015-02-12
'ybd': 'rki', // Yangbye; deprecated 2012-08-12
'yma': 'lrr', // Yamphe; deprecated 2012-08-12
'ymt': 'mtm', // Mator-Taygi-Karagas; deprecated 2015-02-12
'yos': 'zom', // Yos; deprecated 2013-09-10
'yuu': 'yug', // Yugh; deprecated 2014-02-28
};
final String? scriptCode;
String? get countryCode => _deprecatedRegionSubtagMap[_countryCode] ?? _countryCode;
final String? _countryCode;
// This map is generated by //flutter/tools/gen_locale.dart
// Mappings generated for language subtag registry as of 2019-02-27.
static const Map<String, String> _deprecatedRegionSubtagMap = <String, String>{
'BU': 'MM', // Burma; deprecated 1989-12-05
'DD': 'DE', // German Democratic Republic; deprecated 1990-10-30
'FX': 'FR', // Metropolitan France; deprecated 1997-07-14
'TP': 'TL', // East Timor; deprecated 2002-05-20
'YD': 'YE', // Democratic Yemen; deprecated 1990-08-14
'ZR': 'CD', // Zaire; deprecated 1997-07-14
};
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is Locale
&& other.languageCode == languageCode
&& other.scriptCode == scriptCode
&& other.countryCode == countryCode;
}
@override
int get hashCode => Object.hash(languageCode, scriptCode, countryCode);
@keepToString
@override
String toString() => _rawToString('_');
// TODO(yjbanov): implement to match flutter native.
String toLanguageTag() => _rawToString('-');
String _rawToString(String separator) {
final StringBuffer out = StringBuffer(languageCode);
if (scriptCode != null) {
out.write('$separator$scriptCode');
}
if (_countryCode != null) {
out.write('$separator$countryCode');
}
return out.toString();
}
}
enum DartPerformanceMode {
balanced,
latency,
throughput,
memory,
}
class SemanticsActionEvent {
const SemanticsActionEvent({
required this.type,
required this.viewId,
required this.nodeId,
this.arguments,
});
final SemanticsAction type;
final int viewId;
final int nodeId;
final Object? arguments;
static const Object _noArgumentPlaceholder = Object();
SemanticsActionEvent copyWith({
SemanticsAction? type,
int? viewId,
int? nodeId,
Object? arguments = _noArgumentPlaceholder,
}) {
return SemanticsActionEvent(
type: type ?? this.type,
viewId: viewId ?? this.viewId,
nodeId: nodeId ?? this.nodeId,
arguments: arguments == _noArgumentPlaceholder ? this.arguments : arguments,
);
}
@override
String toString() => 'SemanticsActionEvent($type, view: $viewId, node: $nodeId)';
}
final class ViewFocusEvent {
const ViewFocusEvent({
required this.viewId,
required this.state,
required this.direction,
});
final int viewId;
final ViewFocusState state;
final ViewFocusDirection direction;
@override
String toString() {
return 'ViewFocusEvent(viewId: $viewId, state: $state, direction: $direction)';
}
}
enum ViewFocusState {
unfocused,
focused,
}
enum ViewFocusDirection {
undefined,
forward,
backward,
}
| engine/lib/web_ui/lib/platform_dispatcher.dart/0 | {
"file_path": "engine/lib/web_ui/lib/platform_dispatcher.dart",
"repo_id": "engine",
"token_count": 6150
} | 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.
import 'dart:async';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
/// Instantiates a [ui.Codec] backed by an `SkAnimatedImage` from Skia.
FutureOr<ui.Codec> skiaInstantiateImageCodec(Uint8List list,
[int? targetWidth, int? targetHeight]) {
// If we have either a target width or target height, use canvaskit to decode.
if (browserSupportsImageDecoder && (targetWidth == null && targetHeight == null)) {
return CkBrowserImageDecoder.create(
data: list,
debugSource: 'encoded image bytes',
);
} else {
return CkAnimatedImage.decodeFromBytes(list, 'encoded image bytes', targetWidth: targetWidth, targetHeight: targetHeight);
}
}
void skiaDecodeImageFromPixels(
Uint8List pixels,
int width,
int height,
ui.PixelFormat format,
ui.ImageDecoderCallback callback, {
int? rowBytes,
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) {
if (targetWidth != null) {
assert(allowUpscaling || targetWidth <= width);
}
if (targetHeight != null) {
assert(allowUpscaling || targetHeight <= height);
}
// Run in a timer to avoid janking the current frame by moving the decoding
// work outside the frame event.
Timer.run(() {
final SkImage? skImage = canvasKit.MakeImage(
SkImageInfo(
width: width.toDouble(),
height: height.toDouble(),
colorType: format == ui.PixelFormat.rgba8888 ? canvasKit.ColorType.RGBA_8888 : canvasKit.ColorType.BGRA_8888,
alphaType: canvasKit.AlphaType.Premul,
colorSpace: SkColorSpaceSRGB,
),
pixels,
(rowBytes ?? 4 * width).toDouble(),
);
if (skImage == null) {
domWindow.console.warn('Failed to create image from pixels.');
return;
}
if (targetWidth != null || targetHeight != null) {
if (validUpscale(allowUpscaling, targetWidth, targetHeight, width, height)) {
return callback(scaleImage(skImage, targetWidth, targetHeight));
}
}
return callback(CkImage(skImage));
});
}
// An invalid upscale happens when allowUpscaling is false AND either the given
// targetWidth is larger than the originalWidth OR the targetHeight is larger than originalHeight.
bool validUpscale(bool allowUpscaling, int? targetWidth, int? targetHeight, int originalWidth, int originalHeight) {
if (allowUpscaling) {
return true;
}
final bool targetWidthFits;
final bool targetHeightFits;
if (targetWidth != null) {
targetWidthFits = targetWidth <= originalWidth;
} else {
targetWidthFits = true;
}
if (targetHeight != null) {
targetHeightFits = targetHeight <= originalHeight;
} else {
targetHeightFits = true;
}
return targetWidthFits && targetHeightFits;
}
/// Creates a scaled [CkImage] from an [SkImage] by drawing the [SkImage] to a canvas.
///
/// This function will only be called if either a targetWidth or targetHeight is not null
///
/// If only one of targetWidth or targetHeight are specified, the other
/// dimension will be scaled according to the aspect ratio of the supplied
/// dimension.
///
/// If either targetWidth or targetHeight is less than or equal to zero, it
/// will be treated as if it is null.
CkImage scaleImage(SkImage image, int? targetWidth, int? targetHeight) {
assert(targetWidth != null || targetHeight != null);
if (targetWidth != null && targetWidth <= 0) {
targetWidth = null;
}
if (targetHeight != null && targetHeight <= 0) {
targetHeight = null;
}
if (targetWidth == null && targetHeight != null) {
targetWidth = (targetHeight * (image.width() / image.height())).round();
} else if (targetHeight == null && targetWidth != null) {
targetHeight = targetWidth ~/ (image.width() / image.height());
}
assert(targetWidth != null);
assert(targetHeight != null);
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
final CkPaint paint = CkPaint();
canvas.drawImageRect(
CkImage(image),
ui.Rect.fromLTWH(0, 0, image.width(), image.height()),
ui.Rect.fromLTWH(0, 0, targetWidth!.toDouble(), targetHeight!.toDouble()),
paint,
);
paint.dispose();
final CkPicture picture = recorder.endRecording();
final ui.Image finalImage = picture.toImageSync(
targetWidth,
targetHeight
);
final CkImage ckImage = finalImage as CkImage;
return ckImage;
}
/// Thrown when the web engine fails to decode an image, either due to a
/// network issue, corrupted image contents, or missing codec.
class ImageCodecException implements Exception {
ImageCodecException(this._message);
final String _message;
@override
String toString() => 'ImageCodecException: $_message';
}
const String _kNetworkImageMessage = 'Failed to load network image.';
/// Instantiates a [ui.Codec] backed by an `SkAnimatedImage` from Skia after
/// requesting from URI.
Future<ui.Codec> skiaInstantiateWebImageCodec(
String url, ui_web.ImageCodecChunkCallback? chunkCallback) async {
final Uint8List list = await fetchImage(url, chunkCallback);
if (browserSupportsImageDecoder) {
return CkBrowserImageDecoder.create(data: list, debugSource: url);
} else {
return CkAnimatedImage.decodeFromBytes(list, url);
}
}
/// Sends a request to fetch image data.
Future<Uint8List> fetchImage(String url, ui_web.ImageCodecChunkCallback? chunkCallback) async {
try {
final HttpFetchResponse response = await httpFetch(url);
final int? contentLength = response.contentLength;
if (!response.hasPayload) {
throw ImageCodecException(
'$_kNetworkImageMessage\n'
'Image URL: $url\n'
'Server response code: ${response.status}',
);
}
if (chunkCallback != null && contentLength != null) {
return readChunked(response.payload, contentLength, chunkCallback);
} else {
return await response.asUint8List();
}
} on HttpFetchError catch (_) {
throw ImageCodecException(
'$_kNetworkImageMessage\n'
'Image URL: $url\n'
'Trying to load an image from another domain? Find answers at:\n'
'https://flutter.dev/docs/development/platform-integration/web-images',
);
}
}
/// Reads the [payload] in chunks using the browser's Streams API
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API
Future<Uint8List> readChunked(HttpFetchPayload payload, int contentLength, ui_web.ImageCodecChunkCallback chunkCallback) async {
final JSUint8Array result = createUint8ArrayFromLength(contentLength);
int position = 0;
int cumulativeBytesLoaded = 0;
await payload.read<JSUint8Array>((JSUint8Array chunk) {
cumulativeBytesLoaded += chunk.length.toDartInt;
chunkCallback(cumulativeBytesLoaded, contentLength);
result.set(chunk, position.toJS);
position += chunk.length.toDartInt;
});
return result.toDart;
}
/// A [ui.Image] backed by an `SkImage` from Skia.
class CkImage implements ui.Image, StackTraceDebugger {
CkImage(SkImage skImage, { this.videoFrame }) {
box = CountedRef<CkImage, SkImage>(skImage, this, 'SkImage');
_init();
}
CkImage.cloneOf(this.box, {this.videoFrame}) {
_init();
box.ref(this);
}
void _init() {
assert(() {
_debugStackTrace = StackTrace.current;
return true;
}());
ui.Image.onCreate?.call(this);
}
@override
StackTrace get debugStackTrace => _debugStackTrace;
late StackTrace _debugStackTrace;
// Use ref counting because `SkImage` may be deleted either due to this object
// being garbage-collected, or by an explicit call to [delete].
late final CountedRef<CkImage, SkImage> box;
/// For browsers that support `ImageDecoder` this field holds the video frame
/// from which this image was created.
///
/// Skia owns the video frame and will close it when it's no longer used.
/// However, Flutter co-owns the [SkImage] and therefore it's safe to access
/// the video frame until the image is [dispose]d of.
VideoFrame? videoFrame;
/// The underlying Skia image object.
///
/// Do not store the returned value. It is memory-managed by [CountedRef].
/// Storing it may result in use-after-free bugs.
SkImage get skImage => box.nativeObject;
bool _disposed = false;
bool _debugCheckIsNotDisposed() {
assert(!_disposed, 'This image has been disposed.');
return true;
}
@override
void dispose() {
assert(
!_disposed,
'Cannot dispose an image that has already been disposed.',
);
ui.Image.onDispose?.call(this);
_disposed = true;
box.unref(this);
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError(
'Image.debugDisposed is only available when asserts are enabled.');
}
@override
CkImage clone() {
assert(_debugCheckIsNotDisposed());
return CkImage.cloneOf(box, videoFrame: videoFrame?.clone());
}
@override
bool isCloneOf(ui.Image other) {
assert(_debugCheckIsNotDisposed());
return other is CkImage && other.skImage.isAliasOf(skImage);
}
@override
List<StackTrace>? debugGetOpenHandleStackTraces() =>
box.debugGetStackTraces();
@override
int get width {
assert(_debugCheckIsNotDisposed());
return skImage.width().toInt();
}
@override
int get height {
assert(_debugCheckIsNotDisposed());
return skImage.height().toInt();
}
@override
Future<ByteData> toByteData({
ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba,
}) {
assert(_debugCheckIsNotDisposed());
// readPixelsFromVideoFrame currently does not convert I420, I444, I422
// videoFrame formats to RGBA
if (videoFrame != null && videoFrame!.format != 'I420' && videoFrame!.format != 'I444' && videoFrame!.format != 'I422') {
return readPixelsFromVideoFrame(videoFrame!, format);
} else {
return _readPixelsFromSkImage(format);
}
}
@override
ui.ColorSpace get colorSpace => ui.ColorSpace.sRGB;
Future<ByteData> _readPixelsFromSkImage(ui.ImageByteFormat format) {
final SkAlphaType alphaType = format == ui.ImageByteFormat.rawStraightRgba ? canvasKit.AlphaType.Unpremul : canvasKit.AlphaType.Premul;
final ByteData? data = _encodeImage(
skImage: skImage,
format: format,
alphaType: alphaType,
colorType: canvasKit.ColorType.RGBA_8888,
colorSpace: SkColorSpaceSRGB,
);
if (data == null) {
return Future<ByteData>.error('Failed to encode the image into bytes.');
} else {
return Future<ByteData>.value(data);
}
}
static ByteData? _encodeImage({
required SkImage skImage,
required ui.ImageByteFormat format,
required SkAlphaType alphaType,
required SkColorType colorType,
required ColorSpace colorSpace,
}) {
Uint8List? bytes;
if (format == ui.ImageByteFormat.rawRgba || format == ui.ImageByteFormat.rawStraightRgba) {
final SkImageInfo imageInfo = SkImageInfo(
alphaType: alphaType,
colorType: colorType,
colorSpace: colorSpace,
width: skImage.width(),
height: skImage.height(),
);
bytes = skImage.readPixels(0, 0, imageInfo);
} else {
bytes = skImage.encodeToBytes(); // defaults to PNG 100%
}
return bytes?.buffer.asByteData(0, bytes.length);
}
@override
String toString() {
assert(_debugCheckIsNotDisposed());
return '[$width\u00D7$height]';
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/image.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/image.dart",
"repo_id": "engine",
"token_count": 4174
} | 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.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../scene_painting.dart';
import 'canvas.dart';
import 'canvaskit_api.dart';
import 'image.dart';
import 'native_memory.dart';
import 'renderer.dart';
import 'surface.dart';
/// Implements [ui.Picture] on top of [SkPicture].
class CkPicture implements ScenePicture {
CkPicture(SkPicture skPicture) {
_ref = UniqueRef<SkPicture>(this, skPicture, 'Picture');
}
late final UniqueRef<SkPicture> _ref;
SkPicture get skiaObject => _ref.nativeObject;
@override
ui.Rect get cullRect => fromSkRect(skiaObject.cullRect());
@override
int get approximateBytesUsed => skiaObject.approximateBytesUsed();
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _isDisposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError(
'Picture.debugDisposed is only available when asserts are enabled.');
}
/// This is set to true when [dispose] is called and is never reset back to
/// false.
///
/// This extra flag is necessary on top of [rawSkiaObject] because
/// [rawSkiaObject] being null does not indicate permanent deletion.
bool _isDisposed = false;
/// The stack trace taken when [dispose] was called.
///
/// Returns null if [dispose] has not been called. Returns null in non-debug
/// modes.
StackTrace? _debugDisposalStackTrace;
/// Throws an [AssertionError] if this picture was disposed.
///
/// The [mainErrorMessage] is used as the first line in the error message. It
/// is expected to end with a period, e.g. "Failed to draw picture." The full
/// message will also explain that the error is due to the fact that the
/// picture was disposed and include the stack trace taken when the picture
/// was disposed.
bool debugCheckNotDisposed(String mainErrorMessage) {
if (_isDisposed) {
throw StateError(
'$mainErrorMessage\n'
'The picture has been disposed. When the picture was disposed the '
'stack trace was:\n'
'$_debugDisposalStackTrace',
);
}
return true;
}
@override
void dispose() {
assert(debugCheckNotDisposed('Cannot dispose picture.'));
assert(() {
_debugDisposalStackTrace = StackTrace.current;
return true;
}());
ui.Picture.onDispose?.call(this);
_isDisposed = true;
_ref.dispose();
}
@override
Future<ui.Image> toImage(int width, int height) async {
return toImageSync(width, height);
}
@override
CkImage toImageSync(int width, int height) {
assert(debugCheckNotDisposed('Cannot convert picture to image.'));
final Surface surface = CanvasKitRenderer.instance.pictureToImageSurface;
final CkSurface ckSurface = surface
.createOrUpdateSurface(ui.Size(width.toDouble(), height.toDouble()));
final CkCanvas ckCanvas = ckSurface.getCanvas();
ckCanvas.clear(const ui.Color(0x00000000));
ckCanvas.drawPicture(this);
final SkImage skImage = ckSurface.surface.makeImageSnapshot();
final SkImageInfo imageInfo = SkImageInfo(
alphaType: canvasKit.AlphaType.Premul,
colorType: canvasKit.ColorType.RGBA_8888,
colorSpace: SkColorSpaceSRGB,
width: width.toDouble(),
height: height.toDouble(),
);
final Uint8List pixels = skImage.readPixels(0, 0, imageInfo);
final SkImage? rasterImage =
canvasKit.MakeImage(imageInfo, pixels, (4 * width).toDouble());
if (rasterImage == null) {
throw StateError('Unable to convert image pixels into SkImage.');
}
return CkImage(rasterImage);
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/picture.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/picture.dart",
"repo_id": "engine",
"token_count": 1327
} | 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.
import 'dart:async';
import 'package:ui/ui.dart' as ui;
import '../engine.dart';
class EngineFlutterDisplay extends ui.Display {
EngineFlutterDisplay({
required this.id,
required this.size,
required this.refreshRate,
});
/// The single [EngineFlutterDisplay] that the web page is rendered on.
static EngineFlutterDisplay get instance => _instance;
static final EngineFlutterDisplay _instance = EngineFlutterDisplay(
id: 0,
size: ui.Size(domWindow.screen?.width ?? 0, domWindow.screen?.height ?? 0),
refreshRate: 60,
);
@override
final int id;
// TODO(mdebbar): https://github.com/flutter/flutter/issues/133562
// `size` and `refreshRate` should be kept up-to-date with the
// browser. E.g. the window could be resized or moved to another display with
// a different refresh rate.
@override
final ui.Size size;
@override
final double refreshRate;
@override
double get devicePixelRatio =>
_debugDevicePixelRatioOverride ?? browserDevicePixelRatio;
/// The real device pixel ratio of the browser.
///
/// This value cannot be overriden by tests, for example.
double get browserDevicePixelRatio {
final double ratio = domWindow.devicePixelRatio;
// Guard against WebOS returning 0.
return (ratio == 0.0) ? 1.0 : ratio;
}
/// Overrides the default device pixel ratio.
///
/// This is useful in tests to emulate screens of different dimensions.
///
/// Passing `null` resets the device pixel ratio to the browser's default.
void debugOverrideDevicePixelRatio(double? value) {
_debugDevicePixelRatioOverride = value;
}
double? _debugDevicePixelRatioOverride;
}
/// Controls the screen orientation using the browser's screen orientation API.
class ScreenOrientation {
const ScreenOrientation();
static ScreenOrientation get instance => _instance;
static const ScreenOrientation _instance = ScreenOrientation();
static const String lockTypeAny = 'any';
static const String lockTypeNatural = 'natural';
static const String lockTypeLandscape = 'landscape';
static const String lockTypePortrait = 'portrait';
static const String lockTypePortraitPrimary = 'portrait-primary';
static const String lockTypePortraitSecondary = 'portrait-secondary';
static const String lockTypeLandscapePrimary = 'landscape-primary';
static const String lockTypeLandscapeSecondary = 'landscape-secondary';
/// Sets preferred screen orientation.
///
/// Specifies the set of orientations the application interface can be
/// displayed in.
///
/// The [orientations] argument is a list of DeviceOrientation values.
/// The empty list uses Screen unlock api and causes the application to
/// defer to the operating system default.
///
/// See w3c screen api: https://www.w3.org/TR/screen-orientation/
Future<bool> setPreferredOrientation(List<dynamic> orientations) async {
final DomScreen? screen = domWindow.screen;
if (screen != null) {
final DomScreenOrientation? screenOrientation = screen.orientation;
if (screenOrientation != null) {
if (orientations.isEmpty) {
screenOrientation.unlock();
return true;
} else {
final String? lockType =
_deviceOrientationToLockType(orientations.first as String?);
if (lockType != null) {
try {
await screenOrientation.lock(lockType);
return true;
} catch (_) {
// On Chrome desktop an error with 'not supported on this device
// error' is fired.
return Future<bool>.value(false);
}
}
}
}
}
// API is not supported on this browser return false.
return false;
}
// Converts device orientation to w3c OrientationLockType enum.
//
// See also: https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock
static String? _deviceOrientationToLockType(String? deviceOrientation) {
switch (deviceOrientation) {
case 'DeviceOrientation.portraitUp':
return lockTypePortraitPrimary;
case 'DeviceOrientation.portraitDown':
return lockTypePortraitSecondary;
case 'DeviceOrientation.landscapeLeft':
return lockTypeLandscapePrimary;
case 'DeviceOrientation.landscapeRight':
return lockTypeLandscapeSecondary;
default:
return null;
}
}
}
| engine/lib/web_ui/lib/src/engine/display.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/display.dart",
"repo_id": "engine",
"token_count": 1527
} | 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.
import 'package:ui/ui.dart' as ui;
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 [imageFilter] to its children.
class PersistedImageFilter extends PersistedContainerSurface
implements ui.ImageFilterEngineLayer {
PersistedImageFilter(PersistedImageFilter? super.oldLayer, this.filter, this.offset);
final ui.ImageFilter filter;
final ui.Offset offset;
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
final double dx = offset.dx;
final double dy = offset.dy;
if (dx != 0.0 || dy != 0.0) {
transform = transform!.clone();
transform!.translate(dx, dy);
}
projectedClip = null;
}
/// Cached inverse of transform on this node. Unlike transform, this
/// Matrix only contains local transform (not chain multiplied since root).
Matrix4? _localTransformInverse;
@override
Matrix4 get localTransformInverse => _localTransformInverse ??=
Matrix4.translationValues(-offset.dx, -offset.dy, 0);
DomElement? _svgFilter;
@override
DomElement? get childContainer => _childContainer;
DomElement? _childContainer;
@override
void adoptElements(PersistedImageFilter oldSurface) {
super.adoptElements(oldSurface);
_svgFilter = oldSurface._svgFilter;
_childContainer = oldSurface._childContainer;
oldSurface._svgFilter = null;
oldSurface._childContainer = null;
}
@override
void discard() {
super.discard();
ResourceManager.instance.removeResource(_svgFilter);
_svgFilter = null;
_childContainer = null;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-image-filter');
final DomElement container = defaultCreateElement('flt-image-filter-interior');
if (debugExplainSurfaceStats) {
// This creates an additional interior element. Count it too.
surfaceStatsFor(this).allocatedDomNodeCount++;
}
setElementStyle(container, 'position', 'absolute');
setElementStyle(container, 'transform-origin', '0 0 0');
setElementStyle(element, 'position', 'absolute');
setElementStyle(element, 'transform-origin', '0 0 0');
_childContainer = container;
element.appendChild(container);
return element;
}
@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 (backendFilter is ModeHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(rootElement);
/// Some blendModes do not make an svgFilter. See [EngineHtmlColorFilter.makeSvgFilter()]
if (_svgFilter == null) {
return;
}
} else if (backendFilter is MatrixHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(rootElement);
}
_childContainer!.style.filter = backendFilter.filterAttribute;
_childContainer!.style.transform = backendFilter.transformAttribute;
rootElement!.style
..left = '${offset.dx}px'
..top = '${offset.dy}px';
}
@override
void update(PersistedImageFilter oldSurface) {
super.update(oldSurface);
if (oldSurface.filter != filter || oldSurface.offset != offset) {
apply();
}
}
}
| engine/lib/web_ui/lib/src/engine/html/image_filter.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/image_filter.dart",
"repo_id": "engine",
"token_count": 1251
} | 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.
import '../dom.dart';
import '../platform_dispatcher.dart';
import '../platform_views/slots.dart';
import '../window.dart';
import 'surface.dart';
/// A surface containing a platform view, which is an HTML element.
class PersistedPlatformView extends PersistedLeafSurface {
PersistedPlatformView(this.platformViewId, this.dx, this.dy, this.width, this.height) {
// Ensure platform view with `viewId` is injected into the `implicitView`
// before rendering its shadow DOM `slot`.
final EngineFlutterView implicitView = EnginePlatformDispatcher.instance.implicitView!;
implicitView.dom.injectPlatformView(platformViewId);
}
final int platformViewId;
final double dx;
final double dy;
final double width;
final double height;
@override
DomElement createElement() {
return createPlatformViewSlot(platformViewId);
}
@override
void apply() {
// See `_compositeWithParams` in the HtmlViewEmbedder for the canvaskit equivalent.
rootElement!.style
..transform = 'translate(${dx}px, ${dy}px)'
..width = '${width}px'
..height = '${height}px'
..position = 'absolute';
}
// Platform Views can only be updated if their viewId matches.
@override
bool canUpdateAsMatch(PersistedSurface oldSurface) {
if (super.canUpdateAsMatch(oldSurface)) {
// super checks the runtimeType of the surface, so we can just cast...
return platformViewId == ((oldSurface as PersistedPlatformView).platformViewId);
}
return false;
}
@override
double matchForUpdate(PersistedPlatformView existingSurface) {
return existingSurface.platformViewId == platformViewId ? 0.0 : 1.0;
}
@override
void update(PersistedPlatformView oldSurface) {
assert(
platformViewId == oldSurface.platformViewId,
'PersistedPlatformView with different platformViewId should never be updated. Check the canUpdateAsMatch method.',
);
super.update(oldSurface);
// Only update if the view has been resized
if (dx != oldSurface.dx ||
dy != oldSurface.dy ||
width != oldSurface.width ||
height != oldSurface.height) {
// A change in any of the dimensions is performed by calling apply.
apply();
}
}
}
| engine/lib/web_ui/lib/src/engine/html/platform_view.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/platform_view.dart",
"repo_id": "engine",
"token_count": 786
} | 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.
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'browser_detection.dart';
import 'dom.dart';
import 'safe_browser_api.dart';
Object? get _jsImageDecodeFunction => getJsProperty<Object?>(
getJsProperty<Object>(
getJsProperty<Object>(domWindow, 'Image'),
'prototype',
),
'decode',
);
final bool _supportsDecode = _jsImageDecodeFunction != null;
// TODO(mdebbar): Deprecate this and remove it.
// https://github.com/flutter/flutter/issues/127395
typedef WebOnlyImageCodecChunkCallback = ui_web.ImageCodecChunkCallback;
class HtmlCodec implements ui.Codec {
HtmlCodec(this.src, {this.chunkCallback});
final String src;
final ui_web.ImageCodecChunkCallback? chunkCallback;
@override
int get frameCount => 1;
@override
int get repetitionCount => 0;
@override
Future<ui.FrameInfo> getNextFrame() async {
final Completer<ui.FrameInfo> completer = Completer<ui.FrameInfo>();
// Currently there is no way to watch decode progress, so
// we add 0/100 , 100/100 progress callbacks to enable loading progress
// builders to create UI.
chunkCallback?.call(0, 100);
if (_supportsDecode) {
final DomHTMLImageElement imgElement = createDomHTMLImageElement();
imgElement.src = src;
setJsProperty<String>(imgElement, 'decoding', 'async');
// Ignoring the returned future on purpose because we're communicating
// through the `completer`.
// ignore: unawaited_futures
imgElement.decode().then((dynamic _) {
chunkCallback?.call(100, 100);
int naturalWidth = imgElement.naturalWidth.toInt();
int naturalHeight = imgElement.naturalHeight.toInt();
// Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=700533.
if (naturalWidth == 0 && naturalHeight == 0 && browserEngine == BrowserEngine.firefox) {
const int kDefaultImageSizeFallback = 300;
naturalWidth = kDefaultImageSizeFallback;
naturalHeight = kDefaultImageSizeFallback;
}
final HtmlImage image = HtmlImage(
imgElement,
naturalWidth,
naturalHeight,
);
completer.complete(SingleFrameInfo(image));
}).catchError((dynamic e) {
// This code path is hit on Chrome 80.0.3987.16 when too many
// images are on the page (~1000).
// Fallback here is to load using onLoad instead.
_decodeUsingOnLoad(completer);
});
} else {
_decodeUsingOnLoad(completer);
}
return completer.future;
}
void _decodeUsingOnLoad(Completer<ui.FrameInfo> completer) {
final DomHTMLImageElement imgElement = createDomHTMLImageElement();
// If the browser doesn't support asynchronous decoding of an image,
// then use the `onload` event to decide when it's ready to paint to the
// DOM. Unfortunately, this will cause the image to be decoded synchronously
// on the main thread, and may cause dropped framed.
late DomEventListener errorListener;
DomEventListener? loadListener;
errorListener = createDomEventListener((DomEvent event) {
if (loadListener != null) {
imgElement.removeEventListener('load', loadListener);
}
imgElement.removeEventListener('error', errorListener);
completer.completeError(event);
});
imgElement.addEventListener('error', errorListener);
loadListener = createDomEventListener((DomEvent event) {
if (chunkCallback != null) {
chunkCallback!(100, 100);
}
imgElement.removeEventListener('load', loadListener);
imgElement.removeEventListener('error', errorListener);
final HtmlImage image = HtmlImage(
imgElement,
imgElement.naturalWidth.toInt(),
imgElement.naturalHeight.toInt(),
);
completer.complete(SingleFrameInfo(image));
});
imgElement.addEventListener('load', loadListener);
imgElement.src = src;
}
@override
void dispose() {}
}
class HtmlBlobCodec extends HtmlCodec {
HtmlBlobCodec(this.blob) : super(domWindow.URL.createObjectURL(blob));
final DomBlob blob;
@override
void dispose() {
domWindow.URL.revokeObjectURL(src);
}
}
class SingleFrameInfo implements ui.FrameInfo {
SingleFrameInfo(this.image);
@override
Duration get duration => Duration.zero;
@override
final ui.Image image;
}
class HtmlImage implements ui.Image {
HtmlImage(this.imgElement, this.width, this.height) {
ui.Image.onCreate?.call(this);
}
final DomHTMLImageElement imgElement;
bool _didClone = false;
bool _disposed = false;
@override
void dispose() {
ui.Image.onDispose?.call(this);
// Do nothing. The codec that owns this image should take care of
// releasing the object url.
assert(() {
_disposed = true;
return true;
}());
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError('Image.debugDisposed is only available when asserts are enabled.');
}
@override
ui.Image clone() => this;
@override
bool isCloneOf(ui.Image other) => other == this;
@override
List<StackTrace>? debugGetOpenHandleStackTraces() => null;
@override
final int width;
@override
final int height;
@override
Future<ByteData?> toByteData({ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) {
switch (format) {
// TODO(ColdPaleLight): https://github.com/flutter/flutter/issues/89128
// The format rawRgba always returns straight rather than premul currently.
case ui.ImageByteFormat.rawRgba:
case ui.ImageByteFormat.rawStraightRgba:
final DomCanvasElement canvas = createDomCanvasElement()
..width = width.toDouble()
..height = height.toDouble();
final DomCanvasRenderingContext2D ctx = canvas.context2D;
ctx.drawImage(imgElement, 0, 0);
final DomImageData imageData = ctx.getImageData(0, 0, width, height);
return Future<ByteData?>.value(imageData.data.buffer.asByteData());
default:
if (imgElement.src?.startsWith('data:') ?? false) {
final UriData data = UriData.fromUri(Uri.parse(imgElement.src!));
return Future<ByteData?>.value(data.contentAsBytes().buffer.asByteData());
} else {
return Future<ByteData?>.value();
}
}
}
@override
ui.ColorSpace get colorSpace => ui.ColorSpace.sRGB;
DomHTMLImageElement cloneImageElement() {
if (!_didClone) {
_didClone = true;
imgElement.style.position = 'absolute';
}
return imgElement.cloneNode(true) as DomHTMLImageElement;
}
@override
String toString() => '[$width\u00D7$height]';
}
| engine/lib/web_ui/lib/src/engine/html_image_codec.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html_image_codec.dart",
"repo_id": "engine",
"token_count": 2591
} | 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.
import 'dom.dart';
DomElement? _logElement;
late DomElement _logContainer;
List<_LogMessage> _logBuffer = <_LogMessage>[];
class _LogMessage {
_LogMessage(this.message);
int duplicateCount = 1;
final String message;
@override
String toString() {
if (duplicateCount == 1) {
return message;
}
return '${duplicateCount}x $message';
}
}
/// A drop-in replacement for [print] that prints on the screen into a
/// fixed-positioned element.
///
/// This is useful, for example, for print-debugging on iOS when debugging over
/// USB is not available.
void printOnScreen(Object object) {
if (_logElement == null) {
_initialize();
}
final String message = '$object';
if (_logBuffer.isNotEmpty && _logBuffer.last.message == message) {
_logBuffer.last.duplicateCount += 1;
} else {
_logBuffer.add(_LogMessage(message));
}
if (_logBuffer.length > 80) {
_logBuffer = _logBuffer.sublist(_logBuffer.length - 50);
}
_logContainer.text = _logBuffer.join('\n');
// Also log to console for browsers that give you access to it.
print(message);
}
void _initialize() {
_logElement = createDomElement('flt-onscreen-log');
_logElement!.setAttribute('aria-hidden', 'true');
_logElement!.style
..position = 'fixed'
..left = '0'
..right = '0'
..bottom = '0'
..height = '25%'
..backgroundColor = 'rgba(0, 0, 0, 0.85)'
..color = 'white'
..fontSize = '8px'
..whiteSpace = 'pre-wrap'
..overflow = 'hidden'
..zIndex = '1000';
_logContainer = createDomElement('flt-log-container');
_logContainer.setAttribute('aria-hidden', 'true');
_logContainer.style
..position = 'absolute'
..bottom = '0';
_logElement!.append(_logContainer);
domDocument.body!.append(_logElement!);
}
/// Dump the current stack to the console using [print] and
/// [defaultStackFilter].
///
/// The current stack is obtained using [StackTrace.current].
///
/// The `maxFrames` argument can be given to limit the stack to the given number
/// of lines. By default, all non-filtered stack lines are shown.
///
/// The `label` argument, if present, will be printed before the stack.
void debugPrintStack({String? label, int? maxFrames}) {
if (label != null) {
print(label);
}
Iterable<String> lines =
StackTrace.current.toString().trimRight().split('\n');
if (maxFrames != null) {
lines = lines.take(maxFrames);
}
print(defaultStackFilter(lines).join('\n'));
}
/// Converts a stack to a string that is more readable by omitting stack
/// frames that correspond to Dart internals.
///
/// This function expects its input to be in the format used by
/// [StackTrace.toString()]. The output of this function is similar to that
/// format but the frame numbers will not be consecutive (frames are elided)
/// and the final line may be prose rather than a stack frame.
Iterable<String> defaultStackFilter(Iterable<String> frames) {
const List<String> filteredPackages = <String>[
'dart:async-patch',
'dart:async',
'dart:_runtime',
];
final RegExp stackParser =
RegExp(r'^#[0-9]+ +([^.]+).* \(([^/\\]*)[/\\].+:[0-9]+(?::[0-9]+)?\)$');
final RegExp packageParser = RegExp(r'^([^:]+):(.+)$');
final List<String> result = <String>[];
final List<String> skipped = <String>[];
for (final String line in frames) {
final Match? match = stackParser.firstMatch(line);
if (match != null) {
assert(match.groupCount == 2);
if (filteredPackages.contains(match.group(2))) {
final Match? packageMatch = packageParser.firstMatch(match.group(2)!);
if (packageMatch != null && packageMatch.group(1) == 'package') {
skipped.add(
'package ${packageMatch.group(2)}'); // avoid "package package:foo"
} else {
skipped.add('package ${match.group(2)}');
}
continue;
}
}
result.add(line);
}
if (skipped.length == 1) {
result.add('(elided one frame from ${skipped.single})');
} else if (skipped.length > 1) {
final List<String> where = Set<String>.from(skipped).toList()..sort();
if (where.length > 1) {
where[where.length - 1] = 'and ${where.last}';
}
if (where.length > 2) {
result.add('(elided ${skipped.length} frames from ${where.join(", ")})');
} else {
result.add('(elided ${skipped.length} frames from ${where.join(" ")})');
}
}
return result;
}
String debugIdentify(Object? object) {
return '${object!.runtimeType}(@${object.hashCode})';
}
| engine/lib/web_ui/lib/src/engine/onscreen_logging.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/onscreen_logging.dart",
"repo_id": "engine",
"token_count": 1665
} | 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.
import 'dart:math' as math;
import 'package:ui/ui.dart' as ui;
import 'dom.dart';
import 'util.dart';
/// Renders an RRect using path primitives.
abstract class RRectRenderer {
// To draw the rounded rectangle, perform the following steps:
// 0. Ensure border radius don't overlap
// 1. Flip left,right top,bottom since web doesn't support flipped
// coordinates with negative radii.
// 2. draw the line for the top
// 3. draw the arc for the top-right corner
// 4. draw the line for the right side
// 5. draw the arc for the bottom-right corner
// 6. draw the line for the bottom of the rectangle
// 7. draw the arc for the bottom-left corner
// 8. draw the line for the left side
// 9. draw the arc for the top-left corner
//
// After drawing, the current point will be the left side of the top of the
// rounded rectangle (after the corner).
// TODO(het): Confirm that this is the end point in Flutter for RRect
void render(ui.RRect inputRRect,
{bool startNewPath = true, bool reverse = false}) {
// Ensure border radius curves never overlap
final ui.RRect rrect = inputRRect.scaleRadii();
double left = rrect.left;
double right = rrect.right;
double top = rrect.top;
double bottom = rrect.bottom;
if (left > right) {
left = right;
right = rrect.left;
}
if (top > bottom) {
top = bottom;
bottom = rrect.top;
}
final double trRadiusX = rrect.trRadiusX.abs();
final double tlRadiusX = rrect.tlRadiusX.abs();
final double trRadiusY = rrect.trRadiusY.abs();
final double tlRadiusY = rrect.tlRadiusY.abs();
final double blRadiusX = rrect.blRadiusX.abs();
final double brRadiusX = rrect.brRadiusX.abs();
final double blRadiusY = rrect.blRadiusY.abs();
final double brRadiusY = rrect.brRadiusY.abs();
if (!reverse) {
if (startNewPath) {
beginPath();
}
moveTo(left + trRadiusX, top);
// Top side and top-right corner
lineTo(right - trRadiusX, top);
ellipse(
right - trRadiusX,
top + trRadiusY,
trRadiusX,
trRadiusY,
0,
1.5 * math.pi,
2.0 * math.pi,
false,
);
// Right side and bottom-right corner
lineTo(right, bottom - brRadiusY);
ellipse(
right - brRadiusX,
bottom - brRadiusY,
brRadiusX,
brRadiusY,
0,
0,
0.5 * math.pi,
false,
);
// Bottom side and bottom-left corner
lineTo(left + blRadiusX, bottom);
ellipse(
left + blRadiusX,
bottom - blRadiusY,
blRadiusX,
blRadiusY,
0,
0.5 * math.pi,
math.pi,
false,
);
// Left side and top-left corner
lineTo(left, top + tlRadiusY);
ellipse(
left + tlRadiusX,
top + tlRadiusY,
tlRadiusX,
tlRadiusY,
0,
math.pi,
1.5 * math.pi,
false,
);
} else {
// Draw the rounded rectangle, counterclockwise.
moveTo(right - trRadiusX, top);
if (startNewPath) {
beginPath();
}
// Top side and top-left corner
lineTo(left + tlRadiusX, top);
ellipse(
left + tlRadiusX,
top + tlRadiusY,
tlRadiusX,
tlRadiusY,
0,
1.5 * math.pi,
1 * math.pi,
true,
);
// Left side and bottom-left corner
lineTo(left, bottom - blRadiusY);
ellipse(
left + blRadiusX,
bottom - blRadiusY,
blRadiusX,
blRadiusY,
0,
1 * math.pi,
0.5 * math.pi,
true,
);
// Bottom side and bottom-right corner
lineTo(right - brRadiusX, bottom);
ellipse(
right - brRadiusX,
bottom - brRadiusY,
brRadiusX,
brRadiusY,
0,
0.5 * math.pi,
0 * math.pi,
true,
);
// Right side and top-right corner
lineTo(right, top + trRadiusY);
ellipse(
right - trRadiusX,
top + trRadiusY,
trRadiusX,
trRadiusY,
0,
0 * math.pi,
1.5 * math.pi,
true,
);
}
}
void beginPath();
void moveTo(double x, double y);
void lineTo(double x, double y);
void ellipse(double centerX, double centerY, double radiusX, double radiusY,
double rotation, double startAngle, double endAngle, bool antiClockwise);
}
/// Renders RRect to a 2d canvas.
class RRectToCanvasRenderer extends RRectRenderer {
RRectToCanvasRenderer(this.context);
final DomCanvasRenderingContext2D context;
@override
void beginPath() {
context.beginPath();
}
@override
void moveTo(double x, double y) {
context.moveTo(x, y);
}
@override
void lineTo(double x, double y) {
context.lineTo(x, y);
}
@override
void ellipse(double centerX, double centerY, double radiusX, double radiusY,
double rotation, double startAngle, double endAngle, bool antiClockwise) {
drawEllipse(context, centerX, centerY, radiusX, radiusY, rotation, startAngle,
endAngle, antiClockwise);
}
}
/// Renders RRect to a path.
class RRectToPathRenderer extends RRectRenderer {
RRectToPathRenderer(this.path);
final ui.Path path;
@override
void beginPath() {}
@override
void moveTo(double x, double y) {
path.moveTo(x, y);
}
@override
void lineTo(double x, double y) {
path.lineTo(x, y);
}
@override
void ellipse(double centerX, double centerY, double radiusX, double radiusY,
double rotation, double startAngle, double endAngle, bool antiClockwise) {
path.addArc(
ui.Rect.fromLTRB(centerX - radiusX, centerY - radiusY,
centerX + radiusX, centerY + radiusY),
startAngle,
antiClockwise ? startAngle - endAngle : endAngle - startAngle);
}
}
typedef RRectRendererEllipseCallback = void Function(double centerX, double centerY, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, bool antiClockwise);
typedef RRectRendererCallback = void Function(double x, double y);
/// Converts RRect to path primitives with callbacks.
class RRectMetricsRenderer extends RRectRenderer {
RRectMetricsRenderer({this.moveToCallback, this.lineToCallback, this.ellipseCallback});
final RRectRendererEllipseCallback? ellipseCallback;
final RRectRendererCallback? lineToCallback;
final RRectRendererCallback? moveToCallback;
@override
void beginPath() {}
@override
void ellipse(double centerX, double centerY, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, bool antiClockwise) => ellipseCallback!(
centerX, centerY, radiusX, radiusY, rotation, startAngle, endAngle, antiClockwise);
@override
void lineTo(double x, double y) => lineToCallback!(x, y);
@override
void moveTo(double x, double y) => moveToCallback!(x, y);
}
| engine/lib/web_ui/lib/src/engine/rrect_renderer.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/rrect_renderer.dart",
"repo_id": "engine",
"token_count": 3044
} | 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.
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
/// Implements vertical and horizontal scrolling functionality for semantics
/// objects.
///
/// Scrolling is implemented using a "joystick" method. The absolute value of
/// "scrollTop" in HTML is not important. We only need to know in whether the
/// value changed in the positive or negative direction. If it changes in the
/// positive direction we send a [ui.SemanticsAction.scrollUp]. Otherwise, we
/// send [ui.SemanticsAction.scrollDown]. The actual scrolling is then handled
/// by the framework and we receive a [ui.SemanticsUpdate] containing the new
/// [scrollPosition] and child positions.
///
/// "scrollTop" or "scrollLeft" is always reset to an arbitrarily chosen non-
/// zero "neutral" scroll position value. This is done so we have a
/// predictable range of DOM scroll position values. When the amount of
/// contents is less than the size of the viewport the browser snaps
/// "scrollTop" back to zero. If there is more content than available in the
/// viewport "scrollTop" may take positive values.
class Scrollable extends PrimaryRoleManager {
Scrollable(SemanticsObject semanticsObject)
: super.withBasics(
PrimaryRole.scrollable,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.ariaLabel,
) {
_scrollOverflowElement.style
..position = 'absolute'
..transformOrigin = '0 0 0'
// Ignore pointer events since this is a dummy element.
..pointerEvents = 'none';
append(_scrollOverflowElement);
}
/// Disables browser-driven scrolling in the presence of pointer events.
GestureModeCallback? _gestureModeListener;
/// DOM element used as a workaround for: https://github.com/flutter/flutter/issues/104036
///
/// When the assistive technology gets to the last element of the scrollable
/// list, the browser thinks the scrollable area doesn't have any more content,
/// so it overrides the value of "scrollTop"/"scrollLeft" with zero. As a result,
/// the user can't scroll back up/left.
///
/// As a workaround, we add this DOM element and set its size to
/// [canonicalNeutralScrollPosition] so the browser believes
/// that the scrollable area still has some more content, and doesn't override
/// scrollTop/scrollLetf with zero.
final DomElement _scrollOverflowElement = createDomElement('flt-semantics-scroll-overflow');
/// Listens to HTML "scroll" gestures detected by the browser.
///
/// This gesture is converted to [ui.SemanticsAction.scrollUp] or
/// [ui.SemanticsAction.scrollDown], depending on the direction.
DomEventListener? _scrollListener;
/// The value of the "scrollTop" or "scrollLeft" property of this object's
/// [element] that has zero offset relative to the [scrollPosition].
int _effectiveNeutralScrollPosition = 0;
/// Responds to browser-detected "scroll" gestures.
void _recomputeScrollPosition() {
if (_domScrollPosition != _effectiveNeutralScrollPosition) {
if (!EngineSemantics.instance.shouldAcceptBrowserGesture('scroll')) {
return;
}
final bool doScrollForward =
_domScrollPosition > _effectiveNeutralScrollPosition;
_neutralizeDomScrollPosition();
semanticsObject.recomputePositionAndSize();
final int semanticsId = semanticsObject.id;
if (doScrollForward) {
if (semanticsObject.isVerticalScrollContainer) {
EnginePlatformDispatcher.instance.invokeOnSemanticsAction(
semanticsId, ui.SemanticsAction.scrollUp, null);
} else {
assert(semanticsObject.isHorizontalScrollContainer);
EnginePlatformDispatcher.instance.invokeOnSemanticsAction(
semanticsId, ui.SemanticsAction.scrollLeft, null);
}
} else {
if (semanticsObject.isVerticalScrollContainer) {
EnginePlatformDispatcher.instance.invokeOnSemanticsAction(
semanticsId, ui.SemanticsAction.scrollDown, null);
} else {
assert(semanticsObject.isHorizontalScrollContainer);
EnginePlatformDispatcher.instance.invokeOnSemanticsAction(
semanticsId, ui.SemanticsAction.scrollRight, null);
}
}
}
}
@override
void update() {
super.update();
semanticsObject.owner.addOneTimePostUpdateCallback(() {
_neutralizeDomScrollPosition();
semanticsObject.recomputePositionAndSize();
});
if (_scrollListener == null) {
// We need to set touch-action:none explicitly here, despite the fact
// that we already have it on the <body> tag because overflow:scroll
// still causes the browser to take over pointer events in order to
// process scrolling. We don't want that when scrolling is handled by
// the framework.
//
// This is effective only in Chrome. Safari does not implement this
// CSS property. In Safari the `PointerBinding` uses `preventDefault`
// to prevent browser scrolling.
element.style.touchAction = 'none';
_gestureModeDidChange();
// Memoize the tear-off because Dart does not guarantee that two
// tear-offs of a method on the same instance will produce the same
// object.
_gestureModeListener = (_) {
_gestureModeDidChange();
};
EngineSemantics.instance.addGestureModeListener(_gestureModeListener!);
_scrollListener = createDomEventListener((_) {
_recomputeScrollPosition();
});
addEventListener('scroll', _scrollListener);
}
}
/// The value of "scrollTop" or "scrollLeft", depending on the scroll axis.
int get _domScrollPosition {
if (semanticsObject.isVerticalScrollContainer) {
return element.scrollTop.toInt();
} else {
assert(semanticsObject.isHorizontalScrollContainer);
return element.scrollLeft.toInt();
}
}
/// Resets the scroll position (top or left) to the neutral value.
///
/// The scroll position of the scrollable HTML node that's considered to
/// have zero offset relative to Flutter's notion of scroll position is
/// referred to as "neutral scroll position".
///
/// We always set the scroll position to a non-zero value in order to
/// be able to scroll in the negative direction. When scrollTop/scrollLeft is
/// zero the browser will refuse to scroll back even when there is more
/// content available.
void _neutralizeDomScrollPosition() {
// This value is arbitrary.
const int canonicalNeutralScrollPosition = 10;
final ui.Rect? rect = semanticsObject.rect;
if (rect == null) {
printWarning('Warning! the rect attribute of semanticsObject is null');
return;
}
if (semanticsObject.isVerticalScrollContainer) {
// Place the _scrollOverflowElement at the end of the content and
// make sure that when we neutralize the scrolling position,
// it doesn't scroll into the visible area.
final int verticalOffset = rect.height.ceil() + canonicalNeutralScrollPosition;
_scrollOverflowElement.style
..transform = 'translate(0px,${verticalOffset}px)'
..width = '${rect.width.round()}px'
..height = '${canonicalNeutralScrollPosition}px';
element.scrollTop = canonicalNeutralScrollPosition.toDouble();
// Read back because the effective value depends on the amount of content.
_effectiveNeutralScrollPosition = element.scrollTop.toInt();
semanticsObject
..verticalContainerAdjustment =
_effectiveNeutralScrollPosition.toDouble()
..horizontalContainerAdjustment = 0.0;
} else {
// Place the _scrollOverflowElement at the end of the content and
// make sure that when we neutralize the scrolling position,
// it doesn't scroll into the visible area.
final int horizontalOffset = rect.width.ceil() + canonicalNeutralScrollPosition;
_scrollOverflowElement.style
..transform = 'translate(${horizontalOffset}px,0px)'
..width = '${canonicalNeutralScrollPosition}px'
..height = '${rect.height.round()}px';
element.scrollLeft = canonicalNeutralScrollPosition.toDouble();
// Read back because the effective value depends on the amount of content.
_effectiveNeutralScrollPosition = element.scrollLeft.toInt();
semanticsObject
..verticalContainerAdjustment = 0.0
..horizontalContainerAdjustment =
_effectiveNeutralScrollPosition.toDouble();
}
}
void _gestureModeDidChange() {
switch (EngineSemantics.instance.gestureMode) {
case GestureMode.browserGestures:
// overflow:scroll will cause the browser report "scroll" events when
// the accessibility focus shifts outside the visible bounds.
//
// Note that on Android overflow:hidden also works. However, we prefer
// "scroll" because it works both on Android and iOS.
if (semanticsObject.isVerticalScrollContainer) {
element.style.overflowY = 'scroll';
} else {
assert(semanticsObject.isHorizontalScrollContainer);
element.style.overflowX = 'scroll';
}
case GestureMode.pointerEvents:
// We use "hidden" instead of "scroll" so that the browser does
// not "steal" pointer events. Flutter gesture recognizers need
// all pointer events in order to recognize gestures correctly.
if (semanticsObject.isVerticalScrollContainer) {
element.style.overflowY = 'hidden';
} else {
assert(semanticsObject.isHorizontalScrollContainer);
element.style.overflowX = 'hidden';
}
}
}
@override
void dispose() {
super.dispose();
final DomCSSStyleDeclaration style = element.style;
assert(_gestureModeListener != null);
style.removeProperty('overflowY');
style.removeProperty('overflowX');
style.removeProperty('touch-action');
if (_scrollListener != null) {
removeEventListener('scroll', _scrollListener);
_scrollListener = null;
}
if (_gestureModeListener != null) {
EngineSemantics.instance.removeGestureModeListener(_gestureModeListener!);
_gestureModeListener = null;
}
}
@override
bool focusAsRouteDefault() => focusable?.focusAsRouteDefault() ?? false;
}
| engine/lib/web_ui/lib/src/engine/semantics/scrollable.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/semantics/scrollable.dart",
"repo_id": "engine",
"token_count": 3409
} | 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.
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
import 'package:ui/ui.dart' as ui;
class SkwasmImageFilter extends SkwasmObjectWrapper<RawImageFilter> implements SceneImageFilter {
SkwasmImageFilter._(ImageFilterHandle handle) : super(handle, _registry);
factory SkwasmImageFilter.blur({
double sigmaX = 0.0,
double sigmaY = 0.0,
ui.TileMode tileMode = ui.TileMode.clamp,
}) => SkwasmImageFilter._(imageFilterCreateBlur(sigmaX, sigmaY, tileMode.index));
factory SkwasmImageFilter.dilate({
double radiusX = 0.0,
double radiusY = 0.0,
}) => SkwasmImageFilter._(imageFilterCreateDilate(radiusX, radiusY));
factory SkwasmImageFilter.erode({
double radiusX = 0.0,
double radiusY = 0.0,
}) => SkwasmImageFilter._(imageFilterCreateErode(radiusX, radiusY));
factory SkwasmImageFilter.matrix(
Float64List matrix4, {
ui.FilterQuality filterQuality = ui.FilterQuality.low
}) => withStackScope((StackScope scope) => SkwasmImageFilter._(imageFilterCreateMatrix(
scope.convertMatrix4toSkMatrix(matrix4),
filterQuality.index
)));
factory SkwasmImageFilter.fromColorFilter(SkwasmColorFilter filter) =>
SkwasmImageFilter._(imageFilterCreateFromColorFilter(filter.handle));
factory SkwasmImageFilter.fromUiFilter(ui.ImageFilter filter) {
if (filter is ui.ColorFilter) {
final SkwasmColorFilter colorFilter =
SkwasmColorFilter.fromEngineColorFilter(filter as EngineColorFilter);
final SkwasmImageFilter outputFilter = SkwasmImageFilter.fromColorFilter(colorFilter);
colorFilter.dispose();
return outputFilter;
} else {
return filter as SkwasmImageFilter;
}
}
factory SkwasmImageFilter.compose(
ui.ImageFilter outer,
ui.ImageFilter inner,
) {
final SkwasmImageFilter nativeOuter = SkwasmImageFilter.fromUiFilter(outer);
final SkwasmImageFilter nativeInner = SkwasmImageFilter.fromUiFilter(inner);
return SkwasmImageFilter._(imageFilterCompose(nativeOuter.handle, nativeInner.handle));
}
static final SkwasmFinalizationRegistry<RawImageFilter> _registry =
SkwasmFinalizationRegistry<RawImageFilter>(imageFilterDispose);
@override
ui.Rect filterBounds(ui.Rect inputBounds) => withStackScope((StackScope scope) {
final RawIRect rawRect = scope.convertIRectToNative(inputBounds);
imageFilterGetFilterBounds(handle, rawRect);
return scope.convertIRectFromNative(rawRect);
});
}
class SkwasmColorFilter extends SkwasmObjectWrapper<RawColorFilter> {
SkwasmColorFilter._(ColorFilterHandle handle) : super(handle, _registry);
factory SkwasmColorFilter.fromEngineColorFilter(EngineColorFilter colorFilter) =>
switch (colorFilter.type) {
ColorFilterType.mode => SkwasmColorFilter._(colorFilterCreateMode(
colorFilter.color!.value,
colorFilter.blendMode!.index,
)),
ColorFilterType.linearToSrgbGamma => SkwasmColorFilter._(colorFilterCreateLinearToSRGBGamma()),
ColorFilterType.srgbToLinearGamma => SkwasmColorFilter._(colorFilterCreateSRGBToLinearGamma()),
ColorFilterType.matrix => withStackScope((StackScope scope) {
final Pointer<Float> nativeMatrix = scope.convertDoublesToNative(colorFilter.matrix!);
return SkwasmColorFilter._(colorFilterCreateMatrix(nativeMatrix));
}),
};
factory SkwasmColorFilter.composed(
SkwasmColorFilter outer,
SkwasmColorFilter inner,
) => SkwasmColorFilter._(colorFilterCompose(outer.handle, inner.handle));
static final SkwasmFinalizationRegistry<RawColorFilter> _registry =
SkwasmFinalizationRegistry<RawColorFilter>(colorFilterDispose);
}
class SkwasmMaskFilter extends SkwasmObjectWrapper<RawMaskFilter> {
SkwasmMaskFilter._(MaskFilterHandle handle) : super(handle, _registry);
factory SkwasmMaskFilter.fromUiMaskFilter(ui.MaskFilter maskFilter) =>
SkwasmMaskFilter._(maskFilterCreateBlur(
maskFilter.webOnlyBlurStyle.index,
maskFilter.webOnlySigma
));
static final SkwasmFinalizationRegistry<RawMaskFilter> _registry =
SkwasmFinalizationRegistry<RawMaskFilter>(maskFilterDispose);
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/filters.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/filters.dart",
"repo_id": "engine",
"token_count": 1500
} | 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.
@DefaultAsset('skwasm')
library skwasm_impl;
import 'dart:ffi';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
final class RawPath extends Opaque {}
typedef PathHandle = Pointer<RawPath>;
@Native<PathHandle Function()>(symbol: 'path_create', isLeaf: true)
external PathHandle pathCreate();
@Native<Void Function(PathHandle)>(symbol: 'path_dispose', isLeaf: true)
external void pathDispose(PathHandle path);
@Native<PathHandle Function(PathHandle)>(symbol: 'path_copy', isLeaf: true)
external PathHandle pathCopy(PathHandle path);
@Native<Void Function(PathHandle, Int)>(symbol: 'path_setFillType', isLeaf: true)
external void pathSetFillType(PathHandle path, int fillType);
@Native<Int Function(PathHandle)>(symbol: 'path_getFillType', isLeaf: true)
external int pathGetFillType(PathHandle path);
@Native<Void Function(PathHandle, Float, Float)>(symbol: 'path_moveTo', isLeaf: true)
external void pathMoveTo(PathHandle path, double x, double y);
@Native<Void Function(PathHandle, Float, Float)>(symbol: 'path_relativeMoveTo', isLeaf: true)
external void pathRelativeMoveTo(PathHandle path, double x, double y);
@Native<Void Function(PathHandle, Float, Float)>(symbol: 'path_lineTo', isLeaf: true)
external void pathLineTo(PathHandle path, double x, double y);
@Native<Void Function(PathHandle, Float, Float)>(
symbol: 'path_relativeLineTo',
isLeaf: true)
external void pathRelativeLineTo(PathHandle path, double x, double y);
@Native<Void Function(PathHandle, Float, Float, Float, Float)>(
symbol: 'path_quadraticBezierTo',
isLeaf: true)
external void pathQuadraticBezierTo(
PathHandle path, double x1, double y1, double x2, double y2);
@Native<Void Function(PathHandle, Float, Float, Float, Float)>(
symbol: 'path_relativeQuadraticBezierTo',
isLeaf: true)
external void pathRelativeQuadraticBezierTo(
PathHandle path, double x1, double y1, double x2, double y2);
@Native<Void Function(PathHandle, Float, Float, Float, Float, Float, Float)>(
symbol: 'path_cubicTo',
isLeaf: true)
external void pathCubicTo(
PathHandle path,
double x1,
double y1,
double x2,
double y2,
double x3,
double y3
);
@Native<Void Function(PathHandle, Float, Float, Float, Float, Float, Float)>(
symbol: 'path_relativeCubicTo',
isLeaf: true)
external void pathRelativeCubicTo(
PathHandle path,
double x1,
double y1,
double x2,
double y2,
double x3,
double y3
);
@Native<Void Function(PathHandle, Float, Float, Float, Float, Float)>(
symbol: 'path_conicTo',
isLeaf: true)
external void pathConicTo(
PathHandle path,
double x1,
double y1,
double x2,
double y2,
double w
);
@Native<Void Function(PathHandle, Float, Float, Float, Float, Float)>(
symbol: 'path_relativeConicTo',
isLeaf: true)
external void pathRelativeConicTo(
PathHandle path,
double x1,
double y1,
double x2,
double y2,
double w
);
@Native<Void Function(PathHandle, RawRect, Float, Float, Bool)>(
symbol: 'path_arcToOval',
isLeaf: true)
external void pathArcToOval(
PathHandle path,
RawRect rect,
double startAngle,
double sweepAngle,
bool forceMoveto
);
@Native<Void Function(PathHandle, Float, Float, Float, Int, Int, Float, Float)>(
symbol: 'path_arcToRotated',
isLeaf: true)
external void pathArcToRotated(
PathHandle path,
double rx,
double ry,
double xAxisRotate,
int arcSize,
int pathDirection,
double x,
double y
);
@Native<Void Function(PathHandle, Float, Float, Float, Int, Int, Float, Float)>(
symbol: 'path_relativeArcToRotated',
isLeaf: true)
external void pathRelativeArcToRotated(
PathHandle path,
double rx,
double ry,
double xAxisRotate,
int arcSize,
int pathDirection,
double x,
double y
);
@Native<Void Function(PathHandle, RawRect)>(symbol: 'path_addRect', isLeaf: true)
external void pathAddRect(PathHandle path, RawRect oval);
@Native<Void Function(PathHandle, RawRect)>(symbol: 'path_addOval', isLeaf: true)
external void pathAddOval(PathHandle path, RawRect oval);
@Native<Void Function(PathHandle, RawRect, Float, Float)>(
symbol: 'path_addArc',
isLeaf: true)
external void pathAddArc(
PathHandle path,
RawRect ovalRect,
double startAngleDegrees,
double sweepAngleDegrees
);
@Native<Void Function(PathHandle, RawPointArray, Int, Bool)>(
symbol: 'path_addPolygon',
isLeaf: true)
external void pathAddPolygon(
PathHandle path,
RawPointArray points,
int pointCount,
bool close
);
@Native<Void Function(PathHandle, RawRRect)>(symbol: 'path_addRRect', isLeaf: true)
external void pathAddRRect(PathHandle path, RawRRect rrectValues);
@Native<Void Function(PathHandle, PathHandle, RawMatrix33, Bool)>(
symbol: 'path_addPath',
isLeaf: true)
external void pathAddPath(
PathHandle path,
PathHandle other,
RawMatrix33 matrix33,
bool extendPath
);
@Native<Void Function(PathHandle)>(symbol: 'path_close', isLeaf: true)
external void pathClose(PathHandle path);
@Native<Void Function(PathHandle)>(symbol: 'path_reset', isLeaf: true)
external void pathReset(PathHandle path);
@Native<Bool Function(PathHandle, Float, Float)>(symbol: 'path_contains', isLeaf: true)
external bool pathContains(PathHandle path, double x, double y);
@Native<Void Function(PathHandle, RawMatrix33)>(symbol: 'path_transform', isLeaf: true)
external void pathTransform(PathHandle path, RawMatrix33 matrix33);
@Native<Void Function(PathHandle, RawRect)>(symbol: 'path_getBounds', isLeaf: true)
external void pathGetBounds(PathHandle path, RawRect outRect);
@Native<PathHandle Function(Int, PathHandle, PathHandle)>(
symbol: 'path_combine',
isLeaf: true)
external PathHandle pathCombine(int operation, PathHandle path1, PathHandle path2);
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_path.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_path.dart",
"repo_id": "engine",
"token_count": 2037
} | 257 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
import 'package:ui/ui.dart' as ui;
// A shared interface for shaders for which you can acquire a native handle
abstract class SkwasmShader implements ui.Shader {
ShaderHandle get handle;
}
// An implementation that handles the storage, disposal, and finalization of
// a native shader handle.
class SkwasmNativeShader extends SkwasmObjectWrapper<RawShader> implements SkwasmShader {
SkwasmNativeShader(ShaderHandle handle) : super(handle, _registry);
static final SkwasmFinalizationRegistry<RawShader> _registry =
SkwasmFinalizationRegistry<RawShader>(shaderDispose);
}
class SkwasmGradient extends SkwasmNativeShader implements ui.Gradient {
factory SkwasmGradient.linear({
required ui.Offset from,
required ui.Offset to,
required List<ui.Color> colors,
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4,
}) => withStackScope((StackScope scope) {
final RawPointArray endPoints =
scope.convertPointArrayToNative(<ui.Offset>[from, to]);
final RawColorArray nativeColors = scope.convertColorArrayToNative(colors);
final Pointer<Float> stops = colorStops != null
? scope.convertDoublesToNative(colorStops)
: nullptr;
final Pointer<Float> matrix = matrix4 != null
? scope.convertMatrix4toSkMatrix(matrix4)
: nullptr;
final ShaderHandle handle = shaderCreateLinearGradient(
endPoints,
nativeColors,
stops,
colors.length,
tileMode.index,
matrix
);
return SkwasmGradient._(handle);
});
factory SkwasmGradient.radial({
required ui.Offset center,
required double radius,
required List<ui.Color> colors,
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4,
}) => withStackScope((StackScope scope) {
final RawColorArray rawColors = scope.convertColorArrayToNative(colors);
final Pointer<Float> rawStops = colorStops != null
? scope.convertDoublesToNative(colorStops)
: nullptr;
final Pointer<Float> matrix = matrix4 != null
? scope.convertMatrix4toSkMatrix(matrix4)
: nullptr;
final ShaderHandle handle = shaderCreateRadialGradient(
center.dx,
center.dy,
radius,
rawColors,
rawStops,
colors.length,
tileMode.index,
matrix,
);
return SkwasmGradient._(handle);
});
factory SkwasmGradient.conical({
required ui.Offset focal,
required double focalRadius,
required ui.Offset center,
required double centerRadius,
required List<ui.Color> colors,
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4,
}) => withStackScope((StackScope scope) {
final RawPointArray endPoints =
scope.convertPointArrayToNative(<ui.Offset>[focal, center]);
final RawColorArray rawColors = scope.convertColorArrayToNative(colors);
final Pointer<Float> rawStops = colorStops != null
? scope.convertDoublesToNative(colorStops)
: nullptr;
final Pointer<Float> matrix = matrix4 != null
? scope.convertMatrix4toSkMatrix(matrix4)
: nullptr;
final ShaderHandle handle = shaderCreateConicalGradient(
endPoints,
focalRadius,
centerRadius,
rawColors,
rawStops,
colors.length,
tileMode.index,
matrix
);
return SkwasmGradient._(handle);
});
factory SkwasmGradient.sweep({
required ui.Offset center,
required List<ui.Color> colors,
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
required double startAngle,
required double endAngle,
Float32List? matrix4,
}) => withStackScope((StackScope scope) {
final RawColorArray rawColors = scope.convertColorArrayToNative(colors);
final Pointer<Float> rawStops = colorStops != null
? scope.convertDoublesToNative(colorStops)
: nullptr;
final Pointer<Float> matrix = matrix4 != null
? scope.convertMatrix4toSkMatrix(matrix4)
: nullptr;
final ShaderHandle handle = shaderCreateSweepGradient(
center.dx,
center.dy,
rawColors,
rawStops,
colors.length,
tileMode.index,
ui.toDegrees(startAngle),
ui.toDegrees(endAngle),
matrix
);
return SkwasmGradient._(handle);
});
SkwasmGradient._(super.handle);
@override
String toString() => 'Gradient()';
}
class SkwasmImageShader extends SkwasmNativeShader implements ui.ImageShader {
SkwasmImageShader._(super.handle);
factory SkwasmImageShader.imageShader(
SkwasmImage image,
ui.TileMode tmx,
ui.TileMode tmy,
Float64List? matrix4,
ui.FilterQuality? filterQuality,
) {
if (matrix4 != null) {
return withStackScope((StackScope scope) {
final RawMatrix33 localMatrix = scope.convertMatrix4toSkMatrix(matrix4);
return SkwasmImageShader._(shaderCreateFromImage(
image.handle,
tmx.index,
tmy.index,
(filterQuality ?? ui.FilterQuality.medium).index,
localMatrix,
));
});
} else {
return SkwasmImageShader._(shaderCreateFromImage(
image.handle,
tmx.index,
tmy.index,
(filterQuality ?? ui.FilterQuality.medium).index,
nullptr,
));
}
}
}
class SkwasmFragmentProgram extends SkwasmObjectWrapper<RawRuntimeEffect> implements ui.FragmentProgram {
SkwasmFragmentProgram._(
this.name,
RuntimeEffectHandle handle,
this.floatUniformCount,
this.childShaderCount,
) : super(handle, _registry);
factory SkwasmFragmentProgram.fromBytes(String name, Uint8List bytes) {
final ShaderData shaderData = ShaderData.fromBytes(bytes);
// TODO(jacksongardner): Can we avoid this copy?
final List<int> sourceData = utf8.encode(shaderData.source);
final SkStringHandle sourceString = skStringAllocate(sourceData.length);
final Pointer<Int8> sourceBuffer = skStringGetData(sourceString);
int i = 0;
for (final int byte in sourceData) {
sourceBuffer[i] = byte;
i++;
}
final RuntimeEffectHandle handle = runtimeEffectCreate(sourceString);
skStringFree(sourceString);
return SkwasmFragmentProgram._(
name,
handle,
shaderData.floatCount,
shaderData.textureCount
);
}
static final SkwasmFinalizationRegistry<RawRuntimeEffect> _registry =
SkwasmFinalizationRegistry<RawRuntimeEffect>(runtimeEffectDispose);
final String name;
final int floatUniformCount;
final int childShaderCount;
@override
ui.FragmentShader fragmentShader() => SkwasmFragmentShader(this);
int get uniformSize => runtimeEffectGetUniformSize(handle);
}
class SkwasmShaderData extends SkwasmObjectWrapper<RawSkData> {
SkwasmShaderData(int size) : super(skDataCreate(size), _registry);
static final SkwasmFinalizationRegistry<RawSkData> _registry =
SkwasmFinalizationRegistry<RawSkData>(skDataDispose);
}
// This class does not inherit from SkwasmNativeShader, as its handle might
// change over time if the uniforms or image shaders are changed. Instead this
// wraps a SkwasmNativeShader that it creates and destroys on demand. It does
// implement SkwasmShader though, in order to provide the handle for the
// underlying shader object.
class SkwasmFragmentShader implements SkwasmShader, ui.FragmentShader {
SkwasmFragmentShader(SkwasmFragmentProgram program) :
_program = program,
_uniformData = SkwasmShaderData(program.uniformSize),
_floatUniformCount = program.floatUniformCount,
_childShaders = List<SkwasmShader?>.filled(program.childShaderCount, null);
@override
ShaderHandle get handle {
if (_nativeShader == null) {
final ShaderHandle newHandle = withStackScope((StackScope s) {
Pointer<ShaderHandle> childShaders = nullptr;
if (_childShaders.isNotEmpty) {
childShaders = s.allocPointerArray(_childShaders.length)
.cast<ShaderHandle>();
for (int i = 0; i < _childShaders.length; i++) {
final SkwasmShader? child = _childShaders[i];
childShaders[i] = child != null ? child.handle : nullptr;
}
}
return shaderCreateRuntimeEffectShader(
_program.handle,
_uniformData.handle,
childShaders,
_childShaders.length,
);
});
_nativeShader = SkwasmNativeShader(newHandle);
}
return _nativeShader!.handle;
}
SkwasmShader? _nativeShader;
final SkwasmFragmentProgram _program;
final SkwasmShaderData _uniformData;
bool _isDisposed = false;
final int _floatUniformCount;
final List<SkwasmShader?> _childShaders;
@override
void dispose() {
assert(!_isDisposed);
_nativeShader?.dispose();
_uniformData.dispose();
_isDisposed = true;
}
@override
bool get debugDisposed => _isDisposed;
@override
void setFloat(int index, double value) {
if (_nativeShader != null) {
// Invalidate the previous shader so that it is recreated with the new
// uniform data.
_nativeShader!.dispose();
_nativeShader = null;
}
final Pointer<Float> dataPointer = skDataGetPointer(_uniformData.handle).cast<Float>();
dataPointer[index] = value;
}
@override
void setImageSampler(int index, ui.Image image) {
if (_nativeShader != null) {
// Invalidate the previous shader so that it is recreated with the new
// child shaders.
_nativeShader!.dispose();
_nativeShader = null;
}
final SkwasmImageShader shader = SkwasmImageShader.imageShader(
image as SkwasmImage,
ui.TileMode.clamp,
ui.TileMode.clamp,
null,
ui.FilterQuality.none,
);
final SkwasmShader? oldShader = _childShaders[index];
_childShaders[index] = shader;
oldShader?.dispose();
final Pointer<Float> dataPointer = skDataGetPointer(_uniformData.handle).cast<Float>();
dataPointer[_floatUniformCount + index * 2] = image.width.toDouble();
dataPointer[_floatUniformCount + index * 2 + 1] = image.height.toDouble();
}
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/shaders.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/shaders.dart",
"repo_id": "engine",
"token_count": 3978
} | 258 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../html/bitmap_canvas.dart';
import '../html/painting.dart';
import 'canvas_paragraph.dart';
import 'layout_fragmenter.dart';
import 'paragraph.dart';
/// Responsible for painting a [CanvasParagraph] on a [BitmapCanvas].
class TextPaintService {
TextPaintService(this.paragraph);
final CanvasParagraph paragraph;
void paint(BitmapCanvas canvas, ui.Offset offset) {
// Loop through all the lines, for each line, loop through all fragments and
// paint them. The fragment objects have enough information to be painted
// individually.
final List<ParagraphLine> lines = paragraph.lines;
for (final ParagraphLine line in lines) {
for (final LayoutFragment fragment in line.fragments) {
_paintBackground(canvas, offset, fragment);
_paintText(canvas, offset, line, fragment);
}
}
}
void _paintBackground(
BitmapCanvas canvas,
ui.Offset offset,
LayoutFragment fragment,
) {
if (fragment.isPlaceholder) {
return;
}
// Paint the background of the box, if the span has a background.
final SurfacePaint? background = fragment.style.background as SurfacePaint?;
if (background != null) {
final ui.Rect rect = fragment.toPaintingTextBox().toRect();
if (!rect.isEmpty) {
canvas.drawRect(rect.shift(offset), background.paintData);
}
}
}
void _paintText(
BitmapCanvas canvas,
ui.Offset offset,
ParagraphLine line,
LayoutFragment fragment,
) {
// There's no text to paint in placeholder spans.
if (fragment.isPlaceholder) {
return;
}
// Don't paint the text for space-only boxes. This is just an
// optimization, it doesn't have any effect on the output.
if (fragment.isSpaceOnly) {
return;
}
_prepareCanvasForFragment(canvas, fragment);
final double fragmentX = fragment.textDirection! == ui.TextDirection.ltr
? fragment.left
: fragment.right;
final double x = offset.dx + line.left + fragmentX;
final double y = offset.dy + line.baseline;
final EngineTextStyle style = fragment.style;
final String text = fragment.getText(paragraph);
canvas.drawText(text, x, y, style: style.foreground?.style, shadows: style.shadows);
canvas.tearDownPaint();
}
void _prepareCanvasForFragment(BitmapCanvas canvas, LayoutFragment fragment) {
final EngineTextStyle style = fragment.style;
final SurfacePaint? paint;
final ui.Paint? foreground = style.foreground;
if (foreground != null) {
paint = foreground as SurfacePaint;
} else {
paint = ui.Paint() as SurfacePaint;
if (style.color != null) {
paint.color = style.color!;
}
}
canvas.setCssFont(style.cssFontString, fragment.textDirection!);
canvas.setUpPaint(paint.paintData, null);
}
}
| engine/lib/web_ui/lib/src/engine/text/paint_service.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/text/paint_service.dart",
"repo_id": "engine",
"token_count": 1088
} | 259 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:ui/src/engine/display.dart';
import 'package:ui/src/engine/dom.dart';
import 'package:ui/src/engine/window.dart';
import 'package:ui/ui.dart' as ui show Size;
import 'dimensions_provider.dart';
/// This class provides observable, real-time dimensions of a host element.
///
/// This class needs a `Stream` of `devicePixelRatio` changes, like the one
/// provided by [DisplayDprStream], because html resize observers do not report
/// DPR changes.
///
/// All the measurements returned from this class are potentially *expensive*,
/// and should be cached as needed. Every call to every method on this class
/// WILL perform actual DOM measurements.
///
/// This broadcasts `null` size events, to match the implementation of the
/// FullPageDimensionsProvider, but it could broadcast the size coming from the
/// DomResizeObserverEntry. Further changes in the engine are required for this
/// to be effective.
class CustomElementDimensionsProvider extends DimensionsProvider {
/// Creates a [CustomElementDimensionsProvider] from a [_hostElement].
CustomElementDimensionsProvider(this._hostElement, {
Stream<double>? onDprChange,
}) {
// Send a resize event when the page DPR changes.
_dprChangeStreamSubscription = onDprChange?.listen((_) {
_broadcastSize(null);
});
// Hook up a resize observer on the hostElement (if supported!).
_hostElementResizeObserver = createDomResizeObserver((
List<DomResizeObserverEntry> entries,
DomResizeObserver _,
) {
for (final DomResizeObserverEntry _ in entries) {
_broadcastSize(null);
}
});
assert(() {
if (_hostElementResizeObserver == null) {
domWindow.console.warn('ResizeObserver API not supported. '
'Flutter will not resize with its hostElement.');
}
return true;
}());
_hostElementResizeObserver?.observe(_hostElement);
}
// The host element that will be used to retrieve (and observe) app size measurements.
final DomElement _hostElement;
// Handle resize events
late DomResizeObserver? _hostElementResizeObserver;
late StreamSubscription<double>? _dprChangeStreamSubscription;
final StreamController<ui.Size?> _onResizeStreamController =
StreamController<ui.Size?>.broadcast();
// Broadcasts the last seen `Size`.
void _broadcastSize(ui.Size? size) {
_onResizeStreamController.add(size);
}
@override
void close() {
super.close();
_hostElementResizeObserver?.disconnect();
// ignore:unawaited_futures
_dprChangeStreamSubscription?.cancel();
// ignore:unawaited_futures
_onResizeStreamController.close();
}
@override
Stream<ui.Size?> get onResize => _onResizeStreamController.stream;
@override
ui.Size computePhysicalSize() {
final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio;
return ui.Size(
_hostElement.clientWidth * devicePixelRatio,
_hostElement.clientHeight * devicePixelRatio,
);
}
@override
ViewPadding computeKeyboardInsets(
double physicalHeight,
bool isEditingOnMobile,
) {
return const ViewPadding(
top: 0,
right: 0,
bottom: 0,
left: 0,
);
}
}
| engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/custom_element_dimensions_provider.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/custom_element_dimensions_provider.dart",
"repo_id": "engine",
"token_count": 1114
} | 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.
// This library defines the web-specific additions that go along with dart:ui
//
// The web_sdk/sdk_rewriter.dart uses this directive.
// ignore: unnecessary_library_directive
library ui_web;
export 'ui_web/asset_manager.dart';
export 'ui_web/benchmarks.dart';
export 'ui_web/flutter_views_proxy.dart';
export 'ui_web/images.dart';
export 'ui_web/initialization.dart';
export 'ui_web/navigation/platform_location.dart';
export 'ui_web/navigation/url_strategy.dart';
export 'ui_web/platform_view_registry.dart';
export 'ui_web/plugins.dart';
export 'ui_web/testing.dart';
| engine/lib/web_ui/lib/ui_web/src/ui_web.dart/0 | {
"file_path": "engine/lib/web_ui/lib/ui_web/src/ui_web.dart",
"repo_id": "engine",
"token_count": 245
} | 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 "export.h"
#include "third_party/skia/include/core/SkData.h"
SKWASM_EXPORT SkData* skData_create(size_t size) {
return SkData::MakeUninitialized(size).release();
}
SKWASM_EXPORT void* skData_getPointer(SkData* data) {
return data->writable_data();
}
SKWASM_EXPORT const void* skData_getConstPointer(SkData* data) {
return data->data();
}
SKWASM_EXPORT size_t skData_getSize(SkData* data) {
return data->size();
}
SKWASM_EXPORT void skData_dispose(SkData* data) {
return data->unref();
}
| engine/lib/web_ui/skwasm/data.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/data.cpp",
"repo_id": "engine",
"token_count": 246
} | 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.
#include "third_party/skia/modules/skparagraph/include/Paragraph.h"
#include "../export.h"
#include "DartTypes.h"
#include "TextStyle.h"
#include "include/core/SkScalar.h"
using namespace skia::textlayout;
SKWASM_EXPORT void paragraph_dispose(Paragraph* paragraph) {
delete paragraph;
}
SKWASM_EXPORT SkScalar paragraph_getWidth(Paragraph* paragraph) {
return paragraph->getMaxWidth();
}
SKWASM_EXPORT SkScalar paragraph_getHeight(Paragraph* paragraph) {
return paragraph->getHeight();
}
SKWASM_EXPORT SkScalar paragraph_getLongestLine(Paragraph* paragraph) {
return paragraph->getLongestLine();
}
SKWASM_EXPORT SkScalar paragraph_getMinIntrinsicWidth(Paragraph* paragraph) {
return paragraph->getMinIntrinsicWidth();
}
SKWASM_EXPORT SkScalar paragraph_getMaxIntrinsicWidth(Paragraph* paragraph) {
return paragraph->getMaxIntrinsicWidth();
}
SKWASM_EXPORT SkScalar paragraph_getAlphabeticBaseline(Paragraph* paragraph) {
return paragraph->getAlphabeticBaseline();
}
SKWASM_EXPORT SkScalar paragraph_getIdeographicBaseline(Paragraph* paragraph) {
return paragraph->getIdeographicBaseline();
}
SKWASM_EXPORT bool paragraph_getDidExceedMaxLines(Paragraph* paragraph) {
return paragraph->didExceedMaxLines();
}
SKWASM_EXPORT void paragraph_layout(Paragraph* paragraph, SkScalar width) {
paragraph->layout(width);
}
SKWASM_EXPORT int32_t paragraph_getPositionForOffset(Paragraph* paragraph,
SkScalar offsetX,
SkScalar offsetY,
Affinity* outAffinity) {
auto position = paragraph->getGlyphPositionAtCoordinate(offsetX, offsetY);
if (outAffinity) {
*outAffinity = position.affinity;
}
return position.position;
}
SKWASM_EXPORT bool paragraph_getClosestGlyphInfoAtCoordinate(
Paragraph* paragraph,
SkScalar offsetX,
SkScalar offsetY,
// Out parameters:
SkRect* graphemeLayoutBounds, // 1 SkRect
size_t* graphemeCodeUnitRange, // 2 size_ts: [start, end]
bool* booleanFlags) { // 1 boolean: isLTR
Paragraph::GlyphInfo glyphInfo;
if (!paragraph->getClosestUTF16GlyphInfoAt(offsetX, offsetY, &glyphInfo)) {
return false;
}
// This is more verbose than memcpying the whole struct but ideally we don't
// want to depend on the exact memory layout of the struct.
std::memcpy(graphemeLayoutBounds, &glyphInfo.fGraphemeLayoutBounds,
sizeof(SkRect));
std::memcpy(graphemeCodeUnitRange, &glyphInfo.fGraphemeClusterTextRange,
2 * sizeof(size_t));
booleanFlags[0] =
glyphInfo.fDirection == skia::textlayout::TextDirection::kLtr;
return true;
}
SKWASM_EXPORT bool paragraph_getGlyphInfoAt(
Paragraph* paragraph,
size_t index,
// Out parameters:
SkRect* graphemeLayoutBounds, // 1 SkRect
size_t* graphemeCodeUnitRange, // 2 size_ts: [start, end]
bool* booleanFlags) { // 1 boolean: isLTR
Paragraph::GlyphInfo glyphInfo;
if (!paragraph->getGlyphInfoAtUTF16Offset(index, &glyphInfo)) {
return false;
}
std::memcpy(graphemeLayoutBounds, &glyphInfo.fGraphemeLayoutBounds,
sizeof(SkRect));
std::memcpy(graphemeCodeUnitRange, &glyphInfo.fGraphemeClusterTextRange,
2 * sizeof(size_t));
booleanFlags[0] =
glyphInfo.fDirection == skia::textlayout::TextDirection::kLtr;
return true;
}
SKWASM_EXPORT void paragraph_getWordBoundary(
Paragraph* paragraph,
unsigned int position,
int32_t* outRange // Two `int32_t`s, start and end
) {
auto range = paragraph->getWordBoundary(position);
outRange[0] = range.start;
outRange[1] = range.end;
}
SKWASM_EXPORT size_t paragraph_getLineCount(Paragraph* paragraph) {
return paragraph->lineNumber();
}
SKWASM_EXPORT int paragraph_getLineNumberAt(Paragraph* paragraph,
size_t characterIndex) {
return paragraph->getLineNumberAtUTF16Offset(characterIndex);
}
SKWASM_EXPORT LineMetrics* paragraph_getLineMetricsAtIndex(Paragraph* paragraph,
size_t lineNumber) {
auto metrics = new LineMetrics();
if (paragraph->getLineMetricsAt(lineNumber, metrics)) {
return metrics;
} else {
delete metrics;
return nullptr;
}
}
struct TextBoxList {
std::vector<TextBox> boxes;
};
SKWASM_EXPORT void textBoxList_dispose(TextBoxList* list) {
delete list;
}
SKWASM_EXPORT size_t textBoxList_getLength(TextBoxList* list) {
return list->boxes.size();
}
SKWASM_EXPORT TextDirection textBoxList_getBoxAtIndex(TextBoxList* list,
size_t index,
SkRect* outRect) {
const auto& box = list->boxes[index];
*outRect = box.rect;
return box.direction;
}
SKWASM_EXPORT TextBoxList* paragraph_getBoxesForRange(
Paragraph* paragraph,
int start,
int end,
RectHeightStyle heightStyle,
RectWidthStyle widthStyle) {
return new TextBoxList{
paragraph->getRectsForRange(start, end, heightStyle, widthStyle)};
}
SKWASM_EXPORT TextBoxList* paragraph_getBoxesForPlaceholders(
Paragraph* paragraph) {
return new TextBoxList{paragraph->getRectsForPlaceholders()};
}
// Returns a list of the code points that were unable to be rendered with the
// selected fonts. The list is deduplicated, so each code point in the output
// is unique.
// If `nullptr` is passed in for `outCodePoints`, we simply return the count
// of the code points.
// Note: This must be called after the paragraph has been laid out at least
// once in order to get valid data.
SKWASM_EXPORT int paragraph_getUnresolvedCodePoints(Paragraph* paragraph,
SkUnichar* outCodePoints,
int outLength) {
if (!outCodePoints) {
return paragraph->unresolvedCodepoints().size();
}
int outIndex = 0;
for (SkUnichar character : paragraph->unresolvedCodepoints()) {
if (outIndex < outLength) {
outCodePoints[outIndex] = character;
outIndex++;
} else {
break;
}
}
return outIndex;
}
| engine/lib/web_ui/skwasm/text/paragraph.cpp/0 | {
"file_path": "engine/lib/web_ui/skwasm/text/paragraph.cpp",
"repo_id": "engine",
"token_count": 2604
} | 263 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'common.dart';
import 'test_data.dart';
EngineFlutterWindow get implicitView =>
EnginePlatformDispatcher.instance.implicitView!;
DomElement get platformViewsHost => implicitView.dom.platformViewsHost;
DomElement get sceneHost => implicitView.dom.sceneHost;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$HtmlViewEmbedder', () {
setUpCanvasKitTest(withImplicitView: true);
setUp(() {
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(1);
});
tearDown(() {
PlatformViewManager.instance.debugClear();
CanvasKitRenderer.instance.debugClear();
});
test('embeds interactive platform views', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
// The platform view is now split in two parts. The contents live
// as a child of the glassPane, and the slot lives in the glassPane
// shadow root. The slot is the one that has pointer events auto.
final DomElement contents = platformViewsHost.querySelector('#view-0')!;
final DomElement slot = sceneHost.querySelector('slot')!;
final DomElement contentsHost = contents.parent!;
final DomElement slotHost = slot.parent!;
expect(contents, isNotNull,
reason: 'The view from the factory is injected in the DOM.');
expect(contentsHost.tagName, equalsIgnoringCase('flt-platform-view'));
expect(slotHost.tagName, equalsIgnoringCase('flt-platform-view-slot'));
expect(slotHost.style.pointerEvents, 'auto',
reason: 'The slot reenables pointer events.');
expect(contentsHost.getAttribute('slot'), slot.getAttribute('name'),
reason: 'The contents and slot are correctly related.');
});
test('clips platform views with RRects', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.pushClipRRect(
ui.RRect.fromLTRBR(0, 0, 10, 10, const ui.Radius.circular(3)));
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
expect(
sceneHost.querySelectorAll('#sk_path_defs').single,
isNotNull,
);
expect(
sceneHost
.querySelectorAll('#sk_path_defs')
.single
.querySelectorAll('clipPath')
.single,
isNotNull,
);
expect(
sceneHost.querySelectorAll('flt-clip').single.style.clipPath,
'url("#svgClip1")',
);
expect(
sceneHost.querySelectorAll('flt-clip').single.style.width,
'100%',
);
expect(
sceneHost.querySelectorAll('flt-clip').single.style.height,
'100%',
);
});
test('correctly transforms platform views', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
final Matrix4 scaleMatrix = Matrix4.identity()
..scale(5, 5)
..translate(100, 100);
sb.pushTransform(scaleMatrix.toFloat64());
sb.pushOffset(3, 3);
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
// Transformations happen on the slot element.
final DomElement slotHost =
sceneHost.querySelector('flt-platform-view-slot')!;
expect(
slotHost.style.transform,
// We should apply the scale matrix first, then the offset matrix.
// So the translate should be 515 (5 * 100 + 5 * 3), and not
// 503 (5 * 100 + 3).
'matrix3d(5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 515, 515, 0, 1)',
);
});
test('correctly offsets platform views', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.addPlatformView(0, offset: const ui.Offset(3, 4), width: 5, height: 6);
await renderScene(sb.build());
final DomElement slotHost =
sceneHost.querySelector('flt-platform-view-slot')!;
final DomCSSStyleDeclaration style = slotHost.style;
expect(style.transform, 'matrix(1, 0, 0, 1, 3, 4)');
expect(style.width, '5px');
expect(style.height, '6px');
final DomRect slotRect = slotHost.getBoundingClientRect();
expect(slotRect.left, 3);
expect(slotRect.top, 4);
expect(slotRect.right, 8);
expect(slotRect.bottom, 10);
});
// Returns the list of CSS transforms applied to the ancestor chain of
// elements starting from `viewHost`, up until and excluding
// <flt-scene-host>.
List<String> getTransformChain(DomElement viewHost) {
final List<String> chain = <String>[];
DomElement? element = viewHost;
while (element != null &&
element.tagName.toLowerCase() != 'flt-scene-host') {
chain.add(element.style.transform);
element = element.parent;
}
return chain;
}
test('correctly offsets when clip chain length is changed', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(3, 3);
sb.pushClipRect(ui.Rect.largest);
sb.pushOffset(6, 6);
sb.addPlatformView(0, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
// Transformations happen on the slot element.
DomElement slotHost = sceneHost.querySelector('flt-platform-view-slot')!;
expect(
getTransformChain(slotHost),
<String>[
'matrix(1, 0, 0, 1, 6, 6)',
'matrix(1, 0, 0, 1, 3, 3)',
],
);
sb = LayerSceneBuilder();
sb.pushOffset(3, 3);
sb.pushClipRect(ui.Rect.largest);
sb.pushOffset(6, 6);
sb.pushClipRect(ui.Rect.largest);
sb.pushOffset(9, 9);
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
// Transformations happen on the slot element.
slotHost = sceneHost.querySelector('flt-platform-view-slot')!;
expect(
getTransformChain(slotHost),
<String>[
'matrix(1, 0, 0, 1, 9, 9)',
'matrix(1, 0, 0, 1, 6, 6)',
'matrix(1, 0, 0, 1, 3, 3)',
],
);
});
test('converts device pixels to logical pixels (no clips)', () async {
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(4);
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(1, 1);
sb.pushOffset(2, 2);
sb.pushOffset(3, 3);
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
// Transformations happen on the slot element.
final DomElement slotHost =
sceneHost.querySelector('flt-platform-view-slot')!;
expect(
getTransformChain(slotHost),
<String>['matrix(0.25, 0, 0, 0.25, 1.5, 1.5)'],
);
});
test('converts device pixels to logical pixels (with clips)', () async {
EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(4);
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(3, 3);
sb.pushClipRect(ui.Rect.largest);
sb.pushOffset(6, 6);
sb.pushClipRect(ui.Rect.largest);
sb.pushOffset(9, 9);
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
// Transformations happen on the slot element.
final DomElement slotHost =
sceneHost.querySelector('flt-platform-view-slot')!;
expect(
getTransformChain(slotHost),
<String>[
'matrix(1, 0, 0, 1, 9, 9)',
'matrix(1, 0, 0, 1, 6, 6)',
'matrix(0.25, 0, 0, 0.25, 0.75, 0.75)',
],
);
});
test('renders overlays on top of platform views', () async {
final CkPicture testPicture =
paintPicture(const ui.Rect.fromLTRB(0, 0, 10, 10), (CkCanvas canvas) {
canvas.drawCircle(const ui.Offset(5, 5), 5, CkPaint());
});
// Initialize all platform views to be used in the test.
final List<int> platformViewIds = <int>[];
for (int i = 0; i < 16; i++) {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-$i',
);
await createPlatformView(i, 'test-platform-view');
platformViewIds.add(i);
}
Future<void> renderTestScene({required int viewCount}) async {
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
for (int i = 0; i < viewCount; i++) {
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(i, width: 10, height: 10);
}
await renderScene(sb.build());
}
// Frame 1:
// Render: up to cache size platform views.
// Expect: main canvas plus platform view overlays.
await renderTestScene(viewCount: 8);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
]);
// Frame 2:
// Render: zero platform views.
// Expect: main canvas, no overlays.
await renderTestScene(viewCount: 0);
_expectSceneMatches(<_EmbeddedViewMarker>[]);
// Frame 3:
// Render: less than cache size platform views.
// Expect: overlays reused.
await renderTestScene(viewCount: 6);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
]);
// Frame 4:
// Render: more platform views than max overlay count.
// Expect: main canvas, backup overlay, maximum overlays.
await renderTestScene(viewCount: 16);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_platformView,
_platformView,
_platformView,
_platformView,
_platformView,
_platformView,
_overlay,
_platformView,
]);
// Frame 5:
// Render: zero platform views.
// Expect: main canvas, no overlays.
await renderTestScene(viewCount: 0);
_expectSceneMatches(<_EmbeddedViewMarker>[]);
// Frame 6:
// Render: deleted platform views.
// Expect: error.
for (final int id in platformViewIds) {
const StandardMethodCodec codec = StandardMethodCodec();
final Completer<void> completer = Completer<void>();
ui.PlatformDispatcher.instance.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall(
'dispose',
id,
)),
completer.complete,
);
await completer.future;
}
try {
await renderTestScene(viewCount: platformViewIds.length);
fail('Expected to throw');
} on AssertionError catch (error) {
expect(
error.toString(),
'Assertion failed: "Cannot render platform views: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15. These views have not been created, or they have been deleted."',
);
}
// Frame 7:
// Render: a platform view after error.
// Expect: success. Just checking the system is not left in a corrupted state.
await createPlatformView(0, 'test-platform-view');
await renderTestScene(viewCount: 0);
_expectSceneMatches(<_EmbeddedViewMarker>[]);
});
test('correctly reuses overlays', () async {
final CkPicture testPicture =
paintPicture(const ui.Rect.fromLTRB(0, 0, 10, 10), (CkCanvas canvas) {
canvas.drawCircle(const ui.Offset(5, 5), 5, CkPaint());
});
// Initialize all platform views to be used in the test.
final List<int> platformViewIds = <int>[];
for (int i = 0; i < 20; i++) {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-$i',
);
await createPlatformView(i, 'test-platform-view');
platformViewIds.add(i);
}
Future<void> renderTestScene(List<int> views) async {
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
for (final int view in views) {
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(view, width: 10, height: 10);
}
await renderScene(sb.build());
}
// Frame 1:
// Render: Views 1-10
// Expect: main canvas plus platform view overlays; empty cache.
await renderTestScene(<int>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_overlay,
_platformView,
]);
// Frame 2:
// Render: Views 2-11
// Expect: main canvas plus platform view overlays; empty cache.
await renderTestScene(<int>[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_overlay,
_platformView,
]);
// Frame 3:
// Render: Views 3-12
// Expect: main canvas plus platform view overlays; empty cache.
await renderTestScene(<int>[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_overlay,
_platformView,
]);
// Frame 4:
// Render: Views 3-12 again (same as last frame)
// Expect: main canvas plus platform view overlays; empty cache.
await renderTestScene(<int>[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_overlay,
_platformView,
]);
});
test('embeds and disposes of a platform view', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
]);
expect(platformViewsHost.querySelector('flt-platform-view'), isNotNull);
await disposePlatformView(0);
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[]);
expect(platformViewsHost.querySelector('flt-platform-view'), isNull);
});
test(
'does not crash when resizing the window after textures have been registered',
() async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final CkBrowserImageDecoder image = await CkBrowserImageDecoder.create(
data: kAnimatedGif,
debugSource: 'test',
);
final ui.FrameInfo frame = await image.getNextFrame();
final CkImage ckImage = frame.image as CkImage;
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.drawImage(ckImage, ui.Offset.zero, CkPaint());
final CkPicture picture = recorder.endRecording();
sb.addPicture(ui.Offset.zero, picture);
sb.addPlatformView(0, width: 10, height: 10);
implicitView.debugPhysicalSizeOverride = const ui.Size(100, 100);
implicitView.debugForceResize();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
]);
implicitView.debugPhysicalSizeOverride = const ui.Size(200, 200);
implicitView.debugForceResize();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
]);
implicitView.debugPhysicalSizeOverride = null;
implicitView.debugForceResize();
// ImageDecoder is not supported in Safari or Firefox.
}, skip: isSafari || isFirefox);
test('removes the DOM node of an unrendered platform view', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
]);
expect(platformViewsHost.querySelector('flt-platform-view'), isNotNull);
// Render a frame with a different platform view.
await createPlatformView(1, 'test-platform-view');
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPlatformView(1, width: 10, height: 10);
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
]);
expect(
platformViewsHost.querySelectorAll('flt-platform-view'),
hasLength(2),
);
// Render a frame without a platform view, but also without disposing of
// the platform view.
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[]);
// The actual contents of the platform view are kept in the dom, until
// it's actually disposed of!
expect(
platformViewsHost.querySelectorAll('flt-platform-view'),
hasLength(2),
);
});
test(
'removes old SVG clip definitions from the DOM when the view is recomposited',
() async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'test-view',
);
await createPlatformView(0, 'test-platform-view');
Future<void> renderTestScene() async {
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.pushClipRRect(
ui.RRect.fromLTRBR(0, 0, 10, 10, const ui.Radius.circular(3)));
sb.addPlatformView(0, width: 10, height: 10);
await renderScene(sb.build());
}
final DomNode skPathDefs = sceneHost.querySelector('#sk_path_defs')!;
expect(skPathDefs.childNodes, hasLength(0));
await renderTestScene();
expect(skPathDefs.childNodes, hasLength(1));
await renderTestScene();
expect(skPathDefs.childNodes, hasLength(1));
await renderTestScene();
expect(skPathDefs.childNodes, hasLength(1));
});
test('does not crash when a prerolled platform view is not composited',
() async {
ui_web.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => createDomHTMLDivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.pushClipRect(ui.Rect.zero);
sb.addPlatformView(0, width: 10, height: 10);
sb.pop();
// The below line should not throw an error.
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[]);
});
test('does not create overlays for invisible platform views', () async {
final CkPicture testPicture =
paintPicture(const ui.Rect.fromLTRB(0, 0, 10, 10), (CkCanvas canvas) {
canvas.drawCircle(const ui.Offset(5, 5), 5, CkPaint());
});
ui_web.platformViewRegistry.registerViewFactory(
'test-visible-view',
(int viewId) =>
createDomHTMLDivElement()..className = 'visible-platform-view');
ui_web.platformViewRegistry.registerViewFactory(
'test-invisible-view',
(int viewId) =>
createDomHTMLDivElement()..className = 'invisible-platform-view',
isVisible: false,
);
await createPlatformView(0, 'test-visible-view');
await createPlatformView(1, 'test-invisible-view');
await createPlatformView(2, 'test-visible-view');
await createPlatformView(3, 'test-invisible-view');
await createPlatformView(4, 'test-invisible-view');
await createPlatformView(5, 'test-invisible-view');
await createPlatformView(6, 'test-invisible-view');
expect(PlatformViewManager.instance.isInvisible(0), isFalse);
expect(PlatformViewManager.instance.isInvisible(1), isTrue);
LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
_overlay,
], reason: 'Invisible view renders, followed by an overlay.');
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(0, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_platformView,
_overlay,
], reason: 'Overlay created after a group containing a visible view.');
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(0, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(2, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_platformView,
_overlay,
_platformView,
],
reason:
'Overlays created after each group containing a visible view.');
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(0, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(2, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(3, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_platformView,
_overlay,
_platformView,
_platformView,
_overlay,
], reason: 'Invisible views grouped in with visible views.');
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(0, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(2, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(3, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(4, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_overlay,
]);
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(0, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(2, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(3, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(4, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(5, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_platformView,
_overlay,
]);
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(0, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(2, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(3, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(4, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(5, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(6, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_platformView,
_platformView,
_overlay,
]);
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(3, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(4, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(5, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(6, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
_platformView,
_platformView,
_platformView,
_platformView,
_overlay,
],
reason:
'Many invisible views can be rendered on top of the base overlay.');
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(2, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(3, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(4, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
_overlay,
_platformView,
_platformView,
_platformView,
_overlay,
]);
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(4, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(3, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(2, width: 10, height: 10);
sb.addPicture(ui.Offset.zero, testPicture);
sb.addPlatformView(1, width: 10, height: 10);
sb.pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
_platformView,
_overlay,
_platformView,
_platformView,
_overlay,
]);
});
test('can dispose without crashing', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-view',
(int viewId) =>
createDomHTMLDivElement()..className = 'platform-view',
isVisible: false);
await createPlatformView(0, 'test-view');
await createPlatformView(1, 'test-view');
await createPlatformView(2, 'test-view');
final LayerSceneBuilder sb = LayerSceneBuilder()
..pushOffset(0, 0)
..addPlatformView(0, width: 10, height: 10)
..addPlatformView(1, width: 10, height: 10)
..addPlatformView(2, width: 10, height: 10)
..pop();
await renderScene(sb.build());
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
_platformView,
_platformView,
]);
expect(() {
final HtmlViewEmbedder embedder = (renderer as CanvasKitRenderer)
.debugGetRasterizerForView(implicitView)!
.viewEmbedder;
// The following line used to cause a "Concurrent modification during iteration"
embedder.dispose();
}, returnsNormally);
});
test('optimizes overlays when pictures and platform views do not overlap',
() async {
ui_web.platformViewRegistry.registerViewFactory(
'test-view',
(int viewId) => createDomHTMLDivElement()..className = 'platform-view',
);
CkPicture rectPicture(ui.Rect rect) {
return paintPicture(rect, (CkCanvas canvas) {
canvas.drawRect(
rect, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0));
});
}
await createPlatformView(0, 'test-view');
await createPlatformView(1, 'test-view');
await createPlatformView(2, 'test-view');
expect(PlatformViewManager.instance.isVisible(0), isTrue);
expect(PlatformViewManager.instance.isVisible(1), isTrue);
expect(PlatformViewManager.instance.isVisible(2), isTrue);
// Scene 1: Pictures just overlap with the most recently painted platform
// view. Analogous to third-party images with subtitles overlaid. Should
// only need one overlay at the end of the scene.
final LayerSceneBuilder sb1 = LayerSceneBuilder();
sb1.pushOffset(0, 0);
sb1.addPlatformView(0,
offset: const ui.Offset(10, 10), width: 50, height: 50);
sb1.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(12, 12, 10, 10)));
sb1.addPlatformView(1,
offset: const ui.Offset(70, 10), width: 50, height: 50);
sb1.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(72, 12, 10, 10)));
sb1.addPlatformView(2,
offset: const ui.Offset(130, 10), width: 50, height: 50);
sb1.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(132, 12, 10, 10)));
final LayerScene scene1 = sb1.build();
await renderScene(scene1);
_expectSceneMatches(<_EmbeddedViewMarker>[
_platformView,
_platformView,
_platformView,
_overlay,
]);
// Scene 2: Same as scene 1 but with a background painted first. Should only
// need a canvas for the background and one more for the rest of the
// pictures.
final LayerSceneBuilder sb2 = LayerSceneBuilder();
sb2.pushOffset(0, 0);
sb2.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(0, 0, 300, 300)));
sb2.addPlatformView(0,
offset: const ui.Offset(10, 10), width: 50, height: 50);
sb2.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(12, 12, 10, 10)));
sb2.addPlatformView(1,
offset: const ui.Offset(70, 10), width: 50, height: 50);
sb2.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(72, 12, 10, 10)));
sb2.addPlatformView(2,
offset: const ui.Offset(130, 10), width: 50, height: 50);
sb2.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(132, 12, 10, 10)));
final LayerScene scene2 = sb2.build();
await renderScene(scene2);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_platformView,
_platformView,
_overlay,
]);
// Scene 3: Paints a full-screen picture between each platform view. This
// is the worst case scenario. There should be an overlay between each
// platform view.
final LayerSceneBuilder sb3 = LayerSceneBuilder();
sb3.pushOffset(0, 0);
sb3.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(0, 0, 300, 300)));
sb3.addPlatformView(0,
offset: const ui.Offset(10, 10), width: 50, height: 50);
sb3.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(0, 0, 300, 300)));
sb3.addPlatformView(1,
offset: const ui.Offset(70, 10), width: 50, height: 50);
sb3.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(0, 0, 300, 300)));
sb3.addPlatformView(2,
offset: const ui.Offset(130, 10), width: 50, height: 50);
sb3.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(0, 0, 300, 300)));
final LayerScene scene3 = sb3.build();
await renderScene(scene3);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
_platformView,
_overlay,
]);
});
test('optimized overlays correctly with transforms and clips', () async {
ui_web.platformViewRegistry.registerViewFactory(
'test-view',
(int viewId) => createDomHTMLDivElement()..className = 'platform-view',
);
CkPicture rectPicture(ui.Rect rect) {
return paintPicture(rect, (CkCanvas canvas) {
canvas.drawRect(
rect, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0));
});
}
await createPlatformView(0, 'test-view');
expect(PlatformViewManager.instance.isVisible(0), isTrue);
// Test optimization correctly computes bounds with transforms and clips.
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
final Matrix4 scaleMatrix = Matrix4.identity()..scale(3, 3, 1);
sb.pushTransform(scaleMatrix.toFloat64());
sb.pushClipRect(const ui.Rect.fromLTWH(10, 10, 10, 10));
sb.addPicture(
ui.Offset.zero, rectPicture(const ui.Rect.fromLTWH(0, 0, 20, 20)));
sb.addPlatformView(0, width: 20, height: 20);
final LayerScene scene = sb.build();
await renderScene(scene);
_expectSceneMatches(<_EmbeddedViewMarker>[
_overlay,
_platformView,
]);
});
});
}
// Used to test that the platform views and overlays are in the correct order in
// the scene.
enum _EmbeddedViewMarker {
overlay,
platformView,
}
_EmbeddedViewMarker get _overlay => _EmbeddedViewMarker.overlay;
_EmbeddedViewMarker get _platformView => _EmbeddedViewMarker.platformView;
const Map<String, _EmbeddedViewMarker> _tagToViewMarker =
<String, _EmbeddedViewMarker>{
'flt-canvas-container': _EmbeddedViewMarker.overlay,
'flt-platform-view-slot': _EmbeddedViewMarker.platformView,
'flt-clip': _EmbeddedViewMarker.platformView,
};
void _expectSceneMatches(
List<_EmbeddedViewMarker> expectedMarkers, {
String? reason,
}) {
// Convert the scene elements to its corresponding array of _EmbeddedViewMarker
final List<_EmbeddedViewMarker> sceneElements = sceneHost.children
.where((DomElement element) => element.tagName != 'svg')
.map((DomElement element) =>
_tagToViewMarker[element.tagName.toLowerCase()]!)
.toList();
expect(sceneElements, expectedMarkers, reason: reason);
}
| engine/lib/web_ui/test/canvaskit/embedded_views_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/embedded_views_test.dart",
"repo_id": "engine",
"token_count": 17561
} | 264 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('CkPath', () {
setUpCanvasKitTest();
test('Using CanvasKit', () {
expect(renderer is CanvasKitRenderer, isTrue);
});
test(CkPathMetrics, () {
final ui.Path path = ui.Path();
expect(path, isA<CkPath>());
expect(path.computeMetrics().length, 0);
path.addRect(const ui.Rect.fromLTRB(0, 0, 10, 10));
final ui.PathMetric metric = path.computeMetrics().single;
expect(metric.contourIndex, 0);
expect(metric.extractPath(0, 0.5).computeMetrics().length, 1);
final ui.Tangent tangent1 = metric.getTangentForOffset(5)!;
expect(tangent1.position, const ui.Offset(5, 0));
expect(tangent1.vector, const ui.Offset(1, 0));
final ui.Tangent tangent2 = metric.getTangentForOffset(15)!;
expect(tangent2.position, const ui.Offset(10, 5));
expect(tangent2.vector, const ui.Offset(0, 1));
expect(metric.isClosed, isTrue);
path.addOval(const ui.Rect.fromLTRB(10, 10, 100, 100));
expect(path.computeMetrics().length, 2);
// Can simultaneously iterate over multiple metrics from the same path.
final ui.PathMetrics metrics1 = path.computeMetrics();
final ui.PathMetrics metrics2 = path.computeMetrics();
final Iterator<ui.PathMetric> iter1 = metrics1.iterator;
final Iterator<ui.PathMetric> iter2 = metrics2.iterator;
expect(iter1.moveNext(), isTrue);
expect(iter2.moveNext(), isTrue);
expect(iter1.current, isNotNull);
expect(iter2.current, isNotNull);
expect(iter1.moveNext(), isTrue);
expect(iter2.moveNext(), isTrue);
expect(iter1.current, isNotNull);
expect(iter2.current, isNotNull);
expect(iter1.moveNext(), isFalse);
expect(iter2.moveNext(), isFalse);
expect(() => iter1.current, throwsRangeError);
expect(() => iter2.current, throwsRangeError);
});
test('CkPath.reset', () {
final ui.Path path = ui.Path();
expect(path, isA<CkPath>());
path.addRect(const ui.Rect.fromLTRB(0, 0, 10, 10));
expect(path.contains(const ui.Offset(5, 5)), isTrue);
expect(path.fillType, ui.PathFillType.nonZero);
path.fillType = ui.PathFillType.evenOdd;
expect(path.fillType, ui.PathFillType.evenOdd);
path.reset();
expect(path.fillType, ui.PathFillType.nonZero);
expect(path.contains(const ui.Offset(5, 5)), isFalse);
});
test('CkPath.shift creates a shifted copy of the path', () {
const ui.Rect testRect = ui.Rect.fromLTRB(0, 0, 10, 10);
final CkPath path = CkPath();
path.addRect(testRect);
expect(path.getBounds(), testRect);
expect(
path.shift(const ui.Offset(20, 20)).getBounds(),
testRect.shift(const ui.Offset(20, 20)),
);
// Make sure the original path wasn't mutated.
expect(path.getBounds(), testRect);
});
test('CkContourMeasure iteration', () {
final ui.Path path = ui.Path();
expect(path, isA<CkPath>());
path.addRect(const ui.Rect.fromLTRB(0, 0, 10, 10));
path.addRect(const ui.Rect.fromLTRB(20, 20, 30, 30));
path.addRect(const ui.Rect.fromLTRB(40, 40, 50, 50));
final ui.PathMetrics metrics = path.computeMetrics();
final CkContourMeasureIter iterator = metrics.iterator as CkContourMeasureIter;
expect(iterator.moveNext(), isTrue);
expect(iterator.current.contourIndex, 0);
expect(iterator.moveNext(), isTrue);
expect(iterator.current.contourIndex, 1);
});
test('CkContourMeasure index', () {
final ui.Path path = ui.Path();
expect(path, isA<CkPath>());
path.addRect(const ui.Rect.fromLTRB(0, 0, 10, 10));
path.addRect(const ui.Rect.fromLTRB(20, 20, 30, 30));
path.addRect(const ui.Rect.fromLTRB(40, 40, 50, 50));
final ui.PathMetrics metrics = path.computeMetrics();
final CkContourMeasureIter iterator = metrics.iterator as CkContourMeasureIter;
expect(iterator.moveNext(), isTrue);
final CkContourMeasure measure0 = iterator.current as CkContourMeasure;
expect(measure0.contourIndex, 0);
expect(measure0.extractPath(0, 15).getBounds(), const ui.Rect.fromLTRB(0, 0, 10, 5));
expect(iterator.moveNext(), isTrue);
final CkContourMeasure measure1 = iterator.current as CkContourMeasure;
expect(measure1.contourIndex, 1);
expect(measure1.extractPath(0, 15).getBounds(), const ui.Rect.fromLTRB(20, 20, 30, 25));
});
test('Path.from', () {
const ui.Rect rect1 = ui.Rect.fromLTRB(0, 0, 10, 10);
const ui.Rect rect2 = ui.Rect.fromLTRB(10, 10, 20, 20);
final ui.Path original = ui.Path();
original.addRect(rect1);
expect(original, isA<CkPath>());
expect(original.getBounds(), rect1);
final ui.Path copy = ui.Path.from(original);
expect(copy, isA<CkPath>());
expect(copy.getBounds(), rect1);
// Test that when copy is mutated, the original is not affected
copy.addRect(rect2);
expect(original.getBounds(), rect1);
expect(copy.getBounds(), rect1.expandToInclude(rect2));
});
});
}
| engine/lib/web_ui/test/canvaskit/path_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/canvaskit/path_test.dart",
"repo_id": "engine",
"token_count": 2302
} | 265 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/src/engine.dart';
typedef VoidCallback = void Function();
class MockKeyboardEvent implements FlutterHtmlKeyboardEvent {
MockKeyboardEvent({
required this.type,
required this.code,
required this.key,
this.timeStamp = 0,
this.repeat = false,
this.keyCode = 0,
this.isComposing = false,
bool altKey = false,
bool ctrlKey = false,
bool shiftKey = false,
bool metaKey = false,
bool altGrKey = false,
this.location = 0,
this.onPreventDefault,
this.onStopPropagation,
}) : modifierState =
<String>{
if (altKey) 'Alt',
if (ctrlKey) 'Control',
if (shiftKey) 'Shift',
if (metaKey) 'Meta',
if (altGrKey) 'AltGraph',
} {
_lastEvent = this;
}
@override
String type;
@override
String? code;
@override
String? key;
@override
bool? repeat;
@override
int keyCode;
@override
num? timeStamp;
@override
bool isComposing;
@override
bool get altKey => modifierState.contains('Alt');
@override
bool get ctrlKey => modifierState.contains('Control');
@override
bool get shiftKey => modifierState.contains('Shift');
@override
bool get metaKey => modifierState.contains('Meta');
@override
int? location;
@override
bool getModifierState(String key) => modifierState.contains(key);
final Set<String> modifierState;
@override
void preventDefault() {
onPreventDefault?.call();
_defaultPrevented = true;
}
VoidCallback? onPreventDefault;
@override
bool get defaultPrevented => _defaultPrevented;
bool _defaultPrevented = false;
@override
void stopPropagation() {
onStopPropagation?.call();
}
VoidCallback? onStopPropagation;
static bool get lastDefaultPrevented => _lastEvent?.defaultPrevented ?? false;
static MockKeyboardEvent? _lastEvent;
}
| engine/lib/web_ui/test/common/keyboard_test_common.dart/0 | {
"file_path": "engine/lib/web_ui/test/common/keyboard_test_common.dart",
"repo_id": "engine",
"token_count": 745
} | 266 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import '../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
await bootstrapAndRunApp();
// Test successful HTTP roundtrips where the server returns a happy status
// code and a payload.
await _testSuccessfulPayloads();
// Test successful HTTP roundtrips where the server returned something other
// than a happy result (404 in particular is a common one).
await _testHttpErrorCodes();
// Test network errors that prevent the HTTP roundtrip to complete. These
// errors include invalid URLs, CORS issues, lost internet access, etc.
await _testNetworkErrors();
test('window.fetch is banned', () async {
expect(
() => domWindow.fetch('/'),
throwsA(isA<UnsupportedError>()),
);
});
}
Future<void> _testSuccessfulPayloads() async {
test('httpFetch fetches a text file', () async {
final HttpFetchResponse response = await httpFetch('/lib/src/engine/alarm_clock.dart');
expect(response.status, 200);
expect(response.contentLength, greaterThan(0));
expect(response.hasPayload, isTrue);
expect(response.payload, isNotNull);
expect(response.url, '/lib/src/engine/alarm_clock.dart');
expect(
await response.text(),
startsWith('''
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.'''),
);
});
test('httpFetch fetches a binary file as ByteBuffer', () async {
final HttpFetchResponse response = await httpFetch('/test_images/1x1.png');
expect(response.status, 200);
expect(response.contentLength, greaterThan(0));
expect(response.hasPayload, isTrue);
expect(response.payload, isNotNull);
expect(response.url, '/test_images/1x1.png');
expect(
(await response.asByteBuffer()).asUint8List().sublist(0, 8),
<int>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
);
});
test('httpFetch fetches a binary file as Uint8List', () async {
final HttpFetchResponse response = await httpFetch('/test_images/1x1.png');
expect(response.status, 200);
expect(response.contentLength, greaterThan(0));
expect(response.hasPayload, isTrue);
expect(response.payload, isNotNull);
expect(response.url, '/test_images/1x1.png');
expect(
(await response.asUint8List()).sublist(0, 8),
<int>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
);
});
test('httpFetch fetches json', () async {
final HttpFetchResponse response = await httpFetch('/test_images/');
expect(response.status, 200);
expect(response.contentLength, greaterThan(0));
expect(response.hasPayload, isTrue);
expect(response.payload, isNotNull);
expect(response.url, '/test_images/');
expect(
await response.json(),
isA<List<Object?>>(),
);
});
test('httpFetch reads data in chunks', () async {
// There is no guarantee that the server will actually serve the data in any
// particular chunk sizes, but breaking up the data in _some_ way does cause
// it to chunk it.
const List<List<int>> lengthAndChunks = <List<int>>[
<int>[0, 0],
<int>[10, 10],
<int>[1000, 100],
<int>[10000, 1000],
<int>[100000, 10000],
];
for (final List<int> lengthAndChunk in lengthAndChunks) {
final int length = lengthAndChunk.first;
final int chunkSize = lengthAndChunk.last;
final String url = '/long_test_payload?length=$length&chunk=$chunkSize';
final HttpFetchResponse response = await httpFetch(url);
expect(response.status, 200);
expect(response.contentLength, length);
expect(response.hasPayload, isTrue);
expect(response.payload, isNotNull);
expect(response.url, url);
final List<int> result = <int>[];
await response.payload.read<JSUint8Array>((JSUint8Array chunk) => result.addAll(chunk.toDart));
expect(result, hasLength(length));
expect(
result,
List<int>.generate(length, (int i) => i & 0xFF),
);
}
});
test('httpFetchText fetches a text file', () async {
final String text = await httpFetchText('/lib/src/engine/alarm_clock.dart');
expect(
text,
startsWith('''
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.'''),
);
});
test('httpFetchByteBuffer fetches a binary file as ByteBuffer', () async {
final ByteBuffer response = await httpFetchByteBuffer('/test_images/1x1.png');
expect(
response.asUint8List().sublist(0, 8),
<int>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
);
});
test('httpFetchJson fetches json', () async {
final Object? json = await httpFetchJson('/test_images/');
expect(json, isA<List<Object?>>());
});
}
Future<void> _testHttpErrorCodes() async {
test('httpFetch throws HttpFetchNoPayloadError on 404', () async {
final HttpFetchResponse response = await httpFetch('/file_not_found');
expect(response.status, 404);
expect(response.hasPayload, isFalse);
expect(response.url, '/file_not_found');
try {
// Attempting to read the payload when there isn't one should result in
// HttpFetchNoPayloadError thrown.
response.payload;
fail('Expected HttpFetchNoPayloadError');
} on HttpFetchNoPayloadError catch(error) {
expect(error.status, 404);
expect(error.url, '/file_not_found');
expect(
error.toString(),
'Flutter Web engine failed to fetch "/file_not_found". '
'HTTP request succeeded, but the server responded with HTTP status 404.',
);
}
});
test('httpFetch* functions throw HttpFetchNoPayloadError on 404', () async {
final List<AsyncCallback> testFunctions = <AsyncCallback>[
() async => httpFetchText('/file_not_found'),
() async => httpFetchByteBuffer('/file_not_found'),
() async => httpFetchJson('/file_not_found'),
];
for (final AsyncCallback testFunction in testFunctions) {
try {
await testFunction();
fail('Expected HttpFetchNoPayloadError');
} on HttpFetchNoPayloadError catch(error) {
expect(error.status, 404);
expect(error.url, '/file_not_found');
expect(
error.toString(),
'Flutter Web engine failed to fetch "/file_not_found". '
'HTTP request succeeded, but the server responded with HTTP status 404.',
);
}
}
});
}
Future<void> _testNetworkErrors() async {
test('httpFetch* functions throw HttpFetchError on network errors', () async {
// Fetch throws the error this test wants on URLs with user credentials.
const String badUrl = 'https://user:[email protected]/';
final List<AsyncCallback> testFunctions = <AsyncCallback>[
() async => httpFetch(badUrl),
() async => httpFetchText(badUrl),
() async => httpFetchByteBuffer(badUrl),
() async => httpFetchJson(badUrl),
];
for (final AsyncCallback testFunction in testFunctions) {
try {
await testFunction();
fail('Expected HttpFetchError');
} on HttpFetchError catch(error) {
expect(error.url, badUrl);
expect(
error.toString(),
// Browsers agree on throwing a TypeError, but they disagree on the
// error message. So this only checks for the common error prefix, but
// not the entire error message.
startsWith(
'Flutter Web engine failed to complete HTTP request to fetch '
'"https://user:[email protected]/": TypeError: '
),
);
}
}
});
}
typedef AsyncCallback = Future<void> Function();
| engine/lib/web_ui/test/engine/dom_http_fetch_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/dom_http_fetch_test.dart",
"repo_id": "engine",
"token_count": 3055
} | 267 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$ContextMenu', () {
test('can disable context menu', () {
final DomElement rootViewElement = createDomElement('div');
final ContextMenu contextMenu = ContextMenu(rootViewElement);
// When the app starts, contextmenu events are not prevented.
DomEvent event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isFalse);
// Disabling the context menu causes contextmenu events to be prevented.
contextMenu.disable();
event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isTrue);
// Disabling again has no effect.
contextMenu.disable();
event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isTrue);
});
test('does not disable context menu outside root view element', () {
final DomElement rootViewElement = createDomElement('div');
final ContextMenu contextMenu = ContextMenu(rootViewElement);
contextMenu.disable();
// Dispatching on a DOM element outside of target's subtree has no effect.
final DomEvent event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
domDocument.body!.dispatchEvent(event);
expect(event.defaultPrevented, isFalse);
});
test('can enable context menu after disabling', () {
final DomElement rootViewElement = createDomElement('div');
final ContextMenu contextMenu = ContextMenu(rootViewElement);
// When the app starts, contextmenu events are not prevented.
DomEvent event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isFalse);
// Disabling the context menu causes contextmenu events to be prevented.
contextMenu.disable();
event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isTrue);
// Enabling the context menu means that contextmenu events are back to not
// being prevented.
contextMenu.enable();
event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isFalse);
// Enabling again has no effect.
contextMenu.enable();
event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isFalse);
});
test('enabling before disabling has no effect', () {
final DomElement rootViewElement = createDomElement('div');
final ContextMenu contextMenu = ContextMenu(rootViewElement);
// When the app starts, contextmenu events are not prevented.
DomEvent event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isFalse);
// Enabling has no effect.
contextMenu.enable();
event = createDomEvent('Event', 'contextmenu');
expect(event.defaultPrevented, isFalse);
rootViewElement.dispatchEvent(event);
expect(event.defaultPrevented, isFalse);
});
});
}
| engine/lib/web_ui/test/engine/mouse/context_menu_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/mouse/context_menu_test.dart",
"repo_id": "engine",
"token_count": 1339
} | 268 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'scene_builder_utils.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
setUpAll(() {
LayerBuilder.debugRecorderFactory = (ui.Rect rect) {
final StubSceneCanvas canvas = StubSceneCanvas();
final StubPictureRecorder recorder = StubPictureRecorder(canvas);
return (recorder, canvas);
};
});
tearDownAll(() {
LayerBuilder.debugRecorderFactory = null;
});
group('EngineSceneBuilder', () {
test('single picture', () {
final EngineSceneBuilder sceneBuilder = EngineSceneBuilder();
const ui.Rect pictureRect = ui.Rect.fromLTRB(100, 100, 200, 200);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect));
final EngineScene scene = sceneBuilder.build() as EngineScene;
final List<LayerSlice> slices = scene.rootLayer.slices;
expect(slices.length, 1);
expect(slices[0], pictureSliceWithRect(pictureRect));
});
test('two pictures', () {
final EngineSceneBuilder sceneBuilder = EngineSceneBuilder();
const ui.Rect pictureRect1 = ui.Rect.fromLTRB(100, 100, 200, 200);
const ui.Rect pictureRect2 = ui.Rect.fromLTRB(300, 400, 400, 400);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect1));
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect2));
final EngineScene scene = sceneBuilder.build() as EngineScene;
final List<LayerSlice> slices = scene.rootLayer.slices;
expect(slices.length, 1);
expect(slices[0], pictureSliceWithRect(const ui.Rect.fromLTRB(100, 100, 400, 400)));
});
test('picture + platform view (overlapping)', () {
final EngineSceneBuilder sceneBuilder = EngineSceneBuilder();
const ui.Rect pictureRect = ui.Rect.fromLTRB(100, 100, 200, 200);
const ui.Rect platformViewRect = ui.Rect.fromLTRB(150, 150, 250, 250);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect));
sceneBuilder.addPlatformView(
1,
offset: platformViewRect.topLeft,
width: platformViewRect.width,
height: platformViewRect.height
);
final EngineScene scene = sceneBuilder.build() as EngineScene;
final List<LayerSlice> slices = scene.rootLayer.slices;
expect(slices.length, 2);
expect(slices[0], pictureSliceWithRect(pictureRect));
expect(slices[1], platformViewSliceWithViews(<PlatformView>[
PlatformView(1, platformViewRect.size, PlatformViewStyling(
position: PlatformViewPosition.offset(platformViewRect.topLeft)
))
]));
});
test('platform view + picture (overlapping)', () {
final EngineSceneBuilder sceneBuilder = EngineSceneBuilder();
const ui.Rect pictureRect = ui.Rect.fromLTRB(100, 100, 200, 200);
const ui.Rect platformViewRect = ui.Rect.fromLTRB(150, 150, 250, 250);
sceneBuilder.addPlatformView(
1,
offset: platformViewRect.topLeft,
width: platformViewRect.width,
height: platformViewRect.height
);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect));
final EngineScene scene = sceneBuilder.build() as EngineScene;
final List<LayerSlice> slices = scene.rootLayer.slices;
expect(slices.length, 2);
expect(slices[0], platformViewSliceWithViews(<PlatformView>[
PlatformView(1, platformViewRect.size, PlatformViewStyling(
position: PlatformViewPosition.offset(platformViewRect.topLeft)
))
]));
expect(slices[1], pictureSliceWithRect(pictureRect));
});
test('platform view sandwich (overlapping)', () {
final EngineSceneBuilder sceneBuilder = EngineSceneBuilder();
const ui.Rect pictureRect1 = ui.Rect.fromLTRB(100, 100, 200, 200);
const ui.Rect platformViewRect = ui.Rect.fromLTRB(150, 150, 250, 250);
const ui.Rect pictureRect2 = ui.Rect.fromLTRB(200, 200, 300, 300);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect1));
sceneBuilder.addPlatformView(
1,
offset: platformViewRect.topLeft,
width: platformViewRect.width,
height: platformViewRect.height
);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect2));
final EngineScene scene = sceneBuilder.build() as EngineScene;
final List<LayerSlice> slices = scene.rootLayer.slices;
expect(slices.length, 3);
expect(slices[0], pictureSliceWithRect(pictureRect1));
expect(slices[1], platformViewSliceWithViews(<PlatformView>[
PlatformView(1, platformViewRect.size, PlatformViewStyling(
position: PlatformViewPosition.offset(platformViewRect.topLeft)
))
]));
expect(slices[2], pictureSliceWithRect(pictureRect2));
});
test('platform view sandwich (non-overlapping)', () {
final EngineSceneBuilder sceneBuilder = EngineSceneBuilder();
const ui.Rect pictureRect1 = ui.Rect.fromLTRB(100, 100, 200, 200);
const ui.Rect platformViewRect = ui.Rect.fromLTRB(150, 150, 250, 250);
const ui.Rect pictureRect2 = ui.Rect.fromLTRB(50, 50, 100, 100);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect1));
sceneBuilder.addPlatformView(
1,
offset: platformViewRect.topLeft,
width: platformViewRect.width,
height: platformViewRect.height
);
sceneBuilder.addPicture(ui.Offset.zero, StubPicture(pictureRect2));
final EngineScene scene = sceneBuilder.build() as EngineScene;
final List<LayerSlice> slices = scene.rootLayer.slices;
// The top picture does not overlap with the platform view, so it should
// be grouped into the slice below it to reduce the number of canvases we
// need.
expect(slices.length, 2);
expect(slices[0], pictureSliceWithRect(const ui.Rect.fromLTRB(50, 50, 200, 200)));
expect(slices[1], platformViewSliceWithViews(<PlatformView>[
PlatformView(1, platformViewRect.size, PlatformViewStyling(
position: PlatformViewPosition.offset(platformViewRect.topLeft)
))
]));
});
});
}
PictureSliceMatcher pictureSliceWithRect(ui.Rect rect) => PictureSliceMatcher(rect);
PlatformViewSliceMatcher platformViewSliceWithViews(List<PlatformView> views)
=> PlatformViewSliceMatcher(views);
class PictureSliceMatcher extends Matcher {
PictureSliceMatcher(this.expectedRect);
final ui.Rect expectedRect;
@override
Description describe(Description description) {
return description.add('<picture slice with cullRect: $expectedRect>');
}
@override
bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
if (item is! PictureSlice) {
return false;
}
final ScenePicture picture = item.picture;
if (picture is! StubPicture) {
return false;
}
if (picture.cullRect != expectedRect) {
return false;
}
return true;
}
}
class PlatformViewSliceMatcher extends Matcher {
PlatformViewSliceMatcher(this.expectedPlatformViews);
final List<PlatformView> expectedPlatformViews;
@override
Description describe(Description description) {
return description.add('<platform view slice with platform views: $expectedPlatformViews>');
}
@override
bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
if (item is! PlatformViewSlice) {
return false;
}
if (item.views.length != expectedPlatformViews.length) {
return false;
}
for (int i = 0; i < item.views.length; i++) {
final PlatformView expectedView = expectedPlatformViews[i];
final PlatformView actualView = item.views[i];
if (expectedView.viewId != actualView.viewId) {
return false;
}
if (expectedView.size != actualView.size) {
return false;
}
if (expectedView.styling != actualView.styling) {
return false;
}
}
return true;
}
}
| engine/lib/web_ui/test/engine/scene_builder_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/scene_builder_test.dart",
"repo_id": "engine",
"token_count": 3068
} | 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.
import 'dart:math' as math;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
/// Test winding and convexity of a path.
void testMain() {
group('Convexity', () {
test('Empty path should be convex', () {
final SurfacePath path = SurfacePath();
expect(path.isConvex, isTrue);
});
test('Circle should be convex', () {
final SurfacePath path = SurfacePath();
path.addOval(const Rect.fromLTRB(0, 0, 20, 20));
expect(path.isConvex, isTrue);
// 2nd circle.
path.addOval(const Rect.fromLTRB(0, 0, 20, 20));
expect(path.isConvex, isFalse);
});
test('addRect should be convex', () {
SurfacePath path = SurfacePath();
path.addRect(const Rect.fromLTRB(0, 0, 20, 20));
expect(path.isConvex, isTrue);
path = SurfacePath();
path.addRectWithDirection(
const Rect.fromLTRB(0, 0, 20, 20), SPathDirection.kCW, 0);
expect(path.isConvex, isTrue);
path = SurfacePath();
path.addRectWithDirection(
const Rect.fromLTRB(0, 0, 20, 20), SPathDirection.kCCW, 0);
expect(path.isConvex, isTrue);
});
test('Quad should be convex', () {
final SurfacePath path = SurfacePath();
path.quadraticBezierTo(100, 100, 50, 50);
expect(path.isConvex, isTrue);
});
test('moveto/lineto convexity', () {
final List<LineTestCase> testCases = <LineTestCase>[
LineTestCase('', SPathConvexityType.kConvex),
LineTestCase(
'0 0', SPathConvexityType.kConvex),
LineTestCase(
'0 0 10 10', SPathConvexityType.kConvex),
LineTestCase('0 0 10 10 20 20 0 0 10 10', SPathConvexityType.kConcave),
LineTestCase(
'0 0 10 10 10 20', SPathConvexityType.kConvex),
LineTestCase(
'0 0 10 10 10 0', SPathConvexityType.kConvex),
LineTestCase('0 0 10 10 10 0 0 10', SPathConvexityType.kConcave),
LineTestCase('0 0 10 0 0 10 -10 -10', SPathConvexityType.kConcave),
];
for (final LineTestCase testCase in testCases) {
final SurfacePath path = SurfacePath();
setFromString(path, testCase.pathContent);
expect(path.convexityType, testCase.convexity);
}
});
test('Convexity of path with infinite points should return unknown', () {
const List<Offset> nonFinitePts = <Offset>[
Offset(double.infinity, 0),
Offset(0, double.infinity),
Offset.infinite,
Offset(double.negativeInfinity, 0),
Offset(0, double.negativeInfinity),
Offset(double.negativeInfinity, double.negativeInfinity),
Offset(double.negativeInfinity, double.infinity),
Offset(double.infinity, double.negativeInfinity),
Offset(double.nan, 0),
Offset(0, double.nan),
Offset(double.nan, double.nan)
];
final int nonFinitePointsCount = nonFinitePts.length;
const List<Offset> axisAlignedPts = <Offset>[
Offset(kScalarMax, 0),
Offset(0, kScalarMax),
Offset(kScalarMin, 0),
Offset(0, kScalarMin)
];
final int axisAlignedPointsCount = axisAlignedPts.length;
final SurfacePath path = SurfacePath();
for (int index = 0;
index < (13 * nonFinitePointsCount * axisAlignedPointsCount);
index++) {
final int i = index % nonFinitePointsCount;
final int f = index % axisAlignedPointsCount;
final int g = (f + 1) % axisAlignedPointsCount;
path.reset();
switch (index % 13) {
case 0:
path.lineTo(nonFinitePts[i].dx, nonFinitePts[i].dy);
case 1:
path.quadraticBezierTo(nonFinitePts[i].dx, nonFinitePts[i].dy,
nonFinitePts[i].dx, nonFinitePts[i].dy);
case 2:
path.quadraticBezierTo(nonFinitePts[i].dx, nonFinitePts[i].dy,
axisAlignedPts[f].dx, axisAlignedPts[f].dy);
case 3:
path.quadraticBezierTo(axisAlignedPts[f].dx, axisAlignedPts[f].dy,
nonFinitePts[i].dx, nonFinitePts[i].dy);
case 4:
path.cubicTo(
nonFinitePts[i].dx,
nonFinitePts[i].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy);
case 5:
path.cubicTo(
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy);
case 6:
path.cubicTo(
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy);
case 7:
path.cubicTo(
nonFinitePts[i].dx,
nonFinitePts[i].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy);
case 8:
path.cubicTo(
nonFinitePts[i].dx,
nonFinitePts[i].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy);
case 9:
path.cubicTo(
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy);
case 10:
path.cubicTo(
nonFinitePts[i].dx,
nonFinitePts[i].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy,
nonFinitePts[i].dx,
nonFinitePts[i].dy);
case 11:
path.cubicTo(
nonFinitePts[i].dx,
nonFinitePts[i].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[g].dx,
axisAlignedPts[g].dy);
case 12:
path.moveTo(nonFinitePts[i].dx, nonFinitePts[i].dy);
}
expect(path.convexityType, SPathConvexityType.kUnknown);
}
for (int index = 0; index < (11 * axisAlignedPointsCount); ++index) {
final int f = index % axisAlignedPointsCount;
final int g = (f + 1) % axisAlignedPointsCount;
path.reset();
final int curveSelect = index % 11;
switch (curveSelect) {
case 0:
path.moveTo(axisAlignedPts[f].dx, axisAlignedPts[f].dy);
case 1:
path.lineTo(axisAlignedPts[f].dx, axisAlignedPts[f].dy);
case 2:
path.quadraticBezierTo(axisAlignedPts[f].dx, axisAlignedPts[f].dy,
axisAlignedPts[f].dx, axisAlignedPts[f].dy);
case 3:
path.quadraticBezierTo(axisAlignedPts[f].dx, axisAlignedPts[f].dy,
axisAlignedPts[g].dx, axisAlignedPts[g].dy);
case 4:
path.quadraticBezierTo(axisAlignedPts[g].dx, axisAlignedPts[g].dy,
axisAlignedPts[f].dx, axisAlignedPts[f].dy);
case 5:
path.cubicTo(
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy);
case 6:
path.cubicTo(
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[g].dx,
axisAlignedPts[g].dy);
case 7:
path.cubicTo(
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[g].dx,
axisAlignedPts[g].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy);
case 8:
path.cubicTo(
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[g].dx,
axisAlignedPts[g].dy,
axisAlignedPts[g].dx,
axisAlignedPts[g].dy);
case 9:
path.cubicTo(
axisAlignedPts[g].dx,
axisAlignedPts[g].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy);
case 10:
path.cubicTo(
axisAlignedPts[g].dx,
axisAlignedPts[g].dy,
axisAlignedPts[f].dx,
axisAlignedPts[f].dy,
axisAlignedPts[g].dx,
axisAlignedPts[g].dy);
}
if (curveSelect != 7 && curveSelect != 10) {
final int result = path.convexityType;
expect(result, SPathConvexityType.kConvex);
} else {
// we make a copy so that we don't cache the result on the passed
// in path.
final SurfacePath path2 = SurfacePath.from(path);
final int c = path2.convexityType;
assert(SPathConvexityType.kUnknown == c ||
SPathConvexityType.kConcave == c);
}
}
});
test('Concave lines path', () {
final SurfacePath path = SurfacePath();
path.moveTo(-0.284071773, -0.0622361786);
path.lineTo(-0.284072, -0.0622351);
path.lineTo(-0.28407, -0.0622307);
path.lineTo(-0.284067, -0.0622182);
path.lineTo(-0.284084, -0.0622269);
path.lineTo(-0.284072, -0.0622362);
path.close();
expect(path.convexityType, SPathConvexityType.kConcave);
});
test('Single moveTo origin', () {
final SurfacePath path = SurfacePath();
path.moveTo(0, 0);
expect(path.convexityType, SPathConvexityType.kConvex);
});
test('Single diagonal line', () {
final SurfacePath path = SurfacePath();
path.moveTo(12, 20);
path.lineTo(-12, -20);
expect(path.convexityType, SPathConvexityType.kConvex);
});
test('TriLeft', () {
final SurfacePath path = SurfacePath();
path.moveTo(0, 0);
path.lineTo(1, 0);
path.lineTo(1, 1);
path.close();
expect(path.convexityType, SPathConvexityType.kConvex);
});
test('TriRight', () {
final SurfacePath path = SurfacePath();
path.moveTo(0, 0);
path.lineTo(-1, 0);
path.lineTo(1, 1);
path.close();
expect(path.convexityType, SPathConvexityType.kConvex);
});
test('square', () {
final SurfacePath path = SurfacePath();
path.moveTo(0, 0);
path.lineTo(1, 0);
path.lineTo(1, 1);
path.lineTo(0, 1);
path.close();
expect(path.convexityType, SPathConvexityType.kConvex);
});
test('redundant square', () {
final SurfacePath redundantSquare = SurfacePath();
redundantSquare.moveTo(0, 0);
redundantSquare.lineTo(0, 0);
redundantSquare.lineTo(0, 0);
redundantSquare.lineTo(1, 0);
redundantSquare.lineTo(1, 0);
redundantSquare.lineTo(1, 0);
redundantSquare.lineTo(1, 1);
redundantSquare.lineTo(1, 1);
redundantSquare.lineTo(1, 1);
redundantSquare.lineTo(0, 1);
redundantSquare.lineTo(0, 1);
redundantSquare.lineTo(0, 1);
redundantSquare.close();
expect(redundantSquare.convexityType, SPathConvexityType.kConvex);
});
test('bowtie', () {
final SurfacePath bowTie = SurfacePath();
bowTie.moveTo(0, 0);
bowTie.lineTo(0, 0);
bowTie.lineTo(0, 0);
bowTie.lineTo(1, 1);
bowTie.lineTo(1, 1);
bowTie.lineTo(1, 1);
bowTie.lineTo(1, 0);
bowTie.lineTo(1, 0);
bowTie.lineTo(1, 0);
bowTie.lineTo(0, 1);
bowTie.lineTo(0, 1);
bowTie.lineTo(0, 1);
bowTie.close();
expect(bowTie.convexityType, SPathConvexityType.kConcave);
});
test('sprial', () {
final SurfacePath spiral = SurfacePath();
spiral.moveTo(0, 0);
spiral.lineTo(100, 0);
spiral.lineTo(100, 100);
spiral.lineTo(0, 100);
spiral.lineTo(0, 50);
spiral.lineTo(50, 50);
spiral.lineTo(50, 75);
spiral.close();
expect(spiral.convexityType, SPathConvexityType.kConcave);
});
test('dent', () {
final SurfacePath dent = SurfacePath();
dent.moveTo(0, 0);
dent.lineTo(100, 100);
dent.lineTo(0, 100);
dent.lineTo(-50, 200);
dent.lineTo(-200, 100);
dent.close();
expect(dent.convexityType, SPathConvexityType.kConcave);
});
test('degenerate segments1', () {
final SurfacePath strokedSin = SurfacePath();
for (int i = 0; i < 2000; i++) {
final double x = i.toDouble() / 2.0;
final double y = 500 - (x + math.sin(x / 100) * 40) / 3;
if (0 == i) {
strokedSin.moveTo(x, y);
} else {
strokedSin.lineTo(x, y);
}
}
expect(strokedSin.convexityType, SPathConvexityType.kConcave);
});
/// Regression test for https://github.com/flutter/flutter/issues/66560.
test('Quadratic', () {
final SurfacePath path = SurfacePath();
path.moveTo(100.0, 0.0);
path.quadraticBezierTo(200.0, 0.0, 200.0, 100.0);
path.quadraticBezierTo(200.0, 200.0, 100.0, 200.0);
path.quadraticBezierTo(0.0, 200.0, 0.0, 100.0);
path.quadraticBezierTo(0.0, 0.0, 100.0, 0.0);
path.close();
expect(path.contains(const Offset(100, 20)), isTrue);
expect(path.contains(const Offset(100, 120)), isTrue);
expect(path.contains(const Offset(100, -10)), isFalse);
});
});
}
class LineTestCase {
LineTestCase(this.pathContent, this.convexity);
final String pathContent;
final int convexity;
}
/// Parses a string of the format "mx my lx1 ly1 lx2 ly2..." into a path
/// with moveTo/lineTo instructions for points.
void setFromString(SurfacePath path, String value) {
bool first = true;
final List<String> points = value.split(' ');
if (points.length < 2) {
return;
}
for (int i = 0; i < points.length; i += 2) {
if (first) {
path.moveTo(double.parse(points[i]), double.parse(points[i + 1]));
first = false;
} else {
path.lineTo(double.parse(points[i]), double.parse(points[i + 1]));
}
}
}
// Scalar max is based on 32 bit float since [PathRef] stores values in
// Float32List.
const double kScalarMax = 3.402823466e+38;
const double kScalarMin = -kScalarMax;
| engine/lib/web_ui/test/engine/surface/path/path_winding_test.dart/0 | {
"file_path": "engine/lib/web_ui/test/engine/surface/path/path_winding_test.dart",
"repo_id": "engine",
"token_count": 7898
} | 270 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.