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/concurrent_message_loop.h" namespace fml { class ConcurrentMessageLoopDarwin : public ConcurrentMessageLoop { friend class ConcurrentMessageLoop; protected: explicit ConcurrentMessageLoopDarwin(size_t worker_count) : ConcurrentMessageLoop(worker_count) {} void ExecuteTask(const fml::closure& task) override { @autoreleasepool { task(); } } }; std::shared_ptr<ConcurrentMessageLoop> ConcurrentMessageLoop::Create(size_t worker_count) { return std::shared_ptr<ConcurrentMessageLoop>{new ConcurrentMessageLoopDarwin(worker_count)}; } } // namespace fml
engine/fml/platform/darwin/concurrent_message_loop_factory.mm/0
{ "file_path": "engine/fml/platform/darwin/concurrent_message_loop_factory.mm", "repo_id": "engine", "token_count": 236 }
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_FML_PLATFORM_DARWIN_STRING_RANGE_SANITIZATION_H_ #define FLUTTER_FML_PLATFORM_DARWIN_STRING_RANGE_SANITIZATION_H_ #include <Foundation/Foundation.h> namespace fml { // Returns a range encompassing the grapheme cluster in which |index| is located. // // A nil |text| or an index greater than or equal to text.length will result in // `NSRange(NSNotFound, 0)`. NSRange RangeForCharacterAtIndex(NSString* text, NSUInteger index); // Returns a range encompassing the grapheme clusters falling in |range|. // // This method will not alter the length of the input range, but will ensure // that the range's location is not in the middle of a multi-byte unicode // sequence. // // An invalid range will result in `NSRange(NSNotFound, 0)`. NSRange RangeForCharactersInRange(NSString* text, NSRange range); } // namespace fml #endif // FLUTTER_FML_PLATFORM_DARWIN_STRING_RANGE_SANITIZATION_H_
engine/fml/platform/darwin/string_range_sanitization.h/0
{ "file_path": "engine/fml/platform/darwin/string_range_sanitization.h", "repo_id": "engine", "token_count": 341 }
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_FML_PLATFORM_FUCHSIA_TASK_OBSERVERS_H_ #define FLUTTER_FML_PLATFORM_FUCHSIA_TASK_OBSERVERS_H_ #include <lib/fit/function.h> namespace fml { // Executes all closures that were registered via // `CurrentMessageLoopAddAfterTaskObserver` on this thread. // // WARNING(fxbug.dev/77957): These task observers are distinct from the task // observers that can be specified via `fml::MessageLoop::AddTaskObserver` and // they behave differently! // // Task observers registered via `fml::MessageLoop::AddTaskObserver` only fire // after work that was posted via the `fml::MessageLoop`'s `TaskRunner` // completes. Work that is posted directly to the Fuchsia message loop (e.g. // using `async::PostTask(async_get_default_dispatcher(), ...)`) is invisible to // `fml::MessageLoop`, so the `fml::MessageLoop`'s task observers don't fire. // // The task observers registered with `CurrentMessageLoopAddAfterTaskObserver`, // however, fire after _every_ work item is completed, regardless of whether it // was posted to the Fuchsia message loop directly or via `fml::MessageLoop`. // // These two mechanisms are redundant and confusing, so we should fix it // somehow. void ExecuteAfterTaskObservers(); void CurrentMessageLoopAddAfterTaskObserver(intptr_t key, fit::closure observer); void CurrentMessageLoopRemoveAfterTaskObserver(intptr_t key); } // namespace fml #endif // FLUTTER_FML_PLATFORM_FUCHSIA_TASK_OBSERVERS_H_
engine/fml/platform/fuchsia/task_observers.h/0
{ "file_path": "engine/fml/platform/fuchsia/task_observers.h", "repo_id": "engine", "token_count": 525 }
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. #include "flutter/fml/platform/win/errors_win.h" #include <Windows.h> #include <sstream> #include "flutter/fml/platform/win/wstring_conversion.h" namespace fml { std::string GetLastErrorMessage() { DWORD last_error = ::GetLastError(); if (last_error == 0) { return {}; } const DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; wchar_t* buffer = nullptr; size_t size = ::FormatMessage( flags, // dwFlags NULL, // lpSource last_error, // dwMessageId MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // dwLanguageId (LPWSTR)&buffer, // lpBuffer 0, // nSize NULL // Arguments ); std::wstring message(buffer, size); ::LocalFree(buffer); std::wstringstream stream; stream << message << " (" << last_error << ")."; return WideStringToUtf8(stream.str()); } } // namespace fml
engine/fml/platform/win/errors_win.cc/0
{ "file_path": "engine/fml/platform/win/errors_win.cc", "repo_id": "engine", "token_count": 663 }
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. #define FML_USED_ON_EMBEDDER #include "flutter/fml/raster_thread_merger.h" #include <utility> #include "flutter/fml/message_loop_impl.h" namespace fml { RasterThreadMerger::RasterThreadMerger(fml::TaskQueueId platform_queue_id, fml::TaskQueueId gpu_queue_id) : RasterThreadMerger( MakeRefCounted<SharedThreadMerger>(platform_queue_id, gpu_queue_id), platform_queue_id, gpu_queue_id) {} RasterThreadMerger::RasterThreadMerger( fml::RefPtr<fml::SharedThreadMerger> shared_merger, fml::TaskQueueId platform_queue_id, fml::TaskQueueId gpu_queue_id) : platform_queue_id_(platform_queue_id), gpu_queue_id_(gpu_queue_id), shared_merger_(std::move(shared_merger)) {} void RasterThreadMerger::SetMergeUnmergeCallback(const fml::closure& callback) { merge_unmerge_callback_ = callback; } const fml::RefPtr<fml::SharedThreadMerger>& RasterThreadMerger::GetSharedRasterThreadMerger() const { return shared_merger_; } fml::RefPtr<fml::RasterThreadMerger> RasterThreadMerger::CreateOrShareThreadMerger( const fml::RefPtr<fml::RasterThreadMerger>& parent_merger, TaskQueueId platform_id, TaskQueueId raster_id) { if (parent_merger && parent_merger->platform_queue_id_ == platform_id && parent_merger->gpu_queue_id_ == raster_id) { auto shared_merger = parent_merger->GetSharedRasterThreadMerger(); return fml::MakeRefCounted<RasterThreadMerger>(shared_merger, platform_id, raster_id); } else { return fml::MakeRefCounted<RasterThreadMerger>(platform_id, raster_id); } } void RasterThreadMerger::MergeWithLease(size_t lease_term) { std::scoped_lock lock(mutex_); if (TaskQueuesAreSame()) { return; } if (!IsEnabledUnSafe()) { return; } FML_DCHECK(lease_term > 0) << "lease_term should be positive."; if (IsMergedUnSafe()) { merged_condition_.notify_one(); return; } bool success = shared_merger_->MergeWithLease(this, lease_term); if (success && merge_unmerge_callback_ != nullptr) { merge_unmerge_callback_(); } merged_condition_.notify_one(); } void RasterThreadMerger::UnMergeNowIfLastOne() { std::scoped_lock lock(mutex_); if (TaskQueuesAreSame()) { return; } if (!IsEnabledUnSafe()) { return; } bool success = shared_merger_->UnMergeNowIfLastOne(this); if (success && merge_unmerge_callback_ != nullptr) { merge_unmerge_callback_(); } } bool RasterThreadMerger::IsOnPlatformThread() const { return MessageLoop::GetCurrentTaskQueueId() == platform_queue_id_; } bool RasterThreadMerger::IsOnRasterizingThread() { std::scoped_lock lock(mutex_); if (IsMergedUnSafe()) { return IsOnPlatformThread(); } else { return !IsOnPlatformThread(); } } void RasterThreadMerger::ExtendLeaseTo(size_t lease_term) { FML_DCHECK(lease_term > 0) << "lease_term should be positive."; if (TaskQueuesAreSame()) { return; } std::scoped_lock lock(mutex_); if (!IsEnabledUnSafe()) { return; } shared_merger_->ExtendLeaseTo(this, lease_term); } bool RasterThreadMerger::IsMerged() { std::scoped_lock lock(mutex_); return IsMergedUnSafe(); } void RasterThreadMerger::Enable() { std::scoped_lock lock(mutex_); shared_merger_->SetEnabledUnSafe(true); } void RasterThreadMerger::Disable() { std::scoped_lock lock(mutex_); shared_merger_->SetEnabledUnSafe(false); } bool RasterThreadMerger::IsEnabled() { std::scoped_lock lock(mutex_); return IsEnabledUnSafe(); } bool RasterThreadMerger::IsEnabledUnSafe() const { return shared_merger_->IsEnabledUnSafe(); } bool RasterThreadMerger::IsMergedUnSafe() const { return TaskQueuesAreSame() || shared_merger_->IsMergedUnSafe(); } bool RasterThreadMerger::TaskQueuesAreSame() const { return platform_queue_id_ == gpu_queue_id_; } void RasterThreadMerger::WaitUntilMerged() { if (TaskQueuesAreSame()) { return; } FML_CHECK(IsOnPlatformThread()); std::unique_lock<std::mutex> lock(mutex_); merged_condition_.wait(lock, [&] { return IsMergedUnSafe(); }); } RasterThreadStatus RasterThreadMerger::DecrementLease() { if (TaskQueuesAreSame()) { return RasterThreadStatus::kRemainsMerged; } std::scoped_lock lock(mutex_); if (!IsMergedUnSafe()) { return RasterThreadStatus::kRemainsUnmerged; } if (!IsEnabledUnSafe()) { return RasterThreadStatus::kRemainsMerged; } bool unmerged_after_decrement = shared_merger_->DecrementLease(this); if (unmerged_after_decrement) { if (merge_unmerge_callback_ != nullptr) { merge_unmerge_callback_(); } return RasterThreadStatus::kUnmergedNow; } return RasterThreadStatus::kRemainsMerged; } } // namespace fml
engine/fml/raster_thread_merger.cc/0
{ "file_path": "engine/fml/raster_thread_merger.cc", "repo_id": "engine", "token_count": 1923 }
183
// Copyright 2013 The Flutter 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_SYNCHRONIZATION_SEMAPHORE_H_ #define FLUTTER_FML_SYNCHRONIZATION_SEMAPHORE_H_ #include <memory> #include "flutter/fml/compiler_specific.h" #include "flutter/fml/macros.h" namespace fml { class PlatformSemaphore; //------------------------------------------------------------------------------ /// @brief A traditional counting semaphore. `Wait`s decrement the counter /// and `Signal` increments it. /// /// This is a cross-platform replacement for std::counting_semaphore /// which is only available since C++20. Once Flutter migrates past /// that point, this class should become obsolete and must be /// replaced. /// class Semaphore { public: //---------------------------------------------------------------------------- /// @brief Initializes the counting semaphore to a specified start count. /// /// @warning Callers must check if the handle could be successfully created /// by calling the `IsValid` method. `Wait`s on an invalid /// semaphore will always fail and signals will fail silently. /// /// @param[in] count The starting count of the counting semaphore. /// explicit Semaphore(uint32_t count); //---------------------------------------------------------------------------- /// @brief Destroy the counting semaphore. /// ~Semaphore(); //---------------------------------------------------------------------------- /// @brief Check if the underlying semaphore handle could be created. /// Failure modes are platform specific and may occur due to issue /// like handle exhaustion. All `Wait`s on invalid semaphore /// handles will fail and `Signal` calls will be ignored. /// /// @return True if valid, False otherwise. /// bool IsValid() const; //---------------------------------------------------------------------------- /// @brief Decrements the count and waits indefinitely if the value is /// less than zero for a `Signal`. /// /// @return If the `Wait` call was successful. See `IsValid` for failure. /// [[nodiscard]] bool Wait(); //---------------------------------------------------------------------------- /// @brief Decrement the counts if it is greater than zero. Returns false /// if the counter is already at zero. /// /// @warning False is also returned if the semaphore handle is invalid. /// Which makes doing the validity check before this call doubly /// important. /// /// @return If the count could be decremented. /// [[nodiscard]] bool TryWait(); //---------------------------------------------------------------------------- /// @brief Increment the count by one. Any pending `Wait`s will be /// resolved at this point. /// void Signal(); private: std::unique_ptr<PlatformSemaphore> impl_; FML_DISALLOW_COPY_AND_ASSIGN(Semaphore); }; } // namespace fml #endif // FLUTTER_FML_SYNCHRONIZATION_SEMAPHORE_H_
engine/fml/synchronization/semaphore.h/0
{ "file_path": "engine/fml/synchronization/semaphore.h", "repo_id": "engine", "token_count": 1015 }
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. #ifndef FLUTTER_FML_TASK_SOURCE_GRADE_H_ #define FLUTTER_FML_TASK_SOURCE_GRADE_H_ namespace fml { /** * Categories of work dispatched to `MessageLoopTaskQueues` dispatcher. By * specifying the `TaskSourceGrade`, you indicate the task's importance to the * dispatcher. */ enum class TaskSourceGrade { /// This `TaskSourceGrade` indicates that a task is critical to user /// interaction. kUserInteraction, /// This `TaskSourceGrade` indicates that a task corresponds to servicing a /// dart event loop task. These aren't critical to user interaction. kDartEventLoop, /// The absence of a specialized `TaskSourceGrade`. kUnspecified, }; } // namespace fml #endif // FLUTTER_FML_TASK_SOURCE_GRADE_H_
engine/fml/task_source_grade.h/0
{ "file_path": "engine/fml/task_source_grade.h", "repo_id": "engine", "token_count": 263 }
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. #include "flutter/fml/unique_fd.h" #include "flutter/fml/eintr_wrapper.h" namespace fml { namespace internal { #if FML_OS_WIN namespace os_win { std::mutex UniqueFDTraits::file_map_mutex; std::map<HANDLE, DirCacheEntry> UniqueFDTraits::file_map; void UniqueFDTraits::Free_Handle(HANDLE fd) { CloseHandle(fd); } } // namespace os_win #else // FML_OS_WIN namespace os_unix { void UniqueFDTraits::Free(int fd) { close(fd); } void UniqueDirTraits::Free(DIR* dir) { closedir(dir); } } // namespace os_unix #endif // FML_OS_WIN } // namespace internal } // namespace fml
engine/fml/unique_fd.cc/0
{ "file_path": "engine/fml/unique_fd.cc", "repo_id": "engine", "token_count": 283 }
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. #include "impeller/aiks/aiks_playground_inspector.h" #include <initializer_list> #include "impeller/core/capture.h" #include "impeller/entity/entity_pass.h" #include "impeller/renderer/context.h" #include "third_party/imgui/imgui.h" #include "third_party/imgui/imgui_internal.h" namespace impeller { static const char* kElementsWindowName = "Elements"; static const char* kPropertiesWindowName = "Properties"; static const std::initializer_list<std::string> kSupportedDocuments = { EntityPass::kCaptureDocumentName}; AiksInspector::AiksInspector() = default; const std::optional<Picture>& AiksInspector::RenderInspector( AiksContext& aiks_context, const std::function<std::optional<Picture>()>& picture_callback) { //---------------------------------------------------------------------------- /// Configure the next frame. /// RenderCapture(aiks_context.GetContext()->capture); //---------------------------------------------------------------------------- /// Configure the next frame. /// if (ImGui::IsKeyPressed(ImGuiKey_Z)) { wireframe_ = !wireframe_; aiks_context.GetContentContext().SetWireframe(wireframe_); } if (ImGui::IsKeyPressed(ImGuiKey_C)) { capturing_ = !capturing_; if (capturing_) { aiks_context.GetContext()->capture = CaptureContext::MakeAllowlist({kSupportedDocuments}); } } if (!capturing_) { hovered_element_ = nullptr; selected_element_ = nullptr; aiks_context.GetContext()->capture = CaptureContext::MakeInactive(); std::optional<Picture> new_picture = picture_callback(); // If the new picture doesn't have a pass, that means it was already moved // into the inspector. Simply re-emit the last received valid picture. if (!new_picture.has_value() || new_picture->pass) { last_picture_ = std::move(new_picture); } } return last_picture_; } void AiksInspector::HackResetDueToTextureLeaks() { last_picture_.reset(); } static const auto kPropertiesProcTable = CaptureProcTable{ .boolean = [](CaptureBooleanProperty& p) { ImGui::Checkbox(p.label.c_str(), &p.value); }, .integer = [](CaptureIntegerProperty& p) { if (p.options.range.has_value()) { ImGui::SliderInt(p.label.c_str(), &p.value, static_cast<int>(p.options.range->min), static_cast<int>(p.options.range->max)); return; } ImGui::InputInt(p.label.c_str(), &p.value); }, .scalar = [](CaptureScalarProperty& p) { if (p.options.range.has_value()) { ImGui::SliderFloat(p.label.c_str(), &p.value, p.options.range->min, p.options.range->max); return; } ImGui::DragFloat(p.label.c_str(), &p.value, 0.01); }, .point = [](CapturePointProperty& p) { if (p.options.range.has_value()) { ImGui::SliderFloat2(p.label.c_str(), reinterpret_cast<float*>(&p.value), p.options.range->min, p.options.range->max); return; } ImGui::DragFloat2(p.label.c_str(), reinterpret_cast<float*>(&p.value), 0.01); }, .vector3 = [](CaptureVector3Property& p) { if (p.options.range.has_value()) { ImGui::SliderFloat3(p.label.c_str(), reinterpret_cast<float*>(&p.value), p.options.range->min, p.options.range->max); return; } ImGui::DragFloat3(p.label.c_str(), reinterpret_cast<float*>(&p.value), 0.01); }, .rect = [](CaptureRectProperty& p) { ImGui::DragFloat4(p.label.c_str(), reinterpret_cast<float*>(&p.value), 0.01); }, .color = [](CaptureColorProperty& p) { ImGui::ColorEdit4(p.label.c_str(), reinterpret_cast<float*>(&p.value)); }, .matrix = [](CaptureMatrixProperty& p) { float* pointer = reinterpret_cast<float*>(&p.value); ImGui::DragFloat4((p.label + " X basis").c_str(), pointer, 0.001); ImGui::DragFloat4((p.label + " Y basis").c_str(), pointer + 4, 0.001); ImGui::DragFloat4((p.label + " Z basis").c_str(), pointer + 8, 0.001); ImGui::DragFloat4((p.label + " Translation").c_str(), pointer + 12, 0.001); }, .string = [](CaptureStringProperty& p) { ImGui::InputTextEx(p.label.c_str(), "", // Fine as long as it's read-only. const_cast<char*>(p.value.c_str()), p.value.size(), ImVec2(0, 0), ImGuiInputTextFlags_ReadOnly); }, }; void AiksInspector::RenderCapture(CaptureContext& capture_context) { if (!capturing_) { return; } auto document = capture_context.GetDocument(EntityPass::kCaptureDocumentName); //---------------------------------------------------------------------------- /// Setup a shared dockspace to collect the capture windows. /// ImGui::SetNextWindowBgAlpha(0.5); ImGui::Begin("Capture"); auto dockspace_id = ImGui::GetID("CaptureDockspace"); if (!ImGui::DockBuilderGetNode(dockspace_id)) { ImGui::SetWindowSize(ImVec2(370, 680)); ImGui::SetWindowPos(ImVec2(640, 55)); ImGui::DockBuilderRemoveNode(dockspace_id); ImGui::DockBuilderAddNode(dockspace_id); ImGuiID opposite_id; ImGuiID up_id = ImGui::DockBuilderSplitNode(dockspace_id, ImGuiDir_Up, 0.6, nullptr, &opposite_id); ImGuiID down_id = ImGui::DockBuilderSplitNode(opposite_id, ImGuiDir_Down, 0.0, nullptr, nullptr); ImGui::DockBuilderDockWindow(kElementsWindowName, up_id); ImGui::DockBuilderDockWindow(kPropertiesWindowName, down_id); ImGui::DockBuilderFinish(dockspace_id); } ImGui::DockSpace(dockspace_id); ImGui::End(); // Capture window. //---------------------------------------------------------------------------- /// Element hierarchy window. /// ImGui::Begin(kElementsWindowName); auto root_element = document.GetElement(); hovered_element_ = nullptr; if (root_element) { RenderCaptureElement(*root_element); } ImGui::End(); // Hierarchy window. if (selected_element_) { //---------------------------------------------------------------------------- /// Properties window. /// ImGui::Begin(kPropertiesWindowName); { selected_element_->properties.Iterate([&](CaptureProperty& property) { property.Invoke(kPropertiesProcTable); }); } ImGui::End(); // Inspector window. //---------------------------------------------------------------------------- /// Selected coverage highlighting. /// auto coverage_property = selected_element_->properties.FindFirstByLabel("Coverage"); if (coverage_property) { auto coverage = coverage_property->AsRect(); if (coverage.has_value()) { Scalar scale = ImGui::GetWindowDpiScale(); ImGui::GetBackgroundDrawList()->AddRect( ImVec2(coverage->GetLeft() / scale, coverage->GetTop() / scale), // p_min ImVec2(coverage->GetRight() / scale, coverage->GetBottom() / scale), // p_max 0x992222FF, // col 0.0, // rounding ImDrawFlags_None, // flags 8.0); // thickness } } } //---------------------------------------------------------------------------- /// Hover coverage highlight. /// if (hovered_element_) { auto coverage_property = hovered_element_->properties.FindFirstByLabel("Coverage"); if (coverage_property) { auto coverage = coverage_property->AsRect(); if (coverage.has_value()) { Scalar scale = ImGui::GetWindowDpiScale(); ImGui::GetBackgroundDrawList()->AddRect( ImVec2(coverage->GetLeft() / scale, coverage->GetTop() / scale), // p_min ImVec2(coverage->GetRight() / scale, coverage->GetBottom() / scale), // p_max 0x66FF2222, // col 0.0, // rounding ImDrawFlags_None, // flags 8.0); // thickness } } } } void AiksInspector::RenderCaptureElement(CaptureElement& element) { ImGui::PushID(&element); bool is_selected = selected_element_ == &element; bool has_children = element.children.Count() > 0; bool opened = ImGui::TreeNodeEx( element.label.c_str(), (is_selected ? ImGuiTreeNodeFlags_Selected : 0) | (has_children ? 0 : ImGuiTreeNodeFlags_Leaf) | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_DefaultOpen); if (ImGui::IsItemClicked()) { selected_element_ = &element; } if (ImGui::IsItemHovered()) { hovered_element_ = &element; } if (opened) { element.children.Iterate( [&](CaptureElement& child) { RenderCaptureElement(child); }); ImGui::TreePop(); } ImGui::PopID(); } } // namespace impeller
engine/impeller/aiks/aiks_playground_inspector.cc/0
{ "file_path": "engine/impeller/aiks/aiks_playground_inspector.cc", "repo_id": "engine", "token_count": 4524 }
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. #ifndef FLUTTER_IMPELLER_AIKS_IMAGE_H_ #define FLUTTER_IMPELLER_AIKS_IMAGE_H_ #include <memory> #include "flutter/fml/macros.h" #include "impeller/core/texture.h" namespace impeller { class Image { public: explicit Image(std::shared_ptr<Texture> texture); ~Image(); ISize GetSize() const; std::shared_ptr<Texture> GetTexture() const; private: const std::shared_ptr<Texture> texture_; Image(const Image&) = delete; Image& operator=(const Image&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_AIKS_IMAGE_H_
engine/impeller/aiks/image.h/0
{ "file_path": "engine/impeller/aiks/image.h", "repo_id": "engine", "token_count": 256 }
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 <sstream> #include "flutter/testing/testing.h" #include "impeller/aiks/trace_serializer.h" namespace impeller { namespace testing { TEST(TraceSerializer, Save) { CanvasRecorder<TraceSerializer> recorder; std::ostringstream ss; fml::LogMessage::CaptureNextLog(&ss); recorder.Save(); ASSERT_TRUE(ss.str().size() > 0); } } // namespace testing } // namespace impeller
engine/impeller/aiks/trace_serializer_unittests.cc/0
{ "file_path": "engine/impeller/aiks/trace_serializer_unittests.cc", "repo_id": "engine", "token_count": 180 }
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. #ifndef FLUTTER_IMPELLER_BASE_THREAD_H_ #define FLUTTER_IMPELLER_BASE_THREAD_H_ #include <chrono> #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <thread> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "flutter/fml/synchronization/shared_mutex.h" #include "impeller/base/thread_safety.h" namespace impeller { class ConditionVariable; class IPLR_CAPABILITY("mutex") Mutex { public: Mutex() = default; ~Mutex() = default; void Lock() IPLR_ACQUIRE() { mutex_.lock(); } void Unlock() IPLR_RELEASE() { mutex_.unlock(); } private: friend class ConditionVariable; std::mutex mutex_; Mutex(const Mutex&) = delete; Mutex(Mutex&&) = delete; Mutex& operator=(const Mutex&) = delete; Mutex& operator=(Mutex&&) = delete; }; class IPLR_CAPABILITY("mutex") RWMutex { public: RWMutex() : mutex_(std::unique_ptr<fml::SharedMutex>(fml::SharedMutex::Create())) {} ~RWMutex() = default; void LockWriter() IPLR_ACQUIRE() { mutex_->Lock(); } void UnlockWriter() IPLR_RELEASE() { mutex_->Unlock(); } void LockReader() IPLR_ACQUIRE_SHARED() { mutex_->LockShared(); } void UnlockReader() IPLR_RELEASE_SHARED() { mutex_->UnlockShared(); } private: std::unique_ptr<fml::SharedMutex> mutex_; RWMutex(const RWMutex&) = delete; RWMutex(RWMutex&&) = delete; RWMutex& operator=(const RWMutex&) = delete; RWMutex& operator=(RWMutex&&) = delete; }; class IPLR_SCOPED_CAPABILITY Lock { public: explicit Lock(Mutex& mutex) IPLR_ACQUIRE(mutex) : mutex_(mutex) { mutex_.Lock(); } ~Lock() IPLR_RELEASE() { mutex_.Unlock(); } private: Mutex& mutex_; Lock(const Lock&) = delete; Lock(Lock&&) = delete; Lock& operator=(const Lock&) = delete; Lock& operator=(Lock&&) = delete; }; class IPLR_SCOPED_CAPABILITY ReaderLock { public: explicit ReaderLock(RWMutex& mutex) IPLR_ACQUIRE_SHARED(mutex) : mutex_(mutex) { mutex_.LockReader(); } ~ReaderLock() IPLR_RELEASE() { mutex_.UnlockReader(); } private: RWMutex& mutex_; ReaderLock(const ReaderLock&) = delete; ReaderLock(ReaderLock&&) = delete; ReaderLock& operator=(const ReaderLock&) = delete; ReaderLock& operator=(ReaderLock&&) = delete; }; class IPLR_SCOPED_CAPABILITY WriterLock { public: explicit WriterLock(RWMutex& mutex) IPLR_ACQUIRE(mutex) : mutex_(mutex) { mutex_.LockWriter(); } ~WriterLock() IPLR_RELEASE() { mutex_.UnlockWriter(); } private: RWMutex& mutex_; WriterLock(const WriterLock&) = delete; WriterLock(WriterLock&&) = delete; WriterLock& operator=(const WriterLock&) = delete; WriterLock& operator=(WriterLock&&) = delete; }; //------------------------------------------------------------------------------ /// @brief A condition variable exactly similar to the one in libcxx with /// two major differences: /// /// * On the Wait, WaitFor, and WaitUntil calls, static analysis /// annotation are respected. /// * There is no ability to wait on a condition variable and also /// be susceptible to spurious wakes. This is because the /// predicate is mandatory. /// class ConditionVariable { public: ConditionVariable() = default; ~ConditionVariable() = default; ConditionVariable(const ConditionVariable&) = delete; ConditionVariable& operator=(const ConditionVariable&) = delete; void NotifyOne() { cv_.notify_one(); } void NotifyAll() { cv_.notify_all(); } using Predicate = std::function<bool()>; //---------------------------------------------------------------------------- /// @brief Atomically unlocks the mutex and waits on the condition /// variable up to a specified time point. Lock will be reacquired /// when the wait exits. Spurious wakes may happen before the time /// point is reached. In such cases the predicate is invoked and /// it must return `false` for the wait to continue. The predicate /// will be invoked with the mutex locked. /// /// @note Since the predicate is invoked with the mutex locked, if it /// accesses other guarded resources, the predicate itself must be /// decorated with the IPLR_REQUIRES directive. For instance, /// /// ```c++ /// [] () IPLR_REQUIRES(mutex) { /// return my_guarded_resource.should_stop_waiting; /// } /// ``` /// /// @param mutex The mutex. /// @param[in] time_point The time point to wait to. /// @param[in] should_stop_waiting The predicate invoked on spurious wakes. /// Must return false for the wait to /// continue. /// /// @tparam Clock The clock type. /// @tparam Duration The duration type. /// /// @return The value of the predicate at the end of the wait. /// template <class Clock, class Duration> bool WaitUntil(Mutex& mutex, const std::chrono::time_point<Clock, Duration>& time_point, const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { std::unique_lock lock(mutex.mutex_, std::adopt_lock); const auto result = cv_.wait_until(lock, time_point, should_stop_waiting); lock.release(); return result; } //---------------------------------------------------------------------------- /// @brief Atomically unlocks the mutex and waits on the condition /// variable for a designated duration. Lock will be reacquired /// when the wait exits. Spurious wakes may happen before the time /// point is reached. In such cases the predicate is invoked and /// it must return `false` for the wait to continue. The predicate /// will be invoked with the mutex locked. /// /// @note Since the predicate is invoked with the mutex locked, if it /// accesses other guarded resources, the predicate itself must be /// decorated with the IPLR_REQUIRES directive. For instance, /// /// ```c++ /// [] () IPLR_REQUIRES(mutex) { /// return my_guarded_resource.should_stop_waiting; /// } /// ``` /// /// @param mutex The mutex. /// @param[in] duration The duration to wait for. /// @param[in] should_stop_waiting The predicate invoked on spurious wakes. /// Must return false for the wait to /// continue. /// /// @tparam Representation The duration representation type. /// @tparam Period The duration period type. /// /// @return The value of the predicate at the end of the wait. /// template <class Representation, class Period> bool WaitFor(Mutex& mutex, const std::chrono::duration<Representation, Period>& duration, const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { return WaitUntil(mutex, std::chrono::steady_clock::now() + duration, should_stop_waiting); } //---------------------------------------------------------------------------- /// @brief Atomically unlocks the mutex and waits on the condition /// variable indefinitely till the predicate determines that the /// wait must end. Lock will be reacquired when the wait exits. /// Spurious wakes may happen before the time point is reached. In /// such cases the predicate is invoked and it must return `false` /// for the wait to continue. The predicate will be invoked with /// the mutex locked. /// /// @note Since the predicate is invoked with the mutex locked, if it /// accesses other guarded resources, the predicate itself must be /// decorated with the IPLR_REQUIRES directive. For instance, /// /// ```c++ /// [] () IPLR_REQUIRES(mutex) { /// return my_guarded_resource.should_stop_waiting; /// } /// ``` /// /// @param mutex The mutex /// @param[in] should_stop_waiting The should stop waiting /// void Wait(Mutex& mutex, const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { std::unique_lock lock(mutex.mutex_, std::adopt_lock); cv_.wait(lock, should_stop_waiting); lock.release(); } private: std::condition_variable cv_; }; } // namespace impeller #endif // FLUTTER_IMPELLER_BASE_THREAD_H_
engine/impeller/base/thread.h/0
{ "file_path": "engine/impeller/base/thread.h", "repo_id": "engine", "token_count": 3483 }
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. #ifndef FLUTTER_IMPELLER_COMPILER_COMPILER_TEST_H_ #define FLUTTER_IMPELLER_COMPILER_COMPILER_TEST_H_ #include "flutter/fml/macros.h" #include "flutter/testing/testing.h" #include "impeller/base/validation.h" #include "impeller/compiler/compiler.h" #include "impeller/compiler/source_options.h" #include "impeller/compiler/types.h" namespace impeller { namespace compiler { namespace testing { class CompilerTest : public ::testing::TestWithParam<TargetPlatform> { public: CompilerTest(); ~CompilerTest(); std::unique_ptr<fml::FileMapping> GetReflectionJson( const char* fixture_name) const; std::unique_ptr<fml::FileMapping> GetShaderFile( const char* fixture_name, TargetPlatform platform) const; bool CanCompileAndReflect( const char* fixture_name, SourceType source_type = SourceType::kUnknown, SourceLanguage source_language = SourceLanguage::kGLSL, const char* entry_point_name = "main") const; private: std::string intermediates_path_; fml::UniqueFD intermediates_directory_; CompilerTest(const CompilerTest&) = delete; CompilerTest& operator=(const CompilerTest&) = delete; }; } // namespace testing } // namespace compiler } // namespace impeller #endif // FLUTTER_IMPELLER_COMPILER_COMPILER_TEST_H_
engine/impeller/compiler/compiler_test.h/0
{ "file_path": "engine/impeller/compiler/compiler_test.h", "repo_id": "engine", "token_count": 512 }
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_COMPILER_SHADER_BUNDLE_DATA_H_ #define FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_ #include <memory> #include <vector> #include "flutter/fml/mapping.h" #include "impeller/compiler/types.h" #include "impeller/shader_bundle/shader_bundle_flatbuffers.h" namespace impeller { namespace compiler { class ShaderBundleData { public: struct ShaderUniformStructField { std::string name; spirv_cross::SPIRType::BaseType type = spirv_cross::SPIRType::BaseType::Float; size_t offset_in_bytes = 0u; size_t element_size_in_bytes = 0u; size_t total_size_in_bytes = 0u; std::optional<size_t> array_elements = std::nullopt; }; struct ShaderUniformStruct { std::string name; size_t ext_res_0 = 0u; size_t set = 0u; size_t binding = 0u; size_t size_in_bytes = 0u; std::vector<ShaderUniformStructField> fields; }; struct ShaderUniformTexture { std::string name; size_t ext_res_0 = 0u; size_t set = 0u; size_t binding = 0u; }; ShaderBundleData(std::string entrypoint, spv::ExecutionModel stage, TargetPlatform target_platform); ~ShaderBundleData(); void AddUniformStruct(ShaderUniformStruct uniform_struct); void AddUniformTexture(ShaderUniformTexture uniform_texture); void AddInputDescription(InputDescription input); void SetShaderData(std::shared_ptr<fml::Mapping> shader); void SetSkSLData(std::shared_ptr<fml::Mapping> sksl); std::unique_ptr<fb::shaderbundle::BackendShaderT> CreateFlatbuffer() const; private: const std::string entrypoint_; const spv::ExecutionModel stage_; const TargetPlatform target_platform_; std::vector<ShaderUniformStruct> uniform_structs_; std::vector<ShaderUniformTexture> uniform_textures_; std::vector<InputDescription> inputs_; std::shared_ptr<fml::Mapping> shader_; std::shared_ptr<fml::Mapping> sksl_; ShaderBundleData(const ShaderBundleData&) = delete; ShaderBundleData& operator=(const ShaderBundleData&) = delete; }; } // namespace compiler } // namespace impeller #endif // FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_
engine/impeller/compiler/shader_bundle_data.h/0
{ "file_path": "engine/impeller/compiler/shader_bundle_data.h", "repo_id": "engine", "token_count": 885 }
192
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Parallel exclusive prefix sum computes the prefix in place in storage. // BLOCK_SIZE is the overall storage size while ident must be the global // x identifier. #define ExclusivePrefixSum(ident, storage, BLOCK_SIZE) \ do { \ uint offset = 1; \ for (uint n = BLOCK_SIZE / 2; n > 0; n /= 2) { \ if (ident < n) { \ uint ai = offset * (2 * ident + 1) - 1; \ uint bi = offset * (2 * ident + 2) - 1; \ storage[bi] += storage[ai]; \ } \ offset *= 2; \ barrier(); \ } \ \ if (ident == 0) { \ storage[BLOCK_SIZE - 1] = 0; \ } \ barrier(); \ \ for (uint n = 1; n < BLOCK_SIZE; n *= 2) { \ offset /= 2; \ barrier(); \ if (ident < n) { \ uint ai = offset * (2 * ident + 1) - 1; \ uint bi = offset * (2 * ident + 2) - 1; \ uint temp = storage[ai]; \ storage[ai] = storage[bi]; \ storage[bi] += temp; \ } \ } \ barrier(); \ } while (false)
engine/impeller/compiler/shader_lib/impeller/prefix_sum.glsl/0
{ "file_path": "engine/impeller/compiler/shader_lib/impeller/prefix_sum.glsl", "repo_id": "engine", "token_count": 1393 }
193
// Copyright 2013 The Flutter 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/uniform_sorter.h" #include <cstdint> namespace impeller { std::vector<spirv_cross::ID> SortUniforms( const spirv_cross::ParsedIR* ir, const spirv_cross::Compiler* compiler, std::optional<spirv_cross::SPIRType::BaseType> type_filter, bool include) { // Sort the IR so that the uniforms are in declaration order. std::vector<spirv_cross::ID> uniforms; ir->for_each_typed_id<spirv_cross::SPIRVariable>( [&](uint32_t, const spirv_cross::SPIRVariable& var) { if (var.storage != spv::StorageClassUniformConstant) { return; } const auto& type = compiler->get_type(var.basetype); if (!type_filter.has_value() || (include && type_filter.value() == type.basetype) || (!include && type_filter.value() != type.basetype)) { uniforms.push_back(var.self); } }); auto compare_locations = [&ir](spirv_cross::ID id1, spirv_cross::ID id2) { auto& flags1 = ir->get_decoration_bitset(id1); auto& flags2 = ir->get_decoration_bitset(id2); // Put the uniforms with no location after the ones that have a location. if (!flags1.get(spv::Decoration::DecorationLocation)) { return false; } if (!flags2.get(spv::Decoration::DecorationLocation)) { return true; } // Sort in increasing order of location. return ir->get_decoration(id1, spv::Decoration::DecorationLocation) < ir->get_decoration(id2, spv::Decoration::DecorationLocation); }; std::sort(uniforms.begin(), uniforms.end(), compare_locations); return uniforms; } } // namespace impeller
engine/impeller/compiler/uniform_sorter.cc/0
{ "file_path": "engine/impeller/compiler/uniform_sorter.cc", "repo_id": "engine", "token_count": 694 }
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. #include "impeller/core/formats.h" #include <sstream> #include "impeller/base/strings.h" #include "impeller/base/validation.h" #include "impeller/core/texture.h" namespace impeller { constexpr bool StoreActionNeedsResolveTexture(StoreAction action) { switch (action) { case StoreAction::kDontCare: case StoreAction::kStore: return false; case StoreAction::kMultisampleResolve: case StoreAction::kStoreAndMultisampleResolve: return true; } } bool Attachment::IsValid() const { if (!texture || !texture->IsValid()) { VALIDATION_LOG << "Attachment has no texture."; return false; } if (StoreActionNeedsResolveTexture(store_action)) { if (!resolve_texture || !resolve_texture->IsValid()) { VALIDATION_LOG << "Store action needs resolve but no valid resolve " "texture specified."; return false; } } if (resolve_texture) { if (store_action != StoreAction::kMultisampleResolve && store_action != StoreAction::kStoreAndMultisampleResolve) { VALIDATION_LOG << "A resolve texture was specified, but the store action " "doesn't include multisample resolve."; return false; } if (texture->GetTextureDescriptor().storage_mode == StorageMode::kDeviceTransient && store_action == StoreAction::kStoreAndMultisampleResolve) { VALIDATION_LOG << "The multisample texture cannot be transient when " "specifying the StoreAndMultisampleResolve StoreAction."; } } auto storage_mode = resolve_texture ? resolve_texture->GetTextureDescriptor().storage_mode : texture->GetTextureDescriptor().storage_mode; if (storage_mode == StorageMode::kDeviceTransient) { if (load_action == LoadAction::kLoad) { VALIDATION_LOG << "The LoadAction cannot be Load when attaching a device " "transient " + std::string(resolve_texture ? "resolve texture." : "texture."); return false; } if (store_action != StoreAction::kDontCare) { VALIDATION_LOG << "The StoreAction must be DontCare when attaching a " "device transient " + std::string(resolve_texture ? "resolve texture." : "texture."); return false; } } return true; } std::string TextureUsageMaskToString(TextureUsageMask mask) { std::vector<TextureUsage> usages; if (mask & TextureUsage::kShaderRead) { usages.push_back(TextureUsage::kShaderRead); } if (mask & TextureUsage::kShaderWrite) { usages.push_back(TextureUsage::kShaderWrite); } if (mask & TextureUsage::kRenderTarget) { usages.push_back(TextureUsage::kRenderTarget); } std::stringstream stream; stream << "{ "; for (size_t i = 0; i < usages.size(); i++) { stream << TextureUsageToString(usages[i]); if (i != usages.size() - 1u) { stream << ", "; } } stream << " }"; return stream.str(); } std::string AttachmentToString(const Attachment& attachment) { std::stringstream stream; if (attachment.texture) { stream << "Texture=(" << TextureDescriptorToString( attachment.texture->GetTextureDescriptor()) << "),"; } if (attachment.resolve_texture) { stream << "ResolveTexture=(" << TextureDescriptorToString( attachment.resolve_texture->GetTextureDescriptor()) << "),"; } stream << "LoadAction=" << LoadActionToString(attachment.load_action) << ","; stream << "StoreAction=" << StoreActionToString(attachment.store_action); return stream.str(); } std::string ColorAttachmentToString(const ColorAttachment& color) { std::stringstream stream; stream << AttachmentToString(color) << ","; stream << "ClearColor=(" << ColorToString(color.clear_color) << ")"; return stream.str(); } std::string DepthAttachmentToString(const DepthAttachment& depth) { std::stringstream stream; stream << AttachmentToString(depth) << ","; stream << "ClearDepth=" << SPrintF("%.2f", depth.clear_depth); return stream.str(); } std::string StencilAttachmentToString(const StencilAttachment& stencil) { std::stringstream stream; stream << AttachmentToString(stencil) << ","; stream << "ClearStencil=" << stencil.clear_stencil; return stream.str(); } } // namespace impeller
engine/impeller/core/formats.cc/0
{ "file_path": "engine/impeller/core/formats.cc", "repo_id": "engine", "token_count": 1864 }
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. #include "impeller/display_list/dl_vertices_geometry.h" #include "display_list/dl_vertices.h" #include "impeller/display_list/skia_conversions.h" #include "impeller/entity/geometry/vertices_geometry.h" #include "impeller/geometry/point.h" #include "third_party/skia/include/core/SkPoint.h" #include "third_party/skia/include/core/SkRect.h" namespace impeller { static Rect ToRect(const SkRect& rect) { return Rect::MakeLTRB(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom); } static VerticesGeometry::VertexMode ToVertexMode(flutter::DlVertexMode mode) { switch (mode) { case flutter::DlVertexMode::kTriangles: return VerticesGeometry::VertexMode::kTriangles; case flutter::DlVertexMode::kTriangleStrip: return VerticesGeometry::VertexMode::kTriangleStrip; case flutter::DlVertexMode::kTriangleFan: return VerticesGeometry::VertexMode::kTriangleFan; }; } std::shared_ptr<impeller::VerticesGeometry> MakeVertices( const flutter::DlVertices* vertices) { auto bounds = ToRect(vertices->bounds()); auto mode = ToVertexMode(vertices->mode()); std::vector<Point> positions(vertices->vertex_count()); for (auto i = 0; i < vertices->vertex_count(); i++) { positions[i] = skia_conversions::ToPoint(vertices->vertices()[i]); } std::vector<uint16_t> indices(vertices->index_count()); for (auto i = 0; i < vertices->index_count(); i++) { indices[i] = vertices->indices()[i]; } std::vector<Color> colors; if (vertices->colors()) { colors.reserve(vertices->vertex_count()); for (auto i = 0; i < vertices->vertex_count(); i++) { colors.push_back( skia_conversions::ToColor(vertices->colors()[i]).Premultiply()); } } std::vector<Point> texture_coordinates; if (vertices->texture_coordinates()) { texture_coordinates.reserve(vertices->vertex_count()); for (auto i = 0; i < vertices->vertex_count(); i++) { texture_coordinates.push_back( skia_conversions::ToPoint(vertices->texture_coordinates()[i])); } } return std::make_shared<VerticesGeometry>( positions, indices, texture_coordinates, colors, bounds, mode); } } // namespace impeller
engine/impeller/display_list/dl_vertices_geometry.cc/0
{ "file_path": "engine/impeller/display_list/dl_vertices_geometry.cc", "repo_id": "engine", "token_count": 871 }
196
# How Impeller Works Around The Lack of Uniform Buffers in Open GL ES 2.0. The Impeller Renderer API allows callers to specify uniform data in a discrete buffer. Indeed, it is conventional for the higher level layers of the Impeller stack to specify all uniform data for a render pass in a single buffer. This jumbo buffer is allocated using a simple bump allocator on the host before being transferred over to VRAM. The ImpellerC reflection engine generates structs with the correct padding and alignment such that the caller can just populate uniform struct members and `memcpy` them into the jumbo buffer, or use placement-new. Placement-new is used in cases where device buffers can be memory mapped into the client address space. This works extremely well when using a modern rendering backend like Metal. However, OpenGL ES 2.0 does not support uniform buffer objects. Instead, uniform data must be specified to GL from the client side using the `glUniform*` family of APIs. This poses a problem for the OpenGL backend implementation. From a view (an offset and range) into a buffer pointing to uniform data, it must infer the right uniform locations within a program object and bind uniform data at the right offsets within the buffer view. Since command generation is strongly typed, a pointer to metadata about the uniform information is stashed along with the buffer view in the command stream. This metadata is generated by the offline reflection engine part of ImpellerC. The metadata is usually a collection of items the runtime would need to infer the right `glUniform*` calls. An item in this collection would look like the following: ``` struct ShaderStructMemberMetadata { ShaderType type; // the data type (bool, int, float, etc.) std::string name; // the uniform member name "frame_info.mvp" size_t offset; size_t size; size_t array_elements; }; ``` Using this mechanism, the runtime knows how to specify data from a buffer view to GL. But, this is still not sufficient as the buffer bindings are not known until after program link time. To solve this issue, Impeller queries all active uniforms after program link time using `glGet` with `GL_ACTIVE_UNIFORMS`. It then iterates over these uniforms and notes their location using `glGetUniformLocation`. This uniform location in the program is mapped to the reflection engine's notion of the uniform location in the pipeline. This mapping is maintained in the pipeline state generated once during the Impeller runtime setup. In this way, even though there is no explicit notion of a pipeline state object in OpenGL ES, Impeller still maintains one for this backend. Since all commands in the command stream reference the pipeline state object associated with the command, the render pass implementation in the OpenGL ES 2 backend can access the uniform bindings map and use that to bind uniforms using the pointer to metadata already located next to the commands' uniform buffer views. And that’s it. This is convoluted in its implementation, but the higher levels of the tech stack don’t have to care about not having access to uniform buffer objects. Moreover, all the reflection happens offline and reflection information is specified in the command stream via just a pointer. The uniform bindings map is also generated just once during the setup of the faux pipeline state object. This makes the whole scheme extremely low overhead. Moreover, in a modern backend with uniform buffers, this mechanism is entirely irrelevant.
engine/impeller/docs/ubo_gles2.md/0
{ "file_path": "engine/impeller/docs/ubo_gles2.md", "repo_id": "engine", "token_count": 802 }
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_ENTITY_CONTENTS_CONICAL_GRADIENT_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_CONICAL_GRADIENT_CONTENTS_H_ #include <functional> #include <memory> #include <vector> #include "flutter/fml/macros.h" #include "impeller/entity/contents/color_source_contents.h" #include "impeller/entity/entity.h" #include "impeller/geometry/color.h" #include "impeller/geometry/gradient.h" #include "impeller/geometry/path.h" #include "impeller/geometry/point.h" namespace impeller { class ConicalGradientContents final : public ColorSourceContents { public: ConicalGradientContents(); ~ConicalGradientContents() override; // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; // |Contents| [[nodiscard]] bool ApplyColorFilter( const ColorFilterProc& color_filter_proc) override; void SetCenterAndRadius(Point center, Scalar radius); void SetColors(std::vector<Color> colors); void SetStops(std::vector<Scalar> stops); const std::vector<Color>& GetColors() const; const std::vector<Scalar>& GetStops() const; void SetTileMode(Entity::TileMode tile_mode); void SetFocus(std::optional<Point> focus, Scalar radius); private: bool RenderTexture(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const; bool RenderSSBO(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const; Point center_; Scalar radius_ = 0.0f; std::vector<Color> colors_; std::vector<Scalar> stops_; Entity::TileMode tile_mode_; Color decal_border_color_ = Color::BlackTransparent(); std::optional<Point> focus_; Scalar focus_radius_ = 0.0f; ConicalGradientContents(const ConicalGradientContents&) = delete; ConicalGradientContents& operator=(const ConicalGradientContents&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_CONICAL_GRADIENT_CONTENTS_H_
engine/impeller/entity/contents/conical_gradient_contents.h/0
{ "file_path": "engine/impeller/entity/contents/conical_gradient_contents.h", "repo_id": "engine", "token_count": 801 }
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 "impeller/entity/contents/filters/gaussian_blur_filter_contents.h" #include <cmath> #include "flutter/fml/make_copyable.h" #include "impeller/entity/contents/clip_contents.h" #include "impeller/entity/contents/color_source_contents.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/texture_fill.frag.h" #include "impeller/entity/texture_fill.vert.h" #include "impeller/renderer/command.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/texture_mipmap.h" #include "impeller/renderer/vertex_buffer_builder.h" namespace impeller { using GaussianBlurVertexShader = KernelPipeline::VertexShader; using GaussianBlurFragmentShader = KernelPipeline::FragmentShader; const int32_t GaussianBlurFilterContents::kBlurFilterRequiredMipCount = 4; namespace { // 48 comes from kernel.glsl. const int32_t kMaxKernelSize = 48; SamplerDescriptor MakeSamplerDescriptor(MinMagFilter filter, SamplerAddressMode address_mode) { SamplerDescriptor sampler_desc; sampler_desc.min_filter = filter; sampler_desc.mag_filter = filter; sampler_desc.width_address_mode = address_mode; sampler_desc.height_address_mode = address_mode; return sampler_desc; } template <typename T> void BindVertices(RenderPass& pass, HostBuffer& host_buffer, std::initializer_list<typename T::PerVertexData>&& vertices) { VertexBufferBuilder<typename T::PerVertexData> vtx_builder; vtx_builder.AddVertices(vertices); pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer)); } void SetTileMode(SamplerDescriptor* descriptor, const ContentContext& renderer, Entity::TileMode tile_mode) { switch (tile_mode) { case Entity::TileMode::kDecal: if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { descriptor->width_address_mode = SamplerAddressMode::kDecal; descriptor->height_address_mode = SamplerAddressMode::kDecal; } break; case Entity::TileMode::kClamp: descriptor->width_address_mode = SamplerAddressMode::kClampToEdge; descriptor->height_address_mode = SamplerAddressMode::kClampToEdge; break; case Entity::TileMode::kMirror: descriptor->width_address_mode = SamplerAddressMode::kMirror; descriptor->height_address_mode = SamplerAddressMode::kMirror; break; case Entity::TileMode::kRepeat: descriptor->width_address_mode = SamplerAddressMode::kRepeat; descriptor->height_address_mode = SamplerAddressMode::kRepeat; break; } } /// Makes a subpass that will render the scaled down input and add the /// transparent gutter required for the blur halo. fml::StatusOr<RenderTarget> MakeDownsampleSubpass( const ContentContext& renderer, std::shared_ptr<Texture> input_texture, const SamplerDescriptor& sampler_descriptor, const Quad& uvs, const ISize& subpass_size, Entity::TileMode tile_mode) { ContentContext::SubpassCallback subpass_callback = [&](const ContentContext& renderer, RenderPass& pass) { HostBuffer& host_buffer = renderer.GetTransientsBuffer(); pass.SetCommandLabel("Gaussian blur downsample"); auto pipeline_options = OptionsFromPass(pass); pipeline_options.primitive_type = PrimitiveType::kTriangleStrip; pass.SetPipeline(renderer.GetTexturePipeline(pipeline_options)); TextureFillVertexShader::FrameInfo frame_info; frame_info.depth = 0.0; frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)); frame_info.texture_sampler_y_coord_scale = 1.0; frame_info.alpha = 1.0; BindVertices<TextureFillVertexShader>(pass, host_buffer, { {Point(0, 0), uvs[0]}, {Point(1, 0), uvs[1]}, {Point(0, 1), uvs[2]}, {Point(1, 1), uvs[3]}, }); SamplerDescriptor linear_sampler_descriptor = sampler_descriptor; SetTileMode(&linear_sampler_descriptor, renderer, tile_mode); linear_sampler_descriptor.mag_filter = MinMagFilter::kLinear; linear_sampler_descriptor.min_filter = MinMagFilter::kLinear; TextureFillVertexShader::BindFrameInfo( pass, host_buffer.EmplaceUniform(frame_info)); TextureFillFragmentShader::BindTextureSampler( pass, input_texture, renderer.GetContext()->GetSamplerLibrary()->GetSampler( linear_sampler_descriptor)); return pass.Draw().ok(); }; fml::StatusOr<RenderTarget> render_target = renderer.MakeSubpass( "Gaussian Blur Filter", subpass_size, subpass_callback); return render_target; } fml::StatusOr<RenderTarget> MakeBlurSubpass( const ContentContext& renderer, const RenderTarget& input_pass, const SamplerDescriptor& sampler_descriptor, Entity::TileMode tile_mode, const BlurParameters& blur_info, std::optional<RenderTarget> destination_target, const Quad& blur_uvs) { if (blur_info.blur_sigma < kEhCloseEnough) { return input_pass; } std::shared_ptr<Texture> input_texture = input_pass.GetRenderTargetTexture(); // TODO(gaaclarke): This blurs the whole image, but because we know the clip // region we could focus on just blurring that. ISize subpass_size = input_texture->GetSize(); ContentContext::SubpassCallback subpass_callback = [&](const ContentContext& renderer, RenderPass& pass) { GaussianBlurVertexShader::FrameInfo frame_info{ .mvp = Matrix::MakeOrthographic(ISize(1, 1)), .texture_sampler_y_coord_scale = 1.0}; HostBuffer& host_buffer = renderer.GetTransientsBuffer(); ContentContextOptions options = OptionsFromPass(pass); options.primitive_type = PrimitiveType::kTriangleStrip; if (tile_mode == Entity::TileMode::kDecal && !renderer.GetDeviceCapabilities() .SupportsDecalSamplerAddressMode()) { pass.SetPipeline(renderer.GetKernelDecalPipeline(options)); } else { pass.SetPipeline(renderer.GetKernelPipeline(options)); } BindVertices<GaussianBlurVertexShader>(pass, host_buffer, { {blur_uvs[0], blur_uvs[0]}, {blur_uvs[1], blur_uvs[1]}, {blur_uvs[2], blur_uvs[2]}, {blur_uvs[3], blur_uvs[3]}, }); SamplerDescriptor linear_sampler_descriptor = sampler_descriptor; linear_sampler_descriptor.mag_filter = MinMagFilter::kLinear; linear_sampler_descriptor.min_filter = MinMagFilter::kLinear; GaussianBlurFragmentShader::BindTextureSampler( pass, input_texture, renderer.GetContext()->GetSamplerLibrary()->GetSampler( linear_sampler_descriptor)); GaussianBlurVertexShader::BindFrameInfo( pass, host_buffer.EmplaceUniform(frame_info)); KernelPipeline::FragmentShader::KernelSamples kernel_samples = LerpHackKernelSamples(GenerateBlurInfo(blur_info)); FML_CHECK(kernel_samples.sample_count < kMaxKernelSize); GaussianBlurFragmentShader::BindKernelSamples( pass, host_buffer.EmplaceUniform(kernel_samples)); return pass.Draw().ok(); }; if (destination_target.has_value()) { return renderer.MakeSubpass("Gaussian Blur Filter", destination_target.value(), subpass_callback); } else { return renderer.MakeSubpass("Gaussian Blur Filter", subpass_size, subpass_callback); } } /// Returns `rect` relative to `reference`, where Rect::MakeXYWH(0,0,1,1) will /// be returned when `rect` == `reference`. Rect MakeReferenceUVs(const Rect& reference, const Rect& rect) { Rect result = Rect::MakeOriginSize(rect.GetOrigin() - reference.GetOrigin(), rect.GetSize()); return result.Scale(1.0f / Vector2(reference.GetSize())); } int ScaleBlurRadius(Scalar radius, Scalar scalar) { return static_cast<int>(std::round(radius * scalar)); } Entity ApplyClippedBlurStyle(Entity::ClipOperation clip_operation, const Entity& entity, const std::shared_ptr<FilterInput>& input, const Snapshot& input_snapshot, Entity blur_entity, const std::shared_ptr<Geometry>& geometry) { auto clip_contents = std::make_shared<ClipContents>(); clip_contents->SetClipOperation(clip_operation); clip_contents->SetGeometry(geometry); Entity clipper; clipper.SetContents(clip_contents); auto restore = std::make_unique<ClipRestoreContents>(); Matrix entity_transform = entity.GetTransform(); Matrix blur_transform = blur_entity.GetTransform(); auto renderer = fml::MakeCopyable( [blur_entity = blur_entity.Clone(), clipper = std::move(clipper), restore = std::move(restore), entity_transform, blur_transform](const ContentContext& renderer, const Entity& entity, RenderPass& pass) mutable { bool result = true; clipper.SetNewClipDepth(entity.GetNewClipDepth()); clipper.SetTransform(entity.GetTransform() * entity_transform); result = clipper.Render(renderer, pass) && result; blur_entity.SetNewClipDepth(entity.GetNewClipDepth()); blur_entity.SetTransform(entity.GetTransform() * blur_transform); result = blur_entity.Render(renderer, pass) && result; if constexpr (!ContentContext::kEnableStencilThenCover) { result = restore->Render(renderer, entity, pass) && result; } return result; }); auto coverage = fml::MakeCopyable([blur_entity = std::move(blur_entity), blur_transform](const Entity& entity) mutable { blur_entity.SetTransform(entity.GetTransform() * blur_transform); return blur_entity.GetCoverage(); }); Entity result; result.SetContents(Contents::MakeAnonymous(renderer, coverage)); return result; } Entity ApplyBlurStyle(FilterContents::BlurStyle blur_style, const Entity& entity, const std::shared_ptr<FilterInput>& input, const Snapshot& input_snapshot, Entity blur_entity, const std::shared_ptr<Geometry>& geometry) { switch (blur_style) { case FilterContents::BlurStyle::kNormal: return blur_entity; case FilterContents::BlurStyle::kInner: return ApplyClippedBlurStyle(Entity::ClipOperation::kIntersect, entity, input, input_snapshot, std::move(blur_entity), geometry); break; case FilterContents::BlurStyle::kOuter: return ApplyClippedBlurStyle(Entity::ClipOperation::kDifference, entity, input, input_snapshot, std::move(blur_entity), geometry); case FilterContents::BlurStyle::kSolid: { Entity snapshot_entity = Entity::FromSnapshot( input_snapshot, entity.GetBlendMode(), entity.GetClipDepth()); Entity result; Matrix blurred_transform = blur_entity.GetTransform(); Matrix snapshot_transform = snapshot_entity.GetTransform(); result.SetContents(Contents::MakeAnonymous( fml::MakeCopyable([blur_entity = blur_entity.Clone(), blurred_transform, snapshot_transform, snapshot_entity = std::move(snapshot_entity)]( const ContentContext& renderer, const Entity& entity, RenderPass& pass) mutable { bool result = true; blur_entity.SetNewClipDepth(entity.GetNewClipDepth()); blur_entity.SetTransform(entity.GetTransform() * blurred_transform); result = result && blur_entity.Render(renderer, pass); snapshot_entity.SetTransform(entity.GetTransform() * snapshot_transform); snapshot_entity.SetNewClipDepth(entity.GetNewClipDepth()); result = result && snapshot_entity.Render(renderer, pass); return result; }), fml::MakeCopyable([blur_entity = blur_entity.Clone(), blurred_transform](const Entity& entity) mutable { blur_entity.SetTransform(entity.GetTransform() * blurred_transform); return blur_entity.GetCoverage(); }))); return result; } } } } // namespace std::string_view GaussianBlurFilterContents::kNoMipsError = "Applying gaussian blur without mipmap."; GaussianBlurFilterContents::GaussianBlurFilterContents( Scalar sigma_x, Scalar sigma_y, Entity::TileMode tile_mode, BlurStyle mask_blur_style, const std::shared_ptr<Geometry>& mask_geometry) : sigma_x_(sigma_x), sigma_y_(sigma_y), tile_mode_(tile_mode), mask_blur_style_(mask_blur_style), mask_geometry_(mask_geometry) { // This is supposed to be enforced at a higher level. FML_DCHECK(mask_blur_style == BlurStyle::kNormal || mask_geometry); } // This value was extracted from Skia, see: // * https://github.com/google/skia/blob/d29cc3fe182f6e8a8539004a6a4ee8251677a6fd/src/gpu/ganesh/GrBlurUtils.cpp#L2561-L2576 // * https://github.com/google/skia/blob/d29cc3fe182f6e8a8539004a6a4ee8251677a6fd/src/gpu/BlurUtils.h#L57 Scalar GaussianBlurFilterContents::CalculateScale(Scalar sigma) { if (sigma <= 4) { return 1.0; } Scalar raw_result = 4.0 / sigma; // Round to the nearest 1/(2^n) to get the best quality down scaling. Scalar exponent = round(log2f(raw_result)); // Don't scale down below 1/16th to preserve signal. exponent = std::max(-4.0f, exponent); Scalar rounded = powf(2.0f, exponent); Scalar result = rounded; // Extend the range of the 1/8th downsample based on the effective kernel size // for the blur. if (rounded < 0.125f) { Scalar rounded_plus = powf(2.0f, exponent + 1); Scalar blur_radius = CalculateBlurRadius(sigma); int kernel_size_plus = (ScaleBlurRadius(blur_radius, rounded_plus) * 2) + 1; // This constant was picked by looking at the results to make sure no // shimmering was introduced at the highest sigma values that downscale to // 1/16th. static constexpr int32_t kEighthDownsampleKernalWidthMax = 41; result = kernel_size_plus <= kEighthDownsampleKernalWidthMax ? rounded_plus : rounded; } return result; }; std::optional<Rect> GaussianBlurFilterContents::GetFilterSourceCoverage( const Matrix& effect_transform, const Rect& output_limit) const { Vector2 scaled_sigma = {ScaleSigma(sigma_x_), ScaleSigma(sigma_y_)}; Vector2 blur_radius = {CalculateBlurRadius(scaled_sigma.x), CalculateBlurRadius(scaled_sigma.y)}; Vector3 blur_radii = effect_transform.Basis() * Vector3{blur_radius.x, blur_radius.y, 0.0}; return output_limit.Expand(Point(blur_radii.x, blur_radii.y)); } std::optional<Rect> GaussianBlurFilterContents::GetFilterCoverage( const FilterInput::Vector& inputs, const Entity& entity, const Matrix& effect_transform) const { if (inputs.empty()) { return {}; } std::optional<Rect> input_coverage = inputs[0]->GetCoverage(entity); if (!input_coverage.has_value()) { return {}; } Vector2 scaled_sigma = (effect_transform.Basis() * Vector2(ScaleSigma(sigma_x_), ScaleSigma(sigma_y_))) .Abs(); Vector2 blur_radius = Vector2(CalculateBlurRadius(scaled_sigma.x), CalculateBlurRadius(scaled_sigma.y)); Vector2 padding(ceil(blur_radius.x), ceil(blur_radius.y)); Vector2 local_padding = (entity.GetTransform().Basis() * padding).Abs(); return input_coverage.value().Expand(Point(local_padding.x, local_padding.y)); } std::optional<Entity> GaussianBlurFilterContents::RenderFilter( const FilterInput::Vector& inputs, const ContentContext& renderer, const Entity& entity, const Matrix& effect_transform, const Rect& coverage, const std::optional<Rect>& coverage_hint) const { if (inputs.empty()) { return std::nullopt; } Vector2 scaled_sigma = (effect_transform.Basis() * Vector2(ScaleSigma(sigma_x_), ScaleSigma(sigma_y_))) .Abs(); Vector2 blur_radius = Vector2(CalculateBlurRadius(scaled_sigma.x), CalculateBlurRadius(scaled_sigma.y)); Vector2 padding(ceil(blur_radius.x), ceil(blur_radius.y)); Vector2 local_padding = (entity.GetTransform().Basis() * padding).Abs(); // Apply as much of the desired padding as possible from the source. This may // be ignored so must be accounted for in the downsample pass by adding a // transparent gutter. std::optional<Rect> expanded_coverage_hint; if (coverage_hint.has_value()) { expanded_coverage_hint = coverage_hint->Expand(local_padding); } int32_t mip_count = kBlurFilterRequiredMipCount; if (renderer.GetContext()->GetBackendType() == Context::BackendType::kOpenGLES) { // TODO(https://github.com/flutter/flutter/issues/141732): Implement mip map // generation on opengles. mip_count = 1; } std::optional<Snapshot> input_snapshot = inputs[0]->GetSnapshot("GaussianBlur", renderer, entity, /*coverage_limit=*/expanded_coverage_hint, /*mip_count=*/mip_count); if (!input_snapshot.has_value()) { return std::nullopt; } if (scaled_sigma.x < kEhCloseEnough && scaled_sigma.y < kEhCloseEnough) { return Entity::FromSnapshot(input_snapshot.value(), entity.GetBlendMode(), entity.GetClipDepth()); // No blur to render. } // In order to avoid shimmering in downsampling step, we should have mips. if (input_snapshot->texture->GetMipCount() <= 1) { FML_DLOG(ERROR) << kNoMipsError; } FML_DCHECK(!input_snapshot->texture->NeedsMipmapGeneration()); Scalar desired_scalar = std::min(CalculateScale(scaled_sigma.x), CalculateScale(scaled_sigma.y)); // TODO(jonahwilliams): If desired_scalar is 1.0 and we fully acquired the // gutter from the expanded_coverage_hint, we can skip the downsample pass. // pass. Vector2 downsample_scalar(desired_scalar, desired_scalar); Rect source_rect = Rect::MakeSize(input_snapshot->texture->GetSize()); Rect source_rect_padded = source_rect.Expand(padding); Matrix padding_snapshot_adjustment = Matrix::MakeTranslation(-padding); // TODO(gaaclarke): The padding could be removed if we know it's not needed or // resized to account for the expanded_clip_coverage. There doesn't appear // to be the math to make those calculations though. The following // optimization works, but causes a shimmer as a result of // https://github.com/flutter/flutter/issues/140193 so it isn't applied. // // !input_snapshot->GetCoverage()->Expand(-local_padding) // .Contains(coverage_hint.value())) Vector2 downsampled_size = source_rect_padded.GetSize() * downsample_scalar; ISize subpass_size = ISize(round(downsampled_size.x), round(downsampled_size.y)); Vector2 effective_scalar = Vector2(subpass_size) / source_rect_padded.GetSize(); Quad uvs = CalculateUVs(inputs[0], entity, source_rect_padded, input_snapshot->texture->GetSize()); fml::StatusOr<RenderTarget> pass1_out = MakeDownsampleSubpass( renderer, input_snapshot->texture, input_snapshot->sampler_descriptor, uvs, subpass_size, tile_mode_); if (!pass1_out.ok()) { return std::nullopt; } Vector2 pass1_pixel_size = 1.0 / Vector2(pass1_out.value().GetRenderTargetTexture()->GetSize()); std::optional<Rect> input_snapshot_coverage = input_snapshot->GetCoverage(); Quad blur_uvs = {Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1)}; if (expanded_coverage_hint.has_value() && input_snapshot_coverage.has_value() && // TODO(https://github.com/flutter/flutter/issues/140890): Remove this // condition. There is some flaw in coverage stopping us from using this // today. I attempted to use source coordinates to calculate the uvs, // but that didn't work either. input_snapshot.has_value() && input_snapshot.value().transform.IsTranslationScaleOnly()) { // Only process the uvs where the blur is happening, not the whole texture. std::optional<Rect> uvs = MakeReferenceUVs(input_snapshot_coverage.value(), expanded_coverage_hint.value()) .Intersection(Rect::MakeSize(Size(1, 1))); FML_DCHECK(uvs.has_value()); if (uvs.has_value()) { blur_uvs[0] = uvs->GetLeftTop(); blur_uvs[1] = uvs->GetRightTop(); blur_uvs[2] = uvs->GetLeftBottom(); blur_uvs[3] = uvs->GetRightBottom(); } } fml::StatusOr<RenderTarget> pass2_out = MakeBlurSubpass( renderer, /*input_pass=*/pass1_out.value(), input_snapshot->sampler_descriptor, tile_mode_, BlurParameters{ .blur_uv_offset = Point(0.0, pass1_pixel_size.y), .blur_sigma = scaled_sigma.y * effective_scalar.y, .blur_radius = ScaleBlurRadius(blur_radius.y, effective_scalar.y), .step_size = 1, }, /*destination_target=*/std::nullopt, blur_uvs); if (!pass2_out.ok()) { return std::nullopt; } // Only ping pong if the first pass actually created a render target. auto pass3_destination = pass2_out.value().GetRenderTargetTexture() != pass1_out.value().GetRenderTargetTexture() ? std::optional<RenderTarget>(pass1_out.value()) : std::optional<RenderTarget>(std::nullopt); fml::StatusOr<RenderTarget> pass3_out = MakeBlurSubpass( renderer, /*input_pass=*/pass2_out.value(), input_snapshot->sampler_descriptor, tile_mode_, BlurParameters{ .blur_uv_offset = Point(pass1_pixel_size.x, 0.0), .blur_sigma = scaled_sigma.x * effective_scalar.x, .blur_radius = ScaleBlurRadius(blur_radius.x, effective_scalar.x), .step_size = 1, }, pass3_destination, blur_uvs); if (!pass3_out.ok()) { return std::nullopt; } // The ping-pong approach requires that each render pass output has the same // size. FML_DCHECK((pass1_out.value().GetRenderTargetSize() == pass2_out.value().GetRenderTargetSize()) && (pass2_out.value().GetRenderTargetSize() == pass3_out.value().GetRenderTargetSize())); SamplerDescriptor sampler_desc = MakeSamplerDescriptor( MinMagFilter::kLinear, SamplerAddressMode::kClampToEdge); Entity blur_output_entity = Entity::FromSnapshot( Snapshot{.texture = pass3_out.value().GetRenderTargetTexture(), .transform = input_snapshot->transform * padding_snapshot_adjustment * Matrix::MakeScale(1 / effective_scalar), .sampler_descriptor = sampler_desc, .opacity = input_snapshot->opacity}, entity.GetBlendMode(), entity.GetClipDepth()); return ApplyBlurStyle(mask_blur_style_, entity, inputs[0], input_snapshot.value(), std::move(blur_output_entity), mask_geometry_); } Scalar GaussianBlurFilterContents::CalculateBlurRadius(Scalar sigma) { return static_cast<Radius>(Sigma(sigma)).radius; } Quad GaussianBlurFilterContents::CalculateUVs( const std::shared_ptr<FilterInput>& filter_input, const Entity& entity, const Rect& source_rect, const ISize& texture_size) { Matrix input_transform = filter_input->GetLocalTransform(entity); Quad coverage_quad = source_rect.GetTransformedPoints(input_transform); Matrix uv_transform = Matrix::MakeScale( {1.0f / texture_size.width, 1.0f / texture_size.height, 1.0f}); return uv_transform.Transform(coverage_quad); } // This function was calculated by observing Skia's behavior. Its blur at 500 // seemed to be 0.15. Since we clamp at 500 I solved the quadratic equation // that puts the minima there and a f(0)=1. Scalar GaussianBlurFilterContents::ScaleSigma(Scalar sigma) { // Limit the kernel size to 1000x1000 pixels, like Skia does. Scalar clamped = std::min(sigma, 500.0f); constexpr Scalar a = 3.4e-06; constexpr Scalar b = -3.4e-3; constexpr Scalar c = 1.f; Scalar scalar = c + b * clamped + a * clamped * clamped; return clamped * scalar; } KernelPipeline::FragmentShader::KernelSamples GenerateBlurInfo( BlurParameters parameters) { KernelPipeline::FragmentShader::KernelSamples result; result.sample_count = ((2 * parameters.blur_radius) / parameters.step_size) + 1; // Chop off the last samples if the radius >= 3 where they account for < 1.56% // of the result. int x_offset = 0; if (parameters.blur_radius >= 3) { result.sample_count -= 2; x_offset = 1; } Scalar tally = 0.0f; for (int i = 0; i < result.sample_count; ++i) { int x = x_offset + (i * parameters.step_size) - parameters.blur_radius; result.samples[i] = KernelPipeline::FragmentShader::KernelSample{ .uv_offset = parameters.blur_uv_offset * x, .coefficient = expf(-0.5f * (x * x) / (parameters.blur_sigma * parameters.blur_sigma)) / (sqrtf(2.0f * M_PI) * parameters.blur_sigma), }; tally += result.samples[i].coefficient; } // Make sure everything adds up to 1. for (auto& sample : result.samples) { sample.coefficient /= tally; } return result; } // This works by shrinking the kernel size by 2 and relying on lerp to read // between the samples. KernelPipeline::FragmentShader::KernelSamples LerpHackKernelSamples( KernelPipeline::FragmentShader::KernelSamples parameters) { KernelPipeline::FragmentShader::KernelSamples result; result.sample_count = ((parameters.sample_count - 1) / 2) + 1; int32_t middle = result.sample_count / 2; int32_t j = 0; for (int i = 0; i < result.sample_count; i++) { if (i == middle) { result.samples[i] = parameters.samples[j++]; } else { KernelPipeline::FragmentShader::KernelSample left = parameters.samples[j]; KernelPipeline::FragmentShader::KernelSample right = parameters.samples[j + 1]; result.samples[i] = KernelPipeline::FragmentShader::KernelSample{ .uv_offset = (left.uv_offset * left.coefficient + right.uv_offset * right.coefficient) / (left.coefficient + right.coefficient), .coefficient = left.coefficient + right.coefficient, }; j += 2; } } return result; } } // namespace impeller
engine/impeller/entity/contents/filters/gaussian_blur_filter_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/filters/gaussian_blur_filter_contents.cc", "repo_id": "engine", "token_count": 11793 }
199
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/entity/contents/filters/local_matrix_filter_contents.h" namespace impeller { LocalMatrixFilterContents::LocalMatrixFilterContents() = default; LocalMatrixFilterContents::~LocalMatrixFilterContents() = default; void LocalMatrixFilterContents::SetMatrix(Matrix matrix) { matrix_ = matrix; } Matrix LocalMatrixFilterContents::GetLocalTransform( const Matrix& parent_transform) const { return matrix_; } std::optional<Rect> LocalMatrixFilterContents::GetFilterSourceCoverage( const Matrix& effect_transform, const Rect& output_limit) const { auto matrix = matrix_.Basis(); if (matrix.GetDeterminant() == 0.0) { return std::nullopt; } auto inverse = matrix.Invert(); return output_limit.TransformBounds(inverse); } std::optional<Entity> LocalMatrixFilterContents::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 { std::optional<Snapshot> snapshot = inputs[0]->GetSnapshot("LocalMatrix", renderer, entity); if (!snapshot.has_value()) { return std::nullopt; } return Entity::FromSnapshot(snapshot.value(), entity.GetBlendMode(), entity.GetClipDepth()); } } // namespace impeller
engine/impeller/entity/contents/filters/local_matrix_filter_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/filters/local_matrix_filter_contents.cc", "repo_id": "engine", "token_count": 489 }
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. #ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_LINEAR_GRADIENT_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_LINEAR_GRADIENT_CONTENTS_H_ #include <functional> #include <memory> #include <vector> #include "flutter/fml/macros.h" #include "flutter/impeller/core/texture.h" #include "impeller/entity/contents/color_source_contents.h" #include "impeller/entity/entity.h" #include "impeller/geometry/color.h" #include "impeller/geometry/gradient.h" #include "impeller/geometry/path.h" #include "impeller/geometry/point.h" namespace impeller { class LinearGradientContents final : public ColorSourceContents { public: LinearGradientContents(); ~LinearGradientContents() override; // |Contents| bool IsOpaque() const override; // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; // |Contents| [[nodiscard]] bool ApplyColorFilter( const ColorFilterProc& color_filter_proc) override; void SetEndPoints(Point start_point, Point end_point); void SetColors(std::vector<Color> colors); void SetStops(std::vector<Scalar> stops); const std::vector<Color>& GetColors() const; const std::vector<Scalar>& GetStops() const; void SetTileMode(Entity::TileMode tile_mode); private: bool RenderTexture(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const; bool RenderSSBO(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const; Point start_point_; Point end_point_; std::vector<Color> colors_; std::vector<Scalar> stops_; Entity::TileMode tile_mode_; Color decal_border_color_ = Color::BlackTransparent(); LinearGradientContents(const LinearGradientContents&) = delete; LinearGradientContents& operator=(const LinearGradientContents&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_LINEAR_GRADIENT_CONTENTS_H_
engine/impeller/entity/contents/linear_gradient_contents.h/0
{ "file_path": "engine/impeller/entity/contents/linear_gradient_contents.h", "repo_id": "engine", "token_count": 785 }
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_ENTITY_CONTENTS_TEST_RECORDING_RENDER_PASS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_RECORDING_RENDER_PASS_H_ #include "impeller/renderer/render_pass.h" namespace impeller { class RecordingRenderPass : public RenderPass { public: explicit RecordingRenderPass(std::shared_ptr<RenderPass> delegate, const std::shared_ptr<const Context>& context, const RenderTarget& render_target); ~RecordingRenderPass() = default; const std::vector<Command>& GetCommands() const override { return commands_; } // |RenderPass| void SetPipeline( const std::shared_ptr<Pipeline<PipelineDescriptor>>& pipeline) override; void SetCommandLabel(std::string_view label) override; // |RenderPass| void SetStencilReference(uint32_t value) override; // |RenderPass| void SetBaseVertex(uint64_t value) override; // |RenderPass| void SetViewport(Viewport viewport) override; // |RenderPass| void SetScissor(IRect scissor) override; // |RenderPass| void SetInstanceCount(size_t count) override; // |RenderPass| bool SetVertexBuffer(VertexBuffer buffer) override; // |RenderPass| fml::Status Draw() override; // |RenderPass| bool BindResource(ShaderStage stage, DescriptorType type, const ShaderUniformSlot& slot, const ShaderMetadata& metadata, BufferView view) override; // |RenderPass| bool BindResource(ShaderStage stage, DescriptorType type, const ShaderUniformSlot& slot, const std::shared_ptr<const ShaderMetadata>& metadata, BufferView view) override; // |RenderPass| 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; // |RenderPass| void OnSetLabel(std::string label) override; // |RenderPass| bool OnEncodeCommands(const Context& context) const override; bool IsValid() const override { return true; } private: Command pending_; std::shared_ptr<RenderPass> delegate_; std::vector<Command> commands_; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_RECORDING_RENDER_PASS_H_
engine/impeller/entity/contents/test/recording_render_pass.h/0
{ "file_path": "engine/impeller/entity/contents/test/recording_render_pass.h", "repo_id": "engine", "token_count": 1062 }
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_ENTITY_ENTITY_PASS_DELEGATE_H_ #define FLUTTER_IMPELLER_ENTITY_ENTITY_PASS_DELEGATE_H_ #include <memory> #include "flutter/fml/macros.h" #include "impeller/core/texture.h" #include "impeller/entity/contents/contents.h" #include "impeller/entity/contents/filters/filter_contents.h" #include "impeller/entity/contents/filters/inputs/filter_input.h" namespace impeller { class EntityPass; class EntityPassDelegate { public: static std::unique_ptr<EntityPassDelegate> MakeDefault(); EntityPassDelegate(); virtual ~EntityPassDelegate(); virtual bool CanElide() = 0; /// @brief Whether or not this entity pass can be collapsed into the parent. /// If true, this method may modify the entities for the current pass. virtual bool CanCollapseIntoParentPass(EntityPass* entity_pass) = 0; virtual std::shared_ptr<Contents> CreateContentsForSubpassTarget( std::shared_ptr<Texture> target, const Matrix& effect_transform) = 0; virtual std::shared_ptr<FilterContents> WithImageFilter( const FilterInput::Variant& input, const Matrix& effect_transform) const = 0; private: EntityPassDelegate(const EntityPassDelegate&) = delete; EntityPassDelegate& operator=(const EntityPassDelegate&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_ENTITY_PASS_DELEGATE_H_
engine/impeller/entity/entity_pass_delegate.h/0
{ "file_path": "engine/impeller/entity/entity_pass_delegate.h", "repo_id": "engine", "token_count": 512 }
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. #ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_GEOMETRY_H_ #define FLUTTER_IMPELLER_ENTITY_GEOMETRY_GEOMETRY_H_ #include "impeller/core/formats.h" #include "impeller/core/vertex_buffer.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/entity.h" #include "impeller/entity/texture_fill.vert.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/vertex_buffer_builder.h" namespace impeller { class Tessellator; struct GeometryResult { enum class Mode { /// The geometry has no overlapping triangles. kNormal, /// The geometry may have overlapping triangles. The geometry should be /// stenciled with the NonZero fill rule. kNonZero, /// The geometry may have overlapping triangles. The geometry should be /// stenciled with the EvenOdd fill rule. kEvenOdd, /// The geometry may have overlapping triangles, but they should not /// overdraw or cancel each other out. This is a special case for stroke /// geometry. kPreventOverdraw, }; PrimitiveType type = PrimitiveType::kTriangleStrip; VertexBuffer vertex_buffer; Matrix transform; Mode mode = Mode::kNormal; }; static const GeometryResult kEmptyResult = { .vertex_buffer = { .index_type = IndexType::kNone, }, }; enum GeometryVertexType { kPosition, kColor, kUV, }; /// @brief Compute UV geometry for a VBB that contains only position geometry. /// /// texture_origin should be set to 0, 0 for stroke and stroke based geometry, /// like the point field. VertexBufferBuilder<TextureFillVertexShader::PerVertexData> ComputeUVGeometryCPU( VertexBufferBuilder<SolidFillVertexShader::PerVertexData>& input, Point texture_origin, Size texture_coverage, Matrix effect_transform); /// @brief Computes geometry and UV coordinates for a rectangle to be rendered. /// /// UV is the horizontal and vertical coordinates within the texture. /// /// @param source_rect The rectangle to be rendered. /// @param texture_bounds The local space bounding box of the geometry. /// @param effect_transform The transform to apply to the UV coordinates. /// @param renderer The content context to use for allocating buffers. /// @param entity The entity to use for the transform. /// @param pass The render pass to use for the transform. GeometryResult ComputeUVGeometryForRect(Rect source_rect, Rect texture_bounds, Matrix effect_transform, const ContentContext& renderer, const Entity& entity, RenderPass& pass); class Geometry { public: static std::shared_ptr<Geometry> MakeFillPath( const Path& path, std::optional<Rect> inner_rect = std::nullopt); static std::shared_ptr<Geometry> MakeStrokePath( const Path& path, Scalar stroke_width = 0.0, Scalar miter_limit = 4.0, Cap stroke_cap = Cap::kButt, Join stroke_join = Join::kMiter); static std::shared_ptr<Geometry> MakeCover(); static std::shared_ptr<Geometry> MakeRect(const Rect& rect); static std::shared_ptr<Geometry> MakeOval(const Rect& rect); static std::shared_ptr<Geometry> MakeLine(const Point& p0, const Point& p1, Scalar width, Cap cap); static std::shared_ptr<Geometry> MakeCircle(const Point& center, Scalar radius); static std::shared_ptr<Geometry> MakeStrokedCircle(const Point& center, Scalar radius, Scalar stroke_width); static std::shared_ptr<Geometry> MakeRoundRect(const Rect& rect, const Size& radii); static std::shared_ptr<Geometry> MakePointField(std::vector<Point> points, Scalar radius, bool round); virtual GeometryResult GetPositionBuffer(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const = 0; virtual GeometryResult GetPositionUVBuffer(Rect texture_coverage, Matrix effect_transform, const ContentContext& renderer, const Entity& entity, RenderPass& pass) const = 0; virtual GeometryResult::Mode GetResultMode() const; virtual GeometryVertexType GetVertexType() const = 0; virtual std::optional<Rect> GetCoverage(const Matrix& transform) const = 0; /// @brief Determines if this geometry, transformed by the given /// `transform`, will completely cover all surface area of the given /// `rect`. /// /// This is a conservative estimate useful for certain /// optimizations. /// /// @returns `true` if the transformed geometry is guaranteed to cover the /// given `rect`. May return `false` in many undetected cases where /// the transformed geometry does in fact cover the `rect`. virtual bool CoversArea(const Matrix& transform, const Rect& rect) const; virtual bool IsAxisAlignedRect() const; protected: static GeometryResult ComputePositionGeometry( const ContentContext& renderer, const Tessellator::VertexGenerator& generator, const Entity& entity, RenderPass& pass); static GeometryResult ComputePositionUVGeometry( const ContentContext& renderer, const Tessellator::VertexGenerator& generator, const Matrix& uv_transform, const Entity& entity, RenderPass& pass); }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_GEOMETRY_H_
engine/impeller/entity/geometry/geometry.h/0
{ "file_path": "engine/impeller/entity/geometry/geometry.h", "repo_id": "engine", "token_count": 2648 }
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/entity/render_target_cache.h" #include "impeller/renderer/render_target.h" namespace impeller { RenderTargetCache::RenderTargetCache(std::shared_ptr<Allocator> allocator) : RenderTargetAllocator(std::move(allocator)) {} void RenderTargetCache::Start() { for (auto& td : render_target_data_) { td.used_this_frame = false; } } void RenderTargetCache::End() { std::vector<RenderTargetData> retain; for (const auto& td : render_target_data_) { if (td.used_this_frame) { retain.push_back(td); } } render_target_data_.swap(retain); } RenderTarget RenderTargetCache::CreateOffscreen( const Context& context, ISize size, int mip_count, const std::string& label, RenderTarget::AttachmentConfig color_attachment_config, std::optional<RenderTarget::AttachmentConfig> stencil_attachment_config, const std::shared_ptr<Texture>& existing_color_texture, const std::shared_ptr<Texture>& existing_depth_stencil_texture) { FML_DCHECK(existing_color_texture == nullptr && existing_depth_stencil_texture == nullptr); auto config = RenderTargetConfig{ .size = size, .mip_count = static_cast<size_t>(mip_count), .has_msaa = false, .has_depth_stencil = stencil_attachment_config.has_value(), }; for (auto& render_target_data : render_target_data_) { const auto other_config = render_target_data.config; if (!render_target_data.used_this_frame && other_config == config) { render_target_data.used_this_frame = true; auto color0 = render_target_data.render_target.GetColorAttachments() .find(0u) ->second; auto depth = render_target_data.render_target.GetDepthAttachment(); std::shared_ptr<Texture> depth_tex = depth ? depth->texture : nullptr; return RenderTargetAllocator::CreateOffscreen( context, size, mip_count, label, color_attachment_config, stencil_attachment_config, color0.texture, depth_tex); } } RenderTarget created_target = RenderTargetAllocator::CreateOffscreen( context, size, mip_count, label, color_attachment_config, stencil_attachment_config); if (!created_target.IsValid()) { return created_target; } render_target_data_.push_back( RenderTargetData{.used_this_frame = true, .config = config, .render_target = created_target}); return created_target; } RenderTarget RenderTargetCache::CreateOffscreenMSAA( const Context& context, ISize size, int mip_count, const std::string& label, RenderTarget::AttachmentConfigMSAA color_attachment_config, std::optional<RenderTarget::AttachmentConfig> stencil_attachment_config, const std::shared_ptr<Texture>& existing_color_msaa_texture, const std::shared_ptr<Texture>& existing_color_resolve_texture, const std::shared_ptr<Texture>& existing_depth_stencil_texture) { FML_DCHECK(existing_color_msaa_texture == nullptr && existing_color_resolve_texture == nullptr && existing_depth_stencil_texture == nullptr); auto config = RenderTargetConfig{ .size = size, .mip_count = static_cast<size_t>(mip_count), .has_msaa = true, .has_depth_stencil = stencil_attachment_config.has_value(), }; for (auto& render_target_data : render_target_data_) { const auto other_config = render_target_data.config; if (!render_target_data.used_this_frame && other_config == config) { render_target_data.used_this_frame = true; auto color0 = render_target_data.render_target.GetColorAttachments() .find(0u) ->second; auto depth = render_target_data.render_target.GetDepthAttachment(); std::shared_ptr<Texture> depth_tex = depth ? depth->texture : nullptr; return RenderTargetAllocator::CreateOffscreenMSAA( context, size, mip_count, label, color_attachment_config, stencil_attachment_config, color0.texture, color0.resolve_texture, depth_tex); } } RenderTarget created_target = RenderTargetAllocator::CreateOffscreenMSAA( context, size, mip_count, label, color_attachment_config, stencil_attachment_config); if (!created_target.IsValid()) { return created_target; } render_target_data_.push_back( RenderTargetData{.used_this_frame = true, .config = config, .render_target = created_target}); return created_target; } size_t RenderTargetCache::CachedTextureCount() const { return render_target_data_.size(); } } // namespace impeller
engine/impeller/entity/render_target_cache.cc/0
{ "file_path": "engine/impeller/entity/render_target_cache.cc", "repo_id": "engine", "token_count": 1858 }
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. precision mediump float; #include <impeller/color.glsl> #include <impeller/texture.glsl> #include <impeller/types.glsl> // A color filter that transforms colors through a 4x5 color matrix. // // This filter can be used to change the saturation of pixels, convert from YUV // to RGB, etc. // // 4x5 matrix for transforming the color and alpha components of a Bitmap. // The matrix can be passed as single array, and is treated as follows: // // [ a, b, c, d, e, // f, g, h, i, j, // k, l, m, n, o, // p, q, r, s, t ] // // When applied to a color [R, G, B, A], the resulting color is computed as: // // R’ = a*R + b*G + c*B + d*A + e; // G’ = f*R + g*G + h*B + i*A + j; // B’ = k*R + l*G + m*B + n*A + o; // A’ = p*R + q*G + r*B + s*A + t; // // That resulting color [R’, G’, B’, A’] then has each channel clamped to the 0 // to 255 range. uniform FragInfo { mat4 color_m; f16vec4 color_v; float16_t input_alpha; } frag_info; uniform f16sampler2D input_texture; in highp vec2 v_texture_coords; out f16vec4 frag_color; void main() { f16vec4 input_color = texture(input_texture, v_texture_coords) * frag_info.input_alpha; // unpremultiply first, as filter inputs are premultiplied. f16vec4 color = IPHalfUnpremultiply(input_color); color = clamp(f16mat4(frag_info.color_m) * color + frag_info.color_v, float16_t(0), float16_t(1.0)); // premultiply the outputs frag_color = f16vec4(color.rgb * color.a, color.a); }
engine/impeller/entity/shaders/color_matrix_color_filter.frag/0
{ "file_path": "engine/impeller/entity/shaders/color_matrix_color_filter.frag", "repo_id": "engine", "token_count": 671 }
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/transform.glsl> #include <impeller/types.glsl> uniform FrameInfo { mat4 mvp; float depth; mat4 entity_transform; vec2 atlas_size; vec2 offset; f16vec4 text_color; float is_translation_scale; } frame_info; // XYWH. in vec4 atlas_glyph_bounds; // XYWH in vec4 glyph_bounds; in vec2 unit_position; in vec2 glyph_position; out vec2 v_uv; IMPELLER_MAYBE_FLAT out f16vec4 v_text_color; mat4 basis(mat4 m) { return mat4(m[0][0], m[0][1], m[0][2], 0.0, // m[1][0], m[1][1], m[1][2], 0.0, // m[2][0], m[2][1], m[2][2], 0.0, // 0.0, 0.0, 0.0, 1.0 // ); } vec2 project(mat4 m, vec2 v) { float w = v.x * m[0][3] + v.y * m[1][3] + m[3][3]; vec2 result = vec2(v.x * m[0][0] + v.y * m[1][0] + m[3][0], v.x * m[0][1] + v.y * m[1][1] + m[3][1]); // This is Skia's behavior, but it may be reasonable to allow UB for the w=0 // case. if (w != 0) { w = 1 / w; } return result * w; } void main() { vec2 screen_offset = round(project(frame_info.entity_transform, frame_info.offset)); // For each glyph, we compute two rectangles. One for the vertex positions // and one for the texture coordinates (UVs). vec2 uv_origin = (atlas_glyph_bounds.xy - vec2(0.5)) / frame_info.atlas_size; vec2 uv_size = (atlas_glyph_bounds.zw + vec2(1)) / frame_info.atlas_size; // Rounding here prevents most jitter between glyphs in the run when // nearest sampling. mat4 basis_transform = basis(frame_info.entity_transform); vec2 screen_glyph_position = screen_offset + round(project(basis_transform, (glyph_position + glyph_bounds.xy))); vec4 position; if (frame_info.is_translation_scale == 1.0) { // Rouding up here prevents the bounds from becoming 1 pixel too small // when nearest sampling. This path breaks down for projections. position = vec4( screen_glyph_position + ceil(project(basis_transform, unit_position * glyph_bounds.zw)), 0.0, 1.0); } else { position = frame_info.entity_transform * vec4(frame_info.offset + glyph_position + glyph_bounds.xy + unit_position * glyph_bounds.zw, 0.0, 1.0); } gl_Position = frame_info.mvp * position; gl_Position /= gl_Position.w; gl_Position.z = frame_info.depth; v_uv = uv_origin + unit_position * uv_size; v_text_color = frame_info.text_color; }
engine/impeller/entity/shaders/glyph_atlas.vert/0
{ "file_path": "engine/impeller/entity/shaders/glyph_atlas.vert", "repo_id": "engine", "token_count": 1148 }
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 <impeller/types.glsl> uniform FrameInfo { mat4 mvp; float depth; f16vec4 color; } frame_info; in vec2 position; IMPELLER_MAYBE_FLAT out f16vec4 v_color; void main() { v_color = frame_info.color; gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); gl_Position /= gl_Position.w; gl_Position.z = frame_info.depth; }
engine/impeller/entity/shaders/solid_fill.vert/0
{ "file_path": "engine/impeller/entity/shaders/solid_fill.vert", "repo_id": "engine", "token_count": 191 }
208
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; } output_data.count = input_data.count; output_data.elements[ident] = input_data.elements[ident] * 2; }
engine/impeller/fixtures/stage2.comp/0
{ "file_path": "engine/impeller/fixtures/stage2.comp", "repo_id": "engine", "token_count": 165 }
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 "gtest/gtest.h" #include "flutter/impeller/geometry/rect.h" #include "flutter/impeller/geometry/geometry_asserts.h" namespace impeller { namespace testing { TEST(RectTest, RectEmptyDeclaration) { Rect rect; EXPECT_EQ(rect.GetLeft(), 0.0f); EXPECT_EQ(rect.GetTop(), 0.0f); EXPECT_EQ(rect.GetRight(), 0.0f); EXPECT_EQ(rect.GetBottom(), 0.0f); EXPECT_EQ(rect.GetX(), 0.0f); EXPECT_EQ(rect.GetY(), 0.0f); EXPECT_EQ(rect.GetWidth(), 0.0f); EXPECT_EQ(rect.GetHeight(), 0.0f); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } TEST(RectTest, IRectEmptyDeclaration) { IRect rect; EXPECT_EQ(rect.GetLeft(), 0); EXPECT_EQ(rect.GetTop(), 0); EXPECT_EQ(rect.GetRight(), 0); EXPECT_EQ(rect.GetBottom(), 0); EXPECT_EQ(rect.GetX(), 0); EXPECT_EQ(rect.GetY(), 0); EXPECT_EQ(rect.GetWidth(), 0); EXPECT_EQ(rect.GetHeight(), 0); EXPECT_TRUE(rect.IsEmpty()); // EXPECT_TRUE(rect.IsFinite()); // should fail to compile } TEST(RectTest, RectDefaultConstructor) { Rect rect = Rect(); EXPECT_EQ(rect.GetLeft(), 0.0f); EXPECT_EQ(rect.GetTop(), 0.0f); EXPECT_EQ(rect.GetRight(), 0.0f); EXPECT_EQ(rect.GetBottom(), 0.0f); EXPECT_EQ(rect.GetX(), 0.0f); EXPECT_EQ(rect.GetY(), 0.0f); EXPECT_EQ(rect.GetWidth(), 0.0f); EXPECT_EQ(rect.GetHeight(), 0.0f); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } TEST(RectTest, IRectDefaultConstructor) { IRect rect = IRect(); EXPECT_EQ(rect.GetLeft(), 0); EXPECT_EQ(rect.GetTop(), 0); EXPECT_EQ(rect.GetRight(), 0); EXPECT_EQ(rect.GetBottom(), 0); EXPECT_EQ(rect.GetX(), 0); EXPECT_EQ(rect.GetY(), 0); EXPECT_EQ(rect.GetWidth(), 0); EXPECT_EQ(rect.GetHeight(), 0); EXPECT_TRUE(rect.IsEmpty()); } TEST(RectTest, RectSimpleLTRB) { // Using fractional-power-of-2 friendly values for equality tests Rect rect = Rect::MakeLTRB(5.125f, 10.25f, 20.625f, 25.375f); EXPECT_EQ(rect.GetLeft(), 5.125f); EXPECT_EQ(rect.GetTop(), 10.25f); EXPECT_EQ(rect.GetRight(), 20.625f); EXPECT_EQ(rect.GetBottom(), 25.375f); EXPECT_EQ(rect.GetX(), 5.125f); EXPECT_EQ(rect.GetY(), 10.25f); EXPECT_EQ(rect.GetWidth(), 15.5f); EXPECT_EQ(rect.GetHeight(), 15.125f); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } TEST(RectTest, IRectSimpleLTRB) { IRect rect = IRect::MakeLTRB(5, 10, 20, 25); EXPECT_EQ(rect.GetLeft(), 5); EXPECT_EQ(rect.GetTop(), 10); EXPECT_EQ(rect.GetRight(), 20); EXPECT_EQ(rect.GetBottom(), 25); EXPECT_EQ(rect.GetX(), 5); EXPECT_EQ(rect.GetY(), 10); EXPECT_EQ(rect.GetWidth(), 15); EXPECT_EQ(rect.GetHeight(), 15); EXPECT_FALSE(rect.IsEmpty()); } TEST(RectTest, RectSimpleXYWH) { // Using fractional-power-of-2 friendly values for equality tests Rect rect = Rect::MakeXYWH(5.125f, 10.25f, 15.5f, 15.125f); EXPECT_EQ(rect.GetLeft(), 5.125f); EXPECT_EQ(rect.GetTop(), 10.25f); EXPECT_EQ(rect.GetRight(), 20.625f); EXPECT_EQ(rect.GetBottom(), 25.375f); EXPECT_EQ(rect.GetX(), 5.125f); EXPECT_EQ(rect.GetY(), 10.25f); EXPECT_EQ(rect.GetWidth(), 15.5f); EXPECT_EQ(rect.GetHeight(), 15.125f); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } TEST(RectTest, IRectSimpleXYWH) { IRect rect = IRect::MakeXYWH(5, 10, 15, 16); EXPECT_EQ(rect.GetLeft(), 5); EXPECT_EQ(rect.GetTop(), 10); EXPECT_EQ(rect.GetRight(), 20); EXPECT_EQ(rect.GetBottom(), 26); EXPECT_EQ(rect.GetX(), 5); EXPECT_EQ(rect.GetY(), 10); EXPECT_EQ(rect.GetWidth(), 15); EXPECT_EQ(rect.GetHeight(), 16); EXPECT_FALSE(rect.IsEmpty()); } TEST(RectTest, RectOverflowXYWH) { auto min = std::numeric_limits<Scalar>::lowest(); auto max = std::numeric_limits<Scalar>::max(); auto inf = std::numeric_limits<Scalar>::infinity(); // 8 cases: // finite X, max W // max X, max W // finite Y, max H // max Y, max H // finite X, min W // min X, min W // finite Y, min H // min Y, min H // a small finite value added to a max value will remain max // a very large finite value (like max) added to max will go to infinity { Rect rect = Rect::MakeXYWH(5.0, 10.0f, max, 15.0f); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), max); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), max); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeXYWH(max, 10.0f, max, 15.0f); EXPECT_EQ(rect.GetLeft(), max); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), inf); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), max); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), inf); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_FALSE(rect.IsEmpty()); EXPECT_FALSE(rect.IsFinite()); } { Rect rect = Rect::MakeXYWH(5.0f, 10.0f, 20.0f, max); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), 25.0f); EXPECT_EQ(rect.GetBottom(), max); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), 20.0f); EXPECT_EQ(rect.GetHeight(), max); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeXYWH(5.0f, max, 20.0f, max); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), max); EXPECT_EQ(rect.GetRight(), 25.0f); EXPECT_EQ(rect.GetBottom(), inf); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), max); EXPECT_EQ(rect.GetWidth(), 20.0f); EXPECT_EQ(rect.GetHeight(), inf); EXPECT_FALSE(rect.IsEmpty()); EXPECT_FALSE(rect.IsFinite()); } { Rect rect = Rect::MakeXYWH(5.0, 10.0f, min, 15.0f); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), min); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), min); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeXYWH(min, 10.0f, min, 15.0f); EXPECT_EQ(rect.GetLeft(), min); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), -inf); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), min); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), -inf); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_TRUE(rect.IsEmpty()); EXPECT_FALSE(rect.IsFinite()); } { Rect rect = Rect::MakeXYWH(5.0f, 10.0f, 20.0f, min); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), 25.0f); EXPECT_EQ(rect.GetBottom(), min); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), 20.0f); EXPECT_EQ(rect.GetHeight(), min); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeXYWH(5.0f, min, 20.0f, min); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), min); EXPECT_EQ(rect.GetRight(), 25.0f); EXPECT_EQ(rect.GetBottom(), -inf); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), min); EXPECT_EQ(rect.GetWidth(), 20.0f); EXPECT_EQ(rect.GetHeight(), -inf); EXPECT_TRUE(rect.IsEmpty()); EXPECT_FALSE(rect.IsFinite()); } } TEST(RectTest, IRectOverflowXYWH) { auto min = std::numeric_limits<int64_t>::min(); auto max = std::numeric_limits<int64_t>::max(); // 4 cases // x near max, positive w takes it past max // x near min, negative w takes it below min // y near max, positive h takes it past max // y near min, negative h takes it below min { IRect rect = IRect::MakeXYWH(max - 5, 10, 10, 16); EXPECT_EQ(rect.GetLeft(), max - 5); EXPECT_EQ(rect.GetTop(), 10); EXPECT_EQ(rect.GetRight(), max); EXPECT_EQ(rect.GetBottom(), 26); EXPECT_EQ(rect.GetX(), max - 5); EXPECT_EQ(rect.GetY(), 10); EXPECT_EQ(rect.GetWidth(), 5); EXPECT_EQ(rect.GetHeight(), 16); EXPECT_FALSE(rect.IsEmpty()); } { IRect rect = IRect::MakeXYWH(min + 5, 10, -10, 16); EXPECT_EQ(rect.GetLeft(), min + 5); EXPECT_EQ(rect.GetTop(), 10); EXPECT_EQ(rect.GetRight(), min); EXPECT_EQ(rect.GetBottom(), 26); EXPECT_EQ(rect.GetX(), min + 5); EXPECT_EQ(rect.GetY(), 10); EXPECT_EQ(rect.GetWidth(), -5); EXPECT_EQ(rect.GetHeight(), 16); EXPECT_TRUE(rect.IsEmpty()); } { IRect rect = IRect::MakeXYWH(5, max - 10, 10, 16); EXPECT_EQ(rect.GetLeft(), 5); EXPECT_EQ(rect.GetTop(), max - 10); EXPECT_EQ(rect.GetRight(), 15); EXPECT_EQ(rect.GetBottom(), max); EXPECT_EQ(rect.GetX(), 5); EXPECT_EQ(rect.GetY(), max - 10); EXPECT_EQ(rect.GetWidth(), 10); EXPECT_EQ(rect.GetHeight(), 10); EXPECT_FALSE(rect.IsEmpty()); } { IRect rect = IRect::MakeXYWH(5, min + 10, 10, -16); EXPECT_EQ(rect.GetLeft(), 5); EXPECT_EQ(rect.GetTop(), min + 10); EXPECT_EQ(rect.GetRight(), 15); EXPECT_EQ(rect.GetBottom(), min); EXPECT_EQ(rect.GetX(), 5); EXPECT_EQ(rect.GetY(), min + 10); EXPECT_EQ(rect.GetWidth(), 10); EXPECT_EQ(rect.GetHeight(), -10); EXPECT_TRUE(rect.IsEmpty()); } } TEST(RectTest, RectOverflowLTRB) { auto min = std::numeric_limits<Scalar>::lowest(); auto max = std::numeric_limits<Scalar>::max(); auto inf = std::numeric_limits<Scalar>::infinity(); // 8 cases: // finite negative X, max W // ~min X, ~max W // finite negative Y, max H // ~min Y, ~max H // finite positive X, min W // ~min X, ~min W // finite positive Y, min H // ~min Y, ~min H // a small finite value subtracted from a max value will remain max // a very large finite value (like min) subtracted from max will go to inf { Rect rect = Rect::MakeLTRB(-5.0f, 10.0f, max, 25.0f); EXPECT_EQ(rect.GetLeft(), -5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), max); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), -5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), max); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeLTRB(min + 5.0f, 10.0f, max - 5.0f, 25.0f); EXPECT_EQ(rect.GetLeft(), min + 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), max - 5.0f); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), min + 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), inf); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeLTRB(5.0f, -10.0f, 20.0f, max); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), -10.0f); EXPECT_EQ(rect.GetRight(), 20.0f); EXPECT_EQ(rect.GetBottom(), max); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), -10.0f); EXPECT_EQ(rect.GetWidth(), 15.0f); EXPECT_EQ(rect.GetHeight(), max); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeLTRB(5.0f, min + 10.0f, 20.0f, max - 15.0f); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), min + 10.0f); EXPECT_EQ(rect.GetRight(), 20.0f); EXPECT_EQ(rect.GetBottom(), max - 15.0f); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), min + 10.0f); EXPECT_EQ(rect.GetWidth(), 15.0f); EXPECT_EQ(rect.GetHeight(), inf); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeLTRB(5.0f, 10.0f, min, 25.0f); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), min); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), min); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeLTRB(max - 5.0f, 10.0f, min + 10.0f, 25.0f); EXPECT_EQ(rect.GetLeft(), max - 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), min + 10.0f); EXPECT_EQ(rect.GetBottom(), 25.0f); EXPECT_EQ(rect.GetX(), max - 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), -inf); EXPECT_EQ(rect.GetHeight(), 15.0f); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeLTRB(5.0f, 10.0f, 20.0f, min); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), 10.0f); EXPECT_EQ(rect.GetRight(), 20.0f); EXPECT_EQ(rect.GetBottom(), min); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), 10.0f); EXPECT_EQ(rect.GetWidth(), 15.0f); EXPECT_EQ(rect.GetHeight(), min); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } { Rect rect = Rect::MakeLTRB(5.0f, max - 5.0f, 20.0f, min + 10.0f); EXPECT_EQ(rect.GetLeft(), 5.0f); EXPECT_EQ(rect.GetTop(), max - 5.0f); EXPECT_EQ(rect.GetRight(), 20.0f); EXPECT_EQ(rect.GetBottom(), min + 10.0f); EXPECT_EQ(rect.GetX(), 5.0f); EXPECT_EQ(rect.GetY(), max - 5.0f); EXPECT_EQ(rect.GetWidth(), 15.0f); EXPECT_EQ(rect.GetHeight(), -inf); EXPECT_TRUE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } } TEST(RectTest, IRectOverflowLTRB) { auto min = std::numeric_limits<int64_t>::min(); auto max = std::numeric_limits<int64_t>::max(); // 4 cases // negative l, r near max takes width past max // positive l, r near min takes width below min // negative t, b near max takes width past max // positive t, b near min takes width below min { IRect rect = IRect::MakeLTRB(-10, 10, max - 5, 26); EXPECT_EQ(rect.GetLeft(), -10); EXPECT_EQ(rect.GetTop(), 10); EXPECT_EQ(rect.GetRight(), max - 5); EXPECT_EQ(rect.GetBottom(), 26); EXPECT_EQ(rect.GetX(), -10); EXPECT_EQ(rect.GetY(), 10); EXPECT_EQ(rect.GetWidth(), max); EXPECT_EQ(rect.GetHeight(), 16); EXPECT_FALSE(rect.IsEmpty()); } { IRect rect = IRect::MakeLTRB(10, 10, min + 5, 26); EXPECT_EQ(rect.GetLeft(), 10); EXPECT_EQ(rect.GetTop(), 10); EXPECT_EQ(rect.GetRight(), min + 5); EXPECT_EQ(rect.GetBottom(), 26); EXPECT_EQ(rect.GetX(), 10); EXPECT_EQ(rect.GetY(), 10); EXPECT_EQ(rect.GetWidth(), min); EXPECT_EQ(rect.GetHeight(), 16); EXPECT_TRUE(rect.IsEmpty()); } { IRect rect = IRect::MakeLTRB(5, -10, 15, max - 5); EXPECT_EQ(rect.GetLeft(), 5); EXPECT_EQ(rect.GetTop(), -10); EXPECT_EQ(rect.GetRight(), 15); EXPECT_EQ(rect.GetBottom(), max - 5); EXPECT_EQ(rect.GetX(), 5); EXPECT_EQ(rect.GetY(), -10); EXPECT_EQ(rect.GetWidth(), 10); EXPECT_EQ(rect.GetHeight(), max); EXPECT_FALSE(rect.IsEmpty()); } { IRect rect = IRect::MakeLTRB(5, 10, 15, min + 5); EXPECT_EQ(rect.GetLeft(), 5); EXPECT_EQ(rect.GetTop(), 10); EXPECT_EQ(rect.GetRight(), 15); EXPECT_EQ(rect.GetBottom(), min + 5); EXPECT_EQ(rect.GetX(), 5); EXPECT_EQ(rect.GetY(), 10); EXPECT_EQ(rect.GetWidth(), 10); EXPECT_EQ(rect.GetHeight(), min); EXPECT_TRUE(rect.IsEmpty()); } } TEST(RectTest, RectMakeSize) { { Size s(100, 200); Rect r = Rect::MakeSize(s); Rect expected = Rect::MakeLTRB(0, 0, 100, 200); EXPECT_RECT_NEAR(r, expected); } { ISize s(100, 200); Rect r = Rect::MakeSize(s); Rect expected = Rect::MakeLTRB(0, 0, 100, 200); EXPECT_RECT_NEAR(r, expected); } { Size s(100, 200); IRect r = IRect::MakeSize(s); IRect expected = IRect::MakeLTRB(0, 0, 100, 200); EXPECT_EQ(r, expected); } { ISize s(100, 200); IRect r = IRect::MakeSize(s); IRect expected = IRect::MakeLTRB(0, 0, 100, 200); EXPECT_EQ(r, expected); } } TEST(RectTest, RectMakeMaximum) { Rect rect = Rect::MakeMaximum(); auto inf = std::numeric_limits<Scalar>::infinity(); auto min = std::numeric_limits<Scalar>::lowest(); auto max = std::numeric_limits<Scalar>::max(); EXPECT_EQ(rect.GetLeft(), min); EXPECT_EQ(rect.GetTop(), min); EXPECT_EQ(rect.GetRight(), max); EXPECT_EQ(rect.GetBottom(), max); EXPECT_EQ(rect.GetX(), min); EXPECT_EQ(rect.GetY(), min); EXPECT_EQ(rect.GetWidth(), inf); EXPECT_EQ(rect.GetHeight(), inf); EXPECT_FALSE(rect.IsEmpty()); EXPECT_TRUE(rect.IsFinite()); } TEST(RectTest, IRectMakeMaximum) { IRect rect = IRect::MakeMaximum(); auto min = std::numeric_limits<int64_t>::min(); auto max = std::numeric_limits<int64_t>::max(); EXPECT_EQ(rect.GetLeft(), min); EXPECT_EQ(rect.GetTop(), min); EXPECT_EQ(rect.GetRight(), max); EXPECT_EQ(rect.GetBottom(), max); EXPECT_EQ(rect.GetX(), min); EXPECT_EQ(rect.GetY(), min); EXPECT_EQ(rect.GetWidth(), max); EXPECT_EQ(rect.GetHeight(), max); EXPECT_FALSE(rect.IsEmpty()); } TEST(RectTest, RectFromRect) { EXPECT_EQ(Rect(Rect::MakeXYWH(2, 3, 7, 15)), Rect::MakeXYWH(2.0, 3.0, 7.0, 15.0)); EXPECT_EQ(Rect(Rect::MakeLTRB(2, 3, 7, 15)), Rect::MakeLTRB(2.0, 3.0, 7.0, 15.0)); } TEST(RectTest, IRectFromIRect) { EXPECT_EQ(IRect(IRect::MakeXYWH(2, 3, 7, 15)), // IRect::MakeXYWH(2, 3, 7, 15)); EXPECT_EQ(IRect(IRect::MakeLTRB(2, 3, 7, 15)), // IRect::MakeLTRB(2, 3, 7, 15)); } TEST(RectTest, RectCopy) { // Using fractional-power-of-2 friendly values for equality tests Rect rect = Rect::MakeLTRB(5.125f, 10.25f, 20.625f, 25.375f); Rect copy = rect; EXPECT_EQ(rect, copy); EXPECT_EQ(copy.GetLeft(), 5.125f); EXPECT_EQ(copy.GetTop(), 10.25f); EXPECT_EQ(copy.GetRight(), 20.625f); EXPECT_EQ(copy.GetBottom(), 25.375f); EXPECT_EQ(copy.GetX(), 5.125f); EXPECT_EQ(copy.GetY(), 10.25f); EXPECT_EQ(copy.GetWidth(), 15.5f); EXPECT_EQ(copy.GetHeight(), 15.125f); EXPECT_FALSE(copy.IsEmpty()); EXPECT_TRUE(copy.IsFinite()); } TEST(RectTest, IRectCopy) { IRect rect = IRect::MakeLTRB(5, 10, 20, 25); IRect copy = rect; EXPECT_EQ(rect, copy); EXPECT_EQ(copy.GetLeft(), 5); EXPECT_EQ(copy.GetTop(), 10); EXPECT_EQ(copy.GetRight(), 20); EXPECT_EQ(copy.GetBottom(), 25); EXPECT_EQ(copy.GetX(), 5); EXPECT_EQ(copy.GetY(), 10); EXPECT_EQ(copy.GetWidth(), 15); EXPECT_EQ(copy.GetHeight(), 15); EXPECT_FALSE(copy.IsEmpty()); } TEST(RectTest, RectOriginSizeXYWHGetters) { { Rect r = Rect::MakeOriginSize({10, 20}, {50, 40}); EXPECT_EQ(r.GetOrigin(), Point(10, 20)); EXPECT_EQ(r.GetSize(), Size(50, 40)); EXPECT_EQ(r.GetX(), 10); EXPECT_EQ(r.GetY(), 20); EXPECT_EQ(r.GetWidth(), 50); EXPECT_EQ(r.GetHeight(), 40); auto expected_array = std::array<Scalar, 4>{10, 20, 50, 40}; EXPECT_EQ(r.GetXYWH(), expected_array); } { Rect r = Rect::MakeLTRB(10, 20, 50, 40); EXPECT_EQ(r.GetOrigin(), Point(10, 20)); EXPECT_EQ(r.GetSize(), Size(40, 20)); EXPECT_EQ(r.GetX(), 10); EXPECT_EQ(r.GetY(), 20); EXPECT_EQ(r.GetWidth(), 40); EXPECT_EQ(r.GetHeight(), 20); auto expected_array = std::array<Scalar, 4>{10, 20, 40, 20}; EXPECT_EQ(r.GetXYWH(), expected_array); } } TEST(RectTest, IRectOriginSizeXYWHGetters) { { IRect r = IRect::MakeOriginSize({10, 20}, {50, 40}); EXPECT_EQ(r.GetOrigin(), IPoint(10, 20)); EXPECT_EQ(r.GetSize(), ISize(50, 40)); EXPECT_EQ(r.GetX(), 10); EXPECT_EQ(r.GetY(), 20); EXPECT_EQ(r.GetWidth(), 50); EXPECT_EQ(r.GetHeight(), 40); auto expected_array = std::array<int64_t, 4>{10, 20, 50, 40}; EXPECT_EQ(r.GetXYWH(), expected_array); } { IRect r = IRect::MakeLTRB(10, 20, 50, 40); EXPECT_EQ(r.GetOrigin(), IPoint(10, 20)); EXPECT_EQ(r.GetSize(), ISize(40, 20)); EXPECT_EQ(r.GetX(), 10); EXPECT_EQ(r.GetY(), 20); EXPECT_EQ(r.GetWidth(), 40); EXPECT_EQ(r.GetHeight(), 20); auto expected_array = std::array<int64_t, 4>{10, 20, 40, 20}; EXPECT_EQ(r.GetXYWH(), expected_array); } } TEST(RectTest, RectRoundOutEmpty) { Rect rect; EXPECT_EQ(Rect::RoundOut(rect), Rect()); EXPECT_EQ(IRect::RoundOut(rect), IRect()); } TEST(RectTest, RectRoundOutSimple) { Rect rect = Rect::MakeLTRB(5.125f, 10.75f, 20.625f, 25.375f); EXPECT_EQ(Rect::RoundOut(rect), Rect::MakeLTRB(5.0f, 10.0f, 21.0f, 26.0f)); EXPECT_EQ(IRect::RoundOut(rect), IRect::MakeLTRB(5, 10, 21, 26)); } TEST(RectTest, RectRoundOutToIRectHuge) { auto test = [](int corners) { EXPECT_TRUE(corners >= 0 && corners <= 0xf); Scalar l, t, r, b; int64_t il, it, ir, ib; l = il = 50; t = it = 50; r = ir = 80; b = ib = 80; if ((corners & (1 << 0)) != 0) { l = -1E20; il = std::numeric_limits<int64_t>::min(); } if ((corners & (1 << 1)) != 0) { t = -1E20; it = std::numeric_limits<int64_t>::min(); } if ((corners & (1 << 2)) != 0) { r = +1E20; ir = std::numeric_limits<int64_t>::max(); } if ((corners & (1 << 3)) != 0) { b = +1E20; ib = std::numeric_limits<int64_t>::max(); } Rect rect = Rect::MakeLTRB(l, t, r, b); IRect irect = IRect::RoundOut(rect); EXPECT_EQ(irect.GetLeft(), il) << corners; EXPECT_EQ(irect.GetTop(), it) << corners; EXPECT_EQ(irect.GetRight(), ir) << corners; EXPECT_EQ(irect.GetBottom(), ib) << corners; }; for (int corners = 0; corners <= 15; corners++) { test(corners); } } TEST(RectTest, RectDoesNotIntersectEmpty) { Rect rect = Rect::MakeLTRB(50, 50, 100, 100); auto test = [&rect](Scalar l, Scalar t, Scalar r, Scalar b, const std::string& label) { EXPECT_FALSE(rect.IntersectsWithRect(Rect::MakeLTRB(l, b, r, t))) << label << " with Top/Bottom swapped"; EXPECT_FALSE(rect.IntersectsWithRect(Rect::MakeLTRB(r, b, l, t))) << label << " with Left/Right swapped"; EXPECT_FALSE(rect.IntersectsWithRect(Rect::MakeLTRB(r, t, l, b))) << label << " with all sides swapped"; }; test(20, 20, 30, 30, "Above and Left"); test(70, 20, 80, 30, "Above"); test(120, 20, 130, 30, "Above and Right"); test(120, 70, 130, 80, "Right"); test(120, 120, 130, 130, "Below and Right"); test(70, 120, 80, 130, "Below"); test(20, 120, 30, 130, "Below and Left"); test(20, 70, 30, 80, "Left"); test(70, 70, 80, 80, "Inside"); test(40, 70, 60, 80, "Straddling Left"); test(70, 40, 80, 60, "Straddling Top"); test(90, 70, 110, 80, "Straddling Right"); test(70, 90, 80, 110, "Straddling Bottom"); } TEST(RectTest, IRectDoesNotIntersectEmpty) { IRect rect = IRect::MakeLTRB(50, 50, 100, 100); auto test = [&rect](int64_t l, int64_t t, int64_t r, int64_t b, const std::string& label) { EXPECT_FALSE(rect.IntersectsWithRect(IRect::MakeLTRB(l, b, r, t))) << label << " with Top/Bottom swapped"; EXPECT_FALSE(rect.IntersectsWithRect(IRect::MakeLTRB(r, b, l, t))) << label << " with Left/Right swapped"; EXPECT_FALSE(rect.IntersectsWithRect(IRect::MakeLTRB(r, t, l, b))) << label << " with all sides swapped"; }; test(20, 20, 30, 30, "Above and Left"); test(70, 20, 80, 30, "Above"); test(120, 20, 130, 30, "Above and Right"); test(120, 70, 130, 80, "Right"); test(120, 120, 130, 130, "Below and Right"); test(70, 120, 80, 130, "Below"); test(20, 120, 30, 130, "Below and Left"); test(20, 70, 30, 80, "Left"); test(70, 70, 80, 80, "Inside"); test(40, 70, 60, 80, "Straddling Left"); test(70, 40, 80, 60, "Straddling Top"); test(90, 70, 110, 80, "Straddling Right"); test(70, 90, 80, 110, "Straddling Bottom"); } TEST(RectTest, EmptyRectDoesNotIntersect) { Rect rect = Rect::MakeLTRB(50, 50, 100, 100); auto test = [&rect](Scalar l, Scalar t, Scalar r, Scalar b, const std::string& label) { EXPECT_FALSE(Rect::MakeLTRB(l, b, r, t).IntersectsWithRect(rect)) << label << " with Top/Bottom swapped"; EXPECT_FALSE(Rect::MakeLTRB(r, b, l, t).IntersectsWithRect(rect)) << label << " with Left/Right swapped"; EXPECT_FALSE(Rect::MakeLTRB(r, t, l, b).IntersectsWithRect(rect)) << label << " with all sides swapped"; }; test(20, 20, 30, 30, "Above and Left"); test(70, 20, 80, 30, "Above"); test(120, 20, 130, 30, "Above and Right"); test(120, 70, 130, 80, "Right"); test(120, 120, 130, 130, "Below and Right"); test(70, 120, 80, 130, "Below"); test(20, 120, 30, 130, "Below and Left"); test(20, 70, 30, 80, "Left"); test(70, 70, 80, 80, "Inside"); test(40, 70, 60, 80, "Straddling Left"); test(70, 40, 80, 60, "Straddling Top"); test(90, 70, 110, 80, "Straddling Right"); test(70, 90, 80, 110, "Straddling Bottom"); } TEST(RectTest, EmptyIRectDoesNotIntersect) { IRect rect = IRect::MakeLTRB(50, 50, 100, 100); auto test = [&rect](int64_t l, int64_t t, int64_t r, int64_t b, const std::string& label) { EXPECT_FALSE(IRect::MakeLTRB(l, b, r, t).IntersectsWithRect(rect)) << label << " with Top/Bottom swapped"; EXPECT_FALSE(IRect::MakeLTRB(r, b, l, t).IntersectsWithRect(rect)) << label << " with Left/Right swapped"; EXPECT_FALSE(IRect::MakeLTRB(r, t, l, b).IntersectsWithRect(rect)) << label << " with all sides swapped"; }; test(20, 20, 30, 30, "Above and Left"); test(70, 20, 80, 30, "Above"); test(120, 20, 130, 30, "Above and Right"); test(120, 70, 130, 80, "Right"); test(120, 120, 130, 130, "Below and Right"); test(70, 120, 80, 130, "Below"); test(20, 120, 30, 130, "Below and Left"); test(20, 70, 30, 80, "Left"); test(70, 70, 80, 80, "Inside"); test(40, 70, 60, 80, "Straddling Left"); test(70, 40, 80, 60, "Straddling Top"); test(90, 70, 110, 80, "Straddling Right"); test(70, 90, 80, 110, "Straddling Bottom"); } TEST(RectTest, RectScale) { auto test1 = [](Rect rect, Scalar scale) { Rect expected = Rect::MakeXYWH(rect.GetX() * scale, // rect.GetY() * scale, // rect.GetWidth() * scale, // rect.GetHeight() * scale); EXPECT_RECT_NEAR(rect.Scale(scale), expected) // << rect << " * " << scale; EXPECT_RECT_NEAR(rect.Scale(scale, scale), expected) // << rect << " * " << scale; EXPECT_RECT_NEAR(rect.Scale(Point(scale, scale)), expected) // << rect << " * " << scale; EXPECT_RECT_NEAR(rect.Scale(Size(scale, scale)), expected) // << rect << " * " << scale; }; auto test2 = [&test1](Rect rect, Scalar scale_x, Scalar scale_y) { Rect expected = Rect::MakeXYWH(rect.GetX() * scale_x, // rect.GetY() * scale_y, // rect.GetWidth() * scale_x, // rect.GetHeight() * scale_y); EXPECT_RECT_NEAR(rect.Scale(scale_x, scale_y), expected) // << rect << " * " << scale_x << ", " << scale_y; EXPECT_RECT_NEAR(rect.Scale(Point(scale_x, scale_y)), expected) // << rect << " * " << scale_x << ", " << scale_y; EXPECT_RECT_NEAR(rect.Scale(Size(scale_x, scale_y)), expected) // << rect << " * " << scale_x << ", " << scale_y; test1(rect, scale_x); test1(rect, scale_y); }; test2(Rect::MakeLTRB(10, 15, 100, 150), 1.0, 0.0); test2(Rect::MakeLTRB(10, 15, 100, 150), 0.0, 1.0); test2(Rect::MakeLTRB(10, 15, 100, 150), 0.0, 0.0); test2(Rect::MakeLTRB(10, 15, 100, 150), 2.5, 3.5); test2(Rect::MakeLTRB(10, 15, 100, 150), 3.5, 2.5); test2(Rect::MakeLTRB(10, 15, -100, 150), 2.5, 3.5); test2(Rect::MakeLTRB(10, 15, 100, -150), 2.5, 3.5); test2(Rect::MakeLTRB(10, 15, 100, 150), -2.5, 3.5); test2(Rect::MakeLTRB(10, 15, 100, 150), 2.5, -3.5); } TEST(RectTest, IRectScale) { auto test1 = [](IRect rect, int64_t scale) { IRect expected = IRect::MakeXYWH(rect.GetX() * scale, // rect.GetY() * scale, // rect.GetWidth() * scale, // rect.GetHeight() * scale); EXPECT_EQ(rect.Scale(scale), expected) // << rect << " * " << scale; EXPECT_EQ(rect.Scale(scale, scale), expected) // << rect << " * " << scale; EXPECT_EQ(rect.Scale(IPoint(scale, scale)), expected) // << rect << " * " << scale; EXPECT_EQ(rect.Scale(ISize(scale, scale)), expected) // << rect << " * " << scale; }; auto test2 = [&test1](IRect rect, int64_t scale_x, int64_t scale_y) { IRect expected = IRect::MakeXYWH(rect.GetX() * scale_x, // rect.GetY() * scale_y, // rect.GetWidth() * scale_x, // rect.GetHeight() * scale_y); EXPECT_EQ(rect.Scale(scale_x, scale_y), expected) // << rect << " * " << scale_x << ", " << scale_y; EXPECT_EQ(rect.Scale(IPoint(scale_x, scale_y)), expected) // << rect << " * " << scale_x << ", " << scale_y; EXPECT_EQ(rect.Scale(ISize(scale_x, scale_y)), expected) // << rect << " * " << scale_x << ", " << scale_y; test1(rect, scale_x); test1(rect, scale_y); }; test2(IRect::MakeLTRB(10, 15, 100, 150), 2, 3); test2(IRect::MakeLTRB(10, 15, 100, 150), 3, 2); test2(IRect::MakeLTRB(10, 15, -100, 150), 2, 3); test2(IRect::MakeLTRB(10, 15, 100, -150), 2, 3); test2(IRect::MakeLTRB(10, 15, 100, 150), -2, 3); test2(IRect::MakeLTRB(10, 15, 100, 150), 2, -3); } TEST(RectTest, RectArea) { EXPECT_EQ(Rect::MakeXYWH(0, 0, 100, 200).Area(), 20000); EXPECT_EQ(Rect::MakeXYWH(10, 20, 100, 200).Area(), 20000); EXPECT_EQ(Rect::MakeXYWH(0, 0, 200, 100).Area(), 20000); EXPECT_EQ(Rect::MakeXYWH(10, 20, 200, 100).Area(), 20000); EXPECT_EQ(Rect::MakeXYWH(0, 0, 100, 100).Area(), 10000); EXPECT_EQ(Rect::MakeXYWH(10, 20, 100, 100).Area(), 10000); } TEST(RectTest, IRectArea) { EXPECT_EQ(IRect::MakeXYWH(0, 0, 100, 200).Area(), 20000); EXPECT_EQ(IRect::MakeXYWH(10, 20, 100, 200).Area(), 20000); EXPECT_EQ(IRect::MakeXYWH(0, 0, 200, 100).Area(), 20000); EXPECT_EQ(IRect::MakeXYWH(10, 20, 200, 100).Area(), 20000); EXPECT_EQ(IRect::MakeXYWH(0, 0, 100, 100).Area(), 10000); EXPECT_EQ(IRect::MakeXYWH(10, 20, 100, 100).Area(), 10000); } TEST(RectTest, RectGetNormalizingTransform) { { // Checks for expected matrix values auto r = Rect::MakeXYWH(100, 200, 200, 400); EXPECT_EQ(r.GetNormalizingTransform(), Matrix::MakeScale({0.005, 0.0025, 1.0}) * Matrix::MakeTranslation({-100, -200})); } { // Checks for expected transform of points relative to the rect auto r = Rect::MakeLTRB(300, 500, 400, 700); auto m = r.GetNormalizingTransform(); // The 4 corners of the rect => (0, 0) to (1, 1) EXPECT_EQ(m * Point(300, 500), Point(0, 0)); EXPECT_EQ(m * Point(400, 500), Point(1, 0)); EXPECT_EQ(m * Point(400, 700), Point(1, 1)); EXPECT_EQ(m * Point(300, 700), Point(0, 1)); // The center => (0.5, 0.5) EXPECT_EQ(m * Point(350, 600), Point(0.5, 0.5)); // Outside the 4 corners => (-1, -1) to (2, 2) EXPECT_EQ(m * Point(200, 300), Point(-1, -1)); EXPECT_EQ(m * Point(500, 300), Point(2, -1)); EXPECT_EQ(m * Point(500, 900), Point(2, 2)); EXPECT_EQ(m * Point(200, 900), Point(-1, 2)); } { // Checks for behavior with empty rects auto zero = Matrix::MakeScale({0.0, 0.0, 1.0}); // Empty for width and/or height == 0 EXPECT_EQ(Rect::MakeXYWH(10, 10, 0, 10).GetNormalizingTransform(), zero); EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, 0).GetNormalizingTransform(), zero); EXPECT_EQ(Rect::MakeXYWH(10, 10, 0, 0).GetNormalizingTransform(), zero); // Empty for width and/or height < 0 EXPECT_EQ(Rect::MakeXYWH(10, 10, -1, 10).GetNormalizingTransform(), zero); EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, -1).GetNormalizingTransform(), zero); EXPECT_EQ(Rect::MakeXYWH(10, 10, -1, -1).GetNormalizingTransform(), zero); } { // Checks for behavior with non-finite rects auto z = Matrix::MakeScale({0.0, 0.0, 1.0}); auto nan = std::numeric_limits<Scalar>::quiet_NaN(); auto inf = std::numeric_limits<Scalar>::infinity(); // Non-finite for width and/or height == nan EXPECT_EQ(Rect::MakeXYWH(10, 10, nan, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, nan).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, 10, nan, nan).GetNormalizingTransform(), z); // Non-finite for width and/or height == inf EXPECT_EQ(Rect::MakeXYWH(10, 10, inf, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, inf).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, 10, inf, inf).GetNormalizingTransform(), z); // Non-finite for width and/or height == -inf EXPECT_EQ(Rect::MakeXYWH(10, 10, -inf, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, -inf).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, 10, -inf, -inf).GetNormalizingTransform(), z); // Non-finite for origin X and/or Y == nan EXPECT_EQ(Rect::MakeXYWH(nan, 10, 10, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, nan, 10, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(nan, nan, 10, 10).GetNormalizingTransform(), z); // Non-finite for origin X and/or Y == inf EXPECT_EQ(Rect::MakeXYWH(inf, 10, 10, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, inf, 10, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(inf, inf, 10, 10).GetNormalizingTransform(), z); // Non-finite for origin X and/or Y == -inf EXPECT_EQ(Rect::MakeXYWH(-inf, 10, 10, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(10, -inf, 10, 10).GetNormalizingTransform(), z); EXPECT_EQ(Rect::MakeXYWH(-inf, -inf, 10, 10).GetNormalizingTransform(), z); } } TEST(RectTest, IRectGetNormalizingTransform) { { // Checks for expected matrix values auto r = IRect::MakeXYWH(100, 200, 200, 400); EXPECT_EQ(r.GetNormalizingTransform(), Matrix::MakeScale({0.005, 0.0025, 1.0}) * Matrix::MakeTranslation({-100, -200})); } { // Checks for expected transform of points relative to the rect auto r = IRect::MakeLTRB(300, 500, 400, 700); auto m = r.GetNormalizingTransform(); // The 4 corners of the rect => (0, 0) to (1, 1) EXPECT_EQ(m * Point(300, 500), Point(0, 0)); EXPECT_EQ(m * Point(400, 500), Point(1, 0)); EXPECT_EQ(m * Point(400, 700), Point(1, 1)); EXPECT_EQ(m * Point(300, 700), Point(0, 1)); // The center => (0.5, 0.5) EXPECT_EQ(m * Point(350, 600), Point(0.5, 0.5)); // Outside the 4 corners => (-1, -1) to (2, 2) EXPECT_EQ(m * Point(200, 300), Point(-1, -1)); EXPECT_EQ(m * Point(500, 300), Point(2, -1)); EXPECT_EQ(m * Point(500, 900), Point(2, 2)); EXPECT_EQ(m * Point(200, 900), Point(-1, 2)); } { // Checks for behavior with empty rects auto zero = Matrix::MakeScale({0.0, 0.0, 1.0}); // Empty for width and/or height == 0 EXPECT_EQ(IRect::MakeXYWH(10, 10, 0, 10).GetNormalizingTransform(), zero); EXPECT_EQ(IRect::MakeXYWH(10, 10, 10, 0).GetNormalizingTransform(), zero); EXPECT_EQ(IRect::MakeXYWH(10, 10, 0, 0).GetNormalizingTransform(), zero); // Empty for width and/or height < 0 EXPECT_EQ(IRect::MakeXYWH(10, 10, -1, 10).GetNormalizingTransform(), zero); EXPECT_EQ(IRect::MakeXYWH(10, 10, 10, -1).GetNormalizingTransform(), zero); EXPECT_EQ(IRect::MakeXYWH(10, 10, -1, -1).GetNormalizingTransform(), zero); } } TEST(RectTest, RectXYWHIsEmpty) { auto nan = std::numeric_limits<Scalar>::quiet_NaN(); // Non-empty EXPECT_FALSE(Rect::MakeXYWH(1.5, 2.3, 10.5, 7.2).IsEmpty()); // Empty both width and height both 0 or negative, in all combinations EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 0.0, 0.0).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, -1.0, -1.0).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 0.0, -1.0).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, -1.0, 0.0).IsEmpty()); // Empty for 0 or negative width or height (but not both at the same time) EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 10.5, 0.0).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 10.5, -1.0).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 0.0, 7.2).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, -1.0, 7.2).IsEmpty()); // Empty for NaN in width or height or both EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 10.5, nan).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, nan, 7.2).IsEmpty()); EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, nan, nan).IsEmpty()); } TEST(RectTest, IRectXYWHIsEmpty) { // Non-empty EXPECT_FALSE(IRect::MakeXYWH(1, 2, 10, 7).IsEmpty()); // Empty both width and height both 0 or negative, in all combinations EXPECT_TRUE(IRect::MakeXYWH(1, 2, 0, 0).IsEmpty()); EXPECT_TRUE(IRect::MakeXYWH(1, 2, -1, -1).IsEmpty()); EXPECT_TRUE(IRect::MakeXYWH(1, 2, -1, 0).IsEmpty()); EXPECT_TRUE(IRect::MakeXYWH(1, 2, 0, -1).IsEmpty()); // Empty for 0 or negative width or height (but not both at the same time) EXPECT_TRUE(IRect::MakeXYWH(1, 2, 10, 0).IsEmpty()); EXPECT_TRUE(IRect::MakeXYWH(1, 2, 10, -1).IsEmpty()); EXPECT_TRUE(IRect::MakeXYWH(1, 2, 0, 7).IsEmpty()); EXPECT_TRUE(IRect::MakeXYWH(1, 2, -1, 7).IsEmpty()); } TEST(RectTest, MakePointBoundsQuad) { Quad quad = { Point(10, 10), Point(20, 10), Point(10, 20), Point(20, 20), }; std::optional<Rect> bounds = Rect::MakePointBounds(quad); EXPECT_TRUE(bounds.has_value()); if (bounds.has_value()) { EXPECT_TRUE(RectNear(bounds.value(), Rect::MakeLTRB(10, 10, 20, 20))); } } TEST(RectTest, IsSquare) { EXPECT_TRUE(Rect::MakeXYWH(10, 30, 20, 20).IsSquare()); EXPECT_FALSE(Rect::MakeXYWH(10, 30, 20, 19).IsSquare()); EXPECT_FALSE(Rect::MakeXYWH(10, 30, 19, 20).IsSquare()); EXPECT_TRUE(Rect::MakeMaximum().IsSquare()); EXPECT_TRUE(IRect::MakeXYWH(10, 30, 20, 20).IsSquare()); EXPECT_FALSE(IRect::MakeXYWH(10, 30, 20, 19).IsSquare()); EXPECT_FALSE(IRect::MakeXYWH(10, 30, 19, 20).IsSquare()); EXPECT_TRUE(IRect::MakeMaximum().IsSquare()); } TEST(RectTest, GetCenter) { EXPECT_EQ(Rect::MakeXYWH(10, 30, 20, 20).GetCenter(), Point(20, 40)); EXPECT_EQ(Rect::MakeXYWH(10, 30, 20, 19).GetCenter(), Point(20, 39.5)); EXPECT_EQ(Rect::MakeMaximum().GetCenter(), Point(0, 0)); // Note that we expect a Point as the answer from an IRect EXPECT_EQ(IRect::MakeXYWH(10, 30, 20, 20).GetCenter(), Point(20, 40)); EXPECT_EQ(IRect::MakeXYWH(10, 30, 20, 19).GetCenter(), Point(20, 39.5)); EXPECT_EQ(IRect::MakeMaximum().GetCenter(), Point(0, 0)); } TEST(RectTest, RectExpand) { auto rect = Rect::MakeLTRB(100, 100, 200, 200); // Expand(T amount) EXPECT_EQ(rect.Expand(10), Rect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(-10), Rect::MakeLTRB(110, 110, 190, 190)); // Expand(amount, amount) EXPECT_EQ(rect.Expand(10, 10), Rect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(10, -10), Rect::MakeLTRB(90, 110, 210, 190)); EXPECT_EQ(rect.Expand(-10, 10), Rect::MakeLTRB(110, 90, 190, 210)); EXPECT_EQ(rect.Expand(-10, -10), Rect::MakeLTRB(110, 110, 190, 190)); // Expand(amount, amount, amount, amount) EXPECT_EQ(rect.Expand(10, 20, 30, 40), Rect::MakeLTRB(90, 80, 230, 240)); EXPECT_EQ(rect.Expand(-10, 20, 30, 40), Rect::MakeLTRB(110, 80, 230, 240)); EXPECT_EQ(rect.Expand(10, -20, 30, 40), Rect::MakeLTRB(90, 120, 230, 240)); EXPECT_EQ(rect.Expand(10, 20, -30, 40), Rect::MakeLTRB(90, 80, 170, 240)); EXPECT_EQ(rect.Expand(10, 20, 30, -40), Rect::MakeLTRB(90, 80, 230, 160)); // Expand(Point amount) EXPECT_EQ(rect.Expand(Point{10, 10}), Rect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(Point{10, -10}), Rect::MakeLTRB(90, 110, 210, 190)); EXPECT_EQ(rect.Expand(Point{-10, 10}), Rect::MakeLTRB(110, 90, 190, 210)); EXPECT_EQ(rect.Expand(Point{-10, -10}), Rect::MakeLTRB(110, 110, 190, 190)); // Expand(Size amount) EXPECT_EQ(rect.Expand(Size{10, 10}), Rect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(Size{10, -10}), Rect::MakeLTRB(90, 110, 210, 190)); EXPECT_EQ(rect.Expand(Size{-10, 10}), Rect::MakeLTRB(110, 90, 190, 210)); EXPECT_EQ(rect.Expand(Size{-10, -10}), Rect::MakeLTRB(110, 110, 190, 190)); } TEST(RectTest, IRectExpand) { auto rect = IRect::MakeLTRB(100, 100, 200, 200); // Expand(T amount) EXPECT_EQ(rect.Expand(10), IRect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(-10), IRect::MakeLTRB(110, 110, 190, 190)); // Expand(amount, amount) EXPECT_EQ(rect.Expand(10, 10), IRect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(10, -10), IRect::MakeLTRB(90, 110, 210, 190)); EXPECT_EQ(rect.Expand(-10, 10), IRect::MakeLTRB(110, 90, 190, 210)); EXPECT_EQ(rect.Expand(-10, -10), IRect::MakeLTRB(110, 110, 190, 190)); // Expand(amount, amount, amount, amount) EXPECT_EQ(rect.Expand(10, 20, 30, 40), IRect::MakeLTRB(90, 80, 230, 240)); EXPECT_EQ(rect.Expand(-10, 20, 30, 40), IRect::MakeLTRB(110, 80, 230, 240)); EXPECT_EQ(rect.Expand(10, -20, 30, 40), IRect::MakeLTRB(90, 120, 230, 240)); EXPECT_EQ(rect.Expand(10, 20, -30, 40), IRect::MakeLTRB(90, 80, 170, 240)); EXPECT_EQ(rect.Expand(10, 20, 30, -40), IRect::MakeLTRB(90, 80, 230, 160)); // Expand(IPoint amount) EXPECT_EQ(rect.Expand(IPoint{10, 10}), IRect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(IPoint{10, -10}), IRect::MakeLTRB(90, 110, 210, 190)); EXPECT_EQ(rect.Expand(IPoint{-10, 10}), IRect::MakeLTRB(110, 90, 190, 210)); EXPECT_EQ(rect.Expand(IPoint{-10, -10}), IRect::MakeLTRB(110, 110, 190, 190)); // Expand(ISize amount) EXPECT_EQ(rect.Expand(ISize{10, 10}), IRect::MakeLTRB(90, 90, 210, 210)); EXPECT_EQ(rect.Expand(ISize{10, -10}), IRect::MakeLTRB(90, 110, 210, 190)); EXPECT_EQ(rect.Expand(ISize{-10, 10}), IRect::MakeLTRB(110, 90, 190, 210)); EXPECT_EQ(rect.Expand(ISize{-10, -10}), IRect::MakeLTRB(110, 110, 190, 190)); } TEST(RectTest, ContainsFloatingPoint) { auto rect1 = Rect::MakeXYWH(472.599945f, 440.999969f, 1102.80005f, 654.000061f); auto rect2 = Rect::MakeXYWH(724.f, 618.f, 600.f, 300.f); EXPECT_TRUE(rect1.Contains(rect2)); } template <typename R> static constexpr inline R flip_lr(R rect) { return R::MakeLTRB(rect.GetRight(), rect.GetTop(), // rect.GetLeft(), rect.GetBottom()); } template <typename R> static constexpr inline R flip_tb(R rect) { return R::MakeLTRB(rect.GetLeft(), rect.GetBottom(), // rect.GetRight(), rect.GetTop()); } template <typename R> static constexpr inline R flip_lrtb(R rect) { return flip_lr(flip_tb(rect)); } static constexpr inline Rect swap_nan(const Rect& rect, int index) { Scalar nan = std::numeric_limits<Scalar>::quiet_NaN(); FML_DCHECK(index >= 0 && index <= 15); Scalar l = ((index & (1 << 0)) != 0) ? nan : rect.GetLeft(); Scalar t = ((index & (1 << 1)) != 0) ? nan : rect.GetTop(); Scalar r = ((index & (1 << 2)) != 0) ? nan : rect.GetRight(); Scalar b = ((index & (1 << 3)) != 0) ? nan : rect.GetBottom(); return Rect::MakeLTRB(l, t, r, b); } static constexpr inline Point swap_nan(const Point& point, int index) { Scalar nan = std::numeric_limits<Scalar>::quiet_NaN(); FML_DCHECK(index >= 0 && index <= 3); Scalar x = ((index & (1 << 0)) != 0) ? nan : point.x; Scalar y = ((index & (1 << 1)) != 0) ? nan : point.y; return Point(x, y); } TEST(RectTest, RectUnion) { auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_TRUE(a.IsFinite()) << label; ASSERT_TRUE(b.IsFinite()) << label; ASSERT_FALSE(a.Union(b).IsEmpty()); for (int i = 1; i < 16; i++) { // NaN in a produces b EXPECT_EQ(swap_nan(a, i).Union(b), b) << label << ", index = " << i; // NaN in b produces a EXPECT_EQ(a.Union(swap_nan(b, i)), a) << label << ", index = " << i; // NaN in both is empty for (int j = 1; j < 16; j++) { EXPECT_TRUE(swap_nan(a, i).Union(swap_nan(b, j)).IsEmpty()) << label << ", indices = " << i << ", " << j; } } }; auto check_empty_flips = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // b is allowed to be empty // unflipped a vs flipped (empty) b yields a EXPECT_EQ(a.Union(flip_lr(b)), a) << label; EXPECT_EQ(a.Union(flip_tb(b)), a) << label; EXPECT_EQ(a.Union(flip_lrtb(b)), a) << label; // flipped (empty) a vs unflipped b yields b EXPECT_EQ(flip_lr(a).Union(b), b) << label; EXPECT_EQ(flip_tb(a).Union(b), b) << label; EXPECT_EQ(flip_lrtb(a).Union(b), b) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_TRUE(flip_lr(a).Union(flip_lr(b)).IsEmpty()) << label; EXPECT_TRUE(flip_tb(a).Union(flip_tb(b)).IsEmpty()) << label; EXPECT_TRUE(flip_lrtb(a).Union(flip_lrtb(b)).IsEmpty()) << label; }; auto test = [&check_nans, &check_empty_flips](const Rect& a, const Rect& b, const Rect& result) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_EQ(a.Union(b), result) << label; EXPECT_EQ(b.Union(a), result) << label; check_empty_flips(a, b, label); check_nans(a, b, label); }; { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(0, 0, 0, 0); auto expected = Rect::MakeXYWH(100, 100, 100, 100); test(a, b, expected); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(0, 0, 1, 1); auto expected = Rect::MakeXYWH(0, 0, 200, 200); test(a, b, expected); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(10, 10, 1, 1); auto expected = Rect::MakeXYWH(10, 10, 190, 190); test(a, b, expected); } { auto a = Rect::MakeXYWH(0, 0, 100, 100); auto b = Rect::MakeXYWH(10, 10, 100, 100); auto expected = Rect::MakeXYWH(0, 0, 110, 110); test(a, b, expected); } { auto a = Rect::MakeXYWH(0, 0, 100, 100); auto b = Rect::MakeXYWH(100, 100, 100, 100); auto expected = Rect::MakeXYWH(0, 0, 200, 200); test(a, b, expected); } } TEST(RectTest, OptRectUnion) { auto a = Rect::MakeLTRB(0, 0, 100, 100); auto b = Rect::MakeLTRB(100, 100, 200, 200); auto c = Rect::MakeLTRB(100, 0, 200, 100); // NullOpt, NullOpt EXPECT_FALSE(Rect::Union(std::nullopt, std::nullopt).has_value()); EXPECT_EQ(Rect::Union(std::nullopt, std::nullopt), std::nullopt); auto test1 = [](const Rect& r) { // Rect, NullOpt EXPECT_TRUE(Rect::Union(r, std::nullopt).has_value()); EXPECT_EQ(Rect::Union(r, std::nullopt).value(), r); // OptRect, NullOpt EXPECT_TRUE(Rect::Union(std::optional(r), std::nullopt).has_value()); EXPECT_EQ(Rect::Union(std::optional(r), std::nullopt).value(), r); // NullOpt, Rect EXPECT_TRUE(Rect::Union(std::nullopt, r).has_value()); EXPECT_EQ(Rect::Union(std::nullopt, r).value(), r); // NullOpt, OptRect EXPECT_TRUE(Rect::Union(std::nullopt, std::optional(r)).has_value()); EXPECT_EQ(Rect::Union(std::nullopt, std::optional(r)).value(), r); }; test1(a); test1(b); test1(c); auto test2 = [](const Rect& a, const Rect& b, const Rect& u) { ASSERT_EQ(a.Union(b), u); // Rect, OptRect EXPECT_TRUE(Rect::Union(a, std::optional(b)).has_value()); EXPECT_EQ(Rect::Union(a, std::optional(b)).value(), u); // OptRect, Rect EXPECT_TRUE(Rect::Union(std::optional(a), b).has_value()); EXPECT_EQ(Rect::Union(std::optional(a), b).value(), u); // OptRect, OptRect EXPECT_TRUE(Rect::Union(std::optional(a), std::optional(b)).has_value()); EXPECT_EQ(Rect::Union(std::optional(a), std::optional(b)).value(), u); }; test2(a, b, Rect::MakeLTRB(0, 0, 200, 200)); test2(a, c, Rect::MakeLTRB(0, 0, 200, 100)); test2(b, c, Rect::MakeLTRB(100, 0, 200, 200)); } TEST(RectTest, IRectUnion) { auto check_empty_flips = [](const IRect& a, const IRect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // b is allowed to be empty // unflipped a vs flipped (empty) b yields a EXPECT_EQ(a.Union(flip_lr(b)), a) << label; EXPECT_EQ(a.Union(flip_tb(b)), a) << label; EXPECT_EQ(a.Union(flip_lrtb(b)), a) << label; // flipped (empty) a vs unflipped b yields b EXPECT_EQ(flip_lr(a).Union(b), b) << label; EXPECT_EQ(flip_tb(a).Union(b), b) << label; EXPECT_EQ(flip_lrtb(a).Union(b), b) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_TRUE(flip_lr(a).Union(flip_lr(b)).IsEmpty()) << label; EXPECT_TRUE(flip_tb(a).Union(flip_tb(b)).IsEmpty()) << label; EXPECT_TRUE(flip_lrtb(a).Union(flip_lrtb(b)).IsEmpty()) << label; }; auto test = [&check_empty_flips](const IRect& a, const IRect& b, const IRect& result) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_EQ(a.Union(b), result) << label; EXPECT_EQ(b.Union(a), result) << label; check_empty_flips(a, b, label); }; { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(0, 0, 0, 0); auto expected = IRect::MakeXYWH(100, 100, 100, 100); test(a, b, expected); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(0, 0, 1, 1); auto expected = IRect::MakeXYWH(0, 0, 200, 200); test(a, b, expected); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(10, 10, 1, 1); auto expected = IRect::MakeXYWH(10, 10, 190, 190); test(a, b, expected); } { auto a = IRect::MakeXYWH(0, 0, 100, 100); auto b = IRect::MakeXYWH(10, 10, 100, 100); auto expected = IRect::MakeXYWH(0, 0, 110, 110); test(a, b, expected); } { auto a = IRect::MakeXYWH(0, 0, 100, 100); auto b = IRect::MakeXYWH(100, 100, 100, 100); auto expected = IRect::MakeXYWH(0, 0, 200, 200); test(a, b, expected); } } TEST(RectTest, OptIRectUnion) { auto a = IRect::MakeLTRB(0, 0, 100, 100); auto b = IRect::MakeLTRB(100, 100, 200, 200); auto c = IRect::MakeLTRB(100, 0, 200, 100); // NullOpt, NullOpt EXPECT_FALSE(IRect::Union(std::nullopt, std::nullopt).has_value()); EXPECT_EQ(IRect::Union(std::nullopt, std::nullopt), std::nullopt); auto test1 = [](const IRect& r) { // Rect, NullOpt EXPECT_TRUE(IRect::Union(r, std::nullopt).has_value()); EXPECT_EQ(IRect::Union(r, std::nullopt).value(), r); // OptRect, NullOpt EXPECT_TRUE(IRect::Union(std::optional(r), std::nullopt).has_value()); EXPECT_EQ(IRect::Union(std::optional(r), std::nullopt).value(), r); // NullOpt, Rect EXPECT_TRUE(IRect::Union(std::nullopt, r).has_value()); EXPECT_EQ(IRect::Union(std::nullopt, r).value(), r); // NullOpt, OptRect EXPECT_TRUE(IRect::Union(std::nullopt, std::optional(r)).has_value()); EXPECT_EQ(IRect::Union(std::nullopt, std::optional(r)).value(), r); }; test1(a); test1(b); test1(c); auto test2 = [](const IRect& a, const IRect& b, const IRect& u) { ASSERT_EQ(a.Union(b), u); // Rect, OptRect EXPECT_TRUE(IRect::Union(a, std::optional(b)).has_value()); EXPECT_EQ(IRect::Union(a, std::optional(b)).value(), u); // OptRect, Rect EXPECT_TRUE(IRect::Union(std::optional(a), b).has_value()); EXPECT_EQ(IRect::Union(std::optional(a), b).value(), u); // OptRect, OptRect EXPECT_TRUE(IRect::Union(std::optional(a), std::optional(b)).has_value()); EXPECT_EQ(IRect::Union(std::optional(a), std::optional(b)).value(), u); }; test2(a, b, IRect::MakeLTRB(0, 0, 200, 200)); test2(a, c, IRect::MakeLTRB(0, 0, 200, 100)); test2(b, c, IRect::MakeLTRB(100, 0, 200, 200)); } TEST(RectTest, RectIntersection) { auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_TRUE(a.IsFinite()) << label; ASSERT_TRUE(b.IsFinite()) << label; for (int i = 1; i < 16; i++) { // NaN in a produces empty EXPECT_FALSE(swap_nan(a, i).Intersection(b).has_value()) << label << ", index = " << i; // NaN in b produces empty EXPECT_FALSE(a.Intersection(swap_nan(b, i)).has_value()) << label << ", index = " << i; // NaN in both is empty for (int j = 1; j < 16; j++) { EXPECT_FALSE(swap_nan(a, i).Intersection(swap_nan(b, j)).has_value()) << label << ", indices = " << i << ", " << j; } } }; auto check_empty_flips = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // b is allowed to be empty // unflipped a vs flipped (empty) b yields a EXPECT_FALSE(a.Intersection(flip_lr(b)).has_value()) << label; EXPECT_FALSE(a.Intersection(flip_tb(b)).has_value()) << label; EXPECT_FALSE(a.Intersection(flip_lrtb(b)).has_value()) << label; // flipped (empty) a vs unflipped b yields b EXPECT_FALSE(flip_lr(a).Intersection(b).has_value()) << label; EXPECT_FALSE(flip_tb(a).Intersection(b).has_value()) << label; EXPECT_FALSE(flip_lrtb(a).Intersection(b).has_value()) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_FALSE(flip_lr(a).Intersection(flip_lr(b)).has_value()) << label; EXPECT_FALSE(flip_tb(a).Intersection(flip_tb(b)).has_value()) << label; EXPECT_FALSE(flip_lrtb(a).Intersection(flip_lrtb(b)).has_value()) << label; }; auto test_non_empty = [&check_nans, &check_empty_flips]( const Rect& a, const Rect& b, const Rect& result) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_TRUE(a.Intersection(b).has_value()) << label; EXPECT_TRUE(b.Intersection(a).has_value()) << label; EXPECT_EQ(a.Intersection(b), result) << label; EXPECT_EQ(b.Intersection(a), result) << label; check_empty_flips(a, b, label); check_nans(a, b, label); }; auto test_empty = [&check_nans, &check_empty_flips](const Rect& a, const Rect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_FALSE(a.Intersection(b).has_value()) << label; EXPECT_FALSE(b.Intersection(a).has_value()) << label; check_empty_flips(a, b, label); check_nans(a, b, label); }; { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(0, 0, 0, 0); test_empty(a, b); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(10, 10, 0, 0); test_empty(a, b); } { auto a = Rect::MakeXYWH(0, 0, 100, 100); auto b = Rect::MakeXYWH(10, 10, 100, 100); auto expected = Rect::MakeXYWH(10, 10, 90, 90); test_non_empty(a, b, expected); } { auto a = Rect::MakeXYWH(0, 0, 100, 100); auto b = Rect::MakeXYWH(100, 100, 100, 100); test_empty(a, b); } { auto a = Rect::MakeMaximum(); auto b = Rect::MakeXYWH(10, 10, 300, 300); test_non_empty(a, b, b); } { auto a = Rect::MakeMaximum(); auto b = Rect::MakeMaximum(); test_non_empty(a, b, Rect::MakeMaximum()); } } TEST(RectTest, OptRectIntersection) { auto a = Rect::MakeLTRB(0, 0, 110, 110); auto b = Rect::MakeLTRB(100, 100, 200, 200); auto c = Rect::MakeLTRB(100, 0, 200, 110); // NullOpt, NullOpt EXPECT_FALSE(Rect::Intersection(std::nullopt, std::nullopt).has_value()); EXPECT_EQ(Rect::Intersection(std::nullopt, std::nullopt), std::nullopt); auto test1 = [](const Rect& r) { // Rect, NullOpt EXPECT_TRUE(Rect::Intersection(r, std::nullopt).has_value()); EXPECT_EQ(Rect::Intersection(r, std::nullopt).value(), r); // OptRect, NullOpt EXPECT_TRUE(Rect::Intersection(std::optional(r), std::nullopt).has_value()); EXPECT_EQ(Rect::Intersection(std::optional(r), std::nullopt).value(), r); // NullOpt, Rect EXPECT_TRUE(Rect::Intersection(std::nullopt, r).has_value()); EXPECT_EQ(Rect::Intersection(std::nullopt, r).value(), r); // NullOpt, OptRect EXPECT_TRUE(Rect::Intersection(std::nullopt, std::optional(r)).has_value()); EXPECT_EQ(Rect::Intersection(std::nullopt, std::optional(r)).value(), r); }; test1(a); test1(b); test1(c); auto test2 = [](const Rect& a, const Rect& b, const Rect& i) { ASSERT_EQ(a.Intersection(b), i); // Rect, OptRect EXPECT_TRUE(Rect::Intersection(a, std::optional(b)).has_value()); EXPECT_EQ(Rect::Intersection(a, std::optional(b)).value(), i); // OptRect, Rect EXPECT_TRUE(Rect::Intersection(std::optional(a), b).has_value()); EXPECT_EQ(Rect::Intersection(std::optional(a), b).value(), i); // OptRect, OptRect EXPECT_TRUE( Rect::Intersection(std::optional(a), std::optional(b)).has_value()); EXPECT_EQ(Rect::Intersection(std::optional(a), std::optional(b)).value(), i); }; test2(a, b, Rect::MakeLTRB(100, 100, 110, 110)); test2(a, c, Rect::MakeLTRB(100, 0, 110, 110)); test2(b, c, Rect::MakeLTRB(100, 100, 200, 110)); } TEST(RectTest, IRectIntersection) { auto check_empty_flips = [](const IRect& a, const IRect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // b is allowed to be empty // unflipped a vs flipped (empty) b yields a EXPECT_FALSE(a.Intersection(flip_lr(b)).has_value()) << label; EXPECT_FALSE(a.Intersection(flip_tb(b)).has_value()) << label; EXPECT_FALSE(a.Intersection(flip_lrtb(b)).has_value()) << label; // flipped (empty) a vs unflipped b yields b EXPECT_FALSE(flip_lr(a).Intersection(b).has_value()) << label; EXPECT_FALSE(flip_tb(a).Intersection(b).has_value()) << label; EXPECT_FALSE(flip_lrtb(a).Intersection(b).has_value()) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_FALSE(flip_lr(a).Intersection(flip_lr(b)).has_value()) << label; EXPECT_FALSE(flip_tb(a).Intersection(flip_tb(b)).has_value()) << label; EXPECT_FALSE(flip_lrtb(a).Intersection(flip_lrtb(b)).has_value()) << label; }; auto test_non_empty = [&check_empty_flips](const IRect& a, const IRect& b, const IRect& result) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_TRUE(a.Intersection(b).has_value()) << label; EXPECT_TRUE(b.Intersection(a).has_value()) << label; EXPECT_EQ(a.Intersection(b), result) << label; EXPECT_EQ(b.Intersection(a), result) << label; check_empty_flips(a, b, label); }; auto test_empty = [&check_empty_flips](const IRect& a, const IRect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_FALSE(a.Intersection(b).has_value()) << label; EXPECT_FALSE(b.Intersection(a).has_value()) << label; check_empty_flips(a, b, label); }; { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(0, 0, 0, 0); test_empty(a, b); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(10, 10, 0, 0); test_empty(a, b); } { auto a = IRect::MakeXYWH(0, 0, 100, 100); auto b = IRect::MakeXYWH(10, 10, 100, 100); auto expected = IRect::MakeXYWH(10, 10, 90, 90); test_non_empty(a, b, expected); } { auto a = IRect::MakeXYWH(0, 0, 100, 100); auto b = IRect::MakeXYWH(100, 100, 100, 100); test_empty(a, b); } { auto a = IRect::MakeMaximum(); auto b = IRect::MakeXYWH(10, 10, 300, 300); test_non_empty(a, b, b); } { auto a = IRect::MakeMaximum(); auto b = IRect::MakeMaximum(); test_non_empty(a, b, IRect::MakeMaximum()); } } TEST(RectTest, OptIRectIntersection) { auto a = IRect::MakeLTRB(0, 0, 110, 110); auto b = IRect::MakeLTRB(100, 100, 200, 200); auto c = IRect::MakeLTRB(100, 0, 200, 110); // NullOpt, NullOpt EXPECT_FALSE(IRect::Intersection(std::nullopt, std::nullopt).has_value()); EXPECT_EQ(IRect::Intersection(std::nullopt, std::nullopt), std::nullopt); auto test1 = [](const IRect& r) { // Rect, NullOpt EXPECT_TRUE(IRect::Intersection(r, std::nullopt).has_value()); EXPECT_EQ(IRect::Intersection(r, std::nullopt).value(), r); // OptRect, NullOpt EXPECT_TRUE( IRect::Intersection(std::optional(r), std::nullopt).has_value()); EXPECT_EQ(IRect::Intersection(std::optional(r), std::nullopt).value(), r); // NullOpt, Rect EXPECT_TRUE(IRect::Intersection(std::nullopt, r).has_value()); EXPECT_EQ(IRect::Intersection(std::nullopt, r).value(), r); // NullOpt, OptRect EXPECT_TRUE( IRect::Intersection(std::nullopt, std::optional(r)).has_value()); EXPECT_EQ(IRect::Intersection(std::nullopt, std::optional(r)).value(), r); }; test1(a); test1(b); test1(c); auto test2 = [](const IRect& a, const IRect& b, const IRect& i) { ASSERT_EQ(a.Intersection(b), i); // Rect, OptRect EXPECT_TRUE(IRect::Intersection(a, std::optional(b)).has_value()); EXPECT_EQ(IRect::Intersection(a, std::optional(b)).value(), i); // OptRect, Rect EXPECT_TRUE(IRect::Intersection(std::optional(a), b).has_value()); EXPECT_EQ(IRect::Intersection(std::optional(a), b).value(), i); // OptRect, OptRect EXPECT_TRUE( IRect::Intersection(std::optional(a), std::optional(b)).has_value()); EXPECT_EQ(IRect::Intersection(std::optional(a), std::optional(b)).value(), i); }; test2(a, b, IRect::MakeLTRB(100, 100, 110, 110)); test2(a, c, IRect::MakeLTRB(100, 0, 110, 110)); test2(b, c, IRect::MakeLTRB(100, 100, 200, 110)); } TEST(RectTest, RectIntersectsWithRect) { auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_TRUE(a.IsFinite()) << label; ASSERT_TRUE(b.IsFinite()) << label; for (int i = 1; i < 16; i++) { // NaN in a produces b EXPECT_FALSE(swap_nan(a, i).IntersectsWithRect(b)) << label << ", index = " << i; // NaN in b produces a EXPECT_FALSE(a.IntersectsWithRect(swap_nan(b, i))) << label << ", index = " << i; // NaN in both is empty for (int j = 1; j < 16; j++) { EXPECT_FALSE(swap_nan(a, i).IntersectsWithRect(swap_nan(b, j))) << label << ", indices = " << i << ", " << j; } } }; auto check_empty_flips = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // b is allowed to be empty // unflipped a vs flipped (empty) b yields a EXPECT_FALSE(a.IntersectsWithRect(flip_lr(b))) << label; EXPECT_FALSE(a.IntersectsWithRect(flip_tb(b))) << label; EXPECT_FALSE(a.IntersectsWithRect(flip_lrtb(b))) << label; // flipped (empty) a vs unflipped b yields b EXPECT_FALSE(flip_lr(a).IntersectsWithRect(b)) << label; EXPECT_FALSE(flip_tb(a).IntersectsWithRect(b)) << label; EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(b)) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_FALSE(flip_lr(a).IntersectsWithRect(flip_lr(b))) << label; EXPECT_FALSE(flip_tb(a).IntersectsWithRect(flip_tb(b))) << label; EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(flip_lrtb(b))) << label; }; auto test_non_empty = [&check_nans, &check_empty_flips](const Rect& a, const Rect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_TRUE(a.IntersectsWithRect(b)) << label; EXPECT_TRUE(b.IntersectsWithRect(a)) << label; check_empty_flips(a, b, label); check_nans(a, b, label); }; auto test_empty = [&check_nans, &check_empty_flips](const Rect& a, const Rect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_FALSE(a.IntersectsWithRect(b)) << label; EXPECT_FALSE(b.IntersectsWithRect(a)) << label; check_empty_flips(a, b, label); check_nans(a, b, label); }; { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(0, 0, 0, 0); test_empty(a, b); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(10, 10, 0, 0); test_empty(a, b); } { auto a = Rect::MakeXYWH(0, 0, 100, 100); auto b = Rect::MakeXYWH(10, 10, 100, 100); test_non_empty(a, b); } { auto a = Rect::MakeXYWH(0, 0, 100, 100); auto b = Rect::MakeXYWH(100, 100, 100, 100); test_empty(a, b); } { auto a = Rect::MakeMaximum(); auto b = Rect::MakeXYWH(10, 10, 100, 100); test_non_empty(a, b); } { auto a = Rect::MakeMaximum(); auto b = Rect::MakeMaximum(); test_non_empty(a, b); } } TEST(RectTest, IRectIntersectsWithRect) { auto check_empty_flips = [](const IRect& a, const IRect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // b is allowed to be empty // unflipped a vs flipped (empty) b yields a EXPECT_FALSE(a.IntersectsWithRect(flip_lr(b))) << label; EXPECT_FALSE(a.IntersectsWithRect(flip_tb(b))) << label; EXPECT_FALSE(a.IntersectsWithRect(flip_lrtb(b))) << label; // flipped (empty) a vs unflipped b yields b EXPECT_FALSE(flip_lr(a).IntersectsWithRect(b)) << label; EXPECT_FALSE(flip_tb(a).IntersectsWithRect(b)) << label; EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(b)) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_FALSE(flip_lr(a).IntersectsWithRect(flip_lr(b))) << label; EXPECT_FALSE(flip_tb(a).IntersectsWithRect(flip_tb(b))) << label; EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(flip_lrtb(b))) << label; }; auto test_non_empty = [&check_empty_flips](const IRect& a, const IRect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_TRUE(a.IntersectsWithRect(b)) << label; EXPECT_TRUE(b.IntersectsWithRect(a)) << label; check_empty_flips(a, b, label); }; auto test_empty = [&check_empty_flips](const IRect& a, const IRect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // b is allowed to be empty std::stringstream stream; stream << a << " union " << b; auto label = stream.str(); EXPECT_FALSE(a.IntersectsWithRect(b)) << label; EXPECT_FALSE(b.IntersectsWithRect(a)) << label; check_empty_flips(a, b, label); }; { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(0, 0, 0, 0); test_empty(a, b); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(10, 10, 0, 0); test_empty(a, b); } { auto a = IRect::MakeXYWH(0, 0, 100, 100); auto b = IRect::MakeXYWH(10, 10, 100, 100); test_non_empty(a, b); } { auto a = IRect::MakeXYWH(0, 0, 100, 100); auto b = IRect::MakeXYWH(100, 100, 100, 100); test_empty(a, b); } { auto a = IRect::MakeMaximum(); auto b = IRect::MakeXYWH(10, 10, 100, 100); test_non_empty(a, b); } { auto a = IRect::MakeMaximum(); auto b = IRect::MakeMaximum(); test_non_empty(a, b); } } TEST(RectTest, RectContainsPoint) { auto check_nans = [](const Rect& rect, const Point& point, const std::string& label) { ASSERT_TRUE(rect.IsFinite()) << label; ASSERT_TRUE(point.IsFinite()) << label; for (int i = 1; i < 16; i++) { EXPECT_FALSE(swap_nan(rect, i).Contains(point)) << label << ", index = " << i; for (int j = 1; j < 4; j++) { EXPECT_FALSE(swap_nan(rect, i).Contains(swap_nan(point, j))) << label << ", indices = " << i << ", " << j; } } }; auto check_empty_flips = [](const Rect& rect, const Point& point, const std::string& label) { ASSERT_FALSE(rect.IsEmpty()); EXPECT_FALSE(flip_lr(rect).Contains(point)) << label; EXPECT_FALSE(flip_tb(rect).Contains(point)) << label; EXPECT_FALSE(flip_lrtb(rect).Contains(point)) << label; }; auto test_inside = [&check_nans, &check_empty_flips](const Rect& rect, const Point& point) { ASSERT_FALSE(rect.IsEmpty()) << rect; std::stringstream stream; stream << rect << " contains " << point; auto label = stream.str(); EXPECT_TRUE(rect.Contains(point)) << label; check_empty_flips(rect, point, label); check_nans(rect, point, label); }; auto test_outside = [&check_nans, &check_empty_flips](const Rect& rect, const Point& point) { ASSERT_FALSE(rect.IsEmpty()) << rect; std::stringstream stream; stream << rect << " contains " << point; auto label = stream.str(); EXPECT_FALSE(rect.Contains(point)) << label; check_empty_flips(rect, point, label); check_nans(rect, point, label); }; { // Origin is inclusive auto r = Rect::MakeXYWH(100, 100, 100, 100); auto p = Point(100, 100); test_inside(r, p); } { // Size is exclusive auto r = Rect::MakeXYWH(100, 100, 100, 100); auto p = Point(200, 200); test_outside(r, p); } { auto r = Rect::MakeXYWH(100, 100, 100, 100); auto p = Point(99, 99); test_outside(r, p); } { auto r = Rect::MakeXYWH(100, 100, 100, 100); auto p = Point(199, 199); test_inside(r, p); } { auto r = Rect::MakeMaximum(); auto p = Point(199, 199); test_inside(r, p); } } TEST(RectTest, IRectContainsIPoint) { auto check_empty_flips = [](const IRect& rect, const IPoint& point, const std::string& label) { ASSERT_FALSE(rect.IsEmpty()); EXPECT_FALSE(flip_lr(rect).Contains(point)) << label; EXPECT_FALSE(flip_tb(rect).Contains(point)) << label; EXPECT_FALSE(flip_lrtb(rect).Contains(point)) << label; }; auto test_inside = [&check_empty_flips](const IRect& rect, const IPoint& point) { ASSERT_FALSE(rect.IsEmpty()) << rect; std::stringstream stream; stream << rect << " contains " << point; auto label = stream.str(); EXPECT_TRUE(rect.Contains(point)) << label; check_empty_flips(rect, point, label); }; auto test_outside = [&check_empty_flips](const IRect& rect, const IPoint& point) { ASSERT_FALSE(rect.IsEmpty()) << rect; std::stringstream stream; stream << rect << " contains " << point; auto label = stream.str(); EXPECT_FALSE(rect.Contains(point)) << label; check_empty_flips(rect, point, label); }; { // Origin is inclusive auto r = IRect::MakeXYWH(100, 100, 100, 100); auto p = IPoint(100, 100); test_inside(r, p); } { // Size is exclusive auto r = IRect::MakeXYWH(100, 100, 100, 100); auto p = IPoint(200, 200); test_outside(r, p); } { auto r = IRect::MakeXYWH(100, 100, 100, 100); auto p = IPoint(99, 99); test_outside(r, p); } { auto r = IRect::MakeXYWH(100, 100, 100, 100); auto p = IPoint(199, 199); test_inside(r, p); } { auto r = IRect::MakeMaximum(); auto p = IPoint(199, 199); test_inside(r, p); } } TEST(RectTest, RectContainsRect) { auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_TRUE(a.IsFinite()) << label; ASSERT_TRUE(b.IsFinite()) << label; ASSERT_FALSE(a.IsEmpty()); for (int i = 1; i < 16; i++) { // NaN in a produces false EXPECT_FALSE(swap_nan(a, i).Contains(b)) << label << ", index = " << i; // NaN in b produces false EXPECT_TRUE(a.Contains(swap_nan(b, i))) << label << ", index = " << i; // NaN in both is false for (int j = 1; j < 16; j++) { EXPECT_FALSE(swap_nan(a, i).Contains(swap_nan(b, j))) << label << ", indices = " << i << ", " << j; } } }; auto check_empty_flips = [](const Rect& a, const Rect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // test b rects are allowed to have 0 w/h, but not be backwards ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); // unflipped a vs flipped (empty) b yields false EXPECT_TRUE(a.Contains(flip_lr(b))) << label; EXPECT_TRUE(a.Contains(flip_tb(b))) << label; EXPECT_TRUE(a.Contains(flip_lrtb(b))) << label; // flipped (empty) a vs unflipped b yields false EXPECT_FALSE(flip_lr(a).Contains(b)) << label; EXPECT_FALSE(flip_tb(a).Contains(b)) << label; EXPECT_FALSE(flip_lrtb(a).Contains(b)) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_FALSE(flip_lr(a).Contains(flip_lr(b))) << label; EXPECT_FALSE(flip_tb(a).Contains(flip_tb(b))) << label; EXPECT_FALSE(flip_lrtb(a).Contains(flip_lrtb(b))) << label; }; auto test_inside = [&check_nans, &check_empty_flips](const Rect& a, const Rect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // test b rects are allowed to have 0 w/h, but not be backwards ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); std::stringstream stream; stream << a << " contains " << b; auto label = stream.str(); EXPECT_TRUE(a.Contains(b)) << label; check_empty_flips(a, b, label); check_nans(a, b, label); }; auto test_not_inside = [&check_nans, &check_empty_flips](const Rect& a, const Rect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // If b was empty, it would be contained and should not be tested with // this function - use |test_inside| instead. ASSERT_FALSE(b.IsEmpty()) << b; std::stringstream stream; stream << a << " contains " << b; auto label = stream.str(); EXPECT_FALSE(a.Contains(b)) << label; check_empty_flips(a, b, label); check_nans(a, b, label); }; { auto a = Rect::MakeXYWH(100, 100, 100, 100); test_inside(a, a); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(0, 0, 0, 0); test_inside(a, b); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(150, 150, 20, 20); test_inside(a, b); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(150, 150, 100, 100); test_not_inside(a, b); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(50, 50, 100, 100); test_not_inside(a, b); } { auto a = Rect::MakeXYWH(100, 100, 100, 100); auto b = Rect::MakeXYWH(0, 0, 300, 300); test_not_inside(a, b); } { auto a = Rect::MakeMaximum(); auto b = Rect::MakeXYWH(0, 0, 300, 300); test_inside(a, b); } } TEST(RectTest, IRectContainsIRect) { auto check_empty_flips = [](const IRect& a, const IRect& b, const std::string& label) { ASSERT_FALSE(a.IsEmpty()); // test b rects are allowed to have 0 w/h, but not be backwards ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); // unflipped a vs flipped (empty) b yields true EXPECT_TRUE(a.Contains(flip_lr(b))) << label; EXPECT_TRUE(a.Contains(flip_tb(b))) << label; EXPECT_TRUE(a.Contains(flip_lrtb(b))) << label; // flipped (empty) a vs unflipped b yields false EXPECT_FALSE(flip_lr(a).Contains(b)) << label; EXPECT_FALSE(flip_tb(a).Contains(b)) << label; EXPECT_FALSE(flip_lrtb(a).Contains(b)) << label; // flipped (empty) a vs flipped (empty) b yields empty EXPECT_FALSE(flip_lr(a).Contains(flip_lr(b))) << label; EXPECT_FALSE(flip_tb(a).Contains(flip_tb(b))) << label; EXPECT_FALSE(flip_lrtb(a).Contains(flip_lrtb(b))) << label; }; auto test_inside = [&check_empty_flips](const IRect& a, const IRect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // test b rects are allowed to have 0 w/h, but not be backwards ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); std::stringstream stream; stream << a << " contains " << b; auto label = stream.str(); EXPECT_TRUE(a.Contains(b)) << label; check_empty_flips(a, b, label); }; auto test_not_inside = [&check_empty_flips](const IRect& a, const IRect& b) { ASSERT_FALSE(a.IsEmpty()) << a; // If b was empty, it would be contained and should not be tested with // this function - use |test_inside| instead. ASSERT_FALSE(b.IsEmpty()) << b; std::stringstream stream; stream << a << " contains " << b; auto label = stream.str(); EXPECT_FALSE(a.Contains(b)) << label; check_empty_flips(a, b, label); }; { auto a = IRect::MakeXYWH(100, 100, 100, 100); test_inside(a, a); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(0, 0, 0, 0); test_inside(a, b); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(150, 150, 20, 20); test_inside(a, b); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(150, 150, 100, 100); test_not_inside(a, b); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(50, 50, 100, 100); test_not_inside(a, b); } { auto a = IRect::MakeXYWH(100, 100, 100, 100); auto b = IRect::MakeXYWH(0, 0, 300, 300); test_not_inside(a, b); } { auto a = IRect::MakeMaximum(); auto b = IRect::MakeXYWH(0, 0, 300, 300); test_inside(a, b); } } TEST(RectTest, RectCutOut) { Rect cull_rect = Rect::MakeLTRB(20, 20, 40, 40); auto check_nans = [&cull_rect](const Rect& diff_rect, const std::string& label) { EXPECT_TRUE(cull_rect.IsFinite()) << label; EXPECT_TRUE(diff_rect.IsFinite()) << label; for (int i = 1; i < 16; i++) { // NaN in cull_rect produces empty EXPECT_FALSE(swap_nan(cull_rect, i).Cutout(diff_rect).has_value()) << label << ", index " << i; EXPECT_EQ(swap_nan(cull_rect, i).CutoutOrEmpty(diff_rect), Rect()) << label << ", index " << i; // NaN in diff_rect is nop EXPECT_TRUE(cull_rect.Cutout(swap_nan(diff_rect, i)).has_value()) << label << ", index " << i; EXPECT_EQ(cull_rect.CutoutOrEmpty(swap_nan(diff_rect, i)), cull_rect) << label << ", index " << i; for (int j = 1; j < 16; j++) { // NaN in both is also empty EXPECT_FALSE( swap_nan(cull_rect, i).Cutout(swap_nan(diff_rect, j)).has_value()) << label << ", indices " << i << ", " << j; EXPECT_EQ(swap_nan(cull_rect, i).CutoutOrEmpty(swap_nan(diff_rect, j)), Rect()) << label << ", indices " << i << ", " << j; } } }; auto check_empty_flips = [&cull_rect](const Rect& diff_rect, const std::string& label) { EXPECT_FALSE(cull_rect.IsEmpty()) << label; EXPECT_FALSE(diff_rect.IsEmpty()) << label; // unflipped cull_rect vs flipped(empty) diff_rect // == cull_rect EXPECT_TRUE(cull_rect.Cutout(flip_lr(diff_rect)).has_value()) << label; EXPECT_EQ(cull_rect.Cutout(flip_lr(diff_rect)), cull_rect) << label; EXPECT_TRUE(cull_rect.Cutout(flip_tb(diff_rect)).has_value()) << label; EXPECT_EQ(cull_rect.Cutout(flip_tb(diff_rect)), cull_rect) << label; EXPECT_TRUE(cull_rect.Cutout(flip_lrtb(diff_rect)).has_value()) << label; EXPECT_EQ(cull_rect.Cutout(flip_lrtb(diff_rect)), cull_rect) << label; // flipped(empty) cull_rect vs unflipped diff_rect // == empty EXPECT_FALSE(flip_lr(cull_rect).Cutout(diff_rect).has_value()) << label; EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(diff_rect), Rect()) << label; EXPECT_FALSE(flip_tb(cull_rect).Cutout(diff_rect).has_value()) << label; EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(diff_rect), Rect()) << label; EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(diff_rect).has_value()) << label; EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(diff_rect), Rect()) << label; // flipped(empty) cull_rect vs flipped(empty) diff_rect // == empty EXPECT_FALSE(flip_lr(cull_rect).Cutout(flip_lr(diff_rect)).has_value()) << label; EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(flip_lr(diff_rect)), Rect()) << label; EXPECT_FALSE(flip_tb(cull_rect).Cutout(flip_tb(diff_rect)).has_value()) << label; EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(flip_tb(diff_rect)), Rect()) << label; EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(flip_lrtb(diff_rect)).has_value()) << label; EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(flip_lrtb(diff_rect)), Rect()) << label; }; auto non_reducing = [&cull_rect, &check_empty_flips, &check_nans]( const Rect& diff_rect, const std::string& label) { EXPECT_EQ(cull_rect.Cutout(diff_rect), cull_rect) << label; EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), cull_rect) << label; check_empty_flips(diff_rect, label); check_nans(diff_rect, label); }; auto reducing = [&cull_rect, &check_empty_flips, &check_nans]( const Rect& diff_rect, const Rect& result_rect, const std::string& label) { EXPECT_TRUE(!result_rect.IsEmpty()); EXPECT_EQ(cull_rect.Cutout(diff_rect), result_rect) << label; EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), result_rect) << label; check_empty_flips(diff_rect, label); check_nans(diff_rect, label); }; auto emptying = [&cull_rect, &check_empty_flips, &check_nans]( const Rect& diff_rect, const std::string& label) { EXPECT_FALSE(cull_rect.Cutout(diff_rect).has_value()) << label; EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), Rect()) << label; check_empty_flips(diff_rect, label); check_nans(diff_rect, label); }; // Skim the corners and edge non_reducing(Rect::MakeLTRB(10, 10, 20, 20), "outside UL corner"); non_reducing(Rect::MakeLTRB(20, 10, 40, 20), "Above"); non_reducing(Rect::MakeLTRB(40, 10, 50, 20), "outside UR corner"); non_reducing(Rect::MakeLTRB(40, 20, 50, 40), "Right"); non_reducing(Rect::MakeLTRB(40, 40, 50, 50), "outside LR corner"); non_reducing(Rect::MakeLTRB(20, 40, 40, 50), "Below"); non_reducing(Rect::MakeLTRB(10, 40, 20, 50), "outside LR corner"); non_reducing(Rect::MakeLTRB(10, 20, 20, 40), "Left"); // Overlap corners non_reducing(Rect::MakeLTRB(15, 15, 25, 25), "covering UL corner"); non_reducing(Rect::MakeLTRB(35, 15, 45, 25), "covering UR corner"); non_reducing(Rect::MakeLTRB(35, 35, 45, 45), "covering LR corner"); non_reducing(Rect::MakeLTRB(15, 35, 25, 45), "covering LL corner"); // Overlap edges, but not across an entire side non_reducing(Rect::MakeLTRB(20, 15, 39, 25), "Top edge left-biased"); non_reducing(Rect::MakeLTRB(21, 15, 40, 25), "Top edge, right biased"); non_reducing(Rect::MakeLTRB(35, 20, 45, 39), "Right edge, top-biased"); non_reducing(Rect::MakeLTRB(35, 21, 45, 40), "Right edge, bottom-biased"); non_reducing(Rect::MakeLTRB(20, 35, 39, 45), "Bottom edge, left-biased"); non_reducing(Rect::MakeLTRB(21, 35, 40, 45), "Bottom edge, right-biased"); non_reducing(Rect::MakeLTRB(15, 20, 25, 39), "Left edge, top-biased"); non_reducing(Rect::MakeLTRB(15, 21, 25, 40), "Left edge, bottom-biased"); // Slice all the way through the middle non_reducing(Rect::MakeLTRB(25, 15, 35, 45), "Vertical interior slice"); non_reducing(Rect::MakeLTRB(15, 25, 45, 35), "Horizontal interior slice"); // Slice off each edge reducing(Rect::MakeLTRB(20, 15, 40, 25), // Rect::MakeLTRB(20, 25, 40, 40), // "Slice off top"); reducing(Rect::MakeLTRB(35, 20, 45, 40), // Rect::MakeLTRB(20, 20, 35, 40), // "Slice off right"); reducing(Rect::MakeLTRB(20, 35, 40, 45), // Rect::MakeLTRB(20, 20, 40, 35), // "Slice off bottom"); reducing(Rect::MakeLTRB(15, 20, 25, 40), // Rect::MakeLTRB(25, 20, 40, 40), // "Slice off left"); // cull rect contains diff rect non_reducing(Rect::MakeLTRB(21, 21, 39, 39), "Contained, non-covering"); // cull rect equals diff rect emptying(cull_rect, "Perfectly covering"); // diff rect contains cull rect emptying(Rect::MakeLTRB(15, 15, 45, 45), "Smothering"); } TEST(RectTest, IRectCutOut) { IRect cull_rect = IRect::MakeLTRB(20, 20, 40, 40); auto check_empty_flips = [&cull_rect](const IRect& diff_rect, const std::string& label) { EXPECT_FALSE(diff_rect.IsEmpty()); EXPECT_FALSE(cull_rect.IsEmpty()); // unflipped cull_rect vs flipped(empty) diff_rect // == cull_rect EXPECT_TRUE(cull_rect.Cutout(flip_lr(diff_rect)).has_value()) << label; EXPECT_EQ(cull_rect.Cutout(flip_lr(diff_rect)), cull_rect) << label; EXPECT_TRUE(cull_rect.Cutout(flip_tb(diff_rect)).has_value()) << label; EXPECT_EQ(cull_rect.Cutout(flip_tb(diff_rect)), cull_rect) << label; EXPECT_TRUE(cull_rect.Cutout(flip_lrtb(diff_rect)).has_value()) << label; EXPECT_EQ(cull_rect.Cutout(flip_lrtb(diff_rect)), cull_rect) << label; // flipped(empty) cull_rect vs flipped(empty) diff_rect // == empty EXPECT_FALSE(flip_lr(cull_rect).Cutout(diff_rect).has_value()) << label; EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(diff_rect), IRect()) << label; EXPECT_FALSE(flip_tb(cull_rect).Cutout(diff_rect).has_value()) << label; EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(diff_rect), IRect()) << label; EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(diff_rect).has_value()) << label; EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(diff_rect), IRect()) << label; // flipped(empty) cull_rect vs unflipped diff_rect // == empty EXPECT_FALSE(flip_lr(cull_rect).Cutout(flip_lr(diff_rect)).has_value()) << label; EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(flip_lr(diff_rect)), IRect()) << label; EXPECT_FALSE(flip_tb(cull_rect).Cutout(flip_tb(diff_rect)).has_value()) << label; EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(flip_tb(diff_rect)), IRect()) << label; EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(flip_lrtb(diff_rect)).has_value()) << label; EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(flip_lrtb(diff_rect)), IRect()) << label; }; auto non_reducing = [&cull_rect, &check_empty_flips]( const IRect& diff_rect, const std::string& label) { EXPECT_EQ(cull_rect.Cutout(diff_rect), cull_rect) << label; EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), cull_rect) << label; check_empty_flips(diff_rect, label); }; auto reducing = [&cull_rect, &check_empty_flips](const IRect& diff_rect, const IRect& result_rect, const std::string& label) { EXPECT_TRUE(!result_rect.IsEmpty()); EXPECT_EQ(cull_rect.Cutout(diff_rect), result_rect) << label; EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), result_rect) << label; check_empty_flips(diff_rect, label); }; auto emptying = [&cull_rect, &check_empty_flips](const IRect& diff_rect, const std::string& label) { EXPECT_FALSE(cull_rect.Cutout(diff_rect).has_value()) << label; EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), IRect()) << label; check_empty_flips(diff_rect, label); }; // Skim the corners and edge non_reducing(IRect::MakeLTRB(10, 10, 20, 20), "outside UL corner"); non_reducing(IRect::MakeLTRB(20, 10, 40, 20), "Above"); non_reducing(IRect::MakeLTRB(40, 10, 50, 20), "outside UR corner"); non_reducing(IRect::MakeLTRB(40, 20, 50, 40), "Right"); non_reducing(IRect::MakeLTRB(40, 40, 50, 50), "outside LR corner"); non_reducing(IRect::MakeLTRB(20, 40, 40, 50), "Below"); non_reducing(IRect::MakeLTRB(10, 40, 20, 50), "outside LR corner"); non_reducing(IRect::MakeLTRB(10, 20, 20, 40), "Left"); // Overlap corners non_reducing(IRect::MakeLTRB(15, 15, 25, 25), "covering UL corner"); non_reducing(IRect::MakeLTRB(35, 15, 45, 25), "covering UR corner"); non_reducing(IRect::MakeLTRB(35, 35, 45, 45), "covering LR corner"); non_reducing(IRect::MakeLTRB(15, 35, 25, 45), "covering LL corner"); // Overlap edges, but not across an entire side non_reducing(IRect::MakeLTRB(20, 15, 39, 25), "Top edge left-biased"); non_reducing(IRect::MakeLTRB(21, 15, 40, 25), "Top edge, right biased"); non_reducing(IRect::MakeLTRB(35, 20, 45, 39), "Right edge, top-biased"); non_reducing(IRect::MakeLTRB(35, 21, 45, 40), "Right edge, bottom-biased"); non_reducing(IRect::MakeLTRB(20, 35, 39, 45), "Bottom edge, left-biased"); non_reducing(IRect::MakeLTRB(21, 35, 40, 45), "Bottom edge, right-biased"); non_reducing(IRect::MakeLTRB(15, 20, 25, 39), "Left edge, top-biased"); non_reducing(IRect::MakeLTRB(15, 21, 25, 40), "Left edge, bottom-biased"); // Slice all the way through the middle non_reducing(IRect::MakeLTRB(25, 15, 35, 45), "Vertical interior slice"); non_reducing(IRect::MakeLTRB(15, 25, 45, 35), "Horizontal interior slice"); // Slice off each edge reducing(IRect::MakeLTRB(20, 15, 40, 25), // IRect::MakeLTRB(20, 25, 40, 40), // "Slice off top"); reducing(IRect::MakeLTRB(35, 20, 45, 40), // IRect::MakeLTRB(20, 20, 35, 40), // "Slice off right"); reducing(IRect::MakeLTRB(20, 35, 40, 45), // IRect::MakeLTRB(20, 20, 40, 35), // "Slice off bottom"); reducing(IRect::MakeLTRB(15, 20, 25, 40), // IRect::MakeLTRB(25, 20, 40, 40), // "Slice off left"); // cull rect contains diff rect non_reducing(IRect::MakeLTRB(21, 21, 39, 39), "Contained, non-covering"); // cull rect equals diff rect emptying(cull_rect, "Perfectly covering"); // diff rect contains cull rect emptying(IRect::MakeLTRB(15, 15, 45, 45), "Smothering"); } TEST(RectTest, RectGetPoints) { { Rect r = Rect::MakeXYWH(100, 200, 300, 400); auto points = r.GetPoints(); EXPECT_POINT_NEAR(points[0], Point(100, 200)); EXPECT_POINT_NEAR(points[1], Point(400, 200)); EXPECT_POINT_NEAR(points[2], Point(100, 600)); EXPECT_POINT_NEAR(points[3], Point(400, 600)); } { Rect r = Rect::MakeMaximum(); auto points = r.GetPoints(); EXPECT_EQ(points[0], Point(std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest())); EXPECT_EQ(points[1], Point(std::numeric_limits<float>::max(), std::numeric_limits<float>::lowest())); EXPECT_EQ(points[2], Point(std::numeric_limits<float>::lowest(), std::numeric_limits<float>::max())); EXPECT_EQ(points[3], Point(std::numeric_limits<float>::max(), std::numeric_limits<float>::max())); } } TEST(RectTest, RectShift) { auto r = Rect::MakeLTRB(0, 0, 100, 100); EXPECT_EQ(r.Shift(Point(10, 5)), Rect::MakeLTRB(10, 5, 110, 105)); EXPECT_EQ(r.Shift(Point(-10, -5)), Rect::MakeLTRB(-10, -5, 90, 95)); } TEST(RectTest, RectGetTransformedPoints) { Rect r = Rect::MakeXYWH(100, 200, 300, 400); auto points = r.GetTransformedPoints(Matrix::MakeTranslation({10, 20})); EXPECT_POINT_NEAR(points[0], Point(110, 220)); EXPECT_POINT_NEAR(points[1], Point(410, 220)); EXPECT_POINT_NEAR(points[2], Point(110, 620)); EXPECT_POINT_NEAR(points[3], Point(410, 620)); } TEST(RectTest, RectMakePointBounds) { { std::vector<Point> points{{1, 5}, {4, -1}, {0, 6}}; auto r = Rect::MakePointBounds(points.begin(), points.end()); auto expected = Rect::MakeXYWH(0, -1, 4, 7); EXPECT_TRUE(r.has_value()); if (r.has_value()) { EXPECT_RECT_NEAR(r.value(), expected); } } { std::vector<Point> points; std::optional<Rect> r = Rect::MakePointBounds(points.begin(), points.end()); EXPECT_FALSE(r.has_value()); } } TEST(RectTest, RectGetPositive) { { Rect r = Rect::MakeXYWH(100, 200, 300, 400); auto actual = r.GetPositive(); EXPECT_RECT_NEAR(r, actual); } { Rect r = Rect::MakeXYWH(100, 200, -100, -100); auto actual = r.GetPositive(); Rect expected = Rect::MakeXYWH(0, 100, 100, 100); EXPECT_RECT_NEAR(expected, actual); } } TEST(RectTest, RectDirections) { auto r = Rect::MakeLTRB(1, 2, 3, 4); EXPECT_EQ(r.GetLeft(), 1); EXPECT_EQ(r.GetTop(), 2); EXPECT_EQ(r.GetRight(), 3); EXPECT_EQ(r.GetBottom(), 4); EXPECT_POINT_NEAR(r.GetLeftTop(), Point(1, 2)); EXPECT_POINT_NEAR(r.GetRightTop(), Point(3, 2)); EXPECT_POINT_NEAR(r.GetLeftBottom(), Point(1, 4)); EXPECT_POINT_NEAR(r.GetRightBottom(), Point(3, 4)); } TEST(RectTest, RectProject) { { auto r = Rect::MakeLTRB(-100, -100, 100, 100); auto actual = r.Project(r); auto expected = Rect::MakeLTRB(0, 0, 1, 1); EXPECT_RECT_NEAR(expected, actual); } { auto r = Rect::MakeLTRB(-100, -100, 100, 100); auto actual = r.Project(Rect::MakeLTRB(0, 0, 100, 100)); auto expected = Rect::MakeLTRB(0.5, 0.5, 1, 1); EXPECT_RECT_NEAR(expected, actual); } } TEST(RectTest, RectRoundOut) { { auto r = Rect::MakeLTRB(-100, -100, 100, 100); EXPECT_EQ(Rect::RoundOut(r), r); } { auto r = Rect::MakeLTRB(-100.1, -100.1, 100.1, 100.1); EXPECT_EQ(Rect::RoundOut(r), Rect::MakeLTRB(-101, -101, 101, 101)); } } TEST(RectTest, IRectRoundOut) { { auto r = Rect::MakeLTRB(-100, -100, 100, 100); auto ir = IRect::MakeLTRB(-100, -100, 100, 100); EXPECT_EQ(IRect::RoundOut(r), ir); } { auto r = Rect::MakeLTRB(-100.1, -100.1, 100.1, 100.1); auto ir = IRect::MakeLTRB(-101, -101, 101, 101); EXPECT_EQ(IRect::RoundOut(r), ir); } } } // namespace testing } // namespace impeller
engine/impeller/geometry/rect_unittests.cc/0
{ "file_path": "engine/impeller/geometry/rect_unittests.cc", "repo_id": "engine", "token_count": 43340 }
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. #include "vector.h" #include <sstream> namespace impeller { std::string Vector3::ToString() const { std::stringstream stream; stream << "{" << x << ", " << y << ", " << z << "}"; return stream.str(); } std::string Vector4::ToString() const { std::stringstream stream; stream << "{" << x << ", " << y << ", " << z << ", " << w << "}"; return stream.str(); } } // namespace impeller
engine/impeller/geometry/vector.cc/0
{ "file_path": "engine/impeller/geometry/vector.cc", "repo_id": "engine", "token_count": 181 }
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_GOLDEN_TESTS_SCREENSHOTTER_H_ #define FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOTTER_H_ #include "flutter/fml/macros.h" #include "flutter/impeller/aiks/picture.h" #include "flutter/impeller/golden_tests/screenshot.h" #include "flutter/impeller/playground/playground_impl.h" namespace impeller { namespace testing { /// Converts `Picture`s and `DisplayList`s to `MetalScreenshot`s with the /// playground backend. class Screenshotter { public: virtual ~Screenshotter() = default; virtual std::unique_ptr<Screenshot> MakeScreenshot( AiksContext& aiks_context, const Picture& picture, const ISize& size = {300, 300}, bool scale_content = true) = 0; virtual PlaygroundImpl& GetPlayground() = 0; }; } // namespace testing } // namespace impeller #endif // FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOTTER_H_
engine/impeller/golden_tests/screenshotter.h/0
{ "file_path": "engine/impeller/golden_tests/screenshotter.h", "repo_id": "engine", "token_count": 372 }
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. #ifndef FLUTTER_IMPELLER_PLAYGROUND_COMPUTE_PLAYGROUND_TEST_H_ #define FLUTTER_IMPELLER_PLAYGROUND_COMPUTE_PLAYGROUND_TEST_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/fml/time/time_delta.h" #include "flutter/testing/testing.h" #include "impeller/core/device_buffer.h" #include "impeller/geometry/scalar.h" #include "impeller/playground/playground.h" namespace impeller { class ComputePlaygroundTest : public Playground, public ::testing::TestWithParam<PlaygroundBackend> { public: ComputePlaygroundTest(); virtual ~ComputePlaygroundTest(); void SetUp() override; void TearDown() override; // |Playground| std::unique_ptr<fml::Mapping> OpenAssetAsMapping( std::string asset_name) const override; // |Playground| std::string GetWindowTitle() const override; template <typename T> std::shared_ptr<DeviceBuffer> CreateHostVisibleDeviceBuffer( const std::shared_ptr<Context>& context, const std::string& label) { DeviceBufferDescriptor desc; desc.storage_mode = StorageMode::kHostVisible; desc.size = sizeof(T); auto buffer = context->GetResourceAllocator()->CreateBuffer(desc); buffer->SetLabel(label); return buffer; } private: fml::TimeDelta start_time_; ComputePlaygroundTest(const ComputePlaygroundTest&) = delete; ComputePlaygroundTest& operator=(const ComputePlaygroundTest&) = delete; }; #define INSTANTIATE_COMPUTE_SUITE(playground) \ INSTANTIATE_TEST_SUITE_P( \ Compute, playground, \ ::testing::Values(PlaygroundBackend::kMetal, \ PlaygroundBackend::kVulkan), \ [](const ::testing::TestParamInfo<ComputePlaygroundTest::ParamType>& \ info) { return PlaygroundBackendToString(info.param); }); } // namespace impeller #endif // FLUTTER_IMPELLER_PLAYGROUND_COMPUTE_PLAYGROUND_TEST_H_
engine/impeller/playground/compute_playground_test.h/0
{ "file_path": "engine/impeller/playground/compute_playground_test.h", "repo_id": "engine", "token_count": 908 }
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. #include "impeller/playground/playground_impl.h" #include "flutter/testing/testing.h" #define GLFW_INCLUDE_NONE #include "third_party/glfw/include/GLFW/glfw3.h" #if IMPELLER_ENABLE_METAL #include "impeller/playground/backend/metal/playground_impl_mtl.h" #endif // IMPELLER_ENABLE_METAL #if IMPELLER_ENABLE_OPENGLES #include "impeller/playground/backend/gles/playground_impl_gles.h" #endif // IMPELLER_ENABLE_OPENGLES #if IMPELLER_ENABLE_VULKAN #include "impeller/playground/backend/vulkan/playground_impl_vk.h" #endif // IMPELLER_ENABLE_VULKAN namespace { std::string GetTestName() { std::string suite_name = ::testing::UnitTest::GetInstance()->current_test_suite()->name(); std::string test_name = ::testing::UnitTest::GetInstance()->current_test_info()->name(); std::stringstream ss; ss << "impeller_" << suite_name << "_" << test_name; std::string result = ss.str(); // Make sure there are no slashes in the test name. std::replace(result.begin(), result.end(), '/', '_'); return result; } bool ShouldTestHaveVulkanValidations() { std::string test_name = GetTestName(); return std::find(impeller::kVulkanDenyValidationTests.begin(), impeller::kVulkanDenyValidationTests.end(), test_name) == impeller::kVulkanDenyValidationTests.end(); } } // namespace namespace impeller { std::unique_ptr<PlaygroundImpl> PlaygroundImpl::Create( PlaygroundBackend backend, PlaygroundSwitches switches) { switch (backend) { #if IMPELLER_ENABLE_METAL case PlaygroundBackend::kMetal: return std::make_unique<PlaygroundImplMTL>(switches); #endif // IMPELLER_ENABLE_METAL #if IMPELLER_ENABLE_OPENGLES case PlaygroundBackend::kOpenGLES: return std::make_unique<PlaygroundImplGLES>(switches); #endif // IMPELLER_ENABLE_OPENGLES #if IMPELLER_ENABLE_VULKAN case PlaygroundBackend::kVulkan: if (!PlaygroundImplVK::IsVulkanDriverPresent()) { FML_CHECK(false) << "Attempted to create playground with backend that " "isn't available or was disabled on this platform: " << PlaygroundBackendToString(backend); } switches.enable_vulkan_validation = ShouldTestHaveVulkanValidations(); return std::make_unique<PlaygroundImplVK>(switches); #endif // IMPELLER_ENABLE_VULKAN default: FML_CHECK(false) << "Attempted to create playground with backend that " "isn't available or was disabled on this platform: " << PlaygroundBackendToString(backend); } FML_UNREACHABLE(); } PlaygroundImpl::PlaygroundImpl(PlaygroundSwitches switches) : switches_(switches) {} PlaygroundImpl::~PlaygroundImpl() = default; Vector2 PlaygroundImpl::GetContentScale() const { auto window = reinterpret_cast<GLFWwindow*>(GetWindowHandle()); Vector2 scale(1, 1); ::glfwGetWindowContentScale(window, &scale.x, &scale.y); return scale; } } // namespace impeller
engine/impeller/playground/playground_impl.cc/0
{ "file_path": "engine/impeller/playground/playground_impl.cc", "repo_id": "engine", "token_count": 1212 }
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_BACKEND_GLES_BLIT_PASS_GLES_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_PASS_GLES_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/impeller/base/config.h" #include "flutter/impeller/renderer/backend/gles/reactor_gles.h" #include "flutter/impeller/renderer/blit_pass.h" #include "impeller/renderer/backend/gles/blit_command_gles.h" namespace impeller { class BlitPassGLES final : public BlitPass, public std::enable_shared_from_this<BlitPassGLES> { public: // |BlitPass| ~BlitPassGLES() override; private: friend class CommandBufferGLES; std::vector<std::unique_ptr<BlitEncodeGLES>> commands_; ReactorGLES::Ref reactor_; std::string label_; bool is_valid_ = false; explicit BlitPassGLES(ReactorGLES::Ref reactor); // |BlitPass| bool IsValid() const override; // |BlitPass| void OnSetLabel(std::string label) override; // |BlitPass| bool EncodeCommands( const std::shared_ptr<Allocator>& transients_allocator) const override; // |BlitPass| bool OnCopyTextureToTextureCommand(std::shared_ptr<Texture> source, std::shared_ptr<Texture> destination, IRect source_region, IPoint destination_origin, std::string label) override; // |BlitPass| bool OnCopyTextureToBufferCommand(std::shared_ptr<Texture> source, std::shared_ptr<DeviceBuffer> destination, IRect source_region, size_t destination_offset, std::string label) override; // |BlitPass| bool OnCopyBufferToTextureCommand(BufferView source, std::shared_ptr<Texture> destination, IPoint destination_origin, std::string label) override { IMPELLER_UNIMPLEMENTED; return false; } // |BlitPass| bool OnGenerateMipmapCommand(std::shared_ptr<Texture> texture, std::string label) override; BlitPassGLES(const BlitPassGLES&) = delete; BlitPassGLES& operator=(const BlitPassGLES&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_PASS_GLES_H_
engine/impeller/renderer/backend/gles/blit_pass_gles.h/0
{ "file_path": "engine/impeller/renderer/backend/gles/blit_pass_gles.h", "repo_id": "engine", "token_count": 1214 }
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. #include "impeller/renderer/backend/gles/gpu_tracer_gles.h" #include <thread> #include "fml/trace_event.h" namespace impeller { GPUTracerGLES::GPUTracerGLES(const ProcTableGLES& gl, bool enable_tracing) { #ifdef IMPELLER_DEBUG auto desc = gl.GetDescription(); enabled_ = enable_tracing && desc->HasExtension("GL_EXT_disjoint_timer_query"); #endif // IMPELLER_DEBUG } void GPUTracerGLES::MarkFrameStart(const ProcTableGLES& gl) { if (!enabled_ || active_frame_.has_value() || std::this_thread::get_id() != raster_thread_) { return; } // At the beginning of a frame, check the status of all pending // previous queries. ProcessQueries(gl); uint32_t query = 0; gl.GenQueriesEXT(1, &query); if (query == 0) { return; } active_frame_ = query; gl.BeginQueryEXT(GL_TIME_ELAPSED_EXT, query); } void GPUTracerGLES::RecordRasterThread() { raster_thread_ = std::this_thread::get_id(); } void GPUTracerGLES::ProcessQueries(const ProcTableGLES& gl) { // For reasons unknown to me, querying the state of more than // one query object per frame causes crashes on a Pixel 6 pro. // It does not crash on an S10. while (!pending_traces_.empty()) { auto query = pending_traces_.front(); // First check if the query is complete without blocking // on the result. Incomplete results are left in the pending // trace vector and will not be checked again for another // frame. GLuint available = GL_FALSE; gl.GetQueryObjectuivEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT, &available); if (available != GL_TRUE) { // If a query is not available, then all subsequent queries will be // unavailable. return; } // Return the timer resolution in nanoseconds. uint64_t duration = 0; gl.GetQueryObjectui64vEXT(query, GL_QUERY_RESULT_EXT, &duration); auto gpu_ms = duration / 1000000.0; FML_TRACE_COUNTER("flutter", "GPUTracer", reinterpret_cast<int64_t>(this), // Trace Counter ID "FrameTimeMS", gpu_ms); gl.DeleteQueriesEXT(1, &query); pending_traces_.pop_front(); } } void GPUTracerGLES::MarkFrameEnd(const ProcTableGLES& gl) { if (!enabled_ || std::this_thread::get_id() != raster_thread_ || !active_frame_.has_value()) { return; } auto query = active_frame_.value(); gl.EndQueryEXT(GL_TIME_ELAPSED_EXT); pending_traces_.push_back(query); active_frame_ = std::nullopt; } } // namespace impeller
engine/impeller/renderer/backend/gles/gpu_tracer_gles.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/gpu_tracer_gles.cc", "repo_id": "engine", "token_count": 979 }
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. #include "impeller/renderer/backend/gles/sampler_library_gles.h" #include "impeller/base/config.h" #include "impeller/base/validation.h" #include "impeller/core/formats.h" #include "impeller/renderer/backend/gles/sampler_gles.h" namespace impeller { static const std::unique_ptr<const Sampler> kNullSampler = nullptr; SamplerLibraryGLES::SamplerLibraryGLES(bool supports_decal_sampler_address_mode) : supports_decal_sampler_address_mode_( supports_decal_sampler_address_mode) {} // |SamplerLibrary| SamplerLibraryGLES::~SamplerLibraryGLES() = default; // |SamplerLibrary| const std::unique_ptr<const Sampler>& SamplerLibraryGLES::GetSampler( SamplerDescriptor descriptor) { if (!supports_decal_sampler_address_mode_ && (descriptor.width_address_mode == SamplerAddressMode::kDecal || descriptor.height_address_mode == SamplerAddressMode::kDecal || descriptor.depth_address_mode == SamplerAddressMode::kDecal)) { VALIDATION_LOG << "SamplerAddressMode::kDecal is not supported by the " "current OpenGLES backend."; return kNullSampler; } auto found = samplers_.find(descriptor); if (found != samplers_.end()) { return found->second; } return (samplers_[descriptor] = std::unique_ptr<SamplerGLES>(new SamplerGLES(descriptor))); } } // namespace impeller
engine/impeller/renderer/backend/gles/sampler_library_gles.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/sampler_library_gles.cc", "repo_id": "engine", "token_count": 563 }
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. #include "flutter/testing/testing.h" // IWYU pragma: keep #include "fml/mapping.h" #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 { TEST(SpecConstant, CanCreateShaderWithSpecializationConstant) { auto mock_gles = MockGLES::Init(); auto& proc_table = mock_gles->GetProcTable(); auto shader_source = "#version 100\n" "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" "#endif\n" "void main() { return vec4(0.0); }"; auto test_shader = std::make_shared<fml::DataMapping>(shader_source); auto result = proc_table.ComputeShaderWithDefines(*test_shader, {0}); auto expected_shader_source = "#version 100\n" "#define SPIRV_CROSS_CONSTANT_ID_0 0.000000\n" "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" "#endif\n" "void main() { return vec4(0.0); }"; if (!result.has_value()) { GTEST_FAIL() << "Expected shader source"; } ASSERT_EQ(result.value(), expected_shader_source); } TEST(SpecConstant, CanCreateShaderWithSpecializationConstantMultipleValues) { auto mock_gles = MockGLES::Init(); auto& proc_table = mock_gles->GetProcTable(); auto shader_source = "#version 100\n" "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" "#endif\n" "void main() { return vec4(0.0); }"; auto test_shader = std::make_shared<fml::DataMapping>(shader_source); auto result = proc_table.ComputeShaderWithDefines(*test_shader, {0, 1, 2, 3, 4, 5}); auto expected_shader_source = "#version 100\n" "#define SPIRV_CROSS_CONSTANT_ID_0 0.000000\n" "#define SPIRV_CROSS_CONSTANT_ID_1 1.000000\n" "#define SPIRV_CROSS_CONSTANT_ID_2 2.000000\n" "#define SPIRV_CROSS_CONSTANT_ID_3 3.000000\n" "#define SPIRV_CROSS_CONSTANT_ID_4 4.000000\n" "#define SPIRV_CROSS_CONSTANT_ID_5 5.000000\n" "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" "#endif\n" "void main() { return vec4(0.0); }"; if (!result.has_value()) { GTEST_FAIL() << "Expected shader source"; } ASSERT_EQ(result.value(), expected_shader_source); } } // namespace testing } // namespace impeller
engine/impeller/renderer/backend/gles/test/specialization_constants_unittests.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/test/specialization_constants_unittests.cc", "repo_id": "engine", "token_count": 1111 }
218
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PIPELINE_MTL_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PIPELINE_MTL_H_ #include <Metal/Metal.h> #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" #include "impeller/renderer/pipeline.h" namespace impeller { class ComputePipelineMTL final : public Pipeline<ComputePipelineDescriptor>, public BackendCast<ComputePipelineMTL, Pipeline<ComputePipelineDescriptor>> { public: // |Pipeline| ~ComputePipelineMTL() override; id<MTLComputePipelineState> GetMTLComputePipelineState() const; private: friend class PipelineLibraryMTL; id<MTLComputePipelineState> pipeline_state_; bool is_valid_ = false; ComputePipelineMTL(std::weak_ptr<PipelineLibrary> library, const ComputePipelineDescriptor& desc, id<MTLComputePipelineState> state); // |Pipeline| bool IsValid() const override; ComputePipelineMTL(const ComputePipelineMTL&) = delete; ComputePipelineMTL& operator=(const ComputePipelineMTL&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PIPELINE_MTL_H_
engine/impeller/renderer/backend/metal/compute_pipeline_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/compute_pipeline_mtl.h", "repo_id": "engine", "token_count": 563 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_MTL_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_MTL_H_ #include <Metal/Metal.h> #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" #include "impeller/renderer/pipeline.h" namespace impeller { class PipelineMTL final : public Pipeline<PipelineDescriptor>, public BackendCast<PipelineMTL, Pipeline<PipelineDescriptor>> { public: // |Pipeline| ~PipelineMTL() override; id<MTLRenderPipelineState> GetMTLRenderPipelineState() const; id<MTLDepthStencilState> GetMTLDepthStencilState() const; private: friend class PipelineLibraryMTL; id<MTLRenderPipelineState> pipeline_state_; id<MTLDepthStencilState> depth_stencil_state_; bool is_valid_ = false; PipelineMTL(std::weak_ptr<PipelineLibrary> library, const PipelineDescriptor& desc, id<MTLRenderPipelineState> state, id<MTLDepthStencilState> depth_stencil_state); // |Pipeline| bool IsValid() const override; PipelineMTL(const PipelineMTL&) = delete; PipelineMTL& operator=(const PipelineMTL&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_MTL_H_
engine/impeller/renderer/backend/metal/pipeline_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/pipeline_mtl.h", "repo_id": "engine", "token_count": 550 }
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 "flutter/testing/testing.h" #include "impeller/core/formats.h" #include "impeller/core/texture_descriptor.h" #include "impeller/renderer/backend/metal/formats_mtl.h" #include "impeller/renderer/backend/metal/lazy_drawable_holder.h" #include "impeller/renderer/backend/metal/texture_mtl.h" #include "impeller/renderer/capabilities.h" #include <QuartzCore/CAMetalLayer.h> #include <thread> #include "gtest/gtest.h" namespace impeller { namespace testing { TEST(TextureMTL, CreateFromDrawable) { auto device = MTLCreateSystemDefaultDevice(); auto layer = [[CAMetalLayer alloc] init]; layer.device = device; layer.drawableSize = CGSize{100, 100}; layer.pixelFormat = ToMTLPixelFormat(PixelFormat::kB8G8R8A8UNormInt); TextureDescriptor desc; desc.size = {100, 100}; desc.format = PixelFormat::kB8G8R8A8UNormInt; auto drawable_future = GetDrawableDeferred(layer); auto drawable_texture = CreateTextureFromDrawableFuture(desc, drawable_future); ASSERT_TRUE(drawable_texture->IsValid()); EXPECT_TRUE(drawable_texture->IsDrawable()); // Spawn a thread and acquire the drawable in the thread. auto thread = std::thread([&drawable_texture]() { // Force the drawable to be acquired. drawable_texture->GetMTLTexture(); }); thread.join(); // Block until drawable is acquired. EXPECT_TRUE(drawable_future.get() != nil); // Drawable is cached. EXPECT_TRUE(drawable_texture->GetMTLTexture() != nil); // Once more for good measure. EXPECT_TRUE(drawable_texture->GetMTLTexture() != nil); } } // namespace testing } // namespace impeller
engine/impeller/renderer/backend/metal/texture_mtl_unittests.mm/0
{ "file_path": "engine/impeller/renderer/backend/metal/texture_mtl_unittests.mm", "repo_id": "engine", "token_count": 607 }
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. #include "impeller/renderer/backend/vulkan/blit_pass_vk.h" #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" #include "impeller/renderer/backend/vulkan/command_buffer_vk.h" namespace impeller { BlitPassVK::BlitPassVK(std::weak_ptr<CommandBufferVK> command_buffer) : command_buffer_(std::move(command_buffer)) {} BlitPassVK::~BlitPassVK() = default; void BlitPassVK::OnSetLabel(std::string label) { if (label.empty()) { return; } label_ = std::move(label); } // |BlitPass| bool BlitPassVK::IsValid() const { return true; } // |BlitPass| bool BlitPassVK::EncodeCommands( const std::shared_ptr<Allocator>& transients_allocator) const { TRACE_EVENT0("impeller", "BlitPassVK::EncodeCommands"); if (!IsValid()) { return false; } auto command_buffer = command_buffer_.lock(); if (!command_buffer) { return false; } auto encoder = command_buffer->GetEncoder(); if (!encoder) { return false; } for (auto& command : commands_) { if (!command->Encode(*encoder)) { return false; } } return true; } // |BlitPass| bool BlitPassVK::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<BlitCopyTextureToTextureCommandVK>(); command->source = std::move(source); command->destination = std::move(destination); command->source_region = source_region; command->destination_origin = destination_origin; command->label = std::move(label); commands_.push_back(std::move(command)); return true; } // |BlitPass| bool BlitPassVK::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<BlitCopyTextureToBufferCommandVK>(); command->source = std::move(source); command->destination = std::move(destination); command->source_region = source_region; command->destination_offset = destination_offset; command->label = std::move(label); commands_.push_back(std::move(command)); return true; } // |BlitPass| bool BlitPassVK::OnCopyBufferToTextureCommand( BufferView source, std::shared_ptr<Texture> destination, IPoint destination_origin, std::string label) { auto command = std::make_unique<BlitCopyBufferToTextureCommandVK>(); command->source = std::move(source); command->destination = std::move(destination); command->destination_origin = destination_origin; command->label = std::move(label); commands_.push_back(std::move(command)); return true; } // |BlitPass| bool BlitPassVK::OnGenerateMipmapCommand(std::shared_ptr<Texture> texture, std::string label) { auto command = std::make_unique<BlitGenerateMipmapCommandVK>(); command->texture = std::move(texture); command->label = std::move(label); commands_.push_back(std::move(command)); return true; } } // namespace impeller
engine/impeller/renderer/backend/vulkan/blit_pass_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/blit_pass_vk.cc", "repo_id": "engine", "token_count": 1153 }
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. #include "impeller/renderer/backend/vulkan/compute_pipeline_vk.h" namespace impeller { ComputePipelineVK::ComputePipelineVK( std::weak_ptr<DeviceHolderVK> device_holder, std::weak_ptr<PipelineLibrary> library, const ComputePipelineDescriptor& desc, vk::UniquePipeline pipeline, vk::UniquePipelineLayout layout, vk::UniqueDescriptorSetLayout descriptor_set_layout) : Pipeline(std::move(library), desc), device_holder_(std::move(device_holder)), pipeline_(std::move(pipeline)), layout_(std::move(layout)), descriptor_set_layout_(std::move(descriptor_set_layout)) { is_valid_ = pipeline_ && layout_ && descriptor_set_layout_; } ComputePipelineVK::~ComputePipelineVK() { std::shared_ptr<DeviceHolderVK> device_holder = device_holder_.lock(); if (device_holder) { descriptor_set_layout_.reset(); layout_.reset(); pipeline_.reset(); } else { descriptor_set_layout_.release(); layout_.release(); pipeline_.release(); } } bool ComputePipelineVK::IsValid() const { return is_valid_; } const vk::Pipeline& ComputePipelineVK::GetPipeline() const { return *pipeline_; } const vk::PipelineLayout& ComputePipelineVK::GetPipelineLayout() const { return *layout_; } const vk::DescriptorSetLayout& ComputePipelineVK::GetDescriptorSetLayout() const { return *descriptor_set_layout_; } } // namespace impeller
engine/impeller/renderer/backend/vulkan/compute_pipeline_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/compute_pipeline_vk.cc", "repo_id": "engine", "token_count": 568 }
223
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/backend/vulkan/fence_waiter_vk.h" #include <algorithm> #include <chrono> #include <utility> #include "flutter/fml/cpu_affinity.h" #include "flutter/fml/thread.h" #include "flutter/fml/trace_event.h" #include "impeller/base/validation.h" namespace impeller { class WaitSetEntry { public: static std::shared_ptr<WaitSetEntry> Create(vk::UniqueFence p_fence, const fml::closure& p_callback) { return std::shared_ptr<WaitSetEntry>( new WaitSetEntry(std::move(p_fence), p_callback)); } void UpdateSignalledStatus(const vk::Device& device) { if (is_signalled_) { return; } is_signalled_ = device.getFenceStatus(fence_.get()) == vk::Result::eSuccess; } const vk::Fence& GetFence() const { return fence_.get(); } bool IsSignalled() const { return is_signalled_; } private: vk::UniqueFence fence_; fml::ScopedCleanupClosure callback_; bool is_signalled_ = false; WaitSetEntry(vk::UniqueFence p_fence, const fml::closure& p_callback) : fence_(std::move(p_fence)), callback_(fml::ScopedCleanupClosure{p_callback}) {} WaitSetEntry(const WaitSetEntry&) = delete; WaitSetEntry(WaitSetEntry&&) = delete; WaitSetEntry& operator=(const WaitSetEntry&) = delete; WaitSetEntry& operator=(WaitSetEntry&&) = delete; }; FenceWaiterVK::FenceWaiterVK(std::weak_ptr<DeviceHolderVK> device_holder) : device_holder_(std::move(device_holder)) { waiter_thread_ = std::make_unique<std::thread>([&]() { Main(); }); } FenceWaiterVK::~FenceWaiterVK() { Terminate(); waiter_thread_->join(); } bool FenceWaiterVK::AddFence(vk::UniqueFence fence, const fml::closure& callback) { if (!fence || !callback) { return false; } { // Maintain the invariant that terminate_ is accessed only under the lock. std::scoped_lock lock(wait_set_mutex_); if (terminate_) { return false; } wait_set_.emplace_back(WaitSetEntry::Create(std::move(fence), callback)); } wait_set_cv_.notify_one(); return true; } static std::vector<vk::Fence> GetFencesForWaitSet(const WaitSet& set) { std::vector<vk::Fence> fences; for (const auto& entry : set) { if (!entry->IsSignalled()) { fences.emplace_back(entry->GetFence()); } } return fences; } void FenceWaiterVK::Main() { fml::Thread::SetCurrentThreadName( fml::Thread::ThreadConfig{"IplrVkFenceWait"}); // Since this thread mostly waits on fences, it doesn't need to be fast. fml::RequestAffinity(fml::CpuAffinity::kEfficiency); while (true) { // We'll read the terminate_ flag within the lock below. bool terminate = false; { std::unique_lock lock(wait_set_mutex_); // If there are no fences to wait on, wait on the condition variable. wait_set_cv_.wait(lock, [&]() { return !wait_set_.empty() || terminate_; }); // Still under the lock, check if the waiter has been terminated. terminate = terminate_; } if (terminate) { WaitUntilEmpty(); break; } if (!Wait()) { break; } } } void FenceWaiterVK::WaitUntilEmpty() { // Note, there is no lock because once terminate_ is set to true, no other // fence can be added to the wait set. Just in case, here's a FML_DCHECK: FML_DCHECK(terminate_) << "Fence waiter must be terminated."; while (!wait_set_.empty() && Wait()) { // Intentionally empty. } } bool FenceWaiterVK::Wait() { // Snapshot the wait set and wait on the fences. WaitSet wait_set; { std::scoped_lock lock(wait_set_mutex_); wait_set = wait_set_; } using namespace std::literals::chrono_literals; // Check if the context had died in the meantime. auto device_holder = device_holder_.lock(); if (!device_holder) { return false; } const auto& device = device_holder->GetDevice(); // Wait for one or more fences to be signaled. Any additional fences added // to the waiter will be serviced in the next pass. If a fence that is going // to be signaled at an abnormally long deadline is the only one in the set, // a timeout will bail out the wait. auto fences = GetFencesForWaitSet(wait_set); if (fences.empty()) { return true; } auto result = device.waitForFences( /*fenceCount=*/fences.size(), /*pFences=*/fences.data(), /*waitAll=*/false, /*timeout=*/std::chrono::nanoseconds{100ms}.count()); if (!(result == vk::Result::eSuccess || result == vk::Result::eTimeout)) { VALIDATION_LOG << "Fence waiter encountered an unexpected error. Tearing " "down the waiter thread."; return false; } // One or more fences have been signaled. Find out which ones and update // their signaled statuses. { TRACE_EVENT0("impeller", "CheckFenceStatus"); for (auto& entry : wait_set) { entry->UpdateSignalledStatus(device); } wait_set.clear(); } // Quickly acquire the wait set lock and erase signaled entries. Make sure // the mutex is unlocked before calling the destructors of the erased // entries. These might touch allocators. WaitSet erased_entries; { static constexpr auto is_signalled = [](const auto& entry) { return entry->IsSignalled(); }; std::scoped_lock lock(wait_set_mutex_); // TODO(matanlurey): Iterate the list 1x by copying is_signaled into erased. std::copy_if(wait_set_.begin(), wait_set_.end(), std::back_inserter(erased_entries), is_signalled); wait_set_.erase( std::remove_if(wait_set_.begin(), wait_set_.end(), is_signalled), wait_set_.end()); } { TRACE_EVENT0("impeller", "ClearSignaledFences"); // Erase the erased entries which will invoke callbacks. erased_entries.clear(); // Bit redundant because of scope but hey. } return true; } void FenceWaiterVK::Terminate() { { std::scoped_lock lock(wait_set_mutex_); terminate_ = true; } wait_set_cv_.notify_one(); } } // namespace impeller
engine/impeller/renderer/backend/vulkan/fence_waiter_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/fence_waiter_vk.cc", "repo_id": "engine", "token_count": 2339 }
224
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h" #include <algorithm> #include <vector> #include "impeller/renderer/backend/vulkan/formats_vk.h" namespace impeller { constexpr auto kSelfDependencySrcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; constexpr auto kSelfDependencySrcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite; constexpr auto kSelfDependencyDstStageMask = vk::PipelineStageFlagBits::eFragmentShader; constexpr auto kSelfDependencyDstAccessMask = vk::AccessFlagBits::eInputAttachmentRead; constexpr auto kSelfDependencyFlags = vk::DependencyFlagBits::eByRegion; RenderPassBuilderVK::RenderPassBuilderVK() = default; RenderPassBuilderVK::~RenderPassBuilderVK() = default; RenderPassBuilderVK& RenderPassBuilderVK::SetColorAttachment( size_t index, PixelFormat format, SampleCount sample_count, LoadAction load_action, StoreAction store_action) { vk::AttachmentDescription desc; desc.format = ToVKImageFormat(format); desc.samples = ToVKSampleCount(sample_count); desc.loadOp = ToVKAttachmentLoadOp(load_action); desc.storeOp = ToVKAttachmentStoreOp(store_action); desc.stencilLoadOp = vk::AttachmentLoadOp::eDontCare; desc.stencilStoreOp = vk::AttachmentStoreOp::eDontCare; desc.initialLayout = vk::ImageLayout::eGeneral; desc.finalLayout = vk::ImageLayout::eGeneral; colors_[index] = desc; desc.samples = vk::SampleCountFlagBits::e1; resolves_[index] = desc; return *this; } RenderPassBuilderVK& RenderPassBuilderVK::SetDepthStencilAttachment( PixelFormat format, SampleCount sample_count, LoadAction load_action, StoreAction store_action) { vk::AttachmentDescription desc; desc.format = ToVKImageFormat(format); desc.samples = ToVKSampleCount(sample_count); desc.loadOp = ToVKAttachmentLoadOp(load_action); desc.storeOp = ToVKAttachmentStoreOp(store_action); desc.stencilLoadOp = desc.loadOp; // Not separable in Impeller. desc.stencilStoreOp = desc.storeOp; // Not separable in Impeller. desc.initialLayout = vk::ImageLayout::eGeneral; desc.finalLayout = vk::ImageLayout::eGeneral; depth_stencil_ = desc; return *this; } RenderPassBuilderVK& RenderPassBuilderVK::SetStencilAttachment( PixelFormat format, SampleCount sample_count, LoadAction load_action, StoreAction store_action) { vk::AttachmentDescription desc; desc.format = ToVKImageFormat(format); desc.samples = ToVKSampleCount(sample_count); desc.loadOp = vk::AttachmentLoadOp::eDontCare; desc.storeOp = vk::AttachmentStoreOp::eDontCare; desc.stencilLoadOp = ToVKAttachmentLoadOp(load_action); desc.stencilStoreOp = ToVKAttachmentStoreOp(store_action); desc.initialLayout = vk::ImageLayout::eGeneral; desc.finalLayout = vk::ImageLayout::eGeneral; depth_stencil_ = desc; return *this; } vk::UniqueRenderPass RenderPassBuilderVK::Build( const vk::Device& device) const { FML_DCHECK(colors_.size() == resolves_.size()); // This must be less than `VkPhysicalDeviceLimits::maxColorAttachments` but we // are not checking. const auto color_attachments_count = colors_.empty() ? 0u : colors_.rbegin()->first + 1u; std::vector<vk::AttachmentDescription> attachments; std::vector<vk::AttachmentReference> color_refs(color_attachments_count, kUnusedAttachmentReference); std::vector<vk::AttachmentReference> resolve_refs(color_attachments_count, kUnusedAttachmentReference); vk::AttachmentReference depth_stencil_ref = kUnusedAttachmentReference; for (const auto& color : colors_) { vk::AttachmentReference color_ref; color_ref.attachment = attachments.size(); color_ref.layout = vk::ImageLayout::eGeneral; color_refs[color.first] = color_ref; attachments.push_back(color.second); if (color.second.samples != vk::SampleCountFlagBits::e1) { vk::AttachmentReference resolve_ref; resolve_ref.attachment = attachments.size(); resolve_ref.layout = vk::ImageLayout::eGeneral; resolve_refs[color.first] = resolve_ref; attachments.push_back(resolves_.at(color.first)); } } if (depth_stencil_.has_value()) { depth_stencil_ref.attachment = attachments.size(); depth_stencil_ref.layout = vk::ImageLayout::eGeneral; attachments.push_back(depth_stencil_.value()); } vk::SubpassDescription subpass0; subpass0.pipelineBindPoint = vk::PipelineBindPoint::eGraphics; subpass0.setInputAttachments(color_refs); subpass0.setColorAttachments(color_refs); subpass0.setResolveAttachments(resolve_refs); subpass0.setPDepthStencilAttachment(&depth_stencil_ref); vk::SubpassDependency self_dep; self_dep.srcSubpass = 0u; // first subpass self_dep.dstSubpass = 0u; // to itself self_dep.srcStageMask = kSelfDependencySrcStageMask; self_dep.srcAccessMask = kSelfDependencySrcAccessMask; self_dep.dstStageMask = kSelfDependencyDstStageMask; self_dep.dstAccessMask = kSelfDependencyDstAccessMask; self_dep.dependencyFlags = kSelfDependencyFlags; vk::RenderPassCreateInfo render_pass_desc; render_pass_desc.setAttachments(attachments); render_pass_desc.setSubpasses(subpass0); render_pass_desc.setDependencies(self_dep); auto [result, pass] = device.createRenderPassUnique(render_pass_desc); if (result != vk::Result::eSuccess) { VALIDATION_LOG << "Failed to create render pass: " << vk::to_string(result); return {}; } return std::move(pass); } void InsertBarrierForInputAttachmentRead(const vk::CommandBuffer& buffer, const vk::Image& image) { // This barrier must be a subset of the masks specified in the subpass // dependency setup. vk::ImageMemoryBarrier barrier; barrier.srcAccessMask = kSelfDependencySrcAccessMask; barrier.dstAccessMask = kSelfDependencyDstAccessMask; barrier.oldLayout = vk::ImageLayout::eGeneral; barrier.newLayout = vk::ImageLayout::eGeneral; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; vk::ImageSubresourceRange image_levels; image_levels.aspectMask = vk::ImageAspectFlagBits::eColor; image_levels.baseArrayLayer = 0u; image_levels.baseMipLevel = 0u; image_levels.layerCount = VK_REMAINING_ARRAY_LAYERS; image_levels.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange = image_levels; buffer.pipelineBarrier(kSelfDependencySrcStageMask, // kSelfDependencyDstStageMask, // kSelfDependencyFlags, // {}, // {}, // barrier // ); } } // namespace impeller
engine/impeller/renderer/backend/vulkan/render_pass_builder_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/render_pass_builder_vk.cc", "repo_id": "engine", "token_count": 2675 }
225
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEST_MOCK_VULKAN_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEST_MOCK_VULKAN_H_ #include <functional> #include <memory> #include <string> #include <vector> #include "impeller/base/thread.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "vulkan/vulkan_core.h" #include "vulkan/vulkan_enums.hpp" namespace impeller { namespace testing { std::shared_ptr<std::vector<std::string>> GetMockVulkanFunctions( VkDevice device); // A test-controlled version of |vk::Fence|. class MockFence final { public: MockFence() = default; // Returns the result that was set in the constructor or |SetStatus|. VkResult GetStatus() { return static_cast<VkResult>(result_.load()); } // Sets the result that will be returned by `GetFenceStatus`. void SetStatus(vk::Result result) { result_ = result; } // Sets the result that will be returned by `GetFenceStatus`. static void SetStatus(vk::UniqueFence& fence, vk::Result result) { // Cast the fence to a MockFence and set the result. VkFence raw_fence = fence.get(); MockFence* mock_fence = reinterpret_cast<MockFence*>(raw_fence); mock_fence->SetStatus(result); } // Gets a raw pointer to manipulate the fence after it's been moved. static MockFence* GetRawPointer(vk::UniqueFence& fence) { // Cast the fence to a MockFence and get the result. VkFence raw_fence = fence.get(); MockFence* mock_fence = reinterpret_cast<MockFence*>(raw_fence); return mock_fence; } private: std::atomic<vk::Result> result_ = vk::Result::eSuccess; MockFence(const MockFence&) = delete; MockFence& operator=(const MockFence&) = delete; }; class MockVulkanContextBuilder { public: MockVulkanContextBuilder(); //------------------------------------------------------------------------------ /// @brief Create a Vulkan context with Vulkan functions mocked. The /// caller is given a chance to tinker on the settings right /// before a context is created. /// /// @return A context if one can be created. /// std::shared_ptr<ContextVK> Build(); /// A callback that allows the modification of the ContextVK::Settings before /// the context is made. MockVulkanContextBuilder& SetSettingsCallback( const std::function<void(ContextVK::Settings&)>& settings_callback) { settings_callback_ = settings_callback; return *this; } MockVulkanContextBuilder& SetInstanceExtensions( const std::vector<std::string>& instance_extensions) { instance_extensions_ = instance_extensions; return *this; } MockVulkanContextBuilder& SetInstanceLayers( const std::vector<std::string>& instance_layers) { instance_layers_ = instance_layers; return *this; } /// Set the behavior of vkGetPhysicalDeviceFormatProperties, which needs to /// respond differently for different formats. MockVulkanContextBuilder& SetPhysicalDeviceFormatPropertiesCallback( std::function<void(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties)> format_properties_callback) { format_properties_callback_ = std::move(format_properties_callback); return *this; } private: std::function<void(ContextVK::Settings&)> settings_callback_; std::vector<std::string> instance_extensions_; std::vector<std::string> instance_layers_; std::function<void(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties)> format_properties_callback_; }; /// @brief Override the image size returned by all swapchain images. void SetSwapchainImageSize(ISize size); } // namespace testing } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEST_MOCK_VULKAN_H_
engine/impeller/renderer/backend/vulkan/test/mock_vulkan.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/test/mock_vulkan.h", "repo_id": "engine", "token_count": 1415 }
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/renderer/backend/vulkan/yuv_conversion_vk.h" #include "flutter/fml/hash_combine.h" #include "impeller/base/validation.h" #include "impeller/renderer/backend/vulkan/device_holder_vk.h" #include "impeller/renderer/backend/vulkan/sampler_vk.h" namespace impeller { YUVConversionVK::YUVConversionVK(const vk::Device& device, const YUVConversionDescriptorVK& chain) : chain_(chain) { auto conversion = device.createSamplerYcbcrConversionUnique(chain_.get()); if (conversion.result != vk::Result::eSuccess) { VALIDATION_LOG << "Could not create YUV conversion: " << vk::to_string(conversion.result); return; } conversion_ = std::move(conversion.value); } YUVConversionVK::~YUVConversionVK() = default; bool YUVConversionVK::IsValid() const { return conversion_ && !!conversion_.get(); } vk::SamplerYcbcrConversion YUVConversionVK::GetConversion() const { return conversion_ ? conversion_.get() : static_cast<vk::SamplerYcbcrConversion>(VK_NULL_HANDLE); } const YUVConversionDescriptorVK& YUVConversionVK::GetDescriptor() const { return chain_; } std::size_t YUVConversionDescriptorVKHash::operator()( const YUVConversionDescriptorVK& desc) const { // Hashers in Vulkan HPP hash the pNext member which isn't what we want for // these to be stable. const auto& conv = desc.get(); std::size_t hash = fml::HashCombine(conv.format, // conv.ycbcrModel, // conv.ycbcrRange, // conv.components.r, // conv.components.g, // conv.components.b, // conv.components.a, // conv.xChromaOffset, // conv.yChromaOffset, // conv.chromaFilter, // conv.forceExplicitReconstruction // ); #if FML_OS_ANDROID const auto external_format = desc.get<vk::ExternalFormatANDROID>(); fml::HashCombineSeed(hash, external_format.externalFormat); #endif // FML_OS_ANDROID return hash; }; bool YUVConversionDescriptorVKEqual::operator()( const YUVConversionDescriptorVK& lhs_desc, const YUVConversionDescriptorVK& rhs_desc) const { // Default equality checks in Vulkan HPP checks pNext member members by // pointer which isn't what we want. { const auto& lhs = lhs_desc.get(); const auto& rhs = rhs_desc.get(); if (lhs.format != rhs.format || // lhs.ycbcrModel != rhs.ycbcrModel || // lhs.ycbcrRange != rhs.ycbcrRange || // lhs.components.r != rhs.components.r || // lhs.components.g != rhs.components.g || // lhs.components.b != rhs.components.b || // lhs.components.a != rhs.components.a || // lhs.xChromaOffset != rhs.xChromaOffset || // lhs.yChromaOffset != rhs.yChromaOffset || // lhs.chromaFilter != rhs.chromaFilter || // lhs.forceExplicitReconstruction != rhs.forceExplicitReconstruction // ) { return false; } } #if FML_OS_ANDROID { const auto lhs = lhs_desc.get<vk::ExternalFormatANDROID>(); const auto rhs = rhs_desc.get<vk::ExternalFormatANDROID>(); return lhs.externalFormat == rhs.externalFormat; } #else // FML_OS_ANDROID return true; #endif // FML_OS_ANDROID } ImmutableSamplerKeyVK::ImmutableSamplerKeyVK(const SamplerVK& sampler) : sampler(sampler.GetDescriptor()) { if (const auto& conversion = sampler.GetYUVConversion()) { yuv_conversion = conversion->GetDescriptor(); } } bool ImmutableSamplerKeyVK::IsEqual(const ImmutableSamplerKeyVK& other) const { return sampler.IsEqual(other.sampler) && YUVConversionDescriptorVKEqual{}(yuv_conversion, other.yuv_conversion); } std::size_t ImmutableSamplerKeyVK::GetHash() const { return fml::HashCombine(sampler.GetHash(), YUVConversionDescriptorVKHash{}(yuv_conversion)); } } // namespace impeller
engine/impeller/renderer/backend/vulkan/yuv_conversion_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/yuv_conversion_vk.cc", "repo_id": "engine", "token_count": 2381 }
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/renderer/compute_pass.h" namespace impeller { ComputePass::ComputePass(std::shared_ptr<const Context> context) : context_(std::move(context)) {} ComputePass::~ComputePass() = default; void ComputePass::SetLabel(const std::string& label) { if (label.empty()) { return; } OnSetLabel(label); } } // namespace impeller
engine/impeller/renderer/compute_pass.cc/0
{ "file_path": "engine/impeller/renderer/compute_pass.cc", "repo_id": "engine", "token_count": 170 }
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. #define FML_USED_ON_EMBEDDER #include <memory> #include "flutter/common/settings.h" #include "flutter/common/task_runners.h" #include "flutter/lib/gpu/context.h" #include "flutter/lib/gpu/shader_library.h" #include "flutter/runtime/dart_isolate.h" #include "flutter/runtime/dart_vm_lifecycle.h" #include "flutter/testing/dart_fixture.h" #include "flutter/testing/dart_isolate_runner.h" #include "flutter/testing/testing.h" #include "fml/memory/ref_ptr.h" #include "impeller/playground/playground_test.h" #include "impeller/renderer/render_pass.h" #include "gtest/gtest.h" #include "third_party/imgui/imgui.h" namespace impeller { namespace testing { static void InstantiateTestShaderLibrary(Context::BackendType backend_type) { auto fixture = flutter::testing::OpenFixtureAsMapping("playground.shaderbundle"); auto library = flutter::gpu::ShaderLibrary::MakeFromFlatbuffer( backend_type, std::move(fixture)); flutter::gpu::ShaderLibrary::SetOverride(library); } class RendererDartTest : public PlaygroundTest, public flutter::testing::DartFixture { public: RendererDartTest() : settings_(CreateSettingsForFixture()), vm_ref_(flutter::DartVMRef::Create(settings_)) { fml::MessageLoop::EnsureInitializedForCurrentThread(); current_task_runner_ = fml::MessageLoop::GetCurrent().GetTaskRunner(); isolate_ = CreateDartIsolate(); assert(isolate_); assert(isolate_->get()->GetPhase() == flutter::DartIsolate::Phase::Running); } flutter::testing::AutoIsolateShutdown* GetIsolate() { // Sneak the context into the Flutter GPU API. assert(GetContext() != nullptr); flutter::gpu::Context::SetOverrideContext(GetContext()); InstantiateTestShaderLibrary(GetContext()->GetBackendType()); return isolate_.get(); } private: std::unique_ptr<flutter::testing::AutoIsolateShutdown> CreateDartIsolate() { const auto settings = CreateSettingsForFixture(); flutter::TaskRunners task_runners(flutter::testing::GetCurrentTestName(), current_task_runner_, // current_task_runner_, // current_task_runner_, // current_task_runner_ // ); return flutter::testing::RunDartCodeInIsolate( vm_ref_, settings, task_runners, "main", {}, flutter::testing::GetDefaultKernelFilePath()); } const flutter::Settings settings_; flutter::DartVMRef vm_ref_; fml::RefPtr<fml::TaskRunner> current_task_runner_; std::unique_ptr<flutter::testing::AutoIsolateShutdown> isolate_; }; INSTANTIATE_PLAYGROUND_SUITE(RendererDartTest); TEST_P(RendererDartTest, CanRunDartInPlaygroundFrame) { auto isolate = GetIsolate(); SinglePassCallback callback = [&](RenderPass& pass) { ImGui::Begin("Dart test", nullptr); ImGui::Text( "This test executes Dart code during the playground frame callback."); ImGui::End(); return isolate->RunInIsolateScope([]() -> bool { if (tonic::CheckAndHandleError(::Dart_Invoke( Dart_RootLibrary(), tonic::ToDart("sayHi"), 0, nullptr))) { return false; } return true; }); }; OpenPlaygroundHere(callback); } TEST_P(RendererDartTest, CanInstantiateFlutterGPUContext) { auto isolate = GetIsolate(); bool result = isolate->RunInIsolateScope([]() -> bool { if (tonic::CheckAndHandleError(::Dart_Invoke( Dart_RootLibrary(), tonic::ToDart("instantiateDefaultContext"), 0, nullptr))) { return false; } return true; }); ASSERT_TRUE(result); } #define DART_TEST_CASE(name) \ TEST_P(RendererDartTest, name) { \ auto isolate = GetIsolate(); \ bool result = isolate->RunInIsolateScope([]() -> bool { \ if (tonic::CheckAndHandleError(::Dart_Invoke( \ Dart_RootLibrary(), tonic::ToDart(#name), 0, nullptr))) { \ return false; \ } \ return true; \ }); \ ASSERT_TRUE(result); \ } /// These test entries correspond to Dart functions located in /// `flutter/impeller/fixtures/dart_tests.dart` DART_TEST_CASE(canCreateShaderLibrary); DART_TEST_CASE(canReflectUniformStructs); DART_TEST_CASE(uniformBindFailsForInvalidHostBufferOffset); DART_TEST_CASE(canCreateRenderPassAndSubmit); } // namespace testing } // namespace impeller
engine/impeller/renderer/renderer_dart_unittests.cc/0
{ "file_path": "engine/impeller/renderer/renderer_dart_unittests.cc", "repo_id": "engine", "token_count": 2226 }
229
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/texture_mipmap.h" #include "impeller/renderer/blit_pass.h" #include "impeller/renderer/command_buffer.h" namespace impeller { fml::Status AddMipmapGeneration( const std::shared_ptr<CommandBuffer>& command_buffer, const std::shared_ptr<Context>& context, const std::shared_ptr<Texture>& texture) { std::shared_ptr<BlitPass> blit_pass = command_buffer->CreateBlitPass(); bool success = blit_pass->GenerateMipmap(texture); if (!success) { return fml::Status(fml::StatusCode::kUnknown, ""); } success = blit_pass->EncodeCommands(context->GetResourceAllocator()); if (!success) { return fml::Status(fml::StatusCode::kUnknown, ""); } return fml::Status(); } } // namespace impeller
engine/impeller/renderer/texture_mipmap.cc/0
{ "file_path": "engine/impeller/renderer/texture_mipmap.cc", "repo_id": "engine", "token_count": 311 }
230
## ⚠️ **Experimental:** Do not use in production! ⚠️ # Impeller Scene Impeller Scene is an experimental realtime 3D renderer powered by Impeller's render layer with the following design priorities: * Ease of use. * Suitability for mobile. * Common case scalability. The aim is to create a familiar and flexible scene graph capable of building complex dynamic scenes for games and beyond. ## Example ```cpp std::shared_ptr<impeller::Context> context = /* Create the backend-specific Impeller context */; auto allocator = context->GetResourceAllocator(); /// Load resources. auto dash_gltf = impeller::scene::LoadGLTF(allocator, "models/dash.glb"); auto environment_hdri = impeller::scene::LoadHDRI(allocator, "environment/table_mountain.hdr"); /// Construct a scene. auto scene = impeller::scene::Scene(context); scene.Add(dash_gltf.scene); auto& dash_player = dash_gltf.scene.CreateAnimationPlayer(); auto& walk_action = dash_player.CreateClipAction(dash_gltf.GetClip("Walk")); walk_action.SetLoop(impeller::scene::AnimationAction::kLoopForever); walk_action.SetWeight(0.7f); walk_action.Seek(0.0f); walk_action.Play(); auto& run_action = dash_player.CreateClipAction(dash_gltf.GetClip("Run")); run_action.SetLoop(impeller::scene::AnimationAction::kLoopForever); run_action.SetWeight(0.3f); run_action.Play(); scene.GetRoot().AddChild( impeller::scene::DirectionalLight( /* color */ impeller::Color::AntiqueWhite(), /* intensity */ 5, /* direction */ {2, 3, 4})); Node sphere_node; Mesh sphere_mesh; sphere_node.SetGlobalTransform( Matrix::MakeRotationEuler({kPiOver4, kPiOver4, 0})); auto sphere_geometry = impeller::scene::Geometry::MakeSphere(allocator, /* radius */ 2); auto material = impeller::scene::Material::MakeStandard(); material->SetAlbedo(impeller::Color::Red()); material->SetRoughness(0.4); material->SetMetallic(0.2); // Common properties shared by all materials. material->SetEnvironmentMap(environment_hdri); material->SetFlatShaded(true); material->SetBlendConfig({ impeller::BlendOperation::kAdd, // color_op impeller::BlendFactor::kOne, // source_color_factor impeller::BlendFactor::kOneMinusSourceAlpha, // destination_color_factor impeller::BlendOperation::kAdd, // alpha_op impeller::BlendFactor::kOne, // source_alpha_factor impeller::BlendFactor::kOneMinusSourceAlpha, // destination_alpha_factor }); material->SetStencilConfig({ impeller::StencilOperation::kIncrementClamp, // operation impeller::CompareFunction::kAlways, // compare }); sphere_mesh.AddPrimitive({sphere_geometry, material}); sphere_node.SetMesh(sphere_mesh); Node cube_node; cube_node.SetLocalTransform(Matrix::MakeTranslation({4, 0, 0})); Mesh cube_mesh; auto cube_geometry = impeller::scene::Geometry::MakeCuboid( allocator, {4, 4, 4}); cube_mesh.AddPrimitive({cube_geometry, material}); cube_node.SetMesh(cube_mesh); sphere_node.AddChild(cube_node); scene.GetRoot().AddChild(sphere_node); /// Post processing. auto dof = impeller::scene::PostProcessingEffect::MakeBokeh( /* aperture_size */ 0.2, /* focus_plane_distance */ 50); scene.SetPostProcessing({dof}); /// Render the scene. auto renderer = impeller::Renderer(context); while(true) { std::unique_ptr<impeller::Surface> surface = /* Wrap the window surface */; renderer->Render(surface, [&scene](RenderTarget& render_target) { /// Render a perspective view. auto camera = impeller::Camera::MakePerspective( /* fov */ kPiOver4, /* position */ {50, -30, 50}) .LookAt( /* target */ impeller::Vector3::Zero, /* up */ {0, -1, 0}); scene.Render(render_target, camera); /// Render an overhead view on the bottom right corner of the screen. auto size = render_target.GetRenderTargetSize(); auto minimap_camera = impeller::Camera::MakeOrthographic( /* view */ Rect::MakeLTRB(-100, -100, 100, 100), /* position */ {0, -50, 0}) .LookAt( /* target */ impeller::Vector3::Zero, /* up */ {0, 0, 1}) .WithViewport(IRect::MakeXYWH(size.width / 4, size.height / 4, size.height / 5, size.height / 5)); scene.Render(render_target, minimap_camera); return true; }); } ```
engine/impeller/scene/README.md/0
{ "file_path": "engine/impeller/scene/README.md", "repo_id": "engine", "token_count": 1654 }
231
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_SCENE_IMPORTER_CONVERSIONS_H_ #define FLUTTER_IMPELLER_SCENE_IMPORTER_CONVERSIONS_H_ #include <cstddef> #include <map> #include <vector> #include "impeller/geometry/matrix.h" #include "impeller/scene/importer/scene_flatbuffers.h" namespace impeller { namespace scene { namespace importer { Matrix ToMatrix(const std::vector<double>& m); //----------------------------------------------------------------------------- /// Flatbuffers -> Impeller /// Matrix ToMatrix(const fb::Matrix& m); Vector2 ToVector2(const fb::Vec2& c); Vector3 ToVector3(const fb::Vec3& c); Vector4 ToVector4(const fb::Vec4& c); Color ToColor(const fb::Color& c); //----------------------------------------------------------------------------- /// Impeller -> Flatbuffers /// fb::Matrix ToFBMatrix(const Matrix& m); std::unique_ptr<fb::Matrix> ToFBMatrixUniquePtr(const Matrix& m); fb::Vec2 ToFBVec2(const Vector2 v); fb::Vec3 ToFBVec3(const Vector3 v); fb::Vec4 ToFBVec4(const Vector4 v); fb::Color ToFBColor(const Color c); std::unique_ptr<fb::Color> ToFBColor(const std::vector<double>& c); } // namespace importer } // namespace scene } // namespace impeller #endif // FLUTTER_IMPELLER_SCENE_IMPORTER_CONVERSIONS_H_
engine/impeller/scene/importer/conversions.h/0
{ "file_path": "engine/impeller/scene/importer/conversions.h", "repo_id": "engine", "token_count": 487 }
232
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_SCENE_NODE_H_ #define FLUTTER_IMPELLER_SCENE_NODE_H_ #include <memory> #include <mutex> #include <optional> #include <vector> #include "flutter/fml/macros.h" #include "impeller/base/thread.h" #include "impeller/base/thread_safety.h" #include "impeller/core/texture.h" #include "impeller/geometry/matrix.h" #include "impeller/renderer/render_target.h" #include "impeller/scene/animation/animation.h" #include "impeller/scene/animation/animation_clip.h" #include "impeller/scene/animation/animation_player.h" #include "impeller/scene/camera.h" #include "impeller/scene/mesh.h" #include "impeller/scene/scene_encoder.h" #include "impeller/scene/skin.h" namespace impeller { namespace scene { class Node final { public: class MutationLog { public: struct SetTransformEntry { Matrix transform; }; struct SetAnimationStateEntry { std::string animation_name; bool playing = false; bool loop = false; Scalar weight = 0; Scalar time_scale = 1; }; struct SeekAnimationEntry { std::string animation_name; float time = 0; }; using Entry = std:: variant<SetTransformEntry, SetAnimationStateEntry, SeekAnimationEntry>; void Append(const Entry& entry); private: std::optional<std::vector<Entry>> Flush(); RWMutex write_mutex_; bool dirty_ IPLR_GUARDED_BY(write_mutex_) = false; std::vector<Entry> entries_ IPLR_GUARDED_BY(write_mutex_); friend Node; }; static std::shared_ptr<Node> MakeFromFlatbuffer( const fml::Mapping& ipscene_mapping, Allocator& allocator); static std::shared_ptr<Node> MakeFromFlatbuffer(const fb::Scene& scene, Allocator& allocator); Node(); ~Node(); const std::string& GetName() const; void SetName(const std::string& new_name); Node* GetParent() const; std::shared_ptr<Node> FindChildByName( const std::string& name, bool exclude_animation_players = false) const; std::shared_ptr<Animation> FindAnimationByName(const std::string& name) const; AnimationClip* AddAnimation(const std::shared_ptr<Animation>& animation); void SetLocalTransform(Matrix transform); Matrix GetLocalTransform() const; void SetGlobalTransform(Matrix transform); Matrix GetGlobalTransform() const; bool AddChild(std::shared_ptr<Node> child); std::vector<std::shared_ptr<Node>>& GetChildren(); void SetMesh(Mesh mesh); Mesh& GetMesh(); void SetIsJoint(bool is_joint); bool IsJoint() const; bool Render(SceneEncoder& encoder, Allocator& allocator, const Matrix& parent_transform); void AddMutation(const MutationLog::Entry& entry); private: void UnpackFromFlatbuffer( const fb::Node& node, const std::vector<std::shared_ptr<Node>>& scene_nodes, const std::vector<std::shared_ptr<Texture>>& textures, Allocator& allocator); mutable MutationLog mutation_log_; Matrix local_transform_; std::string name_; bool is_root_ = false; bool is_joint_ = false; Node* parent_ = nullptr; std::vector<std::shared_ptr<Node>> children_; Mesh mesh_; // For convenience purposes, deserialized nodes hang onto an animation library std::vector<std::shared_ptr<Animation>> animations_; mutable std::optional<AnimationPlayer> animation_player_; std::unique_ptr<Skin> skin_; Node(const Node&) = delete; Node& operator=(const Node&) = delete; friend Scene; }; } // namespace scene } // namespace impeller #endif // FLUTTER_IMPELLER_SCENE_NODE_H_
engine/impeller/scene/node.h/0
{ "file_path": "engine/impeller/scene/node.h", "repo_id": "engine", "token_count": 1381 }
233
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/shader_archive/multi_arch_shader_archive.h" #include "impeller/shader_archive/multi_arch_shader_archive_flatbuffers.h" namespace impeller { constexpr ArchiveRenderingBackend ToArchiveRenderingBackend( fb::RenderingBackend backend) { switch (backend) { case fb::RenderingBackend::kOpenGLES: return ArchiveRenderingBackend::kOpenGLES; case fb::RenderingBackend::kVulkan: return ArchiveRenderingBackend::kVulkan; case fb::RenderingBackend::kMetal: return ArchiveRenderingBackend::kMetal; } FML_UNREACHABLE(); } std::shared_ptr<ShaderArchive> MultiArchShaderArchive::CreateArchiveFromMapping( const std::shared_ptr<const fml::Mapping>& mapping, ArchiveRenderingBackend backend) { { auto multi_archive = std::make_shared<MultiArchShaderArchive>(mapping); if (multi_archive->IsValid()) { return multi_archive->GetShaderArchive(backend); } } { auto single_archive = std::shared_ptr<ShaderArchive>(new ShaderArchive(mapping)); if (single_archive->IsValid()) { return single_archive; } } return nullptr; } MultiArchShaderArchive::MultiArchShaderArchive( const std::shared_ptr<const fml::Mapping>& mapping) { if (!mapping) { return; } if (!fb::MultiArchShaderArchiveBufferHasIdentifier(mapping->GetMapping())) { return; } const auto* multi_arch = fb::GetMultiArchShaderArchive(mapping->GetMapping()); if (!multi_arch) { return; } if (auto archives = multi_arch->items()) { for (auto i = archives->begin(), end = archives->end(); i != end; i++) { // This implementation is unable to handle multiple archives for the same // backend. backend_mappings_[ToArchiveRenderingBackend(i->rendering_backend())] = std::make_shared<fml::NonOwnedMapping>(i->mapping()->Data(), i->mapping()->size(), [mapping](auto, auto) { // Just hold the mapping. }); } } is_valid_ = true; } MultiArchShaderArchive::~MultiArchShaderArchive() = default; bool MultiArchShaderArchive::IsValid() const { return is_valid_; } std::shared_ptr<const fml::Mapping> MultiArchShaderArchive::GetArchive( ArchiveRenderingBackend backend) const { auto found = backend_mappings_.find(backend); if (found == backend_mappings_.end()) { return nullptr; } return found->second; } std::shared_ptr<ShaderArchive> MultiArchShaderArchive::GetShaderArchive( ArchiveRenderingBackend backend) const { auto archive = GetArchive(backend); if (!archive) { return nullptr; } auto shader_archive = std::shared_ptr<ShaderArchive>(new ShaderArchive(std::move(archive))); if (!shader_archive->IsValid()) { return nullptr; } return shader_archive; } } // namespace impeller
engine/impeller/shader_archive/multi_arch_shader_archive.cc/0
{ "file_path": "engine/impeller/shader_archive/multi_arch_shader_archive.cc", "repo_id": "engine", "token_count": 1266 }
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 "tessellator.h" #include <vector> namespace impeller { PathBuilder* CreatePathBuilder() { return new PathBuilder(); } void DestroyPathBuilder(PathBuilder* builder) { delete builder; } void MoveTo(PathBuilder* builder, Scalar x, Scalar y) { builder->MoveTo(Point(x, y)); } void LineTo(PathBuilder* builder, Scalar x, Scalar y) { builder->LineTo(Point(x, y)); } void CubicTo(PathBuilder* builder, Scalar x1, Scalar y1, Scalar x2, Scalar y2, Scalar x3, Scalar y3) { builder->CubicCurveTo(Point(x1, y1), Point(x2, y2), Point(x3, y3)); } void Close(PathBuilder* builder) { builder->Close(); } struct Vertices* Tessellate(PathBuilder* builder, int fill_type, Scalar tolerance) { auto path = builder->CopyPath(static_cast<FillType>(fill_type)); std::vector<float> points; if (Tessellator{}.Tessellate( path, tolerance, [&points](const float* vertices, size_t vertices_count, const uint16_t* indices, size_t indices_count) { // Results are expected to be re-duplicated. std::vector<Point> raw_points; for (auto i = 0u; i < vertices_count * 2; i += 2) { raw_points.emplace_back(Point{vertices[i], vertices[i + 1]}); } for (auto i = 0u; i < indices_count; i++) { auto point = raw_points[indices[i]]; points.push_back(point.x); points.push_back(point.y); } return true; }) != Tessellator::Result::kSuccess) { return nullptr; } Vertices* vertices = new Vertices(); vertices->points = new float[points.size()]; if (!vertices->points) { return nullptr; } vertices->length = points.size(); std::copy(points.begin(), points.end(), vertices->points); return vertices; } void DestroyVertices(Vertices* vertices) { delete vertices->points; delete vertices; } } // namespace impeller
engine/impeller/tessellator/c/tessellator.cc/0
{ "file_path": "engine/impeller/tessellator/c/tessellator.cc", "repo_id": "engine", "token_count": 972 }
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. #ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_PROC_TABLE_H_ #define FLUTTER_IMPELLER_TOOLKIT_ANDROID_PROC_TABLE_H_ #include <EGL/egl.h> #define EGL_EGLEXT_PROTOTYPES #include <EGL/eglext.h> #include <android/api-level.h> #include <android/hardware_buffer.h> #include <android/hardware_buffer_jni.h> #include <android/surface_control.h> #include <android/trace.h> #include <functional> #include "flutter/fml/logging.h" #include "flutter/fml/native_library.h" namespace impeller::android { //------------------------------------------------------------------------------ /// @brief The Android procs along with the device API level on which these /// will be available. There is no checking of the actual API level /// however (because getting the API level is itself only possible /// on API levels 29 and above). /// /// Take care to explicitly check for the availability of these APIs /// at runtime before invoking them. /// /// Typically, you'll never have to deal with the proc. table /// directly. Instead, rely on the handle wrappers (`Choreographer`, /// `HardwareBuffer`, etc..). /// #define FOR_EACH_ANDROID_PROC(INVOKE) \ INVOKE(AChoreographer_getInstance, 24) \ INVOKE(AChoreographer_postFrameCallback, 24) \ INVOKE(AChoreographer_postFrameCallback64, 29) \ INVOKE(AHardwareBuffer_acquire, 26) \ INVOKE(AHardwareBuffer_allocate, 26) \ INVOKE(AHardwareBuffer_describe, 26) \ INVOKE(AHardwareBuffer_fromHardwareBuffer, 26) \ INVOKE(AHardwareBuffer_getId, 31) \ INVOKE(AHardwareBuffer_isSupported, 29) \ INVOKE(AHardwareBuffer_release, 26) \ INVOKE(ANativeWindow_acquire, 0) \ INVOKE(ANativeWindow_getHeight, 0) \ INVOKE(ANativeWindow_getWidth, 0) \ INVOKE(ANativeWindow_release, 0) \ INVOKE(ASurfaceControl_createFromWindow, 29) \ INVOKE(ASurfaceControl_release, 29) \ INVOKE(ASurfaceTransaction_apply, 29) \ INVOKE(ASurfaceTransaction_create, 29) \ INVOKE(ASurfaceTransaction_delete, 29) \ INVOKE(ASurfaceTransaction_reparent, 29) \ INVOKE(ASurfaceTransaction_setBuffer, 29) \ INVOKE(ASurfaceTransaction_setColor, 29) \ INVOKE(ASurfaceTransaction_setOnComplete, 29) \ INVOKE(ATrace_isEnabled, 23) \ INVOKE(eglGetNativeClientBufferANDROID, 0) template <class T> struct AndroidProc { using AndroidProcType = T; const char* proc_name = nullptr; AndroidProcType* proc = nullptr; constexpr bool IsAvailable() const { return proc != nullptr; } explicit constexpr operator bool() const { return IsAvailable(); } template <class... Args> auto operator()(Args&&... args) const { FML_DCHECK(IsAvailable()) << "Android method " << proc_name << " is not available on this device. Missing check."; return proc(std::forward<Args>(args)...); } void Reset() { proc = nullptr; } }; //------------------------------------------------------------------------------ /// @brief The table of Android procs that are resolved dynamically. /// struct ProcTable { ProcTable(); ~ProcTable(); ProcTable(const ProcTable&) = delete; ProcTable& operator=(const ProcTable&) = delete; //---------------------------------------------------------------------------- /// @brief If a valid proc table could be setup. This may fail in case of /// setup on non-Android platforms. /// /// @return `true` if valid. /// bool IsValid() const; //---------------------------------------------------------------------------- /// @brief Check if tracing in enabled in the process. This call can be /// made at any API level. /// /// @return If tracing is enabled. /// bool TraceIsEnabled() const; #define DEFINE_PROC(name, api) \ AndroidProc<decltype(name)> name = {.proc_name = #name}; FOR_EACH_ANDROID_PROC(DEFINE_PROC); #undef DEFINE_PROC private: std::vector<fml::RefPtr<fml::NativeLibrary>> libraries_; bool is_valid_ = false; }; const ProcTable& GetProcTable(); } // namespace impeller::android #endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_PROC_TABLE_H_
engine/impeller/toolkit/android/proc_table.h/0
{ "file_path": "engine/impeller/toolkit/android/proc_table.h", "repo_id": "engine", "token_count": 1694 }
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_IMPELLER_TOOLKIT_EGL_IMAGE_H_ #define FLUTTER_IMPELLER_TOOLKIT_EGL_IMAGE_H_ #include "flutter/fml/unique_object.h" #include "flutter/impeller/toolkit/egl/egl.h" namespace impeller { // Simple holder of an EGLImage and the owning EGLDisplay. struct EGLImageWithDisplay { EGLImage image = EGL_NO_IMAGE; EGLDisplay display = EGL_NO_DISPLAY; constexpr bool operator==(const EGLImageWithDisplay& other) const { return image == other.image && display == other.display; } constexpr bool operator!=(const EGLImageWithDisplay& other) const { return !(*this == other); } }; struct EGLImageWithDisplayTraits { static EGLImageWithDisplay InvalidValue() { return {EGL_NO_IMAGE, EGL_NO_DISPLAY}; } static bool IsValid(const EGLImageWithDisplay& value) { return value != InvalidValue(); } static void Free(EGLImageWithDisplay image) { eglDestroyImage(image.display, image.image); } }; using UniqueEGLImage = fml::UniqueObject<EGLImageWithDisplay, EGLImageWithDisplayTraits>; // Simple holder of an EGLImageKHR and the owning EGLDisplay. struct EGLImageKHRWithDisplay { EGLImageKHR image = EGL_NO_IMAGE_KHR; EGLDisplay display = EGL_NO_DISPLAY; constexpr bool operator==(const EGLImageKHRWithDisplay& other) const { return image == other.image && display == other.display; } constexpr bool operator!=(const EGLImageKHRWithDisplay& other) const { return !(*this == other); } }; struct EGLImageKHRWithDisplayTraits { static EGLImageKHRWithDisplay InvalidValue() { return {EGL_NO_IMAGE_KHR, EGL_NO_DISPLAY}; } static bool IsValid(const EGLImageKHRWithDisplay& value) { return value != InvalidValue(); } static void Free(EGLImageKHRWithDisplay image) { eglDestroyImageKHR(image.display, image.image); } }; using UniqueEGLImageKHR = fml::UniqueObject<EGLImageKHRWithDisplay, EGLImageKHRWithDisplayTraits>; } // namespace impeller #endif // FLUTTER_IMPELLER_TOOLKIT_EGL_IMAGE_H_
engine/impeller/toolkit/egl/image.h/0
{ "file_path": "engine/impeller/toolkit/egl/image.h", "repo_id": "engine", "token_count": 759 }
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. import("//flutter/impeller/tools/impeller.gni") impeller_component("typographer") { sources = [ "font.cc", "font.h", "font_glyph_pair.cc", "font_glyph_pair.h", "glyph.cc", "glyph.h", "glyph_atlas.cc", "glyph_atlas.h", "lazy_glyph_atlas.cc", "lazy_glyph_atlas.h", "rectangle_packer.cc", "rectangle_packer.h", "text_frame.cc", "text_frame.h", "text_run.cc", "text_run.h", "typeface.cc", "typeface.h", "typographer_context.cc", "typographer_context.h", ] public_deps = [ "../base", "../geometry", "../renderer", ] deps = [ "//flutter/fml" ] } impeller_component("typographer_unittests") { testonly = true sources = [ "typographer_unittests.cc" ] deps = [ "../playground:playground_test", "backends/skia:typographer_skia_backend", "backends/stb:typographer_stb_backend", "//flutter/display_list/testing:display_list_testing", "//flutter/third_party/txt", ] }
engine/impeller/typographer/BUILD.gn/0
{ "file_path": "engine/impeller/typographer/BUILD.gn", "repo_id": "engine", "token_count": 512 }
238
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_TYPEFACE_STB_H_ #define FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_TYPEFACE_STB_H_ #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "flutter/third_party/stb/stb_truetype.h" #include "impeller/base/backend_cast.h" #include "impeller/typographer/typeface.h" namespace impeller { class TypefaceSTB final : public Typeface, public BackendCast<TypefaceSTB, Typeface> { public: // "Typical" conversion from font Points to Pixels. // This assumes a constant pixels per em. static constexpr float kPointsToPixels = 96.0 / 72.0; explicit TypefaceSTB(std::unique_ptr<fml::Mapping> typeface_mapping); ~TypefaceSTB() override; // |Typeface| bool IsValid() const override; // |Comparable<Typeface>| std::size_t GetHash() const override; // |Comparable<Typeface>| bool IsEqual(const Typeface& other) const override; const uint8_t* GetTypefaceFile() const; const stbtt_fontinfo* GetFontInfo() const; private: std::unique_ptr<fml::Mapping> typeface_mapping_; std::unique_ptr<stbtt_fontinfo> font_info_; bool is_valid_ = false; TypefaceSTB(const TypefaceSTB&) = delete; TypefaceSTB& operator=(const TypefaceSTB&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_TYPEFACE_STB_H_
engine/impeller/typographer/backends/stb/typeface_stb.h/0
{ "file_path": "engine/impeller/typographer/backends/stb/typeface_stb.h", "repo_id": "engine", "token_count": 573 }
239
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_FRAME_H_ #define FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_FRAME_H_ #include "flutter/fml/macros.h" #include "impeller/typographer/glyph_atlas.h" #include "impeller/typographer/text_run.h" namespace impeller { //------------------------------------------------------------------------------ /// @brief Represents a collection of shaped text runs. /// /// This object is typically the entrypoint in the Impeller type /// rendering subsystem. /// class TextFrame { public: TextFrame(); TextFrame(std::vector<TextRun>& runs, Rect bounds, bool has_color); ~TextFrame(); void CollectUniqueFontGlyphPairs(FontGlyphMap& glyph_map, Scalar scale) const; static Scalar RoundScaledFontSize(Scalar scale, Scalar point_size); //---------------------------------------------------------------------------- /// @brief The conservative bounding box for this text frame. /// /// @return The bounds rectangle. If there are no glyphs in this text /// frame and empty Rectangle is returned instead. /// Rect GetBounds() const; //---------------------------------------------------------------------------- /// @brief The number of runs in this text frame. /// /// @return The run count. /// size_t GetRunCount() const; //---------------------------------------------------------------------------- /// @brief Returns a reference to all the text runs in this frame. /// /// @return The runs in this frame. /// const std::vector<TextRun>& GetRuns() const; //---------------------------------------------------------------------------- /// @brief Whether any of the glyphs of this run are potentially /// overlapping /// /// It is always safe to return true from this method. Generally, /// any large blobs of text should return true to avoid /// computationally complex calculations. This information is used /// to apply opacity peephole optimizations to text blobs. bool MaybeHasOverlapping() const; //---------------------------------------------------------------------------- /// @brief The type of atlas this run should be emplaced in. GlyphAtlas::Type GetAtlasType() const; TextFrame& operator=(TextFrame&& other) = default; TextFrame(const TextFrame& other) = default; private: std::vector<TextRun> runs_; Rect bounds_; bool has_color_ = false; }; } // namespace impeller #endif // FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_FRAME_H_
engine/impeller/typographer/text_frame.h/0
{ "file_path": "engine/impeller/typographer/text_frame.h", "repo_id": "engine", "token_count": 815 }
240
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs part of flutter_gpu; base class ShaderLibrary extends NativeFieldWrapperClass1 { static ShaderLibrary? fromAsset(String assetName) { final lib = ShaderLibrary._(); final error = lib._initializeWithAsset(assetName); if (error != null) { throw Exception("Failed to initialize ShaderLibrary: ${error}"); } return lib; } ShaderLibrary._(); // Hold a Dart-side reference to shaders in the library as they're wrapped for // the first time. This prevents the wrapper from getting prematurely // destroyed. final Map<String, Shader?> shaders_ = {}; Shader? operator [](String shaderName) { // This `flutter_gpu` library isn't always registered as part of the builtin // DartClassLibrary, and so we can't instantiate the Dart classes on the // engine side. // Providing a new wrapper to [_getShader] for wrapping the native // counterpart (if it hasn't been wrapped already) is a hack to work around // this. return shaders_.putIfAbsent( shaderName, () => _getShader(shaderName, Shader._())); } @Native<Handle Function(Handle, Handle)>( symbol: 'InternalFlutterGpu_ShaderLibrary_InitializeWithAsset') external String? _initializeWithAsset(String assetName); @Native<Handle Function(Pointer<Void>, Handle, Handle)>( symbol: 'InternalFlutterGpu_ShaderLibrary_GetShader') external Shader? _getShader(String shaderName, Shader shaderWrapper); }
engine/lib/gpu/lib/src/shader_library.dart/0
{ "file_path": "engine/lib/gpu/lib/src/shader_library.dart", "repo_id": "engine", "token_count": 510 }
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. import("//flutter/build/dart/dart.gni") source_set("io") { sources = [ "dart_io.cc", "dart_io.h", ] deps = [ "$dart_src/runtime:dart_api", "$dart_src/runtime/bin:dart_io_api", "//flutter/fml", "//flutter/third_party/tonic", ] configs += [ "$dart_src/runtime:dart_config" ] public_configs = [ "//flutter:config" ] }
engine/lib/io/BUILD.gn/0
{ "file_path": "engine/lib/io/BUILD.gn", "repo_id": "engine", "token_count": 213 }
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. #include "flutter/lib/ui/compositing/scene_builder.h" #include "flutter/flow/layers/backdrop_filter_layer.h" #include "flutter/flow/layers/clip_path_layer.h" #include "flutter/flow/layers/clip_rect_layer.h" #include "flutter/flow/layers/clip_rrect_layer.h" #include "flutter/flow/layers/color_filter_layer.h" #include "flutter/flow/layers/container_layer.h" #include "flutter/flow/layers/display_list_layer.h" #include "flutter/flow/layers/image_filter_layer.h" #include "flutter/flow/layers/layer.h" #include "flutter/flow/layers/layer_tree.h" #include "flutter/flow/layers/opacity_layer.h" #include "flutter/flow/layers/performance_overlay_layer.h" #include "flutter/flow/layers/platform_view_layer.h" #include "flutter/flow/layers/shader_mask_layer.h" #include "flutter/flow/layers/texture_layer.h" #include "flutter/flow/layers/transform_layer.h" #include "flutter/fml/build_config.h" #include "flutter/lib/ui/floating_point.h" #include "flutter/lib/ui/painting/matrix.h" #include "flutter/lib/ui/painting/shader.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder); SceneBuilder::SceneBuilder() { // Add a ContainerLayer as the root layer, so that AddLayer operations are // always valid. PushLayer(std::make_shared<flutter::ContainerLayer>()); } SceneBuilder::~SceneBuilder() = default; void SceneBuilder::pushTransform(Dart_Handle layer_handle, tonic::Float64List& matrix4, const fml::RefPtr<EngineLayer>& oldLayer) { SkM44 sk_matrix = ToSkM44(matrix4); auto layer = std::make_shared<flutter::TransformLayer>(sk_matrix); PushLayer(layer); // matrix4 has to be released before we can return another Dart object matrix4.Release(); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushOffset(Dart_Handle layer_handle, double dx, double dy, const fml::RefPtr<EngineLayer>& oldLayer) { SkMatrix sk_matrix = SkMatrix::Translate(SafeNarrow(dx), SafeNarrow(dy)); auto layer = std::make_shared<flutter::TransformLayer>(sk_matrix); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushClipRect(Dart_Handle layer_handle, double left, double right, double top, double bottom, int clipBehavior, const fml::RefPtr<EngineLayer>& oldLayer) { SkRect clipRect = SkRect::MakeLTRB(SafeNarrow(left), SafeNarrow(top), SafeNarrow(right), SafeNarrow(bottom)); flutter::Clip clip_behavior = static_cast<flutter::Clip>(clipBehavior); auto layer = std::make_shared<flutter::ClipRectLayer>(clipRect, clip_behavior); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushClipRRect(Dart_Handle layer_handle, const RRect& rrect, int clipBehavior, const fml::RefPtr<EngineLayer>& oldLayer) { flutter::Clip clip_behavior = static_cast<flutter::Clip>(clipBehavior); auto layer = std::make_shared<flutter::ClipRRectLayer>(rrect.sk_rrect, clip_behavior); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushClipPath(Dart_Handle layer_handle, const CanvasPath* path, int clipBehavior, const fml::RefPtr<EngineLayer>& oldLayer) { flutter::Clip clip_behavior = static_cast<flutter::Clip>(clipBehavior); FML_DCHECK(clip_behavior != flutter::Clip::kNone); auto layer = std::make_shared<flutter::ClipPathLayer>(path->path(), clip_behavior); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushOpacity(Dart_Handle layer_handle, int alpha, double dx, double dy, const fml::RefPtr<EngineLayer>& oldLayer) { auto layer = std::make_shared<flutter::OpacityLayer>( alpha, SkPoint::Make(SafeNarrow(dx), SafeNarrow(dy))); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushColorFilter(Dart_Handle layer_handle, const ColorFilter* color_filter, const fml::RefPtr<EngineLayer>& oldLayer) { auto layer = std::make_shared<flutter::ColorFilterLayer>(color_filter->filter()); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushImageFilter(Dart_Handle layer_handle, const ImageFilter* image_filter, double dx, double dy, const fml::RefPtr<EngineLayer>& oldLayer) { auto layer = std::make_shared<flutter::ImageFilterLayer>( image_filter->filter(), SkPoint::Make(SafeNarrow(dx), SafeNarrow(dy))); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushBackdropFilter( Dart_Handle layer_handle, ImageFilter* filter, int blendMode, const fml::RefPtr<EngineLayer>& oldLayer) { auto layer = std::make_shared<flutter::BackdropFilterLayer>( filter->filter(), static_cast<DlBlendMode>(blendMode)); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::pushShaderMask(Dart_Handle layer_handle, Shader* shader, double maskRectLeft, double maskRectRight, double maskRectTop, double maskRectBottom, int blendMode, int filterQualityIndex, const fml::RefPtr<EngineLayer>& oldLayer) { SkRect rect = SkRect::MakeLTRB(SafeNarrow(maskRectLeft), SafeNarrow(maskRectTop), SafeNarrow(maskRectRight), SafeNarrow(maskRectBottom)); auto sampling = ImageFilter::SamplingFromIndex(filterQualityIndex); auto layer = std::make_shared<flutter::ShaderMaskLayer>( shader->shader(sampling), rect, static_cast<DlBlendMode>(blendMode)); PushLayer(layer); EngineLayer::MakeRetained(layer_handle, layer); if (oldLayer && oldLayer->Layer()) { layer->AssignOldLayer(oldLayer->Layer().get()); } } void SceneBuilder::addRetained(const fml::RefPtr<EngineLayer>& retainedLayer) { AddLayer(retainedLayer->Layer()); } void SceneBuilder::pop() { PopLayer(); } void SceneBuilder::addPicture(double dx, double dy, Picture* picture, int hints) { if (!picture) { // Picture::dispose was called and it has been collected. return; } // Explicitly check for display_list, since the picture object might have // been disposed but not collected yet, but the display list is null. if (picture->display_list()) { auto layer = std::make_unique<flutter::DisplayListLayer>( SkPoint::Make(SafeNarrow(dx), SafeNarrow(dy)), picture->display_list(), !!(hints & 1), !!(hints & 2)); AddLayer(std::move(layer)); } } void SceneBuilder::addTexture(double dx, double dy, double width, double height, int64_t textureId, bool freeze, int filterQualityIndex) { auto sampling = ImageFilter::SamplingFromIndex(filterQualityIndex); auto layer = std::make_unique<flutter::TextureLayer>( SkPoint::Make(SafeNarrow(dx), SafeNarrow(dy)), SkSize::Make(SafeNarrow(width), SafeNarrow(height)), textureId, freeze, sampling); AddLayer(std::move(layer)); } void SceneBuilder::addPlatformView(double dx, double dy, double width, double height, int64_t viewId) { auto layer = std::make_unique<flutter::PlatformViewLayer>( SkPoint::Make(SafeNarrow(dx), SafeNarrow(dy)), SkSize::Make(SafeNarrow(width), SafeNarrow(height)), viewId); AddLayer(std::move(layer)); } void SceneBuilder::addPerformanceOverlay(uint64_t enabledOptions, double left, double right, double top, double bottom) { SkRect rect = SkRect::MakeLTRB(SafeNarrow(left), SafeNarrow(top), SafeNarrow(right), SafeNarrow(bottom)); auto layer = std::make_unique<flutter::PerformanceOverlayLayer>(enabledOptions); layer->set_paint_bounds(rect); AddLayer(std::move(layer)); } void SceneBuilder::setRasterizerTracingThreshold(uint32_t frameInterval) { rasterizer_tracing_threshold_ = frameInterval; } void SceneBuilder::setCheckerboardRasterCacheImages(bool checkerboard) { checkerboard_raster_cache_images_ = checkerboard; } void SceneBuilder::setCheckerboardOffscreenLayers(bool checkerboard) { checkerboard_offscreen_layers_ = checkerboard; } void SceneBuilder::build(Dart_Handle scene_handle) { FML_DCHECK(layer_stack_.size() >= 1); Scene::create( scene_handle, std::move(layer_stack_[0]), rasterizer_tracing_threshold_, checkerboard_raster_cache_images_, checkerboard_offscreen_layers_); layer_stack_.clear(); ClearDartWrapper(); // may delete this object. } void SceneBuilder::AddLayer(std::shared_ptr<Layer> layer) { FML_DCHECK(layer); if (!layer_stack_.empty()) { layer_stack_.back()->Add(std::move(layer)); } } void SceneBuilder::PushLayer(std::shared_ptr<ContainerLayer> layer) { AddLayer(layer); layer_stack_.push_back(std::move(layer)); } void SceneBuilder::PopLayer() { // We never pop the root layer, so that AddLayer operations are always valid. if (layer_stack_.size() > 1) { layer_stack_.pop_back(); } } } // namespace flutter
engine/lib/ui/compositing/scene_builder.cc/0
{ "file_path": "engine/lib/ui/compositing/scene_builder.cc", "repo_id": "engine", "token_count": 5178 }
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("//build/compiled_action.gni") import("//flutter/impeller/tools/impeller.gni") import("//flutter/testing/testing.gni") if (enable_unittests) { test_shaders = [ "127_OpFNegate.frag", "129_OpFAdd.frag", "131_OpFSub.frag", "142_OpVectorTimesScalar.frag", "143_OpMatrixTimesScalar.frag", "144_OpVectorTimesMatrix.frag", "145_OpMatrixTimesVector.frag", "146_OpMatrixTimesMatrix.frag", "148_OpDot.frag", "164_OpLogicalEqual.frag", "165_OpLogicalNotEqual.frag", "166_OpLogicalOr.frag", "167_OpLogicalAnd.frag", "168_OpLogicalNot.frag", "180_OpFOrdEqual.frag", "183_OpFUnordNotEqual.frag", "184_OpFOrdLessThan.frag", "186_OpFOrdGreaterThan.frag", "188_OpFOrdLessThanEqual.frag", "190_OpFOrdGreaterThanEqual.frag", "19_OpTypeVoid.frag", "20_OpTypeBool.frag", "21_OpTypeInt.frag", "22_OpTypeFloat.frag", "23_OpTypeVector.frag", "246_OpLoopMerge.frag", "24_OpTypeMatrix.frag", "250_OpBranchConditional.frag", "33_OpTypeFunction.frag", ] group("supported_op_shaders") { testonly = true deps = [ ":fixtures" ] } impellerc("compile_supported_op_shaders") { shaders = test_shaders shader_target_flags = [ "--sksl" ] intermediates_subdir = "iplr" sl_file_extension = "iplr" iplr = true } test_fixtures("fixtures") { deps = [ ":compile_supported_op_shaders" ] fixtures = get_target_outputs(":compile_supported_op_shaders") dest = "$root_gen_dir/flutter/lib/ui" } }
engine/lib/ui/fixtures/shaders/supported_op_shaders/BUILD.gn/0
{ "file_path": "engine/lib/ui/fixtures/shaders/supported_op_shaders/BUILD.gn", "repo_id": "engine", "token_count": 770 }
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. part of dart.ui; /// Same as [num.clamp] but optimized for a non-null [double]. /// /// This is faster because it avoids polymorphism, boxing, and special cases for /// floating point numbers. // // See also: //dev/benchmarks/microbenchmarks/lib/foundation/clamp.dart double clampDouble(double x, double min, double max) { assert(min <= max && !max.isNaN && !min.isNaN); if (x < min) { return min; } if (x > max) { return max; } if (x.isNaN) { return max; } return x; }
engine/lib/ui/math.dart/0
{ "file_path": "engine/lib/ui/math.dart", "repo_id": "engine", "token_count": 224 }
245
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_PAINTING_ENGINE_LAYER_H_ #define FLUTTER_LIB_UI_PAINTING_ENGINE_LAYER_H_ #include "flutter/flow/layers/container_layer.h" #include "flutter/lib/ui/dart_wrapper.h" namespace flutter { class EngineLayer; class EngineLayer : public RefCountedDartWrappable<EngineLayer> { DEFINE_WRAPPERTYPEINFO(); public: ~EngineLayer() override; static void MakeRetained( Dart_Handle dart_handle, const std::shared_ptr<flutter::ContainerLayer>& layer) { auto engine_layer = fml::MakeRefCounted<EngineLayer>(layer); engine_layer->AssociateWithDartWrapper(dart_handle); } void dispose(); std::shared_ptr<flutter::ContainerLayer> Layer() const { return layer_; } private: explicit EngineLayer(std::shared_ptr<flutter::ContainerLayer> layer); std::shared_ptr<flutter::ContainerLayer> layer_; FML_FRIEND_MAKE_REF_COUNTED(EngineLayer); }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_ENGINE_LAYER_H_
engine/lib/ui/painting/engine_layer.h/0
{ "file_path": "engine/lib/ui/painting/engine_layer.h", "repo_id": "engine", "token_count": 399 }
246
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_SKIA_H_ #define FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_SKIA_H_ #include "flutter/fml/macros.h" #include "flutter/lib/ui/painting/image_decoder.h" namespace flutter { class ImageDecoderSkia final : public ImageDecoder { public: ImageDecoderSkia( const TaskRunners& runners, std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner, fml::WeakPtr<IOManager> io_manager); ~ImageDecoderSkia() override; // |ImageDecoder| void Decode(fml::RefPtr<ImageDescriptor> descriptor, uint32_t target_width, uint32_t target_height, const ImageResult& result) override; static sk_sp<SkImage> ImageFromCompressedData( ImageDescriptor* descriptor, uint32_t target_width, uint32_t target_height, const fml::tracing::TraceFlow& flow); private: FML_DISALLOW_COPY_AND_ASSIGN(ImageDecoderSkia); }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_SKIA_H_
engine/lib/ui/painting/image_decoder_skia.h/0
{ "file_path": "engine/lib/ui/painting/image_decoder_skia.h", "repo_id": "engine", "token_count": 471 }
247
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_GENERATOR_H_ #define FLUTTER_LIB_UI_PAINTING_IMAGE_GENERATOR_H_ #include <optional> #include "flutter/fml/macros.h" #include "third_party/skia/include/codec/SkCodec.h" #include "third_party/skia/include/codec/SkCodecAnimation.h" #include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkImageGenerator.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkSize.h" namespace flutter { /// @brief The minimal interface necessary for defining a decoder that can be /// used for both single and multi-frame image decoding. Image /// generators can also optionally support decoding into a subscaled /// buffer. Implementers of `ImageGenerator` regularly keep internal /// state which is not thread safe, and so aliasing and parallel access /// should never be done with `ImageGenerator`s. /// @see `ImageGenerator::GetScaledDimensions` class ImageGenerator { public: /// Frame count value to denote infinite looping. const static unsigned int kInfinitePlayCount = std::numeric_limits<unsigned int>::max(); /// @brief Info about a single frame in the context of a multi-frame image, /// useful for animation and blending. struct FrameInfo { /// The frame index of the frame that, if any, this frame needs to be /// blended with. std::optional<unsigned int> required_frame; /// Number of milliseconds to show this frame. 0 means only show it for one /// frame. unsigned int duration; /// How this frame should be modified before decoding the next one. SkCodecAnimation::DisposalMethod disposal_method; /// The region of the frame that is affected by the disposal method. std::optional<SkIRect> disposal_rect; /// How this frame should be blended with the previous frame. SkCodecAnimation::Blend blend_mode; }; virtual ~ImageGenerator(); /// @brief Returns basic information about the contents of the encoded /// image. This information can almost always be collected by just /// interpreting the header of a decoded image. /// @return Size and color information describing the image. /// @note This method is executed on the UI thread and used for layout /// purposes by the framework, and so this method should not perform /// long synchronous tasks. virtual const SkImageInfo& GetInfo() = 0; /// @brief Get the number of frames that the encoded image stores. This /// method is always expected to be called before `GetFrameInfo`, as /// the underlying image decoder may interpret frame information that /// is then used when calling `GetFrameInfo`. /// @return The number of frames that the encoded image stores. This will /// always be 1 for single-frame images. virtual unsigned int GetFrameCount() const = 0; /// @brief The number of times an animated image should play through before /// playback stops. /// @return If this image is animated, the number of times the animation /// should play through is returned, otherwise it'll just return 1. /// If the animation should loop forever, `kInfinitePlayCount` is /// returned. virtual unsigned int GetPlayCount() const = 0; /// @brief Get information about a single frame in the context of a /// multi-frame image, useful for animation and frame blending. /// This method should only ever be called after `GetFrameCount` /// has been called. This information is nonsensical for /// single-frame images. /// @param[in] frame_index The index of the frame to get information about. /// @return Information about the given frame. If the image is /// single-frame, a default result is returned. /// @see `GetFrameCount` virtual const FrameInfo GetFrameInfo(unsigned int frame_index) = 0; /// @brief Given a scale value, find the closest image size that can be /// used for efficiently decoding the image. If subpixel image /// decoding is not supported by the decoder, this method should /// just return the original image size. /// @param[in] scale The desired scale factor of the image for decoding. /// @return The closest image size that can be used for efficiently /// decoding the image. /// @note This method is called prior to `GetPixels` in order to query /// for supported sizes. /// @see `GetPixels` virtual SkISize GetScaledDimensions(float scale) = 0; /// @brief Decode the image into a given buffer. This method is currently /// always used for sub-pixel image decoding. For full-sized still /// images, `GetImage` is always attempted first. /// @param[in] info The desired size and color info of the decoded /// image to be returned. The implementation of /// `GetScaledDimensions` determines which sizes are /// supported by the image decoder. /// @param[in] pixels The location where the raw decoded image data /// should be written. /// @param[in] row_bytes The total number of bytes that should make up a /// single row of decoded image data /// (i.e. width * bytes_per_pixel). /// @param[in] frame_index Which frame to decode. This is only useful for /// multi-frame images. /// @param[in] prior_frame Optional frame index parameter for multi-frame /// images which specifies the previous frame that /// should be use for blending. This hints to the /// decoder that it should use a previously cached /// frame instead of decoding dependency frame(s). /// If an empty value is supplied, the decoder should /// decode any necessary frames first. /// @return True if the image was successfully decoded. /// @note This method performs potentially long synchronous work, and so /// it should never be executed on the UI thread. Image decoders /// do not require GPU acceleration, and so threads without a GPU /// context may also be used. /// @see `GetScaledDimensions` virtual bool GetPixels( const SkImageInfo& info, void* pixels, size_t row_bytes, unsigned int frame_index = 0, std::optional<unsigned int> prior_frame = std::nullopt) = 0; /// @brief Creates an `SkImage` based on the current `ImageInfo` of this /// `ImageGenerator`. /// @return A new `SkImage` containing the decoded image data. sk_sp<SkImage> GetImage(); }; class BuiltinSkiaImageGenerator : public ImageGenerator { public: ~BuiltinSkiaImageGenerator(); explicit BuiltinSkiaImageGenerator( std::unique_ptr<SkImageGenerator> generator); // |ImageGenerator| const SkImageInfo& GetInfo() override; // |ImageGenerator| unsigned int GetFrameCount() const override; // |ImageGenerator| unsigned int GetPlayCount() const override; // |ImageGenerator| const ImageGenerator::FrameInfo GetFrameInfo( unsigned int frame_index) override; // |ImageGenerator| SkISize GetScaledDimensions(float desired_scale) override; // |ImageGenerator| bool GetPixels( const SkImageInfo& info, void* pixels, size_t row_bytes, unsigned int frame_index = 0, std::optional<unsigned int> prior_frame = std::nullopt) override; static std::unique_ptr<ImageGenerator> MakeFromGenerator( std::unique_ptr<SkImageGenerator> generator); private: FML_DISALLOW_COPY_ASSIGN_AND_MOVE(BuiltinSkiaImageGenerator); std::unique_ptr<SkImageGenerator> generator_; }; class BuiltinSkiaCodecImageGenerator : public ImageGenerator { public: ~BuiltinSkiaCodecImageGenerator(); explicit BuiltinSkiaCodecImageGenerator(std::unique_ptr<SkCodec> codec); explicit BuiltinSkiaCodecImageGenerator(sk_sp<SkData> buffer); // |ImageGenerator| const SkImageInfo& GetInfo() override; // |ImageGenerator| unsigned int GetFrameCount() const override; // |ImageGenerator| unsigned int GetPlayCount() const override; // |ImageGenerator| const ImageGenerator::FrameInfo GetFrameInfo( unsigned int frame_index) override; // |ImageGenerator| SkISize GetScaledDimensions(float desired_scale) override; // |ImageGenerator| bool GetPixels( const SkImageInfo& info, void* pixels, size_t row_bytes, unsigned int frame_index = 0, std::optional<unsigned int> prior_frame = std::nullopt) override; static std::unique_ptr<ImageGenerator> MakeFromData(sk_sp<SkData> data); private: FML_DISALLOW_COPY_ASSIGN_AND_MOVE(BuiltinSkiaCodecImageGenerator); std::unique_ptr<SkCodec> codec_; SkImageInfo image_info_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_IMAGE_GENERATOR_H_
engine/lib/ui/painting/image_generator.h/0
{ "file_path": "engine/lib/ui/painting/image_generator.h", "repo_id": "engine", "token_count": 3310 }
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. #include "flutter/lib/ui/painting/paint.h" #include "flutter/shell/common/shell_test.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { TEST_F(ShellTest, ConvertPaintToDlPaint) { auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); DlPaint dl_paint; auto nativeToDlPaint = [message_latch, &dl_paint](Dart_NativeArguments args) { Dart_Handle dart_paint = Dart_GetNativeArgument(args, 0); Dart_Handle paint_objects = Dart_GetField(dart_paint, tonic::ToDart("_objects")); Dart_Handle paint_data = Dart_GetField(dart_paint, tonic::ToDart("_data")); Paint ui_paint(paint_objects, paint_data); ui_paint.toDlPaint(dl_paint); message_latch->Signal(); }; Settings settings = CreateSettingsForFixture(); TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform CreateNewThread(), // raster CreateNewThread(), // ui CreateNewThread() // io ); AddNativeCallback("ConvertPaintToDlPaint", CREATE_NATIVE_ENTRY(nativeToDlPaint)); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("convertPaintToDlPaint"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); DestroyShell(std::move(shell), task_runners); ASSERT_EQ(dl_paint.getBlendMode(), DlBlendMode::kModulate); ASSERT_EQ(static_cast<uint32_t>(dl_paint.getColor().argb()), 0x11223344u); ASSERT_EQ(*dl_paint.getColorFilter(), DlBlendColorFilter(DlColor(0x55667788), DlBlendMode::kXor)); ASSERT_EQ(*dl_paint.getMaskFilter(), DlBlurMaskFilter(DlBlurStyle::kInner, 0.75)); ASSERT_EQ(dl_paint.getDrawStyle(), DlDrawStyle::kStroke); } } // namespace testing } // namespace flutter
engine/lib/ui/painting/paint_unittests.cc/0
{ "file_path": "engine/lib/ui/painting/paint_unittests.cc", "repo_id": "engine", "token_count": 959 }
249
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/painting/shader.h" #include "flutter/lib/ui/ui_dart_state.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, Shader); Shader::~Shader() = default; } // namespace flutter
engine/lib/ui/painting/shader.cc/0
{ "file_path": "engine/lib/ui/painting/shader.cc", "repo_id": "engine", "token_count": 126 }
250
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/semantics/semantics_node.h" #include <cstring> namespace flutter { constexpr int32_t kMinPlatformViewId = -1; SemanticsNode::SemanticsNode() = default; SemanticsNode::SemanticsNode(const SemanticsNode& other) = default; SemanticsNode::~SemanticsNode() = default; bool SemanticsNode::HasAction(SemanticsAction action) const { return (actions & static_cast<int32_t>(action)) != 0; } bool SemanticsNode::HasFlag(SemanticsFlags flag) const { return (flags & static_cast<int32_t>(flag)) != 0; } bool SemanticsNode::IsPlatformViewNode() const { return platformViewId > kMinPlatformViewId; } } // namespace flutter
engine/lib/ui/semantics/semantics_node.cc/0
{ "file_path": "engine/lib/ui/semantics/semantics_node.cc", "repo_id": "engine", "token_count": 257 }
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. #include "flutter/lib/ui/text/paragraph.h" #include "flutter/common/settings.h" #include "flutter/common/task_runners.h" #include "flutter/fml/logging.h" #include "flutter/fml/task_runner.h" #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/skia/modules/skparagraph/include/DartTypes.h" #include "third_party/skia/modules/skparagraph/include/Paragraph.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" #include "third_party/tonic/logging/dart_invoke.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, Paragraph); Paragraph::Paragraph(std::unique_ptr<txt::Paragraph> paragraph) : m_paragraph_(std::move(paragraph)) {} Paragraph::~Paragraph() = default; double Paragraph::width() { return m_paragraph_->GetMaxWidth(); } double Paragraph::height() { return m_paragraph_->GetHeight(); } double Paragraph::longestLine() { return m_paragraph_->GetLongestLine(); } double Paragraph::minIntrinsicWidth() { return m_paragraph_->GetMinIntrinsicWidth(); } double Paragraph::maxIntrinsicWidth() { return m_paragraph_->GetMaxIntrinsicWidth(); } double Paragraph::alphabeticBaseline() { return m_paragraph_->GetAlphabeticBaseline(); } double Paragraph::ideographicBaseline() { return m_paragraph_->GetIdeographicBaseline(); } bool Paragraph::didExceedMaxLines() { return m_paragraph_->DidExceedMaxLines(); } void Paragraph::layout(double width) { m_paragraph_->Layout(width); } void Paragraph::paint(Canvas* canvas, double x, double y) { if (!m_paragraph_ || !canvas) { // disposed. return; } DisplayListBuilder* builder = canvas->builder(); if (builder) { m_paragraph_->Paint(builder, x, y); } } static tonic::Float32List EncodeTextBoxes( const std::vector<txt::Paragraph::TextBox>& boxes) { // Layout: // First value is the number of values. // Then there are boxes.size() groups of 5 which are LTRBD, where D is the // text direction index. tonic::Float32List result( Dart_NewTypedData(Dart_TypedData_kFloat32, boxes.size() * 5)); uint64_t position = 0; for (uint64_t i = 0; i < boxes.size(); i++) { const txt::Paragraph::TextBox& box = boxes[i]; result[position++] = box.rect.fLeft; result[position++] = box.rect.fTop; result[position++] = box.rect.fRight; result[position++] = box.rect.fBottom; result[position++] = static_cast<float>(box.direction); } return result; } tonic::Float32List Paragraph::getRectsForRange(unsigned start, unsigned end, unsigned boxHeightStyle, unsigned boxWidthStyle) { std::vector<txt::Paragraph::TextBox> boxes = m_paragraph_->GetRectsForRange( start, end, static_cast<txt::Paragraph::RectHeightStyle>(boxHeightStyle), static_cast<txt::Paragraph::RectWidthStyle>(boxWidthStyle)); return EncodeTextBoxes(boxes); } tonic::Float32List Paragraph::getRectsForPlaceholders() { std::vector<txt::Paragraph::TextBox> boxes = m_paragraph_->GetRectsForPlaceholders(); return EncodeTextBoxes(boxes); } Dart_Handle Paragraph::getPositionForOffset(double dx, double dy) { txt::Paragraph::PositionWithAffinity pos = m_paragraph_->GetGlyphPositionAtCoordinate(dx, dy); std::vector<size_t> result = { pos.position, // size_t already static_cast<size_t>(pos.affinity) // affinity (enum) }; return tonic::DartConverter<decltype(result)>::ToDart(result); } Dart_Handle glyphInfoFrom( Dart_Handle constructor, const skia::textlayout::Paragraph::GlyphInfo& glyphInfo) { std::array<Dart_Handle, 7> arguments = { Dart_NewDouble(glyphInfo.fGraphemeLayoutBounds.fLeft), Dart_NewDouble(glyphInfo.fGraphemeLayoutBounds.fTop), Dart_NewDouble(glyphInfo.fGraphemeLayoutBounds.fRight), Dart_NewDouble(glyphInfo.fGraphemeLayoutBounds.fBottom), Dart_NewInteger(glyphInfo.fGraphemeClusterTextRange.start), Dart_NewInteger(glyphInfo.fGraphemeClusterTextRange.end), Dart_NewBoolean(glyphInfo.fDirection == skia::textlayout::TextDirection::kLtr), }; return Dart_InvokeClosure(constructor, arguments.size(), arguments.data()); } Dart_Handle Paragraph::getGlyphInfoAt(unsigned utf16Offset, Dart_Handle constructor) const { skia::textlayout::Paragraph::GlyphInfo glyphInfo; const bool found = m_paragraph_->GetGlyphInfoAt(utf16Offset, &glyphInfo); if (!found) { return Dart_Null(); } Dart_Handle handle = glyphInfoFrom(constructor, glyphInfo); tonic::CheckAndHandleError(handle); return handle; } Dart_Handle Paragraph::getClosestGlyphInfo(double dx, double dy, Dart_Handle constructor) const { skia::textlayout::Paragraph::GlyphInfo glyphInfo; const bool found = m_paragraph_->GetClosestGlyphInfoAtCoordinate(dx, dy, &glyphInfo); if (!found) { return Dart_Null(); } Dart_Handle handle = glyphInfoFrom(constructor, glyphInfo); tonic::CheckAndHandleError(handle); return handle; } Dart_Handle Paragraph::getWordBoundary(unsigned utf16Offset) { txt::Paragraph::Range<size_t> point = m_paragraph_->GetWordBoundary(utf16Offset); std::vector<size_t> result = {point.start, point.end}; return tonic::DartConverter<decltype(result)>::ToDart(result); } Dart_Handle Paragraph::getLineBoundary(unsigned utf16Offset) { std::vector<txt::LineMetrics> metrics = m_paragraph_->GetLineMetrics(); int line_start = -1; int line_end = -1; for (txt::LineMetrics& line : metrics) { if (utf16Offset >= line.start_index && utf16Offset <= line.end_index) { line_start = line.start_index; line_end = line.end_index; break; } } std::vector<int> result = {line_start, line_end}; return tonic::DartConverter<decltype(result)>::ToDart(result); } tonic::Float64List Paragraph::computeLineMetrics() const { std::vector<txt::LineMetrics> metrics = m_paragraph_->GetLineMetrics(); // Layout: // boxes.size() groups of 9 which are the line metrics // properties tonic::Float64List result( Dart_NewTypedData(Dart_TypedData_kFloat64, metrics.size() * 9)); uint64_t position = 0; for (uint64_t i = 0; i < metrics.size(); i++) { const txt::LineMetrics& line = metrics[i]; result[position++] = static_cast<double>(line.hard_break); result[position++] = line.ascent; result[position++] = line.descent; result[position++] = line.unscaled_ascent; // We add then round to get the height. The // definition of height here is different // than the one in LibTxt. result[position++] = round(line.ascent + line.descent); result[position++] = line.width; result[position++] = line.left; result[position++] = line.baseline; result[position++] = static_cast<double>(line.line_number); } return result; } Dart_Handle Paragraph::getLineMetricsAt(int lineNumber, Dart_Handle constructor) const { skia::textlayout::LineMetrics line; const bool found = m_paragraph_->GetLineMetricsAt(lineNumber, &line); if (!found) { return Dart_Null(); } std::array<Dart_Handle, 9> arguments = { Dart_NewBoolean(line.fHardBreak), Dart_NewDouble(line.fAscent), Dart_NewDouble(line.fDescent), Dart_NewDouble(line.fUnscaledAscent), // We add then round to get the height. The // definition of height here is different // than the one in LibTxt. Dart_NewDouble(round(line.fAscent + line.fDescent)), Dart_NewDouble(line.fWidth), Dart_NewDouble(line.fLeft), Dart_NewDouble(line.fBaseline), Dart_NewInteger(line.fLineNumber), }; Dart_Handle handle = Dart_InvokeClosure(constructor, arguments.size(), arguments.data()); tonic::CheckAndHandleError(handle); return handle; } size_t Paragraph::getNumberOfLines() const { return m_paragraph_->GetNumberOfLines(); } int Paragraph::getLineNumberAt(size_t utf16Offset) const { return m_paragraph_->GetLineNumberAt(utf16Offset); } void Paragraph::dispose() { m_paragraph_.reset(); ClearDartWrapper(); } } // namespace flutter
engine/lib/ui/text/paragraph.cc/0
{ "file_path": "engine/lib/ui/text/paragraph.cc", "repo_id": "engine", "token_count": 3343 }
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. #ifndef FLUTTER_LIB_UI_WINDOW_PLATFORM_CONFIGURATION_H_ #define FLUTTER_LIB_UI_WINDOW_PLATFORM_CONFIGURATION_H_ #include <functional> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "flutter/assets/asset_manager.h" #include "flutter/fml/time/time_point.h" #include "flutter/lib/ui/semantics/semantics_update.h" #include "flutter/lib/ui/window/platform_message_response.h" #include "flutter/lib/ui/window/pointer_data_packet.h" #include "flutter/lib/ui/window/viewport_metrics.h" #include "flutter/shell/common/display.h" #include "third_party/tonic/dart_persistent_value.h" #include "third_party/tonic/typed_data/dart_byte_data.h" namespace flutter { class FontCollection; class PlatformMessage; class PlatformMessageHandler; class PlatformIsolateManager; class Scene; //-------------------------------------------------------------------------- /// @brief An enum for defining the different kinds of accessibility features /// that can be enabled by the platform. /// /// Must match the `AccessibilityFeatures` class in framework. enum class AccessibilityFeatureFlag : int32_t { kAccessibleNavigation = 1 << 0, kInvertColors = 1 << 1, kDisableAnimations = 1 << 2, kBoldText = 1 << 3, kReduceMotion = 1 << 4, kHighContrast = 1 << 5, kOnOffSwitchLabels = 1 << 6, }; //-------------------------------------------------------------------------- /// @brief A client interface that the `RuntimeController` uses to define /// handlers for `PlatformConfiguration` requests. /// /// @see `PlatformConfiguration` /// class PlatformConfigurationClient { public: //-------------------------------------------------------------------------- /// @brief The route or path that the embedder requested when the /// application was launched. /// /// This will be the string "`/`" if no particular route was /// requested. /// virtual std::string DefaultRouteName() = 0; //-------------------------------------------------------------------------- /// @brief Requests that, at the next appropriate opportunity, a new /// frame be scheduled for rendering. /// virtual void ScheduleFrame() = 0; //-------------------------------------------------------------------------- /// @brief Called when a warm up frame has ended. /// /// For more introduction, see `Animator::EndWarmUpFrame`. /// virtual void EndWarmUpFrame() = 0; //-------------------------------------------------------------------------- /// @brief Updates the client's rendering on the GPU with the newly /// provided Scene. /// virtual void Render(int64_t view_id, Scene* scene, double width, double height) = 0; //-------------------------------------------------------------------------- /// @brief Receives an updated semantics tree from the Framework. /// /// @param[in] update The updated semantic tree to apply. /// virtual void UpdateSemantics(SemanticsUpdate* update) = 0; //-------------------------------------------------------------------------- /// @brief When the Flutter application has a message to send to the /// underlying platform, the message needs to be forwarded to /// the platform on the appropriate thread (via the platform /// task runner). The PlatformConfiguration delegates this task /// to the engine via this method. /// /// @see `PlatformView::HandlePlatformMessage` /// /// @param[in] message The message from the Flutter application to send to /// the underlying platform. /// virtual void HandlePlatformMessage( std::unique_ptr<PlatformMessage> message) = 0; //-------------------------------------------------------------------------- /// @brief Returns the current collection of fonts available on the /// platform. /// /// This function reads an XML file and makes font families and /// collections of them. MinikinFontForTest is used for FontFamily /// creation. virtual FontCollection& GetFontCollection() = 0; //-------------------------------------------------------------------------- /// @brief Returns the current collection of assets available on the /// platform. virtual std::shared_ptr<AssetManager> GetAssetManager() = 0; //-------------------------------------------------------------------------- /// @brief Notifies this client of the name of the root isolate and its /// port when that isolate is launched, restarted (in the /// cold-restart scenario) or the application itself updates the /// name of the root isolate (via `Window.setIsolateDebugName` /// in `window.dart`). The name of the isolate is meaningless to /// the engine but is used in instrumentation and tooling. /// Currently, this information is to update the service /// protocol list of available root isolates running in the VM /// and their names so that the appropriate isolate can be /// selected in the tools for debugging and instrumentation. /// /// @param[in] isolate_name The isolate name /// @param[in] isolate_port The isolate port /// virtual void UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) = 0; //-------------------------------------------------------------------------- /// @brief Notifies this client that the application has an opinion about /// whether its frame timings need to be reported backed to it. /// Due to the asynchronous nature of rendering in Flutter, it is /// not possible for the application to determine the total time /// it took to render a specific frame. While the layer-tree is /// constructed on the UI thread, it needs to be rendering on the /// raster thread. Dart code cannot execute on this thread. So any /// instrumentation about the frame times gathered on this thread /// needs to be aggregated and sent back to the UI thread for /// processing in Dart. /// /// When the application indicates that frame times need to be /// reported, it collects this information till a specified number /// of data points are gathered. Then this information is sent /// back to Dart code via `Engine::ReportTimings`. /// /// This option is engine counterpart of the /// `Window._setNeedsReportTimings` in `window.dart`. /// /// @param[in] needs_reporting If reporting information should be collected /// and send back to Dart. /// virtual void SetNeedsReportTimings(bool value) = 0; //-------------------------------------------------------------------------- /// @brief The embedder can specify data that the isolate can request /// synchronously on launch. This accessor fetches that data. /// /// This data is persistent for the duration of the Flutter /// application and is available even after isolate restarts. /// Because of this lifecycle, the size of this data must be kept /// to a minimum. /// /// For asynchronous communication between the embedder and /// isolate, a platform channel may be used. /// /// @return A map of the isolate data that the framework can request upon /// launch. /// virtual std::shared_ptr<const fml::Mapping> GetPersistentIsolateData() = 0; //-------------------------------------------------------------------------- /// @brief Directly invokes platform-specific APIs to compute the /// locale the platform would have natively resolved to. /// /// @param[in] supported_locale_data The vector of strings that represents /// the locales supported by the app. /// Each locale consists of three /// strings: languageCode, countryCode, /// and scriptCode in that order. /// /// @return A vector of 3 strings languageCode, countryCode, and /// scriptCode that represents the locale selected by the /// platform. Empty strings mean the value was unassigned. Empty /// vector represents a null locale. /// virtual std::unique_ptr<std::vector<std::string>> ComputePlatformResolvedLocale( const std::vector<std::string>& supported_locale_data) = 0; //-------------------------------------------------------------------------- /// @brief Invoked when the Dart VM requests that a deferred library /// be loaded. Notifies the engine that the deferred library /// identified by the specified loading unit id should be /// downloaded and loaded into the Dart VM via /// `LoadDartDeferredLibrary` /// /// Upon encountering errors or otherwise failing to load a /// loading unit with the specified id, the failure should be /// directly reported to dart by calling /// `LoadDartDeferredLibraryFailure` to ensure the waiting dart /// future completes with an error. /// /// @param[in] loading_unit_id The unique id of the deferred library's /// loading unit. This id is to be passed /// back into LoadDartDeferredLibrary /// in order to identify which deferred /// library to load. /// virtual void RequestDartDeferredLibrary(intptr_t loading_unit_id) = 0; //-------------------------------------------------------------------------- /// @brief Invoked when a listener is registered on a platform channel. /// /// @param[in] name The name of the platform channel to which a /// listener has been registered or cleared. /// /// @param[in] listening Whether the listener has been set (true) or /// cleared (false). /// virtual void SendChannelUpdate(std::string name, bool listening) = 0; //-------------------------------------------------------------------------- /// @brief Synchronously invokes platform-specific APIs to apply the /// system text scaling on the given unscaled font size. /// /// Platforms that support this feature (currently it's only /// implemented for Android SDK level 34+) will send a valid /// configuration_id to potential callers, before this method can /// be called. /// /// @param[in] unscaled_font_size The unscaled font size specified by the /// app developer. The value is in logical /// pixels, and is guaranteed to be finite and /// non-negative. /// @param[in] configuration_id The unique id of the configuration to use /// for computing the scaled font size. /// /// @return The scaled font size in logical pixels, or -1 if the given /// configuration_id did not match a valid configuration. /// virtual double GetScaledFontSize(double unscaled_font_size, int configuration_id) const = 0; virtual std::shared_ptr<PlatformIsolateManager> GetPlatformIsolateManager() = 0; protected: virtual ~PlatformConfigurationClient(); }; //---------------------------------------------------------------------------- /// @brief A class for holding and distributing platform-level information /// to and from the Dart code in Flutter's framework. /// /// It handles communication between the engine and the framework, /// and owns the main window. /// /// It communicates with the RuntimeController through the use of a /// PlatformConfigurationClient interface, which the /// RuntimeController defines. /// class PlatformConfiguration final { public: //---------------------------------------------------------------------------- /// @brief Creates a new PlatformConfiguration, typically created by the /// RuntimeController. /// /// @param[in] client The `PlatformConfigurationClient` to be injected into /// the PlatformConfiguration. This client is used to /// forward requests to the RuntimeController. /// explicit PlatformConfiguration(PlatformConfigurationClient* client); // PlatformConfiguration is not copyable. PlatformConfiguration(const PlatformConfiguration&) = delete; PlatformConfiguration& operator=(const PlatformConfiguration&) = delete; ~PlatformConfiguration(); //---------------------------------------------------------------------------- /// @brief Access to the platform configuration client (which typically /// is implemented by the RuntimeController). /// /// @return Returns the client used to construct this /// PlatformConfiguration. /// PlatformConfigurationClient* client() const { return client_; } //---------------------------------------------------------------------------- /// @brief Called by the RuntimeController once it has created the root /// isolate, so that the PlatformController can get a handle to /// the 'dart:ui' library. /// /// It uses the handle to call the hooks in hooks.dart. /// void DidCreateIsolate(); //---------------------------------------------------------------------------- /// @brief Notify the framework that a new view is available. /// /// A view must be added before other methods can refer to it, /// including the implicit view. Adding a view that already exists /// triggers an assertion. /// /// @param[in] view_id The ID of the new view. /// @param[in] viewport_metrics The initial viewport metrics for the view. /// void AddView(int64_t view_id, const ViewportMetrics& view_metrics); //---------------------------------------------------------------------------- /// @brief Notify the framework that a view is no longer available. /// /// Removing a view that does not exist triggers an assertion. /// /// The implicit view (kFlutterImplicitViewId) should never be /// removed. Doing so triggers an assertion. /// /// @param[in] view_id The ID of the view. /// /// @return Whether the view was removed. /// bool RemoveView(int64_t view_id); //---------------------------------------------------------------------------- /// @brief Update the view metrics for the specified view. /// /// If the view is not found, silently return false. /// /// @param[in] view_id The ID of the view. /// @param[in] metrics The new metrics of the view. /// /// @return Whether the view is found. /// bool UpdateViewMetrics(int64_t view_id, const ViewportMetrics& metrics); //---------------------------------------------------------------------------- /// @brief Update the specified display data in the framework. /// /// @param[in] displays The display data to send to Dart. /// void UpdateDisplays(const std::vector<DisplayData>& displays); //---------------------------------------------------------------------------- /// @brief Update the specified locale data in the framework. /// /// @param[in] locale_data The locale data. This should consist of groups of /// 4 strings, each group representing a single locale. /// void UpdateLocales(const std::vector<std::string>& locales); //---------------------------------------------------------------------------- /// @brief Update the user settings data in the framework. /// /// @param[in] data The user settings data. /// void UpdateUserSettingsData(const std::string& data); //---------------------------------------------------------------------------- /// @brief Updates the lifecycle state data in the framework. /// /// @param[in] data The lifecycle state data. /// void UpdateInitialLifecycleState(const std::string& data); //---------------------------------------------------------------------------- /// @brief Notifies the PlatformConfiguration that the embedder has /// expressed an opinion about whether the accessibility tree /// should be generated or not. This call originates in the /// platform view and is forwarded to the PlatformConfiguration /// here by the engine. /// /// @param[in] enabled Whether the accessibility tree is enabled or /// disabled. /// void UpdateSemanticsEnabled(bool enabled); //---------------------------------------------------------------------------- /// @brief Forward the preference of accessibility features that must be /// enabled in the semantics tree to the framwork. /// /// @param[in] flags The accessibility features that must be generated in /// the semantics tree. /// void UpdateAccessibilityFeatures(int32_t flags); //---------------------------------------------------------------------------- /// @brief Notifies the PlatformConfiguration that the client has sent /// it a message. This call originates in the platform view and /// has been forwarded through the engine to here. /// /// @param[in] message The message sent from the embedder to the Dart /// application. /// void DispatchPlatformMessage(std::unique_ptr<PlatformMessage> message); //---------------------------------------------------------------------------- /// @brief Notifies the PlatformConfiguration that the client has sent /// it pointer events. This call originates in the platform view /// and has been forwarded through the engine to here. /// /// @param[in] packet The pointer event(s) serialized into a packet. /// void DispatchPointerDataPacket(const PointerDataPacket& packet); //---------------------------------------------------------------------------- /// @brief Notifies the framework that the embedder encountered an /// accessibility related action on the specified node. This call /// originates on the platform view and has been forwarded to the /// platform configuration here by the engine. /// /// @param[in] node_id The identifier of the accessibility node. /// @param[in] action The accessibility related action performed on the /// node of the specified ID. /// @param[in] args Optional data that applies to the specified action. /// void DispatchSemanticsAction(int32_t node_id, SemanticsAction action, fml::MallocMapping args); //---------------------------------------------------------------------------- /// @brief Notifies the framework that it is time to begin working on a /// new frame previously scheduled via a call to /// `PlatformConfigurationClient::ScheduleFrame`. This call /// originates in the animator. /// /// The frame time given as the argument indicates the point at /// which the current frame interval began. It is very slightly /// (because of scheduling overhead) in the past. If a new layer /// tree is not produced and given to the raster task runner /// within one frame interval from this point, the Flutter /// application will jank. /// /// This method calls the `::_beginFrame` method in `hooks.dart`. /// /// @param[in] frame_time The point at which the current frame interval /// began. May be used by animation interpolators, /// physics simulations, etc.. /// /// @param[in] frame_number The frame number recorded by the animator. Used /// by the framework to associate frame specific /// debug information with frame timings and timeline /// events. /// void BeginFrame(fml::TimePoint frame_time, uint64_t frame_number); //---------------------------------------------------------------------------- /// @brief Dart code cannot fully measure the time it takes for a /// specific frame to be rendered. This is because Dart code only /// runs on the UI task runner. That is only a small part of the /// overall frame workload. The raster task runner frame workload /// is executed on a thread where Dart code cannot run (and hence /// instrument). Besides, due to the pipelined nature of rendering /// in Flutter, there may be multiple frame workloads being /// processed at any given time. However, for non-Timeline based /// profiling, it is useful for trace collection and processing to /// happen in Dart. To do this, the raster task runner frame /// workloads need to be instrumented separately. After a set /// number of these profiles have been gathered, they need to be /// reported back to Dart code. The engine reports this extra /// instrumentation information back to the framework by invoking /// this method at predefined intervals. /// /// @see `FrameTiming` /// /// @param[in] timings Collection of `FrameTiming::kStatisticsCount` * 'n' /// values for `n` frames whose timings have not been /// reported yet. Many of the values are timestamps, but /// a collection of integers is reported here for easier /// conversions to Dart objects. The timestamps are /// measured against the system monotonic clock measured /// in microseconds. /// void ReportTimings(std::vector<int64_t> timings); //---------------------------------------------------------------------------- /// @brief Retrieves the viewport metrics with the given ID managed by /// the `PlatformConfiguration`. /// /// @param[in] view_id The id of the view's viewport metrics to return. /// /// @return a pointer to the ViewportMetrics. Returns nullptr if the ID is /// not found. /// const ViewportMetrics* GetMetrics(int view_id); //---------------------------------------------------------------------------- /// @brief Responds to a previous platform message to the engine from the /// framework. /// /// @param[in] response_id The unique id that identifies the original platform /// message to respond to. /// @param[in] data The data to send back in the response. /// void CompletePlatformMessageResponse(int response_id, std::vector<uint8_t> data); //---------------------------------------------------------------------------- /// @brief Responds to a previous platform message to the engine from the /// framework with an empty response. /// /// @param[in] response_id The unique id that identifies the original platform /// message to respond to. /// void CompletePlatformMessageEmptyResponse(int response_id); Dart_Handle on_error() { return on_error_.Get(); } private: PlatformConfigurationClient* client_; tonic::DartPersistentValue on_error_; tonic::DartPersistentValue add_view_; tonic::DartPersistentValue remove_view_; tonic::DartPersistentValue update_window_metrics_; tonic::DartPersistentValue update_displays_; tonic::DartPersistentValue update_locales_; tonic::DartPersistentValue update_user_settings_data_; tonic::DartPersistentValue update_initial_lifecycle_state_; tonic::DartPersistentValue update_semantics_enabled_; tonic::DartPersistentValue update_accessibility_features_; tonic::DartPersistentValue dispatch_platform_message_; tonic::DartPersistentValue dispatch_pointer_data_packet_; tonic::DartPersistentValue dispatch_semantics_action_; tonic::DartPersistentValue begin_frame_; tonic::DartPersistentValue draw_frame_; tonic::DartPersistentValue report_timings_; // All current views' view metrics mapped from view IDs. std::unordered_map<int64_t, ViewportMetrics> metrics_; // ID starts at 1 because an ID of 0 indicates that no response is expected. int next_response_id_ = 1; std::unordered_map<int, fml::RefPtr<PlatformMessageResponse>> pending_responses_; }; //---------------------------------------------------------------------------- /// An inteface that the result of `Dart_CurrentIsolateGroupData` should /// implement for registering background isolates to work. class PlatformMessageHandlerStorage { public: virtual ~PlatformMessageHandlerStorage() = default; virtual void SetPlatformMessageHandler( int64_t root_isolate_token, std::weak_ptr<PlatformMessageHandler> handler) = 0; virtual std::weak_ptr<PlatformMessageHandler> GetPlatformMessageHandler( int64_t root_isolate_token) const = 0; }; //---------------------------------------------------------------------------- // API exposed as FFI calls in Dart. // // These are probably not supposed to be called directly, and should instead // be called through their sibling API in `PlatformConfiguration` or // `PlatformConfigurationClient`. // // These are intentionally undocumented. Refer instead to the sibling methods // above. //---------------------------------------------------------------------------- class PlatformConfigurationNativeApi { public: static std::string DefaultRouteName(); static void ScheduleFrame(); static void EndWarmUpFrame(); static void Render(int64_t view_id, Scene* scene, double width, double height); static void UpdateSemantics(SemanticsUpdate* update); static void SetNeedsReportTimings(bool value); static Dart_Handle GetPersistentIsolateData(); static Dart_Handle ComputePlatformResolvedLocale( Dart_Handle supportedLocalesHandle); static void SetIsolateDebugName(const std::string& name); static Dart_Handle SendPlatformMessage(const std::string& name, Dart_Handle callback, Dart_Handle data_handle); static Dart_Handle SendPortPlatformMessage(const std::string& name, Dart_Handle identifier, Dart_Handle send_port, Dart_Handle data_handle); static void RespondToPlatformMessage(int response_id, const tonic::DartByteData& data); static void SendChannelUpdate(const std::string& name, bool listening); //-------------------------------------------------------------------------- /// @brief Requests the Dart VM to adjusts the GC heuristics based on /// the requested `performance_mode`. Returns the old performance /// mode. /// /// Requesting a performance mode doesn't guarantee any /// performance characteristics. This is best effort, and should /// be used after careful consideration of the various GC /// trade-offs. /// /// @param[in] performance_mode The requested performance mode. Please refer /// to documentation of `Dart_PerformanceMode` /// for more details about what each performance /// mode does. /// static int RequestDartPerformanceMode(int mode); //-------------------------------------------------------------------------- /// @brief Returns the current performance mode of the Dart VM. Defaults /// to `Dart_PerformanceMode_Default` if no prior requests to change the /// performance mode have been made. static Dart_PerformanceMode GetDartPerformanceMode(); static int64_t GetRootIsolateToken(); static void RegisterBackgroundIsolate(int64_t root_isolate_token); static double GetScaledFontSize(double unscaled_font_size, int configuration_id); private: static Dart_PerformanceMode current_performance_mode_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_WINDOW_PLATFORM_CONFIGURATION_H_
engine/lib/ui/window/platform_configuration.h/0
{ "file_path": "engine/lib/ui/window/platform_configuration.h", "repo_id": "engine", "token_count": 9761 }
253
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/window/pointer_data_packet.h" #include "flutter/fml/logging.h" #include <cstring> namespace flutter { PointerDataPacket::PointerDataPacket(size_t count) : data_(count * sizeof(PointerData)) {} PointerDataPacket::PointerDataPacket(uint8_t* data, size_t num_bytes) : data_(data, data + num_bytes) {} PointerDataPacket::~PointerDataPacket() = default; void PointerDataPacket::SetPointerData(size_t i, const PointerData& data) { FML_DCHECK(i < GetLength()); memcpy(&data_[i * sizeof(PointerData)], &data, sizeof(PointerData)); } PointerData PointerDataPacket::GetPointerData(size_t i) const { FML_DCHECK(i < GetLength()); PointerData result; memcpy(&result, &data_[i * sizeof(PointerData)], sizeof(PointerData)); return result; } size_t PointerDataPacket::GetLength() const { return data_.size() / sizeof(PointerData); } } // namespace flutter
engine/lib/ui/window/pointer_data_packet.cc/0
{ "file_path": "engine/lib/ui/window/pointer_data_packet.cc", "repo_id": "engine", "token_count": 374 }
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 'dart:async'; import 'package:args/command_runner.dart'; import 'environment.dart'; import 'pipeline.dart'; import 'utils.dart'; class AnalyzeCommand extends Command<bool> with ArgUtils<bool> { @override String get name => 'analyze'; @override String get description => 'Analyze the Flutter web engine.'; @override FutureOr<bool> run() async { final Pipeline buildPipeline = Pipeline(steps: <PipelineStep>[ PubGetStep(), AnalyzeStep(), ]); await buildPipeline.run(); return true; } } /// Runs `dart pub get`. class PubGetStep extends ProcessStep { @override String get description => 'pub get'; @override bool get isSafeToInterrupt => true; @override Future<ProcessManager> createProcess() { print('Running `dart pub get`...'); return startProcess( environment.dartExecutable, <String>['pub', 'get'], workingDirectory: environment.webUiRootDir.path, ); } } /// Runs `dart analyze --fatal-infos`. class AnalyzeStep extends ProcessStep { @override String get description => 'analyze'; @override bool get isSafeToInterrupt => true; @override Future<ProcessManager> createProcess() { print('Running `dart analyze`...'); return startProcess( environment.dartExecutable, <String>['analyze', '--fatal-infos'], workingDirectory: environment.webUiRootDir.path, ); } }
engine/lib/web_ui/dev/analyze.dart/0
{ "file_path": "engine/lib/web_ui/dev/analyze.dart", "repo_id": "engine", "token_count": 541 }
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:io' as io; import 'package:yaml/yaml.dart'; enum Compiler { dart2js, dart2wasm } enum Renderer { html, canvaskit, skwasm, } class CompileConfiguration { CompileConfiguration(this.name, this.compiler, this.renderer); final String name; final Compiler compiler; final Renderer renderer; } class TestSet { TestSet(this.name, this.directory); final String name; final String directory; } class TestBundle { TestBundle(this.name, this.testSet, this.compileConfigs); final String name; final TestSet testSet; final List<CompileConfiguration> compileConfigs; } enum CanvasKitVariant { full, chromium, } enum BrowserName { chrome, edge, firefox, safari, } class RunConfiguration { RunConfiguration(this.name, this.browser, this.variant); final String name; final BrowserName browser; final CanvasKitVariant? variant; } class ArtifactDependencies { ArtifactDependencies({ required this.canvasKit, required this.canvasKitChromium, required this.skwasm }); ArtifactDependencies.none() : canvasKit = false, canvasKitChromium = false, skwasm = false; final bool canvasKit; final bool canvasKitChromium; final bool skwasm; ArtifactDependencies operator|(ArtifactDependencies other) { return ArtifactDependencies( canvasKit: canvasKit || other.canvasKit, canvasKitChromium: canvasKitChromium || other.canvasKitChromium, skwasm: skwasm || other.skwasm, ); } ArtifactDependencies operator&(ArtifactDependencies other) { return ArtifactDependencies( canvasKit: canvasKit && other.canvasKit, canvasKitChromium: canvasKitChromium && other.canvasKitChromium, skwasm: skwasm && other.skwasm, ); } } class TestSuite { TestSuite( this.name, this.testBundle, this.runConfig, this.artifactDependencies ); String name; TestBundle testBundle; RunConfiguration runConfig; ArtifactDependencies artifactDependencies; } class FeltConfig { FeltConfig( this.compileConfigs, this.testSets, this.testBundles, this.runConfigs, this.testSuites, ); factory FeltConfig.fromFile(String filePath) { final io.File configFile = io.File(filePath); final YamlMap yaml = loadYaml(configFile.readAsStringSync()) as YamlMap; final List<CompileConfiguration> compileConfigs = <CompileConfiguration>[]; final Map<String, CompileConfiguration> compileConfigsByName = <String, CompileConfiguration>{}; for (final dynamic node in yaml['compile-configs'] as YamlList) { final YamlMap configYaml = node as YamlMap; final String name = configYaml['name'] as String; final Compiler compiler = Compiler.values.byName(configYaml['compiler'] as String); final Renderer renderer = Renderer.values.byName(configYaml['renderer'] as String); final CompileConfiguration config = CompileConfiguration(name, compiler, renderer); compileConfigs.add(config); if (compileConfigsByName.containsKey(name)) { throw AssertionError('Duplicate compile config name: $name'); } compileConfigsByName[name] = config; } final List<TestSet> testSets = <TestSet>[]; final Map<String, TestSet> testSetsByName = <String, TestSet>{}; for (final dynamic node in yaml['test-sets'] as YamlList) { final YamlMap testSetYaml = node as YamlMap; final String name = testSetYaml['name'] as String; final String directory = testSetYaml['directory'] as String; final TestSet testSet = TestSet(name, directory); testSets.add(testSet); if (testSetsByName.containsKey(name)) { throw AssertionError('Duplicate test set name: $name'); } testSetsByName[name] = testSet; } final List<TestBundle> testBundles = <TestBundle>[]; final Map<String, TestBundle> testBundlesByName = <String, TestBundle>{}; for (final dynamic node in yaml['test-bundles'] as YamlList) { final YamlMap testBundleYaml = node as YamlMap; final String name = testBundleYaml['name'] as String; final String testSetName = testBundleYaml['test-set'] as String; final TestSet? testSet = testSetsByName[testSetName]; if (testSet == null) { throw AssertionError('Test set not found with name: `$testSetName` (referenced by test bundle: `$name`)'); } final dynamic compileConfigsValue = testBundleYaml['compile-configs']; final List<CompileConfiguration> compileConfigs; if (compileConfigsValue is String) { compileConfigs = <CompileConfiguration>[compileConfigsByName[compileConfigsValue]!]; } else { compileConfigs = (compileConfigsValue as List<dynamic>).map( (dynamic configName) => compileConfigsByName[configName as String]! ).toList(); } final TestBundle bundle = TestBundle(name, testSet, compileConfigs); testBundles.add(bundle); if (testBundlesByName.containsKey(name)) { throw AssertionError('Duplicate test bundle name: $name'); } testBundlesByName[name] = bundle; } final List<RunConfiguration> runConfigs = <RunConfiguration>[]; final Map<String, RunConfiguration> runConfigsByName = <String, RunConfiguration>{}; for (final dynamic node in yaml['run-configs'] as YamlList) { final YamlMap runConfigYaml = node as YamlMap; final String name = runConfigYaml['name'] as String; final BrowserName browser = BrowserName.values.byName(runConfigYaml['browser'] as String); final dynamic variantNode = runConfigYaml['canvaskit-variant']; final CanvasKitVariant? variant = variantNode == null ? null : CanvasKitVariant.values.byName(variantNode as String); final RunConfiguration runConfig = RunConfiguration(name, browser, variant); runConfigs.add(runConfig); if (runConfigsByName.containsKey(name)) { throw AssertionError('Duplicate run config name: $name'); } runConfigsByName[name] = runConfig; } final List<TestSuite> testSuites = <TestSuite>[]; for (final dynamic node in yaml['test-suites'] as YamlList) { final YamlMap testSuiteYaml = node as YamlMap; final String name = testSuiteYaml['name'] as String; final String testBundleName = testSuiteYaml['test-bundle'] as String; final TestBundle? bundle = testBundlesByName[testBundleName]; if (bundle == null) { throw AssertionError('Test bundle not found with name: `$testBundleName` (referenced by test suite: `$name`)'); } final String runConfigName = testSuiteYaml['run-config'] as String; final RunConfiguration? runConfig = runConfigsByName[runConfigName]; if (runConfig == null) { throw AssertionError('Run config not found with name: `$runConfigName` (referenced by test suite: `$name`)'); } bool canvasKit = false; bool canvasKitChromium = false; bool skwasm = false; final dynamic depsNode = testSuiteYaml['artifact-deps']; if (depsNode != null) { for (final dynamic dep in depsNode as YamlList) { switch (dep as String) { case 'canvaskit': if (canvasKit) { throw AssertionError('Artifact dep $dep listed twice in suite $name.'); } canvasKit = true; case 'canvaskit_chromium': if (canvasKitChromium) { throw AssertionError('Artifact dep $dep listed twice in suite $name.'); } canvasKitChromium = true; case 'skwasm': if (skwasm) { throw AssertionError('Artifact dep $dep listed twice in suite $name.'); } skwasm = true; default: throw AssertionError('Unrecognized artifact dependency: $dep'); } } } final ArtifactDependencies artifactDeps = ArtifactDependencies( canvasKit: canvasKit, canvasKitChromium: canvasKitChromium, skwasm: skwasm ); final TestSuite suite = TestSuite(name, bundle, runConfig, artifactDeps); testSuites.add(suite); } return FeltConfig(compileConfigs, testSets, testBundles, runConfigs, testSuites); } List<CompileConfiguration> compileConfigs; List<TestSet> testSets; List<TestBundle> testBundles; List<RunConfiguration> runConfigs; List<TestSuite> testSuites; }
engine/lib/web_ui/dev/felt_config.dart/0
{ "file_path": "engine/lib/web_ui/dev/felt_config.dart", "repo_id": "engine", "token_count": 3317 }
256
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:path/path.dart' as path; import 'package:watcher/src/watch_event.dart'; import 'environment.dart'; import 'exceptions.dart'; import 'felt_config.dart'; import 'generate_builder_json.dart'; import 'pipeline.dart'; import 'steps/compile_bundle_step.dart'; import 'steps/copy_artifacts_step.dart'; import 'steps/run_suite_step.dart'; import 'suite_filter.dart'; import 'utils.dart'; /// Runs tests. class TestCommand extends Command<bool> with ArgUtils<bool> { TestCommand() { argParser ..addFlag( 'start-paused', help: 'Pauses the browser before running a test, giving you an ' 'opportunity to add breakpoints or inspect loaded code before ' 'running the code.', ) ..addFlag( 'verbose', abbr: 'v', help: 'Enable verbose output.' ) ..addFlag( 'watch', abbr: 'w', help: 'Run in watch mode so the tests re-run whenever a change is ' 'made.', ) ..addFlag( 'list', help: 'Lists the bundles that would be compiled and the suites that ' 'will be run as part of this invocation, without actually ' 'compiling or running them.' ) ..addFlag( 'generate-builder-json', help: 'Generates JSON for the engine_v2 builders to build and copy all' 'artifacts, compile all test bundles, and run all test suites on' 'all platforms.' ) ..addFlag( 'compile', help: 'Compile test bundles. If this is specified on its own, we will ' 'only compile and not run the suites.' ) ..addFlag( 'run', help: 'Run test suites. If this is specified on its own, we will only ' 'run the suites and not compile the bundles.' ) ..addFlag( 'copy-artifacts', help: 'Copy artifacts needed for test suites. If this is specified on ' 'its own, we will only copy the artifacts and not compile or run' 'the tests bundles or suites.' ) ..addFlag( 'profile', help: 'Use artifacts from the profile build instead of release.' ) ..addFlag( 'debug', help: 'Use artifacts from the debug build instead of release.' ) ..addFlag( 'dwarf', help: 'Debug wasm modules using embedded DWARF data.' ) ..addFlag( 'require-skia-gold', help: 'Whether we require Skia Gold to be available or not. When this ' 'flag is true, the tests will fail if Skia Gold is not available.', ) ..addFlag( 'update-screenshot-goldens', help: 'When running screenshot tests writes them to the file system into ' '.dart_tool/goldens. Use this option to bulk-update all screenshots, ' 'for example, when a new browser version affects pixels.', ) ..addMultiOption( 'browser', help: 'Filter test suites by browser.', ) ..addMultiOption( 'compiler', help: 'Filter test suites by compiler.', ) ..addMultiOption( 'renderer', help: 'Filter test suites by renderer.', ) ..addMultiOption( 'canvaskit-variant', help: 'Filter test suites by CanvasKit variant.', ) ..addMultiOption( 'suite', help: 'Filter test suites by suite name.', ) ..addMultiOption( 'bundle', help: 'Filter test suites by bundle name.', ) ..addFlag( 'fail-early', help: 'If set, causes the test runner to exit upon the first test ' 'failure. If not set, the test runner will continue running ' 'test despite failures and will report them after all tests ' 'finish.', ) ..addOption( 'canvaskit-path', help: 'Optional. The path to a local build of CanvasKit to use in ' 'tests. If omitted, the test runner uses the default CanvasKit ' 'build.', ) ..addFlag( 'wasm', help: 'Whether the test we are running are compiled to webassembly.' ); } @override final String name = 'test'; @override final String description = 'Run tests.'; bool get isWatchMode => boolArg('watch'); bool get isList => boolArg('list'); bool get failEarly => boolArg('fail-early'); /// Whether to start the browser in debug mode. /// /// In this mode the browser pauses before running the test to allow /// you set breakpoints or inspect the code. bool get startPaused => boolArg('start-paused'); bool get isVerbose => boolArg('verbose'); /// The target test files to run. List<FilePath> get targetFiles => argResults!.rest.map((String t) => FilePath.fromCwd(t)).toList(); /// When running screenshot tests, require Skia Gold to be available and /// reachable. bool get requireSkiaGold => boolArg('require-skia-gold'); /// When running screenshot tests writes them to the file system into /// ".dart_tool/goldens". bool get doUpdateScreenshotGoldens => boolArg('update-screenshot-goldens'); /// Path to a CanvasKit build. Overrides the default CanvasKit. String? get overridePathToCanvasKit => argResults!['canvaskit-path'] as String?; final FeltConfig config = FeltConfig.fromFile( path.join(environment.webUiTestDir.path, 'felt_config.yaml') ); BrowserSuiteFilter? makeBrowserFilter() { final List<String>? browserArgs = argResults!['browser'] as List<String>?; if (browserArgs == null || browserArgs.isEmpty) { return null; } final Set<BrowserName> browserNames = Set<BrowserName>.from(browserArgs.map((String arg) => BrowserName.values.byName(arg))); return BrowserSuiteFilter(allowList: browserNames); } CompilerFilter? makeCompilerFilter() { final List<String>? compilerArgs = argResults!['compiler'] as List<String>?; if (compilerArgs == null || compilerArgs.isEmpty) { return null; } final Set<Compiler> compilers = Set<Compiler>.from(compilerArgs.map((String arg) => Compiler.values.byName(arg))); return CompilerFilter(allowList: compilers); } RendererFilter? makeRendererFilter() { final List<String>? rendererArgs = argResults!['renderer'] as List<String>?; if (rendererArgs == null || rendererArgs.isEmpty) { return null; } final Set<Renderer> renderers = Set<Renderer>.from(rendererArgs.map((String arg) => Renderer.values.byName(arg))); return RendererFilter(allowList: renderers); } CanvasKitVariantFilter? makeCanvasKitVariantFilter() { final List<String>? variantArgs = argResults!['canvaskit-variant'] as List<String>?; if (variantArgs == null || variantArgs.isEmpty) { return null; } final Set<CanvasKitVariant> variants = Set<CanvasKitVariant>.from(variantArgs.map((String arg) => CanvasKitVariant.values.byName(arg))); return CanvasKitVariantFilter(allowList: variants); } SuiteNameFilter? makeSuiteNameFilter() { final List<String>? suiteNameArgs = argResults!['suite'] as List<String>?; if (suiteNameArgs == null || suiteNameArgs.isEmpty) { return null; } final Iterable<String> allSuiteNames = config.testSuites.map((TestSuite suite) => suite.name); for (final String suiteName in suiteNameArgs) { if (!allSuiteNames.contains(suiteName)) { throw ToolExit('No suite found named $suiteName'); } } return SuiteNameFilter(allowList: Set<String>.from(suiteNameArgs)); } BundleNameFilter? makeBundleNameFilter() { final List<String>? bundleNameArgs = argResults!['bundle'] as List<String>?; if (bundleNameArgs == null || bundleNameArgs.isEmpty) { return null; } final Iterable<String> allBundleNames = config.testSuites.map( (TestSuite suite) => suite.testBundle.name ); for (final String bundleName in bundleNameArgs) { if (!allBundleNames.contains(bundleName)) { throw ToolExit('No bundle found named $bundleName'); } } return BundleNameFilter(allowList: Set<String>.from(bundleNameArgs)); } FileFilter? makeFileFilter() { final List<FilePath> tests = targetFiles; if (tests.isEmpty) { return null; } final Set<String> bundleNames = <String>{}; for (final FilePath testPath in tests) { if (!io.File(testPath.absolute).existsSync()) { throw ToolExit('Test path not found: $testPath'); } bool bundleFound = false; for (final TestBundle bundle in config.testBundles) { final String testSetPath = getTestSetDirectory(bundle.testSet).path; if (path.isWithin(testSetPath, testPath.absolute)) { bundleFound = true; bundleNames.add(bundle.name); } } if (!bundleFound) { throw ToolExit('Test path not in any known test bundle: $testPath'); } } return FileFilter(allowList: bundleNames); } List<SuiteFilter> get suiteFilters { final BrowserSuiteFilter? browserFilter = makeBrowserFilter(); final CompilerFilter? compilerFilter = makeCompilerFilter(); final RendererFilter? rendererFilter = makeRendererFilter(); final CanvasKitVariantFilter? canvaskitVariantFilter = makeCanvasKitVariantFilter(); final SuiteNameFilter? suiteNameFilter = makeSuiteNameFilter(); final BundleNameFilter? bundleNameFilter = makeBundleNameFilter(); final FileFilter? fileFilter = makeFileFilter(); return <SuiteFilter>[ PlatformBrowserFilter(), if (browserFilter != null) browserFilter, if (compilerFilter != null) compilerFilter, if (rendererFilter != null) rendererFilter, if (canvaskitVariantFilter != null) canvaskitVariantFilter, if (suiteNameFilter != null) suiteNameFilter, if (bundleNameFilter != null) bundleNameFilter, if (fileFilter != null) fileFilter, ]; } List<TestSuite> _filterTestSuites() { if (isVerbose) { print('Filtering suites...'); } final List<SuiteFilter> filters = suiteFilters; final List<TestSuite> filteredSuites = config.testSuites.where((TestSuite suite) { for (final SuiteFilter filter in filters) { final SuiteFilterResult result = filter.filterSuite(suite); if (!result.isAccepted) { if (isVerbose) { print(' ${suite.name.ansiCyan} rejected for reason: ${result.rejectReason}'); } return false; } } return true; }).toList(); return filteredSuites; } List<TestBundle> _filterBundlesForSuites(List<TestSuite> suites) { final Set<TestBundle> seenBundles = Set<TestBundle>.from(suites.map((TestSuite suite) => suite.testBundle)); return config.testBundles.where((TestBundle bundle) => seenBundles.contains(bundle)).toList(); } ArtifactDependencies _artifactsForSuites(List<TestSuite> suites) { return suites.fold(ArtifactDependencies.none(), (ArtifactDependencies deps, TestSuite suite) => deps | suite.artifactDependencies); } @override Future<bool> run() async { final List<TestSuite> filteredSuites = _filterTestSuites(); final List<TestBundle> bundles = _filterBundlesForSuites(filteredSuites); final ArtifactDependencies artifacts = _artifactsForSuites(filteredSuites); if (boolArg('generate-builder-json')) { final String configString = generateBuilderJson(config); final io.File configFile = io.File(path.join( environment.flutterDirectory.path, 'ci', 'builders', 'linux_web_engine.json', )); configFile.writeAsStringSync(configString); return true; } if (isList || isVerbose) { print('Suites:'); for (final TestSuite suite in filteredSuites) { print(' ${suite.name.ansiCyan}'); } print('Bundles:'); for (final TestBundle bundle in bundles) { print(' ${bundle.name.ansiMagenta}'); } print('Artifacts:'); if (artifacts.canvasKit) { print(' canvaskit'.ansiYellow); } if (artifacts.canvasKitChromium) { print(' canvaskit_chromium'.ansiYellow); } if (artifacts.skwasm) { print(' skwasm'.ansiYellow); } } if (isList) { return true; } bool shouldRun = boolArg('run'); bool shouldCompile = boolArg('compile'); bool shouldCopyArtifacts = boolArg('copy-artifacts'); if (!shouldRun && !shouldCompile && !shouldCopyArtifacts) { // If none of these is specified, we should assume we need to do all of them. shouldRun = true; shouldCompile = true; shouldCopyArtifacts = true; } final Set<FilePath>? testFiles = targetFiles.isEmpty ? null : Set<FilePath>.from(targetFiles); final Pipeline testPipeline = Pipeline(steps: <PipelineStep>[ if (isWatchMode) ClearTerminalScreenStep(), if (shouldCopyArtifacts) CopyArtifactsStep(artifacts, runtimeMode: runtimeMode), if (shouldCompile) for (final TestBundle bundle in bundles) CompileBundleStep( bundle: bundle, isVerbose: isVerbose, testFiles: testFiles, ), if (shouldRun) for (final TestSuite suite in filteredSuites) RunSuiteStep( suite, startPaused: startPaused, isVerbose: isVerbose, doUpdateScreenshotGoldens: doUpdateScreenshotGoldens, requireSkiaGold: requireSkiaGold, overridePathToCanvasKit: overridePathToCanvasKit, testFiles: testFiles, useDwarf: boolArg('dwarf'), ), ]); try { await testPipeline.run(); if (isWatchMode) { print(''); print('Initial test succeeded!'); } } catch(error, stackTrace) { if (isWatchMode) { // The error is printed but not rethrown in watch mode because // failures are expected. The idea is that the developer corrects the // error, saves the file, and the pipeline reruns. print(''); print('Initial test failed!\n'); print(error); print(stackTrace); } else { rethrow; } } if (isWatchMode) { final FilePath dir = FilePath.fromWebUi(''); print(''); print( 'Watching ${dir.relativeToCwd}/lib and ${dir.relativeToCwd}/test to re-run tests'); print(''); await PipelineWatcher( dir: dir.absolute, pipeline: testPipeline, ignore: (WatchEvent event) { // Ignore font files that are copied whenever tests run. if (event.path.endsWith('.ttf')) { return true; } // React to changes in lib/ and test/ folders. final String relativePath = path.relative(event.path, from: dir.absolute); if (path.isWithin('lib', relativePath) || path.isWithin('test', relativePath)) { return false; } // Ignore anything else. return true; }).start(); } return true; } } /// Clears the terminal screen and places the cursor at the top left corner. /// /// This works on Linux and Mac. On Windows, it's a no-op. class ClearTerminalScreenStep implements PipelineStep { @override String get description => 'clearing terminal screen'; @override bool get isSafeToInterrupt => false; @override Future<void> interrupt() async {} @override Future<void> run() async { if (!io.Platform.isWindows) { // See: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences print('\x1B[2J\x1B[1;2H'); } } }
engine/lib/web_ui/dev/test_runner.dart/0
{ "file_path": "engine/lib/web_ui/dev/test_runner.dart", "repo_id": "engine", "token_count": 6444 }
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. type JSCompileTarget = "dart2js" | "dartdevc"; type WasmCompileTarget = "dart2wasm"; export type CompileTarget = JSCompileTarget | WasmCompileTarget; export type WebRenderer = "html" | "canvaskit" | "skwasm"; interface ApplicationBuildBase { renderer: WebRenderer; } export interface JSApplicationBuild extends ApplicationBuildBase { compileTarget: JSCompileTarget; mainJsPath: string; } export interface WasmApplicationBuild extends ApplicationBuildBase { compileTarget: WasmCompileTarget; mainWasmPath: string; jsSupportRuntimePath: string; } export type ApplicationBuild = JSApplicationBuild | WasmApplicationBuild; export interface BuildConfig { serviceWorkerVersion: string; engineRevision: string; builds: ApplicationBuild[]; } export interface BrowserEnvironment { hasImageCodecs: boolean; hasChromiumBreakIterators: boolean; supportsWasmGC: boolean; crossOriginIsolated: boolean; } type CanvasKitVariant = "auto" | "full" | "chromium"; export interface FlutterConfiguration { assetBase: string?; canvasKitBaseUrl: string?; canvasKitVariant: CanvasKitVariant?; renderer: WebRenderer?; hostElement: HtmlElement?; } export interface ServiceWorkerSettings { serviceWorkerVersion: string; serviceWorkerUrl: string?; timeoutMillis: number?; } export interface AppRunner { runApp: () => void; } export interface EngineInitializer { initializeEngine: () => Promise<AppRunner>; } export type OnEntrypointLoadedCallback = (initializer: EngineInitializer) => void;
engine/lib/web_ui/flutter_js/src/types.d.ts/0
{ "file_path": "engine/lib/web_ui/flutter_js/src/types.d.ts", "repo_id": "engine", "token_count": 522 }
258
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of ui; /// Runs [computation] on the platform thread and returns the result. /// /// This may run the computation on a separate isolate. That isolate will be /// reused for subsequent [runOnPlatformThread] calls. This means that global /// state is maintained in that isolate between calls. /// /// The [computation] and any state it captures may be sent to that isolate. /// See [SendPort.send] for information about what types can be sent. /// /// If [computation] is asynchronous (returns a `Future<R>`) then /// that future is awaited in the new isolate, completing the entire /// asynchronous computation, before returning the result. /// /// If [computation] throws, the `Future` returned by this function completes /// with that error. /// /// The [computation] function and its result (or error) must be /// sendable between isolates. Objects that cannot be sent include open /// files and sockets (see [SendPort.send] for details). /// /// This method can only be invoked from the main isolate. /// /// This API is currently experimental. Future<R> runOnPlatformThread<R>(FutureOr<R> Function() computation) => Future<R>(computation); /// Returns whether the current isolate is running on the platform thread. bool isRunningOnPlatformThread = true;
engine/lib/web_ui/lib/platform_isolate.dart/0
{ "file_path": "engine/lib/web_ui/lib/platform_isolate.dart", "repo_id": "engine", "token_count": 362 }
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:typed_data'; import 'package:ui/src/engine/vector_math.dart'; import 'package:ui/ui.dart' as ui; import '../util.dart'; import 'canvaskit_api.dart'; import 'color_filter.dart'; import 'native_memory.dart'; typedef SkImageFilterBorrow = void Function(SkImageFilter); /// An [ImageFilter] that can create a managed skia [SkImageFilter] object. /// /// Concrete subclasses of this interface must provide efficient implementation /// of [operator==], to avoid re-creating the underlying skia filters /// whenever possible. /// /// Currently implemented by [CkImageFilter] and [CkColorFilter]. abstract class CkManagedSkImageFilterConvertible implements ui.ImageFilter { void imageFilter(SkImageFilterBorrow borrow); Matrix4 get transform; } /// The CanvasKit implementation of [ui.ImageFilter]. /// /// Currently only supports `blur`, `matrix`, and ColorFilters. abstract class CkImageFilter implements CkManagedSkImageFilterConvertible { factory CkImageFilter.blur( {required double sigmaX, required double sigmaY, required ui.TileMode tileMode}) = _CkBlurImageFilter; factory CkImageFilter.color({required CkColorFilter colorFilter}) = CkColorFilterImageFilter; factory CkImageFilter.matrix( {required Float64List matrix, required ui.FilterQuality filterQuality}) = _CkMatrixImageFilter; factory CkImageFilter.compose( {required CkImageFilter outer, required CkImageFilter inner}) = _CkComposeImageFilter; CkImageFilter._(); @override Matrix4 get transform => Matrix4.identity(); } class CkColorFilterImageFilter extends CkImageFilter { CkColorFilterImageFilter({required this.colorFilter}) : super._() { final SkImageFilter skImageFilter = colorFilter.initRawImageFilter(); _ref = UniqueRef<SkImageFilter>(this, skImageFilter, 'ImageFilter.color'); } final CkColorFilter colorFilter; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } void dispose() { _ref.dispose(); } @override int get hashCode => colorFilter.hashCode; @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is CkColorFilterImageFilter && other.colorFilter == colorFilter; } @override String toString() => colorFilter.toString(); } class _CkBlurImageFilter extends CkImageFilter { _CkBlurImageFilter( {required this.sigmaX, required this.sigmaY, required this.tileMode}) : super._() { /// Return the identity matrix when both sigmaX and sigmaY are 0. Replicates /// effect of applying no filter final SkImageFilter skImageFilter; if (sigmaX == 0 && sigmaY == 0) { skImageFilter = canvasKit.ImageFilter.MakeMatrixTransform( toSkMatrixFromFloat32(Matrix4.identity().storage), toSkFilterOptions(ui.FilterQuality.none), null ); } else { skImageFilter = canvasKit.ImageFilter.MakeBlur( sigmaX, sigmaY, toSkTileMode(tileMode), null, ); } _ref = UniqueRef<SkImageFilter>(this, skImageFilter, 'ImageFilter.blur'); } final double sigmaX; final double sigmaY; final ui.TileMode tileMode; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is _CkBlurImageFilter && other.sigmaX == sigmaX && other.sigmaY == sigmaY && other.tileMode == tileMode; } @override int get hashCode => Object.hash(sigmaX, sigmaY, tileMode); @override String toString() { return 'ImageFilter.blur($sigmaX, $sigmaY, ${tileModeString(tileMode)})'; } } class _CkMatrixImageFilter extends CkImageFilter { _CkMatrixImageFilter( {required Float64List matrix, required this.filterQuality}) : matrix = Float64List.fromList(matrix), _transform = Matrix4.fromFloat32List(toMatrix32(matrix)), super._() { final SkImageFilter skImageFilter = canvasKit.ImageFilter.MakeMatrixTransform( toSkMatrixFromFloat64(matrix), toSkFilterOptions(filterQuality), null, ); _ref = UniqueRef<SkImageFilter>(this, skImageFilter, 'ImageFilter.matrix'); } final Float64List matrix; final ui.FilterQuality filterQuality; final Matrix4 _transform; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is _CkMatrixImageFilter && other.filterQuality == filterQuality && listEquals<double>(other.matrix, matrix); } @override int get hashCode => Object.hash(filterQuality, Object.hashAll(matrix)); @override String toString() => 'ImageFilter.matrix($matrix, $filterQuality)'; @override Matrix4 get transform => _transform; } class _CkComposeImageFilter extends CkImageFilter { _CkComposeImageFilter({required this.outer, required this.inner}) : super._() { outer.imageFilter((SkImageFilter outerFilter) { inner.imageFilter((SkImageFilter innerFilter) { final SkImageFilter skImageFilter = canvasKit.ImageFilter.MakeCompose( outerFilter, innerFilter, ); _ref = UniqueRef<SkImageFilter>( this, skImageFilter, 'ImageFilter.compose'); }); }); } final CkImageFilter outer; final CkImageFilter inner; late final UniqueRef<SkImageFilter> _ref; @override void imageFilter(SkImageFilterBorrow borrow) { borrow(_ref.nativeObject); } @override bool operator ==(Object other) { if (runtimeType != other.runtimeType) { return false; } return other is _CkComposeImageFilter && other.outer == outer && other.inner == inner; } @override int get hashCode => Object.hash(outer, inner); @override String toString() { return 'ImageFilter.compose($outer, $inner)'; } }
engine/lib/web_ui/lib/src/engine/canvaskit/image_filter.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/image_filter.dart", "repo_id": "engine", "token_count": 2253 }
260
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import 'canvas.dart'; import 'canvaskit_api.dart'; import 'picture.dart'; class CkPictureRecorder implements ui.PictureRecorder { SkPictureRecorder? _skRecorder; CkCanvas? _recordingCanvas; CkCanvas beginRecording(ui.Rect bounds) { final SkPictureRecorder recorder = _skRecorder = SkPictureRecorder(); final Float32List skRect = toSkRect(bounds); final SkCanvas skCanvas = recorder.beginRecording(skRect); return _recordingCanvas = CkCanvas(skCanvas); } CkCanvas? get recordingCanvas => _recordingCanvas; @override CkPicture endRecording() { final SkPictureRecorder? recorder = _skRecorder; if (recorder == null) { throw StateError('PictureRecorder is not recording'); } final SkPicture skPicture = recorder.finishRecordingAsPicture(); recorder.delete(); _skRecorder = null; final CkPicture result = CkPicture(skPicture); // We invoke the handler here, not in the picture constructor, because we want // [result.approximateBytesUsed] to be available for the handler. ui.Picture.onCreate?.call(result); return result; } @override bool get isRecording => _skRecorder != null; }
engine/lib/web_ui/lib/src/engine/canvaskit/picture_recorder.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/picture_recorder.dart", "repo_id": "engine", "token_count": 470 }
261
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:js_interop'; import 'dart:math' as math; import 'dart:typed_data'; import 'package:js/js_util.dart' as js_util; import 'package:meta/meta.dart'; import 'package:ui/src/engine/skwasm/skwasm_stub.dart' if (dart.library.ffi) 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'browser_detection.dart'; /// This file contains static interop classes for interacting with the DOM and /// some helpers. All of the classes in this file are named after their /// counterparts in the DOM. To extend any of these classes, simply add an /// external method to the appropriate class's extension. To add a new class, /// simply name the class after it's counterpart in the DOM and prefix the /// class name with `Dom`. /// NOTE: Currently, optional parameters do not behave as expected. /// For the time being, avoid passing optional parameters directly to JS. // TODO(joshualitt): To make it clearer to users of this shim that this is where // the boundary between Dart and JS interop exists, we should expose JS types // directly to the engine. /// Conversions methods to facilitate migrating to JS types. /// /// The existing behavior across the JS interop boundary involves many implicit /// conversions. For efficiency reasons, on JS backends we still want those /// implicit conversions, but on Wasm backends we need to 'shallowly' convert /// these types. /// /// Note: Due to discrepancies between how `null`, `JSNull`, and `JSUndefined` /// are currently represented across web backends, these extensions should be /// used carefully and only on types that are known to not contains `JSNull` and /// `JSUndefined`. extension ObjectToJSAnyExtension on Object { // Once `Object.toJSBox` is faster (see // https://github.com/dart-lang/sdk/issues/55183) we can remove this // backend-specific workaround. @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') JSAny get toJSWrapper => dartToJsWrapper(this); @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') JSAny get toJSAnyShallow { if (isWasm) { return toJSAnyDeep; } else { return this as JSAny; } } @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') JSAny get toJSAnyDeep => js_util.jsify(this) as JSAny; } extension JSAnyToObjectExtension on JSAny { @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') Object get fromJSWrapper => jsWrapperToDart(this); @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') Object get toObjectShallow { if (isWasm) { return toObjectDeep; } else { return this; } } @pragma('wasm:prefer-inline') @pragma('dart2js:tryInline') Object get toObjectDeep => js_util.dartify(this)!; } @JS('Object') external DomObjectConstructor get objectConstructor; @JS() @staticInterop class DomObjectConstructor {} extension DomObjectConstructorExtension on DomObjectConstructor { external JSObject assign(JSAny? target, JSAny? source1, JSAny? source2); } @JS() @staticInterop class DomWindow extends DomEventTarget {} extension DomWindowExtension on DomWindow { external DomConsole get console; @JS('devicePixelRatio') external JSNumber get _devicePixelRatio; double get devicePixelRatio => _devicePixelRatio.toDartDouble; external DomDocument get document; external DomHistory get history; @JS('innerHeight') external JSNumber? get _innerHeight; double? get innerHeight => _innerHeight?.toDartDouble; @JS('innerWidth') external JSNumber? get _innerWidth; double? get innerWidth => _innerWidth?.toDartDouble; external DomLocation get location; external DomNavigator get navigator; external DomVisualViewport? get visualViewport; external DomPerformance get performance; @visibleForTesting Future<Object?> fetch(String url) { // To make sure we have a consistent approach for handling and reporting // network errors, all code related to making HTTP calls is consolidated // into the `httpFetch` function, and a few convenience wrappers. throw UnsupportedError( 'Do not use window.fetch directly. ' 'Use httpFetch* family of functions instead.', ); } @JS('fetch') external JSPromise<JSAny?> _fetch1(JSString url); @JS('fetch') external JSPromise<JSAny?> _fetch2(JSString url, JSAny headers); // ignore: non_constant_identifier_names external DomURL get URL; @JS('dispatchEvent') external JSBoolean _dispatchEvent(DomEvent event); bool dispatchEvent(DomEvent event) => _dispatchEvent(event).toDart; @JS('matchMedia') external DomMediaQueryList _matchMedia(JSString? query); DomMediaQueryList matchMedia(String? query) => _matchMedia(query?.toJS); @JS('getComputedStyle') external DomCSSStyleDeclaration _getComputedStyle1(DomElement elt); @JS('getComputedStyle') external DomCSSStyleDeclaration _getComputedStyle2( DomElement elt, JSString pseudoElt); DomCSSStyleDeclaration getComputedStyle(DomElement elt, [String? pseudoElt]) { if (pseudoElt == null) { return _getComputedStyle1(elt); } else { return _getComputedStyle2(elt, pseudoElt.toJS); } } external DomScreen? get screen; @JS('requestAnimationFrame') external JSNumber _requestAnimationFrame(JSFunction callback); double requestAnimationFrame(DomRequestAnimationFrameCallback callback) => _requestAnimationFrame(callback.toJS).toDartDouble; @JS('postMessage') external JSVoid _postMessage1(JSAny message, JSString targetOrigin); @JS('postMessage') external JSVoid _postMessage2( JSAny message, JSString targetOrigin, JSArray<JSAny?> messagePorts); void postMessage(Object message, String targetOrigin, [List<DomMessagePort>? messagePorts]) { if (messagePorts == null) { _postMessage1(message.toJSAnyShallow, targetOrigin.toJS); } else { _postMessage2( message.toJSAnyShallow, targetOrigin.toJS, // Cast is necessary so we can call `.toJS` on the right extension. // ignore: unnecessary_cast (messagePorts as List<JSAny>).toJS); } } /// The Trusted Types API (when available). /// See: https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API external DomTrustedTypePolicyFactory? get trustedTypes; } typedef DomRequestAnimationFrameCallback = void Function(JSNumber highResTime); @JS() @staticInterop class DomConsole {} extension DomConsoleExtension on DomConsole { @JS('warn') external JSVoid _warn(JSString? arg); void warn(Object? arg) => _warn(arg.toString().toJS); @JS('error') external JSVoid _error(JSString? arg); void error(Object? arg) => _error(arg.toString().toJS); @JS('debug') external JSVoid _debug(JSString? arg); void debug(Object? arg) => _debug(arg.toString().toJS); } @JS('window') external DomWindow get domWindow; @JS('Intl') external DomIntl get domIntl; @JS('Symbol') external DomSymbol get domSymbol; @JS('createImageBitmap') external JSPromise<JSAny?> _createImageBitmap1( JSAny source, ); @JS('createImageBitmap') external JSPromise<JSAny?> _createImageBitmap2( JSAny source, JSNumber x, JSNumber y, JSNumber width, JSNumber height, ); Future<DomImageBitmap> createImageBitmap(JSAny source, [({int x, int y, int width, int height})? bounds]) { JSPromise<JSAny?> jsPromise; if (bounds != null) { jsPromise = _createImageBitmap2(source, bounds.x.toJS, bounds.y.toJS, bounds.width.toJS, bounds.height.toJS); } else { jsPromise = _createImageBitmap1(source); } return js_util.promiseToFuture<DomImageBitmap>(jsPromise); } @JS() @staticInterop class DomNavigator {} extension DomNavigatorExtension on DomNavigator { external DomClipboard? get clipboard; @JS('maxTouchPoints') external JSNumber? get _maxTouchPoints; double? get maxTouchPoints => _maxTouchPoints?.toDartDouble; @JS('vendor') external JSString get _vendor; String get vendor => _vendor.toDart; @JS('language') external JSString get _language; String get language => _language.toDart; @JS('platform') external JSString? get _platform; String? get platform => _platform?.toDart; @JS('userAgent') external JSString get _userAgent; String get userAgent => _userAgent.toDart; @JS('languages') external JSArray<JSAny?>? get _languages; List<String>? get languages => _languages?.toDart .map<String>((JSAny? any) => (any! as JSString).toDart) .toList(); } @JS() @staticInterop class DomDocument extends DomNode {} extension DomDocumentExtension on DomDocument { external DomElement? get documentElement; @JS('querySelector') external DomElement? _querySelector(JSString selectors); DomElement? querySelector(String selectors) => _querySelector(selectors.toJS); @JS('querySelectorAll') external _DomList _querySelectorAll(JSString selectors); Iterable<DomElement> querySelectorAll(String selectors) => createDomListWrapper<DomElement>(_querySelectorAll(selectors.toJS)); @JS('createElement') external DomElement _createElement1(JSString name); @JS('createElement') external DomElement _createElement2(JSString name, JSAny? options); DomElement createElement(String name, [Object? options]) { if (options == null) { return _createElement1(name.toJS); } else { return _createElement2(name.toJS, options.toJSAnyDeep); } } @JS('execCommand') external JSBoolean _execCommand(JSString commandId); bool execCommand(String commandId) => _execCommand(commandId.toJS).toDart; external DomHTMLScriptElement? get currentScript; @JS('createElementNS') external DomElement _createElementNS( JSString namespaceURI, JSString qualifiedName); DomElement createElementNS(String namespaceURI, String qualifiedName) => _createElementNS(namespaceURI.toJS, qualifiedName.toJS); @JS('createTextNode') external DomText _createTextNode(JSString data); DomText createTextNode(String data) => _createTextNode(data.toJS); @JS('createEvent') external DomEvent _createEvent(JSString eventType); DomEvent createEvent(String eventType) => _createEvent(eventType.toJS); external DomElement? get activeElement; @JS('elementFromPoint') external DomElement? _elementFromPoint(JSNumber x, JSNumber y); DomElement? elementFromPoint(int x, int y) => _elementFromPoint(x.toJS, y.toJS); } @JS() @staticInterop class DomHTMLDocument extends DomDocument {} extension DomHTMLDocumentExtension on DomHTMLDocument { external DomFontFaceSet? get fonts; external DomHTMLHeadElement? get head; external DomHTMLBodyElement? get body; @JS('title') external set _title(JSString? value); set title(String? value) => _title = value?.toJS; @JS('title') external JSString? get _title; String? get title => _title?.toDart; @JS('getElementsByTagName') external _DomList _getElementsByTagName(JSString tag); Iterable<DomElement> getElementsByTagName(String tag) => createDomListWrapper<DomElement>(_getElementsByTagName(tag.toJS)); external DomElement? get activeElement; @JS('getElementById') external DomElement? _getElementById(JSString id); DomElement? getElementById(String id) => _getElementById(id.toJS); @JS('visibilityState') external JSString get _visibilityState; String get visibilityState => _visibilityState.toDart; } @JS('document') external DomHTMLDocument get domDocument; @JS() @staticInterop class DomEventTarget {} extension DomEventTargetExtension on DomEventTarget { @JS('addEventListener') external JSVoid _addEventListener1(JSString type, DomEventListener listener); @JS('addEventListener') external JSVoid _addEventListener2( JSString type, DomEventListener listener, JSBoolean useCapture); void addEventListener(String type, DomEventListener? listener, [bool? useCapture]) { if (listener != null) { if (useCapture == null) { _addEventListener1(type.toJS, listener); } else { _addEventListener2(type.toJS, listener, useCapture.toJS); } } } @JS('addEventListener') external JSVoid _addEventListener3( JSString type, DomEventListener listener, JSAny options); void addEventListenerWithOptions(String type, DomEventListener listener, Map<String, Object> options) => _addEventListener3(type.toJS, listener, options.toJSAnyDeep); @JS('removeEventListener') external JSVoid _removeEventListener1( JSString type, DomEventListener listener); @JS('removeEventListener') external JSVoid _removeEventListener2( JSString type, DomEventListener listener, JSBoolean useCapture); void removeEventListener(String type, DomEventListener? listener, [bool? useCapture]) { if (listener != null) { if (useCapture == null) { _removeEventListener1(type.toJS, listener); } else { _removeEventListener2(type.toJS, listener, useCapture.toJS); } } } @JS('dispatchEvent') external JSBoolean _dispatchEvent(DomEvent event); bool dispatchEvent(DomEvent event) => _dispatchEvent(event).toDart; } typedef DartDomEventListener = JSVoid Function(DomEvent event); @JS() @staticInterop class DomEventListener {} DomEventListener createDomEventListener(DartDomEventListener listener) => listener.toJS as DomEventListener; @JS() @staticInterop class DomEvent {} extension DomEventExtension on DomEvent { external DomEventTarget? get target; external DomEventTarget? get currentTarget; @JS('timeStamp') external JSNumber? get _timeStamp; double? get timeStamp => _timeStamp?.toDartDouble; @JS('type') external JSString get _type; String get type => _type.toDart; external JSVoid preventDefault(); external JSVoid stopPropagation(); @JS('initEvent') external JSVoid _initEvent1(JSString type); @JS('initEvent') external JSVoid _initEvent2(JSString type, JSBoolean bubbles); @JS('initEvent') external JSVoid _initEvent3( JSString type, JSBoolean bubbles, JSBoolean cancelable); void initEvent(String type, [bool? bubbles, bool? cancelable]) { if (bubbles == null) { _initEvent1(type.toJS); } else if (cancelable == null) { _initEvent2(type.toJS, bubbles.toJS); } else { _initEvent3(type.toJS, bubbles.toJS, cancelable.toJS); } } @JS('defaultPrevented') external JSBoolean get _defaultPrevented; bool get defaultPrevented => _defaultPrevented.toDart; } DomEvent createDomEvent(String type, String name) { final DomEvent event = domDocument.createEvent(type); event.initEvent(name, true, true); return event; } @JS('ProgressEvent') @staticInterop class DomProgressEvent extends DomEvent { factory DomProgressEvent(String type) => DomProgressEvent._(type.toJS); external factory DomProgressEvent._(JSString type); } extension DomProgressEventExtension on DomProgressEvent { @JS('loaded') external JSNumber? get _loaded; double? get loaded => _loaded?.toDartDouble; @JS('total') external JSNumber? get _total; double? get total => _total?.toDartDouble; } @JS() @staticInterop class DomNode extends DomEventTarget {} extension DomNodeExtension on DomNode { @JS('baseURI') external JSString? get _baseUri; String? get baseUri => _baseUri?.toDart; external DomNode? get firstChild; @JS('innerText') external JSString get _innerText; String get innerText => _innerText.toDart; @JS('innerText') external set _innerText(JSString text); set innerText(String text) => _innerText = text.toJS; external DomNode? get lastChild; external DomNode appendChild(DomNode node); @JS('parentElement') external DomElement? get parentElement; DomElement? get parent => parentElement; @JS('textContent') external JSString? get _textContent; String? get text => _textContent?.toDart; external DomNode? get parentNode; external DomNode? get nextSibling; external DomNode insertBefore(DomNode newNode, DomNode? referenceNode); void remove() { if (parentNode != null) { final DomNode parent = parentNode!; parent.removeChild(this); } } external DomNode removeChild(DomNode child); @JS('isConnected') external JSBoolean? get _isConnected; bool? get isConnected => _isConnected?.toDart; @JS('textContent') external set _textContent(JSString? value); set text(String? value) => _textContent = value?.toJS; @JS('cloneNode') external DomNode _cloneNode(JSBoolean? deep); DomNode cloneNode(bool? deep) => _cloneNode(deep?.toJS); @JS('contains') external JSBoolean _contains(DomNode? other); bool contains(DomNode? other) => _contains(other).toDart; external JSVoid append(DomNode node); @JS('childNodes') external _DomList get _childNodes; Iterable<DomNode> get childNodes => createDomListWrapper<DomElement>(_childNodes); external DomDocument? get ownerDocument; void clearChildren() { while (firstChild != null) { removeChild(firstChild!); } } } @JS() @staticInterop class DomElement extends DomNode {} DomElement createDomElement(String tag) => domDocument.createElement(tag); extension DomElementExtension on DomElement { @JS('children') external _DomList get _children; Iterable<DomElement> get children => createDomListWrapper<DomElement>(_children); external DomElement? get firstElementChild; external DomElement? get lastElementChild; external DomElement? get nextElementSibling; @JS('clientHeight') external JSNumber get _clientHeight; double get clientHeight => _clientHeight.toDartDouble; @JS('clientWidth') external JSNumber get _clientWidth; double get clientWidth => _clientWidth.toDartDouble; @JS('id') external JSString get _id; String get id => _id.toDart; @JS('id') external set _id(JSString id); set id(String id) => _id = id.toJS; @JS('innerHtml') external set _innerHtml(JSString? html); set innerHtml(String? html) => _innerHtml = html?.toJS; @JS('outerHTML') external JSString? get _outerHTML; String? get outerHTML => _outerHTML?.toDart; @JS('spellcheck') external set _spellcheck(JSBoolean? value); set spellcheck(bool? value) => _spellcheck = value?.toJS; @JS('tagName') external JSString get _tagName; String get tagName => _tagName.toDart; external DomCSSStyleDeclaration get style; external JSVoid append(DomNode node); @JS('getAttribute') external JSString? _getAttribute(JSString attributeName); String? getAttribute(String attributeName) => _getAttribute(attributeName.toJS)?.toDart; external DomRect getBoundingClientRect(); external JSVoid prepend(DomNode node); @JS('querySelector') external DomElement? _querySelector(JSString selectors); DomElement? querySelector(String selectors) => _querySelector(selectors.toJS); @JS('closest') external DomElement? _closest(JSString selectors); DomElement? closest(String selectors) => _closest(selectors.toJS); @JS('matches') external JSBoolean _matches(JSString selectors); bool matches(String selectors) => _matches(selectors.toJS).toDart; @JS('querySelectorAll') external _DomList _querySelectorAll(JSString selectors); Iterable<DomElement> querySelectorAll(String selectors) => createDomListWrapper<DomElement>(_querySelectorAll(selectors.toJS)); external JSVoid remove(); @JS('setAttribute') external JSVoid _setAttribute(JSString name, JSAny value); JSVoid setAttribute(String name, Object value) => _setAttribute(name.toJS, value.toJSAnyDeep); void appendText(String text) => append(createDomText(text)); @JS('removeAttribute') external JSVoid _removeAttribute(JSString name); void removeAttribute(String name) => _removeAttribute(name.toJS); @JS('tabIndex') external set _tabIndex(JSNumber? value); set tabIndex(double? value) => _tabIndex = value?.toJS; @JS('tabIndex') external JSNumber? get _tabIndex; double? get tabIndex => _tabIndex?.toDartDouble; external JSVoid focus(); @JS('scrollTop') external JSNumber get _scrollTop; double get scrollTop => _scrollTop.toDartDouble; @JS('scrollTop') external set _scrollTop(JSNumber value); set scrollTop(double value) => _scrollTop = value.toJS; @JS('scrollLeft') external JSNumber get _scrollLeft; double get scrollLeft => _scrollLeft.toDartDouble; @JS('scrollLeft') external set _scrollLeft(JSNumber value); set scrollLeft(double value) => _scrollLeft = value.toJS; external DomTokenList get classList; @JS('className') external set _className(JSString value); set className(String value) => _className = value.toJS; @JS('className') external JSString get _className; String get className => _className.toDart; external JSVoid blur(); @JS('getElementsByTagName') external _DomList _getElementsByTagName(JSString tag); Iterable<DomNode> getElementsByTagName(String tag) => createDomListWrapper(_getElementsByTagName(tag.toJS)); @JS('getElementsByClassName') external _DomList _getElementsByClassName(JSString className); Iterable<DomNode> getElementsByClassName(String className) => createDomListWrapper(_getElementsByClassName(className.toJS)); external JSVoid click(); @JS('hasAttribute') external JSBoolean _hasAttribute(JSString name); bool hasAttribute(String name) => _hasAttribute(name.toJS).toDart; @JS('childNodes') external _DomList get _childNodes; Iterable<DomNode> get childNodes => createDomListWrapper<DomElement>(_childNodes); @JS('attachShadow') external DomShadowRoot _attachShadow(JSAny initDict); DomShadowRoot attachShadow(Map<Object?, Object?> initDict) => _attachShadow(initDict.toJSAnyDeep); external DomShadowRoot? get shadowRoot; void clearChildren() { while (firstChild != null) { removeChild(firstChild!); } } } @JS() @staticInterop class DomCSSStyleDeclaration {} extension DomCSSStyleDeclarationExtension on DomCSSStyleDeclaration { set width(String value) => setProperty('width', value); set height(String value) => setProperty('height', value); set position(String value) => setProperty('position', value); set clip(String value) => setProperty('clip', value); set clipPath(String value) => setProperty('clip-path', value); set transform(String value) => setProperty('transform', value); set transformOrigin(String value) => setProperty('transform-origin', value); set opacity(String value) => setProperty('opacity', value); set color(String value) => setProperty('color', value); set top(String value) => setProperty('top', value); set left(String value) => setProperty('left', value); set right(String value) => setProperty('right', value); set bottom(String value) => setProperty('bottom', value); set backgroundColor(String value) => setProperty('background-color', value); set caretColor(String value) => setProperty('caret-color', value); set pointerEvents(String value) => setProperty('pointer-events', value); set filter(String value) => setProperty('filter', value); set zIndex(String value) => setProperty('z-index', value); set whiteSpace(String value) => setProperty('white-space', value); set lineHeight(String value) => setProperty('line-height', value); set textStroke(String value) => setProperty('-webkit-text-stroke', value); set fontSize(String value) => setProperty('font-size', value); set fontWeight(String value) => setProperty('font-weight', value); set fontStyle(String value) => setProperty('font-style', value); set fontFamily(String value) => setProperty('font-family', value); set letterSpacing(String value) => setProperty('letter-spacing', value); set wordSpacing(String value) => setProperty('word-spacing', value); set textShadow(String value) => setProperty('text-shadow', value); set textDecoration(String value) => setProperty('text-decoration', value); set textDecorationColor(String value) => setProperty('text-decoration-color', value); set fontFeatureSettings(String value) => setProperty('font-feature-settings', value); set fontVariationSettings(String value) => setProperty('font-variation-settings', value); set visibility(String value) => setProperty('visibility', value); set overflow(String value) => setProperty('overflow', value); set boxShadow(String value) => setProperty('box-shadow', value); set borderTopLeftRadius(String value) => setProperty('border-top-left-radius', value); set borderTopRightRadius(String value) => setProperty('border-top-right-radius', value); set borderBottomLeftRadius(String value) => setProperty('border-bottom-left-radius', value); set borderBottomRightRadius(String value) => setProperty('border-bottom-right-radius', value); set borderRadius(String value) => setProperty('border-radius', value); set perspective(String value) => setProperty('perspective', value); set padding(String value) => setProperty('padding', value); set backgroundImage(String value) => setProperty('background-image', value); set border(String value) => setProperty('border', value); set mixBlendMode(String value) => setProperty('mix-blend-mode', value); set backgroundSize(String value) => setProperty('background-size', value); set backgroundBlendMode(String value) => setProperty('background-blend-mode', value); set transformStyle(String value) => setProperty('transform-style', value); set display(String value) => setProperty('display', value); set flexDirection(String value) => setProperty('flex-direction', value); set alignItems(String value) => setProperty('align-items', value); set margin(String value) => setProperty('margin', value); set background(String value) => setProperty('background', value); set touchAction(String value) => setProperty('touch-action', value); set overflowY(String value) => setProperty('overflow-y', value); set overflowX(String value) => setProperty('overflow-x', value); set outline(String value) => setProperty('outline', value); set resize(String value) => setProperty('resize', value); set alignContent(String value) => setProperty('align-content', value); set textAlign(String value) => setProperty('text-align', value); set font(String value) => setProperty('font', value); set cursor(String value) => setProperty('cursor', value); String get width => getPropertyValue('width'); String get height => getPropertyValue('height'); String get position => getPropertyValue('position'); String get clip => getPropertyValue('clip'); String get clipPath => getPropertyValue('clip-path'); String get transform => getPropertyValue('transform'); String get transformOrigin => getPropertyValue('transform-origin'); String get opacity => getPropertyValue('opacity'); String get color => getPropertyValue('color'); String get top => getPropertyValue('top'); String get left => getPropertyValue('left'); String get right => getPropertyValue('right'); String get bottom => getPropertyValue('bottom'); String get backgroundColor => getPropertyValue('background-color'); String get caretColor => getPropertyValue('caret-color'); String get pointerEvents => getPropertyValue('pointer-events'); String get filter => getPropertyValue('filter'); String get zIndex => getPropertyValue('z-index'); String get whiteSpace => getPropertyValue('white-space'); String get lineHeight => getPropertyValue('line-height'); String get textStroke => getPropertyValue('-webkit-text-stroke'); String get fontSize => getPropertyValue('font-size'); String get fontWeight => getPropertyValue('font-weight'); String get fontStyle => getPropertyValue('font-style'); String get fontFamily => getPropertyValue('font-family'); String get letterSpacing => getPropertyValue('letter-spacing'); String get wordSpacing => getPropertyValue('word-spacing'); String get textShadow => getPropertyValue('text-shadow'); String get textDecorationColor => getPropertyValue('text-decoration-color'); String get fontFeatureSettings => getPropertyValue('font-feature-settings'); String get fontVariationSettings => getPropertyValue('font-variation-settings'); String get visibility => getPropertyValue('visibility'); String get overflow => getPropertyValue('overflow'); String get boxShadow => getPropertyValue('box-shadow'); String get borderTopLeftRadius => getPropertyValue('border-top-left-radius'); String get borderTopRightRadius => getPropertyValue('border-top-right-radius'); String get borderBottomLeftRadius => getPropertyValue('border-bottom-left-radius'); String get borderBottomRightRadius => getPropertyValue('border-bottom-right-radius'); String get borderRadius => getPropertyValue('border-radius'); String get perspective => getPropertyValue('perspective'); String get padding => getPropertyValue('padding'); String get backgroundImage => getPropertyValue('background-image'); String get border => getPropertyValue('border'); String get mixBlendMode => getPropertyValue('mix-blend-mode'); String get backgroundSize => getPropertyValue('background-size'); String get backgroundBlendMode => getPropertyValue('background-blend-mode'); String get transformStyle => getPropertyValue('transform-style'); String get display => getPropertyValue('display'); String get flexDirection => getPropertyValue('flex-direction'); String get alignItems => getPropertyValue('align-items'); String get margin => getPropertyValue('margin'); String get background => getPropertyValue('background'); String get touchAction => getPropertyValue('touch-action'); String get overflowY => getPropertyValue('overflow-y'); String get overflowX => getPropertyValue('overflow-x'); String get outline => getPropertyValue('outline'); String get resize => getPropertyValue('resize'); String get alignContent => getPropertyValue('align-content'); String get textAlign => getPropertyValue('text-align'); String get font => getPropertyValue('font'); String get cursor => getPropertyValue('cursor'); @JS('getPropertyValue') external JSString _getPropertyValue(JSString property); String getPropertyValue(String property) => _getPropertyValue(property.toJS).toDart; @JS('setProperty') external JSVoid _setProperty( JSString propertyName, JSString value, JSString priority); void setProperty(String propertyName, String value, [String? priority]) { priority ??= ''; _setProperty(propertyName.toJS, value.toJS, priority.toJS); } @JS('removeProperty') external JSString _removeProperty(JSString property); String removeProperty(String property) => _removeProperty(property.toJS).toDart; } @JS() @staticInterop class DomHTMLElement extends DomElement {} extension DomHTMLElementExtension on DomHTMLElement { @JS('offsetWidth') external JSNumber get _offsetWidth; double get offsetWidth => _offsetWidth.toDartDouble; @JS('offsetLeft') external JSNumber get _offsetLeft; double get offsetLeft => _offsetLeft.toDartDouble; @JS('offsetTop') external JSNumber get _offsetTop; double get offsetTop => _offsetTop.toDartDouble; external DomHTMLElement? get offsetParent; } @JS() @staticInterop class DomHTMLMetaElement extends DomHTMLElement {} extension DomHTMLMetaElementExtension on DomHTMLMetaElement { @JS('name') external JSString get _name; String get name => _name.toDart; @JS('name') external set _name(JSString value); set name(String value) => _name = value.toJS; @JS('content') external JSString get _content; String get content => _content.toDart; @JS('content') external set _content(JSString value); set content(String value) => _content = value.toJS; } DomHTMLMetaElement createDomHTMLMetaElement() => domDocument.createElement('meta') as DomHTMLMetaElement; @JS() @staticInterop class DomHTMLHeadElement extends DomHTMLElement {} @JS() @staticInterop class DomHTMLBodyElement extends DomHTMLElement {} @JS() @staticInterop class DomHTMLImageElement extends DomHTMLElement implements DomCanvasImageSource {} DomHTMLImageElement createDomHTMLImageElement() => domDocument.createElement('img') as DomHTMLImageElement; extension DomHTMLImageElementExtension on DomHTMLImageElement { @JS('alt') external JSString? get _alt; String? get alt => _alt?.toDart; @JS('alt') external set _alt(JSString? value); set alt(String? value) => _alt = value?.toJS; @JS('src') external JSString? get _src; String? get src => _src?.toDart; @JS('src') external set _src(JSString? value); set src(String? value) => _src = value?.toJS; @JS('naturalWidth') external JSNumber get _naturalWidth; double get naturalWidth => _naturalWidth.toDartDouble; @JS('naturalHeight') external JSNumber get _naturalHeight; double get naturalHeight => _naturalHeight.toDartDouble; @JS('width') external set _width(JSNumber? value); set width(double? value) => _width = value?.toJS; @JS('height') external set _height(JSNumber? value); set height(double? value) => _height = value?.toJS; @JS('decode') external JSPromise<JSAny?> _decode(); Future<Object?> decode() => js_util.promiseToFuture<Object?>(_decode()); } @JS() @staticInterop class DomHTMLScriptElement extends DomHTMLElement {} extension DomHTMLScriptElementExtension on DomHTMLScriptElement { @JS('src') external set _src(JSAny value); set src(Object /* String|TrustedScriptURL */ value) => _src = value.toJSAnyShallow; @JS('nonce') external set _nonce(JSString? value); set nonce(String? value) => _nonce = value?.toJS; } DomHTMLScriptElement createDomHTMLScriptElement(String? nonce) { final DomHTMLScriptElement script = domDocument.createElement('script') as DomHTMLScriptElement; if (nonce != null) { script.nonce = nonce; } return script; } @JS() @staticInterop class DomHTMLDivElement extends DomHTMLElement {} DomHTMLDivElement createDomHTMLDivElement() => domDocument.createElement('div') as DomHTMLDivElement; @JS() @staticInterop class DomHTMLSpanElement extends DomHTMLElement {} DomHTMLSpanElement createDomHTMLSpanElement() => domDocument.createElement('span') as DomHTMLSpanElement; @JS() @staticInterop class DomHTMLButtonElement extends DomHTMLElement {} DomHTMLButtonElement createDomHTMLButtonElement() => domDocument.createElement('button') as DomHTMLButtonElement; @JS() @staticInterop class DomHTMLParagraphElement extends DomHTMLElement {} DomHTMLParagraphElement createDomHTMLParagraphElement() => domDocument.createElement('p') as DomHTMLParagraphElement; @JS() @staticInterop class DomHTMLStyleElement extends DomHTMLElement {} extension DomHTMLStyleElementExtension on DomHTMLStyleElement { @JS('type') external set _type(JSString? value); set type(String? value) => _type = value?.toJS; @JS('nonce') external set _nonce(JSString? value); set nonce(String? value) => _nonce = value?.toJS; @JS('nonce') external JSString? get _nonce; String? get nonce => _nonce?.toDart; external DomStyleSheet? get sheet; } DomHTMLStyleElement createDomHTMLStyleElement(String? nonce) { final DomHTMLStyleElement style = domDocument.createElement('style') as DomHTMLStyleElement; if (nonce != null) { style.nonce = nonce; } return style; } @JS() @staticInterop class DomPerformance extends DomEventTarget {} extension DomPerformanceExtension on DomPerformance { @JS('mark') external DomPerformanceEntry? _mark(JSString markName); DomPerformanceEntry? mark(String markName) => _mark(markName.toJS); @JS('measure') external DomPerformanceMeasure? _measure( JSString measureName, JSString? startMark, JSString? endMark); DomPerformanceMeasure? measure( String measureName, String? startMark, String? endMark) => _measure(measureName.toJS, startMark?.toJS, endMark?.toJS); @JS('now') external JSNumber _now(); double now() => _now().toDartDouble; } @JS() @staticInterop class DomPerformanceEntry {} @JS() @staticInterop class DomPerformanceMeasure extends DomPerformanceEntry {} @JS() @staticInterop class DomCanvasElement extends DomHTMLElement {} @visibleForTesting int debugCanvasCount = 0; @visibleForTesting void debugResetCanvasCount() { debugCanvasCount = 0; } DomCanvasElement createDomCanvasElement({int? width, int? height}) { debugCanvasCount++; final DomCanvasElement canvas = domWindow.document.createElement('canvas') as DomCanvasElement; if (width != null) { canvas.width = width.toDouble(); } if (height != null) { canvas.height = height.toDouble(); } return canvas; } extension DomCanvasElementExtension on DomCanvasElement { @JS('width') external JSNumber? get _width; double? get width => _width?.toDartDouble; @JS('width') external set _width(JSNumber? value); set width(double? value) => _width = value?.toJS; @JS('height') external JSNumber? get _height; double? get height => _height?.toDartDouble; @JS('height') external set _height(JSNumber? value); set height(double? value) => _height = value?.toJS; @JS('isConnected') external JSBoolean? get _isConnected; bool? get isConnected => _isConnected?.toDart; @JS('toDataURL') external JSString _toDataURL(JSString type); String toDataURL([String type = 'image/png']) => _toDataURL(type.toJS).toDart; @JS('getContext') external JSAny? _getContext1(JSString contextType); @JS('getContext') external JSAny? _getContext2(JSString contextType, JSAny attributes); Object? getContext(String contextType, [Map<dynamic, dynamic>? attributes]) { if (attributes == null) { return _getContext1(contextType.toJS); } else { return _getContext2(contextType.toJS, attributes.toJSAnyDeep); } } DomCanvasRenderingContext2D get context2D => getContext('2d')! as DomCanvasRenderingContext2D; WebGLContext getGlContext(int majorVersion) { if (majorVersion == 1) { return getContext('webgl')! as WebGLContext; } return getContext('webgl2')! as WebGLContext; } DomCanvasRenderingContextBitmapRenderer get contextBitmapRenderer => getContext('bitmaprenderer')! as DomCanvasRenderingContextBitmapRenderer; } @JS() @staticInterop class WebGLContext {} extension WebGLContextExtension on WebGLContext { @JS('getParameter') external JSNumber _getParameter(JSNumber value); int getParameter(int value) => _getParameter(value.toJS).toDartDouble.toInt(); @JS('SAMPLES') external JSNumber get _samples; int get samples => _samples.toDartDouble.toInt(); @JS('STENCIL_BITS') external JSNumber get _stencilBits; int get stencilBits => _stencilBits.toDartDouble.toInt(); } @JS() @staticInterop abstract class DomCanvasImageSource {} @JS() @staticInterop class DomCanvasRenderingContext2D {} extension DomCanvasRenderingContext2DExtension on DomCanvasRenderingContext2D { external DomCanvasElement? get canvas; @JS('fillStyle') external JSAny? get _fillStyle; Object? get fillStyle => _fillStyle?.toObjectShallow; @JS('fillStyle') external set _fillStyle(JSAny? style); set fillStyle(Object? style) => _fillStyle = style?.toJSAnyShallow; @JS('font') external JSString get _font; String get font => _font.toDart; @JS('font') external set _font(JSString value); set font(String value) => _font = value.toJS; @JS('direction') external JSString get _direction; String get direction => _direction.toDart; @JS('direction') external set _direction(JSString value); set direction(String value) => _direction = value.toJS; @JS('lineWidth') external set _lineWidth(JSNumber? value); set lineWidth(num? value) => _lineWidth = value?.toJS; @JS('strokeStyle') external set _strokeStyle(JSAny? value); set strokeStyle(Object? value) => _strokeStyle = value?.toJSAnyShallow; @JS('strokeStyle') external JSAny? get _strokeStyle; Object? get strokeStyle => _strokeStyle?.toObjectShallow; external JSVoid beginPath(); external JSVoid closePath(); @JS('createLinearGradient') external DomCanvasGradient _createLinearGradient( JSNumber x0, JSNumber y0, JSNumber x1, JSNumber y1); DomCanvasGradient createLinearGradient(num x0, num y0, num x1, num y1) => _createLinearGradient(x0.toJS, y0.toJS, x1.toJS, y1.toJS); @JS('createPattern') external DomCanvasPattern? _createPattern( JSAny image, JSString reptitionType); DomCanvasPattern? createPattern(Object image, String reptitionType) => _createPattern(image.toJSAnyShallow, reptitionType.toJS); @JS('createRadialGradient') external DomCanvasGradient _createRadialGradient(JSNumber x0, JSNumber y0, JSNumber r0, JSNumber x1, JSNumber y1, JSNumber r1); DomCanvasGradient createRadialGradient( num x0, num y0, num r0, num x1, num y1, num r1) => _createRadialGradient( x0.toJS, y0.toJS, r0.toJS, x1.toJS, y1.toJS, r1.toJS); @JS('drawImage') external JSVoid _drawImage1( DomCanvasImageSource source, JSNumber dx, JSNumber dy); @JS('drawImage') external JSVoid _drawImage2( DomCanvasImageSource source, JSNumber sx, JSNumber sy, JSNumber sWidth, JSNumber sHeight, JSNumber dx, JSNumber dy, JSNumber dWidth, JSNumber dHeight, ); void drawImage( DomCanvasImageSource source, num srcxOrDstX, num srcyOrDstY, [ num? srcWidth, num? srcHeight, num? dstX, num? dstY, num? dstWidth, num? dstHeight, ]) { if (srcWidth == null) { // In this case the numbers provided are the destination x and y offset. return _drawImage1(source, srcxOrDstX.toJS, srcyOrDstY.toJS); } else { assert(srcHeight != null && dstX != null && dstY != null && dstWidth != null && dstHeight != null); return _drawImage2( source, srcxOrDstX.toJS, srcyOrDstY.toJS, srcWidth.toJS, srcHeight!.toJS, dstX!.toJS, dstY!.toJS, dstWidth!.toJS, dstHeight!.toJS, ); } } @JS('fill') external JSVoid _fill1(); @JS('fill') external JSVoid _fill2(JSAny pathOrWinding); void fill([Object? pathOrWinding]) { if (pathOrWinding == null) { _fill1(); } else { _fill2(pathOrWinding.toJSAnyShallow); } } @JS('fillRect') external JSVoid _fillRect( JSNumber x, JSNumber y, JSNumber width, JSNumber height); void fillRect(num x, num y, num width, num height) => _fillRect(x.toJS, y.toJS, width.toJS, height.toJS); @JS('fillText') external JSVoid _fillText1(JSString text, JSNumber x, JSNumber y); @JS('fillText') external JSVoid _fillText2( JSString text, JSNumber x, JSNumber y, JSNumber maxWidth); void fillText(String text, num x, num y, [num? maxWidth]) { if (maxWidth == null) { _fillText1(text.toJS, x.toJS, y.toJS); } else { _fillText2(text.toJS, x.toJS, y.toJS, maxWidth.toJS); } } @JS('getImageData') external DomImageData _getImageData( JSNumber x, JSNumber y, JSNumber sw, JSNumber sh); DomImageData getImageData(int x, int y, int sw, int sh) => _getImageData(x.toJS, y.toJS, sw.toJS, sh.toJS); @JS('lineTo') external JSVoid _lineTo(JSNumber x, JSNumber y); void lineTo(num x, num y) => _lineTo(x.toJS, y.toJS); @JS('measureText') external DomTextMetrics _measureText(JSString text); DomTextMetrics measureText(String text) => _measureText(text.toJS); @JS('moveTo') external JSVoid _moveTo(JSNumber x, JSNumber y); void moveTo(num x, num y) => _moveTo(x.toJS, y.toJS); external JSVoid save(); external JSVoid stroke(); @JS('rect') external JSVoid _rect( JSNumber x, JSNumber y, JSNumber width, JSNumber height); void rect(num x, num y, num width, num height) => _rect(x.toJS, y.toJS, width.toJS, height.toJS); external JSVoid resetTransform(); external JSVoid restore(); @JS('setTransform') external JSVoid _setTransform( JSNumber a, JSNumber b, JSNumber c, JSNumber d, JSNumber e, JSNumber f); void setTransform(num a, num b, num c, num d, num e, num f) => _setTransform(a.toJS, b.toJS, c.toJS, d.toJS, e.toJS, f.toJS); @JS('transform') external JSVoid _transform( JSNumber a, JSNumber b, JSNumber c, JSNumber d, JSNumber e, JSNumber f); void transform(num a, num b, num c, num d, num e, num f) => _transform(a.toJS, b.toJS, c.toJS, d.toJS, e.toJS, f.toJS); @JS('clip') external JSVoid _clip1(); @JS('clip') external JSVoid _clip2(JSAny pathOrWinding); void clip([Object? pathOrWinding]) { if (pathOrWinding == null) { _clip1(); } else { _clip2(pathOrWinding.toJSAnyShallow); } } @JS('scale') external JSVoid _scale(JSNumber x, JSNumber y); void scale(num x, num y) => _scale(x.toJS, y.toJS); @JS('clearRect') external JSVoid _clearRect( JSNumber x, JSNumber y, JSNumber width, JSNumber height); void clearRect(num x, num y, num width, num height) => _clearRect(x.toJS, y.toJS, width.toJS, height.toJS); @JS('translate') external JSVoid _translate(JSNumber x, JSNumber y); void translate(num x, num y) => _translate(x.toJS, y.toJS); @JS('rotate') external JSVoid _rotate(JSNumber angle); void rotate(num angle) => _rotate(angle.toJS); @JS('bezierCurveTo') external JSVoid _bezierCurveTo(JSNumber cp1x, JSNumber cp1y, JSNumber cp2x, JSNumber cp2y, JSNumber x, JSNumber y); void bezierCurveTo(num cp1x, num cp1y, num cp2x, num cp2y, num x, num y) => _bezierCurveTo( cp1x.toJS, cp1y.toJS, cp2x.toJS, cp2y.toJS, x.toJS, y.toJS); @JS('quadraticCurveTo') external JSVoid _quadraticCurveTo( JSNumber cpx, JSNumber cpy, JSNumber x, JSNumber y); void quadraticCurveTo(num cpx, num cpy, num x, num y) => _quadraticCurveTo(cpx.toJS, cpy.toJS, x.toJS, y.toJS); @JS('globalCompositeOperation') external set _globalCompositeOperation(JSString value); set globalCompositeOperation(String value) => _globalCompositeOperation = value.toJS; @JS('lineCap') external set _lineCap(JSString value); set lineCap(String value) => _lineCap = value.toJS; @JS('lineJoin') external set _lineJoin(JSString value); set lineJoin(String value) => _lineJoin = value.toJS; @JS('shadowBlur') external set _shadowBlur(JSNumber value); set shadowBlur(num value) => _shadowBlur = value.toJS; @JS('arc') external JSVoid _arc(JSNumber x, JSNumber y, JSNumber radius, JSNumber startAngle, JSNumber endAngle, JSBoolean antiClockwise); void arc(num x, num y, num radius, num startAngle, num endAngle, [bool antiClockwise = false]) => _arc(x.toJS, y.toJS, radius.toJS, startAngle.toJS, endAngle.toJS, antiClockwise.toJS); @JS('filter') external set _filter(JSString? value); set filter(String? value) => _filter = value?.toJS; @JS('shadowOffsetX') external set _shadowOffsetX(JSNumber? x); set shadowOffsetX(num? x) => _shadowOffsetX = x?.toJS; @JS('shadowOffsetY') external set _shadowOffsetY(JSNumber? y); set shadowOffsetY(num? y) => _shadowOffsetY = y?.toJS; @JS('shadowColor') external set _shadowColor(JSString? value); set shadowColor(String? value) => _shadowColor = value?.toJS; @JS('ellipse') external JSVoid _ellipse( JSNumber x, JSNumber y, JSNumber radiusX, JSNumber radiusY, JSNumber rotation, JSNumber startAngle, JSNumber endAngle, JSBoolean? antiClockwise); void ellipse(num x, num y, num radiusX, num radiusY, num rotation, num startAngle, num endAngle, bool? antiClockwise) => _ellipse(x.toJS, y.toJS, radiusX.toJS, radiusY.toJS, rotation.toJS, startAngle.toJS, endAngle.toJS, antiClockwise?.toJS); @JS('strokeText') external JSVoid _strokeText(JSString text, JSNumber x, JSNumber y); void strokeText(String text, num x, num y) => _strokeText(text.toJS, x.toJS, y.toJS); @JS('globalAlpha') external set _globalAlpha(JSNumber? value); set globalAlpha(num? value) => _globalAlpha = value?.toJS; } @JS() @staticInterop class DomCanvasRenderingContextWebGl {} extension DomCanvasRenderingContextWebGlExtension on DomCanvasRenderingContextWebGl { @JS('isContextLost') external JSBoolean _isContextLost(); bool isContextLost() => _isContextLost().toDart; } @JS() @staticInterop class DomCanvasRenderingContextBitmapRenderer {} extension DomCanvasRenderingContextBitmapRendererExtension on DomCanvasRenderingContextBitmapRenderer { external void transferFromImageBitmap(DomImageBitmap? bitmap); } @JS('ImageData') @staticInterop class DomImageData { external factory DomImageData._(JSAny? data, JSNumber sw, JSNumber sh); external factory DomImageData._empty(JSNumber sw, JSNumber sh); } DomImageData createDomImageData(Object data, int sw, int sh) => DomImageData._(data.toJSAnyShallow, sw.toJS, sh.toJS); DomImageData createBlankDomImageData(int sw, int sh) => DomImageData._empty(sw.toJS, sh.toJS); extension DomImageDataExtension on DomImageData { @JS('data') external JSUint8ClampedArray get _data; Uint8ClampedList get data => _data.toDart; } @JS('ImageBitmap') @staticInterop class DomImageBitmap {} extension DomImageBitmapExtension on DomImageBitmap { external JSNumber get width; external JSNumber get height; external void close(); } @JS() @staticInterop class DomCanvasPattern {} @JS() @staticInterop class DomCanvasGradient {} extension DomCanvasGradientExtension on DomCanvasGradient { @JS('addColorStop') external JSVoid _addColorStop(JSNumber offset, JSString color); void addColorStop(num offset, String color) => _addColorStop(offset.toJS, color.toJS); } @JS() @staticInterop class DomXMLHttpRequestEventTarget extends DomEventTarget {} Future<DomResponse> rawHttpGet(String url) => js_util.promiseToFuture<DomResponse>(domWindow._fetch1(url.toJS)); typedef MockHttpFetchResponseFactory = Future<MockHttpFetchResponse?> Function( String url); MockHttpFetchResponseFactory? mockHttpFetchResponseFactory; /// Makes an HTTP GET request to the given [url] and returns the response. /// /// If the request fails, throws [HttpFetchError]. HTTP error statuses, such as /// 404 and 500 are not treated as request failures. In those cases the HTTP /// part did succeed and correctly passed the HTTP status down from the server /// to the client. Those statuses represent application-level errors that need /// extra interpretation to decide if they are "failures" or not. See /// [HttpFetchResponse.hasPayload] and [HttpFetchResponse.payload]. /// /// This function is designed to handle the most general cases. If the default /// payload handling, including error checking, is sufficient, consider using /// convenience functions [httpFetchByteBuffer], [httpFetchJson], or /// [httpFetchText] instead. Future<HttpFetchResponse> httpFetch(String url) async { if (mockHttpFetchResponseFactory != null) { final MockHttpFetchResponse? response = await mockHttpFetchResponseFactory!(url); if (response != null) { return response; } } try { final DomResponse domResponse = await rawHttpGet(url); return HttpFetchResponseImpl._(url, domResponse); } catch (requestError) { throw HttpFetchError(url, requestError: requestError); } } Future<DomResponse> _rawHttpPost(String url, String data) => js_util.promiseToFuture<DomResponse>(domWindow._fetch2( url.toJS, <String, Object?>{ 'method': 'POST', 'headers': <String, Object?>{ 'Content-Type': 'text/plain', }, 'body': data, }.toJSAnyDeep)); /// Sends a [data] string as HTTP POST request to [url]. /// /// The web engine does not make POST requests in production code because it is /// designed to be able to run web apps served from plain file servers, so this /// is meant for tests only. @visibleForTesting Future<HttpFetchResponse> testOnlyHttpPost(String url, String data) async { try { final DomResponse domResponse = await _rawHttpPost(url, data); return HttpFetchResponseImpl._(url, domResponse); } catch (requestError) { throw HttpFetchError(url, requestError: requestError); } } /// Convenience function for making a fetch request and getting the data as a /// [ByteBuffer], when the default error handling mechanism is sufficient. Future<ByteBuffer> httpFetchByteBuffer(String url) async { final HttpFetchResponse response = await httpFetch(url); return response.asByteBuffer(); } /// Convenience function for making a fetch request and getting the data as a /// JSON object, when the default error handling mechanism is sufficient. Future<Object?> httpFetchJson(String url) async { final HttpFetchResponse response = await httpFetch(url); return response.json(); } /// Convenience function for making a fetch request and getting the data as a /// [String], when the default error handling mechanism is sufficient. Future<String> httpFetchText(String url) async { final HttpFetchResponse response = await httpFetch(url); return response.text(); } /// Successful result of [httpFetch]. abstract class HttpFetchResponse { /// The URL passed to [httpFetch] that returns this response. String get url; /// The HTTP response status, such as 200 or 404. int get status; /// The payload length of this response parsed from the "Content-Length" HTTP /// header. /// /// Returns null if "Content-Length" is missing. int? get contentLength; /// Return true if this response has a [payload]. /// /// Returns false if this response does not have a payload and therefore it is /// unsafe to call the [payload] getter. bool get hasPayload; /// Returns the payload of this response. /// /// It is only safe to call this getter if [hasPayload] is true. If /// [hasPayload] is false, throws [HttpFetchNoPayloadError]. HttpFetchPayload get payload; } /// Convenience methods for simple cases when the default error checking /// mechanisms are sufficient. extension HttpFetchResponseExtension on HttpFetchResponse { /// Reads the payload a chunk at a time. /// /// Combined with [HttpFetchResponse.contentLength], this can be used to /// implement various "progress bar" functionality. Future<void> read<T>(HttpFetchReader<T> reader) { return payload.read(reader); } /// Returns the data as a [ByteBuffer]. Future<ByteBuffer> asByteBuffer() { return payload.asByteBuffer(); } /// Returns the data as a [Uint8List]. Future<Uint8List> asUint8List() async { return (await payload.asByteBuffer()).asUint8List(); } /// Returns the data parsed as JSON. Future<dynamic> json() { return payload.json(); } /// Return the data as a string. Future<String> text() { return payload.text(); } } class HttpFetchResponseImpl implements HttpFetchResponse { HttpFetchResponseImpl._(this.url, this._domResponse); @override final String url; final DomResponse _domResponse; @override int get status => _domResponse.status; @override int? get contentLength { final String? header = _domResponse.headers.get('Content-Length'); if (header == null) { return null; } return int.tryParse(header); } @override bool get hasPayload { final bool accepted = status >= 200 && status < 300; final bool fileUri = status == 0; final bool notModified = status == 304; final bool unknownRedirect = status > 307 && status < 400; return accepted || fileUri || notModified || unknownRedirect; } @override HttpFetchPayload get payload { if (!hasPayload) { throw HttpFetchNoPayloadError(url, status: status); } return HttpFetchPayloadImpl._(_domResponse); } } /// A fake implementation of [HttpFetchResponse] for testing. class MockHttpFetchResponse implements HttpFetchResponse { MockHttpFetchResponse({ required this.url, required this.status, this.contentLength, HttpFetchPayload? payload, }) : _payload = payload; final HttpFetchPayload? _payload; @override final String url; @override final int status; @override final int? contentLength; @override bool get hasPayload => _payload != null; @override HttpFetchPayload get payload => _payload!; } typedef HttpFetchReader<T> = void Function(T chunk); /// Data returned with a [HttpFetchResponse]. abstract class HttpFetchPayload { /// Reads the payload a chunk at a time. /// /// Combined with [HttpFetchResponse.contentLength], this can be used to /// implement various "progress bar" functionality. Future<void> read<T>(HttpFetchReader<T> reader); /// Returns the data as a [ByteBuffer]. Future<ByteBuffer> asByteBuffer(); /// Returns the data parsed as JSON. Future<dynamic> json(); /// Return the data as a string. Future<String> text(); } class HttpFetchPayloadImpl implements HttpFetchPayload { HttpFetchPayloadImpl._(this._domResponse); final DomResponse _domResponse; @override Future<void> read<T>(HttpFetchReader<T> callback) async { final _DomReadableStream stream = _domResponse.body; final _DomStreamReader reader = stream.getReader(); while (true) { final _DomStreamChunk chunk = await reader.read(); if (chunk.done) { break; } callback(chunk.value as T); } } /// Returns the data as a [ByteBuffer]. @override Future<ByteBuffer> asByteBuffer() async { return (await _domResponse.arrayBuffer())! as ByteBuffer; } /// Returns the data parsed as JSON. @override Future<dynamic> json() => _domResponse.json(); /// Return the data as a string. @override Future<String> text() => _domResponse.text(); } typedef MockOnRead = Future<void> Function<T>(HttpFetchReader<T> callback); class MockHttpFetchPayload implements HttpFetchPayload { MockHttpFetchPayload({ required ByteBuffer byteBuffer, int? chunkSize, }) : _byteBuffer = byteBuffer, _chunkSize = chunkSize ?? 64; final ByteBuffer _byteBuffer; final int _chunkSize; @override Future<void> read<T>(HttpFetchReader<T> callback) async { final int totalLength = _byteBuffer.lengthInBytes; int currentIndex = 0; while (currentIndex < totalLength) { final int chunkSize = math.min(_chunkSize, totalLength - currentIndex); final Uint8List chunk = Uint8List.sublistView( _byteBuffer.asByteData(), currentIndex, currentIndex + chunkSize); callback(chunk.toJS as T); currentIndex += chunkSize; } } @override Future<ByteBuffer> asByteBuffer() async => _byteBuffer; @override Future<dynamic> json() async => throw AssertionError('json not supported by mock'); @override Future<String> text() async => throw AssertionError('text not supported by mock'); } /// Indicates a missing HTTP payload when one was expected, such as when /// [HttpFetchResponse.payload] was called. /// /// Unlike [HttpFetchError], this error happens when the HTTP request/response /// succeeded, but the response type is not the kind that provides useful /// payload, such as 404, or 500. class HttpFetchNoPayloadError implements Exception { /// Creates an exception from a successful HTTP request, but an unsuccessful /// HTTP response code, such as 404 or 500. HttpFetchNoPayloadError(this.url, {required this.status}); /// HTTP request URL for asset. final String url; /// If the HTTP request succeeded, the HTTP response status. /// /// Null if the HTTP request failed. final int status; @override String toString() { return 'Flutter Web engine failed to fetch "$url". HTTP request succeeded, ' 'but the server responded with HTTP status $status.'; } } /// Indicates a failure trying to fetch a [url]. /// /// Unlike [HttpFetchNoPayloadError] this error indicates that there was no HTTP /// response and the roundtrip what interrupted by something else, like a loss /// of network connectivity, or request being interrupted by the OS, a browser /// CORS policy, etc. In particular, there's not even a HTTP status code to /// report, such as 200, 404, or 500. class HttpFetchError implements Exception { /// Creates an exception from a failed HTTP request. HttpFetchError(this.url, {required this.requestError}); /// HTTP request URL for asset. final String url; /// The underlying network error that prevented [httpFetch] from succeeding. final Object requestError; @override String toString() { return 'Flutter Web engine failed to complete HTTP request to fetch ' '"$url": $requestError'; } } @JS() @staticInterop class DomResponse {} extension DomResponseExtension on DomResponse { @JS('status') external JSNumber get _status; int get status => _status.toDartInt; external DomHeaders get headers; external _DomReadableStream get body; @JS('arrayBuffer') external JSPromise<JSAny?> _arrayBuffer(); Future<Object?> arrayBuffer() => js_util.promiseToFuture<Object?>(_arrayBuffer()); @JS('json') external JSPromise<JSAny?> _json(); Future<Object?> json() => js_util.promiseToFuture<Object?>(_json()); @JS('text') external JSPromise<JSAny?> _text(); Future<String> text() => js_util.promiseToFuture<String>(_text()); } @JS() @staticInterop class DomHeaders {} extension DomHeadersExtension on DomHeaders { @JS('get') external JSString? _get(JSString? headerName); String? get(String? headerName) => _get(headerName?.toJS)?.toDart; } @JS() @staticInterop class _DomReadableStream {} extension _DomReadableStreamExtension on _DomReadableStream { external _DomStreamReader getReader(); } @JS() @staticInterop class _DomStreamReader {} extension _DomStreamReaderExtension on _DomStreamReader { @JS('read') external JSPromise<JSAny?> _read(); Future<_DomStreamChunk> read() => js_util.promiseToFuture<_DomStreamChunk>(_read()); } @JS() @staticInterop class _DomStreamChunk {} extension _DomStreamChunkExtension on _DomStreamChunk { external JSAny? get value; @JS('done') external JSBoolean get _done; bool get done => _done.toDart; } @JS() @staticInterop class DomCharacterData extends DomNode {} @JS() @staticInterop class DomText extends DomCharacterData {} DomText createDomText(String data) => domDocument.createTextNode(data); @JS() @staticInterop class DomTextMetrics {} extension DomTextMetricsExtension on DomTextMetrics { @JS('width') external JSNumber? get _width; double? get width => _width?.toDartDouble; } @JS() @staticInterop class DomException { static const String notSupported = 'NotSupportedError'; } extension DomExceptionExtension on DomException { @JS('name') external JSString get _name; String get name => _name.toDart; } @JS() @staticInterop class DomRectReadOnly {} extension DomRectReadOnlyExtension on DomRectReadOnly { @JS('x') external JSNumber get _x; double get x => _x.toDartDouble; @JS('y') external JSNumber get _y; double get y => _y.toDartDouble; @JS('width') external JSNumber get _width; double get width => _width.toDartDouble; @JS('height') external JSNumber get _height; double get height => _height.toDartDouble; @JS('top') external JSNumber get _top; double get top => _top.toDartDouble; @JS('right') external JSNumber get _right; double get right => _right.toDartDouble; @JS('bottom') external JSNumber get _bottom; double get bottom => _bottom.toDartDouble; @JS('left') external JSNumber get _left; double get left => _left.toDartDouble; } DomRect createDomRectFromPoints(DomPoint a, DomPoint b) { final num left = math.min(a.x, b.x); final num width = math.max(a.x, b.x) - left; final num top = math.min(a.y, b.y); final num height = math.max(a.y, b.y) - top; return DomRect(left.toJS, top.toJS, width.toJS, height.toJS); } @JS('DOMRect') @staticInterop class DomRect extends DomRectReadOnly { external factory DomRect( JSNumber left, JSNumber top, JSNumber width, JSNumber height); } @JS('FontFace') @staticInterop class DomFontFace { external factory DomFontFace._args2(JSString family, JSAny source); external factory DomFontFace._args3( JSString family, JSAny source, JSAny descriptors); } DomFontFace createDomFontFace(String family, Object source, [Map<Object?, Object?>? descriptors]) { if (descriptors == null) { return DomFontFace._args2(family.toJS, source.toJSAnyShallow); } else { return DomFontFace._args3( family.toJS, source.toJSAnyShallow, descriptors.toJSAnyDeep); } } extension DomFontFaceExtension on DomFontFace { @JS('load') external JSPromise<JSAny?> _load(); Future<DomFontFace> load() => js_util.promiseToFuture(_load()); @JS('family') external JSString? get _family; String? get family => _family?.toDart; @JS('weight') external JSString? get _weight; String? get weight => _weight?.toDart; @JS('status') external JSString? get _status; String? get status => _status?.toDart; } @JS() @staticInterop class DomFontFaceSet extends DomEventTarget {} extension DomFontFaceSetExtension on DomFontFaceSet { external DomFontFaceSet? add(DomFontFace font); external JSVoid clear(); @JS('forEach') external JSVoid _forEach(JSFunction callback); void forEach(DomFontFaceSetForEachCallback callback) => _forEach(callback.toJS); } typedef DomFontFaceSetForEachCallback = void Function( DomFontFace fontFace, DomFontFace fontFaceAgain, DomFontFaceSet set); @JS() @staticInterop class DomVisualViewport extends DomEventTarget {} extension DomVisualViewportExtension on DomVisualViewport { @JS('height') external JSNumber? get _height; double? get height => _height?.toDartDouble; @JS('width') external JSNumber? get _width; double? get width => _width?.toDartDouble; } @JS() @staticInterop class DomHTMLTextAreaElement extends DomHTMLElement {} DomHTMLTextAreaElement createDomHTMLTextAreaElement() => domDocument.createElement('textarea') as DomHTMLTextAreaElement; extension DomHTMLTextAreaElementExtension on DomHTMLTextAreaElement { @JS('value') external set _value(JSString? value); set value(String? value) => _value = value?.toJS; external JSVoid select(); @JS('placeholder') external set _placeholder(JSString? value); set placeholder(String? value) => _placeholder = value?.toJS; @JS('name') external set _name(JSString value); set name(String value) => _name = value.toJS; @JS('selectionDirection') external JSString? get _selectionDirection; String? get selectionDirection => _selectionDirection?.toDart; @JS('selectionStart') external JSNumber? get _selectionStart; double? get selectionStart => _selectionStart?.toDartDouble; @JS('selectionEnd') external JSNumber? get _selectionEnd; double? get selectionEnd => _selectionEnd?.toDartDouble; @JS('selectionStart') external set _selectionStart(JSNumber? value); set selectionStart(double? value) => _selectionStart = value?.toJS; @JS('selectionEnd') external set _selectionEnd(JSNumber? value); set selectionEnd(double? value) => _selectionEnd = value?.toJS; @JS('value') external JSString? get _value; String? get value => _value?.toDart; @JS('setSelectionRange') external JSVoid _setSelectionRange1(JSNumber start, JSNumber end); @JS('setSelectionRange') external JSVoid _setSelectionRange2( JSNumber start, JSNumber end, JSString direction); void setSelectionRange(int start, int end, [String? direction]) { if (direction == null) { _setSelectionRange1(start.toJS, end.toJS); } else { _setSelectionRange2(start.toJS, end.toJS, direction.toJS); } } @JS('name') external JSString get _name; String get name => _name.toDart; @JS('placeholder') external JSString get _placeholder; String get placeholder => _placeholder.toDart; } @JS() @staticInterop class DomClipboard extends DomEventTarget {} extension DomClipboardExtension on DomClipboard { @JS('readText') external JSPromise<JSAny?> _readText(); Future<String> readText() => js_util.promiseToFuture<String>(_readText()); @JS('writeText') external JSPromise<JSAny?> _writeText(JSString data); Future<dynamic> writeText(String data) => js_util.promiseToFuture(_writeText(data.toJS)); } @JS() @staticInterop class DomUIEvent extends DomEvent {} @JS('KeyboardEvent') @staticInterop class DomKeyboardEvent extends DomUIEvent { external factory DomKeyboardEvent.arg1(JSString type); external factory DomKeyboardEvent.arg2(JSString type, JSAny initDict); } extension DomKeyboardEventExtension on DomKeyboardEvent { @JS('altKey') external JSBoolean get _altKey; bool get altKey => _altKey.toDart; @JS('code') external JSString? get _code; String? get code => _code?.toDart; @JS('ctrlKey') external JSBoolean get _ctrlKey; bool get ctrlKey => _ctrlKey.toDart; @JS('key') external JSString? get _key; String? get key => _key?.toDart; @JS('keyCode') external JSNumber get _keyCode; double get keyCode => _keyCode.toDartDouble; @JS('location') external JSNumber get _location; double get location => _location.toDartDouble; @JS('metaKey') external JSBoolean get _metaKey; bool get metaKey => _metaKey.toDart; @JS('repeat') external JSBoolean? get _repeat; bool? get repeat => _repeat?.toDart; @JS('shiftKey') external JSBoolean get _shiftKey; bool get shiftKey => _shiftKey.toDart; @JS('isComposing') external JSBoolean get _isComposing; bool get isComposing => _isComposing.toDart; @JS('getModifierState') external JSBoolean _getModifierState(JSString keyArg); bool getModifierState(String keyArg) => _getModifierState(keyArg.toJS).toDart; } DomKeyboardEvent createDomKeyboardEvent(String type, [Map<dynamic, dynamic>? init]) { if (init == null) { return DomKeyboardEvent.arg1(type.toJS); } else { return DomKeyboardEvent.arg2(type.toJS, init.toJSAnyDeep); } } @JS() @staticInterop class DomHistory {} extension DomHistoryExtension on DomHistory { @JS('state') external JSAny? get _state; dynamic get state => _state?.toObjectDeep; @JS('go') external JSVoid _go1(); @JS('go') external JSVoid _go2(JSNumber delta); void go([int? delta]) { if (delta == null) { _go1(); } else { _go2(delta.toJS); } } @JS('pushState') external JSVoid _pushState(JSAny? data, JSString title, JSString? url); void pushState(Object? data, String title, String? url) => _pushState(data?.toJSAnyDeep, title.toJS, url?.toJS); @JS('replaceState') external JSVoid _replaceState(JSAny? data, JSString title, JSString? url); void replaceState(Object? data, String title, String? url) => _replaceState(data?.toJSAnyDeep, title.toJS, url?.toJS); } @JS() @staticInterop class DomLocation {} extension DomLocationExtension on DomLocation { @JS('pathname') external JSString? get _pathname; String? get pathname => _pathname?.toDart; @JS('search') external JSString? get _search; String? get search => _search?.toDart; @JS('hash') external JSString get _hash; // We have to change the name here because 'hash' is inherited from [Object]. String get locationHash => _hash.toDart; @JS('origin') external JSString get _origin; String get origin => _origin.toDart; @JS('href') external JSString get _href; String get href => _href.toDart; } @JS('PopStateEvent') @staticInterop class DomPopStateEvent extends DomEvent { external factory DomPopStateEvent.arg1(JSString type); external factory DomPopStateEvent.arg2(JSString type, JSAny initDict); } DomPopStateEvent createDomPopStateEvent( String type, Map<Object?, Object?>? eventInitDict) { if (eventInitDict == null) { return DomPopStateEvent.arg1(type.toJS); } else { return DomPopStateEvent.arg2(type.toJS, eventInitDict.toJSAnyDeep); } } extension DomPopStateEventExtension on DomPopStateEvent { @JS('state') external JSAny? get _state; dynamic get state => _state?.toObjectDeep; } @JS() @staticInterop class DomURL {} extension DomURLExtension on DomURL { @JS('createObjectURL') external JSString _createObjectURL(JSAny object); String createObjectURL(Object object) => _createObjectURL(object.toJSAnyShallow).toDart; @JS('revokeObjectURL') external JSVoid _revokeObjectURL(JSString url); void revokeObjectURL(String url) => _revokeObjectURL(url.toJS); } @JS('Blob') @staticInterop class DomBlob { external factory DomBlob(JSArray<JSAny?> parts); external factory DomBlob.withOptions(JSArray<JSAny?> parts, JSAny options); } extension DomBlobExtension on DomBlob { external JSPromise<JSAny?> arrayBuffer(); } DomBlob createDomBlob(List<Object?> parts, [Map<String, dynamic>? options]) { if (options == null) { return DomBlob(parts.toJSAnyShallow as JSArray<JSAny?>); } else { return DomBlob.withOptions( parts.toJSAnyShallow as JSArray<JSAny?>, options.toJSAnyDeep); } } typedef DomMutationCallback = void Function( JSArray<JSAny?> mutation, DomMutationObserver observer); @JS('MutationObserver') @staticInterop class DomMutationObserver { external factory DomMutationObserver(JSFunction callback); } DomMutationObserver createDomMutationObserver(DomMutationCallback callback) => DomMutationObserver(callback.toJS); extension DomMutationObserverExtension on DomMutationObserver { external JSVoid disconnect(); @JS('observe') external JSVoid _observe(DomNode target, JSAny options); void observe(DomNode target, {bool? childList, bool? attributes, List<String>? attributeFilter}) { final Map<String, dynamic> options = <String, dynamic>{ if (childList != null) 'childList': childList, if (attributes != null) 'attributes': attributes, if (attributeFilter != null) 'attributeFilter': attributeFilter }; return _observe(target, options.toJSAnyDeep); } } @JS() @staticInterop class DomMutationRecord {} extension DomMutationRecordExtension on DomMutationRecord { @JS('addedNodes') external _DomList? get _addedNodes; Iterable<DomNode>? get addedNodes { final _DomList? list = _addedNodes; if (list == null) { return null; } return createDomListWrapper<DomNode>(list); } @JS('removedNodes') external _DomList? get _removedNodes; Iterable<DomNode>? get removedNodes { final _DomList? list = _removedNodes; if (list == null) { return null; } return createDomListWrapper<DomNode>(list); } @JS('attributeName') external JSString? get _attributeName; String? get attributeName => _attributeName?.toDart; @JS('type') external JSString? get _type; String? get type => _type?.toDart; } @JS() @staticInterop class DomMediaQueryList extends DomEventTarget {} extension DomMediaQueryListExtension on DomMediaQueryList { @JS('matches') external JSBoolean get _matches; bool get matches => _matches.toDart; @JS('addListener') external JSVoid addListener(DomEventListener? listener); @JS('removeListener') external JSVoid removeListener(DomEventListener? listener); } @JS() @staticInterop class DomMediaQueryListEvent extends DomEvent {} extension DomMediaQueryListEventExtension on DomMediaQueryListEvent { @JS('matches') external JSBoolean? get _matches; bool? get matches => _matches?.toDart; } @JS('Path2D') @staticInterop class DomPath2D { external factory DomPath2D.arg1(); external factory DomPath2D.arg2(JSAny path); } DomPath2D createDomPath2D([Object? path]) { if (path == null) { return DomPath2D.arg1(); } else { return DomPath2D.arg2(path.toJSAnyShallow); } } @JS('InputEvent') @staticInterop class DomInputEvent extends DomUIEvent { external factory DomInputEvent.arg1(JSString type); external factory DomInputEvent.arg2(JSString type, JSAny initDict); } @JS('FocusEvent') @staticInterop class DomFocusEvent extends DomUIEvent {} extension DomFocusEventExtension on DomFocusEvent { external DomEventTarget? get relatedTarget; } @JS('MouseEvent') @staticInterop class DomMouseEvent extends DomUIEvent { external factory DomMouseEvent.arg1(JSString type); external factory DomMouseEvent.arg2(JSString type, JSAny initDict); } extension DomMouseEventExtension on DomMouseEvent { @JS('clientX') external JSNumber get _clientX; double get clientX => _clientX.toDartDouble; @JS('clientY') external JSNumber get _clientY; double get clientY => _clientY.toDartDouble; @JS('offsetX') external JSNumber get _offsetX; double get offsetX => _offsetX.toDartDouble; @JS('offsetY') external JSNumber get _offsetY; double get offsetY => _offsetY.toDartDouble; @JS('pageX') external JSNumber get _pageX; double get pageX => _pageX.toDartDouble; @JS('pageY') external JSNumber get _pageY; double get pageY => _pageY.toDartDouble; DomPoint get client => DomPoint(clientX, clientY); DomPoint get offset => DomPoint(offsetX, offsetY); @JS('button') external JSNumber get _button; double get button => _button.toDartDouble; @JS('buttons') external JSNumber? get _buttons; double? get buttons => _buttons?.toDartDouble; @JS('ctrlKey') external JSBoolean get _ctrlKey; bool get ctrlKey => _ctrlKey.toDart; @JS('getModifierState') external JSBoolean _getModifierState(JSString keyArg); bool getModifierState(String keyArg) => _getModifierState(keyArg.toJS).toDart; } DomMouseEvent createDomMouseEvent(String type, [Map<dynamic, dynamic>? init]) { if (init == null) { return DomMouseEvent.arg1(type.toJS); } else { return DomMouseEvent.arg2(type.toJS, init.toJSAnyDeep); } } DomInputEvent createDomInputEvent(String type, [Map<dynamic, dynamic>? init]) { if (init == null) { return DomInputEvent.arg1(type.toJS); } else { return DomInputEvent.arg2(type.toJS, init.toJSAnyDeep); } } @JS('PointerEvent') @staticInterop class DomPointerEvent extends DomMouseEvent { external factory DomPointerEvent.arg1(JSString type); external factory DomPointerEvent.arg2(JSString type, JSAny initDict); } extension DomPointerEventExtension on DomPointerEvent { @JS('pointerId') external JSNumber? get _pointerId; double? get pointerId => _pointerId?.toDartDouble; @JS('pointerType') external JSString? get _pointerType; String? get pointerType => _pointerType?.toDart; @JS('pressure') external JSNumber? get _pressure; double? get pressure => _pressure?.toDartDouble; @JS('tiltX') external JSNumber? get _tiltX; double? get tiltX => _tiltX?.toDartDouble; @JS('tiltY') external JSNumber? get _tiltY; double? get tiltY => _tiltY?.toDartDouble; @JS('getCoalescedEvents') external JSArray<JSAny?> _getCoalescedEvents(); List<DomPointerEvent> getCoalescedEvents() => _getCoalescedEvents().toDart.cast<DomPointerEvent>(); } DomPointerEvent createDomPointerEvent(String type, [Map<dynamic, dynamic>? init]) { if (init == null) { return DomPointerEvent.arg1(type.toJS); } else { return DomPointerEvent.arg2(type.toJS, init.toJSAnyDeep); } } @JS('WheelEvent') @staticInterop class DomWheelEvent extends DomMouseEvent { external factory DomWheelEvent.arg1(JSString type); external factory DomWheelEvent.arg2(JSString type, JSAny initDict); } extension DomWheelEventExtension on DomWheelEvent { @JS('deltaX') external JSNumber get _deltaX; double get deltaX => _deltaX.toDartDouble; @JS('deltaY') external JSNumber get _deltaY; double get deltaY => _deltaY.toDartDouble; @JS('wheelDeltaX') external JSNumber? get _wheelDeltaX; double? get wheelDeltaX => _wheelDeltaX?.toDartDouble; @JS('wheelDeltaY') external JSNumber? get _wheelDeltaY; double? get wheelDeltaY => _wheelDeltaY?.toDartDouble; @JS('deltaMode') external JSNumber get _deltaMode; double get deltaMode => _deltaMode.toDartDouble; } DomWheelEvent createDomWheelEvent(String type, [Map<dynamic, dynamic>? init]) { if (init == null) { return DomWheelEvent.arg1(type.toJS); } else { return DomWheelEvent.arg2(type.toJS, init.toJSAnyDeep); } } @JS('TouchEvent') @staticInterop class DomTouchEvent extends DomUIEvent { external factory DomTouchEvent.arg1(JSString type); external factory DomTouchEvent.arg2(JSString type, JSAny initDict); } extension DomTouchEventExtension on DomTouchEvent { @JS('altKey') external JSBoolean get _altKey; bool get altKey => _altKey.toDart; @JS('ctrlKey') external JSBoolean get _ctrlKey; bool get ctrlKey => _ctrlKey.toDart; @JS('metaKey') external JSBoolean get _metaKey; bool get metaKey => _metaKey.toDart; @JS('shiftKey') external JSBoolean get _shiftKey; bool get shiftKey => _shiftKey.toDart; @JS('changedTouches') external _DomTouchList get _changedTouches; Iterable<DomTouch> get changedTouches => createDomTouchListWrapper<DomTouch>(_changedTouches); } @JS('Touch') @staticInterop class DomTouch { external factory DomTouch.arg1(); external factory DomTouch.arg2(JSAny initDict); } extension DomTouchExtension on DomTouch { @JS('identifier') external JSNumber? get _identifier; double? get identifier => _identifier?.toDartDouble; @JS('clientX') external JSNumber get _clientX; double get clientX => _clientX.toDartDouble; @JS('clientY') external JSNumber get _clientY; double get clientY => _clientY.toDartDouble; DomPoint get client => DomPoint(clientX, clientY); } DomTouch createDomTouch([Map<dynamic, dynamic>? init]) { if (init == null) { return DomTouch.arg1(); } else { return DomTouch.arg2(init.toJSAnyDeep); } } @JS('CompositionEvent') @staticInterop class DomCompositionEvent extends DomUIEvent { external factory DomCompositionEvent.arg1(JSString type); external factory DomCompositionEvent.arg2(JSString type, JSAny initDict); } extension DomCompositionEventExtension on DomCompositionEvent { @JS('data') external JSString? get _data; String? get data => _data?.toDart; } DomCompositionEvent createDomCompositionEvent(String type, [Map<dynamic, dynamic>? options]) { if (options == null) { return DomCompositionEvent.arg1(type.toJS); } else { return DomCompositionEvent.arg2(type.toJS, options.toJSAnyDeep); } } @JS() @staticInterop class DomHTMLInputElement extends DomHTMLElement {} extension DomHTMLInputElementExtension on DomHTMLInputElement { @JS('type') external set _type(JSString? value); set type(String? value) => _type = value?.toJS; @JS('max') external set _max(JSString? value); set max(String? value) => _max = value?.toJS; @JS('min') external set _min(JSString value); set min(String value) => _min = value.toJS; @JS('value') external set _value(JSString? value); set value(String? v) => _value = v?.toJS; @JS('value') external JSString? get _value; String? get value => _value?.toDart; @JS('disabled') external JSBoolean? get _disabled; bool? get disabled => _disabled?.toDart; @JS('disabled') external set _disabled(JSBoolean? value); set disabled(bool? value) => _disabled = value?.toJS; @JS('placeholder') external set _placeholder(JSString? value); set placeholder(String? value) => _placeholder = value?.toJS; @JS('name') external set _name(JSString? value); set name(String? value) => _name = value?.toJS; @JS('autocomplete') external set _autocomplete(JSString value); set autocomplete(String value) => _autocomplete = value.toJS; @JS('selectionDirection') external JSString? get _selectionDirection; String? get selectionDirection => _selectionDirection?.toDart; @JS('selectionStart') external JSNumber? get _selectionStart; double? get selectionStart => _selectionStart?.toDartDouble; @JS('selectionEnd') external JSNumber? get _selectionEnd; double? get selectionEnd => _selectionEnd?.toDartDouble; @JS('selectionStart') external set _selectionStart(JSNumber? value); set selectionStart(double? value) => _selectionStart = value?.toJS; @JS('selectionEnd') external set _selectionEnd(JSNumber? value); set selectionEnd(double? value) => _selectionEnd = value?.toJS; @JS('setSelectionRange') external JSVoid _setSelectionRange1(JSNumber start, JSNumber end); @JS('setSelectionRange') external JSVoid _setSelectionRange2( JSNumber start, JSNumber end, JSString direction); void setSelectionRange(int start, int end, [String? direction]) { if (direction == null) { _setSelectionRange1(start.toJS, end.toJS); } else { _setSelectionRange2(start.toJS, end.toJS, direction.toJS); } } @JS('autocomplete') external JSString get _autocomplete; String get autocomplete => _autocomplete.toDart; @JS('name') external JSString? get _name; String? get name => _name?.toDart; @JS('type') external JSString? get _type; String? get type => _type?.toDart; @JS('placeholder') external JSString get _placeholder; String get placeholder => _placeholder.toDart; } DomHTMLInputElement createDomHTMLInputElement() => domDocument.createElement('input') as DomHTMLInputElement; @JS() @staticInterop class DomTokenList {} extension DomTokenListExtension on DomTokenList { @JS('add') external JSVoid _add(JSString value); void add(String value) => _add(value.toJS); @JS('remove') external JSVoid _remove(JSString value); void remove(String value) => _remove(value.toJS); @JS('contains') external JSBoolean _contains(JSString token); bool contains(String token) => _contains(token.toJS).toDart; } @JS() @staticInterop class DomHTMLFormElement extends DomHTMLElement {} extension DomHTMLFormElementExtension on DomHTMLFormElement { @JS('noValidate') external set _noValidate(JSBoolean? value); set noValidate(bool? value) => _noValidate = value?.toJS; @JS('method') external set _method(JSString? value); set method(String? value) => _method = value?.toJS; @JS('action') external set _action(JSString? value); set action(String? value) => _action = value?.toJS; } DomHTMLFormElement createDomHTMLFormElement() => domDocument.createElement('form') as DomHTMLFormElement; @JS() @staticInterop class DomHTMLLabelElement extends DomHTMLElement {} DomHTMLLabelElement createDomHTMLLabelElement() => domDocument.createElement('label') as DomHTMLLabelElement; @JS('OffscreenCanvas') @staticInterop class DomOffscreenCanvas extends DomEventTarget { external factory DomOffscreenCanvas(JSNumber width, JSNumber height); } extension DomOffscreenCanvasExtension on DomOffscreenCanvas { @JS('height') external JSNumber? get _height; double? get height => _height?.toDartDouble; @JS('width') external JSNumber? get _width; double? get width => _width?.toDartDouble; @JS('height') external set _height(JSNumber? value); set height(double? value) => _height = value?.toJS; @JS('width') external set _width(JSNumber? value); set width(double? value) => _width = value?.toJS; @JS('getContext') external JSAny? _getContext1(JSString contextType); @JS('getContext') external JSAny? _getContext2(JSString contextType, JSAny attributes); Object? getContext(String contextType, [Map<dynamic, dynamic>? attributes]) { if (attributes == null) { return _getContext1(contextType.toJS); } else { return _getContext2(contextType.toJS, attributes.toJSAnyDeep); } } WebGLContext getGlContext(int majorVersion) { if (majorVersion == 1) { return getContext('webgl')! as WebGLContext; } return getContext('webgl2')! as WebGLContext; } @JS('convertToBlob') external JSPromise<JSAny?> _convertToBlob1(); @JS('convertToBlob') external JSPromise<JSAny?> _convertToBlob2(JSAny options); Future<DomBlob> convertToBlob([Map<Object?, Object?>? options]) { final JSPromise<JSAny?> blob; if (options == null) { blob = _convertToBlob1(); } else { blob = _convertToBlob2(options.toJSAnyDeep); } return js_util.promiseToFuture(blob); } @JS('transferToImageBitmap') external JSAny? _transferToImageBitmap(); DomImageBitmap transferToImageBitmap() => _transferToImageBitmap()! as DomImageBitmap; } DomOffscreenCanvas createDomOffscreenCanvas(int width, int height) => DomOffscreenCanvas(width.toJS, height.toJS); @JS('FileReader') @staticInterop class DomFileReader extends DomEventTarget { external factory DomFileReader(); } extension DomFileReaderExtension on DomFileReader { external JSVoid readAsDataURL(DomBlob blob); } DomFileReader createDomFileReader() => DomFileReader(); @JS() @staticInterop class DomDocumentFragment extends DomNode {} extension DomDocumentFragmentExtension on DomDocumentFragment { external DomElement? get firstElementChild; external DomElement? get lastElementChild; external JSVoid prepend(DomNode node); @JS('querySelector') external DomElement? _querySelector(JSString selectors); DomElement? querySelector(String selectors) => _querySelector(selectors.toJS); @JS('querySelectorAll') external _DomList _querySelectorAll(JSString selectors); Iterable<DomElement> querySelectorAll(String selectors) => createDomListWrapper<DomElement>(_querySelectorAll(selectors.toJS)); } @JS() @staticInterop class DomShadowRoot extends DomDocumentFragment {} extension DomShadowRootExtension on DomShadowRoot { external DomElement? get activeElement; external DomElement? get host; @JS('mode') external JSString? get _mode; String? get mode => _mode?.toDart; @JS('delegatesFocus') external JSBoolean? get _delegatesFocus; bool? get delegatesFocus => _delegatesFocus?.toDart; @JS('elementFromPoint') external DomElement? _elementFromPoint(JSNumber x, JSNumber y); DomElement? elementFromPoint(int x, int y) => _elementFromPoint(x.toJS, y.toJS); } @JS() @staticInterop class DomStyleSheet {} @JS() @staticInterop class DomCSSStyleSheet extends DomStyleSheet {} extension DomCSSStyleSheetExtension on DomCSSStyleSheet { @JS('cssRules') external _DomList get _cssRules; Iterable<DomCSSRule> get cssRules => createDomListWrapper<DomCSSRule>(_cssRules); @JS('insertRule') external JSNumber _insertRule1(JSString rule); @JS('insertRule') external JSNumber _insertRule2(JSString rule, JSNumber index); double insertRule(String rule, [int? index]) { if (index == null) { return _insertRule1(rule.toJS).toDartDouble; } else { return _insertRule2(rule.toJS, index.toJS).toDartDouble; } } } @JS() @staticInterop class DomCSSRule {} @JS() @staticInterop extension DomCSSRuleExtension on DomCSSRule { @JS('cssText') external JSString get _cssText; String get cssText => _cssText.toDart; } @JS() @staticInterop class DomScreen {} extension DomScreenExtension on DomScreen { external DomScreenOrientation? get orientation; external double get width; external double get height; } @JS() @staticInterop class DomScreenOrientation extends DomEventTarget {} extension DomScreenOrientationExtension on DomScreenOrientation { @JS('lock') external JSPromise<JSAny?> _lock(JSString orientation); Future<dynamic> lock(String orientation) => js_util.promiseToFuture(_lock(orientation.toJS)); external JSVoid unlock(); } // A helper class for managing a subscription. On construction it will add an // event listener of the requested type to the target. Calling [cancel] will // remove the listener. class DomSubscription { DomSubscription( this.target, String typeString, DartDomEventListener dartListener) : type = typeString.toJS, listener = createDomEventListener(dartListener) { target._addEventListener1(type, listener); } final JSString type; final DomEventTarget target; final DomEventListener listener; void cancel() => target._removeEventListener1(type, listener); } class DomPoint { DomPoint(this.x, this.y); final num x; final num y; } @JS('WebSocket') @staticInterop class DomWebSocket extends DomEventTarget { external factory DomWebSocket(JSString url); } extension DomWebSocketExtension on DomWebSocket { @JS('send') external JSVoid _send(JSAny? data); void send(Object? data) => _send(data?.toJSAnyShallow); } DomWebSocket createDomWebSocket(String url) => DomWebSocket(url.toJS); @JS() @staticInterop class DomMessageEvent extends DomEvent {} extension DomMessageEventExtension on DomMessageEvent { @JS('data') external JSAny? get _data; dynamic get data => _data?.toObjectDeep; @JS('origin') external JSString get _origin; String get origin => _origin.toDart; /// The source may be a `WindowProxy`, a `MessagePort`, or a `ServiceWorker`. /// /// When a message is sent from an iframe through `window.parent.postMessage` /// the source will be a `WindowProxy` which has the same methods as [Window]. DomMessageEventSource get source => js_util.getProperty(this, 'source'); List<DomMessagePort> get ports => js_util.getProperty<List<Object?>>(this, 'ports').cast<DomMessagePort>(); } @JS() @staticInterop class DomMessageEventSource {} extension DomMEssageEventSourceExtension on DomMessageEventSource { external DomMessageEventLocation? get location; } @JS() @staticInterop class DomMessageEventLocation {} extension DomMessageEventSourceExtension on DomMessageEventLocation { external String? get href; } @JS() @staticInterop class DomHTMLIFrameElement extends DomHTMLElement {} extension DomHTMLIFrameElementExtension on DomHTMLIFrameElement { @JS('src') external set _src(JSString? value); set src(String? value) => _src = value?.toJS; @JS('src') external JSString? get _src; String? get src => _src?.toDart; @JS('height') external set _height(JSString? value); set height(String? value) => _height = value?.toJS; @JS('width') external set _width(JSString? value); set width(String? value) => _width = value?.toJS; external DomWindow get contentWindow; } DomHTMLIFrameElement createDomHTMLIFrameElement() => domDocument.createElement('iframe') as DomHTMLIFrameElement; @JS() @staticInterop class DomMessagePort extends DomEventTarget {} extension DomMessagePortExtension on DomMessagePort { @JS('postMessage') external JSVoid _postMessage(JSAny? message); void postMessage(Object? message) => _postMessage(message?.toJSAnyDeep); external JSVoid start(); } @JS('MessageChannel') @staticInterop class DomMessageChannel { external factory DomMessageChannel(); } extension DomMessageChannelExtension on DomMessageChannel { external DomMessagePort get port1; external DomMessagePort get port2; } /// ResizeObserver JS binding. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver @JS('ResizeObserver') @staticInterop abstract class DomResizeObserver { external factory DomResizeObserver(JSFunction observer); } /// Creates a DomResizeObserver with a callback. /// /// Internally converts the `List<dynamic>` of entries into the expected /// `List<DomResizeObserverEntry>` DomResizeObserver? createDomResizeObserver(DomResizeObserverCallbackFn fn) => DomResizeObserver((JSArray<JSAny?> entries, DomResizeObserver observer) { fn(entries.toDart.cast<DomResizeObserverEntry>(), observer); }.toJS); /// ResizeObserver instance methods. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver#instance_methods extension DomResizeObserverExtension on DomResizeObserver { external JSVoid disconnect(); external JSVoid observe(DomElement target, [DomResizeObserverObserveOptions options]); external JSVoid unobserve(DomElement target); } /// Options object passed to the `observe` method of a [DomResizeObserver]. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/observe#parameters @JS() @staticInterop @anonymous abstract class DomResizeObserverObserveOptions { external factory DomResizeObserverObserveOptions({ JSString box, }); } /// Type of the function used to create a Resize Observer. typedef DomResizeObserverCallbackFn = void Function( List<DomResizeObserverEntry> entries, DomResizeObserver observer); /// The object passed to the [DomResizeObserverCallbackFn], which allows access to the new dimensions of the observed element. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry @JS() @staticInterop abstract class DomResizeObserverEntry {} /// ResizeObserverEntry instance properties. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry#instance_properties extension DomResizeObserverEntryExtension on DomResizeObserverEntry { /// A DOMRectReadOnly object containing the new size of the observed element when the callback is run. /// /// Note that this is better supported than the above two properties, but it /// is left over from an earlier implementation of the Resize Observer API, is /// still included in the spec for web compat reasons, and may be deprecated /// in future versions. external DomRectReadOnly get contentRect; external DomElement get target; // Some more future getters: // // borderBoxSize // contentBoxSize // devicePixelContentBoxSize } /// A factory to create `TrustedTypePolicy` objects. /// See: https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory @JS() @staticInterop abstract class DomTrustedTypePolicyFactory {} /// A subset of TrustedTypePolicyFactory methods. extension DomTrustedTypePolicyFactoryExtension on DomTrustedTypePolicyFactory { /// Creates a TrustedTypePolicy object named `policyName` that implements the /// rules passed as `policyOptions`. external DomTrustedTypePolicy createPolicy( JSString policyName, DomTrustedTypePolicyOptions? policyOptions, ); } /// Options to create a trusted type policy. /// /// The options are user-defined functions for converting strings into trusted /// values. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory/createPolicy#policyoptions @JS() @staticInterop @anonymous abstract class DomTrustedTypePolicyOptions { /// Constructs a TrustedTypePolicyOptions object in JavaScript. /// /// `createScriptURL` is a callback function that contains code to run when /// creating a TrustedScriptURL object. external factory DomTrustedTypePolicyOptions({ JSFunction? createScriptURL, }); } /// Type of the function used to configure createScriptURL. typedef DomCreateScriptUrlOptionFn = String? Function(String input); /// A TrustedTypePolicy defines a group of functions which create TrustedType /// objects. /// /// TrustedTypePolicy objects are created by `TrustedTypePolicyFactory.createPolicy`, /// therefore this class has no constructor. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy @JS() @staticInterop abstract class DomTrustedTypePolicy {} /// A subset of TrustedTypePolicy methods. extension DomTrustedTypePolicyExtension on DomTrustedTypePolicy { /// Creates a `TrustedScriptURL` for the given [input]. /// /// `input` is a string containing the data to be _sanitized_ by the policy. @JS('createScriptURL') external DomTrustedScriptURL _createScriptURL(JSString input); DomTrustedScriptURL createScriptURL(String input) => _createScriptURL(input.toJS); } /// Represents a string that a developer can insert into an _injection sink_ /// that will parse it as an external script. /// /// These objects are created via `createScriptURL` and therefore have no /// constructor. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL @JS() @staticInterop abstract class DomTrustedScriptURL {} /// A subset of TrustedScriptURL methods. extension DomTrustedScriptUrlExtension on DomTrustedScriptURL { /// Exposes the `toString` JS method of TrustedScriptURL. @JS('toString') external JSString _toString(); String get url => _toString().toDart; } // The expected set of files that the flutter-engine TrustedType policy is going // to accept as valid. const Set<String> _expectedFilesForTT = <String>{ 'canvaskit.js', }; // The definition of the `flutter-engine` TrustedType policy. // Only accessible if the Trusted Types API is available. final DomTrustedTypePolicy _ttPolicy = domWindow.trustedTypes!.createPolicy( 'flutter-engine'.toJS, DomTrustedTypePolicyOptions( // Validates the given [url]. createScriptURL: (JSString url) { final Uri uri = Uri.parse(url.toDart); if (_expectedFilesForTT.contains(uri.pathSegments.last)) { return uri.toString().toJS; } domWindow.console .error('URL rejected by TrustedTypes policy flutter-engine: $url' '(download prevented)'); return null; }.toJS), ); /// Converts a String `url` into a [DomTrustedScriptURL] object when the /// Trusted Types API is available, else returns the unmodified `url`. Object createTrustedScriptUrl(String url) { if (domWindow.trustedTypes != null) { // Pass `url` through Flutter Engine's TrustedType policy. final DomTrustedScriptURL trustedUrl = _ttPolicy.createScriptURL(url); assert(trustedUrl.url != '', 'URL: $url rejected by TrustedTypePolicy'); return trustedUrl; } return url; } DomMessageChannel createDomMessageChannel() => DomMessageChannel(); bool domInstanceOfString(Object? element, String objectType) => js_util.instanceOfString(element, objectType); /// This is the shared interface for APIs that return either /// `NodeList` or `HTMLCollection`. Do *not* add any API to this class that /// isn't support by both JS objects. Furthermore, this is an internal class and /// should only be returned as a wrapped object to Dart. @JS() @staticInterop class _DomList {} extension DomListExtension on _DomList { @JS('length') external JSNumber get _length; double get length => _length.toDartDouble; @JS('item') external DomNode _item(JSNumber index); DomNode item(int index) => _item(index.toJS); } class _DomListIterator<T> implements Iterator<T> { _DomListIterator(this.list); final _DomList list; int index = -1; @override bool moveNext() { index++; if (index > list.length) { throw StateError('Iterator out of bounds'); } return index < list.length; } @override T get current => list.item(index) as T; } class _DomListWrapper<T> extends Iterable<T> { _DomListWrapper._(this.list); final _DomList list; @override Iterator<T> get iterator => _DomListIterator<T>(list); /// Override the length to avoid iterating through the whole collection. @override int get length => list.length.toInt(); } /// This is a work around for a `TypeError` which can be triggered by calling /// `toList` on the `Iterable`. Iterable<T> createDomListWrapper<T>(_DomList list) => _DomListWrapper<T>._(list).cast<T>(); // https://developer.mozilla.org/en-US/docs/Web/API/TouchList @JS() @staticInterop class _DomTouchList {} extension DomTouchListExtension on _DomTouchList { @JS('length') external JSNumber get _length; double get length => _length.toDartDouble; @JS('item') external DomNode _item(JSNumber index); DomNode item(int index) => _item(index.toJS); } class _DomTouchListIterator<T> implements Iterator<T> { _DomTouchListIterator(this.list); final _DomTouchList list; int index = -1; @override bool moveNext() { index++; if (index > list.length) { throw StateError('Iterator out of bounds'); } return index < list.length; } @override T get current => list.item(index) as T; } class _DomTouchListWrapper<T> extends Iterable<T> { _DomTouchListWrapper._(this.list); final _DomTouchList list; @override Iterator<T> get iterator => _DomTouchListIterator<T>(list); /// Override the length to avoid iterating through the whole collection. @override int get length => list.length.toInt(); } Iterable<T> createDomTouchListWrapper<T>(_DomTouchList list) => _DomTouchListWrapper<T>._(list).cast<T>(); @JS() @staticInterop class DomSymbol {} extension DomSymbolExtension on DomSymbol { @JS('iterator') external JSAny get iterator; } @JS() @staticInterop class DomIntl {} extension DomIntlExtension on DomIntl { // ignore: non_constant_identifier_names external JSAny? get Segmenter; /// This is a V8-only API for segmenting text. /// /// See: https://code.google.com/archive/p/v8-i18n/wikis/BreakIterator.wiki external JSAny? get v8BreakIterator; } @JS('Intl.Segmenter') @staticInterop // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter class DomSegmenter { // TODO(joshualitt): `locales` should really be typed as `JSAny?`, and we // should pass `JSUndefined`. Revisit this after we reify `JSUndefined` on // Dart2Wasm. external factory DomSegmenter(JSArray<JSAny?> locales, JSAny options); } extension DomSegmenterExtension on DomSegmenter { @JS('segment') external DomSegments segmentRaw(JSString text); DomSegments segment(String text) => segmentRaw(text.toJS); } @JS() @staticInterop // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments class DomSegments {} extension DomSegmentsExtension on DomSegments { DomIteratorWrapper<DomSegment> iterator() { final DomIterator segmentIterator = js_util .callMethod(this, domSymbol.iterator, const <Object?>[]) as DomIterator; return DomIteratorWrapper<DomSegment>(segmentIterator); } } @JS() @staticInterop // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols class DomIterator {} extension DomIteratorExtension on DomIterator { external DomIteratorResult next(); } @JS() @staticInterop class DomIteratorResult {} extension DomIteratorResultExtension on DomIteratorResult { @JS('done') external JSBoolean get _done; bool get done => _done.toDart; external JSAny get value; } /// Wraps a native JS iterator to provide a Dart [Iterator]. class DomIteratorWrapper<T> implements Iterator<T> { DomIteratorWrapper(this._iterator); final DomIterator _iterator; late T _current; @override T get current => _current; @override bool moveNext() { final DomIteratorResult result = _iterator.next(); if (result.done) { return false; } _current = result.value as T; return true; } } @JS() @staticInterop class DomSegment {} extension DomSegmentExtension on DomSegment { @JS('index') external JSNumber get _index; int get index => _index.toDartDouble.toInt(); @JS('isWordLike') external JSBoolean get _isWordLike; bool get isWordLike => _isWordLike.toDart; @JS('segment') external JSString get _segment; String get segment => _segment.toDart; @JS('breakType') external JSString get _breakType; String get breakType => _breakType.toDart; } DomSegmenter createIntlSegmenter({required String granularity}) { if (domIntl.Segmenter == null) { throw UnimplementedError('Intl.Segmenter() is not supported.'); } return DomSegmenter( <JSAny?>[].toJS, <String, String>{'granularity': granularity}.toJSAnyDeep, ); } @JS('Intl.v8BreakIterator') @staticInterop class DomV8BreakIterator { external factory DomV8BreakIterator(JSArray<JSAny?> locales, JSAny options); } extension DomV8BreakIteratorExtension on DomV8BreakIterator { @JS('adoptText') external JSVoid adoptText(JSString text); @JS('first') external JSNumber _first(); double first() => _first().toDartDouble; @JS('next') external JSNumber _next(); double next() => _next().toDartDouble; @JS('current') external JSNumber _current(); double current() => _current().toDartDouble; @JS('breakType') external JSString _breakType(); String breakType() => _breakType().toDart; } DomV8BreakIterator createV8BreakIterator() { if (domIntl.v8BreakIterator == null) { throw UnimplementedError('v8BreakIterator is not supported.'); } return DomV8BreakIterator( <JSAny?>[].toJS, const <String, String>{'type': 'line'}.toJSAnyDeep); } @JS('TextDecoder') @staticInterop class DomTextDecoder { external factory DomTextDecoder(); } extension DomTextDecoderExtension on DomTextDecoder { external JSString decode(JSTypedArray buffer); } @JS('window.FinalizationRegistry') @staticInterop class DomFinalizationRegistry { external factory DomFinalizationRegistry(JSFunction cleanup); } extension DomFinalizationRegistryExtension on DomFinalizationRegistry { @JS('register') external JSVoid register(JSAny target, JSAny value); @JS('register') external JSVoid registerWithToken(JSAny target, JSAny value, JSAny token); @JS('unregister') external JSVoid unregister(JSAny token); } @JS('window.FinalizationRegistry') external JSAny? get _finalizationRegistryConstructor; /// Whether the current browser supports `FinalizationRegistry`. bool browserSupportsFinalizationRegistry = _finalizationRegistryConstructor != null; @JS('window.OffscreenCanvas') external JSAny? get _offscreenCanvasConstructor; bool browserSupportsOffscreenCanvas = _offscreenCanvasConstructor != null; @JS('window.createImageBitmap') external JSAny? get _createImageBitmapFunction; /// Set to `true` to disable `createImageBitmap` support. Used in tests. bool debugDisableCreateImageBitmapSupport = false; bool get browserSupportsCreateImageBitmap => _createImageBitmapFunction != null && !isChrome110OrOlder && !debugDisableCreateImageBitmapSupport; @JS() @staticInterop extension JSArrayExtension on JSArray<JSAny?> { external void push(JSAny value); external JSNumber get length; }
engine/lib/web_ui/lib/src/engine/dom.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/dom.dart", "repo_id": "engine", "token_count": 36341 }
262
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:ui/ui.dart' as ui; import '../dom.dart'; import '../util.dart'; import '../vector_math.dart'; import 'surface.dart'; /// A surface that translates its children using CSS transform and translate. class PersistedOffset extends PersistedContainerSurface implements ui.OffsetEngineLayer { PersistedOffset(PersistedOffset? super.oldLayer, this.dx, this.dy); /// Horizontal displacement. final double dx; /// Vertical displacement. final double dy; @override void recomputeTransformAndClip() { transform = parent!.transform; 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(-dx, -dy, 0); @override DomElement createElement() { final DomElement element = domDocument.createElement('flt-offset'); setElementStyle(element, 'position', 'absolute'); setElementStyle(element, 'transform-origin', '0 0 0'); return element; } @override void apply() { rootElement!.style.transform = 'translate(${dx}px, ${dy}px)'; } @override void update(PersistedOffset oldSurface) { super.update(oldSurface); if (oldSurface.dx != dx || oldSurface.dy != dy) { apply(); } } }
engine/lib/web_ui/lib/src/engine/html/offset.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/offset.dart", "repo_id": "engine", "token_count": 545 }
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:math' as math; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../engine_canvas.dart'; import '../picture.dart'; import '../rrect_renderer.dart'; import '../shadow.dart'; import '../text/canvas_paragraph.dart'; import '../util.dart'; import '../vector_math.dart'; import 'painting.dart'; import 'path/path.dart'; import 'path/path_utils.dart'; import 'render_vertices.dart'; import 'shaders/image_shader.dart'; /// Enable this to print every command applied by a canvas. const bool _debugDumpPaintCommands = false; // Returns the squared length of the x, y (of a border radius). double _measureBorderRadius(double x, double y) => x*x + y*y; /// Records canvas commands to be applied to a [EngineCanvas]. /// /// See [Canvas] for docs for these methods. class RecordingCanvas { RecordingCanvas(ui.Rect? bounds) : _paintBounds = _PaintBounds(bounds ?? ui.Rect.largest); /// Computes [_pictureBounds]. final _PaintBounds _paintBounds; /// Maximum paintable bounds for the picture painted by this recording. /// /// The bounds contain the full picture. The commands recorded for the picture /// are later pruned based on the clip applied to the picture. See the [apply] /// method for more details. ui.Rect? get pictureBounds { assert( _recordingEnded, 'Picture bounds not available yet. Call [endRecording] before accessing picture bounds.', ); return _pictureBounds; } ui.Rect? _pictureBounds; final List<PaintCommand> _commands = <PaintCommand>[]; /// In debug mode returns the list of recorded paint commands for testing. List<PaintCommand> get debugPaintCommands { List<PaintCommand>? result; assert(() { result = _commands; return true; }()); if (result != null) { return result!; } throw UnsupportedError('For debugging only.'); } final RenderStrategy renderStrategy = RenderStrategy(); /// Forces arbitrary paint even for simple pictures. /// /// This is useful for testing bitmap canvas when otherwise the compositor /// would prefer a DOM canvas. void debugEnforceArbitraryPaint() { renderStrategy.hasArbitraryPaint = true; } /// Whether this canvas contain drawing operations. /// /// Some pictures are created but only contain operations that do not result /// in any pixels on the screen. For example, they will only contain saves, /// restores, and translates. This happens when a parent [RenderObject] /// prepares the canvas for its children to paint to, but the child ends up /// not painting anything, such as when an empty [SizedBox] is used to add a /// margin between two widgets. bool get didDraw => _didDraw; bool _didDraw = false; /// Used to ensure that [endRecording] is called before calling [apply] or /// [pictureBounds]. /// /// When [PaintingContext] is used by [ClipContext], the painter may /// end a recording and start a new one and cause [ClipContext] to call /// restore on a new canvas before prior save calls, [_recordingEnded] /// prevents transforms removals in that case. bool _recordingEnded = false; /// Stops recording drawing commands and computes paint bounds. /// /// This must be called prior to passing the picture to the [SceneBuilder] /// for rendering. In a production app, this is done automatically by /// [PictureRecorder] when the framework calls [PictureRecorder.endRecording]. /// However, if you are writing a unit-test and using [RecordingCanvas] /// directly it is up to you to call this method explicitly. void endRecording() { _pictureBounds = _paintBounds.computeBounds(); _recordingEnded = true; } /// Applies the recorded commands onto an [engineCanvas] and signals to /// canvas that all painting is completed for garbage collection/reuse. /// /// The [clipRect] specifies the clip applied to the picture (screen clip at /// a minimum). The commands that fall outside the clip are skipped and are /// not applied to the [engineCanvas]. A command must have a non-zero /// intersection with the clip in order to be applied. void apply(EngineCanvas engineCanvas, ui.Rect clipRect) { applyCommands(engineCanvas, clipRect); engineCanvas.endOfPaint(); } /// Applies the recorded commands onto an [engineCanvas]. /// /// The [clipRect] specifies the clip applied to the picture (screen clip at /// a minimum). The commands that fall outside the clip are skipped and are /// not applied to the [engineCanvas]. A command must have a non-zero /// intersection with the clip in order to be applied. void applyCommands(EngineCanvas engineCanvas, ui.Rect clipRect) { assert(_recordingEnded); if (_debugDumpPaintCommands) { final StringBuffer debugBuf = StringBuffer(); int skips = 0; debugBuf.writeln( '--- Applying RecordingCanvas to ${engineCanvas.runtimeType} ' 'with bounds $_paintBounds and clip $clipRect (w = ${clipRect.width},' ' h = ${clipRect.height})'); for (int i = 0; i < _commands.length; i++) { final PaintCommand command = _commands[i]; if (command is DrawCommand) { if (command.isInvisible(clipRect)) { // The drawing command is outside the clip region. No need to apply. debugBuf.writeln('SKIPPED: ctx.$command;'); skips += 1; continue; } } debugBuf.writeln('ctx.$command;'); command.apply(engineCanvas); } if (skips > 0) { debugBuf.writeln('Total commands skipped: $skips'); } debugBuf.writeln('--- End of command stream'); print(debugBuf); } else { try { if (rectContainsOther(clipRect, _pictureBounds!)) { // No need to check if commands fit in the clip rect if we already // know that the entire picture fits it. final int len = _commands.length; for (int i = 0; i < len; i++) { _commands[i].apply(engineCanvas); } } else { // The picture doesn't fit the clip rect. Check that drawing commands // fit before applying them. final int len = _commands.length; for (int i = 0; i < len; i++) { final PaintCommand command = _commands[i]; if (command is DrawCommand) { if (command.isInvisible(clipRect)) { // The drawing command is outside the clip region. No need to apply. continue; } } command.apply(engineCanvas); } } } catch (e) { // commands should never fail, but... // https://bugzilla.mozilla.org/show_bug.cgi?id=941146 if (!isNsErrorFailureException(e)) { rethrow; } } } } /// Prints recorded commands. String? debugPrintCommands() { String? result; assert(() { final StringBuffer debugBuf = StringBuffer(); for (int i = 0; i < _commands.length; i++) { final PaintCommand command = _commands[i]; debugBuf.writeln('ctx.$command;'); } result = debugBuf.toString(); return true; }()); return result; } void save() { assert(!_recordingEnded); _paintBounds.saveTransformsAndClip(); _commands.add(const PaintSave()); _saveCount++; } void saveLayerWithoutBounds(SurfacePaint paint) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; // TODO(het): Implement this correctly using another canvas. _commands.add(const PaintSave()); _paintBounds.saveTransformsAndClip(); _saveCount++; } void saveLayer(ui.Rect bounds, SurfacePaint paint) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; // TODO(het): Implement this correctly using another canvas. _commands.add(const PaintSave()); _paintBounds.saveTransformsAndClip(); _saveCount++; } void restore() { if (!_recordingEnded && _saveCount > 1) { _paintBounds.restoreTransformsAndClip(); } if (_commands.isNotEmpty && _commands.last is PaintSave) { // A restore followed a save without any drawing operations in between. // This means that the save didn't have any effect on drawing operations // and can be omitted. This makes our communication with the canvas less // chatty. _commands.removeLast(); } else { _commands.add(const PaintRestore()); } _saveCount--; } void restoreToCount(int count) { while (count < _saveCount && _saveCount > 1) { restore(); } } void translate(double dx, double dy) { assert(!_recordingEnded); _paintBounds.translate(dx, dy); _commands.add(PaintTranslate(dx, dy)); } void scale(double sx, double sy) { assert(!_recordingEnded); _paintBounds.scale(sx, sy); _commands.add(PaintScale(sx, sy)); } void rotate(double radians) { assert(!_recordingEnded); _paintBounds.rotateZ(radians); _commands.add(PaintRotate(radians)); } void transform(Float32List matrix4) { assert(!_recordingEnded); _paintBounds.transform(matrix4); _commands.add(PaintTransform(matrix4)); } Float32List getCurrentMatrixUnsafe() => _paintBounds._currentMatrix.storage; void skew(double sx, double sy) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; _paintBounds.skew(sx, sy); _commands.add(PaintSkew(sx, sy)); } void clipRect(ui.Rect rect, ui.ClipOp clipOp) { assert(!_recordingEnded); final DrawCommand command = PaintClipRect(rect, clipOp); switch (clipOp) { case ui.ClipOp.intersect: _paintBounds.clipRect(rect, command); case ui.ClipOp.difference: // Since this refers to inverse, can't shrink paintBounds. break; } renderStrategy.hasArbitraryPaint = true; _commands.add(command); } void clipRRect(ui.RRect roundedRect) { assert(!_recordingEnded); final PaintClipRRect command = PaintClipRRect(roundedRect); _paintBounds.clipRect(roundedRect.outerRect, command); renderStrategy.hasArbitraryPaint = true; _commands.add(command); } void clipPath(ui.Path path, {bool doAntiAlias = true}) { assert(!_recordingEnded); final PaintClipPath command = PaintClipPath(path as SurfacePath); _paintBounds.clipRect(path.getBounds(), command); renderStrategy.hasArbitraryPaint = true; _commands.add(command); } ui.Rect? getDestinationClipBounds() => _paintBounds.getDestinationClipBounds(); void drawColor(ui.Color color, ui.BlendMode blendMode) { assert(!_recordingEnded); final PaintDrawColor command = PaintDrawColor(color, blendMode); _commands.add(command); _paintBounds.grow(_paintBounds.maxPaintBounds, command); } void drawLine(ui.Offset p1, ui.Offset p2, SurfacePaint paint) { assert(!_recordingEnded); assert(paint.shader == null || paint.shader is! EngineImageShader, 'ImageShader not supported yet'); final double paintSpread = math.max(_getPaintSpread(paint), 1.0); final PaintDrawLine command = PaintDrawLine(p1, p2, paint.paintData); // TODO(yjbanov): This can be optimized. Currently we create a box around // the line and then apply the transform on the box to get // the bounding box. If you have a 45-degree line and a // 45-degree transform, the bounding box should be the length // of the line long and stroke width wide, but our current // algorithm produces a square with each side of the length // matching the length of the line. _paintBounds.growLTRB( math.min(p1.dx, p2.dx) - paintSpread, math.min(p1.dy, p2.dy) - paintSpread, math.max(p1.dx, p2.dx) + paintSpread, math.max(p1.dy, p2.dy) + paintSpread, command, ); renderStrategy.hasArbitraryPaint = true; _didDraw = true; _commands.add(command); } void drawPaint(SurfacePaint paint) { assert(!_recordingEnded); assert(paint.shader == null || paint.shader is! EngineImageShader, 'ImageShader not supported yet'); renderStrategy.hasArbitraryPaint = true; _didDraw = true; final PaintDrawPaint command = PaintDrawPaint(paint.paintData); _paintBounds.grow(_paintBounds.maxPaintBounds, command); _commands.add(command); } void drawRect(ui.Rect rect, SurfacePaint paint) { assert(!_recordingEnded); if (paint.shader != null) { renderStrategy.hasArbitraryPaint = true; } _didDraw = true; final double paintSpread = _getPaintSpread(paint); final PaintDrawRect command = PaintDrawRect(rect, paint.paintData); if (paintSpread != 0.0) { _paintBounds.grow(rect.inflate(paintSpread), command); } else { _paintBounds.grow(rect, command); } _commands.add(command); } void drawRRect(ui.RRect rrect, SurfacePaint paint) { assert(!_recordingEnded); if (paint.shader != null || !rrect.webOnlyUniformRadii) { renderStrategy.hasArbitraryPaint = true; } _didDraw = true; final double paintSpread = _getPaintSpread(paint); final double left = math.min(rrect.left, rrect.right) - paintSpread; final double top = math.min(rrect.top, rrect.bottom) - paintSpread; final double right = math.max(rrect.left, rrect.right) + paintSpread; final double bottom = math.max(rrect.top, rrect.bottom) + paintSpread; final PaintDrawRRect command = PaintDrawRRect(rrect, paint.paintData); _paintBounds.growLTRB(left, top, right, bottom, command); _commands.add(command); } void drawDRRect(ui.RRect outer, ui.RRect inner, SurfacePaint paint) { assert(!_recordingEnded); // Check the inner bounds are contained within the outer bounds // see: https://cs.chromium.org/chromium/src/third_party/skia/src/core/SkCanvas.cpp?l=1787-1789 final ui.Rect innerRect = inner.outerRect; final ui.Rect outerRect = outer.outerRect; if (outerRect == innerRect || outerRect.intersect(innerRect) != innerRect) { return; // inner is not fully contained within outer } // Compare radius "length" of the rectangles that are going to be actually drawn final ui.RRect scaledOuter = outer.scaleRadii(); final ui.RRect scaledInner = inner.scaleRadii(); final double outerTl = _measureBorderRadius(scaledOuter.tlRadiusX, scaledOuter.tlRadiusY); final double outerTr = _measureBorderRadius(scaledOuter.trRadiusX, scaledOuter.trRadiusY); final double outerBl = _measureBorderRadius(scaledOuter.blRadiusX, scaledOuter.blRadiusY); final double outerBr = _measureBorderRadius(scaledOuter.brRadiusX, scaledOuter.brRadiusY); final double innerTl = _measureBorderRadius(scaledInner.tlRadiusX, scaledInner.tlRadiusY); final double innerTr = _measureBorderRadius(scaledInner.trRadiusX, scaledInner.trRadiusY); final double innerBl = _measureBorderRadius(scaledInner.blRadiusX, scaledInner.blRadiusY); final double innerBr = _measureBorderRadius(scaledInner.brRadiusX, scaledInner.brRadiusY); if (innerTl > outerTl || innerTr > outerTr || innerBl > outerBl || innerBr > outerBr) { return; // Some inner radius is overlapping some outer radius } renderStrategy.hasArbitraryPaint = true; _didDraw = true; final double paintSpread = _getPaintSpread(paint); final PaintDrawDRRect command = PaintDrawDRRect(outer, inner, paint.paintData); final double left = math.min(outer.left, outer.right); final double right = math.max(outer.left, outer.right); final double top = math.min(outer.top, outer.bottom); final double bottom = math.max(outer.top, outer.bottom); _paintBounds.growLTRB( left - paintSpread, top - paintSpread, right + paintSpread, bottom + paintSpread, command, ); _commands.add(command); } void drawOval(ui.Rect rect, SurfacePaint paint) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; _didDraw = true; final double paintSpread = _getPaintSpread(paint); final PaintDrawOval command = PaintDrawOval(rect, paint.paintData); if (paintSpread != 0.0) { _paintBounds.grow(rect.inflate(paintSpread), command); } else { _paintBounds.grow(rect, command); } _commands.add(command); } void drawCircle(ui.Offset c, double radius, SurfacePaint paint) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; _didDraw = true; final double paintSpread = _getPaintSpread(paint); final PaintDrawCircle command = PaintDrawCircle(c, radius, paint.paintData); final double distance = radius + paintSpread; _paintBounds.growLTRB( c.dx - distance, c.dy - distance, c.dx + distance, c.dy + distance, command, ); _commands.add(command); } void drawPath(ui.Path path, SurfacePaint paint) { assert(!_recordingEnded); if (paint.shader == null) { // For Rect/RoundedRect paths use drawRect/drawRRect code paths for // DomCanvas optimization. final SurfacePath sPath = path as SurfacePath; final ui.Rect? rect = sPath.toRect(); if (rect != null) { drawRect(rect, paint); return; } final ui.RRect? rrect = sPath.toRoundedRect(); if (rrect != null) { drawRRect(rrect, paint); return; } // Use drawRect for straight line paths painted with a zero strokeWidth final ui.Rect? line = sPath.toStraightLine(); if (line != null && paint.strokeWidth == 0) { final double left = math.min(line.left, line.right); final double top = math.min(line.top, line.bottom); final double width = line.width.abs(); final double height = line.height.abs(); final double inflatedHeight = line.height == 0 ? 1 : height; final double inflatedWidth = line.width == 0 ? 1 : width; final ui.Size inflatedSize = ui.Size(inflatedWidth, inflatedHeight); paint.style = ui.PaintingStyle.fill; drawRect(ui.Offset(left, top) & inflatedSize, paint); return; } } final SurfacePath sPath = path as SurfacePath; if (!sPath.pathRef.isEmpty) { renderStrategy.hasArbitraryPaint = true; _didDraw = true; ui.Rect pathBounds = sPath.getBounds(); final double paintSpread = _getPaintSpread(paint); if (paintSpread != 0.0) { pathBounds = pathBounds.inflate(paintSpread); } // Clone path so it can be reused for subsequent draw calls. final ui.Path clone = SurfacePath.shallowCopy(path); final PaintDrawPath command = PaintDrawPath(clone as SurfacePath, paint.paintData); _paintBounds.grow(pathBounds, command); clone.fillType = sPath.fillType; _commands.add(command); } } void drawImage(ui.Image image, ui.Offset offset, SurfacePaint paint) { assert(!_recordingEnded); assert(paint.shader == null || paint.shader is! EngineImageShader, 'ImageShader not supported yet'); renderStrategy.hasArbitraryPaint = true; renderStrategy.hasImageElements = true; _didDraw = true; final double left = offset.dx; final double top = offset.dy; final PaintDrawImage command = PaintDrawImage(image, offset, paint.paintData); _paintBounds.growLTRB( left, top, left + image.width, top + image.height, command); _commands.add(command); } void drawPicture(ui.Picture picture) { assert(!_recordingEnded); final EnginePicture enginePicture = picture as EnginePicture; if (enginePicture.recordingCanvas == null) { // No contents / nothing to draw. return; } final RecordingCanvas pictureRecording = enginePicture.recordingCanvas!; if (pictureRecording._didDraw) { _didDraw = true; } renderStrategy.merge(pictureRecording.renderStrategy); // Need to save to make sure we don't pick up leftover clips and // transforms from running commands in picture. save(); _commands.addAll(pictureRecording._commands); restore(); if (pictureRecording._pictureBounds != null) { _paintBounds.growBounds(pictureRecording._pictureBounds!); } } void drawImageRect( ui.Image image, ui.Rect src, ui.Rect dst, SurfacePaint paint) { assert(!_recordingEnded); assert(paint.shader == null || paint.shader is! EngineImageShader, 'ImageShader not supported yet'); renderStrategy.hasArbitraryPaint = true; renderStrategy.hasImageElements = true; _didDraw = true; final PaintDrawImageRect command = PaintDrawImageRect(image, src, dst, paint.paintData); _paintBounds.grow(dst, command); _commands.add(command); } void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { assert(!_recordingEnded); final CanvasParagraph engineParagraph = paragraph as CanvasParagraph; if (!engineParagraph.isLaidOut) { // Ignore non-laid out paragraphs. This matches Flutter's behavior. return; } _didDraw = true; if (engineParagraph.hasArbitraryPaint) { renderStrategy.hasArbitraryPaint = true; } renderStrategy.hasParagraphs = true; final PaintDrawParagraph command = PaintDrawParagraph(engineParagraph, offset); final ui.Rect paragraphBounds = engineParagraph.paintBounds; _paintBounds.growLTRB( offset.dx + paragraphBounds.left, offset.dy + paragraphBounds.top, offset.dx + paragraphBounds.right, offset.dy + paragraphBounds.bottom, command, ); _commands.add(command); } void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; _didDraw = true; final ui.Rect shadowRect = computePenumbraBounds(path.getBounds(), elevation); final PaintDrawShadow command = PaintDrawShadow( path as SurfacePath, color, elevation, transparentOccluder); _paintBounds.grow(shadowRect, command); _commands.add(command); } void drawVertices( SurfaceVertices vertices, ui.BlendMode blendMode, SurfacePaint paint) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; _didDraw = true; final PaintDrawVertices command = PaintDrawVertices(vertices, blendMode, paint.paintData); _growPaintBoundsByPoints(vertices.positions, 0, paint, command); _commands.add(command); } void drawRawPoints( ui.PointMode pointMode, Float32List points, SurfacePaint paint) { assert(!_recordingEnded); renderStrategy.hasArbitraryPaint = true; _didDraw = true; final PaintDrawPoints command = PaintDrawPoints(pointMode, points, paint.paintData); _growPaintBoundsByPoints(points, paint.strokeWidth, paint, command); _commands.add(command); } void _growPaintBoundsByPoints(Float32List points, double thickness, SurfacePaint paint, DrawCommand command) { double minValueX, maxValueX, minValueY, maxValueY; minValueX = maxValueX = points[0]; minValueY = maxValueY = points[1]; final int len = points.length; for (int i = 2; i < len; i += 2) { final double x = points[i]; final double y = points[i + 1]; if (x.isNaN || y.isNaN) { // Follows skia implementation that sets bounds to empty // and aborts. return; } minValueX = math.min(minValueX, x); maxValueX = math.max(maxValueX, x); minValueY = math.min(minValueY, y); maxValueY = math.max(maxValueY, y); } final double distance = thickness / 2.0; final double paintSpread = _getPaintSpread(paint); _paintBounds.growLTRB( minValueX - distance - paintSpread, minValueY - distance - paintSpread, maxValueX + distance + paintSpread, maxValueY + distance + paintSpread, command, ); } int _saveCount = 1; int get saveCount => _saveCount; /// Prints the commands recorded by this canvas to the console. void debugDumpCommands() { print('${'/' * 40} CANVAS COMMANDS ${'/' * 40}'); _commands.forEach(print); print('${'/' * 37} END OF CANVAS COMMANDS ${'/' * 36}'); } } abstract class PaintCommand { const PaintCommand(); void apply(EngineCanvas canvas); } /// A [PaintCommand] that affect pixels on the screen (unlike, for example, the /// [SaveCommand]). abstract class DrawCommand extends PaintCommand { /// Whether the command is completely clipped out of the picture. bool isClippedOut = false; /// The left bound of the graphic produced by this command in picture-global /// coordinates. double leftBound = double.negativeInfinity; /// The top bound of the graphic produced by this command in picture-global /// coordinates. double topBound = double.negativeInfinity; /// The right bound of the graphic produced by this command in picture-global /// coordinates. double rightBound = double.infinity; /// The bottom bound of the graphic produced by this command in /// picture-global coordinates. double bottomBound = double.infinity; /// Whether this command intersects with the [clipRect]. bool isInvisible(ui.Rect clipRect) { if (isClippedOut) { return true; } // Check top and bottom first because vertical scrolling is more common // than horizontal scrolling. return bottomBound < clipRect.top || topBound > clipRect.bottom || rightBound < clipRect.left || leftBound > clipRect.right; } } class PaintSave extends PaintCommand { const PaintSave(); @override void apply(EngineCanvas canvas) { canvas.save(); } @override String toString() { String result = super.toString(); assert(() { result = 'save()'; return true; }()); return result; } } class PaintRestore extends PaintCommand { const PaintRestore(); @override void apply(EngineCanvas canvas) { canvas.restore(); } @override String toString() { String result = super.toString(); assert(() { result = 'restore()'; return true; }()); return result; } } class PaintTranslate extends PaintCommand { PaintTranslate(this.dx, this.dy); final double dx; final double dy; @override void apply(EngineCanvas canvas) { canvas.translate(dx, dy); } @override String toString() { String result = super.toString(); assert(() { result = 'translate($dx, $dy)'; return true; }()); return result; } } class PaintScale extends PaintCommand { PaintScale(this.sx, this.sy); final double sx; final double sy; @override void apply(EngineCanvas canvas) { canvas.scale(sx, sy); } @override String toString() { String result = super.toString(); assert(() { result = 'scale($sx, $sy)'; return true; }()); return result; } } class PaintRotate extends PaintCommand { PaintRotate(this.radians); final double radians; @override void apply(EngineCanvas canvas) { canvas.rotate(radians); } @override String toString() { String result = super.toString(); assert(() { result = 'rotate($radians)'; return true; }()); return result; } } class PaintTransform extends PaintCommand { PaintTransform(this.matrix4); final Float32List matrix4; @override void apply(EngineCanvas canvas) { canvas.transform(matrix4); } @override String toString() { String result = super.toString(); assert(() { result = 'transform(Matrix4.fromFloat32List(Float32List.fromList(<double>[${matrix4.join(', ')}])))'; return true; }()); return result; } } class PaintSkew extends PaintCommand { PaintSkew(this.sx, this.sy); final double sx; final double sy; @override void apply(EngineCanvas canvas) { canvas.skew(sx, sy); } @override String toString() { String result = super.toString(); assert(() { result = 'skew($sx, $sy)'; return true; }()); return result; } } class PaintClipRect extends DrawCommand { PaintClipRect(this.rect, this.clipOp); final ui.Rect rect; final ui.ClipOp clipOp; @override void apply(EngineCanvas canvas) { canvas.clipRect(rect, clipOp); } @override String toString() { String result = super.toString(); assert(() { result = 'clipRect($rect)'; return true; }()); return result; } } class PaintClipRRect extends DrawCommand { PaintClipRRect(this.rrect); final ui.RRect rrect; @override void apply(EngineCanvas canvas) { canvas.clipRRect(rrect); } @override String toString() { String result = super.toString(); assert(() { result = 'clipRRect($rrect)'; return true; }()); return result; } } class PaintClipPath extends DrawCommand { PaintClipPath(this.path); final SurfacePath path; @override void apply(EngineCanvas canvas) { canvas.clipPath(path); } @override String toString() { String result = super.toString(); assert(() { result = 'clipPath($path)'; return true; }()); return result; } } class PaintDrawColor extends DrawCommand { PaintDrawColor(this.color, this.blendMode); final ui.Color color; final ui.BlendMode blendMode; @override void apply(EngineCanvas canvas) { canvas.drawColor(color, blendMode); } @override String toString() { String result = super.toString(); assert(() { result = 'drawColor($color, $blendMode)'; return true; }()); return result; } } class PaintDrawLine extends DrawCommand { PaintDrawLine(this.p1, this.p2, this.paint); final ui.Offset p1; final ui.Offset p2; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawLine(p1, p2, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawLine($p1, $p2, $paint)'; return true; }()); return result; } } class PaintDrawPaint extends DrawCommand { PaintDrawPaint(this.paint); final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawPaint(paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawPaint($paint)'; return true; }()); return result; } } class PaintDrawVertices extends DrawCommand { PaintDrawVertices(this.vertices, this.blendMode, this.paint); final ui.Vertices vertices; final ui.BlendMode blendMode; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawVertices(vertices as SurfaceVertices, blendMode, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawVertices($vertices, $blendMode, $paint)'; return true; }()); return result; } } class PaintDrawPoints extends DrawCommand { PaintDrawPoints(this.pointMode, this.points, this.paint); final Float32List points; final ui.PointMode pointMode; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawPoints(pointMode, points, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawPoints($pointMode, $points, $paint)'; return true; }()); return result; } } class PaintDrawRect extends DrawCommand { PaintDrawRect(this.rect, this.paint); final ui.Rect rect; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawRect(rect, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawRect($rect, $paint)'; return true; }()); return result; } } class PaintDrawRRect extends DrawCommand { PaintDrawRRect(this.rrect, this.paint); final ui.RRect rrect; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawRRect(rrect, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawRRect($rrect, $paint)'; return true; }()); return result; } } class PaintDrawDRRect extends DrawCommand { PaintDrawDRRect(this.outer, this.inner, this.paint) { path = ui.Path() ..fillType = ui.PathFillType.evenOdd ..addRRect(outer) ..addRRect(inner) ..close(); } final ui.RRect outer; final ui.RRect inner; final SurfacePaintData paint; ui.Path? path; @override void apply(EngineCanvas canvas) { paint.style ??= ui.PaintingStyle.fill; canvas.drawPath(path!, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawDRRect($outer, $inner, $paint)'; return true; }()); return result; } } class PaintDrawOval extends DrawCommand { PaintDrawOval(this.rect, this.paint); final ui.Rect rect; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawOval(rect, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawOval($rect, $paint)'; return true; }()); return result; } } class PaintDrawCircle extends DrawCommand { PaintDrawCircle(this.c, this.radius, this.paint); final ui.Offset c; final double radius; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawCircle(c, radius, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawCircle($c, $radius, $paint)'; return true; }()); return result; } } class PaintDrawPath extends DrawCommand { PaintDrawPath(this.path, this.paint); final SurfacePath path; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawPath(path, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawPath($path, $paint)'; return true; }()); return result; } } class PaintDrawShadow extends DrawCommand { PaintDrawShadow( this.path, this.color, this.elevation, this.transparentOccluder); final SurfacePath path; final ui.Color color; final double elevation; final bool transparentOccluder; @override void apply(EngineCanvas canvas) { canvas.drawShadow(path, color, elevation, transparentOccluder); } @override String toString() { String result = super.toString(); assert(() { result = 'drawShadow($path, $color, $elevation, $transparentOccluder)'; return true; }()); return result; } } class PaintDrawImage extends DrawCommand { PaintDrawImage(this.image, this.offset, this.paint); final ui.Image image; final ui.Offset offset; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawImage(image, offset, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawImage($image, $offset, $paint)'; return true; }()); return result; } } class PaintDrawImageRect extends DrawCommand { PaintDrawImageRect(this.image, this.src, this.dst, this.paint); final ui.Image image; final ui.Rect src; final ui.Rect dst; final SurfacePaintData paint; @override void apply(EngineCanvas canvas) { canvas.drawImageRect(image, src, dst, paint); } @override String toString() { String result = super.toString(); assert(() { result = 'drawImageRect($image, $src, $dst, $paint)'; return true; }()); return result; } } class PaintDrawParagraph extends DrawCommand { PaintDrawParagraph(this.paragraph, this.offset); final CanvasParagraph paragraph; final ui.Offset offset; @override void apply(EngineCanvas canvas) { canvas.drawParagraph(paragraph, offset); } @override String toString() { String result = super.toString(); assert(() { result = 'DrawParagraph(${paragraph.plainText}, $offset)'; return true; }()); return result; } } class Subpath { Subpath(this.startX, this.startY) : commands = <PathCommand>[]; double startX = 0.0; double startY = 0.0; double currentX = 0.0; double currentY = 0.0; final List<PathCommand> commands; Subpath shift(ui.Offset offset) { final Subpath result = Subpath(startX + offset.dx, startY + offset.dy) ..currentX = currentX + offset.dx ..currentY = currentY + offset.dy; for (final PathCommand command in commands) { result.commands.add(command.shifted(offset)); } return result; } @override String toString() { String result = super.toString(); assert(() { result = 'Subpath(${commands.join(', ')})'; return true; }()); return result; } } abstract class PathCommand { const PathCommand(); PathCommand shifted(ui.Offset offset); /// Transform the command and add to targetPath. void transform(Float32List matrix4, SurfacePath targetPath); /// Helper method for implementing transforms. static ui.Offset _transformOffset(double x, double y, Float32List matrix4) => ui.Offset((matrix4[0] * x) + (matrix4[4] * y) + matrix4[12], (matrix4[1] * x) + (matrix4[5] * y) + matrix4[13]); } class MoveTo extends PathCommand { const MoveTo(this.x, this.y); final double x; final double y; @override MoveTo shifted(ui.Offset offset) { return MoveTo(x + offset.dx, y + offset.dy); } @override void transform(Float32List matrix4, ui.Path targetPath) { final ui.Offset offset = PathCommand._transformOffset(x, y, matrix4); targetPath.moveTo(offset.dx, offset.dy); } @override String toString() { String result = super.toString(); assert(() { result = 'MoveTo($x, $y)'; return true; }()); return result; } } class LineTo extends PathCommand { const LineTo(this.x, this.y); final double x; final double y; @override LineTo shifted(ui.Offset offset) { return LineTo(x + offset.dx, y + offset.dy); } @override void transform(Float32List matrix4, ui.Path targetPath) { final ui.Offset offset = PathCommand._transformOffset(x, y, matrix4); targetPath.lineTo(offset.dx, offset.dy); } @override String toString() { String result = super.toString(); assert(() { result = 'LineTo($x, $y)'; return true; }()); return result; } } class Ellipse extends PathCommand { const Ellipse(this.x, this.y, this.radiusX, this.radiusY, this.rotation, this.startAngle, this.endAngle, this.anticlockwise); final double x; final double y; final double radiusX; final double radiusY; final double rotation; final double startAngle; final double endAngle; final bool anticlockwise; @override Ellipse shifted(ui.Offset offset) { return Ellipse(x + offset.dx, y + offset.dy, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise); } @override void transform(Float32List matrix4, SurfacePath targetPath) { final ui.Path bezierPath = ui.Path(); _drawArcWithBezier( x, y, radiusX, radiusY, rotation, startAngle, anticlockwise ? startAngle - endAngle : endAngle - startAngle, matrix4, bezierPath); targetPath.addPathWithMode(bezierPath, 0, 0, matrix4, SPathAddPathMode.kAppend); } void _drawArcWithBezier( double centerX, double centerY, double radiusX, double radiusY, double rotation, double startAngle, double sweep, Float32List matrix4, ui.Path targetPath) { double ratio = sweep.abs() / (math.pi / 2.0); if ((1.0 - ratio).abs() < 0.0000001) { ratio = 1.0; } final int segments = math.max(ratio.ceil(), 1); final double anglePerSegment = sweep / segments; double angle = startAngle; for (int segment = 0; segment < segments; segment++) { _drawArcSegment(targetPath, centerX, centerY, radiusX, radiusY, rotation, angle, anglePerSegment, segment == 0, matrix4); angle += anglePerSegment; } } void _drawArcSegment( ui.Path path, double centerX, double centerY, double radiusX, double radiusY, double rotation, double startAngle, double sweep, bool startPath, Float32List matrix4) { final double s = 4 / 3 * math.tan(sweep / 4); // Rotate unit vector to startAngle and endAngle to use for computing start // and end points of segment. final double x1 = math.cos(startAngle); final double y1 = math.sin(startAngle); final double endAngle = startAngle + sweep; final double x2 = math.cos(endAngle); final double y2 = math.sin(endAngle); // Compute scaled curve control points. final double cpx1 = (x1 - y1 * s) * radiusX; final double cpy1 = (y1 + x1 * s) * radiusY; final double cpx2 = (x2 + y2 * s) * radiusX; final double cpy2 = (y2 - x2 * s) * radiusY; final double endPointX = centerX + x2 * radiusX; final double endPointY = centerY + y2 * radiusY; final double rotationRad = rotation * math.pi / 180.0; final double cosR = math.cos(rotationRad); final double sinR = math.sin(rotationRad); if (startPath) { final double scaledX1 = x1 * radiusX; final double scaledY1 = y1 * radiusY; if (rotation == 0.0) { path.moveTo(centerX + scaledX1, centerY + scaledY1); } else { final double rotatedStartX = (scaledX1 * cosR) + (scaledY1 * sinR); final double rotatedStartY = (scaledY1 * cosR) - (scaledX1 * sinR); path.moveTo(centerX + rotatedStartX, centerY + rotatedStartY); } } if (rotation == 0.0) { path.cubicTo(centerX + cpx1, centerY + cpy1, centerX + cpx2, centerY + cpy2, endPointX, endPointY); } else { final double rotatedCpx1 = centerX + (cpx1 * cosR) + (cpy1 * sinR); final double rotatedCpy1 = centerY + (cpy1 * cosR) - (cpx1 * sinR); final double rotatedCpx2 = centerX + (cpx2 * cosR) + (cpy2 * sinR); final double rotatedCpy2 = centerY + (cpy2 * cosR) - (cpx2 * sinR); final double rotatedEndX = centerX + ((endPointX - centerX) * cosR) + ((endPointY - centerY) * sinR); final double rotatedEndY = centerY + ((endPointY - centerY) * cosR) - ((endPointX - centerX) * sinR); path.cubicTo(rotatedCpx1, rotatedCpy1, rotatedCpx2, rotatedCpy2, rotatedEndX, rotatedEndY); } } @override String toString() { String result = super.toString(); assert(() { result = 'Ellipse($x, $y, $radiusX, $radiusY)'; return true; }()); return result; } } class QuadraticCurveTo extends PathCommand { const QuadraticCurveTo(this.x1, this.y1, this.x2, this.y2); final double x1; final double y1; final double x2; final double y2; @override QuadraticCurveTo shifted(ui.Offset offset) { return QuadraticCurveTo( x1 + offset.dx, y1 + offset.dy, x2 + offset.dx, y2 + offset.dy); } @override void transform(Float32List matrix4, ui.Path targetPath) { final double m0 = matrix4[0]; final double m1 = matrix4[1]; final double m4 = matrix4[4]; final double m5 = matrix4[5]; final double m12 = matrix4[12]; final double m13 = matrix4[13]; final double transformedX1 = (m0 * x1) + (m4 * y1) + m12; final double transformedY1 = (m1 * x1) + (m5 * y1) + m13; final double transformedX2 = (m0 * x2) + (m4 * y2) + m12; final double transformedY2 = (m1 * x2) + (m5 * y2) + m13; targetPath.quadraticBezierTo( transformedX1, transformedY1, transformedX2, transformedY2); } @override String toString() { String result = super.toString(); assert(() { result = 'QuadraticCurveTo($x1, $y1, $x2, $y2)'; return true; }()); return result; } } class BezierCurveTo extends PathCommand { const BezierCurveTo(this.x1, this.y1, this.x2, this.y2, this.x3, this.y3); final double x1; final double y1; final double x2; final double y2; final double x3; final double y3; @override BezierCurveTo shifted(ui.Offset offset) { return BezierCurveTo(x1 + offset.dx, y1 + offset.dy, x2 + offset.dx, y2 + offset.dy, x3 + offset.dx, y3 + offset.dy); } @override void transform(Float32List matrix4, ui.Path targetPath) { final double s0 = matrix4[0]; final double s1 = matrix4[1]; final double s4 = matrix4[4]; final double s5 = matrix4[5]; final double s12 = matrix4[12]; final double s13 = matrix4[13]; final double transformedX1 = (s0 * x1) + (s4 * y1) + s12; final double transformedY1 = (s1 * x1) + (s5 * y1) + s13; final double transformedX2 = (s0 * x2) + (s4 * y2) + s12; final double transformedY2 = (s1 * x2) + (s5 * y2) + s13; final double transformedX3 = (s0 * x3) + (s4 * y3) + s12; final double transformedY3 = (s1 * x3) + (s5 * y3) + s13; targetPath.cubicTo(transformedX1, transformedY1, transformedX2, transformedY2, transformedX3, transformedY3); } @override String toString() { String result = super.toString(); assert(() { result = 'BezierCurveTo($x1, $y1, $x2, $y2, $x3, $y3)'; return true; }()); return result; } } class RectCommand extends PathCommand { const RectCommand(this.x, this.y, this.width, this.height); final double x; final double y; final double width; final double height; @override RectCommand shifted(ui.Offset offset) { return RectCommand(x + offset.dx, y + offset.dy, width, height); } @override void transform(Float32List matrix4, ui.Path targetPath) { final double s0 = matrix4[0]; final double s1 = matrix4[1]; final double s4 = matrix4[4]; final double s5 = matrix4[5]; final double s12 = matrix4[12]; final double s13 = matrix4[13]; final double transformedX1 = (s0 * x) + (s4 * y) + s12; final double transformedY1 = (s1 * x) + (s5 * y) + s13; final double x2 = x + width; final double y2 = y + height; final double transformedX2 = (s0 * x2) + (s4 * y) + s12; final double transformedY2 = (s1 * x2) + (s5 * y) + s13; final double transformedX3 = (s0 * x2) + (s4 * y2) + s12; final double transformedY3 = (s1 * x2) + (s5 * y2) + s13; final double transformedX4 = (s0 * x) + (s4 * y2) + s12; final double transformedY4 = (s1 * x) + (s5 * y2) + s13; if (transformedY1 == transformedY2 && transformedY3 == transformedY4 && transformedX1 == transformedX4 && transformedX2 == transformedX3) { // It is still a rectangle. targetPath.addRect(ui.Rect.fromLTRB( transformedX1, transformedY1, transformedX3, transformedY3)); } else { targetPath.moveTo(transformedX1, transformedY1); targetPath.lineTo(transformedX2, transformedY2); targetPath.lineTo(transformedX3, transformedY3); targetPath.lineTo(transformedX4, transformedY4); targetPath.close(); } } @override String toString() { String result = super.toString(); assert(() { result = 'Rect($x, $y, $width, $height)'; return true; }()); return result; } } class RRectCommand extends PathCommand { const RRectCommand(this.rrect); final ui.RRect rrect; @override RRectCommand shifted(ui.Offset offset) { return RRectCommand(rrect.shift(offset)); } @override void transform(Float32List matrix4, SurfacePath targetPath) { final ui.Path roundRectPath = ui.Path(); RRectToPathRenderer(roundRectPath).render(rrect); targetPath.addPathWithMode(roundRectPath, 0, 0, matrix4, SPathAddPathMode.kAppend); } @override String toString() { String result = super.toString(); assert(() { result = '$rrect'; return true; }()); return result; } } class CloseCommand extends PathCommand { @override CloseCommand shifted(ui.Offset offset) { return this; } @override void transform(Float32List matrix4, ui.Path targetPath) { targetPath.close(); } @override String toString() { String result = super.toString(); assert(() { result = 'Close()'; return true; }()); return result; } } class _PaintBounds { _PaintBounds(this.maxPaintBounds); // Bounds of maximum area that is paintable by canvas ops. final ui.Rect maxPaintBounds; bool _didPaintInsideClipArea = false; // Bounds of actually painted area. If _left is not set, reported paintBounds // should be empty since growLTRB calls were outside active clipping // region. double _left = double.maxFinite; double _top = double.maxFinite; double _right = -double.maxFinite; double _bottom = -double.maxFinite; // Stack of transforms. final List<Matrix4> _transforms = <Matrix4>[]; // Stack of clip bounds. final List<ui.Rect?> _clipStack = <ui.Rect?>[]; bool _currentMatrixIsIdentity = true; Matrix4 _currentMatrix = Matrix4.identity(); bool _clipRectInitialized = false; double _currentClipLeft = 0.0, _currentClipTop = 0.0, _currentClipRight = 0.0, _currentClipBottom = 0.0; void translate(double dx, double dy) { if (dx != 0.0 || dy != 0.0) { _currentMatrixIsIdentity = false; } _currentMatrix.translate(dx, dy); } void scale(double sx, double sy) { if (sx != 1.0 || sy != 1.0) { _currentMatrixIsIdentity = false; } _currentMatrix.scale(sx, sy, 1.0); } void rotateZ(double radians) { if (radians != 0.0) { _currentMatrixIsIdentity = false; } _currentMatrix.rotateZ(radians); } void transform(Float32List matrix4) { final Matrix4 m4 = Matrix4.fromFloat32List(matrix4); _currentMatrix.multiply(m4); _currentMatrixIsIdentity = _currentMatrix.isIdentity(); } void skew(double sx, double sy) { _currentMatrixIsIdentity = false; // DO NOT USE Matrix4.skew(sx, sy)! It treats sx and sy values as radians, // but in our case they are transform matrix values. final Matrix4 skewMatrix = Matrix4.identity(); final Float32List storage = skewMatrix.storage; storage[1] = sy; storage[4] = sx; _currentMatrix.multiply(skewMatrix); } static final Float32List _tempRectData = Float32List(4); void clipRect(final ui.Rect rect, DrawCommand command) { double left = rect.left; double top = rect.top; double right = rect.right; double bottom = rect.bottom; // If we have an active transform, calculate screen relative clipping // rectangle and union with current clipping rectangle. if (!_currentMatrixIsIdentity) { _tempRectData[0] = left; _tempRectData[1] = top; _tempRectData[2] = right; _tempRectData[3] = bottom; transformLTRB(_currentMatrix, _tempRectData); left = _tempRectData[0]; top = _tempRectData[1]; right = _tempRectData[2]; bottom = _tempRectData[3]; } if (!_clipRectInitialized) { _currentClipLeft = left; _currentClipTop = top; _currentClipRight = right; _currentClipBottom = bottom; _clipRectInitialized = true; } else { if (left > _currentClipLeft) { _currentClipLeft = left; } if (top > _currentClipTop) { _currentClipTop = top; } if (right < _currentClipRight) { _currentClipRight = right; } if (bottom < _currentClipBottom) { _currentClipBottom = bottom; } } if (_currentClipLeft >= _currentClipRight || _currentClipTop >= _currentClipBottom) { command.isClippedOut = true; } else { command.leftBound = _currentClipLeft; command.topBound = _currentClipTop; command.rightBound = _currentClipRight; command.bottomBound = _currentClipBottom; } } ui.Rect? getDestinationClipBounds() { if (!_clipRectInitialized) { return null; } else { return ui.Rect.fromLTRB( _currentClipLeft, _currentClipTop, _currentClipRight, _currentClipBottom, ); } } /// Grow painted area to include given rectangle. void grow(ui.Rect r, DrawCommand command) { growLTRB(r.left, r.top, r.right, r.bottom, command); } /// Grow painted area to include given rectangle and precompute /// clipped out state for command. void growLTRB(double left, double top, double right, double bottom, DrawCommand command) { if (left == right || top == bottom) { command.isClippedOut = true; return; } double transformedPointLeft = left; double transformedPointTop = top; double transformedPointRight = right; double transformedPointBottom = bottom; if (!_currentMatrixIsIdentity) { _tempRectData[0] = left; _tempRectData[1] = top; _tempRectData[2] = right; _tempRectData[3] = bottom; transformLTRB(_currentMatrix, _tempRectData); transformedPointLeft = _tempRectData[0]; transformedPointTop = _tempRectData[1]; transformedPointRight = _tempRectData[2]; transformedPointBottom = _tempRectData[3]; } if (_clipRectInitialized) { if (transformedPointLeft >= _currentClipRight) { command.isClippedOut = true; return; } if (transformedPointRight <= _currentClipLeft) { command.isClippedOut = true; return; } if (transformedPointTop >= _currentClipBottom) { command.isClippedOut = true; return; } if (transformedPointBottom <= _currentClipTop) { command.isClippedOut = true; return; } if (transformedPointLeft < _currentClipLeft) { transformedPointLeft = _currentClipLeft; } if (transformedPointRight > _currentClipRight) { transformedPointRight = _currentClipRight; } if (transformedPointTop < _currentClipTop) { transformedPointTop = _currentClipTop; } if (transformedPointBottom > _currentClipBottom) { transformedPointBottom = _currentClipBottom; } } command.leftBound = transformedPointLeft; command.topBound = transformedPointTop; command.rightBound = transformedPointRight; command.bottomBound = transformedPointBottom; if (_didPaintInsideClipArea) { _left = math.min( math.min(_left, transformedPointLeft), transformedPointRight); _right = math.max( math.max(_right, transformedPointLeft), transformedPointRight); _top = math.min(math.min(_top, transformedPointTop), transformedPointBottom); _bottom = math.max( math.max(_bottom, transformedPointTop), transformedPointBottom); } else { _left = math.min(transformedPointLeft, transformedPointRight); _right = math.max(transformedPointLeft, transformedPointRight); _top = math.min(transformedPointTop, transformedPointBottom); _bottom = math.max(transformedPointTop, transformedPointBottom); } _didPaintInsideClipArea = true; } /// Grow painted area to include given rectangle. void growBounds(ui.Rect bounds) { final double left = bounds.left; final double top = bounds.top; final double right = bounds.right; final double bottom = bounds.bottom; if (left == right || top == bottom) { return; } double transformedPointLeft = left; double transformedPointTop = top; double transformedPointRight = right; double transformedPointBottom = bottom; if (!_currentMatrixIsIdentity) { _tempRectData[0] = left; _tempRectData[1] = top; _tempRectData[2] = right; _tempRectData[3] = bottom; transformLTRB(_currentMatrix, _tempRectData); transformedPointLeft = _tempRectData[0]; transformedPointTop = _tempRectData[1]; transformedPointRight = _tempRectData[2]; transformedPointBottom = _tempRectData[3]; } if (_didPaintInsideClipArea) { _left = math.min( math.min(_left, transformedPointLeft), transformedPointRight); _right = math.max( math.max(_right, transformedPointLeft), transformedPointRight); _top = math.min(math.min(_top, transformedPointTop), transformedPointBottom); _bottom = math.max( math.max(_bottom, transformedPointTop), transformedPointBottom); } else { _left = math.min(transformedPointLeft, transformedPointRight); _right = math.max(transformedPointLeft, transformedPointRight); _top = math.min(transformedPointTop, transformedPointBottom); _bottom = math.max(transformedPointTop, transformedPointBottom); } _didPaintInsideClipArea = true; } void saveTransformsAndClip() { _transforms.add(_currentMatrix.clone()); _clipStack.add(_clipRectInitialized ? ui.Rect.fromLTRB(_currentClipLeft, _currentClipTop, _currentClipRight, _currentClipBottom) : null); } void restoreTransformsAndClip() { _currentMatrix = _transforms.removeLast(); final ui.Rect? clipRect = _clipStack.removeLast(); if (clipRect != null) { _currentClipLeft = clipRect.left; _currentClipTop = clipRect.top; _currentClipRight = clipRect.right; _currentClipBottom = clipRect.bottom; _clipRectInitialized = true; } else if (_clipRectInitialized) { _clipRectInitialized = false; } } ui.Rect computeBounds() { if (!_didPaintInsideClipArea) { return ui.Rect.zero; } // The framework may send us NaNs in the case when it attempts to invert an // infinitely size rect. final double maxLeft = maxPaintBounds.left.isNaN ? double.negativeInfinity : maxPaintBounds.left; final double maxRight = maxPaintBounds.right.isNaN ? double.infinity : maxPaintBounds.right; final double maxTop = maxPaintBounds.top.isNaN ? double.negativeInfinity : maxPaintBounds.top; final double maxBottom = maxPaintBounds.bottom.isNaN ? double.infinity : maxPaintBounds.bottom; final double left = math.min(_left, _right); final double right = math.max(_left, _right); final double top = math.min(_top, _bottom); final double bottom = math.max(_top, _bottom); if (right < maxLeft || bottom < maxTop) { // Computed and max bounds do not intersect. return ui.Rect.zero; } return ui.Rect.fromLTRB( math.max(left, maxLeft), math.max(top, maxTop), math.min(right, maxRight), math.min(bottom, maxBottom), ); } @override String toString() { String result = super.toString(); assert(() { final ui.Rect bounds = computeBounds(); result = '_PaintBounds($bounds of size ${bounds.size})'; return true; }()); return result; } } /// Computes the length of the visual effect caused by paint parameters, such /// as blur and stroke width. /// /// This paint spread should be taken into accound when estimating bounding /// boxes for paint operations that apply the paint. double _getPaintSpread(SurfacePaint paint) { double spread = 0.0; final ui.MaskFilter? maskFilter = paint.maskFilter; if (maskFilter != null) { // Multiply by 2 because the sigma is the standard deviation rather than // the length of the blur. // See also: https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/blur spread += maskFilter.webOnlySigma * 2.0; } if (paint.strokeWidth != 0) { // The multiplication by sqrt(2) is to account for line joints that // meet at 90-degree angle. Division by 2 is because only half of the // stroke is sticking out of the original shape. The other half is // inside the shape. const double sqrtOfTwoDivByTwo = 0.70710678118; spread += paint.strokeWidth * sqrtOfTwoDivByTwo; } return spread; } /// Contains metrics collected by recording canvas to provide data for /// rendering heuristics (canvas use vs DOM). class RenderStrategy { RenderStrategy(); /// Whether paint commands contain image elements. bool hasImageElements = false; /// Whether paint commands contain paragraphs. bool hasParagraphs = false; /// Whether paint commands are doing arbitrary operations /// not expressible via pure DOM elements. /// /// This is used to decide whether to use simplified DomCanvas. bool hasArbitraryPaint = false; /// Whether commands are executed within a shadermask or color filter. /// /// Webkit doesn't apply filters to canvas elements in its child /// element tree. When this is set to true, we prevent canvas usage in /// bitmap canvas and instead render using dom primitives and svg only. bool isInsideSvgFilterTree = false; /// Merges render strategy settings from a child recording. void merge(RenderStrategy childStrategy) { hasImageElements |= childStrategy.hasImageElements; hasParagraphs |= childStrategy.hasParagraphs; hasArbitraryPaint |= childStrategy.hasArbitraryPaint; } }
engine/lib/web_ui/lib/src/engine/html/recording_canvas.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/recording_canvas.dart", "repo_id": "engine", "token_count": 23375 }
264
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'dart:typed_data'; import 'package:meta/meta.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; Duration _kDefaultWebDecoderExpireDuration = const Duration(seconds: 3); Duration _kWebDecoderExpireDuration = _kDefaultWebDecoderExpireDuration; /// Overrides the inactivity duration after which the web decoder is closed. /// /// This should only be used in tests. void debugOverrideWebDecoderExpireDuration(Duration override) { _kWebDecoderExpireDuration = override; } /// Restores the web decoder inactivity expiry duration to its original value. /// /// This should only be used in tests. void debugRestoreWebDecoderExpireDuration() { _kWebDecoderExpireDuration = _kDefaultWebDecoderExpireDuration; } /// Image decoder backed by the browser's `ImageDecoder`. abstract class BrowserImageDecoder implements ui.Codec { BrowserImageDecoder({ required this.contentType, required this.dataSource, required this.debugSource, }); final String contentType; final JSAny dataSource; final String debugSource; @override late int frameCount; @override late int repetitionCount; /// Whether this decoder has been disposed of. /// /// Once this turns true it stays true forever, and this decoder becomes /// unusable. bool _isDisposed = false; @override void dispose() { _isDisposed = true; // This releases all resources, including any currently running decoding work. _cachedWebDecoder?.close(); _cachedWebDecoder = null; } void _debugCheckNotDisposed() { assert( !_isDisposed, 'Cannot use this image decoder. It has been disposed of.' ); } /// The index of the frame that will be decoded on the next call of [getNextFrame]; int _nextFrameIndex = 0; /// Creating a new decoder is expensive, so we cache the decoder for reuse. /// /// This decoder is closed and the field is nulled out after some time of /// inactivity. /// // TODO(jacksongardner): Evaluate whether this complexity is necessary. // See https://github.com/flutter/flutter/issues/127548 ImageDecoder? _cachedWebDecoder; /// The underlying image decoder used to decode images. /// /// This value is volatile. It may be closed or become null any time. /// /// /// This is only meant to be used in tests. @visibleForTesting ImageDecoder? get debugCachedWebDecoder => _cachedWebDecoder; final AlarmClock _cacheExpirationClock = AlarmClock(() => DateTime.now()); Future<void> initialize() => _getOrCreateWebDecoder(); Future<ImageDecoder> _getOrCreateWebDecoder() async { if (_cachedWebDecoder != null) { // Give the cached value some time for reuse, e.g. if the image is // currently animating. _cacheExpirationClock.datetime = DateTime.now().add(_kWebDecoderExpireDuration); return _cachedWebDecoder!; } // Null out the callback so the clock doesn't try to expire the decoder // while it's initializing. There's no way to tell how long the // initialization will take place. We just let it proceed at its own pace. _cacheExpirationClock.callback = null; try { final ImageDecoder webDecoder = ImageDecoder(ImageDecoderOptions( type: contentType.toJS, data: dataSource, // Flutter always uses premultiplied alpha when decoding. premultiplyAlpha: 'premultiply'.toJS, // "default" gives the browser the liberty to convert to display-appropriate // color space, typically SRGB, which is what we want. colorSpaceConversion: 'default'.toJS, // Flutter doesn't give the developer a way to customize this, so if this // is an animated image we should prefer the animated track. preferAnimation: true.toJS, )); await promiseToFuture<void>(webDecoder.tracks.ready); // Flutter doesn't have an API for progressive loading of images, so we // wait until the image is fully decoded. // package:js bindings don't work with getters that return a Promise, which // is why js_util is used instead. await promiseToFuture<void>(getJsProperty(webDecoder, 'completed')); frameCount = webDecoder.tracks.selectedTrack!.frameCount.toInt(); // We coerce the DOM's `repetitionCount` into an int by explicitly // handling `infinity`. Note: This will still throw if the DOM returns a // `NaN`. final double rawRepetitionCount = webDecoder.tracks.selectedTrack!.repetitionCount; repetitionCount = rawRepetitionCount == double.infinity ? -1 : rawRepetitionCount.toInt(); _cachedWebDecoder = webDecoder; // Expire the decoder if it's not used for several seconds. If the image is // not animated, it could mean that the framework has cached the frame and // therefore doesn't need the decoder any more, or it could mean that the // widget is gone and it's time to collect resources associated with it. // If it's an animated image it means the animation has stopped, otherwise // we'd see calls to [getNextFrame] which would update the expiry date on // the decoder. If the animation is stopped for long enough, it's better // to collect resources. If and when the animation resumes, a new decoder // will be instantiated. _cacheExpirationClock.callback = () { _cachedWebDecoder?.close(); _cachedWebDecoder = null; _cacheExpirationClock.callback = null; }; _cacheExpirationClock.datetime = DateTime.now().add(_kWebDecoderExpireDuration); return webDecoder; } catch (error) { if (domInstanceOfString(error, 'DOMException')) { if ((error as DomException).name == DomException.notSupported) { throw ImageCodecException( "Image file format ($contentType) is not supported by this browser's ImageDecoder API.\n" 'Image source: $debugSource', ); } } throw ImageCodecException( "Failed to decode image using the browser's ImageDecoder API.\n" 'Image source: $debugSource\n' 'Original browser error: $error' ); } } @override Future<ui.FrameInfo> getNextFrame() async { _debugCheckNotDisposed(); final ImageDecoder webDecoder = await _getOrCreateWebDecoder(); final DecodeResult result = await promiseToFuture<DecodeResult>( webDecoder.decode(DecodeOptions(frameIndex: _nextFrameIndex.toJS)), ); final VideoFrame frame = result.image; _nextFrameIndex = (_nextFrameIndex + 1) % frameCount; // Duration can be null if the image is not animated. However, Flutter // requires a non-null value. 0 indicates that the frame is meant to be // displayed indefinitely, which is fine for a static image. final Duration duration = Duration(microseconds: frame.duration?.toInt() ?? 0); final ui.Image image = generateImageFromVideoFrame(frame); return AnimatedImageFrameInfo(duration, image); } ui.Image generateImageFromVideoFrame(VideoFrame frame); } /// Data for a single frame of an animated image. class AnimatedImageFrameInfo implements ui.FrameInfo { AnimatedImageFrameInfo(this.duration, this.image); @override final Duration duration; @override final ui.Image image; } /// Detects the image file format and returns the corresponding "Content-Type" /// value (a.k.a. MIME type). /// /// The returned value can be passed to `ImageDecoder` when decoding an image. /// /// Returns null if [data] cannot be mapped to a known content type. String? detectContentType(Uint8List data) { if (debugContentTypeDetector != null) { return debugContentTypeDetector!.call(data); } formatLoop: for (final ImageFileFormat format in ImageFileFormat.values) { if (data.length < format.header.length) { continue; } for (int i = 0; i < format.header.length; i++) { final int? magicByte = format.header[i]; if (magicByte == null) { // Wildcard, accepts everything. continue; } final int headerByte = data[i]; if (headerByte != magicByte) { continue formatLoop; } } return format.contentType; } if (isAvif(data)) { return 'image/avif'; } return null; } /// Represents an image file format, such as PNG or JPEG. class ImageFileFormat { const ImageFileFormat(this.header, this.contentType); /// First few bytes in the file that uniquely identify the image file format. /// /// Null elements are treated as wildcard values and are not checked. This is /// used to detect formats whose header is split up into multiple disjoint /// parts, such that the first part is not unique enough to identify the /// format. For example, without this, WebP may be confused with .ani /// (animated cursor), .cda, and other formats that start with "RIFF". final List<int?> header; /// The value that's passed as [_ImageDecoderOptions.type]. /// /// The server typically also uses this value as the "Content-Type" header, /// but servers are not required to correctly detect the type. This value /// is also known as MIME type. final String contentType; /// All image file formats known to the Flutter Web engine. /// /// This list may need to be changed as browsers adopt new formats, and drop /// support for obsolete ones. /// /// This list is checked linearly from top to bottom when detecting an image /// type. It should therefore contain the most popular file formats at the /// top, and less popular towards the bottom. static const List<ImageFileFormat> values = <ImageFileFormat>[ // ICO is not supported in Chrome. It is deemed too simple and too specific. See also: // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/webcodecs/image_decoder_external.cc;l=38;drc=fd8802b593110ea18a97ef044f8a40dd24a622ec // PNG ImageFileFormat(<int?>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], 'image/png'), // GIF87a ImageFileFormat(<int?>[0x47, 0x49, 0x46, 0x38, 0x37, 0x61], 'image/gif'), // GIF89a ImageFileFormat(<int?>[0x47, 0x49, 0x46, 0x38, 0x39, 0x61], 'image/gif'), // JPEG ImageFileFormat(<int?>[0xFF, 0xD8, 0xFF], 'image/jpeg'), // WebP ImageFileFormat(<int?>[0x52, 0x49, 0x46, 0x46, null, null, null, null, 0x57, 0x45, 0x42, 0x50], 'image/webp'), // BMP ImageFileFormat(<int?>[0x42, 0x4D], 'image/bmp'), ]; } /// Function signature of [debugContentTypeDetector], which is the same as the /// signature of [detectContentType]. typedef DebugContentTypeDetector = String? Function(Uint8List); /// If not null, replaces the functionality of [detectContentType] with its own. /// /// This is useful in tests, for example, to test unsupported content types. DebugContentTypeDetector? debugContentTypeDetector; /// A string of bytes that every AVIF image contains somehwere in its first 16 /// bytes. /// /// This signature is necessary but not sufficient, which may lead to false /// positives. For example, the file may be HEIC or a video. This is OK, /// because in the worst case, the image decoder fails to decode the file. /// This is something we must anticipate regardless of this detection logic. /// The codec must already protect itself from downloaded files lying about /// their contents. /// /// The alternative would be to implement a more precise detection, which would /// add complexity and code size. This is how Chromium does it: /// /// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/image-decoders/avif/avif_image_decoder.cc;l=504;drc=fd8802b593110ea18a97ef044f8a40dd24a622ec final List<int> _avifSignature = 'ftyp'.codeUnits; /// Optimistically detects whether [data] is an AVIF image file. bool isAvif(Uint8List data) { firstByteLoop: for (int i = 0; i < 16; i += 1) { for (int j = 0; j < _avifSignature.length; j += 1) { if (i + j >= data.length) { // Reached EOF without finding the signature. return false; } if (data[i + j] != _avifSignature[j]) { continue firstByteLoop; } } return true; } return false; } // Wraps another codec and resizes each output image. class ResizingCodec implements ui.Codec { ResizingCodec( this.delegate, { this.targetWidth, this.targetHeight, this.allowUpscaling = true, }); final ui.Codec delegate; final int? targetWidth; final int? targetHeight; final bool allowUpscaling; @override void dispose() => delegate.dispose(); @override int get frameCount => delegate.frameCount; @override Future<ui.FrameInfo> getNextFrame() async { final ui.FrameInfo frameInfo = await delegate.getNextFrame(); return AnimatedImageFrameInfo( frameInfo.duration, scaleImageIfNeeded( frameInfo.image, targetWidth: targetWidth, targetHeight: targetHeight, allowUpscaling: allowUpscaling ), ); } @override int get repetitionCount => delegate.frameCount; } ui.Size? _scaledSize( int width, int height, int? targetWidth, int? targetHeight, ) { if (targetWidth == width && targetHeight == height) { // Not scaled return null; } if (targetWidth == null) { if (targetHeight == null || targetHeight == height) { // Not scaled. return null; } targetWidth = (width * targetHeight / height).round(); } else if (targetHeight == null) { if (targetWidth == targetWidth) { // Not scaled. return null; } targetHeight = (height * targetWidth / width).round(); } return ui.Size(targetWidth.toDouble(), targetHeight.toDouble()); } ui.Image scaleImageIfNeeded( ui.Image image, { int? targetWidth, int? targetHeight, bool allowUpscaling = true, }) { final int width = image.width; final int height = image.height; final ui.Size? scaledSize = _scaledSize( width, height, targetWidth, targetHeight ); if (scaledSize == null) { return image; } if (!allowUpscaling && (scaledSize.width > width || scaledSize.height > height)) { return image; } final ui.Rect outputRect = ui.Rect.fromLTWH(0, 0, scaledSize.width, scaledSize.height); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder, outputRect); canvas.drawImageRect( image, ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()), outputRect, ui.Paint(), ); final ui.Picture picture = recorder.endRecording(); final ui.Image finalImage = picture.toImageSync( scaledSize.width.round(), scaledSize.height.round() ); picture.dispose(); image.dispose(); return finalImage; }
engine/lib/web_ui/lib/src/engine/image_decoder.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/image_decoder.dart", "repo_id": "engine", "token_count": 5008 }
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 'dart:async'; import 'package:ui/ui.dart' as ui; import 'dom.dart'; import 'html/bitmap_canvas.dart'; import 'html/recording_canvas.dart'; import 'html_image_codec.dart'; /// An implementation of [ui.PictureRecorder] backed by a [RecordingCanvas]. class EnginePictureRecorder implements ui.PictureRecorder { EnginePictureRecorder(); RecordingCanvas? _canvas; late ui.Rect cullRect; bool _isRecording = false; RecordingCanvas beginRecording(ui.Rect bounds) { assert(!_isRecording); cullRect = bounds; _isRecording = true; return _canvas = RecordingCanvas(cullRect); } @override bool get isRecording => _isRecording; @override EnginePicture endRecording() { if (!_isRecording) { // The mobile version returns an empty picture in this case. To match the // behavior we produce a blank picture too. beginRecording(ui.Rect.largest); } _isRecording = false; _canvas!.endRecording(); final EnginePicture result = EnginePicture(_canvas, cullRect); // We invoke the handler here, not in the Picture constructor, because we want // [result.approximateBytesUsed] to be available for the handler. ui.Picture.onCreate?.call(result); return result; } } /// An implementation of [ui.Picture] which is backed by a [RecordingCanvas]. class EnginePicture implements ui.Picture { /// This class is created by the engine, and should not be instantiated /// or extended directly. /// /// To create a [Picture], use a [PictureRecorder]. EnginePicture(this.recordingCanvas, this.cullRect); @override Future<ui.Image> toImage(int width, int height) async { final ui.Rect imageRect = ui.Rect.fromLTRB(0, 0, width.toDouble(), height.toDouble()); final BitmapCanvas canvas = BitmapCanvas.imageData(imageRect); recordingCanvas!.apply(canvas, imageRect); final String imageDataUrl = canvas.toDataUrl(); final DomHTMLImageElement imageElement = createDomHTMLImageElement() ..src = imageDataUrl ..width = width.toDouble() ..height = height.toDouble(); // The image loads asynchronously. We need to wait before returning, // otherwise the returned HtmlImage will be temporarily unusable. final Completer<ui.Image> onImageLoaded = Completer<ui.Image>.sync(); // Ignoring the returned futures from onError and onLoad because we're // communicating through the `onImageLoaded` completer. late final DomEventListener errorListener; errorListener = createDomEventListener((DomEvent event) { onImageLoaded.completeError(event); imageElement.removeEventListener('error', errorListener); }); imageElement.addEventListener('error', errorListener); late final DomEventListener loadListener; loadListener = createDomEventListener((DomEvent event) { onImageLoaded.complete(HtmlImage( imageElement, width, height, )); imageElement.removeEventListener('load', loadListener); }); imageElement.addEventListener('load', loadListener); return onImageLoaded.future; } @override ui.Image toImageSync(int width, int height) { throw UnsupportedError('toImageSync is not supported on the HTML backend. Use drawPicture instead, or toImage.'); } bool _disposed = false; @override void dispose() { ui.Picture.onDispose?.call(this); _disposed = true; } @override bool get debugDisposed { bool? result; assert(() { result = _disposed; return true; }()); if (result != null) { return result!; } throw StateError('Picture.debugDisposed is only available when asserts are enabled.'); } @override int get approximateBytesUsed => 0; final RecordingCanvas? recordingCanvas; final ui.Rect? cullRect; }
engine/lib/web_ui/lib/src/engine/picture.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/picture.dart", "repo_id": "engine", "token_count": 1310 }
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. /// JavaScript API bindings for browser APIs. /// /// The public surface of this API must be safe to use. In particular, using the /// API of this library it must not be possible to execute arbitrary code from /// strings by injecting it into HTML or URLs. @JS() library browser_api; import 'dart:async'; import 'dart:js_interop'; import 'dart:js_util' as js_util; import 'dart:math' as math; import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import 'browser_detection.dart'; import 'display.dart'; import 'dom.dart'; import 'vector_math.dart'; /// Returns true if [object] has property [name], false otherwise. /// /// This is equivalent to writing `name in object` in plain JavaScript. bool hasJsProperty(Object object, String name) { return js_util.hasProperty(object, name); } /// Returns the value of property [name] from a JavaScript [object]. /// /// This is equivalent to writing `object.name` in plain JavaScript. T getJsProperty<T>(Object object, String name) { return js_util.getProperty<T>(object, name); } const Set<String> _safeJsProperties = <String>{ 'decoding', '__flutter_state', }; /// Sets the value of property [name] on a JavaScript [object]. /// /// This is equivalent to writing `object.name = value` in plain JavaScript. T setJsProperty<T>(Object object, String name, T value) { assert( _safeJsProperties.contains(name), 'Attempted to set property "$name" on a JavaScript object. This property ' 'has not been checked for safety. Possible solutions to this problem:\n' ' - Do not set this property.\n' ' - Use a `js_util` API that does the same thing.\n' ' - Ensure that the property is safe then add it to _safeJsProperties set.', ); return js_util.setProperty<T>(object, name, value); } /// Converts a JavaScript `Promise` into Dart [Future]. Future<T> promiseToFuture<T>(Object jsPromise) { return js_util.promiseToFuture<T>(jsPromise); } /// Parses a string [source] into a double. /// /// Uses the JavaScript `parseFloat` function instead of Dart's [double.parse] /// because the latter can't parse strings like "20px". /// /// Returns null if it fails to parse. num? parseFloat(String source) { // Using JavaScript's `parseFloat` here because it can parse values // like "20px", while Dart's `double.tryParse` fails. final num? result = js_util.callMethod(domWindow, 'parseFloat', <Object>[source]); if (result == null || result.isNaN) { return null; } return result; } /// Used to decide if the browser tab still has the focus. /// /// This information is useful for deciding on the blur behavior. /// See [DefaultTextEditingStrategy]. /// /// This getter calls the `hasFocus` method of the `Document` interface. /// See for more details: /// https://developer.mozilla.org/en-US/docs/Web/API/Document/hasFocus bool get windowHasFocus => js_util.callMethod<bool>(domDocument, 'hasFocus', <dynamic>[]); /// Parses the font size of [element] and returns the value without a unit. num? parseFontSize(DomElement element) { num? fontSize; if (hasJsProperty(element, 'computedStyleMap')) { // Use the newer `computedStyleMap` API available on some browsers. final Object? computedStyleMap = js_util.callMethod<Object?>(element, 'computedStyleMap', const <Object?>[]); if (computedStyleMap is Object) { final Object? fontSizeObject = js_util.callMethod<Object?>(computedStyleMap, 'get', <Object?>['font-size']); if (fontSizeObject is Object) { fontSize = js_util.getProperty<num>(fontSizeObject, 'value'); } } } if (fontSize == null) { // Fallback to `getComputedStyle`. final String fontSizeString = domWindow.getComputedStyle(element).getPropertyValue('font-size'); fontSize = parseFloat(fontSizeString); } return fontSize; } /// Provides haptic feedback. void vibrate(int durationMs) { final DomNavigator navigator = domWindow.navigator; if (hasJsProperty(navigator, 'vibrate')) { js_util.callMethod<void>(navigator, 'vibrate', <num>[durationMs]); } } /// Creates a `<canvas>` but anticipates that the result may be null. /// /// The [DomCanvasElement] factory assumes that element allocation will /// succeed and will return a non-null element. This is not always true. For /// example, when Safari on iOS runs out of memory it returns null. DomCanvasElement? tryCreateCanvasElement(int width, int height) { final DomCanvasElement? canvas = js_util.callMethod<DomCanvasElement?>( domDocument, 'createElement', <dynamic>['CANVAS'], ); if (canvas == null) { return null; } try { canvas.width = width.toDouble(); canvas.height = height.toDouble(); } catch (e) { // It seems the tribal knowledge of why we anticipate an exception while // setting width/height on a non-null canvas and why it's OK to return null // in this case has been lost. Kudos to the one who can recover it and leave // a proper comment here! return null; } return canvas; } @JS('window.ImageDecoder') external JSAny? get __imageDecoderConstructor; Object? get _imageDecoderConstructor => __imageDecoderConstructor?.toObjectShallow; /// Environment variable that allows the developer to opt out of using browser's /// `ImageDecoder` API, and use the WASM codecs bundled with CanvasKit. /// /// While all reported severe issues with `ImageDecoder` have been fixed, this /// API remains relatively new. This option will allow developers to opt out of /// it, if they hit a severe bug that we did not anticipate. // TODO(yjbanov): remove this flag once we're fully confident in the new API. // https://github.com/flutter/flutter/issues/95277 const bool _browserImageDecodingEnabled = bool.fromEnvironment( 'BROWSER_IMAGE_DECODING_ENABLED', defaultValue: true, ); /// Whether the current browser supports `ImageDecoder`. bool browserSupportsImageDecoder = _defaultBrowserSupportsImageDecoder; /// Sets the value of [browserSupportsImageDecoder] to its default value. void debugResetBrowserSupportsImageDecoder() { browserSupportsImageDecoder = _defaultBrowserSupportsImageDecoder; } bool get _defaultBrowserSupportsImageDecoder => _browserImageDecodingEnabled && _imageDecoderConstructor != null && _isBrowserImageDecoderStable; // TODO(yjbanov): https://github.com/flutter/flutter/issues/122761 // Frequently, when a browser launches an API that other browsers already // support, there are subtle incompatibilities that may cause apps to crash if, // we blindly adopt the new implementation. This variable prevents us from // picking up potentially incompatible implementations of ImagdeDecoder API. // Instead, when a new browser engine launches the API, we'll evaluate it and // enable it explicitly. bool get _isBrowserImageDecoderStable => browserEngine == BrowserEngine.blink; /// Corresponds to the browser's `ImageDecoder` type. /// /// See also: /// /// * https://www.w3.org/TR/webcodecs/#imagedecoder-interface @JS('window.ImageDecoder') @staticInterop class ImageDecoder { external factory ImageDecoder(ImageDecoderOptions options); } extension ImageDecoderExtension on ImageDecoder { external ImageTrackList get tracks; @JS('complete') external JSBoolean get _complete; bool get complete => _complete.toDart; external JSPromise<JSAny?> decode(DecodeOptions options); external JSVoid close(); } /// Options passed to the `ImageDecoder` constructor. /// /// See also: /// /// * https://www.w3.org/TR/webcodecs/#imagedecoderinit-interface @JS() @anonymous @staticInterop class ImageDecoderOptions { external factory ImageDecoderOptions({ required JSString type, required JSAny data, required JSString premultiplyAlpha, JSNumber? desiredWidth, JSNumber? desiredHeight, required JSString colorSpaceConversion, required JSBoolean preferAnimation, }); } /// The result of [ImageDecoder.decode]. /// /// See also: /// /// * https://www.w3.org/TR/webcodecs/#imagedecoderesult-interface @JS() @anonymous @staticInterop class DecodeResult {} extension DecodeResultExtension on DecodeResult { external VideoFrame get image; @JS('complete') external JSBoolean get _complete; bool get complete => _complete.toDart; } /// Options passed to [ImageDecoder.decode]. /// /// See also: /// /// * https://www.w3.org/TR/webcodecs/#dictdef-imagedecodeoptions @JS() @anonymous @staticInterop class DecodeOptions { external factory DecodeOptions({ required JSNumber frameIndex, }); } /// The only frame in a static image, or one of the frames in an animated one. /// /// This class maps to the `VideoFrame` type provided by the browser. /// /// See also: /// /// * https://www.w3.org/TR/webcodecs/#videoframe-interface @JS() @anonymous @staticInterop class VideoFrame implements DomCanvasImageSource {} extension VideoFrameExtension on VideoFrame { @JS('allocationSize') external JSNumber _allocationSize(); double allocationSize() => _allocationSize().toDartDouble; @JS('copyTo') external JSPromise<JSAny?> _copyTo(JSAny destination); JSPromise<JSAny?> copyTo(Object destination) => _copyTo(destination.toJSAnyShallow); @JS('format') external JSString? get _format; String? get format => _format?.toDart; @JS('codedWidth') external JSNumber get _codedWidth; double get codedWidth => _codedWidth.toDartDouble; @JS('codedHeight') external JSNumber get _codedHeight; double get codedHeight => _codedHeight.toDartDouble; @JS('displayWidth') external JSNumber get _displayWidth; double get displayWidth => _displayWidth.toDartDouble; @JS('displayHeight') external JSNumber get _displayHeight; double get displayHeight => _displayHeight.toDartDouble; @JS('duration') external JSNumber? get _duration; double? get duration => _duration?.toDartDouble; external VideoFrame clone(); external JSVoid close(); } /// Corresponds to the browser's `ImageTrackList` type. /// /// See also: /// /// * https://www.w3.org/TR/webcodecs/#imagetracklist-interface @JS() @anonymous @staticInterop class ImageTrackList {} extension ImageTrackListExtension on ImageTrackList { external JSPromise<JSAny?> get ready; external ImageTrack? get selectedTrack; } /// Corresponds to the browser's `ImageTrack` type. /// /// See also: /// /// * https://www.w3.org/TR/webcodecs/#imagetrack @JS() @anonymous @staticInterop class ImageTrack {} extension ImageTrackExtension on ImageTrack { @JS('repetitionCount') external JSNumber get _repetitionCount; double get repetitionCount => _repetitionCount.toDartDouble; @JS('frameCount') external JSNumber get _frameCount; double get frameCount => _frameCount.toDartDouble; } void scaleCanvas2D(Object context2d, num x, num y) { js_util.callMethod<void>(context2d, 'scale', <dynamic>[x, y]); } void drawImageCanvas2D(Object context2d, Object imageSource, num width, num height) { js_util.callMethod<void>(context2d, 'drawImage', <dynamic>[ imageSource, width, height, ]); } void vertexAttribPointerGlContext( Object glContext, Object index, num size, Object type, bool normalized, num stride, num offset, ) { js_util.callMethod<void>(glContext, 'vertexAttribPointer', <dynamic>[ index, size, type, normalized, stride, offset, ]); } /// Compiled and cached gl program. class GlProgram { GlProgram(this.program); final Object program; } /// JS Interop helper for webgl apis. class GlContext { factory GlContext(OffScreenCanvas offScreenCanvas) { return OffScreenCanvas.supported ? GlContext._fromOffscreenCanvas(offScreenCanvas.offScreenCanvas!) : GlContext._fromCanvasElement( offScreenCanvas.canvasElement!, webGLVersion == WebGLVersion.webgl1); } GlContext._fromOffscreenCanvas(DomOffscreenCanvas canvas) : glContext = canvas.getContext('webgl2', <String, dynamic>{'premultipliedAlpha': false})!, isOffscreen = true { _programCache = <String, GlProgram?>{}; _canvas = canvas; } GlContext._fromCanvasElement(DomCanvasElement canvas, bool useWebGl1) : glContext = canvas.getContext(useWebGl1 ? 'webgl' : 'webgl2', <String, dynamic>{'premultipliedAlpha': false})!, isOffscreen = false { _programCache = <String, GlProgram?>{}; _canvas = canvas; } final Object glContext; final bool isOffscreen; Object? _kCompileStatus; Object? _kArrayBuffer; Object? _kElementArrayBuffer; Object? _kStaticDraw; Object? _kFloat; Object? _kColorBufferBit; Object? _kTexture2D; Object? _kTextureWrapS; Object? _kTextureWrapT; Object? _kRepeat; Object? _kClampToEdge; Object? _kMirroredRepeat; Object? _kTriangles; Object? _kLinkStatus; Object? _kUnsignedByte; Object? _kUnsignedShort; Object? _kRGBA; Object? _kLinear; Object? _kTextureMinFilter; double? _kTexture0; Object? _canvas; int? _widthInPixels; int? _heightInPixels; static late Map<String, GlProgram?> _programCache; void setViewportSize(int width, int height) { _widthInPixels = width; _heightInPixels = height; } /// Draws Gl context contents to canvas context. void drawImage(DomCanvasRenderingContext2D context, double left, double top) { // Actual size of canvas may be larger than viewport size. Use // source/destination to draw part of the image data. js_util.callMethod<void>(context, 'drawImage', <dynamic>[_canvas, 0, 0, _widthInPixels, _heightInPixels, left, top, _widthInPixels, _heightInPixels]); } GlProgram cacheProgram( String vertexShaderSource, String fragmentShaderSource) { final String cacheKey = '$vertexShaderSource||$fragmentShaderSource'; GlProgram? cachedProgram = _programCache[cacheKey]; if (cachedProgram == null) { // Create and compile shaders. final Object vertexShader = compileShader('VERTEX_SHADER', vertexShaderSource); final Object fragmentShader = compileShader('FRAGMENT_SHADER', fragmentShaderSource); // Create a gl program and link shaders. final Object program = createProgram(); attachShader(program, vertexShader); attachShader(program, fragmentShader); linkProgram(program); cachedProgram = GlProgram(program); _programCache[cacheKey] = cachedProgram; } return cachedProgram; } Object compileShader(String shaderType, String source) { final Object? shader = _createShader(shaderType); if (shader == null) { throw Exception(error); } js_util.callMethod<void>(glContext, 'shaderSource', <dynamic>[shader, source]); js_util.callMethod<void>(glContext, 'compileShader', <dynamic>[shader]); final bool shaderStatus = js_util.callMethod<bool>( glContext, 'getShaderParameter', <dynamic>[shader, compileStatus], ); if (!shaderStatus) { throw Exception('Shader compilation failed: ${getShaderInfoLog(shader)}'); } return shader; } Object createProgram() => js_util.callMethod<Object>(glContext, 'createProgram', const <dynamic>[]); void attachShader(Object? program, Object shader) { js_util.callMethod<void>(glContext, 'attachShader', <dynamic>[program, shader]); } void linkProgram(Object program) { js_util.callMethod<void>(glContext, 'linkProgram', <dynamic>[program]); final bool programStatus = js_util.callMethod<bool>( glContext, 'getProgramParameter', <dynamic>[program, kLinkStatus], ); if (!programStatus) { throw Exception(getProgramInfoLog(program)); } } void useProgram(GlProgram program) { js_util.callMethod<void>(glContext, 'useProgram', <dynamic>[program.program]); } Object? createBuffer() => js_util.callMethod(glContext, 'createBuffer', const <dynamic>[]); void bindArrayBuffer(Object? buffer) { js_util.callMethod<void>(glContext, 'bindBuffer', <dynamic>[kArrayBuffer, buffer]); } Object? createVertexArray() => js_util.callMethod(glContext, 'createVertexArray', const <dynamic>[]); void bindVertexArray(Object vertexObjectArray) { js_util.callMethod<void>(glContext, 'bindVertexArray', <dynamic>[vertexObjectArray]); } void unbindVertexArray() { js_util.callMethod<void>(glContext, 'bindVertexArray', <dynamic>[null]); } void bindElementArrayBuffer(Object? buffer) { js_util.callMethod<void>(glContext, 'bindBuffer', <dynamic>[kElementArrayBuffer, buffer]); } Object? createTexture() => js_util.callMethod(glContext, 'createTexture', const <dynamic>[]); void generateMipmap(dynamic target) => js_util.callMethod(glContext, 'generateMipmap', <dynamic>[target]); void bindTexture(dynamic target, Object? buffer) { js_util.callMethod<void>(glContext, 'bindTexture', <dynamic>[target, buffer]); } void activeTexture(double textureUnit) { js_util.callMethod<void>(glContext, 'activeTexture', <dynamic>[textureUnit]); } void texImage2D(dynamic target, int level, dynamic internalFormat, dynamic format, dynamic dataType, dynamic pixels, {int? width, int? height, int border = 0}) { if (width == null) { js_util.callMethod<void>(glContext, 'texImage2D', <dynamic>[ target, level, internalFormat, format, dataType, pixels]); } else { js_util.callMethod<void>(glContext, 'texImage2D', <dynamic>[ target, level, internalFormat, width, height, border, format, dataType, pixels]); } } void texParameteri(dynamic target, dynamic parameterName, dynamic value) { js_util.callMethod<void>(glContext, 'texParameteri', <dynamic>[ target, parameterName, value]); } void deleteBuffer(Object buffer) { js_util.callMethod<void>(glContext, 'deleteBuffer', <dynamic>[buffer]); } void bufferData(TypedData? data, dynamic type) { js_util.callMethod<void>(glContext, 'bufferData', <dynamic>[kArrayBuffer, data, type]); } void bufferElementData(TypedData? data, dynamic type) { js_util.callMethod<void>(glContext, 'bufferData', <dynamic>[kElementArrayBuffer, data, type]); } void enableVertexAttribArray(dynamic index) { js_util.callMethod<void>(glContext, 'enableVertexAttribArray', <dynamic>[index]); } /// Clear background. void clear() { js_util.callMethod<void>(glContext, 'clear', <dynamic>[kColorBufferBit]); } /// Destroys gl context. void dispose() { final Object? loseContextExtension = _getExtension('WEBGL_lose_context'); if (loseContextExtension != null) { js_util.callMethod<void>( loseContextExtension, 'loseContext', const <dynamic>[], ); } } void deleteProgram(Object program) { js_util.callMethod<void>(glContext, 'deleteProgram', <dynamic>[program]); } void deleteShader(Object shader) { js_util.callMethod<void>(glContext, 'deleteShader', <dynamic>[shader]); } Object? _getExtension(String extensionName) => js_util.callMethod<Object?>(glContext, 'getExtension', <dynamic>[extensionName]); void drawTriangles(int triangleCount, ui.VertexMode vertexMode) { final dynamic mode = _triangleTypeFromMode(vertexMode); js_util.callMethod<void>(glContext, 'drawArrays', <dynamic>[mode, 0, triangleCount]); } void drawElements(dynamic type, int indexCount, dynamic indexType) { js_util.callMethod<void>(glContext, 'drawElements', <dynamic>[type, indexCount, indexType, 0]); } /// Sets affine transformation from normalized device coordinates /// to window coordinates void viewport(double x, double y, double width, double height) { js_util.callMethod<void>(glContext, 'viewport', <dynamic>[x, y, width, height]); } Object _triangleTypeFromMode(ui.VertexMode mode) { switch (mode) { case ui.VertexMode.triangles: return kTriangles; case ui.VertexMode.triangleFan: return kTriangleFan; case ui.VertexMode.triangleStrip: return kTriangleStrip; } } Object? _createShader(String shaderType) => js_util.callMethod( glContext, 'createShader', <Object?>[js_util.getProperty<Object?>(glContext, shaderType)]); /// Error state of gl context. Object? get error => js_util.callMethod(glContext, 'getError', const <dynamic>[]); /// Shader compiler error, if this returns [kFalse], to get details use /// [getShaderInfoLog]. Object? get compileStatus => _kCompileStatus ??= js_util.getProperty(glContext, 'COMPILE_STATUS'); Object? get kArrayBuffer => _kArrayBuffer ??= js_util.getProperty(glContext, 'ARRAY_BUFFER'); Object? get kElementArrayBuffer => _kElementArrayBuffer ??= js_util.getProperty(glContext, 'ELEMENT_ARRAY_BUFFER'); Object get kLinkStatus => _kLinkStatus ??= js_util.getProperty<Object>(glContext, 'LINK_STATUS'); Object get kFloat => _kFloat ??= js_util.getProperty<Object>(glContext, 'FLOAT'); Object? get kRGBA => _kRGBA ??= js_util.getProperty(glContext, 'RGBA'); Object get kUnsignedByte => _kUnsignedByte ??= js_util.getProperty<Object>(glContext, 'UNSIGNED_BYTE'); Object? get kUnsignedShort => _kUnsignedShort ??= js_util.getProperty(glContext, 'UNSIGNED_SHORT'); Object? get kStaticDraw => _kStaticDraw ??= js_util.getProperty(glContext, 'STATIC_DRAW'); Object get kTriangles => _kTriangles ??= js_util.getProperty<Object>(glContext, 'TRIANGLES'); Object get kTriangleFan => _kTriangles ??= js_util.getProperty<Object>(glContext, 'TRIANGLE_FAN'); Object get kTriangleStrip => _kTriangles ??= js_util.getProperty<Object>(glContext, 'TRIANGLE_STRIP'); Object? get kColorBufferBit => _kColorBufferBit ??= js_util.getProperty(glContext, 'COLOR_BUFFER_BIT'); Object? get kTexture2D => _kTexture2D ??= js_util.getProperty(glContext, 'TEXTURE_2D'); double get kTexture0 => _kTexture0 ??= js_util.getProperty<double>(glContext, 'TEXTURE0'); Object? get kTextureWrapS => _kTextureWrapS ??= js_util.getProperty(glContext, 'TEXTURE_WRAP_S'); Object? get kTextureWrapT => _kTextureWrapT ??= js_util.getProperty(glContext, 'TEXTURE_WRAP_T'); Object? get kRepeat => _kRepeat ??= js_util.getProperty(glContext, 'REPEAT'); Object? get kClampToEdge => _kClampToEdge ??= js_util.getProperty(glContext, 'CLAMP_TO_EDGE'); Object? get kMirroredRepeat => _kMirroredRepeat ??= js_util.getProperty(glContext, 'MIRRORED_REPEAT'); Object? get kLinear => _kLinear ??= js_util.getProperty(glContext, 'LINEAR'); Object? get kTextureMinFilter => _kTextureMinFilter ??= js_util.getProperty(glContext, 'TEXTURE_MIN_FILTER'); /// Returns reference to uniform in program. Object getUniformLocation(Object program, String uniformName) { final Object? res = js_util .callMethod(glContext, 'getUniformLocation', <dynamic>[program, uniformName]); if (res == null) { throw Exception('$uniformName not found'); } else { return res; } } /// Returns true if uniform exists. bool containsUniform(Object program, String uniformName) { final Object? res = js_util .callMethod(glContext, 'getUniformLocation', <dynamic>[program, uniformName]); return res != null; } /// Returns reference to uniform in program. Object getAttributeLocation(Object program, String attribName) { final Object? res = js_util .callMethod(glContext, 'getAttribLocation', <dynamic>[program, attribName]); if (res == null) { throw Exception('$attribName not found'); } else { return res; } } /// Sets float uniform value. void setUniform1f(Object uniform, double value) { js_util.callMethod<void>(glContext, 'uniform1f', <dynamic>[uniform, value]); } /// Sets vec2 uniform values. void setUniform2f(Object uniform, double value1, double value2) { js_util.callMethod<void>(glContext, 'uniform2f', <dynamic>[uniform, value1, value2]); } /// Sets vec4 uniform values. void setUniform4f(Object uniform, double value1, double value2, double value3, double value4) { js_util.callMethod<void>( glContext, 'uniform4f', <dynamic>[uniform, value1, value2, value3, value4]); } /// Sets mat4 uniform values. void setUniformMatrix4fv(Object uniform, bool transpose, Float32List value) { js_util.callMethod<void>( glContext, 'uniformMatrix4fv', <dynamic>[uniform, transpose, value]); } /// Shader compile error log. Object? getShaderInfoLog(Object glShader) { return js_util.callMethod(glContext, 'getShaderInfoLog', <dynamic>[glShader]); } /// Errors that occurred during failed linking or validation of program /// objects. Typically called after [linkProgram]. String? getProgramInfoLog(Object glProgram) { return js_util.callMethod<String?>(glContext, 'getProgramInfoLog', <dynamic>[glProgram]); } int? get drawingBufferWidth => js_util.getProperty<int?>(glContext, 'drawingBufferWidth'); int? get drawingBufferHeight => js_util.getProperty<int?>(glContext, 'drawingBufferWidth'); /// Reads gl contents as image data. /// /// Warning: data is read bottom up (flipped). DomImageData readImageData() { const int kBytesPerPixel = 4; final int bufferWidth = _widthInPixels!; final int bufferHeight = _heightInPixels!; if (browserEngine == BrowserEngine.webkit || browserEngine == BrowserEngine.firefox) { final Uint8List pixels = Uint8List(bufferWidth * bufferHeight * kBytesPerPixel); js_util.callMethod<void>(glContext, 'readPixels', <dynamic>[0, 0, bufferWidth, bufferHeight, kRGBA, kUnsignedByte, pixels]); return createDomImageData( Uint8ClampedList.fromList(pixels), bufferWidth, bufferHeight); } else { final Uint8ClampedList pixels = Uint8ClampedList(bufferWidth * bufferHeight * kBytesPerPixel); js_util.callMethod<void>(glContext, 'readPixels', <dynamic>[0, 0, bufferWidth, bufferHeight, kRGBA, kUnsignedByte, pixels]); return createDomImageData(pixels, bufferWidth, bufferHeight); } } /// Returns image data in a form that can be used to create Canvas /// context patterns. Object? readPatternData(bool isOpaque) { // When using OffscreenCanvas and transferToImageBitmap is supported by // browser create ImageBitmap otherwise use more expensive canvas // allocation. However, transferToImageBitmap does not properly preserve // the alpha channel, so only use it if the pattern is opaque. if (_canvas != null && js_util.hasProperty(_canvas!, 'transferToImageBitmap') && isOpaque) { // TODO(yjbanov): find out why we need to call getContext and ignore the return value. js_util.callMethod<void>(_canvas!, 'getContext', <dynamic>['webgl2']); final Object? imageBitmap = js_util.callMethod(_canvas!, 'transferToImageBitmap', <dynamic>[]); return imageBitmap; } else { final DomCanvasElement canvas = createDomCanvasElement(width: _widthInPixels, height: _heightInPixels); final DomCanvasRenderingContext2D ctx = canvas.context2D; drawImage(ctx, 0, 0); return canvas; } } /// Returns image data in data url format. String toImageUrl() { final DomCanvasElement canvas = createDomCanvasElement(width: _widthInPixels, height: _heightInPixels); final DomCanvasRenderingContext2D ctx = canvas.context2D; drawImage(ctx, 0, 0); final String dataUrl = canvas.toDataURL(); canvas.width = 0; canvas.height = 0; return dataUrl; } } // ignore: avoid_classes_with_only_static_members /// Creates gl context from cached OffscreenCanvas for webgl rendering to image. class GlContextCache { static int _maxPixelWidth = 0; static int _maxPixelHeight = 0; static GlContext? _cachedContext; static OffScreenCanvas? _offScreenCanvas; static void dispose() { _maxPixelWidth = 0; _maxPixelHeight = 0; _cachedContext = null; _offScreenCanvas?.dispose(); } static GlContext? createGlContext(int widthInPixels, int heightInPixels) { if (widthInPixels > _maxPixelWidth || heightInPixels > _maxPixelHeight) { _cachedContext?.dispose(); _cachedContext = null; _offScreenCanvas = null; _maxPixelWidth = math.max(_maxPixelWidth, widthInPixels); _maxPixelHeight = math.max(_maxPixelHeight, widthInPixels); } _offScreenCanvas ??= OffScreenCanvas(widthInPixels, heightInPixels); _cachedContext ??= GlContext(_offScreenCanvas!); _cachedContext!.setViewportSize(widthInPixels, heightInPixels); return _cachedContext; } } void setupVertexTransforms( GlContext gl, GlProgram glProgram, double offsetX, double offsetY, double widthInPixels, double heightInPixels, Matrix4 transform) { final Object transformUniform = gl.getUniformLocation(glProgram.program, 'u_ctransform'); final Matrix4 transformAtOffset = transform.clone() ..translate(-offsetX, -offsetY); gl.setUniformMatrix4fv(transformUniform, false, transformAtOffset.storage); // Set uniform to scale 0..width/height pixels coordinates to -1..1 // clipspace range and flip the Y axis. final Object resolution = gl.getUniformLocation(glProgram.program, 'u_scale'); gl.setUniform4f(resolution, 2.0 / widthInPixels, -2.0 / heightInPixels, 1, 1); final Object shift = gl.getUniformLocation(glProgram.program, 'u_shift'); gl.setUniform4f(shift, -1, 1, 0, 0); } void setupTextureTransform( GlContext gl, GlProgram glProgram, double offsetx, double offsety, double sx, double sy) { final Object scalar = gl.getUniformLocation(glProgram.program, 'u_textransform'); gl.setUniform4f(scalar, sx, sy, offsetx, offsety); } void bufferVertexData(GlContext gl, Float32List positions, double devicePixelRatio) { if (devicePixelRatio == 1.0) { gl.bufferData(positions, gl.kStaticDraw); } else { final int length = positions.length; final Float32List scaledList = Float32List(length); for (int i = 0; i < length; i++) { scaledList[i] = positions[i] * devicePixelRatio; } gl.bufferData(scaledList, gl.kStaticDraw); } } dynamic tileModeToGlWrapping(GlContext gl, ui.TileMode tileMode) { switch (tileMode) { case ui.TileMode.clamp: return gl.kClampToEdge; case ui.TileMode.decal: return gl.kClampToEdge; case ui.TileMode.mirror: return gl.kMirroredRepeat; case ui.TileMode.repeated: return gl.kRepeat; } } /// Polyfill for DomOffscreenCanvas that is not supported on some browsers. class OffScreenCanvas { OffScreenCanvas(this.width, this.height) { if (OffScreenCanvas.supported) { offScreenCanvas = createDomOffscreenCanvas(width, height); } else { canvasElement = createDomCanvasElement( width: width, height: height, ); canvasElement!.className = 'gl-canvas'; _updateCanvasCssSize(canvasElement!); } } DomOffscreenCanvas? offScreenCanvas; DomCanvasElement? canvasElement; int width; int height; static bool? _supported; void _updateCanvasCssSize(DomCanvasElement element) { final double cssWidth = width / EngineFlutterDisplay.instance.browserDevicePixelRatio; final double cssHeight = height / EngineFlutterDisplay.instance.browserDevicePixelRatio; element.style ..position = 'absolute' ..width = '${cssWidth}px' ..height = '${cssHeight}px'; } void resize(int requestedWidth, int requestedHeight) { if(requestedWidth != width && requestedHeight != height) { width = requestedWidth; height = requestedHeight; if(offScreenCanvas != null) { offScreenCanvas!.width = requestedWidth.toDouble(); offScreenCanvas!.height = requestedHeight.toDouble(); } else if (canvasElement != null) { canvasElement!.width = requestedWidth.toDouble(); canvasElement!.height = requestedHeight.toDouble(); _updateCanvasCssSize(canvasElement!); } } } void dispose() { offScreenCanvas = null; canvasElement = null; } /// Returns CanvasRenderContext2D or OffscreenCanvasRenderingContext2D to /// paint into. Object? getContext2d() { return offScreenCanvas != null ? offScreenCanvas!.getContext('2d') : canvasElement!.getContext('2d'); } DomCanvasRenderingContextBitmapRenderer? getBitmapRendererContext() { return (offScreenCanvas != null ? offScreenCanvas!.getContext('bitmaprenderer') : canvasElement!.getContext('bitmaprenderer')) as DomCanvasRenderingContextBitmapRenderer?; } /// Feature detection for transferToImageBitmap on OffscreenCanvas. bool get transferToImageBitmapSupported => js_util.hasProperty(offScreenCanvas!, 'transferToImageBitmap'); /// Creates an ImageBitmap object from the most recently rendered image /// of the OffscreenCanvas. /// /// !Warning API still in experimental status, feature detect before using. Object? transferToImageBitmap() { return js_util.callMethod(offScreenCanvas!, 'transferToImageBitmap', <dynamic>[]); } /// Draws canvas contents to a rendering context. void transferImage(Object targetContext) { // Actual size of canvas may be larger than viewport size. Use // source/destination to draw part of the image data. js_util.callMethod<void>(targetContext, 'drawImage', <dynamic>[offScreenCanvas ?? canvasElement!, 0, 0, width, height, 0, 0, width, height]); } /// Converts canvas contents to an image and returns as data URL. Future<String> toDataUrl() { final Completer<String> completer = Completer<String>(); if (offScreenCanvas != null) { offScreenCanvas!.convertToBlob().then((DomBlob value) { final DomFileReader fileReader = createDomFileReader(); fileReader.addEventListener('load', createDomEventListener((DomEvent event) { completer.complete( js_util.getProperty<String>(js_util.getProperty<Object>(event, 'target'), 'result'), ); })); fileReader.readAsDataURL(value); }); return completer.future; } else { return Future<String>.value(canvasElement!.toDataURL()); } } /// Draws an image to canvas for both offscreen canvas context2d. void drawImage(Object image, int x, int y, int width, int height) { js_util.callMethod<void>( getContext2d()!, 'drawImage', <dynamic>[image, x, y, width, height]); } /// Feature detects OffscreenCanvas. static bool get supported => _supported ??= // Safari 16.4 implements OffscreenCanvas, but without WebGL support. So // it's not really supported in a way that is useful to us. !isSafari && js_util.hasProperty(domWindow, 'OffscreenCanvas'); }
engine/lib/web_ui/lib/src/engine/safe_browser_api.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/safe_browser_api.dart", "repo_id": "engine", "token_count": 12013 }
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 'dart:math' as math; import 'dart:typed_data'; import 'package:meta/meta.dart'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; import '../../engine.dart' show registerHotRestartListener; import '../alarm_clock.dart'; import '../browser_detection.dart'; import '../configuration.dart'; import '../dom.dart'; import '../platform_dispatcher.dart'; import '../util.dart'; import '../vector_math.dart'; import '../window.dart'; import 'checkable.dart'; import 'dialog.dart'; import 'focusable.dart'; import 'image.dart'; import 'incrementable.dart'; import 'label_and_value.dart'; import 'link.dart'; import 'live_region.dart'; import 'platform_view.dart'; import 'scrollable.dart'; import 'semantics_helper.dart'; import 'tappable.dart'; import 'text_field.dart'; class EngineAccessibilityFeatures implements ui.AccessibilityFeatures { const EngineAccessibilityFeatures(this._index); static const int _kAccessibleNavigation = 1 << 0; static const int _kInvertColorsIndex = 1 << 1; static const int _kDisableAnimationsIndex = 1 << 2; static const int _kBoldTextIndex = 1 << 3; static const int _kReduceMotionIndex = 1 << 4; static const int _kHighContrastIndex = 1 << 5; static const int _kOnOffSwitchLabelsIndex = 1 << 6; // A bitfield which represents each enabled feature. final int _index; @override bool get accessibleNavigation => _kAccessibleNavigation & _index != 0; @override bool get invertColors => _kInvertColorsIndex & _index != 0; @override bool get disableAnimations => _kDisableAnimationsIndex & _index != 0; @override bool get boldText => _kBoldTextIndex & _index != 0; @override bool get reduceMotion => _kReduceMotionIndex & _index != 0; @override bool get highContrast => _kHighContrastIndex & _index != 0; @override bool get onOffSwitchLabels => _kOnOffSwitchLabelsIndex & _index != 0; @override String toString() { final List<String> features = <String>[]; if (accessibleNavigation) { features.add('accessibleNavigation'); } if (invertColors) { features.add('invertColors'); } if (disableAnimations) { features.add('disableAnimations'); } if (boldText) { features.add('boldText'); } if (reduceMotion) { features.add('reduceMotion'); } if (highContrast) { features.add('highContrast'); } if (onOffSwitchLabels) { features.add('onOffSwitchLabels'); } return 'AccessibilityFeatures$features'; } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is EngineAccessibilityFeatures && other._index == _index; } @override int get hashCode => _index.hashCode; EngineAccessibilityFeatures copyWith({ bool? accessibleNavigation, bool? invertColors, bool? disableAnimations, bool? boldText, bool? reduceMotion, bool? highContrast, bool? onOffSwitchLabels}) { final EngineAccessibilityFeaturesBuilder builder = EngineAccessibilityFeaturesBuilder(0); builder.accessibleNavigation = accessibleNavigation ?? this.accessibleNavigation; builder.invertColors = invertColors ?? this.invertColors; builder.disableAnimations = disableAnimations ?? this.disableAnimations; builder.boldText = boldText ?? this.boldText; builder.reduceMotion = reduceMotion ?? this.reduceMotion; builder.highContrast = highContrast ?? this.highContrast; builder.onOffSwitchLabels = onOffSwitchLabels ?? this.onOffSwitchLabels; return builder.build(); } } class EngineAccessibilityFeaturesBuilder { EngineAccessibilityFeaturesBuilder(this._index); int _index = 0; bool get accessibleNavigation => EngineAccessibilityFeatures._kAccessibleNavigation & _index != 0; bool get invertColors => EngineAccessibilityFeatures._kInvertColorsIndex & _index != 0; bool get disableAnimations => EngineAccessibilityFeatures._kDisableAnimationsIndex & _index != 0; bool get boldText => EngineAccessibilityFeatures._kBoldTextIndex & _index != 0; bool get reduceMotion => EngineAccessibilityFeatures._kReduceMotionIndex & _index != 0; bool get highContrast => EngineAccessibilityFeatures._kHighContrastIndex & _index != 0; bool get onOffSwitchLabels => EngineAccessibilityFeatures._kOnOffSwitchLabelsIndex & _index != 0; set accessibleNavigation(bool value) { const int accessibleNavigation = EngineAccessibilityFeatures._kAccessibleNavigation; _index = value? _index | accessibleNavigation : _index & ~accessibleNavigation; } set invertColors(bool value) { const int invertColors = EngineAccessibilityFeatures._kInvertColorsIndex; _index = value? _index | invertColors : _index & ~invertColors; } set disableAnimations(bool value) { const int disableAnimations = EngineAccessibilityFeatures._kDisableAnimationsIndex; _index = value? _index | disableAnimations : _index & ~disableAnimations; } set boldText(bool value) { const int boldText = EngineAccessibilityFeatures._kBoldTextIndex; _index = value? _index | boldText : _index & ~boldText; } set reduceMotion(bool value) { const int reduceMotion = EngineAccessibilityFeatures._kReduceMotionIndex; _index = value? _index | reduceMotion : _index & ~reduceMotion; } set highContrast(bool value) { const int highContrast = EngineAccessibilityFeatures._kHighContrastIndex; _index = value? _index | highContrast : _index & ~highContrast; } set onOffSwitchLabels(bool value) { const int onOffSwitchLabels = EngineAccessibilityFeatures._kOnOffSwitchLabelsIndex; _index = value? _index | onOffSwitchLabels : _index & ~onOffSwitchLabels; } /// Creates and returns an instance of EngineAccessibilityFeatures based on the value of _index EngineAccessibilityFeatures build() { return EngineAccessibilityFeatures(_index); } } /// Contains updates for the semantics tree. /// /// This class provides private engine-side API that's not available in the /// `dart:ui` [ui.SemanticsUpdate]. class SemanticsUpdate implements ui.SemanticsUpdate { SemanticsUpdate({List<SemanticsNodeUpdate>? nodeUpdates}) : _nodeUpdates = nodeUpdates; /// Updates for individual nodes. final List<SemanticsNodeUpdate>? _nodeUpdates; @override void dispose() { // Intentionally left blank. This method exists for API compatibility with // Flutter, but it is not required as memory resource management is handled // by JavaScript's garbage collector. } } /// Updates the properties of a particular semantics node. class SemanticsNodeUpdate { SemanticsNodeUpdate({ required this.id, required this.flags, required this.actions, required this.maxValueLength, required this.currentValueLength, required this.textSelectionBase, required this.textSelectionExtent, required this.platformViewId, required this.scrollChildren, required this.scrollIndex, required this.scrollPosition, required this.scrollExtentMax, required this.scrollExtentMin, required this.rect, required this.identifier, required this.label, required this.labelAttributes, required this.hint, required this.hintAttributes, required this.value, required this.valueAttributes, required this.increasedValue, required this.increasedValueAttributes, required this.decreasedValue, required this.decreasedValueAttributes, this.tooltip, this.textDirection, required this.transform, required this.elevation, required this.thickness, required this.childrenInTraversalOrder, required this.childrenInHitTestOrder, required this.additionalActions, }); /// See [ui.SemanticsUpdateBuilder.updateNode]. final int id; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int flags; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int actions; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int maxValueLength; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int currentValueLength; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int textSelectionBase; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int textSelectionExtent; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int platformViewId; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int scrollChildren; /// See [ui.SemanticsUpdateBuilder.updateNode]. final int scrollIndex; /// See [ui.SemanticsUpdateBuilder.updateNode]. final double scrollPosition; /// See [ui.SemanticsUpdateBuilder.updateNode]. final double scrollExtentMax; /// See [ui.SemanticsUpdateBuilder.updateNode]. final double scrollExtentMin; /// See [ui.SemanticsUpdateBuilder.updateNode]. final ui.Rect rect; /// See [ui.SemanticsUpdateBuilder.updateNode]. final String identifier; /// See [ui.SemanticsUpdateBuilder.updateNode]. final String label; /// See [ui.SemanticsUpdateBuilder.updateNode]. final List<ui.StringAttribute> labelAttributes; /// See [ui.SemanticsUpdateBuilder.updateNode]. final String hint; /// See [ui.SemanticsUpdateBuilder.updateNode]. final List<ui.StringAttribute> hintAttributes; /// See [ui.SemanticsUpdateBuilder.updateNode]. final String value; /// See [ui.SemanticsUpdateBuilder.updateNode]. final List<ui.StringAttribute> valueAttributes; /// See [ui.SemanticsUpdateBuilder.updateNode]. final String increasedValue; /// See [ui.SemanticsUpdateBuilder.updateNode]. final List<ui.StringAttribute> increasedValueAttributes; /// See [ui.SemanticsUpdateBuilder.updateNode]. final String decreasedValue; /// See [ui.SemanticsUpdateBuilder.updateNode]. final List<ui.StringAttribute> decreasedValueAttributes; /// See [ui.SemanticsUpdateBuilder.updateNode]. final String? tooltip; /// See [ui.SemanticsUpdateBuilder.updateNode]. final ui.TextDirection? textDirection; /// See [ui.SemanticsUpdateBuilder.updateNode]. final Float32List transform; /// See [ui.SemanticsUpdateBuilder.updateNode]. final Int32List childrenInTraversalOrder; /// See [ui.SemanticsUpdateBuilder.updateNode]. final Int32List childrenInHitTestOrder; /// See [ui.SemanticsUpdateBuilder.updateNode]. final Int32List additionalActions; /// See [ui.SemanticsUpdateBuilder.updateNode]. final double elevation; /// See [ui.SemanticsUpdateBuilder.updateNode]. final double thickness; } /// Identifies [PrimaryRoleManager] implementations. /// /// Each value corresponds to the most specific role a semantics node plays in /// the semantics tree. enum PrimaryRole { /// Supports incrementing and/or decrementing its value. incrementable, /// Able to scroll its contents vertically or horizontally. scrollable, /// Accepts tap or click gestures. button, /// Contains editable text. textField, /// A control that has a checked state, such as a check box or a radio button. checkable, /// Visual only element. image, /// Adds the "dialog" ARIA role to the node. /// /// This corresponds to a semantics node that has `scopesRoute` bit set. While /// in Flutter a named route is not necessarily a dialog, this is the closest /// analog on the web. /// /// There are 3 possible situations: /// /// * The node also has the `namesRoute` bit set. This means that the node's /// `label` describes the dialog, which can be expressed by adding the /// `aria-label` attribute. /// * A descendant node has the `namesRoute` bit set. This means that the /// child's content describes the dialog. The child may simply be labelled, /// or it may be a subtree of nodes that describe the dialog together. The /// nearest HTML equivalent is `aria-describedby`. The child acquires the /// [routeName] role, which manages the relevant ARIA attributes. /// * There is no `namesRoute` bit anywhere in the sub-tree rooted at the /// current node. In this case it's likely not a dialog at all, and the node /// should not get a label or the "dialog" role. It's just a group of /// children. For example, a modal barrier has `scopesRoute` set but marking /// it as a dialog would be wrong. dialog, /// The node's primary role is to host a platform view. platformView, /// A role used when a more specific role cannot be assigend to /// a [SemanticsObject]. /// /// Provides a label or a value. generic, /// Contains a link. link, } /// Identifies one of the secondary [RoleManager]s of a [PrimaryRoleManager]. enum Role { /// Supplies generic accessibility focus features to semantics nodes that have /// [ui.SemanticsFlag.isFocusable] set. focusable, /// Supplies generic tapping/clicking functionality. tappable, /// Provides an `aria-label` from `label`, `value`, and/or `tooltip` values. /// /// The two are combined into the same role because they interact with each /// other. labelAndValue, /// Contains a region whose changes will be announced to the screen reader /// without having to be in focus. /// /// These regions can be a snackbar or a text field error. Once identified /// with this role, they will be able to get the assistive technology's /// attention right away. liveRegion, /// Provides a description for an ancestor dialog. /// /// This role is assigned to nodes that have `namesRoute` set but not /// `scopesRoute`. When both flags are set the node only gets the dialog /// role (see [dialog]). /// /// If the ancestor dialog is missing, this role does nothing useful. routeName, } /// Responsible for setting the `role` ARIA attribute and for attaching zero or /// more secondary [RoleManager]s to a [SemanticsObject]. abstract class PrimaryRoleManager { /// Initializes a role for a [semanticsObject] that includes basic /// functionality for focus, labels, live regions, and route names. /// /// If `labelRepresentation` is true, configures the [LabelAndValue] role with /// [LabelAndValue.labelRepresentation] set to true. PrimaryRoleManager.withBasics(this.role, this.semanticsObject, { required LeafLabelRepresentation labelRepresentation }) { element = _initElement(createElement(), semanticsObject); addFocusManagement(); addLiveRegion(); addRouteName(); addLabelAndValue(labelRepresentation: labelRepresentation); } /// Initializes a blank role for a [semanticsObject]. /// /// Use this constructor for highly specialized cases where /// [RoleManager.withBasics] does not work, for example when the default focus /// management intereferes with the widget's functionality. PrimaryRoleManager.blank(this.role, this.semanticsObject) { element = _initElement(createElement(), semanticsObject); } late final DomElement element; /// The primary role identifier. final PrimaryRole role; /// The semantics object managed by this role. final SemanticsObject semanticsObject; /// Secondary role managers, if any. List<RoleManager>? get secondaryRoleManagers => _secondaryRoleManagers; List<RoleManager>? _secondaryRoleManagers; /// Identifiers of secondary roles used by this primary role manager. /// /// This is only meant to be used in tests. @visibleForTesting List<Role> get debugSecondaryRoles => _secondaryRoleManagers?.map((RoleManager manager) => manager.role).toList() ?? const <Role>[]; @protected DomElement createElement() => domDocument.createElement('flt-semantics'); static DomElement _initElement(DomElement element, SemanticsObject semanticsObject) { // DOM nodes created for semantics objects are positioned absolutely using // transforms. element.style.position = 'absolute'; element.setAttribute('id', 'flt-semantic-node-${semanticsObject.id}'); // The root node has some properties that other nodes do not. if (semanticsObject.id == 0 && !configuration.debugShowSemanticsNodes) { // Make all semantics transparent. Use `filter` instead of `opacity` // attribute because `filter` is stronger. `opacity` does not apply to // some elements, particularly on iOS, such as the slider thumb and track. // // Use transparency instead of "visibility:hidden" or "display:none" // so that a screen reader does not ignore these elements. element.style.filter = 'opacity(0%)'; // Make text explicitly transparent to signal to the browser that no // rasterization needs to be done. element.style.color = 'rgba(0,0,0,0)'; } // Make semantic elements visible for debugging by outlining them using a // green border. Do not use `border` attribute because it affects layout // (`outline` does not). if (configuration.debugShowSemanticsNodes) { element.style.outline = '1px solid green'; } return element; } /// Sets the `role` ARIA attribute. void setAriaRole(String ariaRoleName) { setAttribute('role', ariaRoleName); } /// Sets the `role` ARIA attribute. void setAttribute(String name, Object value) { element.setAttribute(name, value); } void append(DomElement child) { element.append(child); } void removeAttribute(String name) => element.removeAttribute(name); void addEventListener(String type, DomEventListener? listener, [bool? useCapture]) => element.addEventListener(type, listener, useCapture); void removeEventListener(String type, DomEventListener? listener, [bool? useCapture]) => element.removeEventListener(type, listener, useCapture); /// Convenience getter for the [Focusable] role manager, if any. Focusable? get focusable => _focusable; Focusable? _focusable; /// Adds generic focus management features. void addFocusManagement() { addSecondaryRole(_focusable = Focusable(semanticsObject, this)); } /// Adds generic live region features. void addLiveRegion() { addSecondaryRole(LiveRegion(semanticsObject, this)); } /// Adds generic route name features. void addRouteName() { addSecondaryRole(RouteName(semanticsObject, this)); } /// Adds generic label features. void addLabelAndValue({ required LeafLabelRepresentation labelRepresentation }) { addSecondaryRole(LabelAndValue(semanticsObject, this, labelRepresentation: labelRepresentation)); } /// Adds generic functionality for handling taps and clicks. void addTappable() { addSecondaryRole(Tappable(semanticsObject, this)); } /// Adds a secondary role to this primary role manager. /// /// This method should be called by concrete implementations of /// [PrimaryRoleManager] during initialization. @protected void addSecondaryRole(RoleManager secondaryRoleManager) { assert( _secondaryRoleManagers?.any((RoleManager manager) => manager.role == secondaryRoleManager.role) != true, 'Cannot add secondary role ${secondaryRoleManager.role}. This object already has this secondary role.', ); _secondaryRoleManagers ??= <RoleManager>[]; _secondaryRoleManagers!.add(secondaryRoleManager); } /// Called immediately after the fields of the [semanticsObject] are updated /// by a [SemanticsUpdate]. /// /// A concrete implementation of this method would typically use some of the /// "is*Dirty" getters to find out exactly what's changed and apply the /// minimum DOM updates. /// /// The base implementation requests every secondary role manager to update /// the object. @mustCallSuper void update() { final List<RoleManager>? secondaryRoles = _secondaryRoleManagers; if (secondaryRoles == null) { return; } for (final RoleManager secondaryRole in secondaryRoles) { secondaryRole.update(); } } /// Whether this role manager was disposed of. bool get isDisposed => _isDisposed; bool _isDisposed = false; /// Called when [semanticsObject] is removed, or when it changes its role such /// that this role is no longer relevant. /// /// This method is expected to remove role-specific functionality from the /// DOM. In particular, this method is the appropriate place to call /// [EngineSemanticsOwner.removeGestureModeListener] if this role reponds to /// gesture mode changes. @mustCallSuper void dispose() { removeAttribute('role'); _isDisposed = true; } /// Transfers the accessibility focus to the [element] managed by this role /// manager as a result of this node taking focus by default. /// /// For example, when a dialog pops up it is expected that one of its child /// nodes takes accessibility focus. /// /// Transferring accessibility focus is different from transferring input /// focus. Not all elements that can take accessibility focus can also take /// input focus. For example, a plain text node cannot take input focus, but /// it can take accessibility focus. /// /// Returns `true` if the role manager took the focus. Returns `false` if /// this role manager did not take the focus. The return value can be used to /// decide whether to stop searching for a node that should take focus. bool focusAsRouteDefault(); } /// A role used when a more specific role couldn't be assigned to the node. final class GenericRole extends PrimaryRoleManager { GenericRole(SemanticsObject semanticsObject) : super.withBasics( PrimaryRole.generic, semanticsObject, labelRepresentation: LeafLabelRepresentation.domText, ) { // Typically a tappable widget would have a more specific role, such as // "link", "button", "checkbox", etc. However, there are situations when a // tappable is not a leaf node, but contains other nodes, which can also be // tappable. For example, the dismiss barrier of a pop-up menu is a tappable // ancestor of the menu itself, while the menu may contain tappable // children. if (semanticsObject.isTappable) { addTappable(); } } @override void update() { super.update(); if (!semanticsObject.hasLabel) { // The node didn't get a more specific role, and it has no label. It is // likely that this node is simply there for positioning its children and // has no other role for the screen reader to be aware of. In this case, // the element does not need a `role` attribute at all. return; } // Assign one of three roles to the element: heading, group, text. // // - "group" is used when the node has children, irrespective of whether the // node is marked as a header or not. This is because marking a group // as a "heading" will prevent the AT from reaching its children. // - "heading" is used when the framework explicitly marks the node as a // heading and the node does not have children. // - "text" is used by default. // // As of October 24, 2022, "text" only has effect on Safari. Other browsers // ignore it. Setting role="text" prevents Safari from treating the element // as a "group" or "empty group". Other browsers still announce it as // "group" or "empty group". However, other options considered produced even // worse results, such as: // // - Ignore the size of the element and size the focus ring to the text // content, which is wrong. The HTML text size is irrelevant because // Flutter renders into canvas, so the focus ring looks wrong. // - Read out the same label multiple times. if (semanticsObject.hasChildren) { setAriaRole('group'); } else if (semanticsObject.hasFlag(ui.SemanticsFlag.isHeader)) { setAriaRole('heading'); } else { setAriaRole('text'); } } @override bool focusAsRouteDefault() { // Case 1: current node has input focus. Let the input focus system decide // default focusability. if (semanticsObject.isFocusable) { final Focusable? focusable = this.focusable; if (focusable != null) { return focusable.focusAsRouteDefault(); } } // Case 2: current node is not focusable, but just a container of other // nodes or lacks a label. Do not focus on it and let the search continue. if (semanticsObject.hasChildren || !semanticsObject.hasLabel) { return false; } // Case 3: current node is visual/informational. Move just the // accessibility focus. // Plain text nodes should not be focusable via keyboard or mouse. They are // only focusable for the purposes of focusing the screen reader. To achieve // this the -1 value is used. // // See also: // // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex element.tabIndex = -1; element.focus(); return true; } } /// Provides a piece of functionality to a [SemanticsObject]. /// /// A secondary role must not set the `role` ARIA attribute. That responsibility /// falls on the [PrimaryRoleManager]. One [SemanticsObject] may have more than /// one [RoleManager] but an element may only have one ARIA role, so setting the /// `role` attribute from a [RoleManager] would cause conflicts. /// /// The [PrimaryRoleManager] decides the list of [RoleManager]s a given semantics /// node should use. abstract class RoleManager { /// Initializes a secondary role for [semanticsObject]. /// /// A single role object manages exactly one [SemanticsObject]. RoleManager(this.role, this.semanticsObject, this.owner); /// Role identifier. final Role role; /// The semantics object managed by this role. final SemanticsObject semanticsObject; final PrimaryRoleManager owner; /// Called immediately after the [semanticsObject] updates some of its fields. /// /// A concrete implementation of this method would typically use some of the /// "is*Dirty" getters to find out exactly what's changed and apply the /// minimum DOM updates. void update(); /// Whether this role manager was disposed of. bool get isDisposed => _isDisposed; bool _isDisposed = false; /// Called when [semanticsObject] is removed, or when it changes its role such /// that this role is no longer relevant. /// /// This method is expected to remove role-specific functionality from the /// DOM. In particular, this method is the appropriate place to call /// [EngineSemanticsOwner.removeGestureModeListener] if this role reponds to /// gesture mode changes. @mustCallSuper void dispose() { _isDisposed = true; } } /// Instantiation of a framework-side semantics node in the DOM. /// /// Instances of this class are retained from frame to frame. Each instance is /// permanently attached to an [id] and a DOM [element] used to convey semantics /// information to the browser. class SemanticsObject { /// Creates a semantics tree node with the given [id] and [owner]. SemanticsObject(this.id, this.owner); /// See [ui.SemanticsUpdateBuilder.updateNode]. int get flags => _flags; int _flags = 0; /// Whether the [flags] field has been updated but has not been applied to the /// DOM yet. bool get isFlagsDirty => _isDirty(_flagsIndex); static const int _flagsIndex = 1 << 0; void _markFlagsDirty() { _dirtyFields |= _flagsIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. int? get actions => _actions; int? _actions; static const int _actionsIndex = 1 << 1; /// Whether the [actions] field has been updated but has not been applied to /// the DOM yet. bool get isActionsDirty => _isDirty(_actionsIndex); void _markActionsDirty() { _dirtyFields |= _actionsIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. int? get textSelectionBase => _textSelectionBase; int? _textSelectionBase; static const int _textSelectionBaseIndex = 1 << 2; /// Whether the [textSelectionBase] field has been updated but has not been /// applied to the DOM yet. bool get isTextSelectionBaseDirty => _isDirty(_textSelectionBaseIndex); void _markTextSelectionBaseDirty() { _dirtyFields |= _textSelectionBaseIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. int? get textSelectionExtent => _textSelectionExtent; int? _textSelectionExtent; static const int _textSelectionExtentIndex = 1 << 3; /// Whether the [textSelectionExtent] field has been updated but has not been /// applied to the DOM yet. bool get isTextSelectionExtentDirty => _isDirty(_textSelectionExtentIndex); void _markTextSelectionExtentDirty() { _dirtyFields |= _textSelectionExtentIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. int? get scrollChildren => _scrollChildren; int? _scrollChildren; static const int _scrollChildrenIndex = 1 << 4; /// Whether the [scrollChildren] field has been updated but has not been /// applied to the DOM yet. bool get isScrollChildrenDirty => _isDirty(_scrollChildrenIndex); void _markScrollChildrenDirty() { _dirtyFields |= _scrollChildrenIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. int? get scrollIndex => _scrollIndex; int? _scrollIndex; static const int _scrollIndexIndex = 1 << 5; /// Whether the [scrollIndex] field has been updated but has not been /// applied to the DOM yet. bool get isScrollIndexDirty => _isDirty(_scrollIndexIndex); void _markScrollIndexDirty() { _dirtyFields |= _scrollIndexIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. double? get scrollPosition => _scrollPosition; double? _scrollPosition; static const int _scrollPositionIndex = 1 << 6; /// Whether the [scrollPosition] field has been updated but has not been /// applied to the DOM yet. bool get isScrollPositionDirty => _isDirty(_scrollPositionIndex); void _markScrollPositionDirty() { _dirtyFields |= _scrollPositionIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. double? get scrollExtentMax => _scrollExtentMax; double? _scrollExtentMax; static const int _scrollExtentMaxIndex = 1 << 7; /// Whether the [scrollExtentMax] field has been updated but has not been /// applied to the DOM yet. bool get isScrollExtentMaxDirty => _isDirty(_scrollExtentMaxIndex); void _markScrollExtentMaxDirty() { _dirtyFields |= _scrollExtentMaxIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. double? get scrollExtentMin => _scrollExtentMin; double? _scrollExtentMin; static const int _scrollExtentMinIndex = 1 << 8; /// Whether the [scrollExtentMin] field has been updated but has not been /// applied to the DOM yet. bool get isScrollExtentMinDirty => _isDirty(_scrollExtentMinIndex); void _markScrollExtentMinDirty() { _dirtyFields |= _scrollExtentMinIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. ui.Rect? get rect => _rect; ui.Rect? _rect; static const int _rectIndex = 1 << 9; /// Whether the [rect] field has been updated but has not been /// applied to the DOM yet. bool get isRectDirty => _isDirty(_rectIndex); void _markRectDirty() { _dirtyFields |= _rectIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. String? get label => _label; String? _label; /// See [ui.SemanticsUpdateBuilder.updateNode] List<ui.StringAttribute>? get labelAttributes => _labelAttributes; List<ui.StringAttribute>? _labelAttributes; /// Whether this object contains a non-empty label. bool get hasLabel => _label != null && _label!.isNotEmpty; static const int _labelIndex = 1 << 10; /// Whether the [label] field has been updated but has not been /// applied to the DOM yet. bool get isLabelDirty => _isDirty(_labelIndex); void _markLabelDirty() { _dirtyFields |= _labelIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. String? get hint => _hint; String? _hint; /// See [ui.SemanticsUpdateBuilder.updateNode] List<ui.StringAttribute>? get hintAttributes => _hintAttributes; List<ui.StringAttribute>? _hintAttributes; static const int _hintIndex = 1 << 11; /// Whether the [hint] field has been updated but has not been /// applied to the DOM yet. bool get isHintDirty => _isDirty(_hintIndex); void _markHintDirty() { _dirtyFields |= _hintIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. String? get value => _value; String? _value; /// See [ui.SemanticsUpdateBuilder.updateNode] List<ui.StringAttribute>? get valueAttributes => _valueAttributes; List<ui.StringAttribute>? _valueAttributes; /// Whether this object contains a non-empty value. bool get hasValue => _value != null && _value!.isNotEmpty; static const int _valueIndex = 1 << 12; /// Whether the [value] field has been updated but has not been /// applied to the DOM yet. bool get isValueDirty => _isDirty(_valueIndex); void _markValueDirty() { _dirtyFields |= _valueIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. String? get increasedValue => _increasedValue; String? _increasedValue; /// See [ui.SemanticsUpdateBuilder.updateNode] List<ui.StringAttribute>? get increasedValueAttributes => _increasedValueAttributes; List<ui.StringAttribute>? _increasedValueAttributes; static const int _increasedValueIndex = 1 << 13; /// Whether the [increasedValue] field has been updated but has not been /// applied to the DOM yet. bool get isIncreasedValueDirty => _isDirty(_increasedValueIndex); void _markIncreasedValueDirty() { _dirtyFields |= _increasedValueIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. String? get decreasedValue => _decreasedValue; String? _decreasedValue; /// See [ui.SemanticsUpdateBuilder.updateNode] List<ui.StringAttribute>? get decreasedValueAttributes => _decreasedValueAttributes; List<ui.StringAttribute>? _decreasedValueAttributes; static const int _decreasedValueIndex = 1 << 14; /// Whether the [decreasedValue] field has been updated but has not been /// applied to the DOM yet. bool get isDecreasedValueDirty => _isDirty(_decreasedValueIndex); void _markDecreasedValueDirty() { _dirtyFields |= _decreasedValueIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. ui.TextDirection? get textDirection => _textDirection; ui.TextDirection? _textDirection; static const int _textDirectionIndex = 1 << 15; /// Whether the [textDirection] field has been updated but has not been /// applied to the DOM yet. bool get isTextDirectionDirty => _isDirty(_textDirectionIndex); void _markTextDirectionDirty() { _dirtyFields |= _textDirectionIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. Float32List? get transform => _transform; Float32List? _transform; static const int _transformIndex = 1 << 16; /// Whether the [transform] field has been updated but has not been /// applied to the DOM yet. bool get isTransformDirty => _isDirty(_transformIndex); void _markTransformDirty() { _dirtyFields |= _transformIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. Int32List? get childrenInTraversalOrder => _childrenInTraversalOrder; Int32List? _childrenInTraversalOrder; static const int _childrenInTraversalOrderIndex = 1 << 19; /// Whether the [childrenInTraversalOrder] field has been updated but has not /// been applied to the DOM yet. bool get isChildrenInTraversalOrderDirty => _isDirty(_childrenInTraversalOrderIndex); void _markChildrenInTraversalOrderDirty() { _dirtyFields |= _childrenInTraversalOrderIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. Int32List? get childrenInHitTestOrder => _childrenInHitTestOrder; Int32List? _childrenInHitTestOrder; static const int _childrenInHitTestOrderIndex = 1 << 20; /// Whether the [childrenInHitTestOrder] field has been updated but has not /// been applied to the DOM yet. bool get isChildrenInHitTestOrderDirty => _isDirty(_childrenInHitTestOrderIndex); void _markChildrenInHitTestOrderDirty() { _dirtyFields |= _childrenInHitTestOrderIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. Int32List? get additionalActions => _additionalActions; Int32List? _additionalActions; static const int _additionalActionsIndex = 1 << 21; /// Whether the [additionalActions] field has been updated but has not been /// applied to the DOM yet. bool get isAdditionalActionsDirty => _isDirty(_additionalActionsIndex); void _markAdditionalActionsDirty() { _dirtyFields |= _additionalActionsIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. String? get tooltip => _tooltip; String? _tooltip; /// Whether this object contains a non-empty tooltip. bool get hasTooltip => _tooltip != null && _tooltip!.isNotEmpty; static const int _tooltipIndex = 1 << 22; /// Whether the [tooltip] field has been updated but has not been /// applied to the DOM yet. bool get isTooltipDirty => _isDirty(_tooltipIndex); void _markTooltipDirty() { _dirtyFields |= _tooltipIndex; } /// See [ui.SemanticsUpdateBuilder.updateNode]. int get platformViewId => _platformViewId; int _platformViewId = -1; /// Whether this object represents a platform view. bool get isPlatformView => _platformViewId != -1; static const int _platformViewIdIndex = 1 << 23; /// Whether the [platformViewId] field has been updated but has not been /// applied to the DOM yet. bool get isPlatformViewIdDirty => _isDirty(_platformViewIdIndex); void _markPlatformViewIdDirty() { _dirtyFields |= _platformViewIdIndex; } /// A unique permanent identifier of the semantics node in the tree. final int id; /// Controls the semantics tree that this node participates in. final EngineSemanticsOwner owner; /// Bitfield showing which fields have been updated but have not yet been /// applied to the DOM. /// /// Instead of use this field directly, prefer using one of the "is*Dirty" /// getters, e.g. [isFlagsDirty]. /// /// The bitfield supports up to 31 bits. int _dirtyFields = -1; // initial value is when all relevant bits are set /// Whether the field corresponding to the [fieldIndex] has been updated. bool _isDirty(int fieldIndex) => (_dirtyFields & fieldIndex) != 0; /// The dom element of this semantics object. DomElement get element => primaryRole!.element; /// Returns the HTML element that contains the HTML elements of direct /// children of this object. /// /// The element is created lazily. When the child list is empty this element /// is not created. This is necessary for "aria-label" to function correctly. /// The browser will ignore the [label] of HTML element that contain child /// elements. DomElement? getOrCreateChildContainer() { if (_childContainerElement == null) { _childContainerElement = createDomElement('flt-semantics-container'); _childContainerElement!.style ..position = 'absolute' // Ignore pointer events on child container so that platform views // behind it can be reached. ..pointerEvents = 'none'; element.append(_childContainerElement!); } return _childContainerElement; } /// The element that contains the elements belonging to the child semantics /// nodes. /// /// This element is used to correct for [_rect] offsets. It is only non-`null` /// when there are non-zero children (i.e. when [hasChildren] is `true`). DomElement? _childContainerElement; /// The parent of this semantics object. /// /// This value is not final until the tree is finalized. It is not safe to /// rely on this value in the middle of a semantics tree update. It is safe to /// use this value in post-update callback (see [SemanticsUpdatePhase] and /// [EngineSemanticsOwner.addOneTimePostUpdateCallback]). SemanticsObject? get parent { assert(owner.phase == SemanticsUpdatePhase.postUpdate); return _parent; } SemanticsObject? _parent; /// Whether this node currently has a given [SemanticsFlag]. bool hasFlag(ui.SemanticsFlag flag) => _flags & flag.index != 0; /// Whether [actions] contains the given action. bool hasAction(ui.SemanticsAction action) => (_actions! & action.index) != 0; /// Whether this object represents a widget that can receive input focus. bool get isFocusable => hasFlag(ui.SemanticsFlag.isFocusable); /// Whether this object currently has input focus. /// /// This value only makes sense if [isFocusable] is true. bool get hasFocus => hasFlag(ui.SemanticsFlag.isFocused); /// Whether this object can be in one of "enabled" or "disabled" state. /// /// If this is true, [isEnabled] communicates the state. bool get hasEnabledState => hasFlag(ui.SemanticsFlag.hasEnabledState); /// Whether this object is enabled. /// /// This field is only meaningful if [hasEnabledState] is true. bool get isEnabled => hasFlag(ui.SemanticsFlag.isEnabled); /// Whether this object represents a vertically scrollable area. bool get isVerticalScrollContainer => hasAction(ui.SemanticsAction.scrollDown) || hasAction(ui.SemanticsAction.scrollUp); /// Whether this object represents a horizontally scrollable area. bool get isHorizontalScrollContainer => hasAction(ui.SemanticsAction.scrollLeft) || hasAction(ui.SemanticsAction.scrollRight); /// Whether this object represents a scrollable area in any direction. bool get isScrollContainer => isVerticalScrollContainer || isHorizontalScrollContainer; /// Whether this object has a non-empty list of children. bool get hasChildren => _childrenInTraversalOrder != null && _childrenInTraversalOrder!.isNotEmpty; /// Whether this object represents an editable text field. bool get isTextField => hasFlag(ui.SemanticsFlag.isTextField); /// Whether this object represents an editable text field. bool get isLink => hasFlag(ui.SemanticsFlag.isLink); /// Whether this object needs screen readers attention right away. bool get isLiveRegion => hasFlag(ui.SemanticsFlag.isLiveRegion) && !hasFlag(ui.SemanticsFlag.isHidden); /// Whether this object represents an image with no tappable functionality. bool get isVisualOnly => hasFlag(ui.SemanticsFlag.isImage) && !isTappable && !isButton; /// Whether this node defines a scope for a route. /// /// See also [Role.dialog]. bool get scopesRoute => hasFlag(ui.SemanticsFlag.scopesRoute); /// Whether this node describes a route. /// /// See also [Role.dialog]. bool get namesRoute => hasFlag(ui.SemanticsFlag.namesRoute); /// Whether this object carry enabled/disabled state (and if so whether it is /// enabled). /// /// See [EnabledState] for more details. EnabledState enabledState() { if (hasFlag(ui.SemanticsFlag.hasEnabledState)) { if (hasFlag(ui.SemanticsFlag.isEnabled)) { return EnabledState.enabled; } else { return EnabledState.disabled; } } else { return EnabledState.noOpinion; } } /// Updates this object from data received from a semantics [update]. /// /// Does not update children. Children are updated in a separate pass because /// at this point children's self information is not ready yet. void updateSelf(SemanticsNodeUpdate update) { // Update all field values and their corresponding dirty flags before // applying the updates to the DOM. if (_flags != update.flags) { _flags = update.flags; _markFlagsDirty(); } if (_value != update.value) { _value = update.value; _markValueDirty(); } if (_valueAttributes != update.valueAttributes) { _valueAttributes = update.valueAttributes; _markValueDirty(); } if (_label != update.label) { _label = update.label; _markLabelDirty(); } if (_labelAttributes != update.labelAttributes) { _labelAttributes = update.labelAttributes; _markLabelDirty(); } if (_rect != update.rect) { _rect = update.rect; _markRectDirty(); } if (_transform != update.transform) { _transform = update.transform; _markTransformDirty(); } if (_scrollPosition != update.scrollPosition) { _scrollPosition = update.scrollPosition; _markScrollPositionDirty(); } if (_actions != update.actions) { _actions = update.actions; _markActionsDirty(); } if (_textSelectionBase != update.textSelectionBase) { _textSelectionBase = update.textSelectionBase; _markTextSelectionBaseDirty(); } if (_textSelectionExtent != update.textSelectionExtent) { _textSelectionExtent = update.textSelectionExtent; _markTextSelectionExtentDirty(); } if (_scrollChildren != update.scrollChildren) { _scrollChildren = update.scrollChildren; _markScrollChildrenDirty(); } if (_scrollIndex != update.scrollIndex) { _scrollIndex = update.scrollIndex; _markScrollIndexDirty(); } if (_scrollExtentMax != update.scrollExtentMax) { _scrollExtentMax = update.scrollExtentMax; _markScrollExtentMaxDirty(); } if (_scrollExtentMin != update.scrollExtentMin) { _scrollExtentMin = update.scrollExtentMin; _markScrollExtentMinDirty(); } if (_hint != update.hint) { _hint = update.hint; _markHintDirty(); } if (_hintAttributes != update.hintAttributes) { _hintAttributes = update.hintAttributes; _markHintDirty(); } if (_increasedValue != update.increasedValue) { _increasedValue = update.increasedValue; _markIncreasedValueDirty(); } if (_increasedValueAttributes != update.increasedValueAttributes) { _increasedValueAttributes = update.increasedValueAttributes; _markIncreasedValueDirty(); } if (_decreasedValue != update.decreasedValue) { _decreasedValue = update.decreasedValue; _markDecreasedValueDirty(); } if (_decreasedValueAttributes != update.decreasedValueAttributes) { _decreasedValueAttributes = update.decreasedValueAttributes; _markDecreasedValueDirty(); } if (_tooltip != update.tooltip) { _tooltip = update.tooltip; _markTooltipDirty(); } if (_textDirection != update.textDirection) { _textDirection = update.textDirection; _markTextDirectionDirty(); } if (_childrenInHitTestOrder != update.childrenInHitTestOrder) { _childrenInHitTestOrder = update.childrenInHitTestOrder; _markChildrenInHitTestOrderDirty(); } if (_childrenInTraversalOrder != update.childrenInTraversalOrder) { _childrenInTraversalOrder = update.childrenInTraversalOrder; _markChildrenInTraversalOrderDirty(); } if (_additionalActions != update.additionalActions) { _additionalActions = update.additionalActions; _markAdditionalActionsDirty(); } if (_platformViewId != update.platformViewId) { _platformViewId = update.platformViewId; _markPlatformViewIdDirty(); } // Apply updates to the DOM. _updateRoles(); // All properties that affect positioning and sizing are checked together // any one of them triggers position and size recomputation. if (isRectDirty || isTransformDirty || isScrollPositionDirty) { recomputePositionAndSize(); } // Ignore pointer events on all container nodes and all platform view nodes. // This is so that the platform views are not obscured by semantic elements // and can be reached by inspecting the web page. if (!hasChildren && !isPlatformView) { element.style.pointerEvents = 'all'; } else { element.style.pointerEvents = 'none'; } } /// The order children are currently rendered in. List<SemanticsObject>? _currentChildrenInRenderOrder; /// Updates direct children of this node, if any. /// /// Specifies two orders of direct children: /// /// * Traversal order: the logical order of child nodes that establishes the /// next and previous relationship between UI widgets. When the user /// traverses the UI using next/previous gestures the accessibility focus /// follows the traversal order. /// * Hit-test order: determines the top/bottom relationship between widgets. /// When the user is inspecting the UI using the drag gesture, the widgets /// that appear "on top" hit-test order wise take the focus. This order is /// communicated in the DOM using the inverse paint order, specified by the /// z-index CSS style attribute. void updateChildren() { // Trivial case: remove all children. if (_childrenInHitTestOrder == null || _childrenInHitTestOrder!.isEmpty) { if (_currentChildrenInRenderOrder == null || _currentChildrenInRenderOrder!.isEmpty) { // A container element must not have been created when child list is empty. assert(_childContainerElement == null); _currentChildrenInRenderOrder = null; return; } // A container element must have been created when child list is not empty. assert(_childContainerElement != null); // Remove all children from this semantics object. final int len = _currentChildrenInRenderOrder!.length; for (int i = 0; i < len; i++) { owner._detachObject(_currentChildrenInRenderOrder![i].id); } _childContainerElement!.remove(); _childContainerElement = null; _currentChildrenInRenderOrder = null; return; } // At this point it is guaranteed to have at least one child. final Int32List childrenInTraversalOrder = _childrenInTraversalOrder!; final Int32List childrenInHitTestOrder = _childrenInHitTestOrder!; final int childCount = childrenInHitTestOrder.length; final DomElement? containerElement = getOrCreateChildContainer(); assert(childrenInTraversalOrder.length == childrenInHitTestOrder.length); // Always render in traversal order, because the accessibility traversal // is determined by the DOM order of elements. final List<SemanticsObject> childrenInRenderOrder = <SemanticsObject>[]; for (int i = 0; i < childCount; i++) { childrenInRenderOrder.add(owner._semanticsTree[childrenInTraversalOrder[i]]!); } // The z-index determines hit testing. Technically, it also affects paint // order. However, this does not matter because our ARIA tree is invisible. // On top of that, it is a bad UI practice when hit test order does not match // paint order, because human eye must be able to predict hit test order // simply by looking at the UI (if a dialog is painted on top of a dismiss // barrier, then tapping on anything inside the dialog should not land on // the barrier). final bool zIndexMatters = childCount > 1; if (zIndexMatters) { for (int i = 0; i < childCount; i++) { final SemanticsObject child = owner._semanticsTree[childrenInHitTestOrder[i]]!; // Invert the z-index because hit-test order is inverted with respect to // paint order. child.element.style.zIndex = '${childCount - i}'; } } // Trivial case: previous list was empty => just populate the container. if (_currentChildrenInRenderOrder == null || _currentChildrenInRenderOrder!.isEmpty) { for (final SemanticsObject child in childrenInRenderOrder) { containerElement!.append(child.element); owner._attachObject(parent: this, child: child); } _currentChildrenInRenderOrder = childrenInRenderOrder; return; } // At this point it is guaranteed to have had a non-empty previous child list. final List<SemanticsObject> previousChildrenInRenderOrder = _currentChildrenInRenderOrder!; final int previousCount = previousChildrenInRenderOrder.length; // Both non-empty case. // Problem: child nodes have been added, removed, and/or reordered. On the // web, many assistive technologies cannot track DOM elements // moving around, losing focus. The best approach is to try to keep // child elements as stable as possible. // Solution: find all common elements in both lists and record their indices // in the old list (in the `intersectionIndicesOld` variable). The // longest increases subsequence provides the longest chain of // semantics nodes that didn't move relative to each other. Those // nodes (represented by the `stationaryIds` variable) are kept // stationary, while all others are moved/inserted/deleted around // them. This gives the maximum node stability, and covers most // use-cases, including scrolling in any direction, insertions, // deletions, drag'n'drop, etc. // Indices into the old child list pointing at children that also exist in // the new child list. final List<int> intersectionIndicesOld = <int>[]; int newIndex = 0; // The smallest of the two child list lengths. final int minLength = math.min(previousCount, childCount); // Scan forward until first discrepancy. while (newIndex < minLength && previousChildrenInRenderOrder[newIndex] == childrenInRenderOrder[newIndex]) { intersectionIndicesOld.add(newIndex); newIndex += 1; } // Trivial case: child lists are identical both in length and order => do nothing. if (previousCount == childrenInRenderOrder.length && newIndex == childCount) { return; } // If child lists are not identical, continue computing the intersection // between the two lists. while (newIndex < childCount) { for (int oldIndex = 0; oldIndex < previousCount; oldIndex += 1) { if (previousChildrenInRenderOrder[oldIndex] == childrenInRenderOrder[newIndex]) { intersectionIndicesOld.add(oldIndex); break; } } newIndex += 1; } // The longest sub-sequence in the old list maximizes the number of children // that do not need to be moved. final List<int?> longestSequence = longestIncreasingSubsequence(intersectionIndicesOld); final List<int> stationaryIds = <int>[]; for (int i = 0; i < longestSequence.length; i += 1) { stationaryIds.add( previousChildrenInRenderOrder[intersectionIndicesOld[longestSequence[i]!]].id ); } // Remove children that are no longer in the list. for (int i = 0; i < previousCount; i++) { if (!intersectionIndicesOld.contains(i)) { // Child not in the intersection. Must be removed. final int childId = previousChildrenInRenderOrder[i].id; owner._detachObject(childId); } } DomElement? refNode; for (int i = childCount - 1; i >= 0; i -= 1) { final SemanticsObject child = childrenInRenderOrder[i]; if (!stationaryIds.contains(child.id)) { if (refNode == null) { containerElement!.append(child.element); } else { containerElement!.insertBefore(child.element, refNode); } owner._attachObject(parent: this, child: child); } else { assert(child._parent == this); } refNode = child.element; } _currentChildrenInRenderOrder = childrenInRenderOrder; } /// The primary role of this node. /// /// The primary role is assigned by [updateSelf] based on the combination of /// semantics flags and actions. PrimaryRoleManager? primaryRole; PrimaryRole _getPrimaryRoleIdentifier() { // The most specific role should take precedence. if (isPlatformView) { return PrimaryRole.platformView; } else if (isTextField) { return PrimaryRole.textField; } else if (isIncrementable) { return PrimaryRole.incrementable; } else if (isVisualOnly) { return PrimaryRole.image; } else if (isCheckable) { return PrimaryRole.checkable; } else if (isButton) { return PrimaryRole.button; } else if (isScrollContainer) { return PrimaryRole.scrollable; } else if (scopesRoute) { return PrimaryRole.dialog; } else if (isLink) { return PrimaryRole.link; } else { return PrimaryRole.generic; } } PrimaryRoleManager _createPrimaryRole(PrimaryRole role) { return switch (role) { PrimaryRole.textField => TextField(this), PrimaryRole.scrollable => Scrollable(this), PrimaryRole.incrementable => Incrementable(this), PrimaryRole.button => Button(this), PrimaryRole.checkable => Checkable(this), PrimaryRole.dialog => Dialog(this), PrimaryRole.image => ImageRoleManager(this), PrimaryRole.platformView => PlatformViewRoleManager(this), PrimaryRole.link => Link(this), PrimaryRole.generic => GenericRole(this), }; } /// Detects the roles that this semantics object corresponds to and asks the /// respective role managers to update the DOM. void _updateRoles() { PrimaryRoleManager? currentPrimaryRole = primaryRole; final PrimaryRole roleId = _getPrimaryRoleIdentifier(); final DomElement? previousElement = primaryRole?.element; if (currentPrimaryRole != null) { if (currentPrimaryRole.role == roleId) { // Already has a primary role assigned and the role is the same as before, // so simply perform an update. currentPrimaryRole.update(); return; } else { // Role changed. This should be avoided as much as possible, but the // web engine will attempt a best with the switch by cleaning old ARIA // role data and start anew. currentPrimaryRole.dispose(); currentPrimaryRole = null; primaryRole = null; } } // This handles two cases: // * The node was just created and needs a primary role manager. // * (Uncommon) the node changed its primary role, its previous primary // role manager was disposed of, and now it needs a new one. if (currentPrimaryRole == null) { currentPrimaryRole = _createPrimaryRole(roleId); primaryRole = currentPrimaryRole; currentPrimaryRole.update(); } // Reparent element. if (previousElement != element) { final DomElement? container = _childContainerElement; if (container != null) { element.append(container); } final DomElement? parent = previousElement?.parent; if (parent != null) { parent.insertBefore(element, previousElement); previousElement!.remove(); } } } /// Whether the object represents an UI element with "increase" or "decrease" /// controls, e.g. a slider. /// /// Such objects are expressed in HTML using `<input type="range">`. bool get isIncrementable => hasAction(ui.SemanticsAction.increase) || hasAction(ui.SemanticsAction.decrease); /// Whether the object represents a button. bool get isButton => hasFlag(ui.SemanticsFlag.isButton); /// Represents a tappable or clickable widget, such as button, icon button, /// "hamburger" menu, etc. bool get isTappable => hasAction(ui.SemanticsAction.tap); bool get isCheckable => hasFlag(ui.SemanticsFlag.hasCheckedState) || hasFlag(ui.SemanticsFlag.hasToggledState); /// Role-specific adjustment of the vertical position of the child container. /// /// This is used, for example, by the [Scrollable] to compensate for the /// `scrollTop` offset in the DOM. /// /// This field must not be null. double verticalContainerAdjustment = 0.0; /// Role-specific adjustment of the horizontal position of the child /// container. /// /// This is used, for example, by the [Scrollable] to compensate for the /// `scrollLeft` offset in the DOM. /// /// This field must not be null. double horizontalContainerAdjustment = 0.0; /// Computes the size and position of [element] and, if this element /// [hasChildren], of [getOrCreateChildContainer]. void recomputePositionAndSize() { element.style ..width = '${_rect!.width}px' ..height = '${_rect!.height}px'; final DomElement? containerElement = hasChildren ? getOrCreateChildContainer() : null; final bool hasZeroRectOffset = _rect!.top == 0.0 && _rect!.left == 0.0; final Float32List? transform = _transform; final bool hasIdentityTransform = transform == null || isIdentityFloat32ListTransform(transform); if (hasZeroRectOffset && hasIdentityTransform && verticalContainerAdjustment == 0.0 && horizontalContainerAdjustment == 0.0) { _clearSemanticElementTransform(element); if (containerElement != null) { _clearSemanticElementTransform(containerElement); } return; } late Matrix4 effectiveTransform; bool effectiveTransformIsIdentity = true; if (!hasZeroRectOffset) { if (transform == null) { final double left = _rect!.left; final double top = _rect!.top; effectiveTransform = Matrix4.translationValues(left, top, 0.0); effectiveTransformIsIdentity = left == 0.0 && top == 0.0; } else { // Clone to avoid mutating _transform. effectiveTransform = Matrix4.fromFloat32List(transform).clone() ..translate(_rect!.left, _rect!.top); effectiveTransformIsIdentity = effectiveTransform.isIdentity(); } } else if (!hasIdentityTransform) { effectiveTransform = Matrix4.fromFloat32List(transform); effectiveTransformIsIdentity = false; } if (!effectiveTransformIsIdentity) { element.style ..transformOrigin = '0 0 0' ..transform = matrix4ToCssTransform(effectiveTransform); } else { _clearSemanticElementTransform(element); } if (containerElement != null) { if (!hasZeroRectOffset || verticalContainerAdjustment != 0.0 || horizontalContainerAdjustment != 0.0) { final double translateX = -_rect!.left + horizontalContainerAdjustment; final double translateY = -_rect!.top + verticalContainerAdjustment; containerElement.style ..top = '${translateY}px' ..left = '${translateX}px'; } else { _clearSemanticElementTransform(containerElement); } } } /// Clears the transform on a semantic element as if an identity transform is /// applied. /// /// On macOS and iOS, VoiceOver requires `left=0; top=0` value to correctly /// handle traversal order. /// /// See https://github.com/flutter/flutter/issues/73347. static void _clearSemanticElementTransform(DomElement element) { element.style ..removeProperty('transform-origin') ..removeProperty('transform'); if (isMacOrIOS) { element.style ..top = '0px' ..left = '0px'; } else { element.style ..removeProperty('top') ..removeProperty('left'); } } /// Recursively visits the tree rooted at `this` node in depth-first fashion /// in the order nodes were rendered into the DOM. /// /// Useful for debugging only. /// /// Calls the [callback] for `this` node, then for all of its descendants. /// /// Unlike [visitDepthFirstInTraversalOrder] this method can traverse /// partially updated, incomplete, or inconsistent tree. void _debugVisitRenderedSemanticNodesDepthFirst(void Function(SemanticsObject) callback) { callback(this); _currentChildrenInRenderOrder?.forEach((SemanticsObject child) { child._debugVisitRenderedSemanticNodesDepthFirst(callback); }); } /// Recursively visits the tree rooted at `this` node in depth-first fashion /// in traversal order. /// /// Calls the [callback] for `this` node, then for all of its descendants. If /// the callback returns true, continues visiting descendants. Otherwise, /// stops immediately after visiting the node that caused the callback to /// return false. void visitDepthFirstInTraversalOrder(bool Function(SemanticsObject) callback) { _visitDepthFirstInTraversalOrder(callback); } bool _visitDepthFirstInTraversalOrder(bool Function(SemanticsObject) callback) { final bool shouldContinueVisiting = callback(this); if (!shouldContinueVisiting) { return false; } final Int32List? childrenInTraversalOrder = _childrenInTraversalOrder; if (childrenInTraversalOrder == null) { return true; } for (final int childId in childrenInTraversalOrder) { final SemanticsObject? child = owner._semanticsTree[childId]; assert( child != null, 'visitDepthFirstInTraversalOrder must only be called after the node ' 'tree has been established. However, child #$childId does not have its ' 'SemanticsNode created at the time this method was called.', ); if (!child!._visitDepthFirstInTraversalOrder(callback)) { return false; } } return true; } @override String toString() { String result = super.toString(); assert(() { final String children = _childrenInTraversalOrder != null && _childrenInTraversalOrder!.isNotEmpty ? '[${_childrenInTraversalOrder!.join(', ')}]' : '<empty>'; result = '$runtimeType(#$id, children: $children)'; return true; }()); return result; } bool _isDisposed = false; void dispose() { assert(!_isDisposed); _isDisposed = true; element.remove(); _parent = null; primaryRole?.dispose(); primaryRole = null; } } /// Controls how pointer events and browser-detected gestures are treated by /// the Web Engine. enum AccessibilityMode { /// Flutter is not told whether the assistive technology is enabled or not. /// /// This is the default mode. /// /// In this mode a gesture recognition system is used that deduplicates /// gestures detected by Flutter with gestures detected by the browser. unknown, /// Flutter is told whether the assistive technology is enabled. known, } /// Called when the current [GestureMode] changes. typedef GestureModeCallback = void Function(GestureMode mode); /// The method used to detect user gestures. enum GestureMode { /// Send pointer events to Flutter to detect gestures using framework-level /// gesture recognizers and gesture arenas. pointerEvents, /// Listen to browser-detected gestures and report them to the framework as /// [ui.SemanticsAction]. browserGestures, } /// The current phase of the semantic update. enum SemanticsUpdatePhase { /// No update is in progress. /// /// When the semantics owner receives an update, it enters the [updating] /// phase from the idle phase. idle, /// Updating individual [SemanticsObject] nodes by calling /// [RoleManager.update] and fixing parent-child relationships. /// /// After this phase is done, the owner enters the [postUpdate] phase. updating, /// Post-update callbacks are being called. /// /// At this point all nodes have been updated, the parent child hierarchy has /// been established, the DOM tree is in sync with the semantics tree, and /// [RoleManager.dispose] has been called on removed nodes. /// /// After this phase is done, the owner switches back to [idle]. postUpdate, } /// The semantics system of the Web Engine. /// /// Maintains global properties and behaviors of semantics in the engine, such /// as whether semantics is currently enabled or disabled. class EngineSemantics { EngineSemantics._(); /// The singleton instance that manages semantics. static EngineSemantics get instance { return _instance ??= EngineSemantics._(); } static EngineSemantics? _instance; /// Disables semantics and uninitializes the singleton [instance]. /// /// Instances of [EngineSemanticsOwner] are no longer valid after calling this /// method. Using them will lead to undefined behavior. This method is only /// meant to be used for testing. static void debugResetSemantics() { if (_instance == null) { return; } _instance!.semanticsEnabled = false; _instance = null; } /// Whether the user has requested that [updateSemantics] be called when the /// semantic contents of window changes. /// /// The [ui.PlatformDispatcher.onSemanticsEnabledChanged] callback is called /// whenever this value changes. /// /// This is separate from accessibility [mode], which controls how gestures /// are interpreted when this value is true. bool get semanticsEnabled => _semanticsEnabled; bool _semanticsEnabled = false; set semanticsEnabled(bool value) { if (value == _semanticsEnabled) { return; } final EngineAccessibilityFeatures original = EnginePlatformDispatcher.instance.configuration.accessibilityFeatures as EngineAccessibilityFeatures; final PlatformConfiguration newConfiguration = EnginePlatformDispatcher.instance.configuration.copyWith( accessibilityFeatures: original.copyWith(accessibleNavigation: value)); EnginePlatformDispatcher.instance.configuration = newConfiguration; _semanticsEnabled = value; if (!_semanticsEnabled) { // Do not process browser events at all when semantics is explicitly // disabled. All gestures are handled by the framework-level gesture // recognizers from pointer events. if (_gestureMode != GestureMode.pointerEvents) { _gestureMode = GestureMode.pointerEvents; _notifyGestureModeListeners(); } for (final EngineFlutterView view in EnginePlatformDispatcher.instance.views) { view.semantics.reset(); } _gestureModeClock?.datetime = null; } EnginePlatformDispatcher.instance.updateSemanticsEnabled(_semanticsEnabled); } /// Prepares the semantics system for a semantic tree update. /// /// This method must be called prior to updating the semantics inside any /// individual view. /// /// Automatically enables semantics in a production setting. In Flutter test /// environment keeps engine semantics turned off due to tests frequently /// sending inconsistent semantics updates. /// /// The caller is expected to check if [semanticsEnabled] is true prior to /// actually updating the semantic DOM. void didReceiveSemanticsUpdate() { if (!_semanticsEnabled) { if (ui_web.debugEmulateFlutterTesterEnvironment) { // Running Flutter widget tests in a fake environment. Don't enable // engine semantics. Test semantics trees violate invariants in ways // production implementation isn't built to handle. For example, tests // routinely reset semantics node IDs, which is messing up the update // process. return; } else { // Running a real app. Auto-enable engine semantics. semanticsHelper.dispose(); // placeholder no longer needed semanticsEnabled = true; } } } TimestampFunction _now = () => DateTime.now(); void debugOverrideTimestampFunction(TimestampFunction value) { _now = value; } void debugResetTimestampFunction() { _now = () => DateTime.now(); } final SemanticsHelper semanticsHelper = SemanticsHelper(); /// Controls how pointer events and browser-detected gestures are treated by /// the Web Engine. /// /// The default mode is [AccessibilityMode.unknown]. AccessibilityMode mode = AccessibilityMode.unknown; /// Currently used [GestureMode]. /// /// This value changes automatically depending on the incoming input events. /// Functionality that implements different strategies depending on this mode /// would use [addGestureModeListener] and [removeGestureModeListener] to get /// notifications about when the value of this field changes. GestureMode get gestureMode => _gestureMode; GestureMode _gestureMode = GestureMode.browserGestures; AlarmClock? _gestureModeClock; AlarmClock? _getGestureModeClock() { if (_gestureModeClock == null) { _gestureModeClock = AlarmClock(_now); _gestureModeClock!.callback = () { if (_gestureMode == GestureMode.browserGestures) { return; } _gestureMode = GestureMode.browserGestures; _notifyGestureModeListeners(); }; } return _gestureModeClock; } /// Disables browser gestures temporarily because pointer events were detected. /// /// This is used to deduplicate gestures detected by Flutter and gestures /// detected by the browser. Flutter-detected gestures have higher precedence. void _temporarilyDisableBrowserGestureMode() { const Duration kDebounceThreshold = Duration(milliseconds: 500); _getGestureModeClock()!.datetime = _now().add(kDebounceThreshold); if (_gestureMode != GestureMode.pointerEvents) { _gestureMode = GestureMode.pointerEvents; _notifyGestureModeListeners(); } } /// Receives DOM events from the pointer event system to correlate with the /// semantics events. /// /// Returns true if the event should be forwarded to the framework. /// /// The browser sends us both raw pointer events and gestures from /// [SemanticsObject.element]s. There could be three possibilities: /// /// 1. Assistive technology is enabled and Flutter knows that it is. /// 2. Assistive technology is disabled and Flutter knows that it isn't. /// 3. Flutter does not know whether an assistive technology is enabled. /// /// If [autoEnableOnTap] was called, this will automatically enable semantics /// if the user requests it. /// /// In the first case ignore raw pointer events and only interpret /// high-level gestures, e.g. "click". /// /// In the second case ignore high-level gestures and interpret the raw /// pointer events directly. /// /// Finally, in a mode when Flutter does not know if an assistive technology /// is enabled or not do a best-effort estimate which to respond to, raw /// pointer or high-level gestures. Avoid doing both because that will /// result in double-firing of event listeners, such as `onTap` on a button. /// The approach is to measure the distance between the last pointer /// event and a gesture event. If a gesture is receive "soon" after the last /// received pointer event (determined by a heuristic), it is debounced as it /// is likely that the gesture detected from the pointer even will do the /// right thing. However, if a standalone gesture is received, map it onto a /// [ui.SemanticsAction] to be processed by the framework. bool receiveGlobalEvent(DomEvent event) { // For pointer event reference see: // // https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events const List<String> pointerEventTypes = <String>[ 'pointerdown', 'pointermove', 'pointerleave', 'pointerup', 'pointercancel', 'touchstart', 'touchend', 'touchmove', 'touchcancel', 'mousedown', 'mousemove', 'mouseleave', 'mouseup', 'keyup', 'keydown', ]; if (pointerEventTypes.contains(event.type)) { _temporarilyDisableBrowserGestureMode(); } return semanticsHelper.shouldEnableSemantics(event); } /// Callbacks called when the [GestureMode] changes. /// /// Callbacks are called synchronously. HTML DOM updates made in a callback /// take effect in the current animation frame and/or the current message loop /// event. final List<GestureModeCallback> _gestureModeListeners = <GestureModeCallback>[]; /// Calls the [callback] every time the current [GestureMode] changes. /// /// The callback is called synchronously. HTML DOM updates made in the /// callback take effect in the current animation frame and/or the current /// message loop event. void addGestureModeListener(GestureModeCallback callback) { _gestureModeListeners.add(callback); } /// Stops calling the [callback] when the [GestureMode] changes. /// /// The passed [callback] must be the exact same object as the one passed to /// [addGestureModeListener]. void removeGestureModeListener(GestureModeCallback callback) { assert(_gestureModeListeners.contains(callback)); _gestureModeListeners.remove(callback); } void _notifyGestureModeListeners() { for (int i = 0; i < _gestureModeListeners.length; i++) { _gestureModeListeners[i](_gestureMode); } } /// Whether a gesture event of type [eventType] should be accepted as a /// semantic action. /// /// If [mode] is [AccessibilityMode.known] the gesture is always accepted if /// [semanticsEnabled] is `true`, and it is always rejected if /// [semanticsEnabled] is `false`. /// /// If [mode] is [AccessibilityMode.unknown] the gesture is accepted if it is /// not accompanied by pointer events. In the presence of pointer events, /// delegate to Flutter's gesture detection system to produce gestures. bool shouldAcceptBrowserGesture(String eventType) { if (mode == AccessibilityMode.known) { // Do not ignore accessibility gestures in known mode, unless semantics // is explicitly disabled. return semanticsEnabled; } const List<String> pointerDebouncedGestures = <String>[ 'click', 'scroll', ]; if (pointerDebouncedGestures.contains(eventType)) { return _gestureMode == GestureMode.browserGestures; } return false; } } /// The top-level service that manages everything semantics-related. class EngineSemanticsOwner { EngineSemanticsOwner(this.semanticsHost) { registerHotRestartListener(() { _rootSemanticsElement?.remove(); }); } /// The permanent element in the view's DOM structure that hosts the semantics /// tree. /// /// The only child of this element is the [rootSemanticsElement]. Unlike the /// root element, this element is never replaced. It is always part of the /// DOM structure of the respective [FlutterView]. // TODO(yjbanov): rename to hostElement final DomElement semanticsHost; /// The DOM element corresponding to the root semantics node in the semantics /// tree. /// /// This element is the direct child of the [semanticsHost] and it is /// replaceable. // TODO(yjbanov): rename to rootElement DomElement? get rootSemanticsElement => _rootSemanticsElement; DomElement? _rootSemanticsElement; /// The current update phase of this semantics owner. SemanticsUpdatePhase get phase => _phase; SemanticsUpdatePhase _phase = SemanticsUpdatePhase.idle; final Map<int, SemanticsObject> _semanticsTree = <int, SemanticsObject>{}; /// Map [SemanticsObject.id] to parent [SemanticsObject] it was attached to /// this frame. Map<int, SemanticsObject> _attachments = <int, SemanticsObject>{}; /// Declares that the [child] must be attached to the [parent]. /// /// Attachments take precedence over detachments (see [_detachObject]). This /// allows the same node to be detached from one parent in the tree and /// reattached to another parent. void _attachObject({required SemanticsObject parent, required SemanticsObject child}) { child._parent = parent; _attachments[child.id] = parent; } /// List of objects that were detached this frame. /// /// The objects in this list will be detached permanently unless they are /// reattached via the [_attachObject] method. List<SemanticsObject> _detachments = <SemanticsObject>[]; /// Declares that the [SemanticsObject] with the given [id] was detached from /// its current parent object. /// /// The object will be detached permanently unless it is reattached via the /// [_attachObject] method. void _detachObject(int id) { final SemanticsObject? object = _semanticsTree[id]; assert(object != null); if (object != null) { _detachments.add(object); } } /// Callbacks called after all objects in the tree have their properties /// populated and their sizes and locations computed. /// /// This list is reset to empty after all callbacks are called. List<ui.VoidCallback> _oneTimePostUpdateCallbacks = <ui.VoidCallback>[]; /// Schedules a one-time callback to be called after all objects in the tree /// have their properties populated and their sizes and locations computed. void addOneTimePostUpdateCallback(ui.VoidCallback callback) { _oneTimePostUpdateCallbacks.add(callback); } /// Reconciles [_attachments] and [_detachments], and after that calls all /// the one-time callbacks scheduled via the [addOneTimePostUpdateCallback] /// method. void _finalizeTree() { // Collect all nodes that need to be permanently removed, i.e. nodes that // were detached from their parent, but not reattached to another parent. final Set<SemanticsObject> removals = <SemanticsObject>{}; for (final SemanticsObject detachmentRoot in _detachments) { // A detached node may or may not have some of its descendants reattached // elsewhere. Walk the descendant tree and find all descendants that were // reattached to a parent. Those descendants need to be removed. detachmentRoot.visitDepthFirstInTraversalOrder((SemanticsObject node) { final SemanticsObject? parent = _attachments[node.id]; if (parent == null) { // Was not reparented and is removed permanently from the tree. removals.add(node); } else { assert(node._parent == parent); assert(node.element.parentNode == parent._childContainerElement); } return true; }); } for (final SemanticsObject removal in removals) { _semanticsTree.remove(removal.id); removal.dispose(); } _detachments = <SemanticsObject>[]; _attachments = <int, SemanticsObject>{}; _phase = SemanticsUpdatePhase.postUpdate; try { if (_oneTimePostUpdateCallbacks.isNotEmpty) { for (final ui.VoidCallback callback in _oneTimePostUpdateCallbacks) { callback(); } _oneTimePostUpdateCallbacks = <ui.VoidCallback>[]; } } finally { _phase = SemanticsUpdatePhase.idle; } _hasNodeRequestingFocus = false; } /// Returns the entire semantics tree for testing. /// /// Works only in debug mode. Map<int, SemanticsObject>? get debugSemanticsTree { Map<int, SemanticsObject>? result; assert(() { result = _semanticsTree; return true; }()); return result; } /// Looks up a [SemanticsObject] in the semantics tree by ID, or creates a new /// instance if it does not exist. SemanticsObject getOrCreateObject(int id) { SemanticsObject? object = _semanticsTree[id]; if (object == null) { object = SemanticsObject(id, this); _semanticsTree[id] = object; } return object; } // Checks the consistency of the semantics node tree against the {ID: node} // map. The two must be in total agreement. Every node in the map must be // somewhere in the tree. (bool, String) _computeNodeMapConsistencyMessage() { final Map<int, List<int>> liveIds = <int, List<int>>{}; final SemanticsObject? root = _semanticsTree[0]; if (root != null) { root._debugVisitRenderedSemanticNodesDepthFirst((SemanticsObject child) { liveIds[child.id] = child._childrenInTraversalOrder?.toList() ?? const <int>[]; }); } final bool isConsistent = _semanticsTree.keys.every(liveIds.keys.contains); final String heading = 'The semantics node map is ${isConsistent ? 'consistent' : 'inconsistent'}'; final StringBuffer message = StringBuffer('$heading:\n'); message.writeln(' Nodes in tree:'); for (final MapEntry<int, List<int>> entry in liveIds.entries) { message.writeln(' ${entry.key}: ${entry.value}'); } message.writeln(' Nodes in map: [${_semanticsTree.keys.join(', ')}]'); return (isConsistent, message.toString()); } /// Updates the semantics tree from data in the [uiUpdate]. void updateSemantics(ui.SemanticsUpdate uiUpdate) { EngineSemantics.instance.didReceiveSemanticsUpdate(); if (!EngineSemantics.instance.semanticsEnabled) { return; } (bool, String)? preUpdateNodeMapConsistency; assert(() { preUpdateNodeMapConsistency = _computeNodeMapConsistencyMessage(); return true; }()); _phase = SemanticsUpdatePhase.updating; final SemanticsUpdate update = uiUpdate as SemanticsUpdate; // First, update each object's information about itself. This information is // later used to fix the parent-child and sibling relationships between // objects. final List<SemanticsNodeUpdate> nodeUpdates = update._nodeUpdates!; for (final SemanticsNodeUpdate nodeUpdate in nodeUpdates) { final SemanticsObject object = getOrCreateObject(nodeUpdate.id); object.updateSelf(nodeUpdate); } // Second, fix the tree structure. This is moved out into its own loop, // because each object's own information must be updated first. for (final SemanticsNodeUpdate nodeUpdate in nodeUpdates) { final SemanticsObject object = _semanticsTree[nodeUpdate.id]!; object.updateChildren(); object._dirtyFields = 0; } final SemanticsObject root = _semanticsTree[0]!; if (_rootSemanticsElement == null) { _rootSemanticsElement = root.element; semanticsHost.append(root.element); } _finalizeTree(); assert(() { // Validate that the node map only contains live elements, i.e. descendants // of the root node. If a node is not reachable from the root, it should // have been removed from the map. final (bool isConsistent, String description) = _computeNodeMapConsistencyMessage(); if (!isConsistent) { // Use StateError because AssertionError escapes line breaks, but this // error message is very detailed and it needs line breaks for // legibility. throw StateError(''' Semantics node map was inconsistent after update: BEFORE: ${preUpdateNodeMapConsistency?.$2} AFTER: $description '''); } // Validate that each node in the final tree is self-consistent. _semanticsTree.forEach((int? id, SemanticsObject object) { assert(id == object.id); // Dirty fields should be cleared after the tree has been finalized. assert(object._dirtyFields == 0); // Make sure a child container is created only when there are children. assert(object._childContainerElement == null || object.hasChildren); // Ensure child ID list is consistent with the parent-child // relationship of the semantics tree. if (object._childrenInTraversalOrder != null) { for (final int childId in object._childrenInTraversalOrder!) { final SemanticsObject? child = _semanticsTree[childId]; if (child == null) { throw AssertionError('Child #$childId is missing in the tree.'); } if (child._parent == null) { throw AssertionError( 'Child #$childId of parent #${object.id} has null parent ' 'reference.'); } if (!identical(child._parent, object)) { throw AssertionError( 'Parent #${object.id} has child #$childId. However, the ' 'child is attached to #${child._parent!.id}.'); } } } }); // Validate that all updates were applied for (final SemanticsNodeUpdate update in nodeUpdates) { // Node was added to the tree. assert(_semanticsTree.containsKey(update.id)); } // Verify that `update._nodeUpdates` has not changed. assert(identical(update._nodeUpdates, nodeUpdates)); return true; }()); } /// Removes the semantics tree for this view from the page and collects all /// resources. /// /// The object remains usable after this operation, but because the previous /// semantics tree is completely removed, partial udpates will not succeed as /// they rely on the prior state of the tree. There is no distinction between /// a full update and partial update, so the failure may be cryptic. void reset() { final List<int> keys = _semanticsTree.keys.toList(); final int len = keys.length; for (int i = 0; i < len; i++) { _detachObject(keys[i]); } _finalizeTree(); _rootSemanticsElement?.remove(); _rootSemanticsElement = null; _semanticsTree.clear(); _attachments.clear(); _detachments.clear(); _phase = SemanticsUpdatePhase.idle; _oneTimePostUpdateCallbacks.clear(); } /// True, if any semantics node requested focus explicitly during the latest /// semantics update. /// /// The default value is `false`, and it is reset back to `false` after the /// semantics update at the end of [updateSemantics]. /// /// Since focus can only be taken by no more than one element, the engine /// should not request focus for multiple elements. This flag helps resolve /// that. bool get hasNodeRequestingFocus => _hasNodeRequestingFocus; bool _hasNodeRequestingFocus = false; /// Declares that a semantics node will explicitly request focus. /// /// This prevents others, [Dialog] in particular, from requesting autofocus, /// as focus can only be taken by one element. Explicit focus has higher /// precedence than autofocus. void willRequestFocus() { _hasNodeRequestingFocus = true; } } /// Computes the [longest increasing subsequence](http://en.wikipedia.org/wiki/Longest_increasing_subsequence). /// /// Returns list of indices (rather than values) into [list]. /// /// Complexity: n*log(n) List<int> longestIncreasingSubsequence(List<int> list) { final int len = list.length; final List<int> predecessors = <int>[]; final List<int> mins = <int>[0]; int longest = 0; for (int i = 0; i < len; i++) { // Binary search for the largest positive `j ≤ longest` // such that `list[mins[j]] < list[i]` final int elem = list[i]; int lo = 1; int hi = longest; while (lo <= hi) { final int mid = (lo + hi) ~/ 2; if (list[mins[mid]] < elem) { lo = mid + 1; } else { hi = mid - 1; } } // After searching, `lo` is 1 greater than the // length of the longest prefix of `list[i]` final int expansionIndex = lo; // The predecessor of `list[i]` is the last index of // the subsequence of length `newLongest - 1` predecessors.add(mins[expansionIndex - 1]); if (expansionIndex >= mins.length) { mins.add(i); } else { mins[expansionIndex] = i; } if (expansionIndex > longest) { // Record the longest subsequence found so far. longest = expansionIndex; } } // Reconstruct the longest subsequence final List<int> seq = List<int>.filled(longest, 0); int k = mins[longest]; for (int i = longest - 1; i >= 0; i--) { seq[i] = k; k = predecessors[k]; } return seq; } /// States that a [ui.SemanticsNode] can have. /// /// SemanticsNodes can be in three distinct states (enabled, disabled, /// no opinion). enum EnabledState { /// Flag [ui.SemanticsFlag.hasEnabledState] is not set. /// /// The node does not have enabled/disabled state. noOpinion, /// Flag [ui.SemanticsFlag.hasEnabledState] and [ui.SemanticsFlag.isEnabled] /// are set. /// /// The node is enabled. enabled, /// Flag [ui.SemanticsFlag.hasEnabledState] is set and /// [ui.SemanticsFlag.isEnabled] is not set. /// /// The node is disabled. disabled, }
engine/lib/web_ui/lib/src/engine/semantics/semantics.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/semantics/semantics.dart", "repo_id": "engine", "token_count": 28839 }
268
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:ffi'; import 'dart:js_interop'; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; // This URL was found by using the Google Fonts Developer API to find the URL // for Roboto. The API warns that this URL is not stable. In order to update // this, list out all of the fonts and find the URL for the regular // Roboto font. The API reference is here: // https://developers.google.com/fonts/docs/developer_api const String _robotoUrl = 'https://fonts.gstatic.com/s/roboto/v20/KFOmCnqEu92Fr1Me5WZLCzYlKw.ttf'; class SkwasmTypeface extends SkwasmObjectWrapper<RawTypeface> { SkwasmTypeface(SkDataHandle data) : super(typefaceCreate(data), _registry); static final SkwasmFinalizationRegistry<RawTypeface> _registry = SkwasmFinalizationRegistry<RawTypeface>(typefaceDispose); } class SkwasmFontCollection implements FlutterFontCollection { SkwasmFontCollection() { setDefaultFontFamilies(<String>['Roboto']); } // Most of the time, when an object deals with native handles to skwasm objects, // we register it with a finalization registry so that it can clean up the handle // when the dart side of object gets GC'd. However, this object is basically a // singleton (the renderer creates one and just hangs onto it forever) so it's // not really worth it to do the finalization dance here. FontCollectionHandle handle = fontCollectionCreate(); SkwasmNativeTextStyle defaultTextStyle = SkwasmNativeTextStyle.defaultTextStyle(); final Map<String, List<SkwasmTypeface>> registeredTypefaces = <String, List<SkwasmTypeface>>{}; void setDefaultFontFamilies(List<String> families) => withStackScope((StackScope scope) { final Pointer<SkStringHandle> familyPointers = scope.allocPointerArray(families.length).cast<SkStringHandle>(); for (int i = 0; i < families.length; i++) { familyPointers[i] = skStringFromDartString(families[i]); } textStyleClearFontFamilies(defaultTextStyle.handle); textStyleAddFontFamilies(defaultTextStyle.handle, familyPointers, families.length); for (int i = 0; i < families.length; i++) { skStringFree(familyPointers[i]); } }); @override late FontFallbackManager fontFallbackManager = FontFallbackManager(SkwasmFallbackRegistry(this)); @override void clear() { fontCollectionDispose(handle); handle = fontCollectionCreate(); } @override Future<AssetFontsResult> loadAssetFonts(FontManifest manifest) async { final List<Future<void>> fontFutures = <Future<void>>[]; final Map<String, FontLoadError> fontFailures = <String, FontLoadError>{}; /// We need a default fallback font for Skwasm, in order to avoid crashing /// while laying out text with an unregistered font. We chose Roboto to /// match Android. if (!manifest.families.any((FontFamily family) => family.name == 'Roboto')) { manifest.families.add( FontFamily('Roboto', <FontAsset>[FontAsset(_robotoUrl, <String, String>{})]) ); } final List<String> loadedFonts = <String>[]; for (final FontFamily family in manifest.families) { for (final FontAsset fontAsset in family.fontAssets) { loadedFonts.add(fontAsset.asset); fontFutures.add(() async { final FontLoadError? error = await _downloadFontAsset(fontAsset, family.name); if (error != null) { fontFailures[fontAsset.asset] = error; } }()); } } await Future.wait(fontFutures); loadedFonts.removeWhere((String assetName) => fontFailures.containsKey(assetName)); return AssetFontsResult(loadedFonts, fontFailures); } Future<FontLoadError?> _downloadFontAsset(FontAsset asset, String family) async { final HttpFetchResponse response; try { response = await ui_web.assetManager.loadAsset(asset.asset) as HttpFetchResponse; } catch (error) { return FontDownloadError(ui_web.assetManager.getAssetUrl(asset.asset), error); } if (!response.hasPayload) { return FontNotFoundError(ui_web.assetManager.getAssetUrl(asset.asset)); } int length = 0; final List<JSUint8Array> chunks = <JSUint8Array>[]; await response.read((JSUint8Array chunk) { length += chunk.length.toDartInt; chunks.add(chunk); }); final SkDataHandle fontData = skDataCreate(length); int dataAddress = skDataGetPointer(fontData).cast<Int8>().address; final JSUint8Array wasmMemory = createUint8ArrayFromBuffer(skwasmInstance.wasmMemory.buffer); for (final JSUint8Array chunk in chunks) { wasmMemory.set(chunk, dataAddress.toJS); dataAddress += chunk.length.toDartInt; } final SkwasmTypeface typeface = SkwasmTypeface(fontData); skDataDispose(fontData); if (typeface.handle != nullptr) { final SkStringHandle familyNameHandle = skStringFromDartString(family); fontCollectionRegisterTypeface(handle, typeface.handle, familyNameHandle); registeredTypefaces.putIfAbsent(family, () => <SkwasmTypeface>[]).add(typeface); skStringFree(familyNameHandle); return null; } else { return FontInvalidDataError(ui_web.assetManager.getAssetUrl(asset.asset)); } } Future<bool> loadFontFromUrl(String familyName, String url) async { final HttpFetchResponse response = await httpFetch(url); int length = 0; final List<JSUint8Array> chunks = <JSUint8Array>[]; await response.read((JSUint8Array chunk) { length += chunk.length.toDartInt; chunks.add(chunk); }); final SkDataHandle fontData = skDataCreate(length); int dataAddress = skDataGetPointer(fontData).cast<Int8>().address; final JSUint8Array wasmMemory = createUint8ArrayFromBuffer(skwasmInstance.wasmMemory.buffer); for (final JSUint8Array chunk in chunks) { wasmMemory.set(chunk, dataAddress.toJS); dataAddress += chunk.length.toDartInt; } final SkwasmTypeface typeface = SkwasmTypeface(fontData); skDataDispose(fontData); if (typeface.handle == nullptr) { return false; } final SkStringHandle familyNameHandle = skStringFromDartString(familyName); fontCollectionRegisterTypeface(handle, typeface.handle, familyNameHandle); registeredTypefaces.putIfAbsent(familyName, () => <SkwasmTypeface>[]).add(typeface); skStringFree(familyNameHandle); return true; } @override Future<bool> loadFontFromList(Uint8List list, {String? fontFamily}) async { final SkDataHandle dataHandle = skDataCreate(list.length); final Pointer<Int8> dataPointer = skDataGetPointer(dataHandle).cast<Int8>(); for (int i = 0; i < list.length; i++) { dataPointer[i] = list[i]; } final SkwasmTypeface typeface = SkwasmTypeface(dataHandle); skDataDispose(dataHandle); if (typeface.handle == nullptr) { return false; } if (fontFamily != null) { final SkStringHandle familyHandle = skStringFromDartString(fontFamily); fontCollectionRegisterTypeface(handle, typeface.handle, familyHandle); skStringFree(familyHandle); } else { fontCollectionRegisterTypeface(handle, typeface.handle, nullptr); } return true; } @override void debugResetFallbackFonts() { setDefaultFontFamilies(<String>['Roboto']); fontFallbackManager = FontFallbackManager(SkwasmFallbackRegistry(this)); fontCollectionClearCaches(handle); } } class SkwasmFallbackRegistry implements FallbackFontRegistry { SkwasmFallbackRegistry(this.fontCollection); final SkwasmFontCollection fontCollection; @override List<int> getMissingCodePoints(List<int> codePoints, List<String> fontFamilies) => withStackScope((StackScope scope) { final List<SkwasmTypeface> typefaces = fontFamilies .map((String family) => fontCollection.registeredTypefaces[family]) .fold(const Iterable<SkwasmTypeface>.empty(), (Iterable<SkwasmTypeface> accumulated, List<SkwasmTypeface>? typefaces) => typefaces == null ? accumulated : accumulated.followedBy(typefaces)).toList(); final Pointer<TypefaceHandle> typefaceBuffer = scope.allocPointerArray(typefaces.length).cast<TypefaceHandle>(); for (int i = 0; i < typefaces.length; i++) { typefaceBuffer[i] = typefaces[i].handle; } final Pointer<Int32> codePointBuffer = scope.allocInt32Array(codePoints.length); for (int i = 0; i < codePoints.length; i++) { codePointBuffer[i] = codePoints[i]; } final int missingCodePointCount = typefacesFilterCoveredCodePoints( typefaceBuffer, typefaces.length, codePointBuffer, codePoints.length ); return List<int>.generate(missingCodePointCount, (int index) => codePointBuffer[index]); }); @override Future<void> loadFallbackFont(String familyName, String url) => fontCollection.loadFontFromUrl(familyName, url); @override void updateFallbackFontFamilies(List<String> families) => fontCollection.setDefaultFontFamilies(families); }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/font_collection.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/font_collection.dart", "repo_id": "engine", "token_count": 3262 }
269
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:ffi'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; final class RawContourMeasure extends Opaque {} final class RawContourMeasureIter extends Opaque {} typedef ContourMeasureHandle = Pointer<RawContourMeasure>; typedef ContourMeasureIterHandle = Pointer<RawContourMeasureIter>; @Native<ContourMeasureIterHandle Function(PathHandle, Bool, Float)>( symbol: 'contourMeasureIter_create') external ContourMeasureIterHandle contourMeasureIterCreate( PathHandle path, bool forceClosed, double resScale); @Native<ContourMeasureHandle Function(ContourMeasureIterHandle)>( symbol: 'contourMeasureIter_next') external ContourMeasureHandle contourMeasureIterNext( ContourMeasureIterHandle handle); @Native<Void Function(ContourMeasureIterHandle)>( symbol: 'contourMeasureIter_dispose') external void contourMeasureIterDispose(ContourMeasureIterHandle handle); @Native<Void Function(ContourMeasureHandle)>(symbol: 'contourMeasure_dispose') external void contourMeasureDispose(ContourMeasureHandle handle); @Native<Float Function(ContourMeasureHandle)>(symbol: 'contourMeasure_length') external double contourMeasureLength(ContourMeasureHandle handle); @Native<Bool Function(ContourMeasureHandle)>(symbol: 'contourMeasure_isClosed') external bool contourMeasureIsClosed(ContourMeasureHandle handle); @Native< Bool Function(ContourMeasureHandle, Float, RawPointArray, RawPointArray)>(symbol: 'contourMeasure_getPosTan') external bool contourMeasureGetPosTan(ContourMeasureHandle handle, double distance, RawPointArray outPosition, RawPointArray outTangent); @Native<PathHandle Function(ContourMeasureHandle, Float, Float, Bool)>( symbol: 'contourMeasure_getSegment') external PathHandle contourMeasureGetSegment(ContourMeasureHandle handle, double start, double stop, bool startWithMoveTo);
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_path_metrics.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_path_metrics.dart", "repo_id": "engine", "token_count": 603 }
270
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:_wasm'; import 'dart:async'; import 'dart:ffi'; import 'dart:js_interop'; 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; @JS() @staticInterop @anonymous class RasterResult {} extension RasterResultExtension on RasterResult { external JSNumber get rasterStartMilliseconds; external JSNumber get rasterEndMilliseconds; external JSArray<JSAny> get imageBitmaps; } @pragma('wasm:export') WasmVoid callbackHandler(WasmI32 callbackId, WasmI32 context, WasmExternRef? jsContext) { // Actually hide this call behind whether skwasm is enabled. Otherwise, the SkwasmCallbackHandler // won't actually be tree-shaken, and we end up with skwasm imports in non-skwasm builds. if (FlutterConfiguration.flutterWebUseSkwasm) { SkwasmCallbackHandler.instance.handleCallback(callbackId, context, jsContext); } return WasmVoid(); } // This class handles callbacks coming from Skwasm by keeping a map of callback IDs to Completers class SkwasmCallbackHandler { SkwasmCallbackHandler._withCallbackPointer(this.callbackPointer); factory SkwasmCallbackHandler._() { final WasmFuncRef wasmFunction = WasmFunction<WasmVoid Function(WasmI32, WasmI32, WasmExternRef?)>.fromFunction(callbackHandler); final int functionIndex = addFunction(wasmFunction).toIntUnsigned(); return SkwasmCallbackHandler._withCallbackPointer( OnRenderCallbackHandle.fromAddress(functionIndex) ); } static SkwasmCallbackHandler instance = SkwasmCallbackHandler._(); final OnRenderCallbackHandle callbackPointer; final Map<CallbackId, Completer<JSAny>> _pendingCallbacks = <int, Completer<JSAny>>{}; // Returns a future that will resolve when Skwasm calls back with the given callbackID Future<JSAny> registerCallback(int callbackId) { final Completer<JSAny> completer = Completer<JSAny>(); _pendingCallbacks[callbackId] = completer; return completer.future; } void handleCallback(WasmI32 callbackId, WasmI32 context, WasmExternRef? jsContext) { // Skwasm can either callback with a JS object (an externref) or it can call back // with a simple integer, which usually refers to a pointer on its heap. In order // to coerce these into a single type, we just make the completers take a JSAny // that either contains the JS object or a JSNumber that contains the integer value. final Completer<JSAny> completer = _pendingCallbacks.remove(callbackId.toIntUnsigned())!; if (!jsContext.isNull) { completer.complete(jsContext!.toJS); } else { completer.complete(context.toIntUnsigned().toJS); } } } class SkwasmSurface { factory SkwasmSurface() { final SurfaceHandle surfaceHandle = withStackScope((StackScope scope) { return surfaceCreate(); }); final SkwasmSurface surface = SkwasmSurface._fromHandle(surfaceHandle); surface._initialize(); return surface; } SkwasmSurface._fromHandle(this.handle) : threadId = surfaceGetThreadId(handle); final SurfaceHandle handle; final int threadId; void _initialize() { surfaceSetCallbackHandler(handle, SkwasmCallbackHandler.instance.callbackPointer); } Future<RenderResult> renderPictures(List<SkwasmPicture> pictures) => withStackScope((StackScope scope) async { final Pointer<PictureHandle> pictureHandles = scope.allocPointerArray(pictures.length).cast<PictureHandle>(); for (int i = 0; i < pictures.length; i++) { pictureHandles[i] = pictures[i].handle; } final int callbackId = surfaceRenderPictures(handle, pictureHandles, pictures.length); final RasterResult rasterResult = (await SkwasmCallbackHandler.instance.registerCallback(callbackId)) as RasterResult; final RenderResult result = ( imageBitmaps: rasterResult.imageBitmaps.toDart.cast<DomImageBitmap>(), rasterStartMicros: (rasterResult.rasterStartMilliseconds.toDartDouble * 1000).toInt(), rasterEndMicros: (rasterResult.rasterEndMilliseconds.toDartDouble * 1000).toInt(), ); return result; }); Future<ByteData> rasterizeImage(SkwasmImage image, ui.ImageByteFormat format) async { final int callbackId = surfaceRasterizeImage( handle, image.handle, format.index, ); final int context = (await SkwasmCallbackHandler.instance.registerCallback(callbackId) as JSNumber).toDartInt; final SkDataHandle dataHandle = SkDataHandle.fromAddress(context); final int byteCount = skDataGetSize(dataHandle); final Pointer<Uint8> dataPointer = skDataGetConstPointer(dataHandle).cast<Uint8>(); final Uint8List output = Uint8List(byteCount); for (int i = 0; i < byteCount; i++) { output[i] = dataPointer[i]; } skDataDispose(dataHandle); return ByteData.sublistView(output); } void dispose() { surfaceDestroy(handle); } }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/surface.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/surface.dart", "repo_id": "engine", "token_count": 1700 }
271
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; 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 '../util.dart'; import '../view_embedder/style_manager.dart'; import 'canvas_paragraph.dart'; import 'layout_fragmenter.dart'; import 'ruler.dart'; class EngineLineMetrics implements ui.LineMetrics { const EngineLineMetrics({ required this.hardBreak, required this.ascent, required this.descent, required this.unscaledAscent, required this.height, required this.width, required this.left, required this.baseline, required this.lineNumber, }); @override final bool hardBreak; @override final double ascent; @override final double descent; @override final double unscaledAscent; @override final double height; @override final double width; @override final double left; @override final double baseline; @override final int lineNumber; @override int get hashCode => Object.hash( hardBreak, ascent, descent, unscaledAscent, height, width, left, baseline, lineNumber, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is EngineLineMetrics && other.hardBreak == hardBreak && other.ascent == ascent && other.descent == descent && other.unscaledAscent == unscaledAscent && other.height == height && other.width == width && other.left == left && other.baseline == baseline && other.lineNumber == lineNumber; } @override String toString() { String result = super.toString(); assert(() { result = 'LineMetrics(hardBreak: $hardBreak, ' 'ascent: $ascent, ' 'descent: $descent, ' 'unscaledAscent: $unscaledAscent, ' 'height: $height, ' 'width: $width, ' 'left: $left, ' 'baseline: $baseline, ' 'lineNumber: $lineNumber)'; return true; }()); return result; } } class ParagraphLine { ParagraphLine({ required bool hardBreak, required double ascent, required double descent, required double height, required double width, required double left, required double baseline, required int lineNumber, required this.startIndex, required this.endIndex, required this.trailingNewlines, required this.trailingSpaces, required this.spaceCount, required this.widthWithTrailingSpaces, required this.fragments, required this.textDirection, required this.paragraph, this.displayText, }) : assert(trailingNewlines <= endIndex - startIndex), lineMetrics = EngineLineMetrics( hardBreak: hardBreak, ascent: ascent, descent: descent, unscaledAscent: ascent, height: height, width: width, left: left, baseline: baseline, lineNumber: lineNumber, ); /// Metrics for this line of the paragraph. final EngineLineMetrics lineMetrics; /// The index (inclusive) in the text where this line begins. final int startIndex; /// The index (exclusive) in the text where this line ends. /// /// When the line contains an overflow, then [endIndex] goes until the end of /// the text and doesn't stop at the overflow cutoff. final int endIndex; /// The largest visible index (exclusive) in this line. /// /// When the line contains an overflow, or is ellipsized at the end, this is /// the largest index that remains visible in this line. If the entire line is /// ellipsized, this returns [startIndex]; late final int visibleEndIndex = switch (fragments) { [] => startIndex, [...final List<LayoutFragment> rest, EllipsisFragment()] || final List<LayoutFragment> rest => rest.last.end, }; /// The number of new line characters at the end of the line. final int trailingNewlines; /// The number of spaces at the end of the line. final int trailingSpaces; /// The number of space characters in the entire line. final int spaceCount; /// The full width of the line including all trailing space but not new lines. /// /// The difference between [width] and [widthWithTrailingSpaces] is that /// [widthWithTrailingSpaces] includes trailing spaces in the width /// calculation while [width] doesn't. /// /// For alignment purposes for example, the [width] property is the right one /// to use because trailing spaces shouldn't affect the centering of text. /// But for placing cursors in text fields, we do care about trailing /// spaces so [widthWithTrailingSpaces] is more suitable. final double widthWithTrailingSpaces; /// The fragments that make up this line. /// /// The fragments in the [List] are sorted by their logical order in within the /// line. In other words, a [LayoutFragment] in the [List] will have larger /// start and end indices than all [LayoutFragment]s that appear before it. final List<LayoutFragment> fragments; /// The text direction of this line, which is the same as the paragraph's. final ui.TextDirection textDirection; /// The text to be rendered on the screen representing this line. final String? displayText; /// The [CanvasParagraph] this line is part of. final CanvasParagraph paragraph; /// The number of space characters in the line excluding trailing spaces. int get nonTrailingSpaces => spaceCount - trailingSpaces; // Convenient getters for line metrics properties. bool get hardBreak => lineMetrics.hardBreak; double get ascent => lineMetrics.ascent; double get descent => lineMetrics.descent; double get unscaledAscent => lineMetrics.unscaledAscent; double get height => lineMetrics.height; double get width => lineMetrics.width; double get left => lineMetrics.left; double get baseline => lineMetrics.baseline; int get lineNumber => lineMetrics.lineNumber; bool overlapsWith(int startIndex, int endIndex) { return startIndex < this.endIndex && this.startIndex < endIndex; } String getText(CanvasParagraph paragraph) { final StringBuffer buffer = StringBuffer(); for (final LayoutFragment fragment in fragments) { buffer.write(fragment.getText(paragraph)); } return buffer.toString(); } // This is the fallback graphme breaker that is only used if Intl.Segmenter() // is not supported so _fromDomSegmenter can't be called. This implementation // breaks the text into UTF-16 codepoints instead of graphme clusters. List<int> _fallbackGraphemeStartIterable(String lineText) { final List<int> graphemeStarts = <int>[]; bool precededByHighSurrogate = false; for (int i = 0; i < lineText.length; i++) { final int maskedCodeUnit = lineText.codeUnitAt(i) & 0xFC00; // Only skip `i` if it points to a low surrogate in a valid surrogate pair. if (maskedCodeUnit != 0xDC00 || !precededByHighSurrogate) { graphemeStarts.add(startIndex + i); } precededByHighSurrogate = maskedCodeUnit == 0xD800; } return graphemeStarts; } // This will be called at most once to lazily populate _graphemeStarts. List<int> _fromDomSegmenter(String fragmentText) { final DomSegmenter domSegmenter = createIntlSegmenter(granularity: 'grapheme'); final List<int> graphemeStarts = <int>[]; final Iterator<DomSegment> segments = domSegmenter.segment(fragmentText).iterator(); while (segments.moveNext()) { graphemeStarts.add(segments.current.index + startIndex); } assert(graphemeStarts.isEmpty || graphemeStarts.first == startIndex); return graphemeStarts; } List<int> _breakTextIntoGraphemes(String text) { final List<int> graphemeStarts = domIntl.Segmenter == null ? _fallbackGraphemeStartIterable(text) : _fromDomSegmenter(text); // Add the end index of the fragment to the list if the text is not empty. if (graphemeStarts.isNotEmpty) { graphemeStarts.add(visibleEndIndex); } return graphemeStarts; } /// This List contains an ascending sequence of UTF16 offsets that points to /// grapheme starts within the line. Each UTF16 offset is relative to the /// start of the paragraph, instead of the start of the line. /// /// For example, `graphemeStarts[n]` gives the UTF16 offset of the `n`-th /// grapheme in the line. late final List<int> graphemeStarts = visibleEndIndex == startIndex ? const <int>[] : _breakTextIntoGraphemes(paragraph.plainText.substring(startIndex, visibleEndIndex)); /// Translate a UTF16 code unit in the paragaph (`offset`), to a grapheme /// offset with in the current line. /// /// The `start` and `end` parameters are both grapheme offsets within the /// current line. They are used to limit the search range (so the return value /// that corresponds to the code unit `offset` must be with in [start, end)). int graphemeStartIndexBefore(int offset, int start, int end) { int low = start; int high = end; assert(0 <= low); assert(low < high); final List<int> lineGraphemeBreaks = graphemeStarts; assert(offset >= lineGraphemeBreaks[start]); assert(offset < lineGraphemeBreaks.last, '$offset, $lineGraphemeBreaks'); assert(end == lineGraphemeBreaks.length || offset < lineGraphemeBreaks[end]); while (low + 2 <= high) { // high >= low + 2, so low + 1 <= mid <= high - 1 final int mid = (low + high) ~/ 2; switch (lineGraphemeBreaks[mid] - offset) { case > 0: high = mid; case < 0: low = mid; case == 0: return mid; } } assert(lineGraphemeBreaks[low] <= offset); assert(high == lineGraphemeBreaks.length || offset < lineGraphemeBreaks[high]); return low; } /// Returns the UTF-16 range of the character that encloses the code unit at /// the given offset. ui.TextRange? getCharacterRangeAt(int codeUnitOffset) { assert(codeUnitOffset >= this.startIndex); if (codeUnitOffset >= visibleEndIndex || graphemeStarts.isEmpty) { return null; } final int startIndex = graphemeStartIndexBefore(codeUnitOffset, 0, graphemeStarts.length); assert(startIndex < graphemeStarts.length - 1); return ui.TextRange(start: graphemeStarts[startIndex], end: graphemeStarts[startIndex + 1]); } LayoutFragment? closestFragmentTo(LayoutFragment targetFragment, bool searchLeft) { ({LayoutFragment fragment, double distance})? closestFragment; for (final LayoutFragment fragment in fragments) { assert(fragment is! EllipsisFragment); if (fragment.start >= visibleEndIndex) { break; } if (fragment.graphemeStartIndexRange == null) { continue; } final double distance = searchLeft ? targetFragment.left - fragment.right : fragment.left - targetFragment.right; final double? minDistance = closestFragment?.distance; switch (distance) { case > 0.0 when minDistance == null || minDistance > distance: closestFragment = (fragment: fragment, distance: distance); case == 0.0: return fragment; case _: continue; } } return closestFragment?.fragment; } /// Finds the closest [LayoutFragment] to the given horizontal offset `dx` in /// this line, that is not an [EllipsisFragment] and contains at least one /// grapheme start. LayoutFragment? closestFragmentAtOffset(double dx) { if (graphemeStarts.isEmpty) { return null; } assert(graphemeStarts.length >= 2); int graphemeIndex = 0; ({LayoutFragment fragment, double distance})? closestFragment; for (final LayoutFragment fragment in fragments) { assert(fragment is! EllipsisFragment); if (fragment.start >= visibleEndIndex) { break; } if (fragment.length == 0) { continue; } while (fragment.start > graphemeStarts[graphemeIndex]) { graphemeIndex += 1; } final int firstGraphemeStartInFragment = graphemeStarts[graphemeIndex]; if (firstGraphemeStartInFragment >= fragment.end) { continue; } final double distance; if (dx < fragment.left) { distance = fragment.left - dx; } else if (dx > fragment.right) { distance = dx - fragment.right; } else { return fragment; } assert(distance > 0); final double? minDistance = closestFragment?.distance; if (minDistance == null || minDistance > distance) { closestFragment = (fragment: fragment, distance: distance); } } return closestFragment?.fragment; } @override int get hashCode => Object.hash( lineMetrics, startIndex, endIndex, trailingNewlines, trailingSpaces, spaceCount, widthWithTrailingSpaces, fragments, textDirection, displayText, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is ParagraphLine && other.lineMetrics == lineMetrics && other.startIndex == startIndex && other.endIndex == endIndex && other.trailingNewlines == trailingNewlines && other.trailingSpaces == trailingSpaces && other.spaceCount == spaceCount && other.widthWithTrailingSpaces == widthWithTrailingSpaces && other.fragments == fragments && other.textDirection == textDirection && other.displayText == displayText; } @override String toString() { return '$ParagraphLine($startIndex, $endIndex, $lineMetrics)'; } } /// The web implementation of [ui.ParagraphStyle]. class EngineParagraphStyle implements ui.ParagraphStyle { /// Creates a new instance of [EngineParagraphStyle]. EngineParagraphStyle({ this.textAlign, this.textDirection, this.maxLines, this.fontFamily, this.fontSize, this.height, ui.TextHeightBehavior? textHeightBehavior, this.fontWeight, this.fontStyle, ui.StrutStyle? strutStyle, this.ellipsis, this.locale, }) : _textHeightBehavior = textHeightBehavior, // TODO(mdebbar): add support for strut style., b/128317744 _strutStyle = strutStyle as EngineStrutStyle?; final ui.TextAlign? textAlign; final ui.TextDirection? textDirection; final ui.FontWeight? fontWeight; final ui.FontStyle? fontStyle; final int? maxLines; final String? fontFamily; final double? fontSize; final double? height; final ui.TextHeightBehavior? _textHeightBehavior; final EngineStrutStyle? _strutStyle; final String? ellipsis; final ui.Locale? locale; // The effective style attributes should be consistent with paragraph_style.h. ui.TextAlign get effectiveTextAlign => textAlign ?? ui.TextAlign.start; ui.TextDirection get effectiveTextDirection => textDirection ?? ui.TextDirection.ltr; double? get lineHeight { // TODO(mdebbar): Implement proper support for strut styles. // https://github.com/flutter/flutter/issues/32243 final EngineStrutStyle? strutStyle = _strutStyle; final double? strutHeight = strutStyle?._height; if (strutStyle == null || strutHeight == null || strutHeight == 0) { // When there's no strut height, always use paragraph style height. return height; } if (strutStyle._forceStrutHeight ?? false) { // When strut height is forced, ignore paragraph style height. return strutHeight; } // In this case, strut height acts as a minimum height for all parts of the // paragraph. So we take the max of strut height and paragraph style height. return math.max(strutHeight, height ?? 0.0); } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is EngineParagraphStyle && other.textAlign == textAlign && other.textDirection == textDirection && other.fontWeight == fontWeight && other.fontStyle == fontStyle && other.maxLines == maxLines && other.fontFamily == fontFamily && other.fontSize == fontSize && other.height == height && other._textHeightBehavior == _textHeightBehavior && other._strutStyle == _strutStyle && other.ellipsis == ellipsis && other.locale == locale; } @override int get hashCode { return Object.hash( textAlign, textDirection, fontWeight, fontStyle, maxLines, fontFamily, fontSize, height, _textHeightBehavior, _strutStyle, ellipsis, locale, ); } @override String toString() { String result = super.toString(); assert(() { final double? fontSize = this.fontSize; final double? height = this.height; result = 'ParagraphStyle(' 'textAlign: ${textAlign ?? "unspecified"}, ' 'textDirection: ${textDirection ?? "unspecified"}, ' 'fontWeight: ${fontWeight ?? "unspecified"}, ' 'fontStyle: ${fontStyle ?? "unspecified"}, ' 'maxLines: ${maxLines ?? "unspecified"}, ' 'textHeightBehavior: ${_textHeightBehavior ?? "unspecified"}, ' 'fontFamily: ${fontFamily ?? "unspecified"}, ' 'fontSize: ${fontSize != null ? fontSize.toStringAsFixed(1) : "unspecified"}, ' 'height: ${height != null ? "${height.toStringAsFixed(1)}x" : "unspecified"}, ' 'strutStyle: ${_strutStyle ?? "unspecified"}, ' 'ellipsis: ${ellipsis != null ? '"$ellipsis"' : "unspecified"}, ' 'locale: ${locale ?? "unspecified"}' ')'; return true; }()); return result; } } /// The web implementation of [ui.TextStyle]. class EngineTextStyle implements ui.TextStyle { /// Constructs an [EngineTextStyle] with all properties being required. /// /// This is good for call sites that need to be updated whenever a new /// property is added to [EngineTextStyle]. Non-updated call sites will fail /// the build otherwise. factory EngineTextStyle({ required ui.Color? color, required ui.TextDecoration? decoration, required ui.Color? decorationColor, required ui.TextDecorationStyle? decorationStyle, required double? decorationThickness, required ui.FontWeight? fontWeight, required ui.FontStyle? fontStyle, required ui.TextBaseline? textBaseline, required String? fontFamily, required List<String>? fontFamilyFallback, required double? fontSize, required double? letterSpacing, required double? wordSpacing, required double? height, required ui.TextLeadingDistribution? leadingDistribution, required ui.Locale? locale, required ui.Paint? background, required ui.Paint? foreground, required List<ui.Shadow>? shadows, required List<ui.FontFeature>? fontFeatures, required List<ui.FontVariation>? fontVariations, }) = EngineTextStyle.only; /// Constructs an [EngineTextStyle] with only the given properties. /// /// This constructor should be used sparingly in tests, for example. Or when /// we know for sure that not all properties are needed. EngineTextStyle.only({ this.color, this.decoration, this.decorationColor, this.decorationStyle, this.decorationThickness, this.fontWeight, this.fontStyle, this.textBaseline, String? fontFamily, this.fontFamilyFallback, this.fontSize, this.letterSpacing, this.wordSpacing, this.height, this.leadingDistribution, this.locale, this.background, this.foreground, this.shadows, this.fontFeatures, this.fontVariations, }) : assert( color == null || foreground == null, 'Cannot provide both a color and a foreground\n' 'The color argument is just a shorthand for "foreground: Paint()..color = color".'), isFontFamilyProvided = fontFamily != null, fontFamily = fontFamily ?? ''; /// Constructs an [EngineTextStyle] by reading properties from an /// [EngineParagraphStyle]. factory EngineTextStyle.fromParagraphStyle( EngineParagraphStyle paragraphStyle, ) { return EngineTextStyle.only( fontWeight: paragraphStyle.fontWeight, fontStyle: paragraphStyle.fontStyle, fontFamily: paragraphStyle.fontFamily, fontSize: paragraphStyle.fontSize, height: paragraphStyle.height, locale: paragraphStyle.locale, ); } final ui.Color? color; final ui.TextDecoration? decoration; final ui.Color? decorationColor; final ui.TextDecorationStyle? decorationStyle; final double? decorationThickness; final ui.FontWeight? fontWeight; final ui.FontStyle? fontStyle; final ui.TextBaseline? textBaseline; final bool isFontFamilyProvided; final String fontFamily; final List<String>? fontFamilyFallback; final List<ui.FontFeature>? fontFeatures; final List<ui.FontVariation>? fontVariations; final double? fontSize; final double? letterSpacing; final double? wordSpacing; final double? height; final ui.TextLeadingDistribution? leadingDistribution; final ui.Locale? locale; final ui.Paint? background; final ui.Paint? foreground; final List<ui.Shadow>? shadows; static final List<String> _testFonts = <String>['FlutterTest', 'Ahem']; String get effectiveFontFamily { final String fontFamily = this.fontFamily.isEmpty ? StyleManager.defaultFontFamily : this.fontFamily; // In the flutter tester environment, we use predictable-size test fonts. // This makes widget tests predictable and less flaky. String result = fontFamily; assert(() { if (ui_web.debugEmulateFlutterTesterEnvironment && !_testFonts.contains(fontFamily)) { result = _testFonts.first; } return true; }()); return result; } String? _cssFontString; /// Font string to be used in CSS. /// /// See <https://developer.mozilla.org/en-US/docs/Web/CSS/font>. String get cssFontString { return _cssFontString ??= buildCssFontString( fontStyle: fontStyle, fontWeight: fontWeight, fontSize: fontSize, fontFamily: effectiveFontFamily, ); } late final TextHeightStyle heightStyle = _createHeightStyle(); TextHeightStyle _createHeightStyle() { return TextHeightStyle( fontFamily: effectiveFontFamily, fontSize: fontSize ?? StyleManager.defaultFontSize, height: height, // TODO(mdebbar): Pass the actual value when font features become supported // https://github.com/flutter/flutter/issues/64595 fontFeatures: null, fontVariations: null, ); } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is EngineTextStyle && other.color == color && other.decoration == decoration && other.decorationColor == decorationColor && other.decorationStyle == decorationStyle && other.fontWeight == fontWeight && other.fontStyle == fontStyle && other.textBaseline == textBaseline && other.leadingDistribution == leadingDistribution && other.fontFamily == fontFamily && other.fontSize == fontSize && other.letterSpacing == letterSpacing && other.wordSpacing == wordSpacing && other.height == height && other.decorationThickness == decorationThickness && other.locale == locale && other.background == background && other.foreground == foreground && listEquals<ui.Shadow>(other.shadows, shadows) && listEquals<String>(other.fontFamilyFallback, fontFamilyFallback) && listEquals<ui.FontFeature>(other.fontFeatures, fontFeatures) && listEquals<ui.FontVariation>(other.fontVariations, fontVariations); } @override int get hashCode { final List<ui.Shadow>? shadows = this.shadows; final List<ui.FontFeature>? fontFeatures = this.fontFeatures; final List<ui.FontVariation>? fontVariations = this.fontVariations; final List<String>? fontFamilyFallback = this.fontFamilyFallback; return Object.hash( color, decoration, decorationColor, decorationStyle, fontWeight, fontStyle, textBaseline, leadingDistribution, fontFamily, fontFamilyFallback == null ? null : Object.hashAll(fontFamilyFallback), fontSize, letterSpacing, wordSpacing, height, locale, background, foreground, shadows == null ? null : Object.hashAll(shadows), decorationThickness, // Object.hash goes up to 20 arguments, but we have 21 Object.hash( fontFeatures == null ? null : Object.hashAll(fontFeatures), fontVariations == null ? null : Object.hashAll(fontVariations), ) ); } @override String toString() { String result = super.toString(); assert(() { final List<String>? fontFamilyFallback = this.fontFamilyFallback; final double? fontSize = this.fontSize; final double? height = this.height; result = 'TextStyle(' 'color: ${color ?? "unspecified"}, ' 'decoration: ${decoration ?? "unspecified"}, ' 'decorationColor: ${decorationColor ?? "unspecified"}, ' 'decorationStyle: ${decorationStyle ?? "unspecified"}, ' 'decorationThickness: ${decorationThickness ?? "unspecified"}, ' 'fontWeight: ${fontWeight ?? "unspecified"}, ' 'fontStyle: ${fontStyle ?? "unspecified"}, ' 'textBaseline: ${textBaseline ?? "unspecified"}, ' 'fontFamily: ${isFontFamilyProvided && fontFamily != '' ? fontFamily : "unspecified"}, ' 'fontFamilyFallback: ${isFontFamilyProvided && fontFamilyFallback != null && fontFamilyFallback.isNotEmpty ? fontFamilyFallback : "unspecified"}, ' 'fontSize: ${fontSize != null ? fontSize.toStringAsFixed(1) : "unspecified"}, ' 'letterSpacing: ${letterSpacing != null ? "${letterSpacing}x" : "unspecified"}, ' 'wordSpacing: ${wordSpacing != null ? "${wordSpacing}x" : "unspecified"}, ' 'height: ${height != null ? "${height.toStringAsFixed(1)}x" : "unspecified"}, ' 'leadingDistribution: ${leadingDistribution ?? "unspecified"}, ' 'locale: ${locale ?? "unspecified"}, ' 'background: ${background ?? "unspecified"}, ' 'foreground: ${foreground ?? "unspecified"}, ' 'shadows: ${shadows ?? "unspecified"}, ' 'fontFeatures: ${fontFeatures ?? "unspecified"}, ' 'fontVariations: ${fontVariations ?? "unspecified"}' ')'; return true; }()); return result; } } /// The web implementation of [ui.StrutStyle]. class EngineStrutStyle implements ui.StrutStyle { EngineStrutStyle({ String? fontFamily, List<String>? fontFamilyFallback, double? fontSize, double? height, ui.TextLeadingDistribution? leadingDistribution, double? leading, ui.FontWeight? fontWeight, ui.FontStyle? fontStyle, bool? forceStrutHeight, }) : _fontFamily = fontFamily, _fontFamilyFallback = fontFamilyFallback, _fontSize = fontSize, _height = height, _leadingDistribution = leadingDistribution, _leading = leading, _fontWeight = fontWeight, _fontStyle = fontStyle, _forceStrutHeight = forceStrutHeight; final String? _fontFamily; final List<String>? _fontFamilyFallback; final double? _fontSize; final double? _height; final double? _leading; final ui.FontWeight? _fontWeight; final ui.FontStyle? _fontStyle; final bool? _forceStrutHeight; final ui.TextLeadingDistribution? _leadingDistribution; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is EngineStrutStyle && other._fontFamily == _fontFamily && other._fontSize == _fontSize && other._height == _height && other._leading == _leading && other._leadingDistribution == _leadingDistribution && other._fontWeight == _fontWeight && other._fontStyle == _fontStyle && other._forceStrutHeight == _forceStrutHeight && listEquals<String>(other._fontFamilyFallback, _fontFamilyFallback); } @override int get hashCode { final List<String>? fontFamilyFallback = _fontFamilyFallback; return Object.hash( _fontFamily, fontFamilyFallback != null ? Object.hashAll(fontFamilyFallback) : null, _fontSize, _height, _leading, _leadingDistribution, _fontWeight, _fontStyle, _forceStrutHeight, ); } } /// Holds information for a placeholder in a paragraph. /// /// [width], [height] and [baselineOffset] are expected to be already scaled. class ParagraphPlaceholder { ParagraphPlaceholder( this.width, this.height, this.alignment, { required this.baselineOffset, required this.baseline, }); /// The scaled width of the placeholder. final double width; /// The scaled height of the placeholder. final double height; /// Specifies how the placeholder rectangle will be vertically aligned with /// the surrounding text. final ui.PlaceholderAlignment alignment; /// When the [alignment] value is [ui.PlaceholderAlignment.baseline], the /// [baselineOffset] indicates the distance from the baseline to the top of /// the placeholder rectangle. final double baselineOffset; /// Dictates whether to use alphabetic or ideographic baseline. final ui.TextBaseline baseline; } extension FontStyleExtension on ui.FontStyle { /// Converts a [ui.FontStyle] value to its CSS equivalent. String toCssString() { return this == ui.FontStyle.normal ? 'normal' : 'italic'; } } extension FontWeightExtension on ui.FontWeight { /// Converts a [ui.FontWeight] value to its CSS equivalent. String toCssString() { return fontWeightIndexToCss(fontWeightIndex: index); } } String fontWeightIndexToCss({int fontWeightIndex = 3}) { switch (fontWeightIndex) { case 0: return '100'; case 1: return '200'; case 2: return '300'; case 3: return 'normal'; case 4: return '500'; case 5: return '600'; case 6: return 'bold'; case 7: return '800'; case 8: return '900'; } assert(() { throw AssertionError( 'Failed to convert font weight $fontWeightIndex to CSS.', ); }()); return ''; } /// Applies a text [style] to an [element], translating the properties to their /// corresponding CSS equivalents. void applyTextStyleToElement({ required DomElement element, required EngineTextStyle style, }) { bool updateDecoration = false; final DomCSSStyleDeclaration cssStyle = element.style; final ui.Color? color = style.foreground?.color ?? style.color; if (style.foreground?.style == ui.PaintingStyle.stroke) { // When comparing the outputs of the Bitmap Canvas and the DOM // implementation, we have found, that we need to set the background color // of the text to transparent to achieve the same effect as in the Bitmap // Canvas and the Skia Engine where only the text stroke is painted. // If we don't set it here to transparent, the text will inherit the color // of it's parent element. cssStyle.color = 'transparent'; // Use hairline (device pixel when strokeWidth is not specified). final double? strokeWidth = style.foreground?.strokeWidth; final double adaptedWidth = strokeWidth != null && strokeWidth > 0 ? strokeWidth : 1.0 / ui.window.devicePixelRatio; cssStyle.textStroke = '${adaptedWidth}px ${color?.toCssString()}'; } else if (color != null) { cssStyle.color = color.toCssString(); } final ui.Color? background = style.background?.color; if (background != null) { cssStyle.backgroundColor = background.toCssString(); } final double? fontSize = style.fontSize; if (fontSize != null) { cssStyle.fontSize = '${fontSize.floor()}px'; } if (style.fontWeight != null) { cssStyle.fontWeight = style.fontWeight!.toCssString(); } if (style.fontStyle != null) { cssStyle.fontStyle = style.fontStyle!.toCssString(); } // For test environment use effectiveFontFamily since we need to // consistently use the correct test font. if (ui_web.debugEmulateFlutterTesterEnvironment) { cssStyle.fontFamily = canonicalizeFontFamily(style.effectiveFontFamily)!; } else { cssStyle.fontFamily = canonicalizeFontFamily(style.fontFamily)!; } if (style.letterSpacing != null) { cssStyle.letterSpacing = '${style.letterSpacing}px'; } if (style.wordSpacing != null) { cssStyle.wordSpacing = '${style.wordSpacing}px'; } if (style.decoration != null) { updateDecoration = true; } final List<ui.Shadow>? shadows = style.shadows; if (shadows != null) { cssStyle.textShadow = _shadowListToCss(shadows); } if (updateDecoration) { if (style.decoration != null) { final String? textDecoration = _textDecorationToCssString(style.decoration, style.decorationStyle); if (textDecoration != null) { if (browserEngine == BrowserEngine.webkit) { setElementStyle(element, '-webkit-text-decoration', textDecoration); } else { cssStyle.textDecoration = textDecoration; } final ui.Color? decorationColor = style.decorationColor; if (decorationColor != null) { cssStyle.textDecorationColor = decorationColor.toCssString(); } } } } final List<ui.FontFeature>? fontFeatures = style.fontFeatures; if (fontFeatures != null && fontFeatures.isNotEmpty) { cssStyle.fontFeatureSettings = _fontFeatureListToCss(fontFeatures); } final List<ui.FontVariation>? fontVariations = style.fontVariations; if (fontVariations != null && fontVariations.isNotEmpty) { cssStyle.setProperty( 'font-variation-settings', _fontVariationListToCss(fontVariations)); } } String _shadowListToCss(List<ui.Shadow> shadows) { if (shadows.isEmpty) { return ''; } // CSS text-shadow is a comma separated list of shadows. // <offsetx> <offsety> <blur-radius> <color>. // Shadows are applied front-to-back with first shadow on top. // Color is optional. offsetx,y are required. blur-radius is optional as well // and defaults to 0. final StringBuffer sb = StringBuffer(); final int len = shadows.length; for (int i = 0; i < len; i++) { if (i != 0) { sb.write(','); } final ui.Shadow shadow = shadows[i]; sb.write('${shadow.offset.dx}px ${shadow.offset.dy}px ' '${shadow.blurRadius}px ${shadow.color.toCssString()}'); } return sb.toString(); } String _fontFeatureListToCss(List<ui.FontFeature> fontFeatures) { assert(fontFeatures.isNotEmpty); // For more details, see: // * https://developer.mozilla.org/en-US/docs/Web/CSS/font-feature-settings final StringBuffer sb = StringBuffer(); final int len = fontFeatures.length; for (int i = 0; i < len; i++) { if (i != 0) { sb.write(','); } final ui.FontFeature fontFeature = fontFeatures[i]; sb.write('"${fontFeature.feature}" ${fontFeature.value}'); } return sb.toString(); } String _fontVariationListToCss(List<ui.FontVariation> fontVariations) { assert(fontVariations.isNotEmpty); final StringBuffer sb = StringBuffer(); final int len = fontVariations.length; for (int i = 0; i < len; i++) { if (i != 0) { sb.write(','); } final ui.FontVariation fontVariation = fontVariations[i]; sb.write('"${fontVariation.axis}" ${fontVariation.value}'); } return sb.toString(); } /// Converts text decoration style to CSS text-decoration-style value. String? _textDecorationToCssString( ui.TextDecoration? decoration, ui.TextDecorationStyle? decorationStyle) { final StringBuffer decorations = StringBuffer(); if (decoration != null) { if (decoration.contains(ui.TextDecoration.underline)) { decorations.write('underline '); } if (decoration.contains(ui.TextDecoration.overline)) { decorations.write('overline '); } if (decoration.contains(ui.TextDecoration.lineThrough)) { decorations.write('line-through '); } } if (decorationStyle != null) { decorations.write(_decorationStyleToCssString(decorationStyle)); } return decorations.isEmpty ? null : decorations.toString(); } String? _decorationStyleToCssString(ui.TextDecorationStyle decorationStyle) { switch (decorationStyle) { case ui.TextDecorationStyle.dashed: return 'dashed'; case ui.TextDecorationStyle.dotted: return 'dotted'; case ui.TextDecorationStyle.double: return 'double'; case ui.TextDecorationStyle.solid: return 'solid'; case ui.TextDecorationStyle.wavy: return 'wavy'; default: return null; } } /// Converts [align] to its corresponding CSS value. /// /// This value is used as the "text-align" CSS property, e.g.: /// /// ```css /// text-align: right; /// ``` String textAlignToCssValue( ui.TextAlign? align, ui.TextDirection textDirection) { switch (align) { case ui.TextAlign.left: return 'left'; case ui.TextAlign.right: return 'right'; case ui.TextAlign.center: return 'center'; case ui.TextAlign.justify: return 'justify'; case ui.TextAlign.end: switch (textDirection) { case ui.TextDirection.ltr: return 'end'; case ui.TextDirection.rtl: return 'left'; } case ui.TextAlign.start: switch (textDirection) { case ui.TextDirection.ltr: return ''; // it's the default case ui.TextDirection.rtl: return 'right'; } case null: // If align is not specified return default. return ''; } }
engine/lib/web_ui/lib/src/engine/text/paragraph.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/text/paragraph.dart", "repo_id": "engine", "token_count": 13996 }
272
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:meta/meta.dart'; import 'package:ui/src/engine/dom.dart'; import 'package:ui/src/engine/view_embedder/display_dpr_stream.dart'; import 'package:ui/src/engine/window.dart'; import 'package:ui/ui.dart' as ui show Size; import 'custom_element_dimensions_provider.dart'; import 'full_page_dimensions_provider.dart'; /// This class provides the dimensions of the "viewport" in which the app is rendered. /// /// Similarly to the `EmbeddingStrategy`, this class is specialized to handle /// different sources of information: /// /// * [FullPageDimensionsProvider] - The default behavior, uses the VisualViewport /// API to measure, and react to, the dimensions of the full browser window. /// * [CustomElementDimensionsProvider] - Uses a custom html Element as the source /// of dimensions, and the ResizeObserver to notify the app of 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. abstract class DimensionsProvider { DimensionsProvider(); /// Creates the appropriate DimensionsProvider depending on the incoming [hostElement]. factory DimensionsProvider.create({DomElement? hostElement}) { if (hostElement != null) { return CustomElementDimensionsProvider( hostElement, onDprChange: DisplayDprStream.instance.dprChanged, ); } else { return FullPageDimensionsProvider(); } } /// Returns the [ui.Size] of the "viewport". /// /// This function is expensive. It triggers browser layout if there are /// pending DOM writes. ui.Size computePhysicalSize(); /// Returns the [ViewPadding] of the keyboard insets (if present). ViewPadding computeKeyboardInsets( double physicalHeight, bool isEditingOnMobile, ); /// Returns a Stream with the changes to [ui.Size] (when cheap to get). /// /// Currently this Stream always returns `null` measurements because the /// resize event that we use for [FullPageDimensionsProvider] does not contain /// the new size, so users of this Stream everywhere immediately retrieve the /// new `physicalSize` from the window. /// /// The [CustomElementDimensionsProvider] *could* broadcast the new size, but /// to keep both implementations consistent (and their consumers), for now all /// events from this Stream are going to be `null` (until we find a performant /// way to retrieve the dimensions in full-page mode). Stream<ui.Size?> get onResize; /// Whether the [DimensionsProvider] instance has been closed or not. @visibleForTesting bool isClosed = false; /// Clears any resources grabbed by the DimensionsProvider instance. /// /// All internal event handlers will be disconnected, and the [onResize] Stream /// will be closed. @mustCallSuper void close() { isClosed = true; } }
engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/dimensions_provider.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/dimensions_provider.dart", "repo_id": "engine", "token_count": 860 }
273
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:typed_data'; import 'package:ui/src/engine.dart'; /// Provides the [AssetManager] used by the Flutter Engine. AssetManager get assetManager => engineAssetManager; /// This class downloads assets over the network. /// /// Assets are resolved relative to [assetsDir] inside the absolute base /// specified by [assetBase] (optional). /// /// By default, URLs are relative to the `<base>` of the current website. class AssetManager { /// Initializes [AssetManager] with paths. AssetManager({ this.assetsDir = _defaultAssetsDir, String? assetBase, }) : assert( assetBase == null || assetBase.endsWith('/'), '`assetBase` must end with a `/` character.', ), _assetBase = assetBase; static const String _defaultAssetsDir = 'assets'; /// The directory containing the assets. final String assetsDir; /// The absolute base URL for assets. String? _assetBase; // Cache a value for `_assetBase` so we don't hit the DOM multiple times. String get _baseUrl => _assetBase ??= _deprecatedAssetBase ?? ''; // Retrieves the `assetBase` value from the DOM. // // This warns the user and points them to the new initializeEngine style. String? get _deprecatedAssetBase { final DomHTMLMetaElement? meta = domWindow.document .querySelector('meta[name=assetBase]') as DomHTMLMetaElement?; final String? fallbackBaseUrl = meta?.content; if (fallbackBaseUrl != null) { // Warn users that they're using a deprecated configuration style... domWindow.console.warn('The `assetBase` meta tag is now deprecated.\n' 'Use engineInitializer.initializeEngine(config) instead.\n' 'See: https://docs.flutter.dev/development/platform-integration/web/initialization'); } return fallbackBaseUrl; } /// Returns the URL to load the asset from, given the asset key. /// /// We URL-encode the asset URL in order to correctly issue the right /// HTTP request to the server. /// /// For example, if you have an asset in the file "assets/hello world.png", /// two things will happen. When the app is built, the asset will be copied /// to an asset directory with the file name URL-encoded. So our asset will /// be copied to something like "assets/hello%20world.png". To account for /// the assets being copied over with a URL-encoded name, the Flutter /// framework URL-encodes the asset key so when it sends a request to the /// engine to load "assets/hello world.png", it actually sends a request to /// load "assets/hello%20world.png". However, on the web, if we try to load /// "assets/hello%20world.png", the request will be URL-decoded, we will /// request "assets/hello world.png", and the request will 404. Therefore, we /// must URL-encode the asset key *again* so when it is decoded, it is /// requesting the once-URL-encoded asset key. String getAssetUrl(String asset) { if (Uri.parse(asset).hasScheme) { return Uri.encodeFull(asset); } return Uri.encodeFull('$_baseUrl$assetsDir/$asset'); } /// Loads an asset and returns the server response. Future<Object> loadAsset(String asset) { return httpFetch(getAssetUrl(asset)); } /// Loads an asset using an [XMLHttpRequest] and returns data as [ByteData]. Future<ByteData> load(String asset) async { final String url = getAssetUrl(asset); final HttpFetchResponse response = await httpFetch(url); if (response.status == 404 && asset == 'AssetManifest.json') { printWarning('Asset manifest does not exist at `$url` - ignoring.'); return ByteData.sublistView(utf8.encode('{}')); } return (await response.payload.asByteBuffer()).asByteData(); } }
engine/lib/web_ui/lib/ui_web/src/ui_web/asset_manager.dart/0
{ "file_path": "engine/lib/web_ui/lib/ui_web/src/ui_web/asset_manager.dart", "repo_id": "engine", "token_count": 1227 }
274
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "../export.h" #include "../wrappers.h" #include "third_party/skia/modules/skparagraph/include/ParagraphBuilder.h" using namespace skia::textlayout; using namespace Skwasm; SKWASM_EXPORT ParagraphBuilder* paragraphBuilder_create( ParagraphStyle* style, FlutterFontCollection* collection) { return ParagraphBuilder::make(*style, collection->collection).release(); } SKWASM_EXPORT void paragraphBuilder_dispose(ParagraphBuilder* builder) { delete builder; } SKWASM_EXPORT void paragraphBuilder_addPlaceholder( ParagraphBuilder* builder, SkScalar width, SkScalar height, PlaceholderAlignment alignment, SkScalar baselineOffset, TextBaseline baseline) { builder->addPlaceholder( PlaceholderStyle(width, height, alignment, baseline, baselineOffset)); } SKWASM_EXPORT void paragraphBuilder_addText(ParagraphBuilder* builder, std::u16string* text) { builder->addText(*text); } SKWASM_EXPORT char* paragraphBuilder_getUtf8Text(ParagraphBuilder* builder, uint32_t* outLength) { auto span = builder->getText(); *outLength = span.size(); return span.data(); } SKWASM_EXPORT void paragraphBuilder_pushStyle(ParagraphBuilder* builder, TextStyle* style) { builder->pushStyle(*style); } SKWASM_EXPORT void paragraphBuilder_pop(ParagraphBuilder* builder) { builder->pop(); } SKWASM_EXPORT Paragraph* paragraphBuilder_build(ParagraphBuilder* builder) { return builder->Build().release(); } SKWASM_EXPORT std::vector<SkUnicode::Position>* unicodePositionBuffer_create( size_t length) { return new std::vector<SkUnicode::Position>(length); } SKWASM_EXPORT SkUnicode::Position* unicodePositionBuffer_getDataPointer( std::vector<SkUnicode::Position>* buffer) { return buffer->data(); } SKWASM_EXPORT void unicodePositionBuffer_free( std::vector<SkUnicode::Position>* buffer) { delete buffer; } SKWASM_EXPORT std::vector<SkUnicode::LineBreakBefore>* lineBreakBuffer_create( size_t length) { return new std::vector<SkUnicode::LineBreakBefore>( length, {0, SkUnicode::LineBreakType::kSoftLineBreak}); } SKWASM_EXPORT SkUnicode::LineBreakBefore* lineBreakBuffer_getDataPointer( std::vector<SkUnicode::LineBreakBefore>* buffer) { return buffer->data(); } SKWASM_EXPORT void lineBreakBuffer_free( std::vector<SkUnicode::LineBreakBefore>* buffer) { delete buffer; } SKWASM_EXPORT void paragraphBuilder_setGraphemeBreaksUtf16( ParagraphBuilder* builder, std::vector<SkUnicode::Position>* breaks) { builder->setGraphemeBreaksUtf16(std::move(*breaks)); } SKWASM_EXPORT void paragraphBuilder_setWordBreaksUtf16( ParagraphBuilder* builder, std::vector<SkUnicode::Position>* breaks) { builder->setWordsUtf16(std::move(*breaks)); } SKWASM_EXPORT void paragraphBuilder_setLineBreaksUtf16( ParagraphBuilder* builder, std::vector<SkUnicode::LineBreakBefore>* breaks) { builder->setLineBreaksUtf16(std::move(*breaks)); }
engine/lib/web_ui/skwasm/text/paragraph_builder.cpp/0
{ "file_path": "engine/lib/web_ui/skwasm/text/paragraph_builder.cpp", "repo_id": "engine", "token_count": 1203 }
275
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { List<CkColorFilter> createColorFilters() { return <CkColorFilter>[ createCkColorFilter(const EngineColorFilter.mode(ui.Color(0x12345678), ui.BlendMode.srcOver))!, createCkColorFilter(const EngineColorFilter.mode(ui.Color(0x12345678), ui.BlendMode.dstOver))!, createCkColorFilter(const EngineColorFilter.mode(ui.Color(0x87654321), ui.BlendMode.dstOver))!, createCkColorFilter(const EngineColorFilter.matrix(<double>[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, ]))!, createCkColorFilter(EngineColorFilter.matrix(Float32List.fromList(<double>[ 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, ])))!, createCkColorFilter(const EngineColorFilter.linearToSrgbGamma())!, createCkColorFilter(const EngineColorFilter.srgbToLinearGamma())!, ]; } List<CkImageFilter> createImageFilters() { final List<CkImageFilter> filters = <CkImageFilter>[ CkImageFilter.blur(sigmaX: 5, sigmaY: 6, tileMode: ui.TileMode.clamp), CkImageFilter.blur(sigmaX: 6, sigmaY: 5, tileMode: ui.TileMode.clamp), CkImageFilter.blur(sigmaX: 6, sigmaY: 5, tileMode: ui.TileMode.decal), for (final CkColorFilter colorFilter in createColorFilters()) CkImageFilter.color(colorFilter: colorFilter), ]; filters.add(CkImageFilter.compose(outer: filters[0], inner: filters[1])); filters.add(CkImageFilter.compose(outer: filters[1], inner: filters[3])); return filters; } setUpCanvasKitTest(withImplicitView: true); group('ImageFilters', () { test('can be constructed', () { final CkImageFilter imageFilter = CkImageFilter.blur(sigmaX: 5, sigmaY: 10, tileMode: ui.TileMode.clamp); expect(imageFilter, isA<CkImageFilter>()); SkImageFilter? skFilter; imageFilter.imageFilter((SkImageFilter value) { skFilter = value; }); expect(skFilter, isNotNull); }); test('== operator', () { final List<ui.ImageFilter> filters1 = <ui.ImageFilter>[ ...createImageFilters(), ...createColorFilters(), ]; final List<ui.ImageFilter> filters2 = <ui.ImageFilter>[ ...createImageFilters(), ...createColorFilters(), ]; for (int index1 = 0; index1 < filters1.length; index1 += 1) { final ui.ImageFilter imageFilter1 = filters1[index1]; expect(imageFilter1 == imageFilter1, isTrue); for (int index2 = 0; index2 < filters2.length; index2 += 1) { final ui.ImageFilter imageFilter2 = filters2[index2]; expect(imageFilter1 == imageFilter2, imageFilter2 == imageFilter1); expect(imageFilter1 == imageFilter2, index1 == index2); } } }); test('reuses the Skia filter', () { final CkPaint paint = CkPaint(); paint.imageFilter = CkImageFilter.blur(sigmaX: 5, sigmaY: 10, tileMode: ui.TileMode.clamp); final CkManagedSkImageFilterConvertible managedFilter1 = paint.imageFilter! as CkManagedSkImageFilterConvertible; paint.imageFilter = CkImageFilter.blur(sigmaX: 5, sigmaY: 10, tileMode: ui.TileMode.clamp); final CkManagedSkImageFilterConvertible managedFilter2 = paint.imageFilter! as CkManagedSkImageFilterConvertible; expect(managedFilter1, same(managedFilter2)); }); test('does not throw for both sigmaX and sigmaY set to 0', () async { final CkImageFilter imageFilter = CkImageFilter.blur(sigmaX: 0, sigmaY: 0, tileMode: ui.TileMode.clamp); expect(imageFilter, isNotNull); const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 250); final LayerSceneBuilder builder = LayerSceneBuilder(); builder.pushOffset(0,0); final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); canvas.drawCircle( const ui.Offset(75, 125), 50, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0), ); final CkPicture redCircle1 = recorder.endRecording(); builder.addPicture(ui.Offset.zero, redCircle1); builder.pushImageFilter(imageFilter); // Draw another red circle and apply it to the scene. // This one should also be red with the image filter doing nothing final CkPictureRecorder recorder2 = CkPictureRecorder(); final CkCanvas canvas2 = recorder2.beginRecording(region); canvas2.drawCircle( const ui.Offset(425, 125), 50, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0), ); final CkPicture redCircle2 = recorder2.endRecording(); builder.addPicture(ui.Offset.zero, redCircle2); await matchSceneGolden('canvaskit_zero_sigma_blur.png', builder.build(), region: region); }); test('using a colorFilter', () async { final CkColorFilter colorFilter = createCkColorFilter( const EngineColorFilter.mode( ui.Color.fromARGB(255, 0, 255, 0), ui.BlendMode.srcIn ))!; const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 250); final LayerSceneBuilder builder = LayerSceneBuilder(); builder.pushOffset(0,0); builder.pushImageFilter(colorFilter); final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); canvas.drawCircle( const ui.Offset(75, 125), 50, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0), ); final CkPicture redCircle1 = recorder.endRecording(); builder.addPicture(ui.Offset.zero, redCircle1); // The drawn red circle should actually be green with the colorFilter. await matchSceneGolden( 'canvaskit_imageFilter_using_colorFilter.png', builder.build(), region: region); }); test('using a compose filter', () async { final CkImageFilter blurFilter = CkImageFilter.blur( sigmaX: 5, sigmaY: 5, tileMode: ui.TileMode.clamp, ); final CkColorFilter colorFilter = createCkColorFilter( const EngineColorFilter.mode( ui.Color.fromARGB(255, 0, 255, 0), ui.BlendMode.srcIn))!; final CkImageFilter colorImageFilter = CkImageFilter.color(colorFilter: colorFilter); final CkImageFilter composeFilter = CkImageFilter.compose(outer: blurFilter, inner: colorImageFilter); const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 250); final LayerSceneBuilder builder = LayerSceneBuilder(); builder.pushOffset(0, 0); builder.pushImageFilter(composeFilter); final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); canvas.drawCircle( const ui.Offset(75, 125), 50, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0), ); final CkPicture redCircle1 = recorder.endRecording(); builder.addPicture(ui.Offset.zero, redCircle1); // The drawn red circle should actually be green and blurred. await matchSceneGolden( 'canvaskit_composeImageFilter.png', builder.build(), region: region); }); }); group('MaskFilter', () { test('with 0 sigma can be set on a Paint', () { final ui.Paint paint = ui.Paint(); const ui.MaskFilter filter = ui.MaskFilter.blur(ui.BlurStyle.normal, 0); expect(() => paint.maskFilter = filter, isNot(throwsException)); }); }); }
engine/lib/web_ui/test/canvaskit/filter_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/filter_test.dart", "repo_id": "engine", "token_count": 3269 }
276
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import '../common/matchers.dart'; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('CkPicture', () { setUpCanvasKitTest(); group('lifecycle', () { test('can be disposed of manually', () { final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawPaint(ui.Paint()); final CkPicture picture = recorder.endRecording() as CkPicture; expect(picture.skiaObject, isNotNull); expect(picture.debugDisposed, isFalse); picture.debugCheckNotDisposed('Test.'); // must not throw picture.dispose(); expect(() => picture.skiaObject, throwsA(isAssertionError)); expect(picture.debugDisposed, isTrue); StateError? actualError; try { picture.debugCheckNotDisposed('Test.'); } on StateError catch (error) { actualError = error; } expect(actualError, isNotNull); // TODO(yjbanov): cannot test precise message due to https://github.com/flutter/flutter/issues/96298 expect( '$actualError', startsWith('Bad state: Test.\n' 'The picture has been disposed. ' 'When the picture was disposed the stack trace was:\n')); }); }); test('toImageSync', () async { const ui.Color color = ui.Color(0xFFAAAAAA); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawPaint(ui.Paint()..color = color); final ui.Picture picture = recorder.endRecording(); final ui.Image image = picture.toImageSync(10, 15); expect(image.width, 10); expect(image.height, 15); final ByteData? data = await image.toByteData(); expect(data, isNotNull); expect(data!.lengthInBytes, 10 * 15 * 4); expect(data.buffer.asUint32List().first, color.value); }); test('cullRect bounds are tight', () async { const ui.Color red = ui.Color.fromRGBO(255, 0, 0, 1); const ui.Color green = ui.Color.fromRGBO(0, 255, 0, 1); const ui.Color blue = ui.Color.fromRGBO(0, 0, 255, 1); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawRRect( ui.RRect.fromRectXY(const ui.Rect.fromLTRB(20, 20, 150, 300), 15, 15), ui.Paint()..color = red, ); canvas.drawCircle( const ui.Offset(200, 200), 100, ui.Paint()..color = green, ); canvas.drawOval( const ui.Rect.fromLTRB(210, 40, 268, 199), ui.Paint()..color = blue, ); final CkPicture picture = recorder.endRecording() as CkPicture; final ui.Rect bounds = picture.cullRect; // Top left bounded by the red rrect, right bounded by right edge // of red rrect, bottom bounded by bottom of green circle. expect(bounds, equals(const ui.Rect.fromLTRB(20, 20, 300, 300))); }); test('cullRect bounds with infinite size draw', () async { const ui.Color red = ui.Color.fromRGBO(255, 0, 0, 1); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawColor(red, ui.BlendMode.src); final CkPicture picture = recorder.endRecording() as CkPicture; final ui.Rect bounds = picture.cullRect; // Since the drawColor command fills the entire canvas, the computed // bounds default to the cullRect that is passed in when the // PictureRecorder is created, ie ui.Rect.largest. expect(bounds, equals(ui.Rect.largest)); }); test('approximateBytesUsed', () async { const ui.Color red = ui.Color.fromRGBO(255, 0, 0, 1); const ui.Color green = ui.Color.fromRGBO(0, 255, 0, 1); const ui.Color blue = ui.Color.fromRGBO(0, 0, 255, 1); final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas canvas = ui.Canvas(recorder); canvas.drawRRect( ui.RRect.fromRectXY(const ui.Rect.fromLTRB(20, 20, 150, 300), 15, 15), ui.Paint()..color = red, ); canvas.drawCircle( const ui.Offset(200, 200), 100, ui.Paint()..color = green, ); canvas.drawOval( const ui.Rect.fromLTRB(210, 40, 268, 199), ui.Paint()..color = blue, ); final CkPicture picture = recorder.endRecording() as CkPicture; final int bytesUsed = picture.approximateBytesUsed; // Sanity check: the picture should use more than 20 bytes of memory. expect(bytesUsed, greaterThan(20)); }); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040 }, skip: isIosSafari); }
engine/lib/web_ui/test/canvaskit/picture_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/picture_test.dart", "repo_id": "engine", "token_count": 2148 }
277
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Provides utilities for testing engine code. library matchers; import 'dart:math' as math; import 'package:html/dom.dart' as html_package; import 'package:html/parser.dart' as html_package; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; /// The epsilon of tolerable double precision error. /// /// This is used in various places in the framework to allow for floating point /// precision loss in calculations. Differences below this threshold are safe /// to disregard. const double precisionErrorTolerance = 1e-10; /// Enumerates all persisted surfaces in the tree rooted at [root]. /// /// If [root] is `null` returns all surfaces from the last rendered scene. /// /// Surfaces are returned in a depth-first order. Iterable<PersistedSurface> enumerateSurfaces([PersistedSurface? root]) { root ??= SurfaceSceneBuilder.debugLastFrameScene; final List<PersistedSurface> surfaces = <PersistedSurface>[root!]; root.visitChildren((PersistedSurface surface) { surfaces.addAll(enumerateSurfaces(surface)); }); return surfaces; } /// Enumerates all pictures nested under [root]. /// /// If [root] is `null` returns all pictures from the last rendered scene. Iterable<PersistedPicture> enumeratePictures([PersistedSurface? root]) { root ??= SurfaceSceneBuilder.debugLastFrameScene; return enumerateSurfaces(root).whereType<PersistedPicture>(); } /// Enumerates all offset surfaces nested under [root]. /// /// If [root] is `null` returns all pictures from the last rendered scene. Iterable<PersistedOffset> enumerateOffsets([PersistedSurface? root]) { root ??= SurfaceSceneBuilder.debugLastFrameScene; return enumerateSurfaces(root).whereType<PersistedOffset>(); } /// Computes the distance between two values. /// /// The distance should be a metric in a metric space (see /// https://en.wikipedia.org/wiki/Metric_space). Specifically, if `f` is a /// distance function then the following conditions should hold: /// /// - f(a, b) >= 0 /// - f(a, b) == 0 if and only if a == b /// - f(a, b) == f(b, a) /// - f(a, c) <= f(a, b) + f(b, c), known as triangle inequality /// /// This makes it useful for comparing numbers, [Color]s, [Offset]s and other /// sets of value for which a metric space is defined. typedef DistanceFunction<T> = double Function(T a, T b); /// The type of a union of instances of [DistanceFunction<T>] for various types /// T. /// /// This type is used to describe a collection of [DistanceFunction<T>] /// functions which have (potentially) unrelated argument types. Since the /// argument types of the functions may be unrelated, the only thing that the /// type system can statically assume about them is that they accept null (since /// all types in Dart are nullable). /// /// Calling an instance of this type must either be done dynamically, or by /// first casting it to a [DistanceFunction<T>] for some concrete T. typedef AnyDistanceFunction = double Function(Never a, Never b); const Map<Type, AnyDistanceFunction> _kStandardDistanceFunctions = <Type, AnyDistanceFunction>{ Color: _maxComponentColorDistance, Offset: _offsetDistance, int: _intDistance, double: _doubleDistance, Rect: _rectDistance, Size: _sizeDistance, }; double _intDistance(int a, int b) => (b - a).abs().toDouble(); double _doubleDistance(double a, double b) => (b - a).abs(); double _offsetDistance(Offset a, Offset b) => (b - a).distance; double _maxComponentColorDistance(Color a, Color b) { int delta = math.max<int>((a.red - b.red).abs(), (a.green - b.green).abs()); delta = math.max<int>(delta, (a.blue - b.blue).abs()); delta = math.max<int>(delta, (a.alpha - b.alpha).abs()); return delta.toDouble(); } double _rectDistance(Rect a, Rect b) { double delta = math.max<double>((a.left - b.left).abs(), (a.top - b.top).abs()); delta = math.max<double>(delta, (a.right - b.right).abs()); delta = math.max<double>(delta, (a.bottom - b.bottom).abs()); return delta; } double _sizeDistance(Size a, Size b) { final Offset delta = (b - a) as Offset; // ignore: unnecessary_parenthesis return delta.distance; } /// Asserts that two values are within a certain distance from each other. /// /// The distance is computed by a [DistanceFunction]. /// /// If `distanceFunction` is null, a standard distance function is used for the /// type `T` . Standard functions are defined for the following types: /// /// * [Color], whose distance is the maximum component-wise delta. /// * [Offset], whose distance is the Euclidean distance computed using the /// method [Offset.distance]. /// * [Rect], whose distance is the maximum component-wise delta. /// * [Size], whose distance is the [Offset.distance] of the offset computed as /// the difference between two sizes. /// * [int], whose distance is the absolute difference between two integers. /// * [double], whose distance is the absolute difference between two doubles. /// /// See also: /// /// * [moreOrLessEquals], which is similar to this function, but specializes in /// [double]s and has an optional `epsilon` parameter. /// * [closeTo], which specializes in numbers only. Matcher within<T>({ required T from, double distance = precisionErrorTolerance, DistanceFunction<T>? distanceFunction, }) { distanceFunction ??= _kStandardDistanceFunctions[T] as DistanceFunction<T>?; if (distanceFunction == null) { throw ArgumentError( 'The specified distanceFunction was null, and a standard distance ' 'function was not found for type $T of the provided ' '`from` argument.'); } return _IsWithinDistance<T>(distanceFunction, from, distance); } class _IsWithinDistance<T> extends Matcher { const _IsWithinDistance(this.distanceFunction, this.value, this.epsilon); final DistanceFunction<T> distanceFunction; final T value; final double epsilon; @override bool matches(Object? object, Map<dynamic, dynamic> matchState) { if (object is! T) { return false; } if (object == value) { return true; } final T test = object; final double distance = distanceFunction(test, value); if (distance < 0) { throw ArgumentError( 'Invalid distance function was used to compare a ${value.runtimeType} ' 'to a ${object.runtimeType}. The function must return a non-negative ' 'double value, but it returned $distance.'); } matchState['distance'] = distance; return distance <= epsilon; } @override Description describe(Description description) => description.add('$value (±$epsilon)'); @override Description describeMismatch( Object? object, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose, ) { mismatchDescription .add('was ${matchState['distance']} away from the desired value.'); return mismatchDescription; } } /// Controls how test HTML is canonicalized by [canonicalizeHtml] function. /// /// In all cases whitespace between elements is stripped. enum HtmlComparisonMode { /// Retains all attributes. /// /// Useful when very precise HTML comparison is needed that includes both /// layout and non-layout style attributes. This mode is rarely needed. Most /// tests should use [layoutOnly] or [nonLayoutOnly]. everything, /// Retains only layout style attributes, such as "width". /// /// Useful when testing layout because it filters out all the noise that does /// not affect layout. layoutOnly, /// Retains only non-layout style attributes, such as "color". /// /// Useful when testing styling because it filters out all the noise from the /// layout attributes. nonLayoutOnly, /// Do not consider attributes when comparing HTML. noAttributes, } /// Rewrites [htmlContent] by removing irrelevant style attributes. /// /// If [throwOnUnusedStyleProperties] is `true`, throws instead of rewriting. Set /// [throwOnUnusedStyleProperties] to `true` to check that expected HTML strings do /// not contain irrelevant attributes. It is ok for actual HTML to contain all /// kinds of attributes. They only need to be filtered out before testing. String canonicalizeHtml( String htmlContent, { HtmlComparisonMode mode = HtmlComparisonMode.nonLayoutOnly, bool throwOnUnusedStyleProperties = false, List<String>? ignoredStyleProperties, }) { if (htmlContent.trim().isEmpty) { return ''; } String? unusedStyleProperty(String name) { if (throwOnUnusedStyleProperties) { fail('Provided HTML contains style property "$name" which ' 'is not used for comparison in the test. The HTML was:\n\n$htmlContent'); } return null; } html_package.Element cleanup(html_package.Element original) { String replacementTag = original.localName!; switch (replacementTag) { case 'flt-scene': replacementTag = 's'; case 'flt-transform': replacementTag = 't'; case 'flt-opacity': replacementTag = 'o'; case 'flt-clip': final String? clipType = original.attributes['clip-type']; switch (clipType) { case 'rect': replacementTag = 'clip'; case 'rrect': replacementTag = 'rclip'; case 'physical-shape': replacementTag = 'pshape'; default: throw Exception('Unknown clip type: $clipType'); } case 'flt-clip-interior': replacementTag = 'clip-i'; case 'flt-picture': replacementTag = 'pic'; case 'flt-canvas': replacementTag = 'c'; case 'flt-dom-canvas': replacementTag = 'd'; case 'flt-semantics': replacementTag = 'sem'; case 'flt-semantics-container': replacementTag = 'sem-c'; case 'flt-semantics-img': replacementTag = 'sem-img'; case 'flt-semantics-text-field': replacementTag = 'sem-tf'; } final html_package.Element replacement = html_package.Element.tag(replacementTag); if (mode != HtmlComparisonMode.noAttributes) { // Sort the attributes so tests are not sensitive to their order, which // does not matter in terms of functionality. final List<String> attributeNames = original.attributes.keys.cast<String>().toList(); attributeNames.sort(); for (final String name in attributeNames) { final String value = original.attributes[name]!; if (name == 'style') { // The style attribute is handled separately because it contains substructure. continue; } // These are the only attributes we're interested in testing. This list // can change over time. if (name.startsWith('aria-') || name.startsWith('flt-') || name == 'role') { replacement.attributes[name] = value; } } if (original.attributes.containsKey('style')) { final String styleValue = original.attributes['style']!; int attrCount = 0; final String processedAttributes = styleValue .split(';') .map((String attr) { attr = attr.trim(); if (attr.isEmpty) { return null; } if (mode != HtmlComparisonMode.everything) { final bool forLayout = mode == HtmlComparisonMode.layoutOnly; final List<String> parts = attr.split(':'); if (parts.length == 2) { final String name = parts.first; if (ignoredStyleProperties != null && ignoredStyleProperties.contains(name)) { return null; } // Whether the attribute is one that's set to the same value and // never changes. Such attributes are usually not interesting to // test. final bool isStaticAttribute = const <String>[ 'top', 'left', 'position', ].contains(name); if (isStaticAttribute) { return unusedStyleProperty(name); } // Whether the attribute is set by the layout system. final bool isLayoutAttribute = const <String>[ 'top', 'left', 'bottom', 'right', 'position', 'width', 'height', 'font-size', 'transform', 'transform-origin', 'white-space', ].contains(name); if (forLayout && !isLayoutAttribute || !forLayout && isLayoutAttribute) { return unusedStyleProperty(name); } } } attrCount++; return attr.trim(); }) .where((String? attr) => attr != null && attr.isNotEmpty) .join('; '); if (attrCount > 0) { replacement.attributes['style'] = processedAttributes; } } } else if (throwOnUnusedStyleProperties && original.attributes.isNotEmpty) { fail('Provided HTML contains attributes. However, the comparison mode ' 'is $mode. The HTML was:\n\n$htmlContent'); } for (final html_package.Node child in original.nodes) { if (child is html_package.Text && child.text.trim().isEmpty) { continue; } if (child is html_package.Element) { replacement.append(cleanup(child)); } else { replacement.append(child.clone(true)); } } return replacement; } final html_package.DocumentFragment originalDom = html_package.parseFragment(htmlContent); final html_package.DocumentFragment cleanDom = html_package.DocumentFragment(); for (final html_package.Element child in originalDom.children) { cleanDom.append(cleanup(child)); } return cleanDom.outerHtml; } /// Tests that [element] has the HTML structure described by [expectedHtml]. void expectHtml(DomElement element, String expectedHtml, {HtmlComparisonMode mode = HtmlComparisonMode.nonLayoutOnly}) { expectedHtml = canonicalizeHtml(expectedHtml, mode: mode, throwOnUnusedStyleProperties: true); final String actualHtml = canonicalizeHtml(element.outerHTML!, mode: mode); expect(actualHtml, expectedHtml); } class SceneTester { SceneTester(this.scene); final SurfaceScene scene; void expectSceneHtml(String expectedHtml) { expectHtml(scene.webOnlyRootElement!, expectedHtml, mode: HtmlComparisonMode.noAttributes); } } /// A matcher for functions that throw [AssertionError]. /// /// This is equivalent to `throwsA(isInstanceOf<AssertionError>())`. /// /// If you are trying to test whether a call to [WidgetTester.pumpWidget] /// results in an [AssertionError], see /// [TestWidgetsFlutterBinding.takeException]. /// /// See also: /// /// * [throwsFlutterError], to test if a function throws a [FlutterError]. /// * [throwsArgumentError], to test if a functions throws an [ArgumentError]. /// * [isAssertionError], to test if any object is any kind of [AssertionError]. final Matcher throwsAssertionError = throwsA(isAssertionError); /// A matcher for [AssertionError]. /// /// This is equivalent to `isInstanceOf<AssertionError>()`. /// /// See also: /// /// * [throwsAssertionError], to test if a function throws any [AssertionError]. /// * [isFlutterError], to test if any object is a [FlutterError]. const Matcher isAssertionError = TypeMatcher<AssertionError>();
engine/lib/web_ui/test/common/matchers.dart/0
{ "file_path": "engine/lib/web_ui/test/common/matchers.dart", "repo_id": "engine", "token_count": 5676 }
278