hash
stringlengths
40
40
date
stringdate
2019-01-22 05:28:56
2025-03-19 19:23:00
author
stringclasses
199 values
commit_message
stringlengths
18
96
is_merge
bool
1 class
masked_commit_message
stringlengths
12
90
type
stringclasses
74 values
git_diff
stringlengths
222
1.21M
892006218a5d5679f221f4eef58d447430153251
2022-11-26 14:08:13
cflip
libgl: Refactor TextureNameAllocator to a more general NameAllocator
false
Refactor TextureNameAllocator to a more general NameAllocator
libgl
diff --git a/Userland/Libraries/LibGL/CMakeLists.txt b/Userland/Libraries/LibGL/CMakeLists.txt index 133f87229c80..3c9bb6672536 100644 --- a/Userland/Libraries/LibGL/CMakeLists.txt +++ b/Userland/Libraries/LibGL/CMakeLists.txt @@ -8,8 +8,8 @@ set(SOURCES Lighting.cpp List.cpp Matrix.cpp + NameAllocator.cpp Stencil.cpp - Tex/NameAllocator.cpp Tex/Texture2D.cpp Texture.cpp Vertex.cpp diff --git a/Userland/Libraries/LibGL/GLContext.h b/Userland/Libraries/LibGL/GLContext.h index bcac8232ffef..f76ed24ef57e 100644 --- a/Userland/Libraries/LibGL/GLContext.h +++ b/Userland/Libraries/LibGL/GLContext.h @@ -15,7 +15,7 @@ #include <AK/Tuple.h> #include <AK/Variant.h> #include <AK/Vector.h> -#include <LibGL/Tex/NameAllocator.h> +#include <LibGL/NameAllocator.h> #include <LibGL/Tex/Texture.h> #include <LibGL/Tex/TextureUnit.h> #include <LibGPU/Device.h> @@ -373,7 +373,7 @@ class GLContext final { return static_cast<T*>(default_texture.value()); } - TextureNameAllocator m_name_allocator; + NameAllocator m_texture_name_allocator; HashMap<GLuint, RefPtr<Texture>> m_allocated_textures; HashMap<GLenum, RefPtr<Texture>> m_default_textures; Vector<TextureUnit> m_texture_units; diff --git a/Userland/Libraries/LibGL/NameAllocator.cpp b/Userland/Libraries/LibGL/NameAllocator.cpp new file mode 100644 index 000000000000..ccd9350e5a8f --- /dev/null +++ b/Userland/Libraries/LibGL/NameAllocator.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021, Jesse Buhagiar <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibGL/NameAllocator.h> + +namespace GL { + +void NameAllocator::allocate(GLsizei count, GLuint* names) +{ + for (auto i = 0; i < count; ++i) { + if (!m_free_names.is_empty()) { + names[i] = m_free_names.top(); + m_free_names.pop(); + } else { + // We're out of free previously allocated names. Let's allocate a new contiguous amount from the + // last known texture name + names[i] = m_last_id++; + } + } +} + +void NameAllocator::free(GLuint name) +{ + m_free_names.push(name); +} + +bool NameAllocator::has_allocated_name(GLuint name) const +{ + return name < m_last_id && !m_free_names.contains_slow(name); +} + +} diff --git a/Userland/Libraries/LibGL/NameAllocator.h b/Userland/Libraries/LibGL/NameAllocator.h new file mode 100644 index 000000000000..186f211b3fde --- /dev/null +++ b/Userland/Libraries/LibGL/NameAllocator.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021, Jesse Buhagiar <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Stack.h> +#include <LibGL/GL/gl.h> + +namespace GL { + +class NameAllocator { +public: + NameAllocator() = default; + + void allocate(GLsizei count, GLuint* names); + void free(GLuint name); + bool has_allocated_name(GLuint name) const; + +private: + Stack<GLuint, 512> m_free_names; + GLuint m_last_id { 1 }; +}; + +} diff --git a/Userland/Libraries/LibGL/Tex/NameAllocator.cpp b/Userland/Libraries/LibGL/Tex/NameAllocator.cpp deleted file mode 100644 index f1cd1be75807..000000000000 --- a/Userland/Libraries/LibGL/Tex/NameAllocator.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2021, Jesse Buhagiar <[email protected]> - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include <LibGL/Tex/NameAllocator.h> - -namespace GL { - -void TextureNameAllocator::allocate(GLsizei count, GLuint* textures) -{ - for (auto i = 0; i < count; ++i) { - if (!m_free_texture_names.is_empty()) { - textures[i] = m_free_texture_names.top(); - m_free_texture_names.pop(); - } else { - // We're out of free previously allocated names. Let's allocate a new contiguous amount from the - // last known texture name - textures[i] = m_last_texture_id++; - } - } -} - -void TextureNameAllocator::free(GLuint texture) -{ - m_free_texture_names.push(texture); -} - -} diff --git a/Userland/Libraries/LibGL/Tex/NameAllocator.h b/Userland/Libraries/LibGL/Tex/NameAllocator.h deleted file mode 100644 index c40a88476b6f..000000000000 --- a/Userland/Libraries/LibGL/Tex/NameAllocator.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2021, Jesse Buhagiar <[email protected]> - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include <AK/Stack.h> -#include <LibGL/GL/gl.h> - -namespace GL { - -class TextureNameAllocator { -public: - TextureNameAllocator() = default; - - void allocate(GLsizei count, GLuint* textures); - void free(GLuint texture); - -private: - Stack<GLuint, 512> m_free_texture_names; - GLuint m_last_texture_id { 1 }; -}; - -} diff --git a/Userland/Libraries/LibGL/Texture.cpp b/Userland/Libraries/LibGL/Texture.cpp index 300183d31408..880cf2cd4260 100644 --- a/Userland/Libraries/LibGL/Texture.cpp +++ b/Userland/Libraries/LibGL/Texture.cpp @@ -190,7 +190,7 @@ void GLContext::gl_delete_textures(GLsizei n, GLuint const* textures) if (texture_object == m_allocated_textures.end() || texture_object->value.is_null()) continue; - m_name_allocator.free(name); + m_texture_name_allocator.free(name); auto texture = texture_object->value; @@ -211,7 +211,7 @@ void GLContext::gl_gen_textures(GLsizei n, GLuint* textures) RETURN_WITH_ERROR_IF(n < 0, GL_INVALID_VALUE); RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION); - m_name_allocator.allocate(n, textures); + m_texture_name_allocator.allocate(n, textures); // Initialize all texture names with a nullptr for (auto i = 0; i < n; ++i) {
5884ef8425e21d66acfba2ffb3524d77599a2bc7
2020-02-14 22:05:04
Andreas Kling
libgui: Add missing Event.cpp file
false
Add missing Event.cpp file
libgui
diff --git a/Libraries/LibGUI/Event.cpp b/Libraries/LibGUI/Event.cpp new file mode 100644 index 000000000000..94acc7d57d91 --- /dev/null +++ b/Libraries/LibGUI/Event.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2020, Andreas Kling <[email protected]> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <LibCore/MimeData.h> +#include <LibGUI/Event.h> + +namespace GUI { + +DropEvent::DropEvent(const Gfx::Point& position, const String& text, NonnullRefPtr<Core::MimeData> mime_data) + : Event(Event::Drop) + , m_position(position) + , m_text(text) + , m_mime_data(move(mime_data)) +{ +} + +DropEvent::~DropEvent() +{ +} + +}
854b269338b1a1b31c0346f48dc58fa55ccf7d9f
2024-06-24 16:52:59
Aliaksandr Kalenik
libweb: Rename RecordingPainter to DisplayListRecorder
false
Rename RecordingPainter to DisplayListRecorder
libweb
diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn index 1a353cb098c6..83a889adcc16 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn @@ -17,6 +17,7 @@ source_set("Painting") { "Command.cpp", "CommandExecutorCPU.cpp", "DisplayList.cpp", + "DisplayListRecorder.cpp", "FilterPainting.cpp", "GradientPainting.cpp", "ImagePaintable.cpp", @@ -30,7 +31,6 @@ source_set("Painting") { "PaintableBox.cpp", "PaintableFragment.cpp", "RadioButtonPaintable.cpp", - "RecordingPainter.cpp", "SVGClipPaintable.cpp", "SVGForeignObjectPaintable.cpp", "SVGGraphicsPaintable.cpp", diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index cfa603cbf1f4..55fe2e6d7459 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -544,6 +544,7 @@ set(SOURCES Painting/CheckBoxPaintable.cpp Painting/ClippableAndScrollable.cpp Painting/DisplayList.cpp + Painting/DisplayListRecorder.cpp Painting/GradientPainting.cpp Painting/FilterPainting.cpp Painting/ImagePaintable.cpp @@ -558,7 +559,6 @@ set(SOURCES Painting/PaintableBox.cpp Painting/PaintableFragment.cpp Painting/RadioButtonPaintable.cpp - Painting/RecordingPainter.cpp Painting/SVGForeignObjectPaintable.cpp Painting/SVGPathPaintable.cpp Painting/SVGGraphicsPaintable.cpp diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp index e93a3fc588f2..53ad12c6d59e 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/ConicGradientStyleValue.cpp @@ -47,7 +47,7 @@ void ConicGradientStyleValue::paint(PaintContext& context, DevicePixelRect const VERIFY(m_resolved.has_value()); auto destination_rect = dest_rect.to_type<int>(); auto position = context.rounded_device_point(m_resolved->position).to_type<int>(); - context.recording_painter().fill_rect_with_conic_gradient(destination_rect, m_resolved->data, position, clip_paths); + context.display_list_recorder().fill_rect_with_conic_gradient(destination_rect, m_resolved->data, position, clip_paths); } bool ConicGradientStyleValue::equals(StyleValue const& other) const diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp index 9c7d9c6e3684..389f2dd690a4 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp @@ -14,8 +14,8 @@ #include <LibWeb/HTML/DecodedImageData.h> #include <LibWeb/HTML/ImageRequest.h> #include <LibWeb/HTML/PotentialCORSRequest.h> +#include <LibWeb/Painting/DisplayListRecorder.h> #include <LibWeb/Painting/PaintContext.h> -#include <LibWeb/Painting/RecordingPainter.h> #include <LibWeb/Platform/Timer.h> namespace Web::CSS { @@ -137,7 +137,7 @@ void ImageStyleValue::paint(PaintContext& context, DevicePixelRect const& dest_r { if (auto const* b = bitmap(m_current_frame_index, dest_rect.size().to_type<int>()); b != nullptr) { auto scaling_mode = to_gfx_scaling_mode(image_rendering, b->rect(), dest_rect.to_type<int>()); - context.recording_painter().draw_scaled_immutable_bitmap(dest_rect.to_type<int>(), *b, b->rect(), scaling_mode, clip_paths); + context.display_list_recorder().draw_scaled_immutable_bitmap(dest_rect.to_type<int>(), *b, b->rect(), scaling_mode, clip_paths); } } diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp index f6c62f0d6252..2786b9de32c9 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/LinearGradientStyleValue.cpp @@ -112,7 +112,7 @@ void LinearGradientStyleValue::resolve_for_size(Layout::NodeWithStyleAndBoxModel void LinearGradientStyleValue::paint(PaintContext& context, DevicePixelRect const& dest_rect, CSS::ImageRendering, Vector<Gfx::Path> const& clip_paths) const { VERIFY(m_resolved.has_value()); - context.recording_painter().fill_rect_with_linear_gradient(dest_rect.to_type<int>(), m_resolved->data, clip_paths); + context.display_list_recorder().fill_rect_with_linear_gradient(dest_rect.to_type<int>(), m_resolved->data, clip_paths); } } diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp index 8105874f1e08..99a7a93ddcab 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/RadialGradientStyleValue.cpp @@ -212,7 +212,7 @@ void RadialGradientStyleValue::paint(PaintContext& context, DevicePixelRect cons VERIFY(m_resolved.has_value()); auto center = context.rounded_device_point(m_resolved->center).to_type<int>(); auto size = context.rounded_device_size(m_resolved->gradient_size).to_type<int>(); - context.recording_painter().fill_rect_with_radial_gradient(dest_rect.to_type<int>(), m_resolved->data, center, size, clip_paths); + context.display_list_recorder().fill_rect_with_radial_gradient(dest_rect.to_type<int>(), m_resolved->data, center, size, clip_paths); } } diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index 43ac60b0be6f..fe0ffee7feb2 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -24,7 +24,7 @@ class XMLDocumentBuilder; } namespace Web::Painting { -class RecordingPainter; +class DisplayListRecorder; class SVGGradientPaintStyle; using PaintStyle = RefPtr<SVGGradientPaintStyle>; } diff --git a/Userland/Libraries/LibWeb/HTML/Navigable.cpp b/Userland/Libraries/LibWeb/HTML/Navigable.cpp index 781e6dd4f1c8..edb468260fde 100644 --- a/Userland/Libraries/LibWeb/HTML/Navigable.cpp +++ b/Userland/Libraries/LibWeb/HTML/Navigable.cpp @@ -2092,7 +2092,7 @@ void Navigable::inform_the_navigation_api_about_aborting_navigation() })); } -void Navigable::record_display_list(Painting::RecordingPainter& recording_painter, PaintConfig config) +void Navigable::record_display_list(Painting::DisplayListRecorder& display_list_recorder, PaintConfig config) { auto document = active_document(); if (!document) @@ -2104,12 +2104,12 @@ void Navigable::record_display_list(Painting::RecordingPainter& recording_painte auto background_color = document->background_color(); - recording_painter.fill_rect(bitmap_rect, background_color); + display_list_recorder.fill_rect(bitmap_rect, background_color); if (!document->paintable()) { VERIFY_NOT_REACHED(); } - Web::PaintContext context(recording_painter, page.palette(), page.client().device_pixels_per_css_pixel()); + Web::PaintContext context(display_list_recorder, page.palette(), page.client().device_pixels_per_css_pixel()); context.set_device_viewport_rect(viewport_rect); context.set_should_show_line_box_borders(config.should_show_line_box_borders); context.set_should_paint_overlay(config.paint_overlay); @@ -2136,8 +2136,8 @@ void Navigable::record_display_list(Painting::RecordingPainter& recording_painte auto scroll_offset = context.rounded_device_point(scrollable_frame->offset).to_type<int>(); scroll_offsets_by_frame_id[scrollable_frame->id] = scroll_offset; } - recording_painter.display_list().apply_scroll_offsets(scroll_offsets_by_frame_id); - recording_painter.display_list().mark_unnecessary_commands(); + display_list_recorder.display_list().apply_scroll_offsets(scroll_offsets_by_frame_id); + display_list_recorder.display_list().mark_unnecessary_commands(); } m_needs_repaint = false; diff --git a/Userland/Libraries/LibWeb/HTML/Navigable.h b/Userland/Libraries/LibWeb/HTML/Navigable.h index ffaec209e29d..fc7d7bae6028 100644 --- a/Userland/Libraries/LibWeb/HTML/Navigable.h +++ b/Userland/Libraries/LibWeb/HTML/Navigable.h @@ -183,7 +183,7 @@ class Navigable : public JS::Cell { bool should_show_line_box_borders { false }; bool has_focus { false }; }; - void record_display_list(Painting::RecordingPainter& recording_painter, PaintConfig); + void record_display_list(Painting::DisplayListRecorder& display_list_recorder, PaintConfig); Page& page() { return m_page; } Page const& page() const { return m_page; } diff --git a/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp b/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp index 487d9633e9ab..96c93340b8c7 100644 --- a/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp +++ b/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp @@ -1177,16 +1177,16 @@ JS::GCPtr<DOM::Node> TraversableNavigable::currently_focused_area() void TraversableNavigable::paint(Web::DevicePixelRect const& content_rect, Gfx::Bitmap& target, Web::PaintOptions paint_options) { Painting::DisplayList display_list; - Painting::RecordingPainter recording_painter(display_list); + Painting::DisplayListRecorder display_list_recorder(display_list); Gfx::IntRect bitmap_rect { {}, content_rect.size().to_type<int>() }; - recording_painter.fill_rect(bitmap_rect, Web::CSS::SystemColor::canvas()); + display_list_recorder.fill_rect(bitmap_rect, Web::CSS::SystemColor::canvas()); Web::HTML::Navigable::PaintConfig paint_config; paint_config.paint_overlay = paint_options.paint_overlay == Web::PaintOptions::PaintOverlay::Yes; paint_config.should_show_line_box_borders = paint_options.should_show_line_box_borders; paint_config.has_focus = paint_options.has_focus; - record_display_list(recording_painter, paint_config); + record_display_list(display_list_recorder, paint_config); auto painting_command_executor_type = page().client().painting_command_executor_type(); if (painting_command_executor_type == PaintingCommandExecutorType::GPU) { diff --git a/Userland/Libraries/LibWeb/Painting/AudioPaintable.cpp b/Userland/Libraries/LibWeb/Painting/AudioPaintable.cpp index d46004840ed4..91db701bbb4a 100644 --- a/Userland/Libraries/LibWeb/Painting/AudioPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/AudioPaintable.cpp @@ -49,10 +49,10 @@ void AudioPaintable::paint(PaintContext& context, PaintPhase phase) const if (phase != PaintPhase::Foreground) return; - RecordingPainterStateSaver saver { context.recording_painter() }; + DisplayListRecorderStateSaver saver { context.display_list_recorder() }; auto audio_rect = context.rounded_device_rect(absolute_rect()); - context.recording_painter().add_clip_rect(audio_rect.to_type<int>()); + context.display_list_recorder().add_clip_rect(audio_rect.to_type<int>()); ScopedCornerRadiusClip corner_clip { context, audio_rect, normalized_border_radii_data(ShrinkRadiiForBorders::Yes) }; diff --git a/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp b/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp index 2a456e8f7e82..26e21a910714 100644 --- a/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp +++ b/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp @@ -126,7 +126,7 @@ void paint_background(PaintContext& context, Layout::NodeWithStyleAndBoxModelMet clip_paths = compute_text_clip_paths(context, *layout_node.paintable()); } - auto& painter = context.recording_painter(); + auto& display_list_recorder = context.display_list_recorder(); struct BackgroundBox { CSSPixelRect rect; @@ -181,7 +181,7 @@ void paint_background(PaintContext& context, Layout::NodeWithStyleAndBoxModelMet } } - painter.fill_rect_with_rounded_corners( + display_list_recorder.fill_rect_with_rounded_corners( context.rounded_device_rect(color_box.rect).to_type<int>(), background_color, color_box.radii.top_left.as_corner(context), @@ -217,14 +217,14 @@ void paint_background(PaintContext& context, Layout::NodeWithStyleAndBoxModelMet for (auto& layer : background_layers->in_reverse()) { if (!layer_is_paintable(layer)) continue; - RecordingPainterStateSaver state { painter }; + DisplayListRecorderStateSaver state { display_list_recorder }; // Clip auto clip_box = get_box(layer.clip); CSSPixelRect const& css_clip_rect = clip_box.rect; auto clip_rect = context.rounded_device_rect(css_clip_rect); - painter.add_clip_rect(clip_rect.to_type<int>()); + display_list_recorder.add_clip_rect(clip_rect.to_type<int>()); ScopedCornerRadiusClip corner_clip { context, clip_rect, clip_box.radii }; if (layer.clip == CSS::BackgroundBox::BorderBox) { @@ -452,7 +452,7 @@ void paint_background(PaintContext& context, Layout::NodeWithStyleAndBoxModelMet fill_rect = fill_rect->united(image_device_rect); } }); - painter.fill_rect(fill_rect->to_type<int>(), color.value(), clip_paths); + display_list_recorder.fill_rect(fill_rect->to_type<int>(), color.value(), clip_paths); } else { for_each_image_device_rect([&](auto const& image_device_rect) { image.paint(context, image_device_rect, image_rendering, clip_paths); diff --git a/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp b/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp index ba5978f2945b..9d2e332bec42 100644 --- a/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp +++ b/Userland/Libraries/LibWeb/Painting/BorderPainting.cpp @@ -61,7 +61,7 @@ Gfx::Color border_color(BorderEdge edge, BordersDataDevicePixels const& borders_ return border_data.color; } -void paint_border(RecordingPainter& painter, BorderEdge edge, DevicePixelRect const& rect, Gfx::AntiAliasingPainter::CornerRadius const& radius, Gfx::AntiAliasingPainter::CornerRadius const& opposite_radius, BordersDataDevicePixels const& borders_data, Gfx::Path& path, bool last) +void paint_border(DisplayListRecorder& painter, BorderEdge edge, DevicePixelRect const& rect, Gfx::AntiAliasingPainter::CornerRadius const& radius, Gfx::AntiAliasingPainter::CornerRadius const& opposite_radius, BordersDataDevicePixels const& borders_data, Gfx::Path& path, bool last) { auto const& border_data = [&] { switch (edge) { @@ -491,7 +491,7 @@ void paint_border(RecordingPainter& painter, BorderEdge edge, DevicePixelRect co } } -void paint_all_borders(RecordingPainter& painter, DevicePixelRect const& border_rect, CornerRadii const& corner_radii, BordersDataDevicePixels const& borders_data) +void paint_all_borders(DisplayListRecorder& painter, DevicePixelRect const& border_rect, CornerRadii const& corner_radii, BordersDataDevicePixels const& borders_data) { if (borders_data.top.width <= 0 && borders_data.right.width <= 0 && borders_data.left.width <= 0 && borders_data.bottom.width <= 0) return; diff --git a/Userland/Libraries/LibWeb/Painting/BorderPainting.h b/Userland/Libraries/LibWeb/Painting/BorderPainting.h index 196641d0a56a..0b417215e04d 100644 --- a/Userland/Libraries/LibWeb/Painting/BorderPainting.h +++ b/Userland/Libraries/LibWeb/Painting/BorderPainting.h @@ -26,8 +26,8 @@ enum class BorderEdge { // Returns OptionalNone if there is no outline to paint. Optional<BordersData> borders_data_for_outline(Layout::Node const&, Color outline_color, CSS::OutlineStyle outline_style, CSSPixels outline_width); -void paint_border(RecordingPainter& painter, BorderEdge edge, DevicePixelRect const& rect, Gfx::AntiAliasingPainter::CornerRadius const& radius, Gfx::AntiAliasingPainter::CornerRadius const& opposite_radius, BordersDataDevicePixels const& borders_data, Gfx::Path& path, bool last); -void paint_all_borders(RecordingPainter& painter, DevicePixelRect const& border_rect, CornerRadii const& corner_radii, BordersDataDevicePixels const&); +void paint_border(DisplayListRecorder& painter, BorderEdge edge, DevicePixelRect const& rect, Gfx::AntiAliasingPainter::CornerRadius const& radius, Gfx::AntiAliasingPainter::CornerRadius const& opposite_radius, BordersDataDevicePixels const& borders_data, Gfx::Path& path, bool last); +void paint_all_borders(DisplayListRecorder& painter, DevicePixelRect const& border_rect, CornerRadii const& corner_radii, BordersDataDevicePixels const&); Gfx::Color border_color(BorderEdge edge, BordersDataDevicePixels const& borders_data); diff --git a/Userland/Libraries/LibWeb/Painting/BorderRadiusCornerClipper.cpp b/Userland/Libraries/LibWeb/Painting/BorderRadiusCornerClipper.cpp index 9e665b5c1de8..3ac2d0a413c2 100644 --- a/Userland/Libraries/LibWeb/Painting/BorderRadiusCornerClipper.cpp +++ b/Userland/Libraries/LibWeb/Painting/BorderRadiusCornerClipper.cpp @@ -128,14 +128,14 @@ ScopedCornerRadiusClip::ScopedCornerRadiusClip(PaintContext& context, DevicePixe m_has_radius = corner_radii.has_any_radius(); if (!m_has_radius) return; - m_context.recording_painter().sample_under_corners(m_id, corner_radii, border_rect.to_type<int>(), corner_clip); + m_context.display_list_recorder().sample_under_corners(m_id, corner_radii, border_rect.to_type<int>(), corner_clip); } ScopedCornerRadiusClip::~ScopedCornerRadiusClip() { if (!m_has_radius) return; - m_context.recording_painter().blit_corner_clipping(m_id); + m_context.display_list_recorder().blit_corner_clipping(m_id); } } diff --git a/Userland/Libraries/LibWeb/Painting/CanvasPaintable.cpp b/Userland/Libraries/LibWeb/Painting/CanvasPaintable.cpp index 92f15298e6d8..eade794b9742 100644 --- a/Userland/Libraries/LibWeb/Painting/CanvasPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/CanvasPaintable.cpp @@ -40,7 +40,7 @@ void CanvasPaintable::paint(PaintContext& context, PaintPhase phase) const // FIXME: Remove this const_cast. const_cast<HTML::HTMLCanvasElement&>(layout_box().dom_node()).present(); auto scaling_mode = to_gfx_scaling_mode(computed_values().image_rendering(), layout_box().dom_node().bitmap()->rect(), canvas_rect.to_type<int>()); - context.recording_painter().draw_scaled_bitmap(canvas_rect.to_type<int>(), *layout_box().dom_node().bitmap(), layout_box().dom_node().bitmap()->rect(), scaling_mode); + context.display_list_recorder().draw_scaled_bitmap(canvas_rect.to_type<int>(), *layout_box().dom_node().bitmap(), layout_box().dom_node().bitmap()->rect(), scaling_mode); } } } diff --git a/Userland/Libraries/LibWeb/Painting/CheckBoxPaintable.cpp b/Userland/Libraries/LibWeb/Painting/CheckBoxPaintable.cpp index f5600e230891..a43fd773f4cd 100644 --- a/Userland/Libraries/LibWeb/Painting/CheckBoxPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/CheckBoxPaintable.cpp @@ -99,11 +99,11 @@ void CheckBoxPaintable::paint(PaintContext& context, PaintPhase phase) const // Little heuristic that smaller things look better with more smoothness. if (checkbox.checked() && !checkbox.indeterminate()) { auto background_color = enabled ? input_colors.accent : input_colors.mid_gray; - context.recording_painter().fill_rect_with_rounded_corners(checkbox_rect, modify_color(background_color), checkbox_radius); + context.display_list_recorder().fill_rect_with_rounded_corners(checkbox_rect, modify_color(background_color), checkbox_radius); auto tick_color = increase_contrast(input_colors.base, background_color); if (!enabled) tick_color = shade(tick_color, 0.5f); - context.recording_painter().fill_path({ + context.display_list_recorder().fill_path({ .path = check_mark_path(checkbox_rect), .color = tick_color, .translation = checkbox_rect.location().to_type<float>(), @@ -111,14 +111,14 @@ void CheckBoxPaintable::paint(PaintContext& context, PaintPhase phase) const } else { auto background_color = input_colors.background_color(enabled); auto border_thickness = max(1, checkbox_rect.width() / 10); - context.recording_painter().fill_rect_with_rounded_corners(checkbox_rect, modify_color(input_colors.border_color(enabled)), checkbox_radius); - context.recording_painter().fill_rect_with_rounded_corners(checkbox_rect.shrunken(border_thickness, border_thickness, border_thickness, border_thickness), + context.display_list_recorder().fill_rect_with_rounded_corners(checkbox_rect, modify_color(input_colors.border_color(enabled)), checkbox_radius); + context.display_list_recorder().fill_rect_with_rounded_corners(checkbox_rect.shrunken(border_thickness, border_thickness, border_thickness, border_thickness), background_color, max(0, checkbox_radius - border_thickness)); if (checkbox.indeterminate()) { int radius = 0.05 * checkbox_rect.width(); auto dash_color = increase_contrast(input_colors.dark_gray, background_color); auto dash_rect = checkbox_rect.inflated(-0.4 * checkbox_rect.width(), -0.8 * checkbox_rect.height()); - context.recording_painter().fill_rect_with_rounded_corners(dash_rect, dash_color, radius, radius, radius, radius); + context.display_list_recorder().fill_rect_with_rounded_corners(dash_rect, dash_color, radius, radius, radius, radius); } } } diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp index 87c925efe772..29634cb37f6e 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp @@ -9,8 +9,8 @@ #include <LibWeb/CSS/ComputedValues.h> #include <LibWeb/Painting/BorderRadiusCornerClipper.h> #include <LibWeb/Painting/CommandExecutorCPU.h> +#include <LibWeb/Painting/DisplayListRecorder.h> #include <LibWeb/Painting/FilterPainting.h> -#include <LibWeb/Painting/RecordingPainter.h> #include <LibWeb/Painting/ShadowPainting.h> namespace Web::Painting { diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h index 4458584ec9a8..e22dc1b758c4 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h @@ -8,7 +8,7 @@ #include <AK/MaybeOwned.h> #include <LibGfx/ScalingMode.h> -#include <LibWeb/Painting/RecordingPainter.h> +#include <LibWeb/Painting/DisplayListRecorder.h> namespace Web::Painting { diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h b/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h index f09390189006..32187f3be665 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h @@ -8,7 +8,7 @@ #include <AK/MaybeOwned.h> #include <LibAccelGfx/Painter.h> -#include <LibWeb/Painting/RecordingPainter.h> +#include <LibWeb/Painting/DisplayListRecorder.h> namespace Web::Painting { diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorSkia.h b/Userland/Libraries/LibWeb/Painting/CommandExecutorSkia.h index 86ae0495df15..b1e14e251a2d 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorSkia.h +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorSkia.h @@ -7,7 +7,7 @@ #pragma once #include <LibGfx/Bitmap.h> -#include <LibWeb/Painting/RecordingPainter.h> +#include <LibWeb/Painting/DisplayListRecorder.h> namespace Web::Painting { diff --git a/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.cpp similarity index 70% rename from Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp rename to Userland/Libraries/LibWeb/Painting/DisplayListRecorder.cpp index 6e5b9dfb147b..ab212050466a 100644 --- a/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp +++ b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.cpp @@ -4,28 +4,28 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <LibWeb/Painting/RecordingPainter.h> +#include <LibWeb/Painting/DisplayListRecorder.h> #include <LibWeb/Painting/ShadowPainting.h> namespace Web::Painting { -RecordingPainter::RecordingPainter(DisplayList& command_list) +DisplayListRecorder::DisplayListRecorder(DisplayList& command_list) : m_command_list(command_list) { m_state_stack.append(State()); } -RecordingPainter::~RecordingPainter() +DisplayListRecorder::~DisplayListRecorder() { VERIFY(m_corner_clip_state_stack.is_empty()); } -void RecordingPainter::append(Command&& command) +void DisplayListRecorder::append(Command&& command) { m_command_list.append(move(command), state().scroll_frame_id); } -void RecordingPainter::sample_under_corners(u32 id, CornerRadii corner_radii, Gfx::IntRect border_rect, CornerClip corner_clip) +void DisplayListRecorder::sample_under_corners(u32 id, CornerRadii corner_radii, Gfx::IntRect border_rect, CornerClip corner_clip) { m_corner_clip_state_stack.append({ id, border_rect }); if (m_corner_clip_state_stack.size() > display_list().corner_clip_max_depth()) @@ -37,14 +37,14 @@ void RecordingPainter::sample_under_corners(u32 id, CornerRadii corner_radii, Gf corner_clip }); } -void RecordingPainter::blit_corner_clipping(u32 id) +void DisplayListRecorder::blit_corner_clipping(u32 id) { auto clip_state = m_corner_clip_state_stack.take_last(); VERIFY(clip_state.id == id); append(BlitCornerClipping { id, state().translation.map(clip_state.rect) }); } -void RecordingPainter::fill_rect(Gfx::IntRect const& rect, Color color, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::fill_rect(Gfx::IntRect const& rect, Color color, Vector<Gfx::Path> const& clip_paths) { if (rect.is_empty()) return; @@ -55,7 +55,7 @@ void RecordingPainter::fill_rect(Gfx::IntRect const& rect, Color color, Vector<G }); } -void RecordingPainter::fill_path(FillPathUsingColorParams params) +void DisplayListRecorder::fill_path(FillPathUsingColorParams params) { auto aa_translation = state().translation.map(params.translation.value_or(Gfx::FloatPoint {})); auto path_bounding_rect = params.path.bounding_box().translated(aa_translation).to_type<int>(); @@ -70,7 +70,7 @@ void RecordingPainter::fill_path(FillPathUsingColorParams params) }); } -void RecordingPainter::fill_path(FillPathUsingPaintStyleParams params) +void DisplayListRecorder::fill_path(FillPathUsingPaintStyleParams params) { auto aa_translation = state().translation.map(params.translation.value_or(Gfx::FloatPoint {})); auto path_bounding_rect = params.path.bounding_box().translated(aa_translation).to_type<int>(); @@ -86,7 +86,7 @@ void RecordingPainter::fill_path(FillPathUsingPaintStyleParams params) }); } -void RecordingPainter::stroke_path(StrokePathUsingColorParams params) +void DisplayListRecorder::stroke_path(StrokePathUsingColorParams params) { auto aa_translation = state().translation.map(params.translation.value_or(Gfx::FloatPoint {})); auto path_bounding_rect = params.path.bounding_box().translated(aa_translation).to_type<int>(); @@ -103,7 +103,7 @@ void RecordingPainter::stroke_path(StrokePathUsingColorParams params) }); } -void RecordingPainter::stroke_path(StrokePathUsingPaintStyleParams params) +void DisplayListRecorder::stroke_path(StrokePathUsingPaintStyleParams params) { auto aa_translation = state().translation.map(params.translation.value_or(Gfx::FloatPoint {})); auto path_bounding_rect = params.path.bounding_box().translated(aa_translation).to_type<int>(); @@ -121,7 +121,7 @@ void RecordingPainter::stroke_path(StrokePathUsingPaintStyleParams params) }); } -void RecordingPainter::draw_ellipse(Gfx::IntRect const& a_rect, Color color, int thickness) +void DisplayListRecorder::draw_ellipse(Gfx::IntRect const& a_rect, Color color, int thickness) { if (a_rect.is_empty()) return; @@ -132,7 +132,7 @@ void RecordingPainter::draw_ellipse(Gfx::IntRect const& a_rect, Color color, int }); } -void RecordingPainter::fill_ellipse(Gfx::IntRect const& a_rect, Color color) +void DisplayListRecorder::fill_ellipse(Gfx::IntRect const& a_rect, Color color) { if (a_rect.is_empty()) return; @@ -142,7 +142,7 @@ void RecordingPainter::fill_ellipse(Gfx::IntRect const& a_rect, Color color) }); } -void RecordingPainter::fill_rect_with_linear_gradient(Gfx::IntRect const& gradient_rect, LinearGradientData const& data, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::fill_rect_with_linear_gradient(Gfx::IntRect const& gradient_rect, LinearGradientData const& data, Vector<Gfx::Path> const& clip_paths) { if (gradient_rect.is_empty()) return; @@ -152,7 +152,7 @@ void RecordingPainter::fill_rect_with_linear_gradient(Gfx::IntRect const& gradie .clip_paths = clip_paths }); } -void RecordingPainter::fill_rect_with_conic_gradient(Gfx::IntRect const& rect, ConicGradientData const& data, Gfx::IntPoint const& position, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::fill_rect_with_conic_gradient(Gfx::IntRect const& rect, ConicGradientData const& data, Gfx::IntPoint const& position, Vector<Gfx::Path> const& clip_paths) { if (rect.is_empty()) return; @@ -163,7 +163,7 @@ void RecordingPainter::fill_rect_with_conic_gradient(Gfx::IntRect const& rect, C .clip_paths = clip_paths }); } -void RecordingPainter::fill_rect_with_radial_gradient(Gfx::IntRect const& rect, RadialGradientData const& data, Gfx::IntPoint center, Gfx::IntSize size, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::fill_rect_with_radial_gradient(Gfx::IntRect const& rect, RadialGradientData const& data, Gfx::IntPoint center, Gfx::IntSize size, Vector<Gfx::Path> const& clip_paths) { if (rect.is_empty()) return; @@ -175,7 +175,7 @@ void RecordingPainter::fill_rect_with_radial_gradient(Gfx::IntRect const& rect, .clip_paths = clip_paths }); } -void RecordingPainter::draw_rect(Gfx::IntRect const& rect, Color color, bool rough) +void DisplayListRecorder::draw_rect(Gfx::IntRect const& rect, Color color, bool rough) { if (rect.is_empty()) return; @@ -185,7 +185,7 @@ void RecordingPainter::draw_rect(Gfx::IntRect const& rect, Color color, bool rou .rough = rough }); } -void RecordingPainter::draw_scaled_bitmap(Gfx::IntRect const& dst_rect, Gfx::Bitmap const& bitmap, Gfx::IntRect const& src_rect, Gfx::ScalingMode scaling_mode) +void DisplayListRecorder::draw_scaled_bitmap(Gfx::IntRect const& dst_rect, Gfx::Bitmap const& bitmap, Gfx::IntRect const& src_rect, Gfx::ScalingMode scaling_mode) { if (dst_rect.is_empty()) return; @@ -197,7 +197,7 @@ void RecordingPainter::draw_scaled_bitmap(Gfx::IntRect const& dst_rect, Gfx::Bit }); } -void RecordingPainter::draw_scaled_immutable_bitmap(Gfx::IntRect const& dst_rect, Gfx::ImmutableBitmap const& bitmap, Gfx::IntRect const& src_rect, Gfx::ScalingMode scaling_mode, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::draw_scaled_immutable_bitmap(Gfx::IntRect const& dst_rect, Gfx::ImmutableBitmap const& bitmap, Gfx::IntRect const& src_rect, Gfx::ScalingMode scaling_mode, Vector<Gfx::Path> const& clip_paths) { if (dst_rect.is_empty()) return; @@ -210,7 +210,7 @@ void RecordingPainter::draw_scaled_immutable_bitmap(Gfx::IntRect const& dst_rect }); } -void RecordingPainter::draw_line(Gfx::IntPoint from, Gfx::IntPoint to, Color color, int thickness, Gfx::LineStyle style, Color alternate_color) +void DisplayListRecorder::draw_line(Gfx::IntPoint from, Gfx::IntPoint to, Color color, int thickness, Gfx::LineStyle style, Color alternate_color) { append(DrawLine { .color = color, @@ -222,7 +222,7 @@ void RecordingPainter::draw_line(Gfx::IntPoint from, Gfx::IntPoint to, Color col }); } -void RecordingPainter::draw_text(Gfx::IntRect const& rect, String raw_text, Gfx::Font const& font, Gfx::TextAlignment alignment, Color color) +void DisplayListRecorder::draw_text(Gfx::IntRect const& rect, String raw_text, Gfx::Font const& font, Gfx::TextAlignment alignment, Color color) { if (rect.is_empty()) return; @@ -254,7 +254,7 @@ void RecordingPainter::draw_text(Gfx::IntRect const& rect, String raw_text, Gfx: draw_text_run(Gfx::IntPoint(roundf(baseline_x), roundf(baseline_y)), *glyph_run, color, rect, 1.0); } -void RecordingPainter::draw_text_run(Gfx::IntPoint baseline_start, Gfx::GlyphRun const& glyph_run, Color color, Gfx::IntRect const& rect, double scale) +void DisplayListRecorder::draw_text_run(Gfx::IntPoint baseline_start, Gfx::GlyphRun const& glyph_run, Color color, Gfx::IntRect const& rect, double scale) { if (rect.is_empty()) return; @@ -268,28 +268,28 @@ void RecordingPainter::draw_text_run(Gfx::IntPoint baseline_start, Gfx::GlyphRun }); } -void RecordingPainter::add_clip_rect(Gfx::IntRect const& rect) +void DisplayListRecorder::add_clip_rect(Gfx::IntRect const& rect) { append(AddClipRect { .rect = state().translation.map(rect) }); } -void RecordingPainter::translate(int dx, int dy) +void DisplayListRecorder::translate(int dx, int dy) { m_state_stack.last().translation.translate(dx, dy); } -void RecordingPainter::translate(Gfx::IntPoint delta) +void DisplayListRecorder::translate(Gfx::IntPoint delta) { m_state_stack.last().translation.translate(delta.to_type<float>()); } -void RecordingPainter::save() +void DisplayListRecorder::save() { append(Save {}); m_state_stack.append(m_state_stack.last()); } -void RecordingPainter::restore() +void DisplayListRecorder::restore() { append(Restore {}); @@ -297,7 +297,7 @@ void RecordingPainter::restore() m_state_stack.take_last(); } -void RecordingPainter::push_stacking_context(PushStackingContextParams params) +void DisplayListRecorder::push_stacking_context(PushStackingContextParams params) { append(PushStackingContext { .opacity = params.opacity, @@ -316,13 +316,13 @@ void RecordingPainter::push_stacking_context(PushStackingContextParams params) m_state_stack.append(State()); } -void RecordingPainter::pop_stacking_context() +void DisplayListRecorder::pop_stacking_context() { m_state_stack.take_last(); append(PopStackingContext {}); } -void RecordingPainter::apply_backdrop_filter(Gfx::IntRect const& backdrop_region, BorderRadiiData const& border_radii_data, CSS::ResolvedBackdropFilter const& backdrop_filter) +void DisplayListRecorder::apply_backdrop_filter(Gfx::IntRect const& backdrop_region, BorderRadiiData const& border_radii_data, CSS::ResolvedBackdropFilter const& backdrop_filter) { if (backdrop_region.is_empty()) return; @@ -333,18 +333,18 @@ void RecordingPainter::apply_backdrop_filter(Gfx::IntRect const& backdrop_region }); } -void RecordingPainter::paint_outer_box_shadow_params(PaintBoxShadowParams params) +void DisplayListRecorder::paint_outer_box_shadow_params(PaintBoxShadowParams params) { params.device_content_rect = state().translation.map(params.device_content_rect); append(PaintOuterBoxShadow { .box_shadow_params = params }); } -void RecordingPainter::paint_inner_box_shadow_params(PaintBoxShadowParams params) +void DisplayListRecorder::paint_inner_box_shadow_params(PaintBoxShadowParams params) { append(PaintInnerBoxShadow { .box_shadow_params = params }); } -void RecordingPainter::paint_text_shadow(int blur_radius, Gfx::IntRect bounding_rect, Gfx::IntRect text_rect, Span<Gfx::DrawGlyphOrEmoji const> glyph_run, Color color, int fragment_baseline, Gfx::IntPoint draw_location) +void DisplayListRecorder::paint_text_shadow(int blur_radius, Gfx::IntRect bounding_rect, Gfx::IntRect text_rect, Span<Gfx::DrawGlyphOrEmoji const> glyph_run, Color color, int fragment_baseline, Gfx::IntPoint draw_location) { append(PaintTextShadow { .blur_radius = blur_radius, @@ -356,7 +356,7 @@ void RecordingPainter::paint_text_shadow(int blur_radius, Gfx::IntRect bounding_ .draw_location = state().translation.map(draw_location) }); } -void RecordingPainter::fill_rect_with_rounded_corners(Gfx::IntRect const& rect, Color color, Gfx::AntiAliasingPainter::CornerRadius top_left_radius, Gfx::AntiAliasingPainter::CornerRadius top_right_radius, Gfx::AntiAliasingPainter::CornerRadius bottom_right_radius, Gfx::AntiAliasingPainter::CornerRadius bottom_left_radius, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::fill_rect_with_rounded_corners(Gfx::IntRect const& rect, Color color, Gfx::AntiAliasingPainter::CornerRadius top_left_radius, Gfx::AntiAliasingPainter::CornerRadius top_right_radius, Gfx::AntiAliasingPainter::CornerRadius bottom_right_radius, Gfx::AntiAliasingPainter::CornerRadius bottom_left_radius, Vector<Gfx::Path> const& clip_paths) { if (rect.is_empty()) return; @@ -377,14 +377,14 @@ void RecordingPainter::fill_rect_with_rounded_corners(Gfx::IntRect const& rect, }); } -void RecordingPainter::fill_rect_with_rounded_corners(Gfx::IntRect const& a_rect, Color color, int radius, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::fill_rect_with_rounded_corners(Gfx::IntRect const& a_rect, Color color, int radius, Vector<Gfx::Path> const& clip_paths) { if (a_rect.is_empty()) return; fill_rect_with_rounded_corners(a_rect, color, radius, radius, radius, radius, clip_paths); } -void RecordingPainter::fill_rect_with_rounded_corners(Gfx::IntRect const& a_rect, Color color, int top_left_radius, int top_right_radius, int bottom_right_radius, int bottom_left_radius, Vector<Gfx::Path> const& clip_paths) +void DisplayListRecorder::fill_rect_with_rounded_corners(Gfx::IntRect const& a_rect, Color color, int top_left_radius, int top_right_radius, int bottom_right_radius, int bottom_left_radius, Vector<Gfx::Path> const& clip_paths) { if (a_rect.is_empty()) return; @@ -396,7 +396,7 @@ void RecordingPainter::fill_rect_with_rounded_corners(Gfx::IntRect const& a_rect clip_paths); } -void RecordingPainter::draw_triangle_wave(Gfx::IntPoint a_p1, Gfx::IntPoint a_p2, Color color, int amplitude, int thickness = 1) +void DisplayListRecorder::draw_triangle_wave(Gfx::IntPoint a_p1, Gfx::IntPoint a_p2, Color color, int amplitude, int thickness = 1) { append(DrawTriangleWave { .p1 = state().translation.map(a_p1), diff --git a/Userland/Libraries/LibWeb/Painting/RecordingPainter.h b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.h similarity index 94% rename from Userland/Libraries/LibWeb/Painting/RecordingPainter.h rename to Userland/Libraries/LibWeb/Painting/DisplayListRecorder.h index e894649db302..90965b39b068 100644 --- a/Userland/Libraries/LibWeb/Painting/RecordingPainter.h +++ b/Userland/Libraries/LibWeb/Painting/DisplayListRecorder.h @@ -35,9 +35,9 @@ namespace Web::Painting { -class RecordingPainter { - AK_MAKE_NONCOPYABLE(RecordingPainter); - AK_MAKE_NONMOVABLE(RecordingPainter); +class DisplayListRecorder { + AK_MAKE_NONCOPYABLE(DisplayListRecorder); + AK_MAKE_NONMOVABLE(DisplayListRecorder); public: void fill_rect(Gfx::IntRect const& rect, Color color, Vector<Gfx::Path> const& clip_paths = {}); @@ -135,8 +135,8 @@ class RecordingPainter { void draw_triangle_wave(Gfx::IntPoint a_p1, Gfx::IntPoint a_p2, Color color, int amplitude, int thickness); - RecordingPainter(DisplayList&); - ~RecordingPainter(); + DisplayListRecorder(DisplayList&); + ~DisplayListRecorder(); DisplayList& display_list() { return m_command_list; } @@ -161,21 +161,21 @@ class RecordingPainter { DisplayList& m_command_list; }; -class RecordingPainterStateSaver { +class DisplayListRecorderStateSaver { public: - explicit RecordingPainterStateSaver(RecordingPainter& painter) + explicit DisplayListRecorderStateSaver(DisplayListRecorder& painter) : m_painter(painter) { m_painter.save(); } - ~RecordingPainterStateSaver() + ~DisplayListRecorderStateSaver() { m_painter.restore(); } private: - RecordingPainter& m_painter; + DisplayListRecorder& m_painter; }; } diff --git a/Userland/Libraries/LibWeb/Painting/FilterPainting.cpp b/Userland/Libraries/LibWeb/Painting/FilterPainting.cpp index 5cf5e9d87660..3f241193e08d 100644 --- a/Userland/Libraries/LibWeb/Painting/FilterPainting.cpp +++ b/Userland/Libraries/LibWeb/Painting/FilterPainting.cpp @@ -103,7 +103,7 @@ void apply_backdrop_filter(PaintContext& context, CSSPixelRect const& backdrop_r auto backdrop_region = context.rounded_device_rect(backdrop_rect); ScopedCornerRadiusClip corner_clipper { context, backdrop_region, border_radii_data }; - context.recording_painter().apply_backdrop_filter(backdrop_region.to_type<int>(), border_radii_data, backdrop_filter); + context.display_list_recorder().apply_backdrop_filter(backdrop_region.to_type<int>(), border_radii_data, backdrop_filter); } } diff --git a/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp b/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp index e5be9444c097..175cec699e95 100644 --- a/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/ImagePaintable.cpp @@ -65,8 +65,8 @@ void ImagePaintable::paint(PaintContext& context, PaintPhase phase) const auto image_rect = context.rounded_device_rect(absolute_rect()); if (m_renders_as_alt_text) { auto enclosing_rect = context.enclosing_device_rect(absolute_rect()).to_type<int>(); - context.recording_painter().draw_rect(enclosing_rect, Gfx::Color::Black); - context.recording_painter().draw_text(enclosing_rect, m_alt_text, Platform::FontPlugin::the().default_font(), Gfx::TextAlignment::Center, computed_values().color()); + context.display_list_recorder().draw_rect(enclosing_rect, Gfx::Color::Black); + context.display_list_recorder().draw_text(enclosing_rect, m_alt_text, Platform::FontPlugin::the().default_font(), Gfx::TextAlignment::Center, computed_values().color()); } else if (auto bitmap = m_image_provider.current_image_bitmap(image_rect.size().to_type<int>())) { ScopedCornerRadiusClip corner_clip { context, image_rect, normalized_border_radii_data(ShrinkRadiiForBorders::Yes) }; auto image_int_rect = image_rect.to_type<int>(); @@ -150,7 +150,7 @@ void ImagePaintable::paint(PaintContext& context, PaintPhase phase) const (int)scaled_bitmap_height }; - context.recording_painter().draw_scaled_immutable_bitmap(draw_rect.intersected(image_int_rect), *bitmap, bitmap_rect.intersected(bitmap_intersect), scaling_mode); + context.display_list_recorder().draw_scaled_immutable_bitmap(draw_rect.intersected(image_int_rect), *bitmap, bitmap_rect.intersected(bitmap_intersect), scaling_mode); } } } diff --git a/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp b/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp index 4f230494cd67..ae5a2beb5f0d 100644 --- a/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/InlinePaintable.cpp @@ -33,26 +33,26 @@ Layout::InlineNode const& InlinePaintable::layout_node() const void InlinePaintable::before_paint(PaintContext& context, PaintPhase) const { if (scroll_frame_id().has_value()) { - context.recording_painter().save(); - context.recording_painter().set_scroll_frame_id(scroll_frame_id().value()); + context.display_list_recorder().save(); + context.display_list_recorder().set_scroll_frame_id(scroll_frame_id().value()); } if (clip_rect().has_value()) { - context.recording_painter().save(); - context.recording_painter().add_clip_rect(context.enclosing_device_rect(*clip_rect()).to_type<int>()); + context.display_list_recorder().save(); + context.display_list_recorder().add_clip_rect(context.enclosing_device_rect(*clip_rect()).to_type<int>()); } } void InlinePaintable::after_paint(PaintContext& context, PaintPhase) const { if (clip_rect().has_value()) - context.recording_painter().restore(); + context.display_list_recorder().restore(); if (scroll_frame_id().has_value()) - context.recording_painter().restore(); + context.display_list_recorder().restore(); } void InlinePaintable::paint(PaintContext& context, PaintPhase phase) const { - auto& painter = context.recording_painter(); + auto& display_list_recorder = context.display_list_recorder(); if (phase == PaintPhase::Background) { auto containing_block_position_in_absolute_coordinates = containing_block()->absolute_position(); @@ -141,9 +141,9 @@ void InlinePaintable::paint(PaintContext& context, PaintPhase phase) const border_radii_data.inflate(outline_data->top.width + outline_offset_y, outline_data->right.width + outline_offset_x, outline_data->bottom.width + outline_offset_y, outline_data->left.width + outline_offset_x); borders_rect.inflate(outline_data->top.width + outline_offset_y, outline_data->right.width + outline_offset_x, outline_data->bottom.width + outline_offset_y, outline_data->left.width + outline_offset_x); - paint_all_borders(context.recording_painter(), context.rounded_device_rect(borders_rect), border_radii_data.as_corners(context), outline_data->to_device_pixels(context)); + paint_all_borders(context.display_list_recorder(), context.rounded_device_rect(borders_rect), border_radii_data.as_corners(context), outline_data->to_device_pixels(context)); } else { - paint_all_borders(context.recording_painter(), context.rounded_device_rect(borders_rect), border_radii_data.as_corners(context), borders_data.to_device_pixels(context)); + paint_all_borders(context.display_list_recorder(), context.rounded_device_rect(borders_rect), border_radii_data.as_corners(context), borders_data.to_device_pixels(context)); } return IterationDecision::Continue; @@ -172,7 +172,7 @@ void InlinePaintable::paint(PaintContext& context, PaintPhase phase) const // would be none. Once we implement non-rectangular outlines for the `outline` CSS // property, we can use that here instead. for_each_fragment([&](auto const& fragment, bool, bool) { - painter.draw_rect(context.enclosing_device_rect(fragment.absolute_rect()).template to_type<int>(), Color::Magenta); + display_list_recorder.draw_rect(context.enclosing_device_rect(fragment.absolute_rect()).template to_type<int>(), Color::Magenta); return IterationDecision::Continue; }); } diff --git a/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp b/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp index 65246a277aa1..739c759ee5fa 100644 --- a/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp @@ -69,13 +69,13 @@ void MarkerPaintable::paint(PaintContext& context, PaintPhase phase) const switch (layout_box().list_style_type()) { case CSS::ListStyleType::Square: - context.recording_painter().fill_rect(device_marker_rect.to_type<int>(), color); + context.display_list_recorder().fill_rect(device_marker_rect.to_type<int>(), color); break; case CSS::ListStyleType::Circle: - context.recording_painter().draw_ellipse(device_marker_rect.to_type<int>(), color, 1); + context.display_list_recorder().draw_ellipse(device_marker_rect.to_type<int>(), color, 1); break; case CSS::ListStyleType::Disc: - context.recording_painter().fill_ellipse(device_marker_rect.to_type<int>(), color); + context.display_list_recorder().fill_ellipse(device_marker_rect.to_type<int>(), color); break; case CSS::ListStyleType::DisclosureClosed: { // https://drafts.csswg.org/css-counter-styles-3/#disclosure-closed @@ -88,7 +88,7 @@ void MarkerPaintable::paint(PaintContext& context, PaintPhase phase) const path.line_to({ left + sin_60_deg * (right - left), (top + bottom) / 2 }); path.line_to({ left, bottom }); path.close(); - context.recording_painter().fill_path({ .path = path, .color = color, .winding_rule = Gfx::WindingRule::EvenOdd }); + context.display_list_recorder().fill_path({ .path = path, .color = color, .winding_rule = Gfx::WindingRule::EvenOdd }); break; } case CSS::ListStyleType::DisclosureOpen: { @@ -102,7 +102,7 @@ void MarkerPaintable::paint(PaintContext& context, PaintPhase phase) const path.line_to({ right, top }); path.line_to({ (left + right) / 2, top + sin_60_deg * (bottom - top) }); path.close(); - context.recording_painter().fill_path({ .path = path, .color = color, .winding_rule = Gfx::WindingRule::EvenOdd }); + context.display_list_recorder().fill_path({ .path = path, .color = color, .winding_rule = Gfx::WindingRule::EvenOdd }); break; } case CSS::ListStyleType::Decimal: @@ -118,7 +118,7 @@ void MarkerPaintable::paint(PaintContext& context, PaintPhase phase) const break; // FIXME: This should use proper text layout logic! // This does not line up with the text in the <li> element which looks very sad :( - context.recording_painter().draw_text(device_enclosing.to_type<int>(), MUST(String::from_byte_string(*text)), layout_box().scaled_font(context), Gfx::TextAlignment::Center, color); + context.display_list_recorder().draw_text(device_enclosing.to_type<int>(), MUST(String::from_byte_string(*text)), layout_box().scaled_font(context), Gfx::TextAlignment::Center, color); break; } case CSS::ListStyleType::None: diff --git a/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp b/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp index aa30370708f2..422bb0d7d69e 100644 --- a/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/MediaPaintable.cpp @@ -44,7 +44,7 @@ Optional<DevicePixelPoint> MediaPaintable::mouse_position(PaintContext& context, return {}; } -void MediaPaintable::fill_triangle(RecordingPainter& painter, Gfx::IntPoint location, Array<Gfx::IntPoint, 3> coordinates, Color color) +void MediaPaintable::fill_triangle(DisplayListRecorder& painter, Gfx::IntPoint location, Array<Gfx::IntPoint, 3> coordinates, Color color) { Gfx::Path path; path.move_to((coordinates[0] + location).to_type<float>()); @@ -61,7 +61,7 @@ void MediaPaintable::fill_triangle(RecordingPainter& painter, Gfx::IntPoint loca void MediaPaintable::paint_media_controls(PaintContext& context, HTML::HTMLMediaElement const& media_element, DevicePixelRect media_rect, Optional<DevicePixelPoint> const& mouse_position) const { auto components = compute_control_bar_components(context, media_element, media_rect); - context.recording_painter().fill_rect(components.control_box_rect.to_type<int>(), control_box_color.with_alpha(0xd0)); + context.display_list_recorder().fill_rect(components.control_box_rect.to_type<int>(), control_box_color.with_alpha(0xd0)); paint_control_bar_playback_button(context, media_element, components, mouse_position); paint_control_bar_timeline(context, media_element, components); @@ -155,7 +155,7 @@ void MediaPaintable::paint_control_bar_playback_button(PaintContext& context, HT { 0, static_cast<int>(playback_button_size) }, } }; - fill_triangle(context.recording_painter(), playback_button_location.to_type<int>(), play_button_coordinates, playback_button_color); + fill_triangle(context.display_list_recorder(), playback_button_location.to_type<int>(), play_button_coordinates, playback_button_color); } else { DevicePixelRect pause_button_left_rect { playback_button_location, @@ -166,8 +166,8 @@ void MediaPaintable::paint_control_bar_playback_button(PaintContext& context, HT { playback_button_size / 3, playback_button_size } }; - context.recording_painter().fill_rect(pause_button_left_rect.to_type<int>(), playback_button_color); - context.recording_painter().fill_rect(pause_button_right_rect.to_type<int>(), playback_button_color); + context.display_list_recorder().fill_rect(pause_button_left_rect.to_type<int>(), playback_button_color); + context.display_list_recorder().fill_rect(pause_button_right_rect.to_type<int>(), playback_button_color); } } @@ -182,11 +182,11 @@ void MediaPaintable::paint_control_bar_timeline(PaintContext& context, HTML::HTM auto timeline_past_rect = components.timeline_rect; timeline_past_rect.set_width(timeline_button_offset_x); - context.recording_painter().fill_rect(timeline_past_rect.to_type<int>(), control_highlight_color.lightened()); + context.display_list_recorder().fill_rect(timeline_past_rect.to_type<int>(), control_highlight_color.lightened()); auto timeline_future_rect = components.timeline_rect; timeline_future_rect.take_from_left(timeline_button_offset_x); - context.recording_painter().fill_rect(timeline_future_rect.to_type<int>(), Color::Black); + context.display_list_recorder().fill_rect(timeline_future_rect.to_type<int>(), Color::Black); } void MediaPaintable::paint_control_bar_timestamp(PaintContext& context, Components const& components) @@ -194,7 +194,7 @@ void MediaPaintable::paint_control_bar_timestamp(PaintContext& context, Componen if (components.timestamp_rect.is_empty()) return; - context.recording_painter().draw_text(components.timestamp_rect.to_type<int>(), components.timestamp, *components.timestamp_font, Gfx::TextAlignment::CenterLeft, Color::White); + context.display_list_recorder().draw_text(components.timestamp_rect.to_type<int>(), components.timestamp, *components.timestamp_font, Gfx::TextAlignment::CenterLeft, Color::White); } void MediaPaintable::paint_control_bar_speaker(PaintContext& context, HTML::HTMLMediaElement const& media_element, Components const& components, Optional<DevicePixelPoint> const& mouse_position) @@ -227,18 +227,18 @@ void MediaPaintable::paint_control_bar_speaker(PaintContext& context, HTML::HTML path.line_to(device_point(0, 11)); path.line_to(device_point(0, 4)); path.close(); - context.recording_painter().fill_path({ .path = path, .color = speaker_button_color, .winding_rule = Gfx::WindingRule::EvenOdd }); + context.display_list_recorder().fill_path({ .path = path, .color = speaker_button_color, .winding_rule = Gfx::WindingRule::EvenOdd }); path.clear(); path.move_to(device_point(13, 3)); path.quadratic_bezier_curve_to(device_point(16, 7.5), device_point(13, 12)); path.move_to(device_point(14, 0)); path.quadratic_bezier_curve_to(device_point(20, 7.5), device_point(14, 15)); - context.recording_painter().stroke_path({ .path = path, .color = speaker_button_color, .thickness = 1 }); + context.display_list_recorder().stroke_path({ .path = path, .color = speaker_button_color, .thickness = 1 }); if (media_element.muted()) { - context.recording_painter().draw_line(device_point(0, 0).to_type<int>(), device_point(20, 15).to_type<int>(), Color::Red, 2); - context.recording_painter().draw_line(device_point(0, 15).to_type<int>(), device_point(20, 0).to_type<int>(), Color::Red, 2); + context.display_list_recorder().draw_line(device_point(0, 0).to_type<int>(), device_point(20, 15).to_type<int>(), Color::Red, 2); + context.display_list_recorder().draw_line(device_point(0, 15).to_type<int>(), device_point(20, 0).to_type<int>(), Color::Red, 2); } } @@ -252,11 +252,11 @@ void MediaPaintable::paint_control_bar_volume(PaintContext& context, HTML::HTMLM auto volume_lower_rect = components.volume_scrub_rect; volume_lower_rect.set_width(volume_button_offset_x); - context.recording_painter().fill_rect_with_rounded_corners(volume_lower_rect.to_type<int>(), control_highlight_color.lightened(), 4); + context.display_list_recorder().fill_rect_with_rounded_corners(volume_lower_rect.to_type<int>(), control_highlight_color.lightened(), 4); auto volume_higher_rect = components.volume_scrub_rect; volume_higher_rect.take_from_left(volume_button_offset_x); - context.recording_painter().fill_rect_with_rounded_corners(volume_higher_rect.to_type<int>(), Color::Black, 4); + context.display_list_recorder().fill_rect_with_rounded_corners(volume_higher_rect.to_type<int>(), Color::Black, 4); auto volume_button_rect = components.volume_scrub_rect; volume_button_rect.shrink(components.volume_scrub_rect.width() - components.volume_button_size, components.volume_scrub_rect.height() - components.volume_button_size); @@ -264,7 +264,7 @@ void MediaPaintable::paint_control_bar_volume(PaintContext& context, HTML::HTMLM auto volume_is_hovered = rect_is_hovered(media_element, components.volume_rect, mouse_position, HTML::HTMLMediaElement::MouseTrackingComponent::Volume); auto volume_color = control_button_color(volume_is_hovered); - context.recording_painter().fill_ellipse(volume_button_rect.to_type<int>(), volume_color); + context.display_list_recorder().fill_ellipse(volume_button_rect.to_type<int>(), volume_color); } MediaPaintable::DispatchEventOfSameName MediaPaintable::handle_mousedown(Badge<EventHandler>, CSSPixelPoint position, unsigned button, unsigned) diff --git a/Userland/Libraries/LibWeb/Painting/MediaPaintable.h b/Userland/Libraries/LibWeb/Painting/MediaPaintable.h index eecabf571923..d4efc4eb973d 100644 --- a/Userland/Libraries/LibWeb/Painting/MediaPaintable.h +++ b/Userland/Libraries/LibWeb/Painting/MediaPaintable.h @@ -20,7 +20,7 @@ class MediaPaintable : public PaintableBox { explicit MediaPaintable(Layout::ReplacedBox const&); static Optional<DevicePixelPoint> mouse_position(PaintContext&, HTML::HTMLMediaElement const&); - static void fill_triangle(RecordingPainter& painter, Gfx::IntPoint location, Array<Gfx::IntPoint, 3> coordinates, Color color); + static void fill_triangle(DisplayListRecorder& painter, Gfx::IntPoint location, Array<Gfx::IntPoint, 3> coordinates, Color color); void paint_media_controls(PaintContext&, HTML::HTMLMediaElement const&, DevicePixelRect media_rect, Optional<DevicePixelPoint> const& mouse_position) const; diff --git a/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp b/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp index 0be606ecd37f..84e6722f7651 100644 --- a/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/NestedBrowsingContextPaintable.cpp @@ -50,23 +50,23 @@ void NestedBrowsingContextPaintable::paint(PaintContext& context, PaintPhase pha if (!hosted_paint_tree) return; - context.recording_painter().save(); + context.display_list_recorder().save(); - context.recording_painter().add_clip_rect(clip_rect.to_type<int>()); + context.display_list_recorder().add_clip_rect(clip_rect.to_type<int>()); auto absolute_device_rect = context.enclosing_device_rect(absolute_rect); - context.recording_painter().translate(absolute_device_rect.x().value(), absolute_device_rect.y().value()); + context.display_list_recorder().translate(absolute_device_rect.x().value(), absolute_device_rect.y().value()); HTML::Navigable::PaintConfig paint_config; paint_config.paint_overlay = context.should_paint_overlay(); paint_config.should_show_line_box_borders = context.should_show_line_box_borders(); paint_config.has_focus = context.has_focus(); - const_cast<DOM::Document*>(hosted_document)->navigable()->record_display_list(context.recording_painter(), paint_config); + const_cast<DOM::Document*>(hosted_document)->navigable()->record_display_list(context.display_list_recorder(), paint_config); - context.recording_painter().restore(); + context.display_list_recorder().restore(); if constexpr (HIGHLIGHT_FOCUSED_FRAME_DEBUG) { if (layout_box().dom_node().content_navigable()->is_focused()) { - context.recording_painter().draw_rect(clip_rect.to_type<int>(), Color::Cyan); + context.display_list_recorder().draw_rect(clip_rect.to_type<int>(), Color::Cyan); } } } diff --git a/Userland/Libraries/LibWeb/Painting/PaintContext.cpp b/Userland/Libraries/LibWeb/Painting/PaintContext.cpp index e99363c9e380..d9753c554111 100644 --- a/Userland/Libraries/LibWeb/Painting/PaintContext.cpp +++ b/Userland/Libraries/LibWeb/Painting/PaintContext.cpp @@ -11,8 +11,8 @@ namespace Web { static u64 s_next_paint_generation_id = 0; -PaintContext::PaintContext(Painting::RecordingPainter& recording_painter, Palette const& palette, double device_pixels_per_css_pixel) - : m_recording_painter(recording_painter) +PaintContext::PaintContext(Painting::DisplayListRecorder& display_list_recorder, Palette const& palette, double device_pixels_per_css_pixel) + : m_display_list_recorder(display_list_recorder) , m_palette(palette) , m_device_pixels_per_css_pixel(device_pixels_per_css_pixel) , m_paint_generation_id(s_next_paint_generation_id++) diff --git a/Userland/Libraries/LibWeb/Painting/PaintContext.h b/Userland/Libraries/LibWeb/Painting/PaintContext.h index 0cf0157eba50..51dfdd9882bd 100644 --- a/Userland/Libraries/LibWeb/Painting/PaintContext.h +++ b/Userland/Libraries/LibWeb/Painting/PaintContext.h @@ -11,16 +11,16 @@ #include <LibGfx/Forward.h> #include <LibGfx/Palette.h> #include <LibGfx/Rect.h> -#include <LibWeb/Painting/RecordingPainter.h> +#include <LibWeb/Painting/DisplayListRecorder.h> #include <LibWeb/PixelUnits.h> namespace Web { class PaintContext { public: - PaintContext(Painting::RecordingPainter& painter, Palette const& palette, double device_pixels_per_css_pixel); + PaintContext(Painting::DisplayListRecorder& painter, Palette const& palette, double device_pixels_per_css_pixel); - Painting::RecordingPainter& recording_painter() const { return m_recording_painter; } + Painting::DisplayListRecorder& display_list_recorder() const { return m_display_list_recorder; } Palette const& palette() const { return m_palette; } bool should_show_line_box_borders() const { return m_should_show_line_box_borders; } @@ -70,7 +70,7 @@ class PaintContext { CSSPixelSize scale_to_css_size(DevicePixelSize) const; CSSPixelRect scale_to_css_rect(DevicePixelRect) const; - PaintContext clone(Painting::RecordingPainter& painter) const + PaintContext clone(Painting::DisplayListRecorder& painter) const { auto clone = PaintContext(painter, m_palette, m_device_pixels_per_css_pixel); clone.m_device_viewport_rect = m_device_viewport_rect; @@ -87,7 +87,7 @@ class PaintContext { u64 paint_generation_id() const { return m_paint_generation_id; } private: - Painting::RecordingPainter& m_recording_painter; + Painting::DisplayListRecorder& m_display_list_recorder; Palette m_palette; double m_device_pixels_per_css_pixel { 0 }; DevicePixelRect m_device_viewport_rect; diff --git a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp index 641138eef32a..70fc9765dbc6 100644 --- a/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp +++ b/Userland/Libraries/LibWeb/Painting/PaintableBox.cpp @@ -333,7 +333,7 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const border_radius_data.inflate(outline_data->top.width + outline_offset_y, outline_data->right.width + outline_offset_x, outline_data->bottom.width + outline_offset_y, outline_data->left.width + outline_offset_x); borders_rect.inflate(outline_data->top.width + outline_offset_y, outline_data->right.width + outline_offset_x, outline_data->bottom.width + outline_offset_y, outline_data->left.width + outline_offset_x); - paint_all_borders(context.recording_painter(), context.rounded_device_rect(borders_rect), border_radius_data.as_corners(context), outline_data->to_device_pixels(context)); + paint_all_borders(context.display_list_recorder(), context.rounded_device_rect(borders_rect), border_radius_data.as_corners(context), outline_data->to_device_pixels(context)); } } @@ -343,11 +343,11 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const int thumb_corner_radius = static_cast<int>(context.rounded_device_pixels(scrollbar_thumb_thickness / 2)); if (auto thumb_rect = scroll_thumb_rect(ScrollDirection::Horizontal); thumb_rect.has_value()) { auto thumb_device_rect = context.enclosing_device_rect(thumb_rect.value()); - context.recording_painter().fill_rect_with_rounded_corners(thumb_device_rect.to_type<int>(), color, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius); + context.display_list_recorder().fill_rect_with_rounded_corners(thumb_device_rect.to_type<int>(), color, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius); } if (auto thumb_rect = scroll_thumb_rect(ScrollDirection::Vertical); thumb_rect.has_value()) { auto thumb_device_rect = context.enclosing_device_rect(thumb_rect.value()); - context.recording_painter().fill_rect_with_rounded_corners(thumb_device_rect.to_type<int>(), color, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius); + context.display_list_recorder().fill_rect_with_rounded_corners(thumb_device_rect.to_type<int>(), color, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius, thumb_corner_radius); } } @@ -366,8 +366,8 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const auto paint_inspector_rect = [&](CSSPixelRect const& rect, Color color) { auto device_rect = context.enclosing_device_rect(rect).to_type<int>(); - context.recording_painter().fill_rect(device_rect, Color(color).with_alpha(100)); - context.recording_painter().draw_rect(device_rect, Color(color)); + context.display_list_recorder().fill_rect(device_rect, Color(color).with_alpha(100)); + context.display_list_recorder().draw_rect(device_rect, Color(color)); }; paint_inspector_rect(margin_rect, Color::Yellow); @@ -390,9 +390,9 @@ void PaintableBox::paint(PaintContext& context, PaintPhase phase) const size_text_rect.set_width(CSSPixels::nearest_value_for(font.width(size_text)) + 4); size_text_rect.set_height(CSSPixels::nearest_value_for(font.pixel_size()) + 4); auto size_text_device_rect = context.enclosing_device_rect(size_text_rect).to_type<int>(); - context.recording_painter().fill_rect(size_text_device_rect, context.palette().color(Gfx::ColorRole::Tooltip)); - context.recording_painter().draw_rect(size_text_device_rect, context.palette().threed_shadow1()); - context.recording_painter().draw_text(size_text_device_rect, size_text, font, Gfx::TextAlignment::Center, context.palette().color(Gfx::ColorRole::TooltipText)); + context.display_list_recorder().fill_rect(size_text_device_rect, context.palette().color(Gfx::ColorRole::Tooltip)); + context.display_list_recorder().draw_rect(size_text_device_rect, context.palette().threed_shadow1()); + context.display_list_recorder().draw_text(size_text_device_rect, size_text, font, Gfx::TextAlignment::Center, context.palette().color(Gfx::ColorRole::TooltipText)); } } @@ -414,7 +414,7 @@ void PaintableBox::paint_border(PaintContext& context) const .bottom = box_model().border.bottom == 0 ? CSS::BorderData() : computed_values().border_bottom(), .left = box_model().border.left == 0 ? CSS::BorderData() : computed_values().border_left(), }; - paint_all_borders(context.recording_painter(), context.rounded_device_rect(absolute_border_box_rect()), normalized_border_radii_data().as_corners(context), borders_data.to_device_pixels(context)); + paint_all_borders(context.display_list_recorder(), context.rounded_device_rect(absolute_border_box_rect()), normalized_border_radii_data().as_corners(context), borders_data.to_device_pixels(context)); } void PaintableBox::paint_backdrop_filter(PaintContext& context) const @@ -482,15 +482,15 @@ BorderRadiiData PaintableBox::normalized_border_radii_data(ShrinkRadiiForBorders void PaintableBox::apply_scroll_offset(PaintContext& context, PaintPhase) const { if (scroll_frame_id().has_value()) { - context.recording_painter().save(); - context.recording_painter().set_scroll_frame_id(scroll_frame_id().value()); + context.display_list_recorder().save(); + context.display_list_recorder().set_scroll_frame_id(scroll_frame_id().value()); } } void PaintableBox::reset_scroll_offset(PaintContext& context, PaintPhase) const { if (scroll_frame_id().has_value()) - context.recording_painter().restore(); + context.display_list_recorder().restore(); } void PaintableBox::apply_clip_overflow_rect(PaintContext& context, PaintPhase phase) const @@ -501,8 +501,8 @@ void PaintableBox::apply_clip_overflow_rect(PaintContext& context, PaintPhase ph if (clip_rect().has_value()) { auto overflow_clip_rect = clip_rect().value(); m_clipping_overflow = true; - context.recording_painter().save(); - context.recording_painter().add_clip_rect(context.enclosing_device_rect(overflow_clip_rect).to_type<int>()); + context.display_list_recorder().save(); + context.display_list_recorder().add_clip_rect(context.enclosing_device_rect(overflow_clip_rect).to_type<int>()); auto const& border_radii_clips = this->border_radii_clips(); m_corner_clipper_ids.resize(border_radii_clips.size()); auto const& combined_transform = combined_css_transform(); @@ -514,7 +514,7 @@ void PaintableBox::apply_clip_overflow_rect(PaintContext& context, PaintPhase ph auto corner_clipper_id = context.allocate_corner_clipper_id(); m_corner_clipper_ids[corner_clip_index] = corner_clipper_id; auto rect = corner_clip.rect.translated(-combined_transform.translation().to_type<CSSPixels>()); - context.recording_painter().sample_under_corners(corner_clipper_id, corner_clip.radii.as_corners(context), context.rounded_device_rect(rect).to_type<int>(), CornerClip::Outside); + context.display_list_recorder().sample_under_corners(corner_clipper_id, corner_clip.radii.as_corners(context), context.rounded_device_rect(rect).to_type<int>(), CornerClip::Outside); } } } @@ -534,9 +534,9 @@ void PaintableBox::clear_clip_overflow_rect(PaintContext& context, PaintPhase ph continue; auto corner_clipper_id = m_corner_clipper_ids[corner_clip_index]; m_corner_clipper_ids[corner_clip_index] = corner_clipper_id; - context.recording_painter().blit_corner_clipping(corner_clipper_id); + context.display_list_recorder().blit_corner_clipping(corner_clipper_id); } - context.recording_painter().restore(); + context.display_list_recorder().restore(); } } @@ -572,12 +572,12 @@ void paint_cursor_if_needed(PaintContext& context, TextPaintable const& paintabl auto cursor_device_rect = context.rounded_device_rect(cursor_rect).to_type<int>(); - context.recording_painter().draw_rect(cursor_device_rect, paintable.computed_values().color()); + context.display_list_recorder().draw_rect(cursor_device_rect, paintable.computed_values().color()); } void paint_text_decoration(PaintContext& context, TextPaintable const& paintable, PaintableFragment const& fragment) { - auto& painter = context.recording_painter(); + auto& painter = context.display_list_recorder(); auto& font = fragment.layout_node().first_available_font(); auto fragment_box = fragment.absolute_rect(); CSSPixels glyph_height = CSSPixels::nearest_value_for(font.pixel_size()); @@ -652,14 +652,14 @@ void paint_text_decoration(PaintContext& context, TextPaintable const& paintable void paint_text_fragment(PaintContext& context, TextPaintable const& paintable, PaintableFragment const& fragment, PaintPhase phase) { - auto& painter = context.recording_painter(); + auto& painter = context.display_list_recorder(); if (phase == PaintPhase::Foreground) { auto fragment_absolute_rect = fragment.absolute_rect(); auto fragment_absolute_device_rect = context.enclosing_device_rect(fragment_absolute_rect); if (paintable.document().inspected_layout_node() == &paintable.layout_node()) - context.recording_painter().draw_rect(fragment_absolute_device_rect.to_type<int>(), Color::Magenta); + context.display_list_recorder().draw_rect(fragment_absolute_device_rect.to_type<int>(), Color::Magenta); auto text = paintable.text_for_rendering(); @@ -670,7 +670,7 @@ void paint_text_fragment(PaintContext& context, TextPaintable const& paintable, auto selection_rect = context.enclosing_device_rect(fragment.selection_rect(paintable.layout_node().first_available_font())).to_type<int>(); if (!selection_rect.is_empty()) { painter.fill_rect(selection_rect, CSS::SystemColor::highlight()); - RecordingPainterStateSaver saver(painter); + DisplayListRecorderStateSaver saver(painter); painter.add_clip_rect(selection_rect); painter.draw_text_run(baseline_start.to_type<int>(), fragment.glyph_run(), CSS::SystemColor::highlight_text(), fragment_absolute_device_rect.to_type<int>(), scale); } @@ -699,12 +699,12 @@ void PaintableWithLines::paint(PaintContext& context, PaintPhase phase) const should_clip_overflow = true; } if (should_clip_overflow) { - context.recording_painter().save(); + context.display_list_recorder().save(); // FIXME: Handle overflow-x and overflow-y being different values. auto clip_box_with_enclosing_scroll_frame_offset = clip_box; if (enclosing_scroll_frame_offset().has_value()) clip_box_with_enclosing_scroll_frame_offset.translate_by(enclosing_scroll_frame_offset().value()); - context.recording_painter().add_clip_rect(context.rounded_device_rect(clip_box_with_enclosing_scroll_frame_offset).to_type<int>()); + context.display_list_recorder().add_clip_rect(context.rounded_device_rect(clip_box_with_enclosing_scroll_frame_offset).to_type<int>()); auto border_radii = normalized_border_radii_data(ShrinkRadiiForBorders::Yes); CornerRadii corner_radii { @@ -715,12 +715,12 @@ void PaintableWithLines::paint(PaintContext& context, PaintPhase phase) const }; if (corner_radii.has_any_radius()) { corner_clip_id = context.allocate_corner_clipper_id(); - context.recording_painter().sample_under_corners(*corner_clip_id, corner_radii, context.rounded_device_rect(clip_box).to_type<int>(), CornerClip::Outside); + context.display_list_recorder().sample_under_corners(*corner_clip_id, corner_radii, context.rounded_device_rect(clip_box).to_type<int>(), CornerClip::Outside); } - context.recording_painter().save(); + context.display_list_recorder().save(); auto scroll_offset = context.rounded_device_point(this->scroll_offset()); - context.recording_painter().translate(-scroll_offset.to_type<int>()); + context.display_list_recorder().translate(-scroll_offset.to_type<int>()); } // Text shadows @@ -737,8 +737,8 @@ void PaintableWithLines::paint(PaintContext& context, PaintPhase phase) const auto fragment_absolute_rect = fragment.absolute_rect(); auto fragment_absolute_device_rect = context.enclosing_device_rect(fragment_absolute_rect); if (context.should_show_line_box_borders()) { - context.recording_painter().draw_rect(fragment_absolute_device_rect.to_type<int>(), Color::Green); - context.recording_painter().draw_line( + context.display_list_recorder().draw_rect(fragment_absolute_device_rect.to_type<int>(), Color::Green); + context.display_list_recorder().draw_line( context.rounded_device_point(fragment_absolute_rect.top_left().translated(0, fragment.baseline())).to_type<int>(), context.rounded_device_point(fragment_absolute_rect.top_right().translated(-1, fragment.baseline())).to_type<int>(), Color::Red); } @@ -747,12 +747,12 @@ void PaintableWithLines::paint(PaintContext& context, PaintPhase phase) const } if (should_clip_overflow) { - context.recording_painter().restore(); + context.display_list_recorder().restore(); if (corner_clip_id.has_value()) { - context.recording_painter().blit_corner_clipping(*corner_clip_id); + context.display_list_recorder().blit_corner_clipping(*corner_clip_id); corner_clip_id = {}; } - context.recording_painter().restore(); + context.display_list_recorder().restore(); } } diff --git a/Userland/Libraries/LibWeb/Painting/RadioButtonPaintable.cpp b/Userland/Libraries/LibWeb/Painting/RadioButtonPaintable.cpp index 8f25ee9a722f..70b88b637923 100644 --- a/Userland/Libraries/LibWeb/Painting/RadioButtonPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/RadioButtonPaintable.cpp @@ -40,7 +40,7 @@ void RadioButtonPaintable::paint(PaintContext& context, PaintPhase phase) const auto draw_circle = [&](auto const& rect, Color color) { // Note: Doing this is a bit more forgiving than draw_circle() which will round to the nearset even radius. // This will fudge it (which works better here). - context.recording_painter().fill_rect_with_rounded_corners(rect, color, rect.width() / 2); + context.display_list_recorder().fill_rect_with_rounded_corners(rect, color, rect.width() / 2); }; auto shrink_all = [&](auto const& rect, int amount) { diff --git a/Userland/Libraries/LibWeb/Painting/SVGMaskable.cpp b/Userland/Libraries/LibWeb/Painting/SVGMaskable.cpp index 6e50cebbc01c..75c4f665f6ea 100644 --- a/Userland/Libraries/LibWeb/Painting/SVGMaskable.cpp +++ b/Userland/Libraries/LibWeb/Painting/SVGMaskable.cpp @@ -82,9 +82,9 @@ RefPtr<Gfx::Bitmap> SVGMaskable::calculate_mask_of_svg(PaintContext& context, CS return {}; mask_bitmap = mask_bitmap_or_error.release_value(); DisplayList display_list; - RecordingPainter recording_painter(display_list); - recording_painter.translate(-mask_rect.location().to_type<int>()); - auto paint_context = context.clone(recording_painter); + DisplayListRecorder display_list_recorder(display_list); + display_list_recorder.translate(-mask_rect.location().to_type<int>()); + auto paint_context = context.clone(display_list_recorder); paint_context.set_svg_transform(graphics_element.get_transform()); paint_context.set_draw_svg_geometry_for_clip_path(is<SVGClipPaintable>(paintable)); StackingContext::paint_node_as_stacking_context(paintable, paint_context); diff --git a/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp b/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp index cde608905bf6..b532c27bdc51 100644 --- a/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/SVGPathPaintable.cpp @@ -66,7 +66,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const auto svg_element_rect = svg_node->paintable_box()->absolute_rect(); // FIXME: This should not be trucated to an int. - RecordingPainterStateSaver save_painter { context.recording_painter() }; + DisplayListRecorderStateSaver save_painter { context.display_list_recorder() }; auto offset = context.floored_device_point(svg_element_rect.location()).to_type<int>().to_type<float>(); auto maybe_view_box = svg_node->dom_node().view_box(); @@ -98,7 +98,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const // The raw geometry of each child element exclusive of rendering properties such as fill, stroke, stroke-width // within a clipPath conceptually defines a 1-bit mask (with the possible exception of anti-aliasing along // the edge of the geometry) which represents the silhouette of the graphics associated with that element. - context.recording_painter().fill_path({ + context.display_list_recorder().fill_path({ .path = closed_path(), .color = Color::Black, .winding_rule = to_gfx_winding_rule(graphics_element.clip_rule().value_or(SVG::ClipRule::Nonzero)), @@ -116,7 +116,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const auto fill_opacity = graphics_element.fill_opacity().value_or(1); auto winding_rule = to_gfx_winding_rule(graphics_element.fill_rule().value_or(SVG::FillRule::Nonzero)); if (auto paint_style = graphics_element.fill_paint_style(paint_context); paint_style.has_value()) { - context.recording_painter().fill_path({ + context.display_list_recorder().fill_path({ .path = closed_path(), .paint_style = *paint_style, .winding_rule = winding_rule, @@ -124,7 +124,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const .translation = offset, }); } else if (auto fill_color = graphics_element.fill_color(); fill_color.has_value()) { - context.recording_painter().fill_path({ + context.display_list_recorder().fill_path({ .path = closed_path(), .color = fill_color->with_opacity(fill_opacity), .winding_rule = winding_rule, @@ -138,7 +138,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const float stroke_thickness = graphics_element.stroke_width().value_or(1) * viewbox_scale; if (auto paint_style = graphics_element.stroke_paint_style(paint_context); paint_style.has_value()) { - context.recording_painter().stroke_path({ + context.display_list_recorder().stroke_path({ .path = path, .paint_style = *paint_style, .thickness = stroke_thickness, @@ -146,7 +146,7 @@ void SVGPathPaintable::paint(PaintContext& context, PaintPhase phase) const .translation = offset, }); } else if (auto stroke_color = graphics_element.stroke_color(); stroke_color.has_value()) { - context.recording_painter().stroke_path({ + context.display_list_recorder().stroke_path({ .path = path, .color = stroke_color->with_opacity(stroke_opacity), .thickness = stroke_thickness, diff --git a/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp b/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp index 78146d373e0a..5d749b99802f 100644 --- a/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/SVGSVGPaintable.cpp @@ -31,10 +31,10 @@ void SVGSVGPaintable::before_children_paint(PaintContext& context, PaintPhase ph PaintableBox::before_children_paint(context, phase); if (phase != PaintPhase::Foreground) return; - context.recording_painter().save(); + context.display_list_recorder().save(); auto clip_rect = absolute_rect(); clip_rect.translate_by(enclosing_scroll_frame_offset().value_or({})); - context.recording_painter().add_clip_rect(context.enclosing_device_rect(clip_rect).to_type<int>()); + context.display_list_recorder().add_clip_rect(context.enclosing_device_rect(clip_rect).to_type<int>()); } void SVGSVGPaintable::after_children_paint(PaintContext& context, PaintPhase phase) const @@ -42,7 +42,7 @@ void SVGSVGPaintable::after_children_paint(PaintContext& context, PaintPhase pha PaintableBox::after_children_paint(context, phase); if (phase != PaintPhase::Foreground) return; - context.recording_painter().restore(); + context.display_list_recorder().restore(); } } diff --git a/Userland/Libraries/LibWeb/Painting/ShadowPainting.cpp b/Userland/Libraries/LibWeb/Painting/ShadowPainting.cpp index 86d3822ed769..49f3bd60ca3b 100644 --- a/Userland/Libraries/LibWeb/Painting/ShadowPainting.cpp +++ b/Userland/Libraries/LibWeb/Painting/ShadowPainting.cpp @@ -569,10 +569,10 @@ void paint_box_shadow(PaintContext& context, auto shrinked_border_radii = border_radii; shrinked_border_radii.shrink(borders_data.top.width, borders_data.right.width, borders_data.bottom.width, borders_data.left.width); ScopedCornerRadiusClip corner_clipper { context, device_content_rect, shrinked_border_radii, CornerClip::Outside }; - context.recording_painter().paint_inner_box_shadow_params(params); + context.display_list_recorder().paint_inner_box_shadow_params(params); } else { ScopedCornerRadiusClip corner_clipper { context, device_content_rect, border_radii, CornerClip::Inside }; - context.recording_painter().paint_outer_box_shadow_params(params); + context.display_list_recorder().paint_outer_box_shadow_params(params); } } } @@ -620,7 +620,7 @@ void paint_text_shadow(PaintContext& context, PaintableFragment const& fragment, draw_rect.y() + offset_y - margin }; - context.recording_painter().paint_text_shadow(blur_radius, bounding_rect, text_rect, scaled_glyph_run, layer.color, fragment_baseline, draw_location); + context.display_list_recorder().paint_text_shadow(blur_radius, bounding_rect, text_rect, scaled_glyph_run, layer.color, fragment_baseline, draw_location); } } diff --git a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp index 820b34488070..8a1cb27a2a07 100644 --- a/Userland/Libraries/LibWeb/Painting/StackingContext.cpp +++ b/Userland/Libraries/LibWeb/Painting/StackingContext.cpp @@ -276,7 +276,7 @@ void StackingContext::paint(PaintContext& context) const if (opacity == 0.0f) return; - RecordingPainterStateSaver saver(context.recording_painter()); + DisplayListRecorderStateSaver saver(context.display_list_recorder()); auto to_device_pixels_scale = float(context.device_pixels_per_css_pixel()); Gfx::IntRect source_paintable_rect; @@ -295,7 +295,7 @@ void StackingContext::paint(PaintContext& context) const transform_origin = paintable_box().transform_origin().to_type<float>(); } - RecordingPainter::PushStackingContextParams push_stacking_context_params { + DisplayListRecorder::PushStackingContextParams push_stacking_context_params { .opacity = opacity, .is_fixed_position = paintable().is_fixed_position(), .source_paintable_rect = source_paintable_rect, @@ -322,13 +322,13 @@ void StackingContext::paint(PaintContext& context) const } } - context.recording_painter().save(); + context.display_list_recorder().save(); if (paintable().is_paintable_box() && paintable_box().scroll_frame_id().has_value()) - context.recording_painter().set_scroll_frame_id(*paintable_box().scroll_frame_id()); - context.recording_painter().push_stacking_context(push_stacking_context_params); + context.display_list_recorder().set_scroll_frame_id(*paintable_box().scroll_frame_id()); + context.display_list_recorder().push_stacking_context(push_stacking_context_params); paint_internal(context); - context.recording_painter().pop_stacking_context(); - context.recording_painter().restore(); + context.display_list_recorder().pop_stacking_context(); + context.display_list_recorder().restore(); } TraversalDecision StackingContext::hit_test(CSSPixelPoint position, HitTestType type, Function<TraversalDecision(HitTestResult)> const& callback) const diff --git a/Userland/Libraries/LibWeb/Painting/TableBordersPainting.cpp b/Userland/Libraries/LibWeb/Painting/TableBordersPainting.cpp index 0ab45c667595..6b7cde0d4b5f 100644 --- a/Userland/Libraries/LibWeb/Painting/TableBordersPainting.cpp +++ b/Userland/Libraries/LibWeb/Painting/TableBordersPainting.cpp @@ -284,12 +284,12 @@ static void paint_collected_edges(PaintContext& context, Vector<BorderEdgePainti : border_edge_painting_info.rect.bottom_left(); if (border_style == CSS::LineStyle::Dotted) { - context.recording_painter().draw_line(p1.to_type<int>(), p2.to_type<int>(), color, width.value(), Gfx::LineStyle::Dotted); + context.display_list_recorder().draw_line(p1.to_type<int>(), p2.to_type<int>(), color, width.value(), Gfx::LineStyle::Dotted); } else if (border_style == CSS::LineStyle::Dashed) { - context.recording_painter().draw_line(p1.to_type<int>(), p2.to_type<int>(), color, width.value(), Gfx::LineStyle::Dashed); + context.display_list_recorder().draw_line(p1.to_type<int>(), p2.to_type<int>(), color, width.value(), Gfx::LineStyle::Dashed); } else { // FIXME: Support the remaining line styles instead of rendering them as solid. - context.recording_painter().fill_rect(Gfx::IntRect(border_edge_painting_info.rect.location(), border_edge_painting_info.rect.size()), color); + context.display_list_recorder().fill_rect(Gfx::IntRect(border_edge_painting_info.rect.location(), border_edge_painting_info.rect.size()), color); } } } @@ -351,7 +351,7 @@ static void paint_separate_cell_borders(PaintableBox const& cell_box, HashMap<Ce .left = cell_box.box_model().border.left == 0 ? CSS::BorderData() : cell_box.computed_values().border_left(), }; auto cell_rect = cell_coordinates_to_device_rect.get({ cell_box.table_cell_coordinates()->row_index, cell_box.table_cell_coordinates()->column_index }).value(); - paint_all_borders(context.recording_painter(), cell_rect, cell_box.normalized_border_radii_data().as_corners(context), borders_data.to_device_pixels(context)); + paint_all_borders(context.display_list_recorder(), cell_rect, cell_box.normalized_border_radii_data().as_corners(context), borders_data.to_device_pixels(context)); } void paint_table_borders(PaintContext& context, PaintableBox const& table_paintable) @@ -436,7 +436,7 @@ void paint_table_borders(PaintContext& context, PaintableBox const& table_painta .bottom = cell_box.box_model().border.bottom == 0 ? CSS::BorderData() : cell_box.computed_values().border_bottom(), .left = cell_box.box_model().border.left == 0 ? CSS::BorderData() : cell_box.computed_values().border_left(), }; - paint_all_borders(context.recording_painter(), context.rounded_device_rect(cell_box.absolute_border_box_rect()), cell_box.normalized_border_radii_data().as_corners(context), borders_data.to_device_pixels(context)); + paint_all_borders(context.display_list_recorder(), context.rounded_device_rect(cell_box.absolute_border_box_rect()), cell_box.normalized_border_radii_data().as_corners(context), borders_data.to_device_pixels(context)); } } } diff --git a/Userland/Libraries/LibWeb/Painting/VideoPaintable.cpp b/Userland/Libraries/LibWeb/Painting/VideoPaintable.cpp index ad467d8a5b43..9059006cd8db 100644 --- a/Userland/Libraries/LibWeb/Painting/VideoPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/VideoPaintable.cpp @@ -58,10 +58,10 @@ void VideoPaintable::paint(PaintContext& context, PaintPhase phase) const if (phase != PaintPhase::Foreground) return; - RecordingPainterStateSaver saver { context.recording_painter() }; + DisplayListRecorderStateSaver saver { context.display_list_recorder() }; auto video_rect = context.rounded_device_rect(absolute_rect()); - context.recording_painter().add_clip_rect(video_rect.to_type<int>()); + context.display_list_recorder().add_clip_rect(video_rect.to_type<int>()); ScopedCornerRadiusClip corner_clip { context, video_rect, normalized_border_radii_data(ShrinkRadiiForBorders::Yes) }; @@ -130,12 +130,12 @@ void VideoPaintable::paint(PaintContext& context, PaintPhase phase) const auto paint_frame = [&](auto const& frame) { auto scaling_mode = to_gfx_scaling_mode(computed_values().image_rendering(), frame->rect(), video_rect.to_type<int>()); - context.recording_painter().draw_scaled_bitmap(video_rect.to_type<int>(), *frame, frame->rect(), scaling_mode); + context.display_list_recorder().draw_scaled_bitmap(video_rect.to_type<int>(), *frame, frame->rect(), scaling_mode); }; auto paint_transparent_black = [&]() { static constexpr auto transparent_black = Gfx::Color::from_argb(0x00'00'00'00); - context.recording_painter().fill_rect(video_rect.to_type<int>(), transparent_black); + context.display_list_recorder().fill_rect(video_rect.to_type<int>(), transparent_black); }; auto paint_loaded_video_controls = [&]() { @@ -211,8 +211,8 @@ void VideoPaintable::paint_placeholder_video_controls(PaintContext& context, Dev auto playback_button_is_hovered = mouse_position.has_value() && control_box_rect.contains(*mouse_position); auto playback_button_color = control_button_color(playback_button_is_hovered); - context.recording_painter().fill_ellipse(control_box_rect.to_type<int>(), control_box_color); - fill_triangle(context.recording_painter(), playback_button_location.to_type<int>(), play_button_coordinates, playback_button_color); + context.display_list_recorder().fill_ellipse(control_box_rect.to_type<int>(), control_box_color); + fill_triangle(context.display_list_recorder(), playback_button_location.to_type<int>(), play_button_coordinates, playback_button_color); } } diff --git a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp index 405ce5b50b98..75ab3bd70cc0 100644 --- a/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/ViewportPaintable.cpp @@ -63,7 +63,7 @@ void ViewportPaintable::build_stacking_context_tree() void ViewportPaintable::paint_all_phases(PaintContext& context) { build_stacking_context_tree_if_needed(); - context.recording_painter().translate(-context.device_viewport_rect().location().to_type<int>()); + context.display_list_recorder().translate(-context.device_viewport_rect().location().to_type<int>()); stacking_context()->paint(context); } diff --git a/Userland/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp b/Userland/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp index 6c10b5724316..52ede856b0ac 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp +++ b/Userland/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp @@ -94,9 +94,9 @@ RefPtr<Gfx::Bitmap> SVGDecodedImageData::render(Gfx::IntSize size) const m_document->update_layout(); Painting::DisplayList display_list; - Painting::RecordingPainter recording_painter(display_list); + Painting::DisplayListRecorder display_list_recorder(display_list); - m_document->navigable()->record_display_list(recording_painter, {}); + m_document->navigable()->record_display_list(display_list_recorder, {}); auto painting_command_executor_type = m_page_client->painting_command_executor_type(); switch (painting_command_executor_type) {
a6cdf6374f391b96919a98255fad57efd321f43c
2023-02-12 05:48:09
Kenneth Myhra
libweb: Introduce the FormDataEvent interface
false
Introduce the FormDataEvent interface
libweb
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 88f8a7cf0101..cefef712fadc 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -186,6 +186,7 @@ set(SOURCES HTML/Focus.cpp HTML/FormAssociatedElement.cpp HTML/FormControlInfrastructure.cpp + HTML/FormDataEvent.cpp HTML/GlobalEventHandlers.cpp HTML/History.cpp HTML/HTMLAnchorElement.cpp diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index 85f5af61b269..9ea06df22e9c 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -246,6 +246,7 @@ struct EnvironmentSettingsObject; class ErrorEvent; class EventHandler; class EventLoop; +class FormDataEvent; class HTMLAnchorElement; class HTMLAreaElement; class HTMLAudioElement; diff --git a/Userland/Libraries/LibWeb/HTML/FormDataEvent.cpp b/Userland/Libraries/LibWeb/HTML/FormDataEvent.cpp new file mode 100644 index 000000000000..aa5fa25f11f6 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/FormDataEvent.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023, Kenneth Myhra <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/Bindings/FormDataEventPrototype.h> +#include <LibWeb/Bindings/Intrinsics.h> +#include <LibWeb/HTML/FormDataEvent.h> + +namespace Web::HTML { + +WebIDL::ExceptionOr<JS::NonnullGCPtr<FormDataEvent>> FormDataEvent::construct_impl(JS::Realm& realm, DeprecatedString const& event_name, FormDataEventInit const& event_init) +{ + return MUST_OR_THROW_OOM(realm.heap().allocate<FormDataEvent>(realm, realm, event_name, event_init)); +} + +FormDataEvent::FormDataEvent(JS::Realm& realm, DeprecatedString const& event_name, FormDataEventInit const& event_init) + : DOM::Event(realm, event_name, event_init) + , m_form_data(event_init.form_data) +{ +} + +FormDataEvent::~FormDataEvent() = default; + +JS::ThrowCompletionOr<void> FormDataEvent::initialize(JS::Realm& realm) +{ + MUST_OR_THROW_OOM(Base::initialize(realm)); + set_prototype(&Bindings::ensure_web_prototype<Bindings::FormDataEventPrototype>(realm, "FormDataEvent")); + + return {}; +} + +void FormDataEvent::visit_edges(Cell::Visitor& visitor) +{ + Base::visit_edges(visitor); + visitor.visit(m_form_data); +} + +} diff --git a/Userland/Libraries/LibWeb/HTML/FormDataEvent.h b/Userland/Libraries/LibWeb/HTML/FormDataEvent.h new file mode 100644 index 000000000000..3c2a4254e2f3 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/FormDataEvent.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023, Kenneth Myhra <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <LibWeb/DOM/Event.h> +#include <LibWeb/XHR/FormData.h> + +namespace Web::HTML { + +struct FormDataEventInit : public DOM::EventInit { + JS::GCPtr<XHR::FormData> form_data {}; +}; + +class FormDataEvent final : public DOM::Event { + WEB_PLATFORM_OBJECT(FormDataEvent, DOM::Event); + +public: + static WebIDL::ExceptionOr<JS::NonnullGCPtr<FormDataEvent>> construct_impl(JS::Realm&, DeprecatedString const& event_name, FormDataEventInit const& event_init); + + virtual ~FormDataEvent() override; + + JS::GCPtr<XHR::FormData> form_data() const { return m_form_data; } + +private: + FormDataEvent(JS::Realm&, DeprecatedString const& event_name, FormDataEventInit const& event_init); + + JS::ThrowCompletionOr<void> initialize(JS::Realm&) override; + + virtual void visit_edges(Cell::Visitor&) override; + + JS::GCPtr<XHR::FormData> m_form_data; +}; + +} diff --git a/Userland/Libraries/LibWeb/HTML/FormDataEvent.idl b/Userland/Libraries/LibWeb/HTML/FormDataEvent.idl new file mode 100644 index 000000000000..3b198d7658ae --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/FormDataEvent.idl @@ -0,0 +1,14 @@ +#import <DOM/Event.idl> +#import <XHR/FormData.idl> + +// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#the-formdataevent-interface +[Exposed=Window] +interface FormDataEvent : Event { + constructor(DOMString type, FormDataEventInit eventInitDict); + + readonly attribute FormData formData; +}; + +dictionary FormDataEventInit : EventInit { + required FormData formData; +}; diff --git a/Userland/Libraries/LibWeb/idl_files.cmake b/Userland/Libraries/LibWeb/idl_files.cmake index e28ec3f418c8..bb83d83a7bf5 100644 --- a/Userland/Libraries/LibWeb/idl_files.cmake +++ b/Userland/Libraries/LibWeb/idl_files.cmake @@ -71,6 +71,7 @@ libweb_js_bindings(HTML/CloseEvent) libweb_js_bindings(HTML/DOMParser) libweb_js_bindings(HTML/DOMStringMap) libweb_js_bindings(HTML/ErrorEvent) +libweb_js_bindings(HTML/FormDataEvent) libweb_js_bindings(HTML/History) libweb_js_bindings(HTML/HTMLAnchorElement) libweb_js_bindings(HTML/HTMLAreaElement)
49f697ed563c26a90732b17f6649fb23cc44057b
2022-12-24 03:18:30
ericLemanissier
libgfx: GIFLoader: Propagate more errors
false
GIFLoader: Propagate more errors
libgfx
diff --git a/Userland/Libraries/LibGfx/GIFLoader.cpp b/Userland/Libraries/LibGfx/GIFLoader.cpp index 053deb31b50a..7d53cbbb9d34 100644 --- a/Userland/Libraries/LibGfx/GIFLoader.cpp +++ b/Userland/Libraries/LibGfx/GIFLoader.cpp @@ -88,7 +88,7 @@ enum class GIFFormat { GIF89a, }; -static Optional<GIFFormat> decode_gif_header(InputMemoryStream& stream) +static ErrorOr<GIFFormat> decode_gif_header(InputMemoryStream& stream) { static auto valid_header_87 = "GIF87a"sv; static auto valid_header_89 = "GIF89a"sv; @@ -96,15 +96,14 @@ static Optional<GIFFormat> decode_gif_header(InputMemoryStream& stream) Array<u8, 6> header; stream >> header; - if (stream.handle_any_error()) - return {}; + TRY(stream.try_handle_any_error()); if (header.span() == valid_header_87.bytes()) return GIFFormat::GIF87a; if (header.span() == valid_header_89.bytes()) return GIFFormat::GIF89a; - return {}; + return Error::from_string_literal("GIF header unknown"); } class LZWDecoder { @@ -144,11 +143,11 @@ class LZWDecoder { m_output.clear(); } - Optional<u16> next_code() + ErrorOr<u16> next_code() { size_t current_byte_index = m_current_bit_index / 8; if (current_byte_index >= m_lzw_bytes.size()) { - return {}; + return Error::from_string_literal("LZWDecoder tries to read ouf of bounds"); } // Extract the code bits using a 32-bit mask to cover the possibility that if @@ -175,13 +174,13 @@ class LZWDecoder { m_current_code, m_current_bit_index, m_code_table.size()); - return {}; + return Error::from_string_literal("Corrupted LZW stream, invalid code"); } else if (m_current_code == m_code_table.size() && m_output.is_empty()) { dbgln_if(GIF_DEBUG, "Corrupted LZW stream, valid new code but output buffer is empty: {} at bit index {}, code table size: {}", m_current_code, m_current_bit_index, m_code_table.size()); - return {}; + return Error::from_string_literal("Corrupted LZW stream, valid new code but output buffer is empty"); } m_current_bit_index += m_code_size; @@ -326,10 +325,10 @@ static ErrorOr<void> decode_frame(GIFLoadingContext& context, size_t frame_index int row = 0; int interlace_pass = 0; while (true) { - Optional<u16> code = decoder.next_code(); - if (!code.has_value()) { + ErrorOr<u16> code = decoder.next_code(); + if (code.is_error()) { dbgln_if(GIF_DEBUG, "Unexpectedly reached end of gif frame data"); - return Error::from_string_literal("Unexpectedly reached end of gif frame data"); + return code.release_error(); } if (code.value() == clear_code) { @@ -378,17 +377,14 @@ static ErrorOr<void> decode_frame(GIFLoadingContext& context, size_t frame_index return {}; } -static bool load_gif_frame_descriptors(GIFLoadingContext& context) +static ErrorOr<void> load_gif_frame_descriptors(GIFLoadingContext& context) { if (context.data_size < 32) - return false; + return Error::from_string_literal("Size too short for GIF frame descriptors"); InputMemoryStream stream { { context.data, context.data_size } }; - Optional<GIFFormat> format = decode_gif_header(stream); - if (!format.has_value()) { - return false; - } + TRY(decode_gif_header(stream)); LittleEndian<u16> value; @@ -398,28 +394,24 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) stream >> value; context.logical_screen.height = value; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); if (context.logical_screen.width > maximum_width_for_decoded_images || context.logical_screen.height > maximum_height_for_decoded_images) { dbgln("This GIF is too large for comfort: {}x{}", context.logical_screen.width, context.logical_screen.height); - return false; + return Error::from_string_literal("This GIF is too large for comfort"); } u8 gcm_info = 0; stream >> gcm_info; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); stream >> context.background_color_index; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); u8 pixel_aspect_ratio = 0; stream >> pixel_aspect_ratio; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); u8 bits_per_pixel = (gcm_info & 7) + 1; int color_map_entry_count = 1; @@ -434,22 +426,19 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) context.logical_screen.color_map[i] = { r, g, b }; } - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); NonnullOwnPtr<GIFImageDescriptor> current_image = make<GIFImageDescriptor>(); for (;;) { u8 sentinel = 0; stream >> sentinel; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); if (sentinel == '!') { u8 extension_type = 0; stream >> extension_type; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); u8 sub_block_length = 0; @@ -457,8 +446,7 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) for (;;) { stream >> sub_block_length; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); if (sub_block_length == 0) break; @@ -469,8 +457,7 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) sub_block.append(dummy); } - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); } if (extension_type == 0xF9) { @@ -533,8 +520,7 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) image.height = tmp; stream >> packed_fields; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); image.use_global_color_map = !(packed_fields & 0x80); image.interlaced = (packed_fields & 0x40) != 0; @@ -552,16 +538,14 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) } stream >> image.lzw_min_code_size; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); u8 lzw_encoded_bytes_expected = 0; for (;;) { stream >> lzw_encoded_bytes_expected; - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); if (lzw_encoded_bytes_expected == 0) break; @@ -569,8 +553,7 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) Array<u8, 256> buffer; stream >> buffer.span().trim(lzw_encoded_bytes_expected); - if (stream.handle_any_error()) - return false; + TRY(stream.try_handle_any_error()); for (int i = 0; i < lzw_encoded_bytes_expected; ++i) { image.lzw_encoded_bytes.append(buffer[i]); @@ -585,11 +568,11 @@ static bool load_gif_frame_descriptors(GIFLoadingContext& context) break; } - return false; + return Error::from_string_literal("Unexpected sentinel"); } context.state = GIFLoadingContext::State::FrameDescriptorsLoaded; - return true; + return {}; } GIFImageDecoderPlugin::GIFImageDecoderPlugin(u8 const* data, size_t size) @@ -608,7 +591,7 @@ IntSize GIFImageDecoderPlugin::size() } if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) { - if (!load_gif_frame_descriptors(*m_context)) { + if (load_gif_frame_descriptors(*m_context).is_error()) { m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors; return {}; } @@ -634,7 +617,7 @@ bool GIFImageDecoderPlugin::set_nonvolatile(bool& was_purged) bool GIFImageDecoderPlugin::sniff() { InputMemoryStream stream { { m_context->data, m_context->data_size } }; - return decode_gif_header(stream).has_value(); + return !decode_gif_header(stream).is_error(); } bool GIFImageDecoderPlugin::is_animated() @@ -644,7 +627,7 @@ bool GIFImageDecoderPlugin::is_animated() } if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) { - if (!load_gif_frame_descriptors(*m_context)) { + if (load_gif_frame_descriptors(*m_context).is_error()) { m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors; return false; } @@ -660,7 +643,7 @@ size_t GIFImageDecoderPlugin::loop_count() } if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) { - if (!load_gif_frame_descriptors(*m_context)) { + if (load_gif_frame_descriptors(*m_context).is_error()) { m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors; return 0; } @@ -676,7 +659,7 @@ size_t GIFImageDecoderPlugin::frame_count() } if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) { - if (!load_gif_frame_descriptors(*m_context)) { + if (load_gif_frame_descriptors(*m_context).is_error()) { m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors; return 1; } @@ -692,9 +675,9 @@ ErrorOr<ImageFrameDescriptor> GIFImageDecoderPlugin::frame(size_t index) } if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) { - if (!load_gif_frame_descriptors(*m_context)) { + if (auto result = load_gif_frame_descriptors(*m_context); result.is_error()) { m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors; - return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed"); + return result.release_error(); } }
f2e381ae19255a7df298476951af2fce58894b5c
2024-04-19 22:12:34
Nico Weber
libcore: Add ".jpf" as a JPEG2000 extension
false
Add ".jpf" as a JPEG2000 extension
libcore
diff --git a/Userland/Libraries/LibCore/MimeData.cpp b/Userland/Libraries/LibCore/MimeData.cpp index 0507f3f02edd..0ac8c695763c 100644 --- a/Userland/Libraries/LibCore/MimeData.cpp +++ b/Userland/Libraries/LibCore/MimeData.cpp @@ -115,7 +115,7 @@ static Array const s_registered_mime_type = { MimeType { .name = "image/bmp"sv, .common_extensions = { ".bmp"sv }, .description = "BMP image data"sv, .magic_bytes = Vector<u8> { 'B', 'M' } }, MimeType { .name = "image/gif"sv, .common_extensions = { ".gif"sv }, .description = "GIF image data"sv, .magic_bytes = Vector<u8> { 'G', 'I', 'F', '8', '7', 'a' } }, MimeType { .name = "image/gif"sv, .common_extensions = { ".gif"sv }, .description = "GIF image data"sv, .magic_bytes = Vector<u8> { 'G', 'I', 'F', '8', '9', 'a' } }, - MimeType { .name = "image/jp2"sv, .common_extensions = { ".jp2"sv, ".jpx"sv }, .description = "JPEG2000 image data"sv, .magic_bytes = Vector<u8> { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A } }, + MimeType { .name = "image/jp2"sv, .common_extensions = { ".jp2"sv, ".jpf"sv, ".jpx"sv }, .description = "JPEG2000 image data"sv, .magic_bytes = Vector<u8> { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A } }, MimeType { .name = "image/jpeg"sv, .common_extensions = { ".jpg"sv, ".jpeg"sv }, .description = "JPEG image data"sv, .magic_bytes = Vector<u8> { 0xFF, 0xD8, 0xFF } }, MimeType { .name = "image/jxl"sv, .common_extensions = { ".jxl"sv }, .description = "JPEG XL image data"sv, .magic_bytes = Vector<u8> { 0xFF, 0x0A } }, MimeType { .name = "image/png"sv, .common_extensions = { ".png"sv }, .description = "PNG image data"sv, .magic_bytes = Vector<u8> { 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A } },
1df9293ea4dfda4b952f069070f35f1aa95c95f9
2020-07-30 20:26:15
AnotherTest
libweb: Complete the redirect URL before loading it
false
Complete the redirect URL before loading it
libweb
diff --git a/Libraries/LibWeb/Loader/FrameLoader.cpp b/Libraries/LibWeb/Loader/FrameLoader.cpp index ed82a8612072..b66edfaeb049 100644 --- a/Libraries/LibWeb/Loader/FrameLoader.cpp +++ b/Libraries/LibWeb/Loader/FrameLoader.cpp @@ -212,7 +212,7 @@ void FrameLoader::resource_did_load() // FIXME: Also check HTTP status code before redirecting auto location = resource()->response_headers().get("Location"); if (location.has_value()) { - load(location.value(), FrameLoader::Type::Navigation); + load(url.complete_url(location.value()), FrameLoader::Type::Navigation); return; }
7906ada01547d13932fdfc63cc4c7cb7cc3560fb
2022-05-10 01:19:48
Jelle Raaijmakers
libsoftgpu: Update coverage mask bits during rasterization
false
Update coverage mask bits during rasterization
libsoftgpu
diff --git a/Userland/Libraries/LibSoftGPU/Device.cpp b/Userland/Libraries/LibSoftGPU/Device.cpp index 90ffcc8a84fb..e014067e3928 100644 --- a/Userland/Libraries/LibSoftGPU/Device.cpp +++ b/Userland/Libraries/LibSoftGPU/Device.cpp @@ -40,7 +40,6 @@ using AK::SIMD::i32x4; using AK::SIMD::load4_masked; using AK::SIMD::maskbits; using AK::SIMD::maskcount; -using AK::SIMD::none; using AK::SIMD::store4_masked; using AK::SIMD::to_f32x4; using AK::SIMD::to_u32x4; @@ -329,15 +328,13 @@ void Device::rasterize_triangle(Triangle const& triangle) && quad.screen_coordinates.x() <= render_bounds_right && quad.screen_coordinates.y() >= render_bounds_top && quad.screen_coordinates.y() <= render_bounds_bottom; - - if (none(quad.mask)) + auto coverage_bits = maskbits(quad.mask); + if (coverage_bits == 0) continue; INCREASE_STATISTICS_COUNTER(g_num_quads, 1); INCREASE_STATISTICS_COUNTER(g_num_pixels, maskcount(quad.mask)); - int coverage_bits = maskbits(quad.mask); - // Stencil testing GPU::StencilType* stencil_ptrs[4]; i32x4 stencil_value; @@ -391,7 +388,8 @@ void Device::rasterize_triangle(Triangle const& triangle) // Update coverage mask + early quad rejection quad.mask &= stencil_test_passed; - if (none(quad.mask)) + coverage_bits = maskbits(quad.mask); + if (coverage_bits == 0) continue; } @@ -489,7 +487,8 @@ void Device::rasterize_triangle(Triangle const& triangle) // Update coverage mask + early quad rejection quad.mask &= depth_test_passed; - if (none(quad.mask)) + coverage_bits = maskbits(quad.mask); + if (coverage_bits == 0) continue; }
d64d03e0d6e0543ca70f422c7fab0aa61c5963b0
2023-09-23 06:09:37
Hendiadyoin1
kernel: Make Graphics device detection a bit more idomatic
false
Make Graphics device detection a bit more idomatic
kernel
diff --git a/Kernel/Bus/PCI/Definitions.h b/Kernel/Bus/PCI/Definitions.h index cdbe15a62d77..c1a2c025f8ad 100644 --- a/Kernel/Bus/PCI/Definitions.h +++ b/Kernel/Bus/PCI/Definitions.h @@ -93,6 +93,7 @@ static constexpr u16 msix_control_enable = 0x8000; // Taken from https://pcisig.com/sites/default/files/files/PCI_Code-ID_r_1_11__v24_Jan_2019.pdf enum class ClassID { + Legacy = 0x00, MassStorage = 0x01, Network = 0x02, Display = 0x03, @@ -114,6 +115,14 @@ enum class ClassID { NonEssentialInstrumentation = 0x13, }; +namespace Legacy { + +enum class SubclassID { + Any = 0x00, + VGACompatible = 0x01 +}; + +} namespace MassStorage { enum class SubclassID { @@ -336,6 +345,7 @@ AK_TYPEDEF_DISTINCT_ORDERED_ID(u8, ClassCode); AK_MAKE_DISTINCT_NUMERIC_COMPARABLE_TO_ENUM(ClassCode, ClassID) AK_TYPEDEF_DISTINCT_ORDERED_ID(u8, SubclassCode); +AK_MAKE_DISTINCT_NUMERIC_COMPARABLE_TO_ENUM(SubclassCode, Legacy::SubclassID); AK_MAKE_DISTINCT_NUMERIC_COMPARABLE_TO_ENUM(SubclassCode, MassStorage::SubclassID); AK_MAKE_DISTINCT_NUMERIC_COMPARABLE_TO_ENUM(SubclassCode, Network::SubclassID); AK_MAKE_DISTINCT_NUMERIC_COMPARABLE_TO_ENUM(SubclassCode, Display::SubclassID); diff --git a/Kernel/Devices/GPU/Management.cpp b/Kernel/Devices/GPU/Management.cpp index 32e24031b073..0f83960522c7 100644 --- a/Kernel/Devices/GPU/Management.cpp +++ b/Kernel/Devices/GPU/Management.cpp @@ -110,14 +110,14 @@ static inline bool is_vga_compatible_pci_device(PCI::DeviceIdentifier const& dev { // Note: Check for Display Controller, VGA Compatible Controller or // Unclassified, VGA-Compatible Unclassified Device - auto is_display_controller_vga_compatible = device_identifier.class_code().value() == 0x3 && device_identifier.subclass_code().value() == 0x0; - auto is_general_pci_vga_compatible = device_identifier.class_code().value() == 0x0 && device_identifier.subclass_code().value() == 0x1; + auto is_display_controller_vga_compatible = device_identifier.class_code() == PCI::ClassID::Display && device_identifier.subclass_code() == PCI::Display::SubclassID::VGA; + auto is_general_pci_vga_compatible = device_identifier.class_code() == PCI::ClassID::Legacy && device_identifier.subclass_code() == PCI::Legacy::SubclassID::VGACompatible; return is_display_controller_vga_compatible || is_general_pci_vga_compatible; } static inline bool is_display_controller_pci_device(PCI::DeviceIdentifier const& device_identifier) { - return device_identifier.class_code().value() == 0x3; + return device_identifier.class_code() == PCI::ClassID::Display; } struct PCIGraphicsDriverInitializer {
dccab569d2f97f694af3b2f486c64df094df97a1
2019-09-15 22:57:44
willmcpherson2
shell: Tab completion for programs in PATH
false
Tab completion for programs in PATH
shell
diff --git a/Shell/LineEditor.cpp b/Shell/LineEditor.cpp index 5e36ca16c55a..ebfaf10150cd 100644 --- a/Shell/LineEditor.cpp +++ b/Shell/LineEditor.cpp @@ -37,6 +37,60 @@ void LineEditor::append(const String& string) m_cursor = m_buffer.size(); } +void LineEditor::tab_complete_first_token() +{ + auto input = String::copy(m_buffer); + + String path = getenv("PATH"); + if (path.is_empty()) + return; + auto directories = path.split(':'); + + String match; + + // Go through the files in PATH. + for (const auto& directory : directories) { + CDirIterator programs(directory.characters(), CDirIterator::SkipDots); + while (programs.has_next()) { + String program = programs.next_path(); + if (!program.starts_with(input)) + continue; + + // Check that the file is an executable program. + struct stat program_status; + StringBuilder program_path; + program_path.append(directory.characters()); + program_path.append('/'); + program_path.append(program.characters()); + int stat_error = stat(program_path.to_string().characters(), &program_status); + if (stat_error || !(program_status.st_mode & S_IXUSR)) + continue; + + // Set `match` to the first one that starts with `input`. + if (match.is_empty()) { + match = program; + } else { + // Remove characters from the end of `match` if they're + // different from another `program` starting with `input`. + int i = input.length(); + while (i < match.length() && i < program.length() && match[i] == program[i]) + ++i; + match = match.substring(0, i); + } + + if (match.length() == input.length()) + return; + } + } + + if (match.is_empty()) + return; + + // Then append `match` to the buffer, excluding the `input` part which is + // already in the buffer. + append(match.substring(input.length(), match.length() - input.length()).characters()); +} + String LineEditor::get_line(const String& prompt) { fputs(prompt.characters(), stdout); @@ -174,7 +228,21 @@ String LineEditor::get_line(const String& prompt) } if (ch == '\t') { - // FIXME: Implement tab-completion. + if (m_buffer.is_empty()) + continue; + + bool is_first_token = true; + for (const auto& character : m_buffer) { + if (isspace(character)) { + is_first_token = false; + break; + } + } + + // FIXME: Implement tab-completion for other tokens (paths). + if (is_first_token) + tab_complete_first_token(); + continue; } diff --git a/Shell/LineEditor.h b/Shell/LineEditor.h index 5f5a4344d7a0..b2a5b1c6dc21 100644 --- a/Shell/LineEditor.h +++ b/Shell/LineEditor.h @@ -1,7 +1,10 @@ #pragma once #include <AK/String.h> +#include <AK/StringBuilder.h> #include <AK/Vector.h> +#include <LibCore/CDirIterator.h> +#include <sys/stat.h> class LineEditor { public: @@ -16,6 +19,7 @@ class LineEditor { private: void clear_line(); void append(const String&); + void tab_complete_first_token(); void vt_save_cursor(); void vt_restore_cursor(); void vt_clear_to_end_of_line();
19a51132f5e952a7db8a9021348eae5ca144b77f
2019-03-13 19:17:21
Andreas Kling
kernel: recvfrom() should treat the address arguments as outparams.
false
recvfrom() should treat the address arguments as outparams.
kernel
diff --git a/Kernel/IPv4Socket.cpp b/Kernel/IPv4Socket.cpp index 6ceae409eace..b4b16979aebf 100644 --- a/Kernel/IPv4Socket.cpp +++ b/Kernel/IPv4Socket.cpp @@ -43,7 +43,7 @@ bool IPv4Socket::get_address(sockaddr* address, socklen_t* address_size) // FIXME: Look into what fallback behavior we should have here. if (*address_size != sizeof(sockaddr_in)) return false; - memcpy(address, &m_peer_address, sizeof(sockaddr_in)); + memcpy(address, &m_destination_address, sizeof(sockaddr_in)); *address_size = sizeof(sockaddr_in); return true; } @@ -117,34 +117,31 @@ ssize_t IPv4Socket::sendto(const void* data, size_t data_length, int flags, cons return -EAFNOSUPPORT; } - auto peer_address = IPv4Address((const byte*)&((const sockaddr_in*)addr)->sin_addr.s_addr); + auto& ia = *(const sockaddr_in*)addr; + m_destination_address = IPv4Address((const byte*)&ia.sin_addr.s_addr); + m_destination_port = ia.sin_port; - kprintf("sendto: peer_address=%s\n", peer_address.to_string().characters()); + kprintf("sendto: destination=%s:%u\n", m_destination_address.to_string().characters(), m_destination_port); // FIXME: If we can't find the right MAC address, block until it's available? // I feel like this should happen in a layer below this code. MACAddress mac_address; - adapter->send_ipv4(mac_address, peer_address, (IPv4Protocol)protocol(), ByteBuffer::copy((const byte*)data, data_length)); + adapter->send_ipv4(mac_address, m_destination_address, (IPv4Protocol)protocol(), ByteBuffer::copy((const byte*)data, data_length)); return data_length; } -ssize_t IPv4Socket::recvfrom(void* buffer, size_t buffer_length, int flags, const sockaddr* addr, socklen_t addr_length) +ssize_t IPv4Socket::recvfrom(void* buffer, size_t buffer_length, int flags, sockaddr* addr, socklen_t* addr_length) { (void)flags; - if (addr_length != sizeof(sockaddr_in)) - return -EINVAL; - // FIXME: Find the adapter some better way! - auto* adapter = NetworkAdapter::from_ipv4_address(IPv4Address(192, 168, 5, 2)); - if (!adapter) { - // FIXME: Figure out which error code to return. - ASSERT_NOT_REACHED(); - } - if (addr->sa_family != AF_INET) { kprintf("recvfrom: Bad address family: %u is not AF_INET!\n", addr->sa_family); return -EAFNOSUPPORT; } + if (*addr_length < sizeof(sockaddr_in)) + return -EINVAL; + *addr_length = sizeof(sockaddr_in); + auto peer_address = IPv4Address((const byte*)&((const sockaddr_in*)addr)->sin_addr.s_addr); #ifdef IPV4_SOCKET_DEBUG kprintf("recvfrom: peer_address=%s\n", peer_address.to_string().characters()); @@ -177,6 +174,9 @@ ssize_t IPv4Socket::recvfrom(void* buffer, size_t buffer_length, int flags, cons ASSERT(!packet_buffer.is_null()); auto& ipv4_packet = *(const IPv4Packet*)(packet_buffer.pointer()); + auto& ia = *(sockaddr_in*)addr; + memcpy(&ia.sin_addr, &m_destination_address, sizeof(IPv4Address)); + if (type() == SOCK_RAW) { ASSERT(buffer_length >= ipv4_packet.payload_size()); memcpy(buffer, ipv4_packet.payload(), ipv4_packet.payload_size()); @@ -187,6 +187,7 @@ ssize_t IPv4Socket::recvfrom(void* buffer, size_t buffer_length, int flags, cons auto& udp_packet = *static_cast<const UDPPacket*>(ipv4_packet.payload()); ASSERT(udp_packet.length() >= sizeof(UDPPacket)); // FIXME: This should be rejected earlier. ASSERT(buffer_length >= (udp_packet.length() - sizeof(UDPPacket))); + ia.sin_port = udp_packet.destination_port(); memcpy(buffer, udp_packet.payload(), udp_packet.length() - sizeof(UDPPacket)); return udp_packet.length() - sizeof(UDPPacket); } diff --git a/Kernel/IPv4Socket.h b/Kernel/IPv4Socket.h index 417ffe0e4d23..b9b9c68e847e 100644 --- a/Kernel/IPv4Socket.h +++ b/Kernel/IPv4Socket.h @@ -23,7 +23,7 @@ class IPv4Socket final : public Socket { virtual ssize_t write(SocketRole, const byte*, ssize_t) override; virtual bool can_write(SocketRole) const override; virtual ssize_t sendto(const void*, size_t, int, const sockaddr*, socklen_t) override; - virtual ssize_t recvfrom(void*, size_t, int flags, const sockaddr*, socklen_t) override; + virtual ssize_t recvfrom(void*, size_t, int flags, sockaddr*, socklen_t*) override; void did_receive(ByteBuffer&&); @@ -38,7 +38,7 @@ class IPv4Socket final : public Socket { bool m_bound { false }; int m_attached_fds { 0 }; - IPv4Address m_peer_address; + IPv4Address m_destination_address; DoubleBuffer m_for_client; DoubleBuffer m_for_server; diff --git a/Kernel/LocalSocket.cpp b/Kernel/LocalSocket.cpp index ab21aabfa72b..d79b1badaca8 100644 --- a/Kernel/LocalSocket.cpp +++ b/Kernel/LocalSocket.cpp @@ -169,7 +169,7 @@ ssize_t LocalSocket::sendto(const void*, size_t, int, const sockaddr*, socklen_t ASSERT_NOT_REACHED(); } -ssize_t LocalSocket::recvfrom(void*, size_t, int flags, const sockaddr*, socklen_t) +ssize_t LocalSocket::recvfrom(void*, size_t, int flags, sockaddr*, socklen_t*) { ASSERT_NOT_REACHED(); } diff --git a/Kernel/LocalSocket.h b/Kernel/LocalSocket.h index e817a1c197fe..f8329cd6eb43 100644 --- a/Kernel/LocalSocket.h +++ b/Kernel/LocalSocket.h @@ -20,7 +20,7 @@ class LocalSocket final : public Socket { virtual ssize_t write(SocketRole, const byte*, ssize_t) override; virtual bool can_write(SocketRole) const override; virtual ssize_t sendto(const void*, size_t, int, const sockaddr*, socklen_t) override; - virtual ssize_t recvfrom(void*, size_t, int flags, const sockaddr*, socklen_t) override; + virtual ssize_t recvfrom(void*, size_t, int flags, sockaddr*, socklen_t*) override; private: explicit LocalSocket(int type); diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index a33327e2b37b..c749d06c98c5 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -2554,12 +2554,14 @@ ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* params) void* buffer = params->buffer; size_t buffer_length = params->buffer_length; int flags = params->flags; - auto* addr = (const sockaddr*)params->addr; - auto addr_length = (socklen_t)params->addr_length; + auto* addr = (sockaddr*)params->addr; + auto* addr_length = (socklen_t*)params->addr_length; if (!validate_write(buffer, buffer_length)) return -EFAULT; - if (!validate_read(addr, addr_length)) + if (!validate_read_typed(addr_length)) + return -EFAULT; + if (!validate_read(addr, *addr_length)) return -EFAULT; auto* descriptor = file_descriptor(sockfd); if (!descriptor) @@ -2567,7 +2569,7 @@ ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* params) if (!descriptor->is_socket()) return -ENOTSOCK; auto& socket = *descriptor->socket(); - kprintf("recvfrom %p (%u), flags=%u, addr: %p (%u)\n", buffer, buffer_length, flags, addr, addr_length); + kprintf("recvfrom %p (%u), flags=%u, addr: %p (%u)\n", buffer, buffer_length, flags, addr, *addr_length); return socket.recvfrom(buffer, buffer_length, flags, addr, addr_length); } diff --git a/Kernel/Socket.h b/Kernel/Socket.h index 96605cec99b8..867c7e970c74 100644 --- a/Kernel/Socket.h +++ b/Kernel/Socket.h @@ -36,7 +36,7 @@ class Socket : public Retainable<Socket> { virtual ssize_t write(SocketRole, const byte*, ssize_t) = 0; virtual bool can_write(SocketRole) const = 0; virtual ssize_t sendto(const void*, size_t, int flags, const sockaddr*, socklen_t) = 0; - virtual ssize_t recvfrom(void*, size_t, int flags, const sockaddr*, socklen_t) = 0; + virtual ssize_t recvfrom(void*, size_t, int flags, sockaddr*, socklen_t*) = 0; KResult setsockopt(int level, int option, const void*, socklen_t); KResult getsockopt(int level, int option, void*, socklen_t*); diff --git a/Kernel/Syscall.h b/Kernel/Syscall.h index 697449af9e13..417ce12dd627 100644 --- a/Kernel/Syscall.h +++ b/Kernel/Syscall.h @@ -146,8 +146,8 @@ struct SC_recvfrom_params { void* buffer; size_t buffer_length; int flags; - const void* addr; // const sockaddr* - size_t addr_length; // socklen_t + void* addr; // sockaddr* + void* addr_length; // socklen_t* }; struct SC_getsockopt_params { diff --git a/LibC/sys/socket.cpp b/LibC/sys/socket.cpp index 1b3cf0569a08..d9db65f010db 100644 --- a/LibC/sys/socket.cpp +++ b/LibC/sys/socket.cpp @@ -41,7 +41,7 @@ ssize_t sendto(int sockfd, const void* data, size_t data_length, int flags, cons __RETURN_WITH_ERRNO(rc, rc, -1); } -ssize_t recvfrom(int sockfd, void* buffer, size_t buffer_length, int flags, const struct sockaddr* addr, socklen_t addr_length) +ssize_t recvfrom(int sockfd, void* buffer, size_t buffer_length, int flags, struct sockaddr* addr, socklen_t* addr_length) { Syscall::SC_recvfrom_params params { sockfd, buffer, buffer_length, flags, addr, addr_length }; int rc = syscall(SC_recvfrom, &params); diff --git a/LibC/sys/socket.h b/LibC/sys/socket.h index 875bb5223a6a..eb6b93ad0cea 100644 --- a/LibC/sys/socket.h +++ b/LibC/sys/socket.h @@ -57,7 +57,7 @@ int listen(int sockfd, int backlog); int accept(int sockfd, sockaddr*, socklen_t*); int connect(int sockfd, const sockaddr*, socklen_t); ssize_t sendto(int sockfd, const void*, size_t, int flags, const struct sockaddr*, socklen_t); -ssize_t recvfrom(int sockfd, void*, size_t, int flags, const struct sockaddr*, socklen_t); +ssize_t recvfrom(int sockfd, void*, size_t, int flags, struct sockaddr*, socklen_t*); int getsockopt(int sockfd, int level, int option, void*, socklen_t*); int setsockopt(int sockfd, int level, int option, const void*, socklen_t); diff --git a/Userland/ping.cpp b/Userland/ping.cpp index 73ce7222b806..21ea2afc528d 100644 --- a/Userland/ping.cpp +++ b/Userland/ping.cpp @@ -89,7 +89,8 @@ int main(int argc, char** argv) } for (;;) { - rc = recvfrom(fd, &pong_packet, sizeof(PingPacket), 0, (const struct sockaddr*)&peer_address, sizeof(sockaddr_in)); + socklen_t peer_address_size = sizeof(peer_address); + rc = recvfrom(fd, &pong_packet, sizeof(PingPacket), 0, (struct sockaddr*)&peer_address, &peer_address_size); if (rc < 0) { if (errno == EAGAIN) { printf("Request (seq=%u) timed out.\n", ntohs(ping_packet.header.un.echo.sequence));
ec43f7a2b0840a97c6d093066750dd28840d9587
2021-10-09 19:18:30
huwdp
libweb: Add initial version of pointer-events CSS property
false
Add initial version of pointer-events CSS property
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/ComputedValues.h b/Userland/Libraries/LibWeb/CSS/ComputedValues.h index 8e207e10b20f..d9537e79cde8 100644 --- a/Userland/Libraries/LibWeb/CSS/ComputedValues.h +++ b/Userland/Libraries/LibWeb/CSS/ComputedValues.h @@ -33,6 +33,7 @@ class InitialValues { static CSS::AlignItems align_items() { return CSS::AlignItems::FlexStart; } static CSS::Overflow overflow() { return CSS::Overflow::Visible; } static CSS::BoxSizing box_sizing() { return CSS::BoxSizing::ContentBox; } + static CSS::PointerEvents pointer_events() { return CSS::PointerEvents::Auto; } }; struct BorderData { @@ -64,6 +65,7 @@ class ComputedValues { CSS::Float float_() const { return m_noninherited.float_; } CSS::Clear clear() const { return m_noninherited.clear; } CSS::Cursor cursor() const { return m_inherited.cursor; } + CSS::PointerEvents pointer_events() const { return m_inherited.pointer_events; } CSS::Display display() const { return m_noninherited.display; } Optional<int> const& z_index() const { return m_noninherited.z_index; } CSS::TextAlign text_align() const { return m_inherited.text_align; } @@ -129,6 +131,7 @@ class ComputedValues { struct { Color color { InitialValues::color() }; CSS::Cursor cursor { InitialValues::cursor() }; + CSS::PointerEvents pointer_events { InitialValues::pointer_events() }; CSS::TextAlign text_align { InitialValues::text_align() }; CSS::TextTransform text_transform { InitialValues::text_transform() }; CSS::WhiteSpace white_space { InitialValues::white_space() }; @@ -189,6 +192,7 @@ class MutableComputedValues final : public ComputedValues { public: void set_color(const Color& color) { m_inherited.color = color; } void set_cursor(CSS::Cursor cursor) { m_inherited.cursor = cursor; } + void set_pointer_events(CSS::PointerEvents value) { m_inherited.pointer_events = value; } void set_background_color(const Color& color) { m_noninherited.background_color = color; } void set_background_repeat_x(CSS::Repeat repeat) { m_noninherited.background_repeat_x = repeat; } void set_background_repeat_y(CSS::Repeat repeat) { m_noninherited.background_repeat_y = repeat; } diff --git a/Userland/Libraries/LibWeb/CSS/Properties.json b/Userland/Libraries/LibWeb/CSS/Properties.json index 78172dab4e71..d53dcfcd21f0 100644 --- a/Userland/Libraries/LibWeb/CSS/Properties.json +++ b/Userland/Libraries/LibWeb/CSS/Properties.json @@ -1073,7 +1073,11 @@ }, "pointer-events": { "inherited": true, - "initial": "auto" + "initial": "auto", + "valid-identifiers": [ + "auto", + "none" + ] }, "position": { "inherited": false, diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp index 18e7dce1f3f5..02205a76f553 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp @@ -355,6 +355,22 @@ Optional<CSS::TextAlign> StyleProperties::text_align() const } } +Optional<CSS::PointerEvents> StyleProperties::pointer_events() const +{ + auto value = property(CSS::PropertyID::PointerEvents); + if (!value.has_value()) + return {}; + + switch (value.value()->to_identifier()) { + case CSS::ValueID::Auto: + return CSS::PointerEvents::Auto; + case CSS::ValueID::None: + return CSS::PointerEvents::None; + default: + return {}; + } +} + Optional<CSS::WhiteSpace> StyleProperties::white_space() const { auto value = property(CSS::PropertyID::WhiteSpace); diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.h b/Userland/Libraries/LibWeb/CSS/StyleProperties.h index b78782889fec..4f1b5308d59d 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleProperties.h +++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.h @@ -67,6 +67,7 @@ class StyleProperties : public RefCounted<StyleProperties> { Optional<CSS::Repeat> background_repeat_y() const; Optional<CSS::BoxShadowData> box_shadow() const; CSS::BoxSizing box_sizing() const; + Optional<CSS::PointerEvents> pointer_events() const; Vector<CSS::Transformation> transformations() const; diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h index 8dfe0acf7b2f..903f67dce66e 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h @@ -211,6 +211,11 @@ enum class WhiteSpace { PreWrap, }; +enum class PointerEvents { + Auto, + None +}; + class StyleValue : public RefCounted<StyleValue> { public: virtual ~StyleValue(); diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp index 41d94142cd2d..cb9b1122207c 100644 --- a/Userland/Libraries/LibWeb/Layout/Node.cpp +++ b/Userland/Libraries/LibWeb/Layout/Node.cpp @@ -312,6 +312,10 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& specified_style) if (cursor.has_value()) computed_values.set_cursor(cursor.value()); + auto pointer_events = specified_style.pointer_events(); + if (pointer_events.has_value()) + computed_values.set_pointer_events(pointer_events.value()); + auto text_decoration_line = specified_style.text_decoration_line(); if (text_decoration_line.has_value()) computed_values.set_text_decoration_line(text_decoration_line.value()); diff --git a/Userland/Libraries/LibWeb/Page/EventHandler.cpp b/Userland/Libraries/LibWeb/Page/EventHandler.cpp index 8acfe1711e33..8541269565c6 100644 --- a/Userland/Libraries/LibWeb/Page/EventHandler.cpp +++ b/Userland/Libraries/LibWeb/Page/EventHandler.cpp @@ -184,10 +184,16 @@ bool EventHandler::handle_mousedown(const Gfx::IntPoint& position, unsigned butt } NonnullRefPtr document = *m_frame.active_document(); + + // TODO: Allow selecting element behind if one on top has pointer-events set to none. + auto result = layout_root()->hit_test(position, Layout::HitTestType::Exact); + auto pointer_events = result.layout_node->computed_values().pointer_events(); + if (pointer_events == CSS::PointerEvents::None) + return false; + RefPtr<DOM::Node> node; { - auto result = layout_root()->hit_test(position, Layout::HitTestType::Exact); if (!result.layout_node) return false; @@ -306,6 +312,10 @@ bool EventHandler::handle_mousemove(const Gfx::IntPoint& position, unsigned butt return false; } + auto pointer_events = result.layout_node->computed_values().pointer_events(); + if (pointer_events == CSS::PointerEvents::None) + return false; + hovered_node_changed = node != document.hovered_node(); document.set_hovered_node(node); if (node) { @@ -313,11 +323,13 @@ bool EventHandler::handle_mousemove(const Gfx::IntPoint& position, unsigned butt if (hovered_link_element) is_hovering_link = true; - auto cursor = result.layout_node->computed_values().cursor(); - if (node->is_text() && cursor == CSS::Cursor::Auto) - hovered_node_cursor = Gfx::StandardCursor::IBeam; - else - hovered_node_cursor = cursor_css_to_gfx(cursor); + if (node->is_text()) { + auto cursor = result.layout_node->computed_values().cursor(); + if (cursor == CSS::Cursor::Auto) + hovered_node_cursor = Gfx::StandardCursor::IBeam; + else + hovered_node_cursor = cursor_css_to_gfx(cursor); + } auto offset = compute_mouse_event_offset(position, *result.layout_node); node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::mousemove, offset.x(), offset.y(), position.x(), position.y()));
46830a0c32930aac3bb390317a87ef42e84f4a07
2020-01-11 15:01:33
Andreas Kling
kernel: Pass a parameter struct to symlink()
false
Pass a parameter struct to symlink()
kernel
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index c2fc303f348d..4b6c062ed4f4 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -2587,14 +2587,19 @@ int Process::sys$unlink(const char* user_path, size_t path_length) return VFS::the().unlink(path.value(), current_directory()); } -int Process::sys$symlink(const char* target, const char* linkpath) +int Process::sys$symlink(const Syscall::SC_symlink_params* user_params) { - SmapDisabler disabler; - if (!validate_read_str(target)) - return -EFAULT; - if (!validate_read_str(linkpath)) + if (!validate_read_typed(user_params)) return -EFAULT; - return VFS::the().symlink(StringView(target), StringView(linkpath), current_directory()); + Syscall::SC_symlink_params params; + copy_from_user(&params, user_params); + auto target = get_syscall_path_argument(params.target.characters, params.target.length); + if (target.is_error()) + return target.error(); + auto linkpath = get_syscall_path_argument(params.linkpath.characters, params.linkpath.length); + if (linkpath.is_error()) + return linkpath.error(); + return VFS::the().symlink(target.value(), linkpath.value(), current_directory()); } KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) diff --git a/Kernel/Process.h b/Kernel/Process.h index 4520fb0a558a..dc21932cb3e2 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -177,7 +177,7 @@ class Process : public InlineLinkedListNode<Process> int sys$utime(const char* pathname, size_t path_length, const struct utimbuf*); int sys$link(const Syscall::SC_link_params*); int sys$unlink(const char* pathname, size_t path_length); - int sys$symlink(const char* target, const char* linkpath); + int sys$symlink(const Syscall::SC_symlink_params*); int sys$rmdir(const char* pathname, size_t path_length); int sys$mount(const char* device, const char* mountpoint, const char* fstype); int sys$umount(const char* mountpoint, size_t mountpoint_length); diff --git a/Kernel/Syscall.h b/Kernel/Syscall.h index 6e71d141d0b6..b2e2c39d8f09 100644 --- a/Kernel/Syscall.h +++ b/Kernel/Syscall.h @@ -345,6 +345,11 @@ struct SC_mknod_params { u32 dev; }; +struct SC_symlink_params { + StringArgument target; + StringArgument linkpath; +}; + void initialize(); int sync(); diff --git a/Libraries/LibC/unistd.cpp b/Libraries/LibC/unistd.cpp index 20d5930461bc..ece2124a88aa 100644 --- a/Libraries/LibC/unistd.cpp +++ b/Libraries/LibC/unistd.cpp @@ -361,7 +361,12 @@ int unlink(const char* pathname) int symlink(const char* target, const char* linkpath) { - int rc = syscall(SC_symlink, target, linkpath); + if (!target || !linkpath) { + errno = EFAULT; + return -1; + } + Syscall::SC_symlink_params params { { target, strlen(target) }, { linkpath, strlen(linkpath) } }; + int rc = syscall(SC_symlink, &params); __RETURN_WITH_ERRNO(rc, rc, -1); }
fc0dbd233452075ba69f0657c43be7fd687e1bef
2024-01-14 07:31:07
Liav A
utilities: Add the listdir utility
false
Add the listdir utility
utilities
diff --git a/Base/usr/share/man/man1/listdir.md b/Base/usr/share/man/man1/listdir.md new file mode 100644 index 000000000000..bb63324537aa --- /dev/null +++ b/Base/usr/share/man/man1/listdir.md @@ -0,0 +1,43 @@ +## Name + +lsdir - list directory entries + +## Synopsis + +```**sh +# lsdir [options...] [path...] +``` + +## Description + +This utility will list all directory entries of a given path (or list of paths) +and print their inode number and file type (in either POSIX DT_* format or human readable). + +The utility uses `LibCore` `DirIterator` object and restrict its functionality +to the `get_dir_entries` syscall only, to get the raw values of each directory +entry. + +## Options + +* `-P`, `--posix-names`: Show POSIX names for file types +* `-t`, `--total-entries-count`: Print count of listed entries when traversing a directory + +## Arguments + +* `path`: Directory to list + +## Examples + +```sh +# List directory entries of working directory +$ lsdir +# List directory entries of /proc directory +$ lsdir /proc +# List directory entries of /proc directory with POSIX names for file types +$ lsdir -P /proc +# List directory entries of /proc directory and print in the end the count of traversed entries +$ lsdir -t /proc +``` + +## See also +* [`ls`(1)](help://man/1/ls) diff --git a/Userland/Utilities/listdir.cpp b/Userland/Utilities/listdir.cpp new file mode 100644 index 000000000000..1a9f8910d1cf --- /dev/null +++ b/Userland/Utilities/listdir.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024, Liav A. <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <AK/Function.h> +#include <AK/StringView.h> +#include <LibCore/ArgsParser.h> +#include <LibCore/DirIterator.h> +#include <LibCore/DirectoryEntry.h> +#include <LibCore/System.h> +#include <LibMain/Main.h> + +static bool flag_show_unix_posix_file_type = false; +static bool flag_show_total_count = false; + +ErrorOr<int> serenity_main(Main::Arguments arguments) +{ + TRY(Core::System::pledge("stdio rpath")); + + Vector<StringView> paths; + + Core::ArgsParser args_parser; + args_parser.set_general_help("List Dirent entries in a directory."); + args_parser.add_option(flag_show_unix_posix_file_type, "Show POSIX names for file types", "posix-names", 'P'); + args_parser.add_option(flag_show_total_count, "Show total count for each directory being iterated", "total-entries-count", 't'); + args_parser.add_positional_argument(paths, "Directory to list", "path", Core::ArgsParser::Required::No); + args_parser.parse(arguments); + + if (paths.is_empty()) + paths.append("."sv); + + for (auto& path : paths) { + Core::DirIterator di(path, Core::DirIterator::NoStat); + if (di.has_error()) { + auto error = di.error(); + warnln("Failed to open {} - {}", path, error); + return error; + } + + outln("Traversing {}", path); + size_t count = 0; + + Function<StringView(Core::DirectoryEntry::Type)> name_from_directory_entry_type; + if (flag_show_unix_posix_file_type) + name_from_directory_entry_type = Core::DirectoryEntry::posix_name_from_directory_entry_type; + else + name_from_directory_entry_type = Core::DirectoryEntry::representative_name_from_directory_entry_type; + + while (di.has_next()) { + auto dir_entry = di.next(); + if (dir_entry.has_value()) { + outln(" {} (Type: {}, Inode number: {})", + dir_entry.value().name, + name_from_directory_entry_type(dir_entry.value().type), + dir_entry.value().inode_number); + count++; + } + } + if (flag_show_total_count) + outln("Directory {} has {} which has being listed during the program runtime", path, count); + } + + return 0; +}
57ee7b3d561ef1bb24ba899a9eeeaa0c99c60b37
2021-09-03 01:46:41
Sam Atkins
libweb: Modify StylePropertiesModel to work with JSON
false
Modify StylePropertiesModel to work with JSON
libweb
diff --git a/Userland/Libraries/LibWeb/StylePropertiesModel.cpp b/Userland/Libraries/LibWeb/StylePropertiesModel.cpp index 50ebd5b5e76e..f2146d5f47aa 100644 --- a/Userland/Libraries/LibWeb/StylePropertiesModel.cpp +++ b/Userland/Libraries/LibWeb/StylePropertiesModel.cpp @@ -1,23 +1,21 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2021, Sam Atkins <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ +#include "StylePropertiesModel.h" #include <AK/QuickSort.h> -#include <LibWeb/CSS/PropertyID.h> -#include <LibWeb/CSS/StyleProperties.h> -#include <LibWeb/DOM/Document.h> -#include <LibWeb/StylePropertiesModel.h> namespace Web { -StylePropertiesModel::StylePropertiesModel(const CSS::StyleProperties& properties) - : m_properties(properties) +StylePropertiesModel::StylePropertiesModel(JsonObject properties) + : m_properties(move(properties)) { - properties.for_each_property([&](auto property_id, auto& property_value) { + m_properties.for_each_member([&](auto& property_name, auto& property_value) { Value value; - value.name = CSS::string_from_property_id(property_id); + value.name = property_name; value.value = property_value.to_string(); m_values.append(value); }); @@ -25,7 +23,11 @@ StylePropertiesModel::StylePropertiesModel(const CSS::StyleProperties& propertie quick_sort(m_values, [](auto& a, auto& b) { return a.name < b.name; }); } -int StylePropertiesModel::row_count(const GUI::ModelIndex&) const +StylePropertiesModel::~StylePropertiesModel() +{ +} + +int StylePropertiesModel::row_count(GUI::ModelIndex const&) const { return m_values.size(); } @@ -41,7 +43,8 @@ String StylePropertiesModel::column_name(int column_index) const VERIFY_NOT_REACHED(); } } -GUI::Variant StylePropertiesModel::data(const GUI::ModelIndex& index, GUI::ModelRole role) const + +GUI::Variant StylePropertiesModel::data(GUI::ModelIndex const& index, GUI::ModelRole role) const { auto& value = m_values[index.row()]; if (role == GUI::ModelRole::Display) { diff --git a/Userland/Libraries/LibWeb/StylePropertiesModel.h b/Userland/Libraries/LibWeb/StylePropertiesModel.h index a5e84c617aa1..3b7ae1742c51 100644 --- a/Userland/Libraries/LibWeb/StylePropertiesModel.h +++ b/Userland/Libraries/LibWeb/StylePropertiesModel.h @@ -1,19 +1,18 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2021, Sam Atkins <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once -#include <AK/NonnullRefPtrVector.h> +#include <AK/JsonObject.h> #include <LibGUI/Model.h> #include <LibWeb/CSS/StyleProperties.h> namespace Web { -class StyleProperties; - class StylePropertiesModel final : public GUI::Model { public: enum Column { @@ -22,18 +21,26 @@ class StylePropertiesModel final : public GUI::Model { __Count }; - static NonnullRefPtr<StylePropertiesModel> create(const CSS::StyleProperties& properties) { return adopt_ref(*new StylePropertiesModel(properties)); } + static NonnullRefPtr<StylePropertiesModel> create(StringView properties) + { + auto json_or_error = JsonValue::from_string(properties); + if (!json_or_error.has_value()) + VERIFY_NOT_REACHED(); + + return adopt_ref(*new StylePropertiesModel(json_or_error.value().as_object())); + } + + virtual ~StylePropertiesModel() override; - virtual int row_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override; - virtual int column_count(const GUI::ModelIndex& = GUI::ModelIndex()) const override { return Column::__Count; } + virtual int row_count(GUI::ModelIndex const& = GUI::ModelIndex()) const override; + virtual int column_count(GUI::ModelIndex const& = GUI::ModelIndex()) const override { return Column::__Count; } virtual String column_name(int) const override; - virtual GUI::Variant data(const GUI::ModelIndex&, GUI::ModelRole) const override; + virtual GUI::Variant data(GUI::ModelIndex const&, GUI::ModelRole) const override; private: - explicit StylePropertiesModel(const CSS::StyleProperties& properties); - const CSS::StyleProperties& properties() const { return *m_properties; } + explicit StylePropertiesModel(JsonObject); - NonnullRefPtr<CSS::StyleProperties> m_properties; + JsonObject m_properties; struct Value { String name;
fb7fadc38f12f45da6a58f17ff904303e58adbd8
2022-02-08 16:18:30
Lady Gegga
base: Add Spacing Modifier Letters to font Katica Regular 10
false
Add Spacing Modifier Letters to font Katica Regular 10
base
diff --git a/Base/res/fonts/KaticaRegular10.font b/Base/res/fonts/KaticaRegular10.font index 3cacdc7ccfbd..1b54ace36eba 100644 Binary files a/Base/res/fonts/KaticaRegular10.font and b/Base/res/fonts/KaticaRegular10.font differ
cd1d369cdd86b4870d65bc9ad856e8a0850cb4fb
2020-04-02 02:08:59
Andreas Kling
libjs: Add argument(i) and argument_count() to Interpreter
false
Add argument(i) and argument_count() to Interpreter
libjs
diff --git a/Libraries/LibJS/Interpreter.h b/Libraries/LibJS/Interpreter.h index 0f366c2df0af..77a4f7622ccf 100644 --- a/Libraries/LibJS/Interpreter.h +++ b/Libraries/LibJS/Interpreter.h @@ -107,6 +107,21 @@ class Interpreter { void pop_call_frame() { m_call_stack.take_last(); } const CallFrame& call_frame() { return m_call_stack.last(); } + size_t argument_count() const + { + if (m_call_stack.is_empty()) + return 0; + return m_call_stack.last().arguments.size(); + } + + Value argument(size_t index) const + { + if (m_call_stack.is_empty()) + return {}; + auto& arguments = m_call_stack.last().arguments; + return index < arguments.size() ? arguments[index] : js_undefined(); + } + Value this_value() const { if (m_call_stack.is_empty()) diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 0d3db3d18893..1fb33347b06b 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -50,9 +50,9 @@ Value ArrayPrototype::push(Interpreter& interpreter) if (!this_object) return {}; ASSERT(this_object->is_array()); - if (interpreter.call_frame().arguments.is_empty()) + if (!interpreter.argument_count()) return js_undefined(); - static_cast<Array*>(this_object)->push(interpreter.call_frame().arguments[0]); + static_cast<Array*>(this_object)->push(interpreter.argument(0)); return Value(static_cast<const Array*>(this_object)->length()); } diff --git a/Libraries/LibJS/Runtime/ConsoleObject.cpp b/Libraries/LibJS/Runtime/ConsoleObject.cpp index ee359d29df09..02c8f6fc674e 100644 --- a/Libraries/LibJS/Runtime/ConsoleObject.cpp +++ b/Libraries/LibJS/Runtime/ConsoleObject.cpp @@ -43,9 +43,9 @@ ConsoleObject::~ConsoleObject() Value ConsoleObject::log(Interpreter& interpreter) { - for (size_t i = 0; i < interpreter.call_frame().arguments.size(); ++i) { - printf("%s", interpreter.call_frame().arguments[i].to_string().characters()); - if (i != interpreter.call_frame().arguments.size() - 1) + for (size_t i = 0; i < interpreter.argument_count(); ++i) { + printf("%s", interpreter.argument(i).to_string().characters()); + if (i != interpreter.argument_count() - 1) putchar(' '); } putchar('\n'); diff --git a/Libraries/LibJS/Runtime/GlobalObject.cpp b/Libraries/LibJS/Runtime/GlobalObject.cpp index c09c5ce3cd0f..2035791fb981 100644 --- a/Libraries/LibJS/Runtime/GlobalObject.cpp +++ b/Libraries/LibJS/Runtime/GlobalObject.cpp @@ -39,9 +39,9 @@ Value GlobalObject::gc(Interpreter& interpreter) Value GlobalObject::is_nan(Interpreter& interpreter) { - if (interpreter.call_frame().arguments.size() < 1) + if (interpreter.argument_count() < 1) return js_undefined(); - return Value(interpreter.call_frame().arguments[0].to_number().is_nan()); + return Value(interpreter.argument(0).to_number().is_nan()); } } diff --git a/Libraries/LibJS/Runtime/MathObject.cpp b/Libraries/LibJS/Runtime/MathObject.cpp index 611a556a6cfe..225d2005b370 100644 --- a/Libraries/LibJS/Runtime/MathObject.cpp +++ b/Libraries/LibJS/Runtime/MathObject.cpp @@ -53,10 +53,10 @@ MathObject::~MathObject() Value MathObject::abs(Interpreter& interpreter) { - if (interpreter.call_frame().arguments.is_empty()) + if (!interpreter.argument_count()) return js_nan(); - auto number = interpreter.call_frame().arguments[0].to_number(); + auto number = interpreter.argument(0).to_number(); if (number.is_nan()) return js_nan(); return Value(number.as_double() >= 0 ? number.as_double() : -number.as_double()); diff --git a/Libraries/LibJS/Runtime/ObjectConstructor.cpp b/Libraries/LibJS/Runtime/ObjectConstructor.cpp index 613e34c76b77..ee529724cb61 100644 --- a/Libraries/LibJS/Runtime/ObjectConstructor.cpp +++ b/Libraries/LibJS/Runtime/ObjectConstructor.cpp @@ -57,9 +57,9 @@ Value ObjectConstructor::construct(Interpreter& interpreter) Value ObjectConstructor::get_own_property_names(Interpreter& interpreter) { - if (interpreter.call_frame().arguments.size() < 1) + if (!interpreter.argument_count()) return {}; - auto* object = interpreter.call_frame().arguments[0].to_object(interpreter.heap()); + auto* object = interpreter.argument(0).to_object(interpreter.heap()); if (interpreter.exception()) return {}; auto* result = interpreter.heap().allocate<Array>(); @@ -75,9 +75,9 @@ Value ObjectConstructor::get_own_property_names(Interpreter& interpreter) Value ObjectConstructor::get_prototype_of(Interpreter& interpreter) { - if (interpreter.call_frame().arguments.size() < 1) + if (!interpreter.argument_count()) return {}; - auto* object = interpreter.call_frame().arguments[0].to_object(interpreter.heap()); + auto* object = interpreter.argument(0).to_object(interpreter.heap()); if (interpreter.exception()) return {}; return object->prototype(); @@ -85,14 +85,14 @@ Value ObjectConstructor::get_prototype_of(Interpreter& interpreter) Value ObjectConstructor::set_prototype_of(Interpreter& interpreter) { - if (interpreter.call_frame().arguments.size() < 2) + if (interpreter.argument_count() < 2) return {}; - if (!interpreter.call_frame().arguments[1].is_object()) + if (!interpreter.argument(0).is_object()) return {}; - auto* object = interpreter.call_frame().arguments[0].to_object(interpreter.heap()); + auto* object = interpreter.argument(0).to_object(interpreter.heap()); if (interpreter.exception()) return {}; - object->set_prototype(&const_cast<Object&>(interpreter.call_frame().arguments[1].as_object())); + object->set_prototype(&const_cast<Object&>(interpreter.argument(1).as_object())); return {}; } diff --git a/Libraries/LibJS/Runtime/ObjectPrototype.cpp b/Libraries/LibJS/Runtime/ObjectPrototype.cpp index 96eaa4260256..8884056e901e 100644 --- a/Libraries/LibJS/Runtime/ObjectPrototype.cpp +++ b/Libraries/LibJS/Runtime/ObjectPrototype.cpp @@ -51,9 +51,9 @@ Value ObjectPrototype::has_own_property(Interpreter& interpreter) auto* this_object = interpreter.this_value().to_object(interpreter.heap()); if (!this_object) return {}; - if (interpreter.call_frame().arguments.is_empty()) - return js_undefined(); - return Value(this_object->has_own_property(interpreter.call_frame().arguments[0].to_string())); + if (!interpreter.argument_count()) + return {}; + return Value(this_object->has_own_property(interpreter.argument(0).to_string())); } Value ObjectPrototype::to_string(Interpreter& interpreter) diff --git a/Libraries/LibJS/Runtime/StringPrototype.cpp b/Libraries/LibJS/Runtime/StringPrototype.cpp index 6e871db06128..6a2cd0e8bd87 100644 --- a/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -54,8 +54,8 @@ Value StringPrototype::char_at(Interpreter& interpreter) if (!this_object) return {}; i32 index = 0; - if (!interpreter.call_frame().arguments.is_empty()) - index = interpreter.call_frame().arguments[0].to_i32(); + if (interpreter.argument_count()) + index = interpreter.argument(0).to_i32(); ASSERT(this_object->is_string_object()); auto underlying_string = static_cast<const StringObject*>(this_object)->primitive_string()->string(); if (index < 0 || index >= static_cast<i32>(underlying_string.length())) @@ -69,13 +69,13 @@ Value StringPrototype::repeat(Interpreter& interpreter) if (!this_object) return {}; ASSERT(this_object->is_string_object()); - if (interpreter.call_frame().arguments.is_empty()) + if (!interpreter.argument_count()) return js_string(interpreter.heap(), String::empty()); i32 count = 0; - count = interpreter.call_frame().arguments[0].to_i32(); + count = interpreter.argument(0).to_i32(); if (count < 0) { // FIXME: throw RangeError - return js_undefined(); + return {}; } auto* string_object = static_cast<StringObject*>(this_object); StringBuilder builder; @@ -89,13 +89,13 @@ Value StringPrototype::starts_with(Interpreter& interpreter) auto* this_object = interpreter.this_value().to_object(interpreter.heap()); if (!this_object) return {}; - if (interpreter.call_frame().arguments.is_empty()) + if (!interpreter.argument_count()) return Value(false); - auto search_string = interpreter.call_frame().arguments[0].to_string(); + auto search_string = interpreter.argument(0).to_string(); auto search_string_length = static_cast<i32>(search_string.length()); i32 position = 0; - if (interpreter.call_frame().arguments.size() > 1) { - auto number = interpreter.call_frame().arguments[1].to_number(); + if (interpreter.argument_count() > 1) { + auto number = interpreter.argument(1).to_number(); if (!number.is_nan()) position = number.to_i32(); } diff --git a/Userland/js.cpp b/Userland/js.cpp index f0a5665a7155..bfe9309a1545 100644 --- a/Userland/js.cpp +++ b/Userland/js.cpp @@ -211,9 +211,9 @@ ReplObject::~ReplObject() JS::Value ReplObject::exit_interpreter(JS::Interpreter& interpreter) { - if (interpreter.call_frame().arguments.is_empty()) + if (!interpreter.argument_count()) exit(0); - int exit_code = interpreter.call_frame().arguments[0].to_number().as_double(); + int exit_code = interpreter.argument(0).to_number().as_double(); exit(exit_code); return JS::js_undefined(); } @@ -230,10 +230,10 @@ JS::Value ReplObject::repl_help(JS::Interpreter& interpreter) JS::Value ReplObject::load_file(JS::Interpreter& interpreter) { - if (interpreter.call_frame().arguments.is_empty()) + if (!interpreter.argument_count()) return JS::Value(false); - Vector<JS::Value> files = interpreter.call_frame().arguments; - for (JS::Value file : files) { + + for (auto& file : interpreter.call_frame().arguments) { String file_name = file.as_string()->string(); auto js_file = Core::File::construct(file_name); if (!js_file->open(Core::IODevice::ReadOnly)) {
3e07b04564acc6cf36124be785d2b4471195d5e7
2021-09-08 23:46:00
Andreas Kling
kernel: Remove some unused code in Graphics::TextModeConsole
false
Remove some unused code in Graphics::TextModeConsole
kernel
diff --git a/Kernel/Graphics/Console/TextModeConsole.cpp b/Kernel/Graphics/Console/TextModeConsole.cpp index 9df455e4bd06..fc55c56e9433 100644 --- a/Kernel/Graphics/Console/TextModeConsole.cpp +++ b/Kernel/Graphics/Console/TextModeConsole.cpp @@ -89,9 +89,7 @@ void TextModeConsole::set_cursor(size_t x, size_t y) { SpinlockLocker main_lock(GraphicsManagement::the().main_vga_lock()); SpinlockLocker lock(m_vga_lock); - m_cursor_x = x; - m_cursor_y = y; - u16 value = m_current_vga_start_address + (y * width() + x); + u16 value = y * width() + x; IO::out8(0x3d4, 0x0e); IO::out8(0x3d5, MSB(value)); IO::out8(0x3d4, 0x0f); @@ -160,18 +158,6 @@ void TextModeConsole::clear_vga_row(u16 row) clear(row * width(), width(), width()); } -void TextModeConsole::set_vga_start_row(u16 row) -{ - SpinlockLocker lock(m_vga_lock); - m_vga_start_row = row; - m_current_vga_start_address = row * width(); - m_current_vga_window = m_current_vga_window + row * width() * bytes_per_base_glyph(); - IO::out8(0x3d4, 0x0c); - IO::out8(0x3d5, MSB(m_current_vga_start_address)); - IO::out8(0x3d4, 0x0d); - IO::out8(0x3d5, LSB(m_current_vga_start_address)); -} - void TextModeConsole::write(char ch, bool critical) { write(m_x, m_y, ch, critical); diff --git a/Kernel/Graphics/Console/TextModeConsole.h b/Kernel/Graphics/Console/TextModeConsole.h index 72e2e28d5ca5..9a5ebfc4da92 100644 --- a/Kernel/Graphics/Console/TextModeConsole.h +++ b/Kernel/Graphics/Console/TextModeConsole.h @@ -35,15 +35,11 @@ class TextModeConsole final : public VGAConsole { private: void clear_vga_row(u16 row); - void set_vga_start_row(u16 row); explicit TextModeConsole(const VGACompatibleAdapter&); mutable Spinlock m_vga_lock; - u16 m_vga_start_row { 0 }; - u16 m_current_vga_start_address { 0 }; u8* m_current_vga_window { nullptr }; - u16 m_cursor_x { 0 }; - u16 m_cursor_y { 0 }; }; + }
973cc67e81ad6a3a70b693a4b0559d93a4c94fc9
2024-04-05 02:47:57
Shannon Booth
libweb: Implement <a> element activation behavior for ismap <img>s
false
Implement <a> element activation behavior for ismap <img>s
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLAnchorElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLAnchorElement.cpp index 56516ed247fb..26a143c75334 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLAnchorElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLAnchorElement.cpp @@ -1,13 +1,19 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2024, Shannon Booth <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibWeb/ARIA/Roles.h> +#include <LibWeb/DOM/Event.h> +#include <LibWeb/HTML/AttributeNames.h> #include <LibWeb/HTML/HTMLAnchorElement.h> +#include <LibWeb/HTML/HTMLImageElement.h> #include <LibWeb/HTML/Window.h> +#include <LibWeb/PixelUnits.h> #include <LibWeb/ReferrerPolicy/ReferrerPolicy.h> +#include <LibWeb/UIEvents/MouseEvent.h> namespace Web::HTML { @@ -61,23 +67,30 @@ void HTMLAnchorElement::activation_behavior(Web::DOM::Event const& event) // 2. Let hyperlinkSuffix be null. Optional<String> hyperlink_suffix {}; - // FIXME: 3. If element is an a element, and event's target is an img with an ismap attribute specified, then: - // - // 3.1. Let x and y be 0. - // - // 3.2. If event's isTrusted attribute is initialized to true, then - // set x to the distance in CSS pixels from the left edge of the image - // to the location of the click, and set y to the distance in CSS - // pixels from the top edge of the image to the location of the click. - // - // 3.3. If x is negative, set x to 0. - // - // 3.4. If y is negative, set y to 0. - // - // 3.5. Set hyperlinkSuffix to the concatenation of U+003F (?), the - // value of x expressed as a base-ten integer using ASCII digits, - // U+002C (,), and the value of y expressed as a base-ten integer - // using ASCII digits. + // 3. If element is an a element, and event's target is an img with an ismap attribute specified, then: + if (event.target() && is<HTMLImageElement>(*event.target()) && static_cast<HTMLImageElement const&>(*event.target()).has_attribute(AttributeNames::ismap)) { + // 1. Let x and y be 0. + CSSPixels x { 0 }; + CSSPixels y { 0 }; + + // 2. If event's isTrusted attribute is initialized to true, then set x to the distance in CSS pixels from the left edge of the image + // to the location of the click, and set y to the distance in CSS pixels from the top edge of the image to the location of the click. + if (event.is_trusted() && is<UIEvents::MouseEvent>(event)) { + auto const& mouse_event = static_cast<UIEvents::MouseEvent const&>(event); + x = CSSPixels { mouse_event.offset_x() }; + y = CSSPixels { mouse_event.offset_y() }; + } + + // 3. If x is negative, set x to 0. + x = max(x, 0); + + // 4. If y is negative, set y to 0. + y = max(y, 0); + + // 5. Set hyperlinkSuffix to the concatenation of U+003F (?), the value of x expressed as a base-ten integer using ASCII digits, + // U+002C (,), and the value of y expressed as a base-ten integer using ASCII digits. + hyperlink_suffix = MUST(String::formatted("?{},{}", x.to_int(), y.to_int())); + } // 4. Let userInvolvement be event's user navigation involvement. auto user_involvement = user_navigation_involvement(event);
775e6d6865a2e74235d3811572982a73bba4cbc5
2023-04-04 14:03:42
Andreas Kling
kernel: Mark sys$fcntl as not needing the big lock
false
Mark sys$fcntl as not needing the big lock
kernel
diff --git a/Kernel/API/Syscall.h b/Kernel/API/Syscall.h index 708e547e83e3..0ea820c6d99e 100644 --- a/Kernel/API/Syscall.h +++ b/Kernel/API/Syscall.h @@ -77,7 +77,7 @@ enum class NeedsBigProcessLock { S(fchdir, NeedsBigProcessLock::No) \ S(fchmod, NeedsBigProcessLock::No) \ S(fchown, NeedsBigProcessLock::No) \ - S(fcntl, NeedsBigProcessLock::Yes) \ + S(fcntl, NeedsBigProcessLock::No) \ S(fork, NeedsBigProcessLock::Yes) \ S(fstat, NeedsBigProcessLock::No) \ S(fstatvfs, NeedsBigProcessLock::No) \ diff --git a/Kernel/Syscalls/fcntl.cpp b/Kernel/Syscalls/fcntl.cpp index 4523f969cba7..81dcef7325f7 100644 --- a/Kernel/Syscalls/fcntl.cpp +++ b/Kernel/Syscalls/fcntl.cpp @@ -12,7 +12,7 @@ namespace Kernel { ErrorOr<FlatPtr> Process::sys$fcntl(int fd, int cmd, uintptr_t arg) { - VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this); + VERIFY_NO_PROCESS_BIG_LOCK(this); TRY(require_promise(Pledge::stdio)); dbgln_if(IO_DEBUG, "sys$fcntl: fd={}, cmd={}, arg={}", fd, cmd, arg); auto description = TRY(open_file_description(fd));
a4aced7f3a388abbc67a1f9a21d9daaad8b53dee
2022-06-28 22:22:42
FrHun
libgui: Introduce UIDimension properties
false
Introduce UIDimension properties
libgui
diff --git a/Userland/Libraries/LibGUI/UIDimensions.h b/Userland/Libraries/LibGUI/UIDimensions.h index b2061a5b4537..257ac1a6aefe 100644 --- a/Userland/Libraries/LibGUI/UIDimensions.h +++ b/Userland/Libraries/LibGUI/UIDimensions.h @@ -288,3 +288,41 @@ inline auto clamp<GUI::UIDimension>(GUI::UIDimension const& input, GUI::UIDimens } } + +#define REGISTER_UI_DIMENSION_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, \ + [this] { \ + return this->getter().as_json_value(); \ + }, \ + [this](auto& value) { \ + auto result = GUI::UIDimension::construct_from_json_value(value); \ + if (result.has_value()) \ + this->setter(result.value()); \ + return result.has_value(); \ + }); + +#define REGISTER_UI_SIZE_PROPERTY(property_name, getter, setter) \ + register_property( \ + property_name, \ + [this] { \ + auto size = this->getter(); \ + JsonObject size_object; \ + size_object.set("width", size.width().as_json_value()); \ + size_object.set("height", size.height().as_json_value()); \ + return size_object; \ + }, \ + [this](auto& value) { \ + if (!value.is_object()) \ + return false; \ + auto result_width = GUI::UIDimension::construct_from_json_value( \ + value.as_object().get("width")); \ + auto result_height = GUI::UIDimension::construct_from_json_value( \ + value.as_object().get("height")); \ + if (result_width.has_value() && result_height.has_value()) { \ + GUI::UISize size(result_width.value(), result_height.value()); \ + setter(size); \ + return true; \ + } \ + return false; \ + }); diff --git a/Userland/Libraries/LibGUI/Widget.cpp b/Userland/Libraries/LibGUI/Widget.cpp index 80cfc8265f4d..80d1e720df03 100644 --- a/Userland/Libraries/LibGUI/Widget.cpp +++ b/Userland/Libraries/LibGUI/Widget.cpp @@ -49,14 +49,14 @@ Widget::Widget() REGISTER_BOOL_PROPERTY("enabled", is_enabled, set_enabled); REGISTER_STRING_PROPERTY("tooltip", tooltip, set_tooltip); - REGISTER_SIZE_PROPERTY("min_size", min_size, set_min_size); - REGISTER_SIZE_PROPERTY("max_size", max_size, set_max_size); + REGISTER_UI_SIZE_PROPERTY("min_size", min_size, set_min_size); + REGISTER_UI_SIZE_PROPERTY("max_size", max_size, set_max_size); REGISTER_INT_PROPERTY("width", width, set_width); - REGISTER_INT_PROPERTY("min_width", min_width, set_min_width); - REGISTER_INT_PROPERTY("max_width", max_width, set_max_width); - REGISTER_INT_PROPERTY("min_height", min_height, set_min_height); + REGISTER_UI_DIMENSION_PROPERTY("min_width", min_width, set_min_width); + REGISTER_UI_DIMENSION_PROPERTY("max_width", max_width, set_max_width); REGISTER_INT_PROPERTY("height", height, set_height); - REGISTER_INT_PROPERTY("max_height", max_height, set_max_height); + REGISTER_UI_DIMENSION_PROPERTY("min_height", min_height, set_min_height); + REGISTER_UI_DIMENSION_PROPERTY("max_height", max_height, set_max_height); REGISTER_INT_PROPERTY("fixed_width", dummy_fixed_width, set_fixed_width); REGISTER_INT_PROPERTY("fixed_height", dummy_fixed_height, set_fixed_height);
c83a3db542d57236efbfba362f136a7ef9246617
2024-11-24 06:05:36
Timothy Flynn
libjs: Handle Temporal.PlainDate in dynamic calendar operations
false
Handle Temporal.PlainDate in dynamic calendar operations
libjs
diff --git a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp index 8f01fabd29d8..3223eb696f9b 100644 --- a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp +++ b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp @@ -624,6 +624,8 @@ ThrowCompletionOr<bool> is_partial_temporal_object(VM& vm, Value value) // [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal // slot, return false. // FIXME: Add the other types as we define them. + if (is<PlainDate>(object)) + return false; if (is<PlainMonthDay>(object)) return false; if (is<PlainYearMonth>(object)) diff --git a/Libraries/LibJS/Runtime/Temporal/Calendar.cpp b/Libraries/LibJS/Runtime/Temporal/Calendar.cpp index fb185cfbeccf..34083508d492 100644 --- a/Libraries/LibJS/Runtime/Temporal/Calendar.cpp +++ b/Libraries/LibJS/Runtime/Temporal/Calendar.cpp @@ -452,6 +452,8 @@ ThrowCompletionOr<String> to_temporal_calendar_identifier(VM& vm, Value temporal // internal slot, then // i. Return temporalCalendarLike.[[Calendar]]. // FIXME: Add the other calendar-holding types as we define them. + if (is<PlainDate>(temporal_calendar_object)) + return static_cast<PlainDate const&>(temporal_calendar_object).calendar(); if (is<PlainMonthDay>(temporal_calendar_object)) return static_cast<PlainMonthDay const&>(temporal_calendar_object).calendar(); if (is<PlainYearMonth>(temporal_calendar_object)) @@ -476,6 +478,8 @@ ThrowCompletionOr<String> get_temporal_calendar_identifier_with_iso_default(VM& // [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then // a. Return item.[[Calendar]]. // FIXME: Add the other calendar-holding types as we define them. + if (is<PlainDate>(item)) + return static_cast<PlainDate const&>(item).calendar(); if (is<PlainMonthDay>(item)) return static_cast<PlainMonthDay const&>(item).calendar(); if (is<PlainYearMonth>(item))
c2b3bab984865796dee3c385b50cb601f84f7363
2022-01-09 04:49:47
Mustafa Quraish
pixelpaint: Move `save` and `save_as` logic inside `ImageEditor`
false
Move `save` and `save_as` logic inside `ImageEditor`
pixelpaint
diff --git a/Userland/Applications/PixelPaint/ImageEditor.cpp b/Userland/Applications/PixelPaint/ImageEditor.cpp index 0468ef861aab..8c560b1fab81 100644 --- a/Userland/Applications/PixelPaint/ImageEditor.cpp +++ b/Userland/Applications/PixelPaint/ImageEditor.cpp @@ -14,7 +14,9 @@ #include "Tools/Tool.h" #include <AK/LexicalPath.h> #include <LibConfig/Client.h> +#include <LibFileSystemAccessClient/Client.h> #include <LibGUI/Command.h> +#include <LibGUI/MessageBox.h> #include <LibGUI/Painter.h> #include <LibGfx/DisjointRectSet.h> #include <LibGfx/Palette.h> @@ -698,6 +700,37 @@ void ImageEditor::image_select_layer(Layer* layer) set_active_layer(layer); } +void ImageEditor::save_project() +{ + if (path().is_empty()) { + save_project_as(); + return; + } + auto response = FileSystemAccessClient::Client::the().request_file(window()->window_id(), path(), Core::OpenMode::Truncate | Core::OpenMode::WriteOnly); + if (response.error != 0) + return; + auto result = save_project_to_fd_and_close(*response.fd); + if (result.is_error()) { + GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", *response.chosen_file, result.error())); + return; + } + undo_stack().set_current_unmodified(); +} + +void ImageEditor::save_project_as() +{ + auto save_result = FileSystemAccessClient::Client::the().save_file(window()->window_id(), "untitled", "pp"); + if (save_result.error != 0) + return; + auto result = save_project_to_fd_and_close(*save_result.fd); + if (result.is_error()) { + GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", *save_result.chosen_file, result.error())); + return; + } + set_path(*save_result.chosen_file); + undo_stack().set_current_unmodified(); +} + Result<void, String> ImageEditor::save_project_to_fd_and_close(int fd) const { StringBuilder builder; diff --git a/Userland/Applications/PixelPaint/ImageEditor.h b/Userland/Applications/PixelPaint/ImageEditor.h index a660ac120221..fd8cf7ca475c 100644 --- a/Userland/Applications/PixelPaint/ImageEditor.h +++ b/Userland/Applications/PixelPaint/ImageEditor.h @@ -109,7 +109,8 @@ class ImageEditor final Gfx::FloatPoint image_position_to_editor_position(Gfx::IntPoint const&) const; Gfx::FloatPoint editor_position_to_image_position(Gfx::IntPoint const&) const; - Result<void, String> save_project_to_fd_and_close(int fd) const; + void save_project_as(); + void save_project(); NonnullRefPtrVector<Guide> const& guides() const { return m_guides; } bool guide_visibility() { return m_show_guides; } @@ -149,6 +150,8 @@ class ImageEditor final GUI::MouseEvent event_adjusted_for_layer(GUI::MouseEvent const&, Layer const&) const; GUI::MouseEvent event_with_pan_and_scale_applied(GUI::MouseEvent const&) const; + Result<void, String> save_project_to_fd_and_close(int fd) const; + void clamped_scale_by(float, bool do_relayout); void relayout(); diff --git a/Userland/Applications/PixelPaint/MainWidget.cpp b/Userland/Applications/PixelPaint/MainWidget.cpp index 144d0deb2043..bd4dfc1f733e 100644 --- a/Userland/Applications/PixelPaint/MainWidget.cpp +++ b/Userland/Applications/PixelPaint/MainWidget.cpp @@ -133,38 +133,13 @@ void MainWidget::initialize_menubar(GUI::Window& window) }); m_save_image_as_action = GUI::CommonActions::make_save_as_action([&](auto&) { - auto* editor = current_image_editor(); - if (!editor) - return; - auto save_result = FileSystemAccessClient::Client::the().save_file(window.window_id(), "untitled", "pp"); - if (save_result.error != 0) - return; - auto result = editor->save_project_to_fd_and_close(*save_result.fd); - if (result.is_error()) { - GUI::MessageBox::show_error(&window, String::formatted("Could not save {}: {}", *save_result.chosen_file, result.error())); - return; - } - editor->set_path(*save_result.chosen_file); - editor->undo_stack().set_current_unmodified(); + if (auto* editor = current_image_editor()) + editor->save_project_as(); }); m_save_image_action = GUI::CommonActions::make_save_action([&](auto&) { - auto* editor = current_image_editor(); - if (!editor) - return; - if (editor->path().is_empty()) { - m_save_image_as_action->activate(); - return; - } - auto response = FileSystemAccessClient::Client::the().request_file(window.window_id(), editor->path(), Core::OpenMode::Truncate | Core::OpenMode::WriteOnly); - if (response.error != 0) - return; - auto result = editor->save_project_to_fd_and_close(*response.fd); - if (result.is_error()) { - GUI::MessageBox::show_error(&window, String::formatted("Could not save {}: {}", *response.chosen_file, result.error())); - return; - } - editor->undo_stack().set_current_unmodified(); + if (auto* editor = current_image_editor()) + editor->save_project(); }); file_menu.add_action(*m_new_image_action);
fff2c35f512a21e414ade5aea8f9f6d237d6eb4f
2022-04-13 02:33:46
Sam Atkins
libweb: Move ComponentValue to CSS::Parser namespace
false
Move ComponentValue to CSS::Parser namespace
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.cpp b/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.cpp index bc5fbf2644d8..58e80cc03540 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.cpp @@ -9,7 +9,7 @@ #include <LibWeb/CSS/Parser/StyleBlockRule.h> #include <LibWeb/CSS/Parser/StyleFunctionRule.h> -namespace Web::CSS { +namespace Web::CSS::Parser { ComponentValue::ComponentValue(Token token) : m_value(token) diff --git a/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.h b/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.h index 1c5fdca31fda..30fa3fa52c59 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/ComponentValue.h @@ -12,9 +12,11 @@ #include <LibWeb/CSS/Parser/Token.h> namespace Web::CSS { - class StyleBlockRule; class StyleFunctionRule; +} + +namespace Web::CSS::Parser { // https://www.w3.org/TR/css-syntax-3/#component-value class ComponentValue { diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h b/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h index 35d8ef744137..45af2a799c08 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/Declaration.h @@ -21,14 +21,14 @@ class Declaration { ~Declaration(); String const& name() const { return m_name; } - Vector<ComponentValue> const& values() const { return m_values; } + Vector<Parser::ComponentValue> const& values() const { return m_values; } Important importance() const { return m_important; } String to_string() const; private: String m_name; - Vector<ComponentValue> m_values; + Vector<Parser::ComponentValue> m_values; Important m_important { Important::No }; }; diff --git a/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h b/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h index d0573bb342c3..fc164cfaa771 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/StyleBlockRule.h @@ -20,7 +20,7 @@ class StyleBlockRule : public RefCounted<StyleBlockRule> { public: StyleBlockRule(); - explicit StyleBlockRule(Token token, Vector<ComponentValue>&& values) + explicit StyleBlockRule(Token token, Vector<Parser::ComponentValue>&& values) : m_token(move(token)) , m_values(move(values)) { @@ -33,12 +33,12 @@ class StyleBlockRule : public RefCounted<StyleBlockRule> { Token const& token() const { return m_token; } - Vector<ComponentValue> const& values() const { return m_values; } + Vector<Parser::ComponentValue> const& values() const { return m_values; } String to_string() const; private: Token m_token; - Vector<ComponentValue> m_values; + Vector<Parser::ComponentValue> m_values; }; } diff --git a/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h b/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h index 356fef1d7f13..239955b4ccc3 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/StyleFunctionRule.h @@ -20,16 +20,16 @@ class StyleFunctionRule : public RefCounted<StyleFunctionRule> { public: explicit StyleFunctionRule(String name); - StyleFunctionRule(String name, Vector<ComponentValue>&& values); + StyleFunctionRule(String name, Vector<Parser::ComponentValue>&& values); ~StyleFunctionRule(); String const& name() const { return m_name; } - Vector<ComponentValue> const& values() const { return m_values; } + Vector<Parser::ComponentValue> const& values() const { return m_values; } String to_string() const; private: String m_name; - Vector<ComponentValue> m_values; + Vector<Parser::ComponentValue> m_values; }; } diff --git a/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h b/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h index b999883abe0a..018599e3de17 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/StyleRule.h @@ -29,7 +29,7 @@ class StyleRule : public RefCounted<StyleRule> { bool is_qualified_rule() const { return m_type == Type::Qualified; } bool is_at_rule() const { return m_type == Type::At; } - Vector<ComponentValue> const& prelude() const { return m_prelude; } + Vector<Parser::ComponentValue> const& prelude() const { return m_prelude; } RefPtr<StyleBlockRule const> block() const { return m_block; } String const& at_rule_name() const { return m_at_rule_name; } @@ -38,7 +38,7 @@ class StyleRule : public RefCounted<StyleRule> { private: Type const m_type; String m_at_rule_name; - Vector<ComponentValue> m_prelude; + Vector<Parser::ComponentValue> m_prelude; RefPtr<StyleBlockRule> m_block; }; diff --git a/Userland/Libraries/LibWeb/CSS/Parser/StyleRules.cpp b/Userland/Libraries/LibWeb/CSS/Parser/StyleRules.cpp index 460f3dec0025..a8bf8e97434d 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/StyleRules.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/StyleRules.cpp @@ -44,7 +44,7 @@ StyleFunctionRule::StyleFunctionRule(String name) { } -StyleFunctionRule::StyleFunctionRule(String name, Vector<ComponentValue>&& values) +StyleFunctionRule::StyleFunctionRule(String name, Vector<Parser::ComponentValue>&& values) : m_name(move(name)) , m_values(move(values)) { diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp index 601818e2d331..8a0d4c857b79 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp @@ -526,10 +526,10 @@ static RefPtr<StyleValue> get_custom_property(DOM::Element const& element, FlySt return nullptr; } -bool StyleComputer::expand_unresolved_values(DOM::Element& element, StringView property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, Vector<ComponentValue> const& source, Vector<ComponentValue>& dest, size_t source_start_index) const +bool StyleComputer::expand_unresolved_values(DOM::Element& element, StringView property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, Vector<Parser::ComponentValue> const& source, Vector<Parser::ComponentValue>& dest, size_t source_start_index) const { // FIXME: Do this better! - // We build a copy of the tree of StyleComponentValueRules, with all var()s and attr()s replaced with their contents. + // We build a copy of the tree of ComponentValues, with all var()s and attr()s replaced with their contents. // This is a very naive solution, and we could do better if the CSS Parser could accept tokens one at a time. // Arbitrary large value chosen to avoid the billion-laughs attack. @@ -619,7 +619,7 @@ bool StyleComputer::expand_unresolved_values(DOM::Element& element, StringView p } auto const& source_function = value.function(); - Vector<ComponentValue> function_values; + Vector<Parser::ComponentValue> function_values; if (!expand_unresolved_values(element, property_name, dependencies, source_function.values(), function_values, 0)) return false; NonnullRefPtr<StyleFunctionRule> function = adopt_ref(*new StyleFunctionRule(source_function.name(), move(function_values))); @@ -628,7 +628,7 @@ bool StyleComputer::expand_unresolved_values(DOM::Element& element, StringView p } if (value.is_block()) { auto const& source_block = value.block(); - Vector<ComponentValue> block_values; + Vector<Parser::ComponentValue> block_values; if (!expand_unresolved_values(element, property_name, dependencies, source_block.values(), block_values, 0)) return false; NonnullRefPtr<StyleBlockRule> block = adopt_ref(*new StyleBlockRule(source_block.token(), move(block_values))); @@ -647,7 +647,7 @@ RefPtr<StyleValue> StyleComputer::resolve_unresolved_style_value(DOM::Element& e // to produce a different StyleValue from it. VERIFY(unresolved.contains_var_or_attr()); - Vector<ComponentValue> expanded_values; + Vector<Parser::ComponentValue> expanded_values; HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies; if (!expand_unresolved_values(element, string_from_property_id(property_id), dependencies, unresolved.values(), expanded_values, 0)) return {}; diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.h b/Userland/Libraries/LibWeb/CSS/StyleComputer.h index d54393ae880c..b9cd4993e400 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.h +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.h @@ -86,7 +86,7 @@ class StyleComputer { void compute_defaulted_property_value(StyleProperties&, DOM::Element const*, CSS::PropertyID, Optional<CSS::Selector::PseudoElement>) const; RefPtr<StyleValue> resolve_unresolved_style_value(DOM::Element&, PropertyID, UnresolvedStyleValue const&) const; - bool expand_unresolved_values(DOM::Element&, StringView property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, Vector<ComponentValue> const& source, Vector<ComponentValue>& dest, size_t source_start_index) const; + bool expand_unresolved_values(DOM::Element&, StringView property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, Vector<Parser::ComponentValue> const& source, Vector<Parser::ComponentValue>& dest, size_t source_start_index) const; template<typename Callback> void for_each_stylesheet(CascadeOrigin, Callback) const; diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h index 951563af9d93..15107f7a7991 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h @@ -1625,7 +1625,7 @@ class TransformationStyleValue final : public StyleValue { class UnresolvedStyleValue final : public StyleValue { public: - static NonnullRefPtr<UnresolvedStyleValue> create(Vector<ComponentValue>&& values, bool contains_var_or_attr) + static NonnullRefPtr<UnresolvedStyleValue> create(Vector<Parser::ComponentValue>&& values, bool contains_var_or_attr) { return adopt_ref(*new UnresolvedStyleValue(move(values), contains_var_or_attr)); } @@ -1633,18 +1633,18 @@ class UnresolvedStyleValue final : public StyleValue { virtual String to_string() const override; - Vector<ComponentValue> const& values() const { return m_values; } + Vector<Parser::ComponentValue> const& values() const { return m_values; } bool contains_var_or_attr() const { return m_contains_var_or_attr; } private: - UnresolvedStyleValue(Vector<ComponentValue>&& values, bool contains_var_or_attr) + UnresolvedStyleValue(Vector<Parser::ComponentValue>&& values, bool contains_var_or_attr) : StyleValue(Type::Unresolved) , m_values(move(values)) , m_contains_var_or_attr(contains_var_or_attr) { } - Vector<ComponentValue> m_values; + Vector<Parser::ComponentValue> m_values; bool m_contains_var_or_attr { false }; }; diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index 933133b5eb3e..b06e1f78c2be 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -99,6 +99,7 @@ enum class ValueID; } namespace Web::CSS::Parser { +class ComponentValue; class Parser; }
693d34fe3d590e1a7c92f3f44e7b0dad02e37dc0
2022-07-10 16:22:18
Karol Kosek
libcompress: Write Deflate window size in the Zlib header
false
Write Deflate window size in the Zlib header
libcompress
diff --git a/Userland/Libraries/LibCompress/Zlib.cpp b/Userland/Libraries/LibCompress/Zlib.cpp index eb0f43e17376..f0ff7354ee16 100644 --- a/Userland/Libraries/LibCompress/Zlib.cpp +++ b/Userland/Libraries/LibCompress/Zlib.cpp @@ -84,9 +84,15 @@ ZlibCompressor::~ZlibCompressor() void ZlibCompressor::write_header(ZlibCompressionMethod compression_method, ZlibCompressionLevel compression_level) { + u8 compression_info = 0; + if (compression_method == ZlibCompressionMethod::Deflate) { + compression_info = AK::log2(DeflateCompressor::window_size) - 8; + VERIFY(compression_info <= 7); + } + ZlibHeader header { .compression_method = compression_method, - .compression_info = 0, + .compression_info = compression_info, .check_bits = 0, .present_dictionary = false, .compression_level = compression_level,
21ae882cfd9a6fb1a95c092916bea346445ea4aa
2022-08-31 19:52:36
Hendiadyoin1
libjs: Implement SuperCall for the Bytecode-VM
false
Implement SuperCall for the Bytecode-VM
libjs
diff --git a/Userland/Libraries/LibJS/AST.h b/Userland/Libraries/LibJS/AST.h index 87f7e9ae5f54..13cf6f55d92a 100644 --- a/Userland/Libraries/LibJS/AST.h +++ b/Userland/Libraries/LibJS/AST.h @@ -1516,6 +1516,7 @@ class SuperCall final : public Expression { virtual Completion execute(Interpreter&) const override; virtual void dump(int indent) const override; + virtual Bytecode::CodeGenerationErrorOr<void> generate_bytecode(Bytecode::Generator&) const override; private: Vector<CallExpression::Argument> const m_arguments; diff --git a/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp b/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp index 5a4e8dd37ff9..7c3bec1fe79b 100644 --- a/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp +++ b/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp @@ -521,6 +521,34 @@ Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Ge return {}; } +Bytecode::CodeGenerationErrorOr<void> SuperCall::generate_bytecode(Bytecode::Generator& generator) const +{ + Vector<Bytecode::Register> argument_registers; + + if (m_is_synthetic == IsPartOfSyntheticConstructor::Yes) { + // NOTE: This is the case where we have a fake constructor(...args) { super(...args); } which + // shouldn't call @@iterator of %Array.prototype%. + VERIFY(m_arguments.size() == 1); + VERIFY(m_arguments[0].is_spread); + auto const& argument = m_arguments[0]; + // This generates a single argument, which will be implicitly passed in accumulator + MUST(argument.value->generate_bytecode(generator)); + } else { + argument_registers.ensure_capacity(m_arguments.size()); + + for (auto const& arg : m_arguments) { + TRY(arg.value->generate_bytecode(generator)); + auto arg_reg = generator.allocate_register(); + generator.emit<Bytecode::Op::Store>(arg_reg); + argument_registers.unchecked_append(arg_reg); + } + } + + generator.emit_with_extra_register_slots<Bytecode::Op::SuperCall>(argument_registers.size(), m_is_synthetic == IsPartOfSyntheticConstructor::Yes, argument_registers); + + return {}; +} + static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg); Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const diff --git a/Userland/Libraries/LibJS/Bytecode/Instruction.h b/Userland/Libraries/LibJS/Bytecode/Instruction.h index d5accd5586bc..befd238fc149 100644 --- a/Userland/Libraries/LibJS/Bytecode/Instruction.h +++ b/Userland/Libraries/LibJS/Bytecode/Instruction.h @@ -80,6 +80,7 @@ O(StrictlyEquals) \ O(StrictlyInequals) \ O(Sub) \ + O(SuperCall) \ O(Throw) \ O(Typeof) \ O(TypeofVariable) \ diff --git a/Userland/Libraries/LibJS/Bytecode/Op.cpp b/Userland/Libraries/LibJS/Bytecode/Op.cpp index b931410d70fc..a9f41f994b88 100644 --- a/Userland/Libraries/LibJS/Bytecode/Op.cpp +++ b/Userland/Libraries/LibJS/Bytecode/Op.cpp @@ -15,6 +15,7 @@ #include <LibJS/Runtime/DeclarativeEnvironment.h> #include <LibJS/Runtime/ECMAScriptFunctionObject.h> #include <LibJS/Runtime/Environment.h> +#include <LibJS/Runtime/FunctionEnvironment.h> #include <LibJS/Runtime/GlobalEnvironment.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/Iterator.h> @@ -525,6 +526,60 @@ ThrowCompletionOr<void> Call::execute_impl(Bytecode::Interpreter& interpreter) c return {}; } +// 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation +ThrowCompletionOr<void> SuperCall::execute_impl(Bytecode::Interpreter& interpreter) const +{ + auto& vm = interpreter.vm(); + // 1. Let newTarget be GetNewTarget(). + auto new_target = vm.get_new_target(); + + // 2. Assert: Type(newTarget) is Object. + VERIFY(new_target.is_object()); + + // 3. Let func be GetSuperConstructor(). + auto* func = get_super_constructor(vm); + + // 4. Let argList be ? ArgumentListEvaluation of Arguments. + MarkedVector<Value> arg_list { vm.heap() }; + if (m_is_synthetic) { + auto const& value = interpreter.accumulator(); + VERIFY(value.is_object() && is<Array>(value.as_object())); + auto const& array_value = static_cast<Array const&>(value.as_object()); + auto length = MUST(length_of_array_like(vm, array_value)); + for (size_t i = 0; i < length; ++i) + arg_list.append(array_value.get_without_side_effects(PropertyKey { i })); + } else { + for (size_t i = 0; i < m_argument_count; ++i) + arg_list.append(interpreter.reg(m_arguments[i])); + } + + // 5. If IsConstructor(func) is false, throw a TypeError exception. + if (!Value(func).is_constructor()) + return vm.throw_completion<TypeError>(ErrorType::NotAConstructor, "Super constructor"); + + // 6. Let result be ? Construct(func, argList, newTarget). + auto* result = TRY(construct(vm, static_cast<FunctionObject&>(*func), move(arg_list), &new_target.as_function())); + + // 7. Let thisER be GetThisEnvironment(). + auto& this_environment = verify_cast<FunctionEnvironment>(get_this_environment(vm)); + + // 8. Perform ? thisER.BindThisValue(result). + TRY(this_environment.bind_this_value(vm, result)); + + // 9. Let F be thisER.[[FunctionObject]]. + auto& f = this_environment.function_object(); + + // 10. Assert: F is an ECMAScript function object. + // NOTE: This is implied by the strong C++ type. + + // 11. Perform ? InitializeInstanceElements(result, F). + TRY(vm.initialize_instance_elements(*result, f)); + + // 12. Return result. + interpreter.accumulator() = result; + return {}; +} + ThrowCompletionOr<void> NewFunction::execute_impl(Bytecode::Interpreter& interpreter) const { auto& vm = interpreter.vm(); @@ -1000,6 +1055,20 @@ String Call::to_string_impl(Bytecode::Executable const&) const return builder.to_string(); } +String SuperCall::to_string_impl(Bytecode::Executable const&) const +{ + StringBuilder builder; + builder.append("SuperCall"sv); + if (m_is_synthetic) { + builder.append(" arguments:[...acc]"sv); + } else if (m_argument_count != 0) { + builder.append(" arguments:["sv); + builder.join(", "sv, Span<Register const>(m_arguments, m_argument_count)); + builder.append(']'); + } + return builder.to_string(); +} + String NewFunction::to_string_impl(Bytecode::Executable const&) const { return "NewFunction"; diff --git a/Userland/Libraries/LibJS/Bytecode/Op.h b/Userland/Libraries/LibJS/Bytecode/Op.h index 2217136147b6..3be84e0465dd 100644 --- a/Userland/Libraries/LibJS/Bytecode/Op.h +++ b/Userland/Libraries/LibJS/Bytecode/Op.h @@ -613,6 +613,33 @@ class Call final : public Instruction { Register m_arguments[]; }; +// NOTE: This instruction is variable-width depending on the number of arguments! +class SuperCall : public Instruction { +public: + explicit SuperCall(bool is_synthetic, Vector<Register> const& arguments) + : Instruction(Type::SuperCall) + , m_is_synthetic(is_synthetic) + , m_argument_count(arguments.size()) + { + for (size_t i = 0; i < m_argument_count; ++i) + m_arguments[i] = arguments[i]; + } + + ThrowCompletionOr<void> execute_impl(Bytecode::Interpreter&) const; + String to_string_impl(Bytecode::Executable const&) const; + void replace_references_impl(BasicBlock const&, BasicBlock const&) { } + + size_t length_impl() const + { + return sizeof(*this) + sizeof(Register) * m_argument_count; + } + +private: + bool m_is_synthetic; + size_t m_argument_count { 0 }; + Register m_arguments[]; +}; + class NewClass final : public Instruction { public: explicit NewClass(ClassExpression const& class_expression) @@ -966,9 +993,11 @@ ALWAYS_INLINE size_t Instruction::length() const { if (type() == Type::Call) return static_cast<Op::Call const&>(*this).length_impl(); - else if (type() == Type::NewArray) + if (type() == Type::SuperCall) + return static_cast<Op::SuperCall const&>(*this).length_impl(); + if (type() == Type::NewArray) return static_cast<Op::NewArray const&>(*this).length_impl(); - else if (type() == Type::CopyObjectExcludingProperties) + if (type() == Type::CopyObjectExcludingProperties) return static_cast<Op::CopyObjectExcludingProperties const&>(*this).length_impl(); #define __BYTECODE_OP(op) \
b7e3a68bfc0cfeda0bbabc35d631764e4a91b77c
2023-05-29 09:05:41
Ali Mohammad Pur
libweb: Keep track of CSS property source declarations
false
Keep track of CSS property source declarations
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp index 305d69360acc..86a104efdb37 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp @@ -277,75 +277,75 @@ static bool contains(Edge a, Edge b) return a == b || b == Edge::All; } -static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document) +static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document, CSS::CSSStyleDeclaration const* declaration) { if (value.is_composite()) { auto& composite_value = value.as_composite(); auto& properties = composite_value.sub_properties(); auto& values = composite_value.values(); for (size_t i = 0; i < properties.size(); ++i) - set_property_expanding_shorthands(style, properties[i], values[i], document); + set_property_expanding_shorthands(style, properties[i], values[i], document, declaration); } - auto assign_edge_values = [&style](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) { + auto assign_edge_values = [&style, &declaration](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) { if (values.size() == 4) { - style.set_property(top_property, values[0]); - style.set_property(right_property, values[1]); - style.set_property(bottom_property, values[2]); - style.set_property(left_property, values[3]); + style.set_property(top_property, values[0], declaration); + style.set_property(right_property, values[1], declaration); + style.set_property(bottom_property, values[2], declaration); + style.set_property(left_property, values[3], declaration); } else if (values.size() == 3) { - style.set_property(top_property, values[0]); - style.set_property(right_property, values[1]); - style.set_property(bottom_property, values[2]); - style.set_property(left_property, values[1]); + style.set_property(top_property, values[0], declaration); + style.set_property(right_property, values[1], declaration); + style.set_property(bottom_property, values[2], declaration); + style.set_property(left_property, values[1], declaration); } else if (values.size() == 2) { - style.set_property(top_property, values[0]); - style.set_property(right_property, values[1]); - style.set_property(bottom_property, values[0]); - style.set_property(left_property, values[1]); + style.set_property(top_property, values[0], declaration); + style.set_property(right_property, values[1], declaration); + style.set_property(bottom_property, values[0], declaration); + style.set_property(left_property, values[1], declaration); } else if (values.size() == 1) { - style.set_property(top_property, values[0]); - style.set_property(right_property, values[0]); - style.set_property(bottom_property, values[0]); - style.set_property(left_property, values[0]); + style.set_property(top_property, values[0], declaration); + style.set_property(right_property, values[0], declaration); + style.set_property(bottom_property, values[0], declaration); + style.set_property(left_property, values[0], declaration); } }; if (property_id == CSS::PropertyID::TextDecoration) { if (value.is_text_decoration()) { auto const& text_decoration = value.as_text_decoration(); - style.set_property(CSS::PropertyID::TextDecorationLine, text_decoration.line()); - style.set_property(CSS::PropertyID::TextDecorationThickness, text_decoration.thickness()); - style.set_property(CSS::PropertyID::TextDecorationStyle, text_decoration.style()); - style.set_property(CSS::PropertyID::TextDecorationColor, text_decoration.color()); + style.set_property(CSS::PropertyID::TextDecorationLine, text_decoration.line(), declaration); + style.set_property(CSS::PropertyID::TextDecorationThickness, text_decoration.thickness(), declaration); + style.set_property(CSS::PropertyID::TextDecorationStyle, text_decoration.style(), declaration); + style.set_property(CSS::PropertyID::TextDecorationColor, text_decoration.color(), declaration); return; } - style.set_property(CSS::PropertyID::TextDecorationLine, value); - style.set_property(CSS::PropertyID::TextDecorationThickness, value); - style.set_property(CSS::PropertyID::TextDecorationStyle, value); - style.set_property(CSS::PropertyID::TextDecorationColor, value); + style.set_property(CSS::PropertyID::TextDecorationLine, value, declaration); + style.set_property(CSS::PropertyID::TextDecorationThickness, value, declaration); + style.set_property(CSS::PropertyID::TextDecorationStyle, value, declaration); + style.set_property(CSS::PropertyID::TextDecorationColor, value, declaration); return; } if (property_id == CSS::PropertyID::Overflow) { if (value.is_overflow()) { auto const& overflow = value.as_overflow(); - style.set_property(CSS::PropertyID::OverflowX, overflow.overflow_x()); - style.set_property(CSS::PropertyID::OverflowY, overflow.overflow_y()); + style.set_property(CSS::PropertyID::OverflowX, overflow.overflow_x(), declaration); + style.set_property(CSS::PropertyID::OverflowY, overflow.overflow_y(), declaration); return; } - style.set_property(CSS::PropertyID::OverflowX, value); - style.set_property(CSS::PropertyID::OverflowY, value); + style.set_property(CSS::PropertyID::OverflowX, value, declaration); + style.set_property(CSS::PropertyID::OverflowY, value, declaration); return; } if (property_id == CSS::PropertyID::Border) { - set_property_expanding_shorthands(style, CSS::PropertyID::BorderTop, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BorderRight, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BorderBottom, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BorderLeft, value, document); + set_property_expanding_shorthands(style, CSS::PropertyID::BorderTop, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BorderRight, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BorderBottom, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BorderLeft, value, document, declaration); // FIXME: Also reset border-image, in line with the spec: https://www.w3.org/TR/css-backgrounds-3/#border-shorthands return; } @@ -353,17 +353,17 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope if (property_id == CSS::PropertyID::BorderRadius) { if (value.is_border_radius_shorthand()) { auto const& shorthand = value.as_border_radius_shorthand(); - style.set_property(CSS::PropertyID::BorderTopLeftRadius, shorthand.top_left()); - style.set_property(CSS::PropertyID::BorderTopRightRadius, shorthand.top_right()); - style.set_property(CSS::PropertyID::BorderBottomRightRadius, shorthand.bottom_right()); - style.set_property(CSS::PropertyID::BorderBottomLeftRadius, shorthand.bottom_left()); + style.set_property(CSS::PropertyID::BorderTopLeftRadius, shorthand.top_left(), declaration); + style.set_property(CSS::PropertyID::BorderTopRightRadius, shorthand.top_right(), declaration); + style.set_property(CSS::PropertyID::BorderBottomRightRadius, shorthand.bottom_right(), declaration); + style.set_property(CSS::PropertyID::BorderBottomLeftRadius, shorthand.bottom_left(), declaration); return; } - style.set_property(CSS::PropertyID::BorderTopLeftRadius, value); - style.set_property(CSS::PropertyID::BorderTopRightRadius, value); - style.set_property(CSS::PropertyID::BorderBottomRightRadius, value); - style.set_property(CSS::PropertyID::BorderBottomLeftRadius, value); + style.set_property(CSS::PropertyID::BorderTopLeftRadius, value, declaration); + style.set_property(CSS::PropertyID::BorderTopRightRadius, value, declaration); + style.set_property(CSS::PropertyID::BorderBottomRightRadius, value, declaration); + style.set_property(CSS::PropertyID::BorderBottomLeftRadius, value, declaration); return; } @@ -393,24 +393,24 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope if (value.is_border()) { auto const& border = value.as_border(); if (contains(Edge::Top, edge)) { - style.set_property(PropertyID::BorderTopWidth, border.border_width()); - style.set_property(PropertyID::BorderTopStyle, border.border_style()); - style.set_property(PropertyID::BorderTopColor, border.border_color()); + style.set_property(PropertyID::BorderTopWidth, border.border_width(), declaration); + style.set_property(PropertyID::BorderTopStyle, border.border_style(), declaration); + style.set_property(PropertyID::BorderTopColor, border.border_color(), declaration); } if (contains(Edge::Right, edge)) { - style.set_property(PropertyID::BorderRightWidth, border.border_width()); - style.set_property(PropertyID::BorderRightStyle, border.border_style()); - style.set_property(PropertyID::BorderRightColor, border.border_color()); + style.set_property(PropertyID::BorderRightWidth, border.border_width(), declaration); + style.set_property(PropertyID::BorderRightStyle, border.border_style(), declaration); + style.set_property(PropertyID::BorderRightColor, border.border_color(), declaration); } if (contains(Edge::Bottom, edge)) { - style.set_property(PropertyID::BorderBottomWidth, border.border_width()); - style.set_property(PropertyID::BorderBottomStyle, border.border_style()); - style.set_property(PropertyID::BorderBottomColor, border.border_color()); + style.set_property(PropertyID::BorderBottomWidth, border.border_width(), declaration); + style.set_property(PropertyID::BorderBottomStyle, border.border_style(), declaration); + style.set_property(PropertyID::BorderBottomColor, border.border_color(), declaration); } if (contains(Edge::Left, edge)) { - style.set_property(PropertyID::BorderLeftWidth, border.border_width()); - style.set_property(PropertyID::BorderLeftStyle, border.border_style()); - style.set_property(PropertyID::BorderLeftColor, border.border_color()); + style.set_property(PropertyID::BorderLeftWidth, border.border_width(), declaration); + style.set_property(PropertyID::BorderLeftStyle, border.border_style(), declaration); + style.set_property(PropertyID::BorderLeftColor, border.border_color(), declaration); } return; } @@ -424,10 +424,10 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - style.set_property(CSS::PropertyID::BorderTopStyle, value); - style.set_property(CSS::PropertyID::BorderRightStyle, value); - style.set_property(CSS::PropertyID::BorderBottomStyle, value); - style.set_property(CSS::PropertyID::BorderLeftStyle, value); + style.set_property(CSS::PropertyID::BorderTopStyle, value, declaration); + style.set_property(CSS::PropertyID::BorderRightStyle, value, declaration); + style.set_property(CSS::PropertyID::BorderBottomStyle, value, declaration); + style.set_property(CSS::PropertyID::BorderLeftStyle, value, declaration); return; } @@ -438,10 +438,10 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - style.set_property(CSS::PropertyID::BorderTopWidth, value); - style.set_property(CSS::PropertyID::BorderRightWidth, value); - style.set_property(CSS::PropertyID::BorderBottomWidth, value); - style.set_property(CSS::PropertyID::BorderLeftWidth, value); + style.set_property(CSS::PropertyID::BorderTopWidth, value, declaration); + style.set_property(CSS::PropertyID::BorderRightWidth, value, declaration); + style.set_property(CSS::PropertyID::BorderBottomWidth, value, declaration); + style.set_property(CSS::PropertyID::BorderLeftWidth, value, declaration); return; } @@ -452,43 +452,43 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - style.set_property(CSS::PropertyID::BorderTopColor, value); - style.set_property(CSS::PropertyID::BorderRightColor, value); - style.set_property(CSS::PropertyID::BorderBottomColor, value); - style.set_property(CSS::PropertyID::BorderLeftColor, value); + style.set_property(CSS::PropertyID::BorderTopColor, value, declaration); + style.set_property(CSS::PropertyID::BorderRightColor, value, declaration); + style.set_property(CSS::PropertyID::BorderBottomColor, value, declaration); + style.set_property(CSS::PropertyID::BorderLeftColor, value, declaration); return; } if (property_id == CSS::PropertyID::Background) { if (value.is_background()) { auto const& background = value.as_background(); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, background.color(), document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, background.image(), document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, background.position(), document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, background.size(), document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, background.repeat(), document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, background.attachment(), document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, background.origin(), document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, background.clip(), document); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, background.color(), document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, background.image(), document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, background.position(), document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, background.size(), document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, background.repeat(), document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, background.attachment(), document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, background.origin(), document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, background.clip(), document, declaration); return; } - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, value, document); - set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, value, document); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, value, document, declaration); + set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, value, document, declaration); return; } if (property_id == CSS::PropertyID::BackgroundPosition) { if (value.is_position()) { auto const& position = value.as_position(); - style.set_property(CSS::PropertyID::BackgroundPositionX, position.edge_x()); - style.set_property(CSS::PropertyID::BackgroundPositionY, position.edge_y()); + style.set_property(CSS::PropertyID::BackgroundPositionX, position.edge_x(), declaration); + style.set_property(CSS::PropertyID::BackgroundPositionY, position.edge_y(), declaration); } else if (value.is_value_list()) { // Expand background-position layer list into separate lists for x and y positions: auto const& values_list = value.as_value_list(); @@ -506,11 +506,11 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope y_positions.unchecked_append(layer); } } - style.set_property(CSS::PropertyID::BackgroundPositionX, StyleValueList::create(move(x_positions), values_list.separator()).release_value_but_fixme_should_propagate_errors()); - style.set_property(CSS::PropertyID::BackgroundPositionY, StyleValueList::create(move(y_positions), values_list.separator()).release_value_but_fixme_should_propagate_errors()); + style.set_property(CSS::PropertyID::BackgroundPositionX, StyleValueList::create(move(x_positions), values_list.separator()).release_value_but_fixme_should_propagate_errors(), declaration); + style.set_property(CSS::PropertyID::BackgroundPositionY, StyleValueList::create(move(y_positions), values_list.separator()).release_value_but_fixme_should_propagate_errors(), declaration); } else { - style.set_property(CSS::PropertyID::BackgroundPositionX, value); - style.set_property(CSS::PropertyID::BackgroundPositionY, value); + style.set_property(CSS::PropertyID::BackgroundPositionX, value, declaration); + style.set_property(CSS::PropertyID::BackgroundPositionY, value, declaration); } return; @@ -523,10 +523,10 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - style.set_property(CSS::PropertyID::MarginTop, value); - style.set_property(CSS::PropertyID::MarginRight, value); - style.set_property(CSS::PropertyID::MarginBottom, value); - style.set_property(CSS::PropertyID::MarginLeft, value); + style.set_property(CSS::PropertyID::MarginTop, value, declaration); + style.set_property(CSS::PropertyID::MarginRight, value, declaration); + style.set_property(CSS::PropertyID::MarginBottom, value, declaration); + style.set_property(CSS::PropertyID::MarginLeft, value, declaration); return; } @@ -537,47 +537,47 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope return; } - style.set_property(CSS::PropertyID::PaddingTop, value); - style.set_property(CSS::PropertyID::PaddingRight, value); - style.set_property(CSS::PropertyID::PaddingBottom, value); - style.set_property(CSS::PropertyID::PaddingLeft, value); + style.set_property(CSS::PropertyID::PaddingTop, value, declaration); + style.set_property(CSS::PropertyID::PaddingRight, value, declaration); + style.set_property(CSS::PropertyID::PaddingBottom, value, declaration); + style.set_property(CSS::PropertyID::PaddingLeft, value, declaration); return; } if (property_id == CSS::PropertyID::ListStyle) { if (value.is_list_style()) { auto const& list_style = value.as_list_style(); - style.set_property(CSS::PropertyID::ListStylePosition, list_style.position()); - style.set_property(CSS::PropertyID::ListStyleImage, list_style.image()); - style.set_property(CSS::PropertyID::ListStyleType, list_style.style_type()); + style.set_property(CSS::PropertyID::ListStylePosition, list_style.position(), declaration); + style.set_property(CSS::PropertyID::ListStyleImage, list_style.image(), declaration); + style.set_property(CSS::PropertyID::ListStyleType, list_style.style_type(), declaration); return; } - style.set_property(CSS::PropertyID::ListStylePosition, value); - style.set_property(CSS::PropertyID::ListStyleImage, value); - style.set_property(CSS::PropertyID::ListStyleType, value); + style.set_property(CSS::PropertyID::ListStylePosition, value, declaration); + style.set_property(CSS::PropertyID::ListStyleImage, value, declaration); + style.set_property(CSS::PropertyID::ListStyleType, value, declaration); return; } if (property_id == CSS::PropertyID::Font) { if (value.is_font()) { auto const& font_shorthand = value.as_font(); - style.set_property(CSS::PropertyID::FontSize, font_shorthand.font_size()); - style.set_property(CSS::PropertyID::FontFamily, font_shorthand.font_families()); - style.set_property(CSS::PropertyID::FontStretch, font_shorthand.font_stretch()); - style.set_property(CSS::PropertyID::FontStyle, font_shorthand.font_style()); - style.set_property(CSS::PropertyID::FontWeight, font_shorthand.font_weight()); - style.set_property(CSS::PropertyID::LineHeight, font_shorthand.line_height()); + style.set_property(CSS::PropertyID::FontSize, font_shorthand.font_size(), declaration); + style.set_property(CSS::PropertyID::FontFamily, font_shorthand.font_families(), declaration); + style.set_property(CSS::PropertyID::FontStretch, font_shorthand.font_stretch(), declaration); + style.set_property(CSS::PropertyID::FontStyle, font_shorthand.font_style(), declaration); + style.set_property(CSS::PropertyID::FontWeight, font_shorthand.font_weight(), declaration); + style.set_property(CSS::PropertyID::LineHeight, font_shorthand.line_height(), declaration); // FIXME: Implement font-variant return; } - style.set_property(CSS::PropertyID::FontStretch, value); - style.set_property(CSS::PropertyID::FontSize, value); - style.set_property(CSS::PropertyID::FontFamily, value); - style.set_property(CSS::PropertyID::FontStyle, value); - style.set_property(CSS::PropertyID::FontWeight, value); - style.set_property(CSS::PropertyID::LineHeight, value); + style.set_property(CSS::PropertyID::FontStretch, value, declaration); + style.set_property(CSS::PropertyID::FontSize, value, declaration); + style.set_property(CSS::PropertyID::FontFamily, value, declaration); + style.set_property(CSS::PropertyID::FontStyle, value, declaration); + style.set_property(CSS::PropertyID::FontWeight, value, declaration); + style.set_property(CSS::PropertyID::LineHeight, value, declaration); // FIXME: Implement font-variant return; } @@ -585,106 +585,106 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope if (property_id == CSS::PropertyID::Flex) { if (value.is_flex()) { auto const& flex = value.as_flex(); - style.set_property(CSS::PropertyID::FlexGrow, flex.grow()); - style.set_property(CSS::PropertyID::FlexShrink, flex.shrink()); - style.set_property(CSS::PropertyID::FlexBasis, flex.basis()); + style.set_property(CSS::PropertyID::FlexGrow, flex.grow(), declaration); + style.set_property(CSS::PropertyID::FlexShrink, flex.shrink(), declaration); + style.set_property(CSS::PropertyID::FlexBasis, flex.basis(), declaration); return; } - style.set_property(CSS::PropertyID::FlexGrow, value); - style.set_property(CSS::PropertyID::FlexShrink, value); - style.set_property(CSS::PropertyID::FlexBasis, value); + style.set_property(CSS::PropertyID::FlexGrow, value, declaration); + style.set_property(CSS::PropertyID::FlexShrink, value, declaration); + style.set_property(CSS::PropertyID::FlexBasis, value, declaration); return; } if (property_id == CSS::PropertyID::FlexFlow) { if (value.is_flex_flow()) { auto const& flex_flow = value.as_flex_flow(); - style.set_property(CSS::PropertyID::FlexDirection, flex_flow.flex_direction()); - style.set_property(CSS::PropertyID::FlexWrap, flex_flow.flex_wrap()); + style.set_property(CSS::PropertyID::FlexDirection, flex_flow.flex_direction(), declaration); + style.set_property(CSS::PropertyID::FlexWrap, flex_flow.flex_wrap(), declaration); return; } - style.set_property(CSS::PropertyID::FlexDirection, value); - style.set_property(CSS::PropertyID::FlexWrap, value); + style.set_property(CSS::PropertyID::FlexDirection, value, declaration); + style.set_property(CSS::PropertyID::FlexWrap, value, declaration); return; } if (property_id == CSS::PropertyID::GridArea) { if (value.is_grid_area_shorthand()) { auto const& shorthand = value.as_grid_area_shorthand(); - style.set_property(CSS::PropertyID::GridRowStart, shorthand.row_start()); - style.set_property(CSS::PropertyID::GridColumnStart, shorthand.column_start()); - style.set_property(CSS::PropertyID::GridRowEnd, shorthand.row_end()); - style.set_property(CSS::PropertyID::GridColumnEnd, shorthand.column_end()); + style.set_property(CSS::PropertyID::GridRowStart, shorthand.row_start(), declaration); + style.set_property(CSS::PropertyID::GridColumnStart, shorthand.column_start(), declaration); + style.set_property(CSS::PropertyID::GridRowEnd, shorthand.row_end(), declaration); + style.set_property(CSS::PropertyID::GridColumnEnd, shorthand.column_end(), declaration); return; } - style.set_property(CSS::PropertyID::GridRowStart, value); - style.set_property(CSS::PropertyID::GridColumnStart, value); - style.set_property(CSS::PropertyID::GridRowEnd, value); - style.set_property(CSS::PropertyID::GridColumnEnd, value); + style.set_property(CSS::PropertyID::GridRowStart, value, declaration); + style.set_property(CSS::PropertyID::GridColumnStart, value, declaration); + style.set_property(CSS::PropertyID::GridRowEnd, value, declaration); + style.set_property(CSS::PropertyID::GridColumnEnd, value, declaration); return; } if (property_id == CSS::PropertyID::GridColumn) { if (value.is_grid_track_placement_shorthand()) { auto const& shorthand = value.as_grid_track_placement_shorthand(); - style.set_property(CSS::PropertyID::GridColumnStart, shorthand.start()); - style.set_property(CSS::PropertyID::GridColumnEnd, shorthand.end()); + style.set_property(CSS::PropertyID::GridColumnStart, shorthand.start(), declaration); + style.set_property(CSS::PropertyID::GridColumnEnd, shorthand.end(), declaration); return; } - style.set_property(CSS::PropertyID::GridColumnStart, value); - style.set_property(CSS::PropertyID::GridColumnEnd, value); + style.set_property(CSS::PropertyID::GridColumnStart, value, declaration); + style.set_property(CSS::PropertyID::GridColumnEnd, value, declaration); return; } if (property_id == CSS::PropertyID::GridRow) { if (value.is_grid_track_placement_shorthand()) { auto const& shorthand = value.as_grid_track_placement_shorthand(); - style.set_property(CSS::PropertyID::GridRowStart, shorthand.start()); - style.set_property(CSS::PropertyID::GridRowEnd, shorthand.end()); + style.set_property(CSS::PropertyID::GridRowStart, shorthand.start(), declaration); + style.set_property(CSS::PropertyID::GridRowEnd, shorthand.end(), declaration); return; } - style.set_property(CSS::PropertyID::GridRowStart, value); - style.set_property(CSS::PropertyID::GridRowEnd, value); + style.set_property(CSS::PropertyID::GridRowStart, value, declaration); + style.set_property(CSS::PropertyID::GridRowEnd, value, declaration); return; } if (property_id == CSS::PropertyID::GridTemplate || property_id == CSS::PropertyID::Grid) { if (value.is_grid_track_size_list_shorthand()) { auto const& shorthand = value.as_grid_track_size_list_shorthand(); - style.set_property(CSS::PropertyID::GridTemplateAreas, shorthand.areas()); - style.set_property(CSS::PropertyID::GridTemplateRows, shorthand.rows()); - style.set_property(CSS::PropertyID::GridTemplateColumns, shorthand.columns()); + style.set_property(CSS::PropertyID::GridTemplateAreas, shorthand.areas(), declaration); + style.set_property(CSS::PropertyID::GridTemplateRows, shorthand.rows(), declaration); + style.set_property(CSS::PropertyID::GridTemplateColumns, shorthand.columns(), declaration); return; } - style.set_property(CSS::PropertyID::GridTemplateAreas, value); - style.set_property(CSS::PropertyID::GridTemplateRows, value); - style.set_property(CSS::PropertyID::GridTemplateColumns, value); + style.set_property(CSS::PropertyID::GridTemplateAreas, value, declaration); + style.set_property(CSS::PropertyID::GridTemplateRows, value, declaration); + style.set_property(CSS::PropertyID::GridTemplateColumns, value, declaration); return; } if (property_id == CSS::PropertyID::Gap || property_id == CSS::PropertyID::GridGap) { if (value.is_value_list()) { auto const& values_list = value.as_value_list(); - style.set_property(CSS::PropertyID::RowGap, values_list.values()[0]); - style.set_property(CSS::PropertyID::ColumnGap, values_list.values()[1]); + style.set_property(CSS::PropertyID::RowGap, values_list.values()[0], declaration); + style.set_property(CSS::PropertyID::ColumnGap, values_list.values()[1], declaration); return; } - style.set_property(CSS::PropertyID::RowGap, value); - style.set_property(CSS::PropertyID::ColumnGap, value); + style.set_property(CSS::PropertyID::RowGap, value, declaration); + style.set_property(CSS::PropertyID::ColumnGap, value, declaration); return; } if (property_id == CSS::PropertyID::RowGap || property_id == CSS::PropertyID::GridRowGap) { - style.set_property(CSS::PropertyID::RowGap, value); + style.set_property(CSS::PropertyID::RowGap, value, declaration); return; } if (property_id == CSS::PropertyID::ColumnGap || property_id == CSS::PropertyID::GridColumnGap) { - style.set_property(CSS::PropertyID::ColumnGap, value); + style.set_property(CSS::PropertyID::ColumnGap, value, declaration); return; } @@ -694,21 +694,21 @@ static void set_property_expanding_shorthands(StyleProperties& style, CSS::Prope if (is_horizontal) { if (property_id == CSS::PropertyID::MaxInlineSize) { - style.set_property(CSS::PropertyID::MaxWidth, value); + style.set_property(CSS::PropertyID::MaxWidth, value, declaration); } else { - style.set_property(CSS::PropertyID::MinWidth, value); + style.set_property(CSS::PropertyID::MinWidth, value, declaration); } } else { if (property_id == CSS::PropertyID::MaxInlineSize) { - style.set_property(CSS::PropertyID::MaxHeight, value); + style.set_property(CSS::PropertyID::MaxHeight, value, declaration); } else { - style.set_property(CSS::PropertyID::MinHeight, value); + style.set_property(CSS::PropertyID::MinHeight, value, declaration); } } return; } - style.set_property(property_id, value); + style.set_property(property_id, value, declaration); } static RefPtr<StyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement> pseudo_element, FlyString const& custom_property_name) @@ -934,7 +934,7 @@ void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& e property_value = resolved.release_nonnull(); } if (!property_value->is_unresolved()) - set_property_expanding_shorthands(style, property.property_id, property_value, m_document); + set_property_expanding_shorthands(style, property.property_id, property_value, m_document, &match.rule->declaration()); } } @@ -949,7 +949,7 @@ void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& e property_value = resolved.release_nonnull(); } if (!property_value->is_unresolved()) - set_property_expanding_shorthands(style, property.property_id, property_value, m_document); + set_property_expanding_shorthands(style, property.property_id, property_value, m_document, inline_style); } } } @@ -1025,9 +1025,9 @@ ErrorOr<void> StyleComputer::compute_cascaded_values(StyleProperties& style, DOM for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) { auto property_id = (CSS::PropertyID)i; auto& property = style.m_property_values[i]; - if (property && property->is_unresolved()) { - if (auto resolved = resolve_unresolved_style_value(element, pseudo_element, property_id, property->as_unresolved())) - property = resolved.release_nonnull(); + if (property.has_value() && property->style->is_unresolved()) { + if (auto resolved = resolve_unresolved_style_value(element, pseudo_element, property_id, property->style->as_unresolved())) + property->style = resolved.release_nonnull(); } } } @@ -1077,33 +1077,33 @@ void StyleComputer::compute_defaulted_property_value(StyleProperties& style, DOM // FIXME: If we don't know the correct initial value for a property, we fall back to InitialStyleValue. auto& value_slot = style.m_property_values[to_underlying(property_id)]; - if (!value_slot) { + if (!value_slot.has_value()) { if (is_inherited_property(property_id)) - style.m_property_values[to_underlying(property_id)] = get_inherit_value(document().realm(), property_id, element, pseudo_element); + style.m_property_values[to_underlying(property_id)] = { { get_inherit_value(document().realm(), property_id, element, pseudo_element), nullptr } }; else - style.m_property_values[to_underlying(property_id)] = property_initial_value(document().realm(), property_id).release_value_but_fixme_should_propagate_errors(); + style.m_property_values[to_underlying(property_id)] = { { property_initial_value(document().realm(), property_id).release_value_but_fixme_should_propagate_errors(), nullptr } }; return; } - if (value_slot->is_initial()) { - value_slot = property_initial_value(document().realm(), property_id).release_value_but_fixme_should_propagate_errors(); + if (value_slot->style->is_initial()) { + value_slot->style = property_initial_value(document().realm(), property_id).release_value_but_fixme_should_propagate_errors(); return; } - if (value_slot->is_inherit()) { - value_slot = get_inherit_value(document().realm(), property_id, element, pseudo_element); + if (value_slot->style->is_inherit()) { + value_slot->style = get_inherit_value(document().realm(), property_id, element, pseudo_element); return; } // https://www.w3.org/TR/css-cascade-4/#inherit-initial // If the cascaded value of a property is the unset keyword, - if (value_slot->is_unset()) { + if (value_slot->style->is_unset()) { if (is_inherited_property(property_id)) { // then if it is an inherited property, this is treated as inherit, - value_slot = get_inherit_value(document().realm(), property_id, element, pseudo_element); + value_slot->style = get_inherit_value(document().realm(), property_id, element, pseudo_element); } else { // and if it is not, this is treated as initial. - value_slot = property_initial_value(document().realm(), property_id).release_value_but_fixme_should_propagate_errors(); + value_slot->style = property_initial_value(document().realm(), property_id).release_value_but_fixme_should_propagate_errors(); } } } @@ -1402,8 +1402,8 @@ void StyleComputer::compute_font(StyleProperties& style, DOM::Element const* ele FontCache::the().set(font_selector, *found_font); - style.set_property(CSS::PropertyID::FontSize, LengthStyleValue::create(CSS::Length::make_px(font_size_in_px)).release_value_but_fixme_should_propagate_errors()); - style.set_property(CSS::PropertyID::FontWeight, NumericStyleValue::create_integer(weight).release_value_but_fixme_should_propagate_errors()); + style.set_property(CSS::PropertyID::FontSize, LengthStyleValue::create(CSS::Length::make_px(font_size_in_px)).release_value_but_fixme_should_propagate_errors(), nullptr); + style.set_property(CSS::PropertyID::FontWeight, NumericStyleValue::create_integer(weight).release_value_but_fixme_should_propagate_errors(), nullptr); style.set_computed_font(found_font.release_nonnull()); @@ -1448,24 +1448,24 @@ ErrorOr<void> StyleComputer::absolutize_values(StyleProperties& style, DOM::Elem // We have to resolve them right away, so that the *computed* line-height is ready for inheritance. // We can't simply absolutize *all* percentage values against the font size, // because most percentages are relative to containing block metrics. - auto& line_height_value_slot = style.m_property_values[to_underlying(CSS::PropertyID::LineHeight)]; - if (line_height_value_slot && line_height_value_slot->is_percentage()) { - line_height_value_slot = TRY(LengthStyleValue::create( - Length::make_px(font_size * static_cast<double>(line_height_value_slot->as_percentage().percentage().as_fraction())))); + auto line_height_value_slot = style.m_property_values[to_underlying(CSS::PropertyID::LineHeight)].map([](auto& x) -> auto& { return x.style; }); + if (line_height_value_slot.has_value() && (*line_height_value_slot)->is_percentage()) { + *line_height_value_slot = TRY(LengthStyleValue::create( + Length::make_px(font_size * static_cast<double>((*line_height_value_slot)->as_percentage().percentage().as_fraction())))); } auto line_height = style.line_height(viewport_rect(), font_metrics, m_root_element_font_metrics); font_metrics.line_height = line_height; // NOTE: line-height might be using lh which should be resolved against the parent line height (like we did here already) - if (line_height_value_slot && line_height_value_slot->is_length()) - line_height_value_slot = TRY(LengthStyleValue::create(Length::make_px(line_height))); + if (line_height_value_slot.has_value() && (*line_height_value_slot)->is_length()) + (*line_height_value_slot) = TRY(LengthStyleValue::create(Length::make_px(line_height))); for (size_t i = 0; i < style.m_property_values.size(); ++i) { auto& value_slot = style.m_property_values[i]; - if (!value_slot) + if (!value_slot.has_value()) continue; - value_slot = TRY(value_slot->absolutized(viewport_rect(), font_metrics, m_root_element_font_metrics)); + value_slot->style = TRY(value_slot->style->absolutized(viewport_rect(), font_metrics, m_root_element_font_metrics)); } return {}; } @@ -1559,7 +1559,7 @@ void StyleComputer::transform_box_type_if_needed(StyleProperties& style, DOM::El } if (new_display != display) - style.set_property(CSS::PropertyID::Display, DisplayStyleValue::create(new_display).release_value_but_fixme_should_propagate_errors()); + style.set_property(CSS::PropertyID::Display, DisplayStyleValue::create(new_display).release_value_but_fixme_should_propagate_errors(), style.property_source_declaration(CSS::PropertyID::Display)); } NonnullRefPtr<StyleProperties> StyleComputer::create_document_style() const @@ -1568,9 +1568,9 @@ NonnullRefPtr<StyleProperties> StyleComputer::create_document_style() const compute_font(style, nullptr, {}); compute_defaulted_values(style, nullptr, {}); absolutize_values(style, nullptr, {}).release_value_but_fixme_should_propagate_errors(); - style->set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().width())).release_value_but_fixme_should_propagate_errors()); - style->set_property(CSS::PropertyID::Height, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().height())).release_value_but_fixme_should_propagate_errors()); - style->set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::Block)).release_value_but_fixme_should_propagate_errors()); + style->set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().width())).release_value_but_fixme_should_propagate_errors(), nullptr); + style->set_property(CSS::PropertyID::Height, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().height())).release_value_but_fixme_should_propagate_errors(), nullptr); + style->set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::Block)).release_value_but_fixme_should_propagate_errors(), nullptr); return style; } diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp index da20b86d464d..21201160887b 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp @@ -45,22 +45,30 @@ NonnullRefPtr<StyleProperties> StyleProperties::clone() const return adopt_ref(*new StyleProperties(*this)); } -void StyleProperties::set_property(CSS::PropertyID id, NonnullRefPtr<StyleValue const> value) +void StyleProperties::set_property(CSS::PropertyID id, NonnullRefPtr<StyleValue const> value, CSS::CSSStyleDeclaration const* source_declaration) { - m_property_values[to_underlying(id)] = move(value); + m_property_values[to_underlying(id)] = StyleAndSourceDeclaration { move(value), source_declaration }; } NonnullRefPtr<StyleValue const> StyleProperties::property(CSS::PropertyID property_id) const { auto value = m_property_values[to_underlying(property_id)]; // By the time we call this method, all properties have values assigned. - VERIFY(!value.is_null()); - return value.release_nonnull(); + VERIFY(value.has_value()); + return value->style; } RefPtr<StyleValue const> StyleProperties::maybe_null_property(CSS::PropertyID property_id) const { - return m_property_values[to_underlying(property_id)]; + auto value = m_property_values[to_underlying(property_id)]; + if (value.has_value()) + return value->style; + return {}; +} + +CSS::CSSStyleDeclaration const* StyleProperties::property_source_declaration(CSS::PropertyID property_id) const +{ + return m_property_values[to_underlying(property_id)].map([](auto& value) { return value.declaration; }).value_or(nullptr); } CSS::Size StyleProperties::size_value(CSS::PropertyID id) const @@ -509,17 +517,17 @@ bool StyleProperties::operator==(StyleProperties const& other) const return false; for (size_t i = 0; i < m_property_values.size(); ++i) { - auto const& my_ptr = m_property_values[i]; - auto const& other_ptr = other.m_property_values[i]; - if (!my_ptr) { - if (other_ptr) + auto const& my_style = m_property_values[i]; + auto const& other_style = other.m_property_values[i]; + if (!my_style.has_value()) { + if (other_style.has_value()) return false; continue; } - if (!other_ptr) + if (!other_style.has_value()) return false; - auto const& my_value = *my_ptr; - auto const& other_value = *other_ptr; + auto const& my_value = *my_style->style; + auto const& other_value = *other_style->style; if (my_value.type() != other_value.type()) return false; if (my_value != other_value) diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.h b/Userland/Libraries/LibWeb/CSS/StyleProperties.h index 8d9e31c789dd..84ef77c7490a 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleProperties.h +++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.h @@ -30,17 +30,18 @@ class StyleProperties : public RefCounted<StyleProperties> { inline void for_each_property(Callback callback) const { for (size_t i = 0; i < m_property_values.size(); ++i) { - if (m_property_values[i]) - callback((CSS::PropertyID)i, *m_property_values[i]); + if (m_property_values[i].has_value()) + callback((CSS::PropertyID)i, *m_property_values[i]->style); } } auto& properties() { return m_property_values; } auto const& properties() const { return m_property_values; } - void set_property(CSS::PropertyID, NonnullRefPtr<StyleValue const> value); + void set_property(CSS::PropertyID, NonnullRefPtr<StyleValue const> value, CSS::CSSStyleDeclaration const* source_declaration = nullptr); NonnullRefPtr<StyleValue const> property(CSS::PropertyID) const; RefPtr<StyleValue const> maybe_null_property(CSS::PropertyID) const; + CSS::CSSStyleDeclaration const* property_source_declaration(CSS::PropertyID) const; CSS::Size size_value(CSS::PropertyID) const; LengthPercentage length_percentage_or_fallback(CSS::PropertyID, LengthPercentage const& fallback) const; @@ -129,7 +130,11 @@ class StyleProperties : public RefCounted<StyleProperties> { private: friend class StyleComputer; - Array<RefPtr<StyleValue const>, to_underlying(CSS::last_property_id) + 1> m_property_values; + struct StyleAndSourceDeclaration { + NonnullRefPtr<StyleValue const> style; + CSS::CSSStyleDeclaration const* declaration = nullptr; + }; + Array<Optional<StyleAndSourceDeclaration>, to_underlying(CSS::last_property_id) + 1> m_property_values; Optional<CSS::Overflow> overflow(CSS::PropertyID) const; Vector<CSS::ShadowData> shadow(CSS::PropertyID) const; diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp index cccc9fda1aa0..18daa1d700fb 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.cpp +++ b/Userland/Libraries/LibWeb/DOM/Element.cpp @@ -412,10 +412,10 @@ static Element::RequiredInvalidationAfterStyleChange compute_required_invalidati auto property_id = static_cast<CSS::PropertyID>(i); auto const& old_value = old_style.properties()[i]; auto const& new_value = new_style.properties()[i]; - if (!old_value && !new_value) + if (!old_value.has_value() && !new_value.has_value()) continue; - bool const property_value_changed = (!old_value || !new_value) || *old_value != *new_value; + bool const property_value_changed = (!old_value.has_value() || !new_value.has_value()) || *old_value->style != *new_value->style; if (!property_value_changed) continue; @@ -428,7 +428,7 @@ static Element::RequiredInvalidationAfterStyleChange compute_required_invalidati // OPTIMIZATION: Special handling for CSS `visibility`: if (property_id == CSS::PropertyID::Visibility) { // We don't need to relayout if the visibility changes from visible to hidden or vice versa. Only collapse requires relayout. - if ((old_value && old_value->to_identifier() == CSS::ValueID::Collapse) != (new_value && new_value->to_identifier() == CSS::ValueID::Collapse)) + if ((old_value.has_value() && old_value->style->to_identifier() == CSS::ValueID::Collapse) != (new_value.has_value() && new_value->style->to_identifier() == CSS::ValueID::Collapse)) invalidation.relayout = true; // Of course, we still have to repaint on any visibility change. invalidation.repaint = true; @@ -481,7 +481,7 @@ NonnullRefPtr<CSS::StyleProperties> Element::resolved_css_values() auto maybe_value = element_computed_style->property(property_id); if (!maybe_value.has_value()) continue; - properties->set_property(property_id, maybe_value.release_value().value); + properties->set_property(property_id, maybe_value.release_value().value, nullptr); } return properties; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLBodyElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLBodyElement.cpp index 096a5bb1b1b6..83eb2b6c71fa 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLBodyElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLBodyElement.cpp @@ -37,15 +37,15 @@ void HTMLBodyElement::apply_presentational_hints(CSS::StyleProperties& style) co // https://html.spec.whatwg.org/multipage/rendering.html#the-page:rules-for-parsing-a-legacy-colour-value auto color = parse_legacy_color_value(value); if (color.has_value()) - style.set_property(CSS::PropertyID::BackgroundColor, CSS::ColorStyleValue::create(color.value()).release_value_but_fixme_should_propagate_errors()); + style.set_property(CSS::PropertyID::BackgroundColor, CSS::ColorStyleValue::create(color.value()).release_value_but_fixme_should_propagate_errors(), nullptr); } else if (name.equals_ignoring_ascii_case("text"sv)) { // https://html.spec.whatwg.org/multipage/rendering.html#the-page:rules-for-parsing-a-legacy-colour-value-2 auto color = parse_legacy_color_value(value); if (color.has_value()) - style.set_property(CSS::PropertyID::Color, CSS::ColorStyleValue::create(color.value()).release_value_but_fixme_should_propagate_errors()); + style.set_property(CSS::PropertyID::Color, CSS::ColorStyleValue::create(color.value()).release_value_but_fixme_should_propagate_errors(), nullptr); } else if (name.equals_ignoring_ascii_case("background"sv)) { VERIFY(m_background_style_value); - style.set_property(CSS::PropertyID::BackgroundImage, *m_background_style_value); + style.set_property(CSS::PropertyID::BackgroundImage, *m_background_style_value, nullptr); } }); }
145e246a5e9f229656bc1182bdc6c397ca8efe8a
2021-05-20 00:11:09
Timothy Flynn
ak: Allow AK::Variant::visit to return a value
false
Allow AK::Variant::visit to return a value
ak
diff --git a/AK/Variant.h b/AK/Variant.h index bc0610510b73..1bde4ad4b174 100644 --- a/AK/Variant.h +++ b/AK/Variant.h @@ -9,6 +9,7 @@ #include <AK/Array.h> #include <AK/BitCast.h> #include <AK/StdLibExtras.h> +#include <AK/TypeList.h> namespace AK::Detail { @@ -68,24 +69,6 @@ struct Variant<IndexType, InitialIndex, F, Ts...> { else Variant<IndexType, InitialIndex + 1, Ts...>::copy_(old_id, old_data, new_data); } - - template<typename Visitor> - static void visit_(IndexType id, void* data, Visitor&& visitor) - { - if (id == current_index) - visitor(*bit_cast<F*>(data)); - else - Variant<IndexType, InitialIndex + 1, Ts...>::visit_(id, data, forward<Visitor>(visitor)); - } - - template<typename Visitor> - static void visit_(IndexType id, const void* data, Visitor&& visitor) - { - if (id == current_index) - visitor(*bit_cast<const F*>(data)); - else - Variant<IndexType, InitialIndex + 1, Ts...>::visit_(id, data, forward<Visitor>(visitor)); - } }; template<typename IndexType, IndexType InitialIndex> @@ -93,10 +76,23 @@ struct Variant<IndexType, InitialIndex> { static void delete_(IndexType, void*) { } static void move_(IndexType, void*, void*) { } static void copy_(IndexType, const void*, void*) { } - template<typename Visitor> - static void visit_(IndexType, void*, Visitor&&) { } - template<typename Visitor> - static void visit_(IndexType, const void*, Visitor&&) { } +}; + +template<typename IndexType, typename... Ts> +struct VisitImpl { + template<typename Visitor, IndexType CurrentIndex = 0> + static constexpr inline decltype(auto) visit(IndexType id, const void* data, Visitor&& visitor) requires(CurrentIndex < sizeof...(Ts)) + { + using T = typename TypeList<Ts...>::template Type<CurrentIndex>; + + if (id == CurrentIndex) + return visitor(*bit_cast<T*>(data)); + + if constexpr ((CurrentIndex + 1) < sizeof...(Ts)) + return visit<Visitor, CurrentIndex + 1>(id, data, forward<Visitor>(visitor)); + else + VERIFY_NOT_REACHED(); + } }; struct VariantNoClearTag { @@ -310,17 +306,17 @@ struct Variant } template<typename... Fs> - void visit(Fs&&... functions) + decltype(auto) visit(Fs&&... functions) { Visitor<Fs...> visitor { forward<Fs>(functions)... }; - Helper::visit_(m_index, m_data, visitor); + return VisitHelper::visit(m_index, m_data, move(visitor)); } template<typename... Fs> - void visit(Fs&&... functions) const + decltype(auto) visit(Fs&&... functions) const { Visitor<Fs...> visitor { forward<Fs>(functions)... }; - Helper::visit_(m_index, m_data, visitor); + return VisitHelper::visit(m_index, m_data, move(visitor)); } template<typename... NewTs> @@ -357,6 +353,7 @@ struct Variant static constexpr auto data_size = integer_sequence_generate_array<size_t>(0, IntegerSequence<size_t, sizeof(Ts)...>()).max(); static constexpr auto data_alignment = integer_sequence_generate_array<size_t>(0, IntegerSequence<size_t, alignof(Ts)...>()).max(); using Helper = Detail::Variant<IndexType, 0, Ts...>; + using VisitHelper = Detail::VisitImpl<IndexType, Ts...>; explicit Variant(IndexType index, Detail::VariantConstructTag) : Detail::MergeAndDeduplicatePacks<Detail::VariantConstructors<Ts, Variant<Ts...>>...>() @@ -367,7 +364,7 @@ struct Variant template<typename... Fs> struct Visitor : Fs... { Visitor(Fs&&... args) - : Fs(args)... + : Fs(forward<Fs>(args))... { } diff --git a/Tests/AK/TestVariant.cpp b/Tests/AK/TestVariant.cpp index 587eae281934..28dc92340c5c 100644 --- a/Tests/AK/TestVariant.cpp +++ b/Tests/AK/TestVariant.cpp @@ -6,8 +6,16 @@ #include <LibTest/TestSuite.h> +#include <AK/RefPtr.h> #include <AK/Variant.h> +namespace { + +struct Object : public RefCounted<Object> { +}; + +} + TEST_CASE(basic) { Variant<int, String> the_value { 42 }; @@ -117,3 +125,50 @@ TEST_CASE(duplicated_types) EXPECT(its_just_an_int.has<int>()); EXPECT_EQ(its_just_an_int.get<int>(), 42); } + +TEST_CASE(return_values) +{ + using MyVariant = Variant<int, String, float>; + { + MyVariant the_value { 42.0f }; + + float value = the_value.visit( + [&](const int&) { return 1.0f; }, + [&](const String&) { return 2.0f; }, + [&](const float& f) { return f; }); + EXPECT_EQ(value, 42.0f); + } + { + MyVariant the_value { 42 }; + + int value = the_value.visit( + [&](int& i) { return i; }, + [&](String&) { return 2; }, + [&](float&) { return 3; }); + EXPECT_EQ(value, 42); + } + { + const MyVariant the_value { "str" }; + + String value = the_value.visit( + [&](const int&) { return String { "wrong" }; }, + [&](const String& s) { return s; }, + [&](const float&) { return String { "wrong" }; }); + EXPECT_EQ(value, "str"); + } +} + +TEST_CASE(return_values_by_reference) +{ + auto ref = adopt_ref_if_nonnull(new Object()); + Variant<int, String, float> the_value { 42.0f }; + + auto& value = the_value.visit( + [&](const int&) -> RefPtr<Object>& { return ref; }, + [&](const String&) -> RefPtr<Object>& { return ref; }, + [&](const float&) -> RefPtr<Object>& { return ref; }); + + EXPECT_EQ(ref, value); + EXPECT_EQ(ref->ref_count(), 1u); + EXPECT_EQ(value->ref_count(), 1u); +}
7daa462ef81618685846a52e715087bcf661b7f3
2023-09-16 20:23:32
Aliaksandr Kalenik
libweb: Remove BrowsingContext::create_a_new_top_level_browsing_context
false
Remove BrowsingContext::create_a_new_top_level_browsing_context
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 13586442158a..86c597749b97 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -126,9 +126,9 @@ static JS::NonnullGCPtr<HTML::BrowsingContext> obtain_a_browsing_context_to_use_ return browsing_context; } - // 3. Let newBrowsingContext be the result of creating a new top-level browsing context. + // 3. Let newBrowsingContext be the first return value of creating a new top-level browsing context and document VERIFY(browsing_context.page()); - auto new_browsing_context = HTML::BrowsingContext::create_a_new_top_level_browsing_context(*browsing_context.page()); + auto new_browsing_context = HTML::create_a_new_top_level_browsing_context_and_document(*browsing_context.page()).release_value_but_fixme_should_propagate_errors().browsing_context; // FIXME: 4. If navigationCOOP's value is "same-origin-plurs-COEP", then set newBrowsingContext's group's // cross-origin isolation mode to either "logical" or "concrete". The choice of which is implementation-defined. diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp index 86c51d9107aa..d9d4f45869f1 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp @@ -105,16 +105,6 @@ HTML::Origin determine_the_origin(AK::URL const& url, SandboxingFlagSet sandbox_ return URL::url_origin(url); } -// https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-top-level-browsing-context -JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_top_level_browsing_context(Web::Page& page) -{ - // 1. Let group be the result of creating a new browsing context group. - auto group = BrowsingContextGroup::create_a_new_browsing_context_group(page); - - // 2. Return group's browsing context set[0]. - return *group->browsing_context_set().begin(); -} - // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-browsing-context JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context(Page& page, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder, BrowsingContextGroup&) { @@ -859,7 +849,7 @@ BrowsingContext::ChosenBrowsingContext BrowsingContext::choose_a_browsing_contex else { // 1. Set chosen to the result of creating a new auxiliary browsing context with current. // FIXME: We have no concept of auxiliary browsing context - chosen = HTML::BrowsingContext::create_a_new_top_level_browsing_context(*m_page); + chosen = HTML::create_a_new_top_level_browsing_context_and_document(*m_page).release_value_but_fixme_should_propagate_errors().browsing_context; // 2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set, then current must be // set as chosen's one permitted sandboxed navigator. diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h index d97ab0bbcdb9..e09220e4f1f5 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.h +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.h @@ -39,7 +39,6 @@ class BrowsingContext final public: static JS::NonnullGCPtr<BrowsingContext> create_a_new_browsing_context(Page&, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder, BrowsingContextGroup&); - static JS::NonnullGCPtr<BrowsingContext> create_a_new_top_level_browsing_context(Page&); struct BrowsingContextAndDocument { JS::NonnullGCPtr<BrowsingContext> browsing_context; diff --git a/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp b/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp index 6eb34026c661..3e0905e2e36f 100644 --- a/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp +++ b/Userland/Libraries/LibWeb/HTML/TraversableNavigable.cpp @@ -36,13 +36,8 @@ static OrderedHashTable<TraversableNavigable*>& user_agent_top_level_traversable return set; } -struct BrowsingContextAndDocument { - JS::NonnullGCPtr<HTML::BrowsingContext> browsing_context; - JS::NonnullGCPtr<DOM::Document> document; -}; - // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-browsing-context -static WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(Page& page) +WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(Page& page) { // 1. Let group and document be the result of creating a new browsing context group and document. auto [group, document] = TRY(BrowsingContextGroup::create_a_new_browsing_context_group_and_document(page)); diff --git a/Userland/Libraries/LibWeb/HTML/TraversableNavigable.h b/Userland/Libraries/LibWeb/HTML/TraversableNavigable.h index 8ddf98c11b8e..72c6bb139b25 100644 --- a/Userland/Libraries/LibWeb/HTML/TraversableNavigable.h +++ b/Userland/Libraries/LibWeb/HTML/TraversableNavigable.h @@ -84,6 +84,12 @@ class TraversableNavigable final : public Navigable { WeakPtr<Page> m_page; }; +struct BrowsingContextAndDocument { + JS::NonnullGCPtr<HTML::BrowsingContext> browsing_context; + JS::NonnullGCPtr<DOM::Document> document; +}; + +WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(Page& page); void finalize_a_same_document_navigation(JS::NonnullGCPtr<TraversableNavigable> traversable, JS::NonnullGCPtr<Navigable> target_navigable, JS::NonnullGCPtr<SessionHistoryEntry> target_entry, JS::GCPtr<SessionHistoryEntry> entry_to_replace); }
c05f296014f9c1b3ce8f825125718cefa457874e
2024-05-23 22:55:29
Andrew Kaster
libweb: Start adding infrastructure for an HTTP Cache
false
Start adding infrastructure for an HTTP Cache
libweb
diff --git a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp index e27393fe7160..f3c0c7ddf5d5 100644 --- a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp @@ -1252,6 +1252,126 @@ WebIDL::ExceptionOr<JS::GCPtr<PendingResponse>> http_redirect_fetch(JS::Realm& r return main_fetch(realm, fetch_params, recursive); } +// https://fetch.spec.whatwg.org/#network-partition-key +struct NetworkPartitionKey { + HTML::Origin top_level_origin; + // FIXME: See https://github.com/whatwg/fetch/issues/1035 + // This is the document origin in other browsers + void* second_key = nullptr; + + bool operator==(NetworkPartitionKey const&) const = default; +}; + +} + +// FIXME: Take this with us to the eventual header these structs end up in to avoid closing and re-opening the namespace. +template<> +class AK::Traits<Web::Fetch::Fetching::NetworkPartitionKey> : public DefaultTraits<Web::Fetch::Fetching::NetworkPartitionKey> { +public: + static unsigned hash(Web::Fetch::Fetching::NetworkPartitionKey const& partition_key) + { + return ::AK::Traits<Web::HTML::Origin>::hash(partition_key.top_level_origin); + } +}; + +namespace Web::Fetch::Fetching { + +struct CachedResponse { + Vector<Infrastructure::Header> headers; + ByteBuffer body; + ByteBuffer method; + URL::URL url; + UnixDateTime current_age; +}; + +class CachePartition { +public: + // FIXME: Copy the headers... less + Optional<CachedResponse> select_response(URL::URL const& url, ReadonlyBytes method, Vector<Infrastructure::Header> const& headers) const + { + auto it = m_cache.find(url); + if (it == m_cache.end()) + return {}; + + auto const& cached_response = it->value; + + // FIXME: Validate headers and method + (void)method; + (void)headers; + return cached_response; + } + +private: + HashMap<URL::URL, CachedResponse> m_cache; +}; + +class HTTPCache { +public: + CachePartition& get(NetworkPartitionKey const& key) + { + return *m_cache.ensure(key, [] { + return make<CachePartition>(); + }); + } + + static HTTPCache& the() + { + static HTTPCache s_cache; + return s_cache; + } + +private: + HashMap<NetworkPartitionKey, NonnullOwnPtr<CachePartition>> m_cache; +}; + +// https://fetch.spec.whatwg.org/#determine-the-network-partition-key +static NetworkPartitionKey determine_the_network_partition_key(HTML::Environment const& environment) +{ + // 1. Let topLevelOrigin be environment’s top-level origin. + auto top_level_origin = environment.top_level_origin; + + // FIXME: 2. If topLevelOrigin is null, then set topLevelOrigin to environment’s top-level creation URL’s origin + // This field is supposed to be nullable + + // 3. Assert: topLevelOrigin is an origin. + + // FIXME: 4. Let topLevelSite be the result of obtaining a site, given topLevelOrigin. + + // 5. Let secondKey be null or an implementation-defined value. + void* second_key = nullptr; + + // 6. Return (topLevelSite, secondKey). + return { top_level_origin, second_key }; +} + +// https://fetch.spec.whatwg.org/#request-determine-the-network-partition-key +static Optional<NetworkPartitionKey> determine_the_network_partition_key(Infrastructure::Request const& request) +{ + // 1. If request’s reserved client is non-null, then return the result of determining the network partition key given request’s reserved client. + if (auto reserved_client = request.reserved_client()) + return determine_the_network_partition_key(*reserved_client); + + // 2. If request’s client is non-null, then return the result of determining the network partition key given request’s client. + if (auto client = request.client()) + return determine_the_network_partition_key(*client); + + return {}; +} + +// https://fetch.spec.whatwg.org/#determine-the-http-cache-partition +static Optional<CachePartition> determine_the_http_cache_partition(Infrastructure::Request const& request) +{ + // 1. Let key be the result of determining the network partition key given request. + auto key = determine_the_network_partition_key(request); + + // 2. If key is null, then return null. + if (!key.has_value()) + return OptionalNone {}; + + // 3. Return the unique HTTP cache associated with key. [HTTP-CACHING] + return HTTPCache::the().get(key.value()); +} + // https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch) { @@ -1277,7 +1397,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet // 6. Let httpCache be null. // (Typeless until we actually implement it, needed for checks below) - void* http_cache = nullptr; + Optional<CachePartition> http_cache; // 7. Let the revalidatingFlag be unset. auto revalidating_flag = RefCountedFlag::create(false); @@ -1519,10 +1639,11 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet // FIXME: 22. If there’s a proxy-authentication entry, use it as appropriate. // NOTE: This intentionally does not depend on httpRequest’s credentials mode. - // FIXME: 23. Set httpCache to the result of determining the HTTP cache partition, given httpRequest. + // 23. Set httpCache to the result of determining the HTTP cache partition, given httpRequest. + http_cache = determine_the_http_cache_partition(*http_request); // 24. If httpCache is null, then set httpRequest’s cache mode to "no-store". - if (!http_cache) + if (!http_cache.has_value()) http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore); // 25. If httpRequest’s cache mode is neither "no-store" nor "reload", then: @@ -1532,10 +1653,15 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet // validation, as per the "Constructing Responses from Caches" chapter of HTTP Caching [HTTP-CACHING], // if any. // NOTE: As mandated by HTTP, this still takes the `Vary` header into account. - stored_response = nullptr; - + auto raw_response = http_cache->select_response(http_request->url(), http_request->method(), *http_request->header_list()); // 2. If storedResponse is non-null, then: - if (stored_response) { + if (raw_response.has_value()) { + + // FIXME: Set more properties from the cached response + auto [body, _] = TRY(extract_body(realm, ReadonlyBytes(raw_response->body))); + stored_response = Infrastructure::Response::create(vm); + stored_response->set_body(body); + // FIXME: Caching is not implemented yet. VERIFY_NOT_REACHED(); } diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h index 6c4ac5336c5b..886dc380b824 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h @@ -33,7 +33,7 @@ struct Header { // A header list is a list of zero or more headers. It is initially the empty list. class HeaderList final : public JS::Cell - , Vector<Header> { + , public Vector<Header> { JS_CELL(HeaderList, JS::Cell); JS_DECLARE_ALLOCATOR(HeaderList);
b3be275cf78e0904f6949390dbe48d8ddd090c7e
2020-09-27 04:32:11
Luke
libelf: Validate PT_GNU_RELRO program header
false
Validate PT_GNU_RELRO program header
libelf
diff --git a/Libraries/LibELF/Validation.cpp b/Libraries/LibELF/Validation.cpp index 62229f923f56..759ce24bc906 100644 --- a/Libraries/LibELF/Validation.cpp +++ b/Libraries/LibELF/Validation.cpp @@ -202,6 +202,12 @@ bool validate_program_headers(const Elf32_Ehdr& elf_header, size_t file_size, u8 dbgprintf("Possible shenanigans! Validating an ELF with executable stack.\n"); } break; + case PT_GNU_RELRO: + if ((program_header.p_flags & PF_X) && (program_header.p_flags & PF_W)) { + dbgprintf("SHENANIGANS! Program header %zu segment is marked write and execute\n", header_index); + return false; + } + break; default: // Not handling other program header types in other code so... let's not surprise them dbgprintf("Found program header (%zu) of unrecognized type %x!\n", header_index, program_header.p_type);
6da0ac3aa71c991e18e96d721b1843c417cdab78
2024-11-05 05:45:15
Shannon Booth
libjs: Update CreateDynamicFunction to latest spec
false
Update CreateDynamicFunction to latest spec
libjs
diff --git a/Userland/Libraries/LibJS/Parser.h b/Userland/Libraries/LibJS/Parser.h index 273b907168b5..531bb74acbc4 100644 --- a/Userland/Libraries/LibJS/Parser.h +++ b/Userland/Libraries/LibJS/Parser.h @@ -209,7 +209,7 @@ class Parser { }; // Needs to mess with m_state, and we're not going to expose a non-const getter for that :^) - friend ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic_function(VM&, FunctionObject&, FunctionObject*, FunctionKind, MarkedVector<Value> const&); + friend ThrowCompletionOr<NonnullGCPtr<ECMAScriptFunctionObject>> FunctionConstructor::create_dynamic_function(VM&, FunctionObject&, FunctionObject*, FunctionKind, ReadonlySpan<String> parameter_args, String const& body_arg); static Parser parse_function_body_from_string(ByteString const& body_string, u16 parse_options, Vector<FunctionParameter> const& parameters, FunctionKind kind, FunctionParsingInsights&); diff --git a/Userland/Libraries/LibJS/Runtime/AsyncFunctionConstructor.cpp b/Userland/Libraries/LibJS/Runtime/AsyncFunctionConstructor.cpp index 7766fbae1b17..2e027279a591 100644 --- a/Userland/Libraries/LibJS/Runtime/AsyncFunctionConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/AsyncFunctionConstructor.cpp @@ -36,7 +36,7 @@ ThrowCompletionOr<Value> AsyncFunctionConstructor::call() return TRY(construct(*this)); } -// 27.7.1.1 AsyncFunction ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-async-function-constructor-arguments +// 27.7.1.1 AsyncFunction ( ...parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-async-function-constructor-arguments ThrowCompletionOr<NonnullGCPtr<Object>> AsyncFunctionConstructor::construct(FunctionObject& new_target) { auto& vm = this->vm(); @@ -44,13 +44,12 @@ ThrowCompletionOr<NonnullGCPtr<Object>> AsyncFunctionConstructor::construct(Func // 1. Let C be the active function object. auto* constructor = vm.active_function_object(); - // 2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]]. - MarkedVector<Value> args(heap()); - for (auto argument : vm.running_execution_context().arguments) - args.append(argument); + // 2. If bodyArg is not present, set bodyArg to the empty String. + // NOTE: This does that, as well as the string extraction done inside of CreateDynamicFunction + auto extracted = TRY(extract_parameter_arguments_and_body(vm, vm.running_execution_context().arguments)); - // 3. Return CreateDynamicFunction(C, NewTarget, async, args). - return *TRY(FunctionConstructor::create_dynamic_function(vm, *constructor, &new_target, FunctionKind::Async, args)); + // 3. Return ? CreateDynamicFunction(C, NewTarget, async, parameterArgs, bodyArg). + return TRY(FunctionConstructor::create_dynamic_function(vm, *constructor, &new_target, FunctionKind::Async, extracted.parameters, extracted.body)); } } diff --git a/Userland/Libraries/LibJS/Runtime/AsyncGeneratorFunctionConstructor.cpp b/Userland/Libraries/LibJS/Runtime/AsyncGeneratorFunctionConstructor.cpp index e52b12820fec..055667e45eba 100644 --- a/Userland/Libraries/LibJS/Runtime/AsyncGeneratorFunctionConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/AsyncGeneratorFunctionConstructor.cpp @@ -37,7 +37,7 @@ ThrowCompletionOr<Value> AsyncGeneratorFunctionConstructor::call() return TRY(construct(*this)); } -// 27.4.1.1 AsyncGeneratorFunction ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-asyncgeneratorfunction +// 27.4.1.1 AsyncGeneratorFunction ( ...parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-asyncgeneratorfunction ThrowCompletionOr<NonnullGCPtr<Object>> AsyncGeneratorFunctionConstructor::construct(FunctionObject& new_target) { auto& vm = this->vm(); @@ -45,13 +45,12 @@ ThrowCompletionOr<NonnullGCPtr<Object>> AsyncGeneratorFunctionConstructor::const // 1. Let C be the active function object. auto* constructor = vm.active_function_object(); - // 2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]]. - MarkedVector<Value> args(heap()); - for (auto argument : vm.running_execution_context().arguments) - args.append(argument); + // 2. If bodyArg is not present, set bodyArg to the empty String. + // NOTE: This does that, as well as the string extraction done inside of CreateDynamicFunction + auto extracted = TRY(extract_parameter_arguments_and_body(vm, vm.running_execution_context().arguments)); - // 3. Return ? CreateDynamicFunction(C, NewTarget, asyncGenerator, args). - return *TRY(FunctionConstructor::create_dynamic_function(vm, *constructor, &new_target, FunctionKind::AsyncGenerator, args)); + // 3. Return ? CreateDynamicFunction(C, NewTarget, async-generator, parameterArgs, bodyArg). + return TRY(FunctionConstructor::create_dynamic_function(vm, *constructor, &new_target, FunctionKind::AsyncGenerator, extracted.parameters, extracted.body)); } } diff --git a/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp b/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp index dc3e680be80d..94bb6ed42c46 100644 --- a/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/FunctionConstructor.cpp @@ -36,16 +36,35 @@ void FunctionConstructor::initialize(Realm& realm) define_direct_property(vm.names.length, Value(1), Attribute::Configurable); } -// 20.2.1.1.1 CreateDynamicFunction ( constructor, newTarget, kind, args ), https://tc39.es/ecma262/#sec-createdynamicfunction -ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic_function(VM& vm, FunctionObject& constructor, FunctionObject* new_target, FunctionKind kind, MarkedVector<Value> const& args) +// NON-STANDARD: Exists to simplify calling CreateDynamicFunction using strong types, instead of a Value. +// Analogous to parts of the following two AO's - and basically just extracts the body and parameters as strings. +// +// 20.2.1.1 Function ( ...parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-function-p1-p2-pn-body +// 20.2.1.1.1 CreateDynamicFunction ( constructor, newTarget, kind, parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-createdynamicfunction +ThrowCompletionOr<ParameterArgumentsAndBody> extract_parameter_arguments_and_body(VM& vm, Span<Value> arguments) { - // 1. Let currentRealm be the current Realm Record. - auto& current_realm = *vm.current_realm(); + if (arguments.is_empty()) + return ParameterArgumentsAndBody {}; - // 2. Perform ? HostEnsureCanCompileStrings(currentRealm). - TRY(vm.host_ensure_can_compile_strings(current_realm)); + auto parameter_values = arguments.slice(0, arguments.size() - 1); + + Vector<String> parameters; + parameters.ensure_capacity(parameter_values.size()); + for (auto const& parameter_value : parameter_values) + parameters.unchecked_append(TRY(parameter_value.to_string(vm))); - // 3. If newTarget is undefined, set newTarget to constructor. + auto body = TRY(arguments.last().to_string(vm)); + + return ParameterArgumentsAndBody { + .parameters = move(parameters), + .body = move(body), + }; +} + +// 20.2.1.1.1 CreateDynamicFunction ( constructor, newTarget, kind, parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-createdynamicfunction +ThrowCompletionOr<NonnullGCPtr<ECMAScriptFunctionObject>> FunctionConstructor::create_dynamic_function(VM& vm, FunctionObject& constructor, FunctionObject* new_target, FunctionKind kind, ReadonlySpan<String> parameter_strings, String const& body_string) +{ + // 1. If newTarget is undefined, set newTarget to constructor. if (new_target == nullptr) new_target = &constructor; @@ -53,7 +72,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic NonnullGCPtr<Object> (Intrinsics::*fallback_prototype)() = nullptr; switch (kind) { - // 4. If kind is normal, then + // 2. If kind is normal, then case FunctionKind::Normal: // a. Let prefix be "function". prefix = "function"sv; @@ -66,7 +85,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic fallback_prototype = &Intrinsics::function_prototype; break; - // 5. Else if kind is generator, then + // 3. Else if kind is generator, then case FunctionKind::Generator: // a. Let prefix be "function*". prefix = "function*"sv; @@ -79,7 +98,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic fallback_prototype = &Intrinsics::generator_function_prototype; break; - // 6. Else if kind is async, then + // 4. Else if kind is async, then case FunctionKind::Async: // a. Let prefix be "async function". prefix = "async function"sv; @@ -92,9 +111,9 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic fallback_prototype = &Intrinsics::async_function_prototype; break; - // 7. Else, + // 5. Else, case FunctionKind::AsyncGenerator: - // a. Assert: kind is asyncGenerator. + // a. Assert: kind is async-generator. // b. Let prefix be "async function*". prefix = "async function*"sv; @@ -111,58 +130,41 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic VERIFY_NOT_REACHED(); } - // 8. Let argCount be the number of elements in args. - auto arg_count = args.size(); + // 6. Let argCount be the number of elements in parameterArgs. + auto arg_count = parameter_strings.size(); + + // NOTE: Done by caller + // 7. Let parameterStrings be a new empty List. + // 8. For each element arg of parameterArgs, do + // a. Append ? ToString(arg) to parameterStrings. + // 9. Let bodyString be ? ToString(bodyArg). - // 9. Let P be the empty String. - ByteString parameters_string = ""; + // 10. Let currentRealm be the current Realm Record. + auto& realm = *vm.current_realm(); - Optional<Value> body_arg; + // FIXME: 11. Perform ? HostEnsureCanCompileStrings(currentRealm, parameterStrings, bodyString, false). + TRY(vm.host_ensure_can_compile_strings(current_realm)); - // 10. If argCount = 0, let bodyArg be the empty String. - if (arg_count == 0) { - // Optimization: Instead of creating a PrimitiveString here, we just check if body_arg is empty in step 16. - } - // 11. Else if argCount = 1, let bodyArg be args[0]. - else if (arg_count == 1) { - body_arg = args[0]; - } - // 12. Else, - else { - // a. Assert: argCount > 1. - VERIFY(arg_count > 1); - - // b. Let firstArg be args[0]. - // c. Set P to ? ToString(firstArg). - // NOTE: Also done in the loop. We start at 0 instead and then join() with a comma. - - // d. Let k be 1. - size_t k = 0; - - // e. Repeat, while k < argCount - 1, - Vector<ByteString> parameters; - for (; k < arg_count - 1; ++k) { - // i. Let nextArg be args[k]. - auto next_arg = args[k]; - - // ii. Let nextArgString be ? ToString(nextArg). - // iii. Set P to the string-concatenation of P, "," (a comma), and nextArgString. - parameters.append(TRY(next_arg.to_byte_string(vm))); - - // iv. Set k to k + 1. - } - parameters_string = ByteString::join(',', parameters); - - // f. Let bodyArg be args[k]. - body_arg = args[k]; + // 12. Let P be the empty String. + String parameters_string; + + // 13. If argCount > 0, then + if (arg_count > 0) { + // a. Set P to parameterStrings[0]. + // b. Let k be 1. + // c. Repeat, while k < argCount, + // i. Let nextArgString be parameterStrings[k]. + // ii. Set P to the string-concatenation of P, "," (a comma), and nextArgString. + // iii. Set k to k + 1. + parameters_string = MUST(String::join(',', parameter_strings)); } - // 13. Let bodyString be the string-concatenation of 0x000A (LINE FEED), ? ToString(bodyArg), and 0x000A (LINE FEED). - auto body_string = ByteString::formatted("\n{}\n", body_arg.has_value() ? TRY(body_arg->to_byte_string(vm)) : ""); + // 14. Let bodyParseString be the string-concatenation of 0x000A (LINE FEED), bodyString, and 0x000A (LINE FEED). + auto body_parse_string = ByteString::formatted("\n{}\n", body_string); - // 14. Let sourceString be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", bodyString, and "}". - // 15. Let sourceText be StringToCodePoints(sourceString). - auto source_text = ByteString::formatted("{} anonymous({}\n) {{{}}}", prefix, parameters_string, body_string); + // 15. Let sourceString be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", bodyParseString, and "}". + // 16. Let sourceText be StringToCodePoints(sourceString). + auto source_text = ByteString::formatted("{} anonymous({}\n) {{{}}}", prefix, parameters_string, body_parse_string); u8 parse_options = FunctionNodeParseOptions::CheckForFunctionAndName; if (kind == FunctionKind::Async || kind == FunctionKind::AsyncGenerator) @@ -170,48 +172,45 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic if (kind == FunctionKind::Generator || kind == FunctionKind::AsyncGenerator) parse_options |= FunctionNodeParseOptions::IsGeneratorFunction; - // 16. Let parameters be ParseText(StringToCodePoints(P), parameterSym). + // 17. Let parameters be ParseText(P, parameterSym). i32 function_length = 0; auto parameters_parser = Parser { Lexer { parameters_string } }; auto parameters = parameters_parser.parse_formal_parameters(function_length, parse_options); - // 17. If parameters is a List of errors, throw a SyntaxError exception. + // 18. If parameters is a List of errors, throw a SyntaxError exception. if (parameters_parser.has_errors()) { auto error = parameters_parser.errors()[0]; return vm.throw_completion<SyntaxError>(error.to_string()); } - // 18. Let body be ParseText(StringToCodePoints(bodyString), bodySym). + // 19. Let body be ParseText(bodyParseString, bodySym). FunctionParsingInsights parsing_insights; - auto body_parser = Parser::parse_function_body_from_string(body_string, parse_options, parameters, kind, parsing_insights); + auto body_parser = Parser::parse_function_body_from_string(body_parse_string, parse_options, parameters, kind, parsing_insights); - // 19. If body is a List of errors, throw a SyntaxError exception. + // 20. If body is a List of errors, throw a SyntaxError exception. if (body_parser.has_errors()) { auto error = body_parser.errors()[0]; return vm.throw_completion<SyntaxError>(error.to_string()); } - // 20. NOTE: The parameters and body are parsed separately to ensure that each is valid alone. For example, new Function("/*", "*/ ) {") is not legal. - // 21. NOTE: If this step is reached, sourceText must have the syntax of exprSym (although the reverse implication does not hold). The purpose of the next two steps is to enforce any Early Error rules which apply to exprSym directly. + // 21. NOTE: The parameters and body are parsed separately to ensure that each is valid alone. For example, new Function("/*", "*/ ) {") does not evaluate to a function. + // 22. NOTE: If this step is reached, sourceText must have the syntax of exprSym (although the reverse implication does not hold). The purpose of the next two steps is to enforce any Early Error rules which apply to exprSym directly. - // 22. Let expr be ParseText(sourceText, exprSym). + // 23. Let expr be ParseText(sourceText, exprSym). auto source_parser = Parser { Lexer { source_text } }; // This doesn't need any parse_options, it determines those & the function type based on the tokens that were found. auto expr = source_parser.parse_function_node<FunctionExpression>(); - // 23. If expr is a List of errors, throw a SyntaxError exception. + // 24. If expr is a List of errors, throw a SyntaxError exception. if (source_parser.has_errors()) { auto error = source_parser.errors()[0]; return vm.throw_completion<SyntaxError>(error.to_string()); } - // 24. Let proto be ? GetPrototypeFromConstructor(newTarget, fallbackProto). + // 25. Let proto be ? GetPrototypeFromConstructor(newTarget, fallbackProto). auto* prototype = TRY(get_prototype_from_constructor(vm, *new_target, fallback_prototype)); - // 25. Let realmF be the current Realm Record. - auto& realm = *vm.current_realm(); - - // 26. Let env be realmF.[[GlobalEnv]]. + // 26. Let env be currentRealm.[[GlobalEnv]]. auto& environment = realm.global_environment(); // 27. Let privateEnv be null. @@ -251,7 +250,7 @@ ThrowCompletionOr<ECMAScriptFunctionObject*> FunctionConstructor::create_dynamic // 33. NOTE: Functions whose kind is async are not constructible and do not have a [[Construct]] internal method or a "prototype" property. // 34. Return F. - return function.ptr(); + return function; } // 20.2.1.1 Function ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-function-p1-p2-pn-body @@ -260,7 +259,7 @@ ThrowCompletionOr<Value> FunctionConstructor::call() return TRY(construct(*this)); } -// 20.2.1.1 Function ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-function-p1-p2-pn-body +// 20.2.1.1 Function ( ...parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-function-p1-p2-pn-body ThrowCompletionOr<NonnullGCPtr<Object>> FunctionConstructor::construct(FunctionObject& new_target) { auto& vm = this->vm(); @@ -268,13 +267,12 @@ ThrowCompletionOr<NonnullGCPtr<Object>> FunctionConstructor::construct(FunctionO // 1. Let C be the active function object. auto* constructor = vm.active_function_object(); - // 2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]]. - MarkedVector<Value> args(heap()); - for (auto argument : vm.running_execution_context().arguments) - args.append(argument); + // 2. If bodyArg is not present, set bodyArg to the empty String. + // NOTE: This does that, as well as the string extraction done inside of CreateDynamicFunction + auto extracted = TRY(extract_parameter_arguments_and_body(vm, vm.running_execution_context().arguments)); - // 3. Return ? CreateDynamicFunction(C, NewTarget, normal, args). - return *TRY(create_dynamic_function(vm, *constructor, &new_target, FunctionKind::Normal, args)); + // 3. Return ? CreateDynamicFunction(C, NewTarget, normal, parameterArgs, bodyArg). + return TRY(create_dynamic_function(vm, *constructor, &new_target, FunctionKind::Normal, extracted.parameters, extracted.body)); } } diff --git a/Userland/Libraries/LibJS/Runtime/FunctionConstructor.h b/Userland/Libraries/LibJS/Runtime/FunctionConstructor.h index 9d3ce488af6b..8ddef827d178 100644 --- a/Userland/Libraries/LibJS/Runtime/FunctionConstructor.h +++ b/Userland/Libraries/LibJS/Runtime/FunctionConstructor.h @@ -11,12 +11,19 @@ namespace JS { +struct ParameterArgumentsAndBody { + Vector<String> parameters; + String body; +}; + +ThrowCompletionOr<ParameterArgumentsAndBody> extract_parameter_arguments_and_body(VM&, Span<Value> arguments); + class FunctionConstructor final : public NativeFunction { JS_OBJECT(FunctionConstructor, NativeFunction); JS_DECLARE_ALLOCATOR(FunctionConstructor); public: - static ThrowCompletionOr<ECMAScriptFunctionObject*> create_dynamic_function(VM&, FunctionObject& constructor, FunctionObject* new_target, FunctionKind kind, MarkedVector<Value> const& args); + static ThrowCompletionOr<NonnullGCPtr<ECMAScriptFunctionObject>> create_dynamic_function(VM&, FunctionObject& constructor, FunctionObject* new_target, FunctionKind kind, ReadonlySpan<String> parameter_args, String const& body_string); virtual void initialize(Realm&) override; virtual ~FunctionConstructor() override = default; diff --git a/Userland/Libraries/LibJS/Runtime/GeneratorFunctionConstructor.cpp b/Userland/Libraries/LibJS/Runtime/GeneratorFunctionConstructor.cpp index 1bea1bd0e1db..cab1711c11bb 100644 --- a/Userland/Libraries/LibJS/Runtime/GeneratorFunctionConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/GeneratorFunctionConstructor.cpp @@ -35,7 +35,7 @@ ThrowCompletionOr<Value> GeneratorFunctionConstructor::call() return TRY(construct(*this)); } -// 27.3.1.1 GeneratorFunction ( p1, p2, … , pn, body ), https://tc39.es/ecma262/#sec-generatorfunction +// 27.3.1.1 GeneratorFunction ( ...parameterArgs, bodyArg ), https://tc39.es/ecma262/#sec-generatorfunction ThrowCompletionOr<NonnullGCPtr<Object>> GeneratorFunctionConstructor::construct(FunctionObject& new_target) { auto& vm = this->vm(); @@ -43,13 +43,12 @@ ThrowCompletionOr<NonnullGCPtr<Object>> GeneratorFunctionConstructor::construct( // 1. Let C be the active function object. auto* constructor = vm.active_function_object(); - // 2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]]. - MarkedVector<Value> args(heap()); - for (auto argument : vm.running_execution_context().arguments) - args.append(argument); + // 2. If bodyArg is not present, set bodyArg to the empty String. + // NOTE: This does that, as well as the string extraction done inside of CreateDynamicFunction + auto extracted = TRY(extract_parameter_arguments_and_body(vm, vm.running_execution_context().arguments)); - // 3. Return ? CreateDynamicFunction(C, NewTarget, generator, args). - return *TRY(FunctionConstructor::create_dynamic_function(vm, *constructor, &new_target, FunctionKind::Generator, args)); + // 3. Return ? CreateDynamicFunction(C, NewTarget, generator, parameterArgs, bodyArg). + return TRY(FunctionConstructor::create_dynamic_function(vm, *constructor, &new_target, FunctionKind::Generator, extracted.parameters, extracted.body)); } }
ee25e2adc22d96bb2dc7113cc5e87c3197defb90
2021-09-13 17:13:53
Mustafa Quraish
pixelpaint: Call `Layer::did_modify_bitmap()` when applying filters
false
Call `Layer::did_modify_bitmap()` when applying filters
pixelpaint
diff --git a/Userland/Applications/PixelPaint/MainWidget.cpp b/Userland/Applications/PixelPaint/MainWidget.cpp index 6bf69d944278..2d4f0f77667d 100644 --- a/Userland/Applications/PixelPaint/MainWidget.cpp +++ b/Userland/Applications/PixelPaint/MainWidget.cpp @@ -577,6 +577,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::LaplacianFilter filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::LaplacianFilter>::get(false)) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -589,6 +590,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::LaplacianFilter filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::LaplacianFilter>::get(true)) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -602,6 +604,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::SpatialGaussianBlurFilter<3> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::SpatialGaussianBlurFilter<3>>::get()) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -614,6 +617,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::SpatialGaussianBlurFilter<5> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::SpatialGaussianBlurFilter<5>>::get()) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -626,6 +630,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::BoxBlurFilter<3> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::BoxBlurFilter<3>>::get()) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -638,6 +643,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::BoxBlurFilter<5> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::BoxBlurFilter<5>>::get()) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -650,6 +656,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::SharpenFilter filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::SharpenFilter>::get()) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -664,6 +671,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) Gfx::GenericConvolutionFilter<5> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::GenericConvolutionFilter<5>>::get(&window)) { filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } } @@ -677,6 +685,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) if (auto* layer = editor->active_layer()) { Gfx::GrayscaleFilter filter; filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect()); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } })); @@ -687,6 +696,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) if (auto* layer = editor->active_layer()) { Gfx::InvertFilter filter; filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect()); + layer->did_modify_bitmap(layer->rect()); editor->did_complete_action(); } }));
34741d09c6e69bd7cd8450668facd552cd69d21b
2024-07-04 18:08:56
Tim Ledbetter
libweb: Update `Range::set_base_and_extent()` to the latest spec text
false
Update `Range::set_base_and_extent()` to the latest spec text
libweb
diff --git a/Tests/LibWeb/Text/expected/set-selection-inside-shadow-root.txt b/Tests/LibWeb/Text/expected/set-selection-inside-shadow-root.txt new file mode 100644 index 000000000000..c31bca59738b --- /dev/null +++ b/Tests/LibWeb/Text/expected/set-selection-inside-shadow-root.txt @@ -0,0 +1,2 @@ + Selection range count: 1 +Selection start offset: 0, end offset: 1 \ No newline at end of file diff --git a/Tests/LibWeb/Text/input/set-selection-inside-shadow-root.html b/Tests/LibWeb/Text/input/set-selection-inside-shadow-root.html new file mode 100644 index 000000000000..df03d6afe725 --- /dev/null +++ b/Tests/LibWeb/Text/input/set-selection-inside-shadow-root.html @@ -0,0 +1,21 @@ +<script src="include.js"></script> +<div id="root"></div> +<script> + function printSelectionDetails(selection) { + println(`Selection range count: ${selection.rangeCount}`); + if (selection.rangeCount > 0) + println(`Selection start offset: ${selection.getRangeAt(0).startOffset}, end offset: ${selection.getRangeAt(0).endOffset}`); + } + + test(() => { + const rootElement = document.getElementById("root"); + const shadowRoot = rootElement.attachShadow({ mode: "open" }); + shadowRoot.innerHTML = "This is some text"; + const selection = window.getSelection(); + selection.setBaseAndExtent(shadowRoot, 0, shadowRoot, 1); + println(`Selection range count: ${selection.rangeCount}`); + println(`Selection start offset: ${selection.getRangeAt(0).startOffset}, end offset: ${selection.getRangeAt(0).endOffset}`); + + shadowRoot.innerHTML = ""; + }); +</script> diff --git a/Userland/Libraries/LibWeb/Selection/Selection.cpp b/Userland/Libraries/LibWeb/Selection/Selection.cpp index b9b9115dd92e..6ec1284454f2 100644 --- a/Userland/Libraries/LibWeb/Selection/Selection.cpp +++ b/Userland/Libraries/LibWeb/Selection/Selection.cpp @@ -306,11 +306,8 @@ WebIDL::ExceptionOr<void> Selection::set_base_and_extent(JS::NonnullGCPtr<DOM::N if (focus_offset > focus_node->length()) return WebIDL::IndexSizeError::create(realm(), "Focus offset points outside of the focus node"_fly_string); - // 2. If the roots of anchorNode or focusNode are not the document associated with this, abort these steps. - if (&anchor_node->root() != m_document.ptr()) - return {}; - - if (&focus_node->root() != m_document.ptr()) + // 2. If document associated with this is not a shadow-including inclusive ancestor of anchorNode or focusNode, abort these steps. + if (!(m_document->is_shadow_including_inclusive_ancestor_of(anchor_node) || m_document->is_shadow_including_inclusive_ancestor_of(focus_node))) return {}; // 3. Let anchor be the boundary point (anchorNode, anchorOffset) and let focus be the boundary point (focusNode, focusOffset).
693d602b2fa73f15c98bb993c7d0317696e47366
2023-09-20 21:58:11
Aliaksandr Kalenik
libweb: Fix infinite loop in GFC growth limit distribution
false
Fix infinite loop in GFC growth limit distribution
libweb
diff --git a/Tests/LibWeb/Layout/expected/grid/should-not-hang-in-size-distribution.txt b/Tests/LibWeb/Layout/expected/grid/should-not-hang-in-size-distribution.txt new file mode 100644 index 000000000000..0676d13e2b5d --- /dev/null +++ b/Tests/LibWeb/Layout/expected/grid/should-not-hang-in-size-distribution.txt @@ -0,0 +1,16 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x33.46875 [BFC] children: not-inline + Box <body> at (8,8) content-size 784x17.46875 [GFC] children: not-inline + BlockContainer <div#item> at (8,8) content-size 784x17.46875 [BFC] children: not-inline + BlockContainer <div#block> at (8,8) content-size 784x17.46875 children: inline + line 0 width: 210.484375, height: 17.46875, bottom: 17.46875, baseline: 13.53125 + frag 0 from TextNode start: 0, length: 26, rect: [8,8 210.484375x17.46875] + "Taika Waititi's Best Roles" + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x33.46875] + PaintableBox (Box<BODY>) [8,8 784x17.46875] + PaintableWithLines (BlockContainer<DIV>#item) [8,8 784x17.46875] + PaintableWithLines (BlockContainer<DIV>#block) [8,8 784x17.46875] + TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/input/grid/should-not-hang-in-size-distribution.html b/Tests/LibWeb/Layout/input/grid/should-not-hang-in-size-distribution.html new file mode 100644 index 000000000000..bf85de9606fc --- /dev/null +++ b/Tests/LibWeb/Layout/input/grid/should-not-hang-in-size-distribution.html @@ -0,0 +1,17 @@ +<!doctype html><style> +* { + outline: 1px solid black; +} +html { + font: inherit; +} +body { + display: grid; +} +#item { + grid-column: span 4 / auto; +} +#block { + min-width: 0px; +} +</style><body><div id="item"><div id="block">Taika Waititi's Best Roles \ No newline at end of file diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp index 649bf8ba4e0d..4d3a0c5b7420 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp @@ -935,7 +935,7 @@ void GridFormattingContext::distribute_extra_space_across_spanned_tracks_growth_ auto extra_space = max(CSSPixels(0), item_size_contribution - spanned_tracks_sizes_sum); // 2. Distribute space up to limits: - while (true) { + while (extra_space > 0) { auto all_frozen = all_of(affected_tracks, [](auto const& track) { return track.growth_limit_frozen; }); if (all_frozen) break; @@ -943,23 +943,24 @@ void GridFormattingContext::distribute_extra_space_across_spanned_tracks_growth_ // Find the item-incurred increase for each spanned track with an affected size by: distributing the space // equally among such tracks, freezing a track’s item-incurred increase as its affected size + item-incurred // increase reaches its limit - CSSPixels increase_per_track = extra_space / affected_tracks.size(); - if (increase_per_track == 0) - break; + CSSPixels increase_per_track = max(CSSPixels::smallest_positive_value(), extra_space / affected_tracks.size()); for (auto& track : affected_tracks) { if (track.growth_limit_frozen) continue; + auto increase = min(increase_per_track, extra_space); + // For growth limits, the limit is infinity if it is marked as infinitely growable, and equal to the // growth limit otherwise. - if (track.infinitely_growable || !track.growth_limit.has_value()) { - track.item_incurred_increase += increase_per_track; - extra_space -= increase_per_track; - } else if (track.growth_limit.has_value() && increase_per_track >= track.growth_limit.value()) { - track.growth_limit_frozen = true; - track.item_incurred_increase = track.growth_limit.value(); - extra_space -= track.growth_limit.value(); + if (!track.infinitely_growable && track.growth_limit.has_value()) { + auto maximum_increase = track.growth_limit.value() - track.base_size; + if (track.item_incurred_increase + increase >= maximum_increase) { + track.growth_limit_frozen = true; + increase = maximum_increase - track.item_incurred_increase; + } } + track.item_incurred_increase += increase; + extra_space -= increase; } }
c1c2e6f7d7a32f04603e5a0f6567c31e62910a43
2022-09-03 21:27:37
kleines Filmröllchen
pixelpaint: Introduce a vectorscope
false
Introduce a vectorscope
pixelpaint
diff --git a/Userland/Applications/PixelPaint/CMakeLists.txt b/Userland/Applications/PixelPaint/CMakeLists.txt index 48525211e7dd..7f75f18ed36a 100644 --- a/Userland/Applications/PixelPaint/CMakeLists.txt +++ b/Userland/Applications/PixelPaint/CMakeLists.txt @@ -72,6 +72,7 @@ set(SOURCES Tools/Tool.cpp Tools/WandSelectTool.cpp Tools/ZoomTool.cpp + VectorscopeWidget.cpp main.cpp ) diff --git a/Userland/Applications/PixelPaint/MainWidget.cpp b/Userland/Applications/PixelPaint/MainWidget.cpp index 00c0f9105140..2b75180022ae 100644 --- a/Userland/Applications/PixelPaint/MainWidget.cpp +++ b/Userland/Applications/PixelPaint/MainWidget.cpp @@ -46,6 +46,7 @@ MainWidget::MainWidget() m_palette_widget = *find_descendant_of_type_named<PixelPaint::PaletteWidget>("palette_widget"); m_histogram_widget = *find_descendant_of_type_named<PixelPaint::HistogramWidget>("histogram_widget"); + m_vectorscope_widget = *find_descendant_of_type_named<PixelPaint::VectorscopeWidget>("vectorscope_widget"); m_layer_list_widget = *find_descendant_of_type_named<PixelPaint::LayerListWidget>("layer_list_widget"); m_layer_list_widget->on_layer_select = [&](auto* layer) { auto* editor = current_image_editor(); @@ -74,6 +75,7 @@ MainWidget::MainWidget() m_tab_widget->remove_tab(image_editor); if (m_tab_widget->children().size() == 0) { m_histogram_widget->set_image(nullptr); + m_vectorscope_widget->set_image(nullptr); m_layer_list_widget->set_image(nullptr); m_layer_properties_widget->set_layer(nullptr); m_palette_widget->set_image_editor(nullptr); @@ -88,12 +90,14 @@ MainWidget::MainWidget() auto& image_editor = verify_cast<PixelPaint::ImageEditor>(widget); m_palette_widget->set_image_editor(&image_editor); m_histogram_widget->set_image(&image_editor.image()); + m_vectorscope_widget->set_image(&image_editor.image()); m_layer_list_widget->set_image(&image_editor.image()); m_layer_properties_widget->set_layer(image_editor.active_layer()); window()->set_modified(image_editor.is_modified()); image_editor.on_modified_change = [this](bool modified) { window()->set_modified(modified); m_histogram_widget->image_changed(); + m_vectorscope_widget->image_changed(); }; if (auto* active_tool = m_toolbox->active_tool()) image_editor.set_active_tool(active_tool); @@ -161,6 +165,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) editor.undo_stack().set_current_unmodified(); m_histogram_widget->set_image(image); + m_vectorscope_widget->set_image(image); m_layer_list_widget->set_image(image); m_layer_list_widget->set_selected_layer(bg_layer); } @@ -978,15 +983,18 @@ ImageEditor& MainWidget::create_new_editor(NonnullRefPtr<Image> image) if (image_rectangle.contains(mouse_position)) { m_statusbar->set_override_text(mouse_position.to_string()); m_histogram_widget->set_color_at_mouseposition(current_image_editor()->image().color_at(mouse_position)); + m_vectorscope_widget->set_color_at_mouseposition(current_image_editor()->image().color_at(mouse_position)); } else { m_statusbar->set_override_text({}); m_histogram_widget->set_color_at_mouseposition(Color::Transparent); + m_vectorscope_widget->set_color_at_mouseposition(Color::Transparent); } }; image_editor.on_leave = [&]() { m_statusbar->set_override_text({}); m_histogram_widget->set_color_at_mouseposition(Color::Transparent); + m_vectorscope_widget->set_color_at_mouseposition(Color::Transparent); }; image_editor.on_set_guide_visibility = [&](bool show_guides) { diff --git a/Userland/Applications/PixelPaint/MainWidget.h b/Userland/Applications/PixelPaint/MainWidget.h index 565ee065e5ad..ce1b06818b93 100644 --- a/Userland/Applications/PixelPaint/MainWidget.h +++ b/Userland/Applications/PixelPaint/MainWidget.h @@ -19,6 +19,7 @@ #include "ToolPropertiesWidget.h" #include "ToolboxWidget.h" #include "Tools/Tool.h" +#include "VectorscopeWidget.h" #include <LibGUI/Action.h> #include <LibGUI/ComboBox.h> #include <LibGUI/Forward.h> @@ -62,6 +63,7 @@ class MainWidget : public GUI::Widget { RefPtr<ToolboxWidget> m_toolbox; RefPtr<PaletteWidget> m_palette_widget; RefPtr<HistogramWidget> m_histogram_widget; + RefPtr<VectorscopeWidget> m_vectorscope_widget; RefPtr<LayerListWidget> m_layer_list_widget; RefPtr<LayerPropertiesWidget> m_layer_properties_widget; RefPtr<ToolPropertiesWidget> m_tool_properties_widget; diff --git a/Userland/Applications/PixelPaint/PixelPaintWindow.gml b/Userland/Applications/PixelPaint/PixelPaintWindow.gml index c4a641899d01..668a3e0a60e9 100644 --- a/Userland/Applications/PixelPaint/PixelPaintWindow.gml +++ b/Userland/Applications/PixelPaint/PixelPaintWindow.gml @@ -77,6 +77,19 @@ } } + @GUI::GroupBox { + title: "Vectorscope" + min_height: 80 + layout: @GUI::VerticalBoxLayout { + margins: [6] + } + + @PixelPaint::VectorscopeWidget { + name: "vectorscope_widget" + preferred_height: "fit" + } + } + @PixelPaint::ToolPropertiesWidget { name: "tool_properties_widget" max_height: 144 diff --git a/Userland/Applications/PixelPaint/VectorscopeWidget.cpp b/Userland/Applications/PixelPaint/VectorscopeWidget.cpp new file mode 100644 index 000000000000..58b7ce1f83e2 --- /dev/null +++ b/Userland/Applications/PixelPaint/VectorscopeWidget.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022, kleines Filmröllchen <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "VectorscopeWidget.h" +#include "Layer.h" +#include <AK/Math.h> +#include <AK/Types.h> +#include <LibGUI/Event.h> +#include <LibGUI/Painter.h> +#include <LibGUI/Widget.h> +#include <LibGfx/AntiAliasingPainter.h> +#include <LibGfx/Bitmap.h> +#include <LibGfx/Palette.h> +#include <LibGfx/SystemTheme.h> +#include <LibGfx/TextAlignment.h> +#include <LibGfx/TextElision.h> + +REGISTER_WIDGET(PixelPaint, VectorscopeWidget); + +namespace PixelPaint { + +void VectorscopeWidget::image_changed() +{ + (void)rebuild_vectorscope_data(); + rebuild_vectorscope_image(); + update(); +} + +ErrorOr<void> VectorscopeWidget::rebuild_vectorscope_data() +{ + if (!m_image) + return {}; + + m_vectorscope_data.fill({}); + VERIFY(AK::abs(m_vectorscope_data[0][0]) < 0.01f); + auto full_bitmap = TRY(m_image->try_compose_bitmap(Gfx::BitmapFormat::BGRA8888)); + + for (size_t x = 0; x < static_cast<size_t>(full_bitmap->width()); ++x) { + for (size_t y = 0; y < static_cast<size_t>(full_bitmap->height()); ++y) { + auto yuv = full_bitmap->get_pixel(x, y).to_yuv(); + auto u_index = u_v_to_index(yuv.u); + auto v_index = u_v_to_index(yuv.v); + m_vectorscope_data[u_index][v_index]++; + } + } + + auto maximum = full_bitmap->width() * full_bitmap->height() * pixel_percentage_for_max_brightness * pixel_percentage_for_max_brightness; + + for (size_t i = 0; i < m_vectorscope_data.size(); ++i) { + for (size_t j = 0; j < m_vectorscope_data[i].size(); ++j) { + m_vectorscope_data[i][j] = AK::sqrt(m_vectorscope_data[i][j]) / maximum; + } + } + + return {}; +} + +void VectorscopeWidget::rebuild_vectorscope_image() +{ + m_vectorscope_image = MUST(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, size())); + m_vectorscope_image->fill(Color::Transparent); + + Gfx::Painter base_painter(*m_vectorscope_image); + Gfx::AntiAliasingPainter painter(base_painter); + + auto const scope_size = min(height(), width()); + auto const min_scope_size = parent_widget()->min_height().as_int(); + auto const color_vector_scale = scope_size / static_cast<float>(min_scope_size); + auto const size_1x1 = Gfx::FloatSize { 2.5f, 2.5f } * static_cast<float>(color_vector_scale); + + base_painter.translate(width() / 2, height() / 2); + painter.translate(static_cast<float>(width()) / 2.0f, static_cast<float>(height()) / 2.0f); + for (size_t u_index = 0; u_index < u_v_steps; ++u_index) { + for (size_t v_index = 0; v_index < u_v_steps; ++v_index) { + auto const color_vector = ColorVector::from_indices(u_index, v_index); + auto const brightness = m_vectorscope_data[u_index][v_index]; + if (brightness < 0.0001f) + continue; + auto const pseudo_rect = Gfx::FloatRect::centered_at(color_vector.to_vector(scope_size) * 2.0f, size_1x1); + auto color = Color::from_yuv(0.6f, color_vector.u, color_vector.v); + color = color.saturated_to(1.0f - min(brightness, 1.0f)); + color.set_alpha(static_cast<u8>(min(AK::sqrt(brightness), alpha_range) * NumericLimits<u8>::max() / alpha_range)); + painter.fill_rect(pseudo_rect, color); + } + } +} + +void VectorscopeWidget::paint_event(GUI::PaintEvent& event) +{ + GUI::Painter base_painter(*this); + Gfx::AntiAliasingPainter painter(base_painter); + base_painter.add_clip_rect(event.rect()); + // From this point on we're working with 0,0 as the scope center to make things easier. + base_painter.translate(width() / 2, height() / 2); + painter.translate(static_cast<float>(width()) / 2.0f, static_cast<float>(height()) / 2.0f); + + auto const graticule_color = Color::White; + auto const scope_size = min(height(), width()); + auto const graticule_size = scope_size / 6; + auto const graticule_thickness = graticule_size / 12; + auto const entire_scope_rect = Gfx::FloatRect::centered_at({ 0, 0 }, { scope_size, scope_size }); + + painter.fill_ellipse(entire_scope_rect.to_rounded<int>().shrunken(graticule_thickness * 2, graticule_thickness * 2), Color::Black); + + // Main scope data + if (m_image) { + if (m_vectorscope_image->size() != this->size()) + rebuild_vectorscope_image(); + + base_painter.blit({ -width() / 2, -height() / 2 }, *m_vectorscope_image, m_vectorscope_image->rect()); + } + + // Graticule(s) + painter.draw_ellipse(entire_scope_rect.to_rounded<int>(), graticule_color, graticule_thickness); + + // FIXME: Translation calls to the painters don't appear to work correctly, and I figured out a combination of calls through trial and error that do what I want, but I don't know how they do that. + // Translation does work correctly with things like rectangle and text drawing, so it's very strange. + painter.translate(-static_cast<float>(width()) / 2.0f, -static_cast<float>(height()) / 2.0f); + // We intentionally draw the skin tone line much further than the actual color we're using for it. + painter.draw_line({ 0, 0 }, skin_tone_color.to_vector(scope_size) * 2.0, graticule_color); + painter.translate(-static_cast<float>(width()) / 2.0f, -static_cast<float>(height()) / 2.0f); + + for (auto const& primary_color : primary_colors) { + // FIXME: Only draw the rectangle corners for a more classical oscilloscope look (& less obscuring of color data) + auto graticule_rect = Gfx::FloatRect::centered_at(primary_color.to_vector(scope_size), { graticule_size, graticule_size }).to_rounded<int>(); + base_painter.draw_rect_with_thickness(graticule_rect, graticule_color, graticule_thickness); + auto text_rect = graticule_rect.translated(graticule_size / 2, graticule_size / 2); + base_painter.draw_text(text_rect, StringView { &primary_color.symbol, 1 }, Gfx::TextAlignment::TopLeft, graticule_color); + } + + if (m_color_at_mouseposition != Color::Transparent) { + auto color_vector = ColorVector { m_color_at_mouseposition }; + painter.draw_ellipse(Gfx::FloatRect::centered_at(color_vector.to_vector(scope_size) * 2.0, { graticule_size, graticule_size }).to_rounded<int>(), graticule_color, graticule_thickness); + } +} + +} diff --git a/Userland/Applications/PixelPaint/VectorscopeWidget.h b/Userland/Applications/PixelPaint/VectorscopeWidget.h new file mode 100644 index 000000000000..03c9a7e37ca7 --- /dev/null +++ b/Userland/Applications/PixelPaint/VectorscopeWidget.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2022, kleines Filmröllchen <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include "Image.h" +#include "ScopeWidget.h" +#include <AK/Array.h> + +namespace PixelPaint { + +// Gfx::Color can produce 64-bit floating-point HSV. +// However, as it internally only uses 8 bits for each color channel, the hue can never have a higher usable resolution than 256 steps. +static constexpr size_t const u_v_steps = 160; + +// Convert to and from U or V (-1 to +1) and an index suitable for the vectorscope table. +constexpr size_t u_v_to_index(float u_v) +{ + float normalized_u_v = (u_v + 1.0f) / 2.0f; + return static_cast<size_t>(floorf(normalized_u_v * u_v_steps)) % u_v_steps; +} +constexpr float u_v_from_index(size_t index) +{ + float normalized_u_v = static_cast<float>(index) / u_v_steps; + return normalized_u_v * 2.0f - 1.0f; +} + +struct PrimaryColorVector; + +struct ColorVector { + constexpr ColorVector(float u, float v) + : u(u) + , v(v) + { + } + + constexpr explicit ColorVector(Color color) + : ColorVector(color.to_yuv().u, color.to_yuv().v) + { + } + + static constexpr ColorVector from_indices(size_t u_index, size_t v_index) + { + return ColorVector(u_v_from_index(u_index), u_v_from_index(v_index)); + } + + constexpr Gfx::FloatPoint to_vector(float scope_size) const + { + auto x = u * scope_size / 2.0f; + // Computer graphics y increases downwards, but mathematical y increases upwards. + auto y = -v * scope_size / 2.0f; + return { x, y }; + } + + constexpr operator PrimaryColorVector() const; + + float u; + float v; +}; + +struct PrimaryColorVector : public ColorVector { + constexpr PrimaryColorVector(Color::NamedColor named_color, char symbol) + : ColorVector(Color { named_color }) + , symbol(symbol) + { + } + + constexpr PrimaryColorVector(Color color, char symbol) + : ColorVector(color.to_yuv().u, color.to_yuv().v) + , symbol(symbol) + { + } + + constexpr PrimaryColorVector(float u, float v, char symbol) + : ColorVector(u, v) + , symbol(symbol) + { + } + + char symbol; +}; + +constexpr ColorVector::operator PrimaryColorVector() const +{ + return PrimaryColorVector { u, v, 'X' }; +} + +// Color vectors that are found in this percentage of pixels and above are displayed with maximum brightness in the scope. +static constexpr float const pixel_percentage_for_max_brightness = 0.01f; +// Which normalized brightness value (and above) gets to be rendered at 100% opacity. +static constexpr float const alpha_range = 2.5f; +// Skin tone line. This was determined manually with a couple of common hex skin tone colors. +static constexpr PrimaryColorVector const skin_tone_color = { Color::from_hsv(18.0, 1.0, 1.0), 'S' }; +// Used for primary color box graticules. +static constexpr Array<PrimaryColorVector, 6> const primary_colors = { { + { Color::Red, 'R' }, + { Color::Magenta, 'M' }, + { Color::Blue, 'B' }, + { Color::Cyan, 'C' }, + { Color::Green, 'G' }, + { Color::Yellow, 'Y' }, +} }; + +// Vectorscopes are a standard tool in professional video/film color grading. +// The Vectorscope shows image colors along the I and Q axis (from YIQ color space), which, to oversimplify, means that you get a weirdly shifted hue circle with the radius being the saturation. +// The brightness for each point in the scope is determined by the number of "color vectors" at that point. +// FIXME: We would want a lot of the scope settings to be user-adjustable. For example: scale, color/bw scope, graticule brightness +class VectorscopeWidget final + : public ScopeWidget { + C_OBJECT(VectorscopeWidget); + +public: + virtual ~VectorscopeWidget() override = default; + + virtual void image_changed() override; + +private: + virtual void paint_event(GUI::PaintEvent&) override; + + ErrorOr<void> rebuild_vectorscope_data(); + void rebuild_vectorscope_image(); + + // First index is u, second index is v. The value is y. + Array<Array<float, u_v_steps + 1>, u_v_steps + 1> m_vectorscope_data; + RefPtr<Gfx::Bitmap> m_vectorscope_image; +}; + +}
a10ad24c760bfe713f1493e49dff7da16d14bf39
2021-05-31 21:56:11
sin-ack
libgfx: Make JPGLoader iterate components deterministically
false
Make JPGLoader iterate components deterministically
libgfx
diff --git a/Userland/Libraries/LibGfx/JPGLoader.cpp b/Userland/Libraries/LibGfx/JPGLoader.cpp index 1c2aefc209cb..e5591ad43d7d 100644 --- a/Userland/Libraries/LibGfx/JPGLoader.cpp +++ b/Userland/Libraries/LibGfx/JPGLoader.cpp @@ -122,7 +122,6 @@ struct MacroblockMeta { }; struct ComponentSpec { - u8 serial_id { 255 }; // In the interval [0, 3). u8 id { 0 }; u8 hsample_factor { 1 }; // Horizontal sampling factor. u8 vsample_factor { 1 }; // Vertical sampling factor. @@ -187,7 +186,7 @@ struct JPGLoadingContext { u8 hsample_factor { 0 }; u8 vsample_factor { 0 }; u8 component_count { 0 }; - HashMap<u8, ComponentSpec> components; + Vector<ComponentSpec, 3> components; RefPtr<Gfx::Bitmap> bitmap; u16 dc_reset_interval { 0 }; HashMap<u8, HuffmanTableSpec> dc_tables; @@ -251,6 +250,18 @@ static Optional<u8> get_next_symbol(HuffmanStreamState& hstream, const HuffmanTa return {}; } +static inline i32* get_component(Macroblock& block, unsigned component) +{ + switch (component) { + case 0: + return block.y; + case 1: + return block.cb; + default: + return block.cr; + } +} + /** * Build the macroblocks possible by reading single (MCU) subsampled pair of CbCr. * Depending on the sampling factors, we may not see triples of y, cb, cr in that @@ -268,8 +279,8 @@ static Optional<u8> get_next_symbol(HuffmanStreamState& hstream, const HuffmanTa */ static bool build_macroblocks(JPGLoadingContext& context, Vector<Macroblock>& macroblocks, u32 hcursor, u32 vcursor) { - for (auto it = context.components.begin(); it != context.components.end(); ++it) { - ComponentSpec& component = it->value; + for (unsigned component_i = 0; component_i < context.component_count; component_i++) { + auto& component = context.components[component_i]; if (component.dc_destination_id >= context.dc_tables.size()) return false; @@ -306,8 +317,8 @@ static bool build_macroblocks(JPGLoadingContext& context, Vector<Macroblock>& ma if (dc_length != 0 && dc_diff < (1 << (dc_length - 1))) dc_diff -= (1 << dc_length) - 1; - i32* select_component = component.serial_id == 0 ? block.y : (component.serial_id == 1 ? block.cb : block.cr); - auto& previous_dc = context.previous_dc_values[component.serial_id]; + auto select_component = get_component(block, component_i); + auto& previous_dc = context.previous_dc_values[component_i]; select_component[0] = previous_dc += dc_diff; // Compute the AC coefficients. @@ -502,21 +513,14 @@ static bool read_start_of_scan(InputMemoryStream& stream, JPGLoadingContext& con } for (int i = 0; i < component_count; i++) { - ComponentSpec* component = nullptr; u8 component_id = 0; stream >> component_id; if (stream.handle_any_error()) return false; - auto it = context.components.find(component_id); - if (it != context.components.end()) { - component = &it->value; - if (i != component->serial_id) { - dbgln("JPEG decode failed (i != component->serial_id)"); - return false; - } - } else { - dbgln_if(JPG_DEBUG, "{}: Unsupported component id: {}!", stream.offset(), component_id); + auto& component = context.components[i]; + if (component.id != component_id) { + dbgln("JPEG decode failed (component.id != component_id)"); return false; } @@ -525,21 +529,21 @@ static bool read_start_of_scan(InputMemoryStream& stream, JPGLoadingContext& con if (stream.handle_any_error()) return false; - component->dc_destination_id = table_ids >> 4; - component->ac_destination_id = table_ids & 0x0F; + component.dc_destination_id = table_ids >> 4; + component.ac_destination_id = table_ids & 0x0F; if (context.dc_tables.size() != context.ac_tables.size()) { dbgln_if(JPG_DEBUG, "{}: DC & AC table count mismatch!", stream.offset()); return false; } - if (!context.dc_tables.contains(component->dc_destination_id)) { - dbgln_if(JPG_DEBUG, "DC table (id: {}) does not exist!", component->dc_destination_id); + if (!context.dc_tables.contains(component.dc_destination_id)) { + dbgln_if(JPG_DEBUG, "DC table (id: {}) does not exist!", component.dc_destination_id); return false; } - if (!context.ac_tables.contains(component->ac_destination_id)) { - dbgln_if(JPG_DEBUG, "AC table (id: {}) does not exist!", component->ac_destination_id); + if (!context.ac_tables.contains(component.ac_destination_id)) { + dbgln_if(JPG_DEBUG, "AC table (id: {}) does not exist!", component.ac_destination_id); return false; } } @@ -731,7 +735,6 @@ static bool read_start_of_frame(InputMemoryStream& stream, JPGLoadingContext& co for (u8 i = 0; i < context.component_count; i++) { ComponentSpec component; - component.serial_id = i; stream >> component.id; if (stream.handle_any_error()) @@ -744,7 +747,7 @@ static bool read_start_of_frame(InputMemoryStream& stream, JPGLoadingContext& co component.hsample_factor = subsample_factors >> 4; component.vsample_factor = subsample_factors & 0x0F; - if (component.serial_id == 0) { + if (i == 0) { // By convention, downsampling is applied only on chroma components. So we should // hope to see the maximum sampling factor in the luma component. if (!validate_luma_and_modify_context(component, context)) { @@ -772,7 +775,7 @@ static bool read_start_of_frame(InputMemoryStream& stream, JPGLoadingContext& co return false; } - context.components.set(component.id, component); + context.components.append(move(component)); } return true; @@ -842,14 +845,14 @@ static void dequantize(JPGLoadingContext& context, Vector<Macroblock>& macrobloc { for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) { for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) { - for (auto it = context.components.begin(); it != context.components.end(); ++it) { - auto& component = it->value; + for (u32 i = 0; i < context.component_count; i++) { + auto& component = context.components[i]; const u32* table = component.qtable_id == 0 ? context.luma_table : context.chroma_table; for (u32 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) { for (u32 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) { u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor); Macroblock& block = macroblocks[mb_index]; - int* block_component = component.serial_id == 0 ? block.y : (component.serial_id == 1 ? block.cb : block.cr); + int* block_component = get_component(block, i); for (u32 k = 0; k < 64; k++) block_component[k] *= table[k]; } @@ -878,13 +881,13 @@ static void inverse_dct(const JPGLoadingContext& context, Vector<Macroblock>& ma for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) { for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) { - for (auto it = context.components.begin(); it != context.components.end(); ++it) { - auto& component = it->value; + for (u32 component_i = 0; component_i < context.component_count; component_i++) { + auto& component = context.components[component_i]; for (u8 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) { for (u8 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) { u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor); Macroblock& block = macroblocks[mb_index]; - i32* block_component = component.serial_id == 0 ? block.y : (component.serial_id == 1 ? block.cb : block.cr); + i32* block_component = get_component(block, component_i); for (u32 k = 0; k < 8; ++k) { const float g0 = block_component[0 * 8 + k] * s0; const float g1 = block_component[4 * 8 + k] * s4;
1322a7e91794893755ae5a3510241e74d45720c5
2024-10-03 04:07:19
Andrew Kaster
libgfx: Use more Span methods in BitmapSequence instead of memcpy
false
Use more Span methods in BitmapSequence instead of memcpy
libgfx
diff --git a/Userland/Libraries/LibGfx/BitmapSequence.cpp b/Userland/Libraries/LibGfx/BitmapSequence.cpp index ce0593ac1fd2..4eb65ce5482b 100644 --- a/Userland/Libraries/LibGfx/BitmapSequence.cpp +++ b/Userland/Libraries/LibGfx/BitmapSequence.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <AK/Checked.h> #include <AK/Forward.h> #include <LibCore/AnonymousBuffer.h> #include <LibGfx/Bitmap.h> @@ -11,7 +12,6 @@ #include <LibGfx/Size.h> #include <LibIPC/Decoder.h> #include <LibIPC/Encoder.h> -#include <LibIPC/File.h> namespace Gfx { @@ -80,12 +80,13 @@ ErrorOr<void> encode(Encoder& encoder, Gfx::BitmapSequence const& bitmap_sequenc // collate all of the bitmap data into one contiguous buffer auto collated_buffer = TRY(Core::AnonymousBuffer::create_with_size(total_buffer_size)); - auto* write_pointer = collated_buffer.data<u8>(); + Bytes buffer_bytes = { collated_buffer.data<u8>(), collated_buffer.size() }; + size_t write_offset = 0; for (auto const& bitmap_option : bitmaps) { if (bitmap_option.has_value()) { auto const& bitmap = bitmap_option.value(); - memcpy(write_pointer, bitmap->scanline(0), bitmap->size_in_bytes()); - write_pointer += bitmap->size_in_bytes(); + buffer_bytes.overwrite(write_offset, bitmap->scanline(0), bitmap->size_in_bytes()); + write_offset += bitmap->size_in_bytes(); } } @@ -97,38 +98,43 @@ ErrorOr<void> encode(Encoder& encoder, Gfx::BitmapSequence const& bitmap_sequenc template<> ErrorOr<Gfx::BitmapSequence> decode(Decoder& decoder) { - auto metadata = TRY(decoder.decode<Vector<Optional<Gfx::BitmapMetadata>>>()); + auto metadata_list = TRY(decoder.decode<Vector<Optional<Gfx::BitmapMetadata>>>()); auto collated_buffer = TRY(decoder.decode<Core::AnonymousBuffer>()); - Vector<Optional<NonnullRefPtr<Gfx::Bitmap>>> bitmaps; - bitmaps.ensure_capacity(metadata.size()); + Gfx::BitmapSequence result = {}; + auto& bitmaps = result.bitmaps; + TRY(bitmaps.try_ensure_capacity(metadata_list.size())); ReadonlyBytes bytes = ReadonlyBytes(collated_buffer.data<u8>(), collated_buffer.size()); size_t bytes_read = 0; // sequentially read each valid bitmap's data from the collated buffer - for (auto const& metadata_option : metadata) { + for (auto const& metadata_option : metadata_list) { Optional<NonnullRefPtr<Gfx::Bitmap>> bitmap = {}; if (metadata_option.has_value()) { auto metadata = metadata_option.value(); size_t size_in_bytes = metadata.size_in_bytes; - if (bytes_read + size_in_bytes > bytes.size()) + Checked<size_t> size_check = bytes_read; + size_check += size_in_bytes; + if (size_check.has_overflow() || size_check.value() > bytes.size()) return Error::from_string_literal("IPC: Invalid Gfx::BitmapSequence buffer data"); auto buffer = TRY(Core::AnonymousBuffer::create_with_size(size_in_bytes)); + auto buffer_bytes = Bytes { buffer.data<u8>(), buffer.size() }; + + bytes.slice(bytes_read, size_in_bytes).copy_to(buffer_bytes); - memcpy(buffer.data<u8>(), bytes.slice(bytes_read, size_in_bytes).data(), size_in_bytes); bytes_read += size_in_bytes; bitmap = TRY(Gfx::Bitmap::create_with_anonymous_buffer(metadata.format, metadata.alpha_type, move(buffer), metadata.size)); } - bitmaps.append(bitmap); + bitmaps.append(move(bitmap)); } - return Gfx::BitmapSequence { bitmaps }; + return result; } }
42f0b2522b6e24e0269265597cebfda9f0b7b329
2020-04-24 22:35:02
Andreas Kling
libgui: Introduce widget content margins + improve splitters
false
Introduce widget content margins + improve splitters
libgui
diff --git a/Libraries/LibGUI/Frame.cpp b/Libraries/LibGUI/Frame.cpp index e2cb7c23d028..9b82c5b7f9af 100644 --- a/Libraries/LibGUI/Frame.cpp +++ b/Libraries/LibGUI/Frame.cpp @@ -42,6 +42,14 @@ Frame::~Frame() { } +void Frame::set_frame_thickness(int thickness) +{ + if (m_thickness == thickness) + return; + m_thickness = thickness; + set_content_margins({ thickness, thickness, thickness, thickness }); +} + void Frame::paint_event(PaintEvent& event) { if (m_shape == Gfx::FrameShape::NoFrame) diff --git a/Libraries/LibGUI/Frame.h b/Libraries/LibGUI/Frame.h index e31bf1305203..10b48e1caed5 100644 --- a/Libraries/LibGUI/Frame.h +++ b/Libraries/LibGUI/Frame.h @@ -37,7 +37,7 @@ class Frame : public Widget { virtual ~Frame() override; int frame_thickness() const { return m_thickness; } - void set_frame_thickness(int thickness) { m_thickness = thickness; } + void set_frame_thickness(int thickness); Gfx::FrameShadow frame_shadow() const { return m_shadow; } void set_frame_shadow(Gfx::FrameShadow shadow) { m_shadow = shadow; } diff --git a/Libraries/LibGUI/MultiView.cpp b/Libraries/LibGUI/MultiView.cpp index 9b542eb67f2c..d80536804b31 100644 --- a/Libraries/LibGUI/MultiView.cpp +++ b/Libraries/LibGUI/MultiView.cpp @@ -39,6 +39,7 @@ namespace GUI { MultiView::MultiView() { set_active_widget(nullptr); + set_content_margins({ 2, 2, 2, 2 }); m_item_view = add<ItemView>(); m_table_view = add<TableView>(); diff --git a/Libraries/LibGUI/Splitter.cpp b/Libraries/LibGUI/Splitter.cpp index b58113f09b43..8b1a86bf8466 100644 --- a/Libraries/LibGUI/Splitter.cpp +++ b/Libraries/LibGUI/Splitter.cpp @@ -76,17 +76,23 @@ void Splitter::leave_event(Core::Event&) bool Splitter::get_resize_candidates_at(const Gfx::Point& position, Widget*& first, Widget*& second) { int x_or_y = position.primary_offset_for_orientation(m_orientation); - int fudge = layout()->spacing(); - for_each_child_widget([&](auto& child) { - int child_start = child.relative_rect().first_edge_for_orientation(m_orientation); - int child_end = child.relative_rect().last_edge_for_orientation(m_orientation); - if (x_or_y > child_end && (x_or_y - fudge) <= child_end) - first = &child; - if (x_or_y < child_start && (x_or_y + fudge) >= child_start) - second = &child; - return IterationDecision::Continue; - }); - return first && second; + + auto child_widgets = this->child_widgets(); + if (child_widgets.size() < 2) + return false; + + for (size_t i = 0; i < child_widgets.size() - 1; ++i) { + auto* first_candidate = child_widgets[i]; + auto* second_candidate = child_widgets[i + 1]; + + if (x_or_y > first_candidate->content_rect().last_edge_for_orientation(m_orientation) + && x_or_y <= second_candidate->content_rect().first_edge_for_orientation(m_orientation)) { + first = first_candidate; + second = second_candidate; + return true; + } + } + return false; } void Splitter::mousedown_event(MouseEvent& event) @@ -109,13 +115,14 @@ void Splitter::mousedown_event(MouseEvent& event) void Splitter::recompute_grabbable_rect(const Widget& first, const Widget& second) { - auto first_edge = first.relative_rect().primary_offset_for_orientation(m_orientation) + first.relative_rect().primary_size_for_orientation(m_orientation); - auto second_edge = second.relative_rect().primary_offset_for_orientation(m_orientation); + auto first_edge = first.content_rect().primary_offset_for_orientation(m_orientation) + first.content_rect().primary_size_for_orientation(m_orientation); + auto second_edge = second.content_rect().primary_offset_for_orientation(m_orientation); Gfx::Rect rect; rect.set_primary_offset_for_orientation(m_orientation, first_edge); rect.set_primary_size_for_orientation(m_orientation, second_edge - first_edge); - rect.set_secondary_offset_for_orientation(m_orientation, first.relative_rect().secondary_offset_for_orientation(m_orientation)); - rect.set_secondary_size_for_orientation(m_orientation, first.relative_rect().secondary_size_for_orientation(m_orientation)); + rect.set_secondary_offset_for_orientation(m_orientation, first.content_rect().secondary_offset_for_orientation(m_orientation)); + rect.set_secondary_size_for_orientation(m_orientation, first.content_rect().secondary_size_for_orientation(m_orientation)); + if (m_grabbable_rect != rect) { m_grabbable_rect = rect; update(); diff --git a/Libraries/LibGUI/Widget.cpp b/Libraries/LibGUI/Widget.cpp index 00b107a5f4dd..ceee7e37f30e 100644 --- a/Libraries/LibGUI/Widget.cpp +++ b/Libraries/LibGUI/Widget.cpp @@ -472,7 +472,7 @@ Widget* Widget::child_at(const Gfx::Point& point) const auto& child = Core::to<Widget>(children()[i]); if (!child.is_visible()) continue; - if (child.relative_rect().contains(point)) + if (child.content_rect().contains(point)) return const_cast<Widget*>(&child); } return nullptr; @@ -811,4 +811,21 @@ void Widget::did_end_inspection() update(); } +void Widget::set_content_margins(const Margins& margins) +{ + if (m_content_margins == margins) + return; + m_content_margins = margins; + invalidate_layout(); +} + +Gfx::Rect Widget::content_rect() const +{ + auto rect = relative_rect(); + rect.move_by(m_content_margins.left(), m_content_margins.top()); + rect.set_width(rect.width() - (m_content_margins.left() + m_content_margins.right())); + rect.set_height(rect.height() - (m_content_margins.top() + m_content_margins.bottom())); + return rect; +} + } diff --git a/Libraries/LibGUI/Widget.h b/Libraries/LibGUI/Widget.h index a90f28c85080..80235582719d 100644 --- a/Libraries/LibGUI/Widget.h +++ b/Libraries/LibGUI/Widget.h @@ -30,6 +30,7 @@ #include <LibCore/Object.h> #include <LibGUI/Event.h> #include <LibGUI/Forward.h> +#include <LibGUI/Margins.h> #include <LibGfx/Color.h> #include <LibGfx/Forward.h> #include <LibGfx/Orientation.h> @@ -266,6 +267,11 @@ class Widget : public Core::Object { Gfx::Palette palette() const; void set_palette(const Gfx::Palette&); + const Margins& content_margins() const { return m_content_margins; } + void set_content_margins(const Margins&); + + Gfx::Rect content_rect() const; + protected: Widget(); @@ -324,6 +330,7 @@ class Widget : public Core::Object { SizePolicy m_horizontal_size_policy { SizePolicy::Fill }; SizePolicy m_vertical_size_policy { SizePolicy::Fill }; Gfx::Size m_preferred_size; + Margins m_content_margins; bool m_fill_with_background_color { false }; bool m_visible { true };
9474e0cd94b4d5885d2ae084690ff09bf2ccd6dd
2023-05-20 03:01:20
Ben Wiederhake
libdebug: Prefer File::read_until_eof over DeprecatedFile
false
Prefer File::read_until_eof over DeprecatedFile
libdebug
diff --git a/Userland/Libraries/LibDebug/DebugSession.cpp b/Userland/Libraries/LibDebug/DebugSession.cpp index cddfe4aed583..0a04620c5e68 100644 --- a/Userland/Libraries/LibDebug/DebugSession.cpp +++ b/Userland/Libraries/LibDebug/DebugSession.cpp @@ -10,7 +10,6 @@ #include <AK/LexicalPath.h> #include <AK/Optional.h> #include <AK/Platform.h> -#include <LibCore/DeprecatedFile.h> #include <LibFileSystem/FileSystem.h> #include <LibRegex/Regex.h> #include <stdlib.h> @@ -126,7 +125,11 @@ OwnPtr<DebugSession> DebugSession::exec_and_attach(DeprecatedString const& comma } // At this point, libraries should have been loaded - debug_session->update_loaded_libs(); + auto update_or_error = debug_session->update_loaded_libs(); + if (update_or_error.is_error()) { + dbgln("update failed: {}", update_or_error.error()); + return {}; + } return debug_session; } @@ -146,7 +149,11 @@ OwnPtr<DebugSession> DebugSession::attach(pid_t pid, DeprecatedString source_roo auto debug_session = adopt_own(*new DebugSession(pid, source_root, move(on_initialization_progress))); // At this point, libraries should have been loaded - debug_session->update_loaded_libs(); + auto update_or_error = debug_session->update_loaded_libs(); + if (update_or_error.is_error()) { + dbgln("update failed: {}", update_or_error.error()); + return {}; + } return debug_session; } @@ -444,14 +451,13 @@ Optional<DebugSession::InsertBreakpointAtSourcePositionResult> DebugSession::ins return InsertBreakpointAtSourcePositionResult { lib->name, address_and_source_position.value().file, address_and_source_position.value().line, address }; } -void DebugSession::update_loaded_libs() +ErrorOr<void> DebugSession::update_loaded_libs() { - auto file = Core::DeprecatedFile::construct(DeprecatedString::formatted("/proc/{}/vm", m_debuggee_pid)); - bool rc = file->open(Core::OpenMode::ReadOnly); - VERIFY(rc); + auto file_name = TRY(String::formatted("/proc/{}/vm", m_debuggee_pid)); + auto file = TRY(Core::File::open(file_name, Core::File::OpenMode::Read)); - auto file_contents = file->read_all(); - auto json = JsonValue::from_string(file_contents).release_value_but_fixme_should_propagate_errors(); + auto file_contents = TRY(file->read_until_eof()); + auto json = TRY(JsonValue::from_string(file_contents)); auto const& vm_entries = json.as_array(); Regex<PosixExtended> segment_name_re("(.+): "); @@ -509,6 +515,8 @@ void DebugSession::update_loaded_libs() return IterationDecision::Continue; }); + + return {}; } void DebugSession::stop_debuggee() diff --git a/Userland/Libraries/LibDebug/DebugSession.h b/Userland/Libraries/LibDebug/DebugSession.h index 70b7ce43d379..c4f18ff1f27e 100644 --- a/Userland/Libraries/LibDebug/DebugSession.h +++ b/Userland/Libraries/LibDebug/DebugSession.h @@ -137,7 +137,7 @@ class DebugSession : public ProcessInspector { // x86 breakpoint instruction "int3" static constexpr u8 BREAKPOINT_INSTRUCTION = 0xcc; - void update_loaded_libs(); + ErrorOr<void> update_loaded_libs(); int m_debuggee_pid { -1 }; DeprecatedString m_source_root;
0af2795662f1640dbda80500a4c9f7200af01a15
2020-10-20 21:38:37
Andreas Kling
libweb: Tear down layout trees properly
false
Tear down layout trees properly
libweb
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp index 90526b6932d9..edcde7700e5e 100644 --- a/Libraries/LibWeb/DOM/Document.cpp +++ b/Libraries/LibWeb/DOM/Document.cpp @@ -206,10 +206,35 @@ void Document::detach_from_frame(Badge<Frame>, Frame& frame) node.document_will_detach_from_frame(frame); return IterationDecision::Continue; }); - m_layout_root = nullptr; + + tear_down_layout_tree(); m_frame = nullptr; } +void Document::tear_down_layout_tree() +{ + if (!m_layout_root) + return; + + // Gather up all the layout nodes in a vector and detach them from parents + // while the vector keeps them alive. + + NonnullRefPtrVector<LayoutNode> layout_nodes; + + for_each_in_subtree([&](auto& node) { + if (node.layout_node()) + layout_nodes.append(*node.layout_node()); + return IterationDecision::Continue; + }); + + for (auto& layout_node : layout_nodes) { + if (layout_node.parent()) + layout_node.parent()->remove_child(layout_node); + } + + m_layout_root = nullptr; +} + Color Document::background_color(const Palette& palette) const { auto default_color = palette.base(); @@ -256,7 +281,7 @@ URL Document::complete_url(const String& string) const void Document::invalidate_layout() { - m_layout_root = nullptr; + tear_down_layout_tree(); } void Document::force_layout() diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h index 0784e99ec5d7..848989cd483f 100644 --- a/Libraries/LibWeb/DOM/Document.h +++ b/Libraries/LibWeb/DOM/Document.h @@ -198,6 +198,8 @@ class Document private: virtual RefPtr<LayoutNode> create_layout_node(const CSS::StyleProperties* parent_style) override; + void tear_down_layout_tree(); + unsigned m_referencing_node_count { 0 }; OwnPtr<CSS::StyleResolver> m_style_resolver;
df34f7b90b0dc8a3319d67d2a75551cba225aaf1
2022-01-17 04:01:01
Andreas Kling
kernel: Use an IntrusiveRedBlackTree for kernel regions
false
Use an IntrusiveRedBlackTree for kernel regions
kernel
diff --git a/Kernel/Memory/MemoryManager.cpp b/Kernel/Memory/MemoryManager.cpp index 75ad1c98007b..d914c723d587 100644 --- a/Kernel/Memory/MemoryManager.cpp +++ b/Kernel/Memory/MemoryManager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2021, Andreas Kling <[email protected]> + * Copyright (c) 2018-2022, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -645,10 +645,10 @@ UNMAP_AFTER_INIT void MemoryManager::initialize(u32 cpu) Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress vaddr) { SpinlockLocker lock(s_mm_lock); - auto* region_ptr = MM.m_kernel_regions.find_largest_not_above(vaddr.get()); - if (!region_ptr) + auto* region = MM.m_kernel_regions.find_largest_not_above(vaddr.get()); + if (!region || !region->contains(vaddr)) return nullptr; - return (*region_ptr)->contains(vaddr) ? *region_ptr : nullptr; + return region; } Region* MemoryManager::find_user_region_from_vaddr_no_lock(AddressSpace& space, VirtualAddress vaddr) @@ -1111,7 +1111,7 @@ void MemoryManager::register_kernel_region(Region& region) { VERIFY(region.is_kernel()); SpinlockLocker lock(s_mm_lock); - m_kernel_regions.insert(region.vaddr().get(), &region); + m_kernel_regions.insert(region.vaddr().get(), region); } void MemoryManager::unregister_kernel_region(Region& region) @@ -1132,8 +1132,7 @@ void MemoryManager::dump_kernel_regions() dbgln("BEGIN{} END{} SIZE{} ACCESS NAME", addr_padding, addr_padding, addr_padding); SpinlockLocker lock(s_mm_lock); - for (auto const* region_ptr : m_kernel_regions) { - auto const& region = *region_ptr; + for (auto const& region : m_kernel_regions) { dbgln("{:p} -- {:p} {:p} {:c}{:c}{:c}{:c}{:c}{:c} {}", region.vaddr().get(), region.vaddr().offset(region.size() - 1).get(), diff --git a/Kernel/Memory/MemoryManager.h b/Kernel/Memory/MemoryManager.h index 4a5e5e5137fe..693709a4ad34 100644 --- a/Kernel/Memory/MemoryManager.h +++ b/Kernel/Memory/MemoryManager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2018-2022, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -8,6 +8,7 @@ #include <AK/Concepts.h> #include <AK/HashTable.h> +#include <AK/IntrusiveRedBlackTree.h> #include <AK/NonnullOwnPtrVector.h> #include <AK/NonnullRefPtrVector.h> #include <Kernel/Forward.h> @@ -293,7 +294,7 @@ class MemoryManager { PhysicalPageEntry* m_physical_page_entries { nullptr }; size_t m_physical_page_entries_count { 0 }; - RedBlackTree<FlatPtr, Region*> m_kernel_regions; + IntrusiveRedBlackTree<&Region::m_tree_node> m_kernel_regions; Vector<UsedMemoryRange> m_used_memory_ranges; Vector<PhysicalMemoryRange> m_physical_memory_ranges; diff --git a/Kernel/Memory/Region.h b/Kernel/Memory/Region.h index b66300c241a1..3c447296e727 100644 --- a/Kernel/Memory/Region.h +++ b/Kernel/Memory/Region.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2018-2022, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -8,6 +8,7 @@ #include <AK/EnumBits.h> #include <AK/IntrusiveList.h> +#include <AK/IntrusiveRedBlackTree.h> #include <AK/Weakable.h> #include <Kernel/Forward.h> #include <Kernel/KString.h> @@ -219,11 +220,11 @@ class Region final bool m_stack : 1 { false }; bool m_mmap : 1 { false }; bool m_syscall_region : 1 { false }; - IntrusiveListNode<Region> m_memory_manager_list_node; + + IntrusiveRedBlackTreeNode<FlatPtr, Region, RawPtr<Region>> m_tree_node; IntrusiveListNode<Region> m_vmobject_list_node; public: - using ListInMemoryManager = IntrusiveList<&Region::m_memory_manager_list_node>; using ListInVMObject = IntrusiveList<&Region::m_vmobject_list_node>; };
e3d5a11d841bb817677c9daa608d0c4a0a8a25f8
2022-02-23 05:18:59
Jelle Raaijmakers
ports: Enable `monkey4` engine for ScummVM
false
Enable `monkey4` engine for ScummVM
ports
diff --git a/Ports/scummvm/package.sh b/Ports/scummvm/package.sh index 42acc0dc3a30..fe2856015a82 100755 --- a/Ports/scummvm/package.sh +++ b/Ports/scummvm/package.sh @@ -4,9 +4,10 @@ useconfigure="true" version="2.5.1" files="https://downloads.scummvm.org/frs/scummvm/${version}/scummvm-${version}.tar.xz scummvm-${version}.tar.xz 9fd8db38e4456144bf8c34dacdf7f204e75f18e8e448ec01ce08ce826a035f01" auth_type=sha256 -depends=("freetype" "libiconv" "libjpeg" "libpng" "libtheora" "SDL2") +depends=("freetype" "libiconv" "libjpeg" "libmad" "libmpeg2" "libpng" "libtheora" "SDL2") configopts=( "--enable-c++11" + "--enable-engine=monkey4" "--enable-optimizations" "--with-sdl-prefix=${SERENITY_INSTALL_ROOT}/usr/local" )
433725fef20e47ab5642acd6fc211e349e983730
2021-09-18 03:12:38
Ali Mohammad Pur
libgfx: Implement cubic bezier curves by splitting them to subcurves
false
Implement cubic bezier curves by splitting them to subcurves
libgfx
diff --git a/Userland/Libraries/LibGfx/AntiAliasingPainter.cpp b/Userland/Libraries/LibGfx/AntiAliasingPainter.cpp index 8d95a50c6470..30dee5d4134d 100644 --- a/Userland/Libraries/LibGfx/AntiAliasingPainter.cpp +++ b/Userland/Libraries/LibGfx/AntiAliasingPainter.cpp @@ -132,6 +132,14 @@ void Gfx::AntiAliasingPainter::stroke_path(Path const& path, Color color, float cursor = segment.point(); break; } + case Segment::Type::CubicBezierCurveTo: { + auto& curve = static_cast<CubicBezierCurveSegment const&>(segment); + auto& through_0 = curve.through_0(); + auto& through_1 = curve.through_1(); + draw_cubic_bezier_curve(through_0, through_1, cursor, segment.point(), color, thickness); + cursor = segment.point(); + break; + } case Segment::Type::EllipticalArcTo: auto& arc = static_cast<EllipticalArcSegment const&>(segment); draw_elliptical_arc(cursor, segment.point(), arc.center(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), color, thickness); @@ -154,3 +162,10 @@ void Gfx::AntiAliasingPainter::draw_quadratic_bezier_curve(FloatPoint const& con draw_line(fp1, fp2, color, thickness, style); }); } + +void Gfx::AntiAliasingPainter::draw_cubic_bezier_curve(const FloatPoint& control_point_0, const FloatPoint& control_point_1, const FloatPoint& p1, const FloatPoint& p2, Color color, float thickness, Painter::LineStyle style) +{ + Gfx::Painter::for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, [&](FloatPoint const& fp1, FloatPoint const& fp2) { + draw_line(fp1, fp2, color, thickness, style); + }); +} diff --git a/Userland/Libraries/LibGfx/AntiAliasingPainter.h b/Userland/Libraries/LibGfx/AntiAliasingPainter.h index 64a3a17a539b..5ae54bd7d4c9 100644 --- a/Userland/Libraries/LibGfx/AntiAliasingPainter.h +++ b/Userland/Libraries/LibGfx/AntiAliasingPainter.h @@ -22,6 +22,7 @@ class AntiAliasingPainter { void fill_path(Path&, Color, Painter::WindingRule rule = Painter::WindingRule::Nonzero); void stroke_path(Path const&, Color, float thickness); void draw_quadratic_bezier_curve(FloatPoint const& control_point, FloatPoint const&, FloatPoint const&, Color, float thickness = 1, Painter::LineStyle style = Painter::LineStyle::Solid); + void draw_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const&, FloatPoint const&, Color, float thickness = 1, Painter::LineStyle style = Painter::LineStyle::Solid); void draw_elliptical_arc(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& center, FloatPoint const& radii, float x_axis_rotation, float theta_1, float theta_delta, Color, float thickness = 1, Painter::LineStyle style = Painter::LineStyle::Solid); void translate(float dx, float dy) { m_transform.translate(dx, dy); } diff --git a/Userland/Libraries/LibGfx/Painter.cpp b/Userland/Libraries/LibGfx/Painter.cpp index 22be719fdf47..29bd782f39a6 100644 --- a/Userland/Libraries/LibGfx/Painter.cpp +++ b/Userland/Libraries/LibGfx/Painter.cpp @@ -1858,6 +1858,76 @@ void Painter::draw_quadratic_bezier_curve(IntPoint const& control_point, IntPoin }); } +void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>&& callback) +{ + for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, callback); +} + +static bool can_approximate_cubic_bezier_curve(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& control_0, FloatPoint const& control_1) +{ + constexpr float tolerance = 15; // Arbitrary, seems like 10-30 produces nice results. + + auto ax = 3 * control_0.x() - 2 * p1.x() - p2.x(); + auto ay = 3 * control_0.y() - 2 * p1.y() - p2.y(); + auto bx = 3 * control_1.x() - p1.x() - 2 * p2.x(); + auto by = 3 * control_1.y() - p1.y() - 2 * p2.y(); + + ax *= ax; + ay *= ay; + bx *= bx; + by *= by; + + return max(ax, bx) + max(ay, by) <= tolerance; +} + +// static +void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>& callback) +{ + struct ControlPair { + FloatPoint control_point_0; + FloatPoint control_point_1; + }; + struct SegmentDescriptor { + ControlPair control_points; + FloatPoint p1; + FloatPoint p2; + }; + + static constexpr auto split_cubic_bezier_curve = [](ControlPair const& original_controls, FloatPoint const& p1, FloatPoint const& p2, auto& segments) { + Array level_1_midpoints { + (p1 + original_controls.control_point_0) / 2, + (original_controls.control_point_0 + original_controls.control_point_1) / 2, + (original_controls.control_point_1 + p2) / 2, + }; + Array level_2_midpoints { + (level_1_midpoints[0] + level_1_midpoints[1]) / 2, + (level_1_midpoints[1] + level_1_midpoints[2]) / 2, + }; + auto level_3_midpoint = (level_2_midpoints[0] + level_2_midpoints[1]) / 2; + + segments.enqueue({ { level_1_midpoints[0], level_2_midpoints[0] }, p1, level_3_midpoint }); + segments.enqueue({ { level_2_midpoints[1], level_1_midpoints[2] }, level_3_midpoint, p2 }); + }; + + Queue<SegmentDescriptor> segments; + segments.enqueue({ { control_point_0, control_point_1 }, p1, p2 }); + while (!segments.is_empty()) { + auto segment = segments.dequeue(); + + if (can_approximate_cubic_bezier_curve(segment.p1, segment.p2, segment.control_points.control_point_0, segment.control_points.control_point_1)) + callback(segment.p1, segment.p2); + else + split_cubic_bezier_curve(segment.control_points, segment.p1, segment.p2, segments); + } +} + +void Painter::draw_cubic_bezier_curve(IntPoint const& control_point_0, IntPoint const& control_point_1, IntPoint const& p1, IntPoint const& p2, Color color, int thickness, Painter::LineStyle style) +{ + for_each_line_segment_on_cubic_bezier_curve(FloatPoint(control_point_0), FloatPoint(control_point_1), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint const& fp1, FloatPoint const& fp2) { + draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style); + }); +} + // static void Painter::for_each_line_segment_on_elliptical_arc(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& center, FloatPoint const radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint const&, FloatPoint const&)>& callback) { @@ -1975,6 +2045,14 @@ void Painter::stroke_path(Path const& path, Color color, int thickness) cursor = segment.point(); break; } + case Segment::Type::CubicBezierCurveTo: { + auto& curve = static_cast<CubicBezierCurveSegment const&>(segment); + auto& through_0 = curve.through_0(); + auto& through_1 = curve.through_1(); + draw_cubic_bezier_curve(through_0.to_type<int>(), through_1.to_type<int>(), cursor.to_type<int>(), segment.point().to_type<int>(), color, thickness); + cursor = segment.point(); + break; + } case Segment::Type::EllipticalArcTo: auto& arc = static_cast<EllipticalArcSegment const&>(segment); draw_elliptical_arc(cursor.to_type<int>(), segment.point().to_type<int>(), arc.center().to_type<int>(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), color, thickness); diff --git a/Userland/Libraries/LibGfx/Painter.h b/Userland/Libraries/LibGfx/Painter.h index d0a01d44cf90..d87ef7aeece4 100644 --- a/Userland/Libraries/LibGfx/Painter.h +++ b/Userland/Libraries/LibGfx/Painter.h @@ -54,6 +54,7 @@ class Painter { void set_pixel(int x, int y, Color color) { set_pixel({ x, y }, color); } void draw_line(IntPoint const&, IntPoint const&, Color, int thickness = 1, LineStyle style = LineStyle::Solid, Color alternate_color = Color::Transparent); void draw_quadratic_bezier_curve(IntPoint const& control_point, IntPoint const&, IntPoint const&, Color, int thickness = 1, LineStyle style = LineStyle::Solid); + void draw_cubic_bezier_curve(IntPoint const& control_point_0, IntPoint const& control_point_1, IntPoint const&, IntPoint const&, Color, int thickness = 1, LineStyle style = LineStyle::Solid); void draw_elliptical_arc(IntPoint const& p1, IntPoint const& p2, IntPoint const& center, FloatPoint const& radii, float x_axis_rotation, float theta_1, float theta_delta, Color, int thickness = 1, LineStyle style = LineStyle::Solid); void blit(IntPoint const&, Gfx::Bitmap const&, IntRect const& src_rect, float opacity = 1.0f, bool apply_alpha = true); void blit_dimmed(IntPoint const&, Gfx::Bitmap const&, IntRect const& src_rect); @@ -88,6 +89,9 @@ class Painter { static void for_each_line_segment_on_bezier_curve(FloatPoint const& control_point, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>&); static void for_each_line_segment_on_bezier_curve(FloatPoint const& control_point, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>&&); + static void for_each_line_segment_on_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>&); + static void for_each_line_segment_on_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>&&); + static void for_each_line_segment_on_elliptical_arc(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& center, FloatPoint const radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint const&, FloatPoint const&)>&); static void for_each_line_segment_on_elliptical_arc(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& center, FloatPoint const radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint const&, FloatPoint const&)>&&); diff --git a/Userland/Libraries/LibGfx/Path.cpp b/Userland/Libraries/LibGfx/Path.cpp index 248fc5dced5f..879e6e76c992 100644 --- a/Userland/Libraries/LibGfx/Path.cpp +++ b/Userland/Libraries/LibGfx/Path.cpp @@ -160,6 +160,7 @@ void Path::close_all_subpaths() } case Segment::Type::LineTo: case Segment::Type::QuadraticBezierCurveTo: + case Segment::Type::CubicBezierCurveTo: case Segment::Type::EllipticalArcTo: if (is_first_point_in_subpath) { start_of_subpath = cursor; @@ -189,6 +190,9 @@ String Path::to_string() const case Segment::Type::QuadraticBezierCurveTo: builder.append("QuadraticBezierCurveTo"); break; + case Segment::Type::CubicBezierCurveTo: + builder.append("CubicBezierCurveTo"); + break; case Segment::Type::EllipticalArcTo: builder.append("EllipticalArcTo"); break; @@ -203,6 +207,12 @@ String Path::to_string() const builder.append(", "); builder.append(static_cast<const QuadraticBezierCurveSegment&>(segment).through().to_string()); break; + case Segment::Type::CubicBezierCurveTo: + builder.append(", "); + builder.append(static_cast<const CubicBezierCurveSegment&>(segment).through_0().to_string()); + builder.append(", "); + builder.append(static_cast<const CubicBezierCurveSegment&>(segment).through_1().to_string()); + break; case Segment::Type::EllipticalArcTo: { auto& arc = static_cast<const EllipticalArcSegment&>(segment); builder.appendff(", {}, {}, {}, {}, {}", @@ -286,6 +296,16 @@ void Path::segmentize_path() cursor = segment.point(); break; } + case Segment::Type::CubicBezierCurveTo: { + auto& curve = static_cast<CubicBezierCurveSegment const&>(segment); + auto& control_0 = curve.through_0(); + auto& control_1 = curve.through_1(); + Painter::for_each_line_segment_on_cubic_bezier_curve(control_0, control_1, cursor, segment.point(), [&](const FloatPoint& p0, const FloatPoint& p1) { + add_line(p0, p1); + }); + cursor = segment.point(); + break; + } case Segment::Type::EllipticalArcTo: { auto& arc = static_cast<EllipticalArcSegment&>(segment); Painter::for_each_line_segment_on_elliptical_arc(cursor, arc.point(), arc.center(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), [&](const FloatPoint& p0, const FloatPoint& p1) { @@ -310,15 +330,4 @@ void Path::segmentize_path() m_bounding_box = Gfx::FloatRect { min_x, min_y, max_x - min_x, max_y - min_y }; } -void Path::cubic_bezier_curve_to(FloatPoint const& c1, FloatPoint const& c2, FloatPoint const& p2) -{ - // FIXME: I'm sure there's a faster and more elegant way to do this. - // FIXME: We should divide it into enough segments to stay within some tolerance. - auto p1 = segments().last().point(); - for (float t = 0; t <= 1.0f; t += 0.02f) { - auto p = cubic_interpolate(p1, p2, c1, c2, t); - line_to(p); - } -} - } diff --git a/Userland/Libraries/LibGfx/Path.h b/Userland/Libraries/LibGfx/Path.h index afda4d00f787..41c0d65ade40 100644 --- a/Userland/Libraries/LibGfx/Path.h +++ b/Userland/Libraries/LibGfx/Path.h @@ -24,6 +24,7 @@ class Segment : public RefCounted<Segment> { MoveTo, LineTo, QuadraticBezierCurveTo, + CubicBezierCurveTo, EllipticalArcTo, }; @@ -83,6 +84,27 @@ class QuadraticBezierCurveSegment final : public Segment { FloatPoint m_through; }; +class CubicBezierCurveSegment final : public Segment { +public: + CubicBezierCurveSegment(const FloatPoint& point, const FloatPoint& through_0, const FloatPoint& through_1) + : Segment(point) + , m_through_0(through_0) + , m_through_1(through_1) + { + } + + virtual ~CubicBezierCurveSegment() override = default; + + const FloatPoint& through_0() const { return m_through_0; } + const FloatPoint& through_1() const { return m_through_1; } + +private: + virtual Type type() const override { return Segment::Type::CubicBezierCurveTo; } + + FloatPoint m_through_0; + FloatPoint m_through_1; +}; + class EllipticalArcSegment final : public Segment { public: EllipticalArcSegment(const FloatPoint& point, const FloatPoint& center, const FloatPoint radii, float x_axis_rotation, float theta_1, float theta_delta) @@ -134,7 +156,11 @@ class Path { invalidate_split_lines(); } - void cubic_bezier_curve_to(FloatPoint const& c1, FloatPoint const& c2, FloatPoint const& p2); + void cubic_bezier_curve_to(FloatPoint const& c1, FloatPoint const& c2, FloatPoint const& p2) + { + append_segment<CubicBezierCurveSegment>(p2, c1, c2); + invalidate_split_lines(); + } void elliptical_arc_to(const FloatPoint& point, const FloatPoint& radii, double x_axis_rotation, bool large_arc, bool sweep); void arc_to(const FloatPoint& point, float radius, bool large_arc, bool sweep)
1298baa9ad9825104b7bd331e73d5be42536bdd4
2022-12-25 20:28:58
Andreas Kling
ladybird: Port over ConsoleWidget from the SerenityOS Browser
false
Port over ConsoleWidget from the SerenityOS Browser
ladybird
diff --git a/Ladybird/CMakeLists.txt b/Ladybird/CMakeLists.txt index 576e1aa6bc50..54a221250a3b 100644 --- a/Ladybird/CMakeLists.txt +++ b/Ladybird/CMakeLists.txt @@ -50,14 +50,15 @@ find_package(Qt6 REQUIRED COMPONENTS Core Widgets Network) set(SOURCES BrowserWindow.cpp + ConsoleWidget.cpp CookieJar.cpp - WebContentView.cpp History.cpp ModelTranslator.cpp Settings.cpp SettingsDialog.cpp Tab.cpp Utilities.cpp + WebContentView.cpp main.cpp ) diff --git a/Ladybird/ConsoleWidget.cpp b/Ladybird/ConsoleWidget.cpp new file mode 100644 index 000000000000..aab3585bb86c --- /dev/null +++ b/Ladybird/ConsoleWidget.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2020, Hunter Salyer <[email protected]> + * Copyright (c) 2021-2022, Andreas Kling <[email protected]> + * Copyright (c) 2021, Sam Atkins <[email protected]> + * Copyright (c) 2022, the SerenityOS developers. + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#define AK_DONT_REPLACE_STD + +#include "ConsoleWidget.h" +#include "Utilities.h" +#include <AK/StringBuilder.h> +#include <LibJS/MarkupGenerator.h> +#include <QLineEdit> +#include <QPushButton> +#include <QTextEdit> +#include <QVBoxLayout> + +namespace Ladybird { + +ConsoleWidget::ConsoleWidget() +{ + setLayout(new QVBoxLayout); + + m_output_view = new QTextEdit(this); + m_output_view->setReadOnly(true); + layout()->addWidget(m_output_view); + + if (on_request_messages) + on_request_messages(0); + + auto* bottom_container = new QWidget(this); + bottom_container->setLayout(new QHBoxLayout); + + layout()->addWidget(bottom_container); + + m_input = new QLineEdit(bottom_container); + bottom_container->layout()->addWidget(m_input); + + QObject::connect(m_input, &QLineEdit::returnPressed, [this] { + auto js_source = akstring_from_qstring(m_input->text()); + + if (js_source.is_whitespace()) + return; + + m_input->clear(); + + print_source_line(js_source); + + if (on_js_input) + on_js_input(js_source); + }); + + setFocusProxy(m_input); + + auto* clear_button = new QPushButton(bottom_container); + bottom_container->layout()->addWidget(clear_button); + clear_button->setFixedSize(22, 22); + clear_button->setText("X"); + clear_button->setToolTip("Clear the console output"); + QObject::connect(clear_button, &QPushButton::pressed, [this] { + clear_output(); + }); + + m_input->setFocus(); +} + +void ConsoleWidget::request_console_messages() +{ + VERIFY(!m_waiting_for_messages); + VERIFY(on_request_messages); + on_request_messages(m_highest_received_message_index + 1); + m_waiting_for_messages = true; +} + +void ConsoleWidget::notify_about_new_console_message(i32 message_index) +{ + if (message_index <= m_highest_received_message_index) { + dbgln("Notified about console message we already have"); + return; + } + if (message_index <= m_highest_notified_message_index) { + dbgln("Notified about console message we're already aware of"); + return; + } + + m_highest_notified_message_index = message_index; + if (!m_waiting_for_messages) + request_console_messages(); +} + +void ConsoleWidget::handle_console_messages(i32 start_index, Vector<String> const& message_types, Vector<String> const& messages) +{ + i32 end_index = start_index + message_types.size() - 1; + if (end_index <= m_highest_received_message_index) { + dbgln("Received old console messages"); + return; + } + + for (size_t i = 0; i < message_types.size(); i++) { + auto& type = message_types[i]; + auto& message = messages[i]; + + if (type == "html") { + print_html(message); + } else if (type == "clear") { + clear_output(); + } else if (type == "group") { + // FIXME: Implement. + } else if (type == "groupCollapsed") { + // FIXME: Implement. + } else if (type == "groupEnd") { + // FIXME: Implement. + } else { + VERIFY_NOT_REACHED(); + } + } + + m_highest_received_message_index = end_index; + m_waiting_for_messages = false; + + if (m_highest_received_message_index < m_highest_notified_message_index) + request_console_messages(); +} + +void ConsoleWidget::print_source_line(StringView source) +{ + StringBuilder html; + html.append("<span class=\"repl-indicator\">"sv); + html.append("&gt; "sv); + html.append("</span>"sv); + + html.append(JS::MarkupGenerator::html_from_source(source)); + + print_html(html.string_view()); +} + +void ConsoleWidget::print_html(StringView line) +{ + m_output_view->append(QString::fromUtf8(line.characters_without_null_termination(), line.length())); +} + +void ConsoleWidget::clear_output() +{ + m_output_view->clear(); +} + +void ConsoleWidget::reset() +{ + clear_output(); + m_highest_notified_message_index = -1; + m_highest_received_message_index = -1; + m_waiting_for_messages = false; +} + +} diff --git a/Ladybird/ConsoleWidget.h b/Ladybird/ConsoleWidget.h new file mode 100644 index 000000000000..7b2d0fb591c9 --- /dev/null +++ b/Ladybird/ConsoleWidget.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2020, Hunter Salyer <[email protected]> + * Copyright (c) 2021-2022, Andreas Kling <[email protected]> + * Copyright (c) 2021, Sam Atkins <[email protected]> + * Copyright (c) 2022, the SerenityOS developers. + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Function.h> +#include <AK/String.h> +#include <AK/Vector.h> +#include <QWidget> + +class QLineEdit; +class QTextEdit; + +namespace Ladybird { + +class ConsoleWidget final : public QWidget { + Q_OBJECT +public: + ConsoleWidget(); + virtual ~ConsoleWidget() = default; + + void notify_about_new_console_message(i32 message_index); + void handle_console_messages(i32 start_index, Vector<String> const& message_types, Vector<String> const& messages); + void print_source_line(StringView); + void print_html(StringView); + void reset(); + + Function<void(String const&)> on_js_input; + Function<void(i32)> on_request_messages; + +private: + void request_console_messages(); + void clear_output(); + + QTextEdit* m_output_view { nullptr }; + QLineEdit* m_input { nullptr }; + + i32 m_highest_notified_message_index { -1 }; + i32 m_highest_received_message_index { -1 }; + bool m_waiting_for_messages { false }; +}; + +} diff --git a/Ladybird/WebContentView.cpp b/Ladybird/WebContentView.cpp index d7cb3527aedb..c3b82d33a483 100644 --- a/Ladybird/WebContentView.cpp +++ b/Ladybird/WebContentView.cpp @@ -7,6 +7,7 @@ #define AK_DONT_REPLACE_STD #include "WebContentView.h" +#include "ConsoleWidget.h" #include "CookieJar.h" #include "ModelTranslator.h" #include "Utilities.h" @@ -446,46 +447,35 @@ void WebContentView::run_javascript(String const& js_source) void WebContentView::did_output_js_console_message(i32 message_index) { - // FIXME - (void)message_index; + if (m_console_widget) + m_console_widget->notify_about_new_console_message(message_index); } -void WebContentView::did_get_js_console_messages(i32, Vector<String>, Vector<String> messages) +void WebContentView::did_get_js_console_messages(i32 start_index, Vector<String> message_types, Vector<String> messages) { - ensure_js_console_widget(); - for (auto& message : messages) { - m_js_console_output_edit->append(qstring_from_akstring(message).trimmed()); - } + if (m_console_widget) + m_console_widget->handle_console_messages(start_index, message_types, messages); } void WebContentView::ensure_js_console_widget() { - if (!m_js_console_widget) { - m_js_console_widget = new QWidget; - m_js_console_widget->setWindowTitle("JS Console"); - auto* layout = new QVBoxLayout(m_js_console_widget); - m_js_console_widget->setLayout(layout); - m_js_console_output_edit = new QTextEdit(this); - m_js_console_output_edit->setReadOnly(true); - m_js_console_input_edit = new QLineEdit(this); - layout->addWidget(m_js_console_output_edit); - layout->addWidget(m_js_console_input_edit); - m_js_console_widget->resize(640, 480); - - QObject::connect(m_js_console_input_edit, &QLineEdit::returnPressed, [this] { - auto code = m_js_console_input_edit->text().trimmed(); - client().async_js_console_input(akstring_from_qstring(code)); - m_js_console_input_edit->clear(); - m_js_console_output_edit->append(QString("> %1").arg(code)); - }); + if (!m_console_widget) { + m_console_widget = new Ladybird::ConsoleWidget; + m_console_widget->setWindowTitle("JS Console"); + m_console_widget->resize(640, 480); + m_console_widget->on_js_input = [this](auto js_source) { + client().async_js_console_input(js_source); + }; + m_console_widget->on_request_messages = [this](i32 start_index) { + client().async_js_console_request_messages(start_index); + }; } } void WebContentView::show_js_console() { ensure_js_console_widget(); - m_js_console_widget->show(); - m_js_console_input_edit->setFocus(); + m_console_widget->show(); } void WebContentView::ensure_inspector_widget() @@ -846,14 +836,14 @@ void WebContentView::notify_server_did_get_dom_node_properties(i32 node_id, Stri void WebContentView::notify_server_did_output_js_console_message(i32 message_index) { - if (on_js_console_new_message) - on_js_console_new_message(message_index); + if (m_console_widget) + m_console_widget->notify_about_new_console_message(message_index); } void WebContentView::notify_server_did_get_js_console_messages(i32 start_index, Vector<String> const& message_types, Vector<String> const& messages) { - if (on_get_js_console_messages) - on_get_js_console_messages(start_index, message_types, messages); + if (m_console_widget) + m_console_widget->handle_console_messages(start_index, message_types, messages); } void WebContentView::notify_server_did_change_favicon(Gfx::Bitmap const& bitmap) diff --git a/Ladybird/WebContentView.h b/Ladybird/WebContentView.h index f34cb2c5796e..80f2976ad756 100644 --- a/Ladybird/WebContentView.h +++ b/Ladybird/WebContentView.h @@ -25,6 +25,10 @@ class QTextEdit; class QLineEdit; +namespace Ladybird { +class ConsoleWidget; +} + namespace WebView { class WebContentClient; } @@ -152,11 +156,9 @@ class WebContentView final qreal m_inverse_pixel_scaling_ratio { 1.0 }; bool m_should_show_line_box_borders { false }; - QPointer<QWidget> m_js_console_widget; QPointer<QWidget> m_inspector_widget; - QTextEdit* m_js_console_output_edit { nullptr }; - QLineEdit* m_js_console_input_edit { nullptr }; + Ladybird::ConsoleWidget* m_console_widget { nullptr }; Gfx::IntRect m_viewport_rect;
f70136a32455e59ef4adf9f35031a22c7027c8f6
2019-01-22 05:28:56
Andreas Kling
kernel: Support open() with O_CREAT.
false
Support open() with O_CREAT.
kernel
diff --git a/Kernel/KSyms.cpp b/Kernel/KSyms.cpp index 4168e8a43cdd..4a89206fee19 100644 --- a/Kernel/KSyms.cpp +++ b/Kernel/KSyms.cpp @@ -124,7 +124,7 @@ void init_ksyms() void load_ksyms() { int error; - auto descriptor = VFS::the().open("/kernel.map", error); + auto descriptor = VFS::the().open("/kernel.map", error, 0, 0); if (!descriptor) { kprintf("Failed to open /kernel.map\n"); } else { diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 71d5a7f0a1ab..df38358ee0b6 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -289,7 +289,7 @@ int Process::do_exec(const String& path, Vector<String>&& arguments, Vector<Stri return -ENOENT; int error; - auto descriptor = VFS::the().open(path, error, 0, m_cwd ? m_cwd->identifier() : InodeIdentifier()); + auto descriptor = VFS::the().open(path, error, 0, 0, m_cwd ? m_cwd->identifier() : InodeIdentifier()); if (!descriptor) { ASSERT(error != 0); return error; @@ -1117,7 +1117,7 @@ int Process::sys$utime(const char* pathname, const Unix::utimbuf* buf) return -EFAULT; String path(pathname); int error; - auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier()); + auto descriptor = VFS::the().open(move(path), error, 0, 0, cwd_inode()->identifier()); if (!descriptor) return error; auto& inode = *descriptor->inode(); @@ -1206,7 +1206,7 @@ int Process::sys$lstat(const char* path, Unix::stat* statbuf) if (!validate_write_typed(statbuf)) return -EFAULT; int error; - auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR, cwd_inode()->identifier()); + auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR, 0, cwd_inode()->identifier()); if (!descriptor) return error; descriptor->stat(statbuf); @@ -1218,7 +1218,7 @@ int Process::sys$stat(const char* path, Unix::stat* statbuf) if (!validate_write_typed(statbuf)) return -EFAULT; int error; - auto descriptor = VFS::the().open(move(path), error, 0, cwd_inode()->identifier()); + auto descriptor = VFS::the().open(move(path), error, 0, 0, cwd_inode()->identifier()); if (!descriptor) return error; descriptor->stat(statbuf); @@ -1233,7 +1233,7 @@ int Process::sys$readlink(const char* path, char* buffer, size_t size) return -EFAULT; int error; - auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, cwd_inode()->identifier()); + auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, 0, cwd_inode()->identifier()); if (!descriptor) return error; @@ -1255,7 +1255,7 @@ int Process::sys$chdir(const char* path) if (!validate_read_str(path)) return -EFAULT; int error; - auto descriptor = VFS::the().open(path, error, 0, cwd_inode()->identifier()); + auto descriptor = VFS::the().open(path, error, 0, 0, cwd_inode()->identifier()); if (!descriptor) return error; if (!descriptor->is_directory()) @@ -1288,7 +1288,7 @@ size_t Process::number_of_open_file_descriptors() const return count; } -int Process::sys$open(const char* path, int options) +int Process::sys$open(const char* path, int options, mode_t mode) { #ifdef DEBUG_IO dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path); @@ -1299,7 +1299,7 @@ int Process::sys$open(const char* path, int options) return -EMFILE; int error = -EWHYTHO; ASSERT(cwd_inode()); - auto descriptor = VFS::the().open(path, error, options, cwd_inode()->identifier()); + auto descriptor = VFS::the().open(path, error, options, mode, cwd_inode()->identifier()); if (!descriptor) return error; if (options & O_DIRECTORY && !descriptor->is_directory()) diff --git a/Kernel/Process.h b/Kernel/Process.h index 858a3f09882b..c4a57402ac6e 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -140,7 +140,7 @@ class Process : public InlineLinkedListNode<Process> { pid_t sys$getpid(); pid_t sys$getppid(); mode_t sys$umask(mode_t); - int sys$open(const char* path, int options); + int sys$open(const char* path, int options, mode_t mode = 0); int sys$close(int fd); ssize_t sys$read(int fd, void* outbuf, size_t nread); ssize_t sys$write(int fd, const void*, size_t); diff --git a/Kernel/Syscall.cpp b/Kernel/Syscall.cpp index 9a551b2a3748..3e8d5ba9a64f 100644 --- a/Kernel/Syscall.cpp +++ b/Kernel/Syscall.cpp @@ -73,7 +73,7 @@ static dword handle(RegisterDump& regs, dword function, dword arg1, dword arg2, case Syscall::SC_getcwd: return current->sys$getcwd((char*)arg1, (size_t)arg2); case Syscall::SC_open: - return current->sys$open((const char*)arg1, (int)arg2); + return current->sys$open((const char*)arg1, (int)arg2, (mode_t)arg3); case Syscall::SC_write: return current->sys$write((int)arg1, (const void*)arg2, (size_t)arg3); case Syscall::SC_close: diff --git a/LibC/unistd.cpp b/LibC/unistd.cpp index d039c1daefab..0e10e7811be8 100644 --- a/LibC/unistd.cpp +++ b/LibC/unistd.cpp @@ -7,6 +7,7 @@ #include <pwd.h> #include <stdio.h> #include <sys/ioctl.h> +#include <sys/types.h> #include <Kernel/Syscall.h> extern "C" { @@ -91,7 +92,7 @@ int open(const char* path, int options, ...) { va_list ap; va_start(ap, options); - int rc = syscall(SC_open, path, options, ap); + int rc = syscall(SC_open, path, options, va_arg(ap, mode_t)); va_end(ap); __RETURN_WITH_ERRNO(rc, rc, -1); } diff --git a/Userland/touch.cpp b/Userland/touch.cpp index 6d857198f649..3d0dcb58bf5a 100644 --- a/Userland/touch.cpp +++ b/Userland/touch.cpp @@ -1,6 +1,26 @@ #include <stdio.h> +#include <errno.h> #include <utime.h> +#include <fcntl.h> +#include <unistd.h> +#include <stdlib.h> #include <sys/types.h> +#include <sys/stat.h> + +static bool file_exists(const char* path) +{ + struct stat st; + int rc = stat(path, &st); + if (rc < 0) { + if (errno == ENOENT) + return false; + } + if (rc == 0) { + return true; + } + perror("stat"); + exit(1); +} int main(int argc, char** argv) { @@ -8,9 +28,22 @@ int main(int argc, char** argv) fprintf(stderr, "usage: touch <path>\n"); return 1; } - int rc = utime(argv[1], nullptr); - if (rc < 0) - perror("utime"); + if (file_exists(argv[1])) { + int rc = utime(argv[1], nullptr); + if (rc < 0) + perror("utime"); + } else { + int fd = open(argv[1], O_CREAT, 0010644); + if (fd < 0) { + perror("open"); + return 1; + } + int rc = close(fd); + if (rc < 0) { + perror("close"); + return 1; + } + } return 0; } diff --git a/VirtualFileSystem/Ext2FileSystem.cpp b/VirtualFileSystem/Ext2FileSystem.cpp index 106b1058ddfe..71b20b8dd327 100644 --- a/VirtualFileSystem/Ext2FileSystem.cpp +++ b/VirtualFileSystem/Ext2FileSystem.cpp @@ -435,7 +435,12 @@ bool Ext2FSInode::add_child(InodeIdentifier child_id, const String& name, byte f } entries.append({ name.characters(), name.length(), child_id, file_type }); - return fs().write_directory_inode(index(), move(entries)); + bool success = fs().write_directory_inode(index(), move(entries)); + if (success) { + LOCKER(m_lock); + m_lookup_cache.set(name, child_id.index()); + } + return success; } bool Ext2FS::write_directory_inode(unsigned directoryInode, Vector<DirectoryEntry>&& entries) @@ -598,27 +603,29 @@ bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode) Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(unsigned group, unsigned count) { - dbgprintf("Ext2FS: allocateBlocks(group: %u, count: %u)\n", group, count); + dbgprintf("Ext2FS: allocate_blocks(group: %u, count: %u)\n", group, count); + if (count == 0) + return { }; auto& bgd = group_descriptor(group); if (bgd.bg_free_blocks_count < count) { - kprintf("ExtFS: allocateBlocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count); + kprintf("Ext2FS: allocate_blocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count); return { }; } // FIXME: Implement a scan that finds consecutive blocks if possible. Vector<BlockIndex> blocks; - traverse_block_bitmap(group, [&blocks, count] (unsigned firstBlockInBitmap, const Bitmap& bitmap) { + traverse_block_bitmap(group, [&blocks, count] (unsigned first_block_in_bitmap, const Bitmap& bitmap) { for (unsigned i = 0; i < bitmap.size(); ++i) { if (!bitmap.get(i)) { - blocks.append(firstBlockInBitmap + i); + blocks.append(first_block_in_bitmap + i); if (blocks.size() == count) return false; } } return true; }); - dbgprintf("Ext2FS: allocateBlock found these blocks:\n"); + dbgprintf("Ext2FS: allocate_block found these blocks:\n"); for (auto& bi : blocks) { dbgprintf(" > %u\n", bi); } @@ -628,7 +635,7 @@ Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(unsigned group, unsigned coun unsigned Ext2FS::allocate_inode(unsigned preferredGroup, unsigned expectedSize) { - dbgprintf("Ext2FS: allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize); + dbgprintf("Ext2FS: allocate_inode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize); unsigned neededBlocks = ceilDiv(expectedSize, blockSize()); @@ -651,11 +658,11 @@ unsigned Ext2FS::allocate_inode(unsigned preferredGroup, unsigned expectedSize) } if (!groupIndex) { - kprintf("Ext2FS: allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks); + kprintf("Ext2FS: allocate_inode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks); return 0; } - dbgprintf("Ext2FS: allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks); + dbgprintf("Ext2FS: allocate_inode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks); unsigned firstFreeInodeInGroup = 0; traverse_inode_bitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) { @@ -669,7 +676,7 @@ unsigned Ext2FS::allocate_inode(unsigned preferredGroup, unsigned expectedSize) }); if (!firstFreeInodeInGroup) { - kprintf("Ext2FS: firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n"); + kprintf("Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(\n"); return 0; } @@ -841,14 +848,15 @@ RetainPtr<Inode> Ext2FS::create_inode(InodeIdentifier parent_id, const String& n // NOTE: This doesn't commit the inode allocation just yet! auto inode_id = allocate_inode(0, 0); if (!inode_id) { - kprintf("Ext2FS: createInode: allocate_inode failed\n"); + kprintf("Ext2FS: create_inode: allocate_inode failed\n"); error = -ENOSPC; return { }; } - auto blocks = allocate_blocks(group_index_from_inode(inode_id), ceilDiv(size, blockSize())); - if (blocks.is_empty()) { - kprintf("Ext2FS: createInode: allocate_blocks failed\n"); + auto needed_blocks = ceilDiv(size, blockSize()); + auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks); + if (blocks.size() != needed_blocks) { + kprintf("Ext2FS: create_inode: allocate_blocks failed\n"); error = -ENOSPC; return { }; } diff --git a/VirtualFileSystem/VirtualFileSystem.cpp b/VirtualFileSystem/VirtualFileSystem.cpp index 957c39421ccf..f6e3484d04ff 100644 --- a/VirtualFileSystem/VirtualFileSystem.cpp +++ b/VirtualFileSystem/VirtualFileSystem.cpp @@ -136,12 +136,15 @@ RetainPtr<FileDescriptor> VFS::open(RetainPtr<CharacterDevice>&& device, int& er return FileDescriptor::create(move(device)); } -RetainPtr<FileDescriptor> VFS::open(const String& path, int& error, int options, InodeIdentifier base) +RetainPtr<FileDescriptor> VFS::open(const String& path, int& error, int options, mode_t mode, InodeIdentifier base) { auto inode_id = resolve_path(path, base, error, options); auto inode = get_inode(inode_id); - if (!inode) + if (!inode) { + if (options & O_CREAT) + return create(path, error, options, mode, base); return nullptr; + } auto metadata = inode->metadata(); if (metadata.isCharacterDevice()) { auto it = m_character_devices.find(encodedDevice(metadata.majorDevice, metadata.minorDevice)); @@ -154,13 +157,37 @@ RetainPtr<FileDescriptor> VFS::open(const String& path, int& error, int options, return FileDescriptor::create(move(inode)); } -RetainPtr<FileDescriptor> VFS::create(const String& path, InodeIdentifier base, int& error) +RetainPtr<FileDescriptor> VFS::create(const String& path, int& error, int options, mode_t mode, InodeIdentifier base) { - // FIXME: Do the real thing, not just this fake thing! - (void) path; - (void) base; - m_root_inode->fs().create_inode(m_root_inode->fs().root_inode(), "empty", 0100644, 0, error); - return nullptr; + (void) options; + error = -EWHYTHO; + // FIXME: This won't work nicely across mount boundaries. + FileSystemPath p(path); + if (!p.is_valid()) { + error = -EINVAL; + return nullptr; + } + + InodeIdentifier parent_dir; + auto existing_dir = resolve_path(path, base, error, 0, &parent_dir); + if (existing_dir.is_valid()) { + error = -EEXIST; + return nullptr; + } + if (!parent_dir.is_valid()) { + error = -ENOENT; + return nullptr; + } + if (error != -ENOENT) { + return nullptr; + } + dbgprintf("VFS::create_file: '%s' in %u:%u\n", p.basename().characters(), parent_dir.fsid(), parent_dir.index()); + auto new_file = base.fs()->create_inode(base.fs()->root_inode(), p.basename(), mode, 0, error); + if (!new_file) + return nullptr; + + error = 0; + return FileDescriptor::create(move(new_file)); } bool VFS::mkdir(const String& path, mode_t mode, InodeIdentifier base, int& error) diff --git a/VirtualFileSystem/VirtualFileSystem.h b/VirtualFileSystem/VirtualFileSystem.h index 4472eb5e34a4..543d9bd4d44a 100644 --- a/VirtualFileSystem/VirtualFileSystem.h +++ b/VirtualFileSystem/VirtualFileSystem.h @@ -64,8 +64,8 @@ class VFS { bool mount(RetainPtr<FS>&&, const String& path); RetainPtr<FileDescriptor> open(RetainPtr<CharacterDevice>&&, int& error, int options); - RetainPtr<FileDescriptor> open(const String& path, int& error, int options = 0, InodeIdentifier base = InodeIdentifier()); - RetainPtr<FileDescriptor> create(const String& path, InodeIdentifier base, int& error); + RetainPtr<FileDescriptor> open(const String& path, int& error, int options, mode_t mode, InodeIdentifier base = InodeIdentifier()); + RetainPtr<FileDescriptor> create(const String& path, int& error, int options, mode_t mode, InodeIdentifier base); bool mkdir(const String& path, mode_t mode, InodeIdentifier base, int& error); bool touch(const String&path);
a63c7549e14498d5d6b85298d5f637c9241a7f5f
2022-11-16 03:18:19
Idan Horowitz
libweb: Implement window.open
false
Implement window.open
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index 8a911c0684b7..4890025fa42a 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -31,6 +31,7 @@ #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Event.h> #include <LibWeb/DOM/EventDispatcher.h> +#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h> #include <LibWeb/HTML/BrowsingContext.h> #include <LibWeb/HTML/EventHandler.h> #include <LibWeb/HTML/EventLoop/EventLoop.h> @@ -297,6 +298,131 @@ static bool check_if_a_popup_window_is_requested(OrderedHashMap<String, String> return false; } +// FIXME: This is based on the old 'browsing context' concept, which was replaced with 'navigable' +// https://html.spec.whatwg.org/multipage/window-object.html#window-open-steps +WebIDL::ExceptionOr<JS::GCPtr<HTML::WindowProxy>> Window::open_impl(StringView url, StringView target, StringView features) +{ + auto& vm = this->vm(); + + // 1. If the event loop's termination nesting level is nonzero, return null. + if (HTML::main_thread_event_loop().termination_nesting_level() != 0) + return nullptr; + + // 2. Let source browsing context be the entry global object's browsing context. + auto* source_browsing_context = verify_cast<Window>(entry_global_object()).browsing_context(); + + // 3. If target is the empty string, then set target to "_blank". + if (target.is_empty()) + target = "_blank"sv; + + // 4. Let tokenizedFeatures be the result of tokenizing features. + auto tokenized_features = tokenize_open_features(features); + + // 5. Let noopener and noreferrer be false. + auto no_opener = false; + auto no_referrer = false; + + // 6. If tokenizedFeatures["noopener"] exists, then: + if (auto no_opener_feature = tokenized_features.get("noopener"sv); no_opener_feature.has_value()) { + // 1. Set noopener to the result of parsing tokenizedFeatures["noopener"] as a boolean feature. + no_opener = parse_boolean_feature(*no_opener_feature); + + // 2. Remove tokenizedFeatures["noopener"]. + tokenized_features.remove("noopener"sv); + } + + // 7. If tokenizedFeatures["noreferrer"] exists, then: + if (auto no_referrer_feature = tokenized_features.get("noreferrer"sv); no_referrer_feature.has_value()) { + // 1. Set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature. + no_referrer = parse_boolean_feature(*no_referrer_feature); + + // 2. Remove tokenizedFeatures["noreferrer"]. + tokenized_features.remove("noreferrer"sv); + } + + // 8. If noreferrer is true, then set noopener to true. + if (no_referrer) + no_opener = true; + + // 9. Let target browsing context and windowType be the result of applying the rules for choosing a browsing context given target, source browsing context, and noopener. + auto [target_browsing_context, window_type] = source_browsing_context->choose_a_browsing_context(target, no_opener); + + // 10. If target browsing context is null, then return null. + if (target_browsing_context == nullptr) + return nullptr; + + // 11. If windowType is either "new and unrestricted" or "new with no opener", then: + if (window_type == BrowsingContext::WindowType::NewAndUnrestricted || window_type == BrowsingContext::WindowType::NewWithNoOpener) { + // 1. Set the target browsing context's is popup to the result of checking if a popup window is requested, given tokenizedFeatures. + target_browsing_context->set_is_popup(check_if_a_popup_window_is_requested(tokenized_features)); + + // FIXME: 2. Set up browsing context features for target browsing context given tokenizedFeatures. [CSSOMVIEW] + // NOTE: While this is not implemented yet, all of observable actions taken by this operation are optional (implementation-defined). + + // 3. Let urlRecord be the URL record about:blank. + auto url_record = AK::URL("about:blank"sv); + + // 4. If url is not the empty string, then parse url relative to the entry settings object, and set urlRecord to the resulting URL record, if any. If the parse a URL algorithm failed, then throw a "SyntaxError" DOMException. + if (!url.is_empty()) { + url_record = entry_settings_object().parse_url(url); + if (!url_record.is_valid()) + return WebIDL::SyntaxError::create(realm(), "URL is not valid"); + } + + // FIXME: 5. If urlRecord matches about:blank, then perform the URL and history update steps given target browsing context's active document and urlRecord. + + // 6. Otherwise: + else { + // 1. Let request be a new request whose URL is urlRecord. + auto request = Fetch::Infrastructure::Request::create(vm); + request->set_url(url_record); + + // 2. If noreferrer is true, then set request's referrer to "no-referrer". + if (no_referrer) + request->set_referrer(Fetch::Infrastructure::Request::Referrer::NoReferrer); + + // 3. Navigate target browsing context to request, with exceptionsEnabled set to true and the source browsing context set to source browsing context. + TRY(target_browsing_context->navigate(request, *source_browsing_context, true)); + } + } + + // 12. Otherwise: + else { + // 1. If url is not the empty string, then: + if (!url.is_empty()) { + // 1. Let urlRecord be the URL record about:blank. + auto url_record = AK::URL("about:blank"sv); + + // 2. Parse url relative to the entry settings object, and set urlRecord to the resulting URL record, if any. If the parse a URL algorithm failed, then throw a "SyntaxError" DOMException. + url_record = entry_settings_object().parse_url(url); + if (!url_record.is_valid()) + return WebIDL::SyntaxError::create(realm(), "URL is not valid"); + + // 3. Let request be a new request whose URL is urlRecord. + auto request = Fetch::Infrastructure::Request::create(vm); + request->set_url(url_record); + + // 4. If noreferrer is true, then set request's referrer to "noreferrer". + if (no_referrer) + request->set_referrer(Fetch::Infrastructure::Request::Referrer::NoReferrer); + + // 5. Navigate target browsing context to request, with exceptionsEnabled set to true and the source browsing context set to source browsing context. + TRY(target_browsing_context->navigate(request, *source_browsing_context, true)); + } + + // 2. If noopener is false, then set target browsing context's opener browsing context to source browsing context. + if (!no_opener) + target_browsing_context->set_opener_browsing_context(source_browsing_context); + } + + // 13. If noopener is true or windowType is "new with no opener", then return null. + if (no_opener || window_type == BrowsingContext::WindowType::NewWithNoOpener) + return nullptr; + + // 14. Return target browsing context's WindowProxy object. + return target_browsing_context->window_proxy(); +} + void Window::alert_impl(String const& message) { if (auto* page = this->page()) @@ -950,6 +1076,7 @@ void Window::initialize_web_interfaces(Badge<WindowEnvironmentSettingsObject>) define_native_accessor(realm, "innerHeight", inner_height_getter, {}, JS::Attribute::Enumerable); define_native_accessor(realm, "devicePixelRatio", device_pixel_ratio_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable); u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable; + define_native_function(realm, "open", open, 0, attr); define_native_function(realm, "alert", alert, 0, attr); define_native_function(realm, "confirm", confirm, 0, attr); define_native_function(realm, "prompt", prompt, 0, attr); @@ -1059,6 +1186,28 @@ static JS::ThrowCompletionOr<HTML::Window*> impl_from(JS::VM& vm) return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Window"); } +JS_DEFINE_NATIVE_FUNCTION(Window::open) +{ + auto* impl = TRY(impl_from(vm)); + + // optional USVString url = "" + String url = ""; + if (!vm.argument(0).is_undefined()) + url = TRY(vm.argument(0).to_string(vm)); + + // optional DOMString target = "_blank" + String target = "_blank"; + if (!vm.argument(1).is_undefined()) + target = TRY(vm.argument(1).to_string(vm)); + + // optional [LegacyNullToEmptyString] DOMString features = "") + String features = ""; + if (!vm.argument(2).is_nullish()) + features = TRY(vm.argument(2).to_string(vm)); + + return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->open_impl(url, target, features); })); +} + JS_DEFINE_NATIVE_FUNCTION(Window::alert) { // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs diff --git a/Userland/Libraries/LibWeb/HTML/Window.h b/Userland/Libraries/LibWeb/HTML/Window.h index 9b5b405ff0b8..d9e7e6715eaf 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.h +++ b/Userland/Libraries/LibWeb/HTML/Window.h @@ -61,6 +61,7 @@ class Window final bool import_maps_allowed() const { return m_import_maps_allowed; } void set_import_maps_allowed(bool import_maps_allowed) { m_import_maps_allowed = import_maps_allowed; } + WebIDL::ExceptionOr<JS::GCPtr<HTML::WindowProxy>> open_impl(StringView url, StringView target, StringView features); void alert_impl(String const&); bool confirm_impl(String const&); String prompt_impl(String const&, String const&); @@ -245,6 +246,7 @@ class Window final JS_DECLARE_NATIVE_FUNCTION(session_storage_getter); JS_DECLARE_NATIVE_FUNCTION(origin_getter); + JS_DECLARE_NATIVE_FUNCTION(open); JS_DECLARE_NATIVE_FUNCTION(alert); JS_DECLARE_NATIVE_FUNCTION(confirm); JS_DECLARE_NATIVE_FUNCTION(prompt);
0c441fa7af9c90e76931203c2e1a3cc9be6fe144
2023-04-10 01:15:39
Matthew Olsson
libweb: Implement WritableStreamDefaultWriter.abort()
false
Implement WritableStreamDefaultWriter.abort()
libweb
diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp index 2fb167a3bc8b..509518da8e40 100644 --- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp +++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp @@ -1308,6 +1308,19 @@ void writable_stream_update_backpressure(WritableStream& stream, bool backpressu stream.set_backpressure(backpressure); } +// https://streams.spec.whatwg.org/#writable-stream-default-writer-abort +WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason) +{ + // 1. Let stream be writer.[[stream]]. + auto stream = writer.stream(); + + // 2. Assert: stream is not undefined. + VERIFY(stream); + + // 3. Return ! WritableStreamAbort(stream, reason). + return writable_stream_abort(*stream, reason); +} + // https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error) { diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h index d9a97f65cc36..bc8ed2b42087 100644 --- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h +++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h @@ -73,6 +73,7 @@ void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream&); WebIDL::ExceptionOr<void> writable_stream_start_erroring(WritableStream&, JS::Value reason); void writable_stream_update_backpressure(WritableStream&, bool backpressure); +WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> writable_stream_default_writer_abort(WritableStreamDefaultWriter&, JS::Value reason); void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter&, JS::Value error); Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const&); diff --git a/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.cpp b/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.cpp index 058b4f0b6594..d393efb23f34 100644 --- a/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.cpp +++ b/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.cpp @@ -49,6 +49,21 @@ JS::GCPtr<JS::Object> WritableStreamDefaultWriter::ready() return m_ready_promise->promise(); } +// https://streams.spec.whatwg.org/#default-writer-abort +WebIDL::ExceptionOr<JS::GCPtr<JS::Object>> WritableStreamDefaultWriter::abort(JS::Value reason) +{ + auto& realm = this->realm(); + + // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception. + if (!m_stream) { + auto exception = MUST_OR_THROW_OOM(JS::TypeError::create(realm, "Cannot abort a writer that has no locked stream"sv)); + return WebIDL::create_rejected_promise(realm, exception)->promise(); + } + + // 2. Return ! WritableStreamDefaultWriterAbort(this, reason). + return TRY(writable_stream_default_writer_abort(*this, reason))->promise(); +} + WritableStreamDefaultWriter::WritableStreamDefaultWriter(JS::Realm& realm) : Bindings::PlatformObject(realm) { diff --git a/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.h b/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.h index a11b1be59670..e328613df977 100644 --- a/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.h +++ b/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.h @@ -27,6 +27,7 @@ class WritableStreamDefaultWriter final : public Bindings::PlatformObject { JS::GCPtr<JS::Object> closed(); WebIDL::ExceptionOr<Optional<double>> desired_size() const; JS::GCPtr<JS::Object> ready(); + WebIDL::ExceptionOr<JS::GCPtr<JS::Object>> abort(JS::Value reason); JS::GCPtr<WebIDL::Promise> closed_promise() { return m_closed_promise; } void set_closed_promise(JS::GCPtr<WebIDL::Promise> value) { m_closed_promise = value; } diff --git a/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idl b/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idl index dd6fff7e2125..b61d6afb0df0 100644 --- a/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idl +++ b/Userland/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idl @@ -8,8 +8,9 @@ interface WritableStreamDefaultWriter { readonly attribute unrestricted double? desiredSize; readonly attribute Promise<undefined> ready; + Promise<undefined> abort(optional any reason); + // FIXME: - // Promise<undefined> abort(optional any reason); // Promise<undefined> close(); // undefined releaseLock(); // Promise<undefined> write(optional any chunk);
ccdef5a675e2a16485b530d96cd24f7ea02f17f4
2020-05-10 13:53:05
AnotherTest
libline: Expose actual_rendered_string_length & accept newlines in prompt
false
Expose actual_rendered_string_length & accept newlines in prompt
libline
diff --git a/Libraries/LibLine/Editor.cpp b/Libraries/LibLine/Editor.cpp index 2f7115da9445..438bca11a77b 100644 --- a/Libraries/LibLine/Editor.cpp +++ b/Libraries/LibLine/Editor.cpp @@ -1031,6 +1031,11 @@ size_t Editor::actual_rendered_string_length(const StringView& string) const state = Escape; continue; } + if (c == '\r' || c == '\n') { + // reset length to 0, since we either overwrite, or are on a newline + length = 0; + continue; + } // FIXME: This will not support anything sophisticated ++length; break; diff --git a/Libraries/LibLine/Editor.h b/Libraries/LibLine/Editor.h index 90dc5aef7959..d911deb5dc83 100644 --- a/Libraries/LibLine/Editor.h +++ b/Libraries/LibLine/Editor.h @@ -130,6 +130,7 @@ class Editor { const Vector<String>& history() const { return m_history; } void register_character_input_callback(char ch, Function<bool(Editor&)> callback); + size_t actual_rendered_string_length(const StringView& string) const; Function<Vector<CompletionSuggestion>(const String&)> on_tab_complete_first_token; Function<Vector<CompletionSuggestion>(const String&)> on_tab_complete_other_token; @@ -252,8 +253,6 @@ class Editor { return (m_drawn_cursor + current_prompt_length()) % m_num_columns; } - size_t actual_rendered_string_length(const StringView& string) const; - void set_origin() { auto position = vt_dsr();
5e9a6302e56201488a04f5251e73baa9e4d6e416
2022-01-20 04:34:10
Sam Atkins
libweb: Convert opacity property from Length to Percentage
false
Convert opacity property from Length to Percentage
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp index 11a31740ddc2..b2435104599a 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp @@ -174,11 +174,8 @@ float StyleProperties::opacity() const if (value->has_number()) return clamp(value->to_number(), 0.0f, 1.0f); - if (value->has_length()) { - auto length = value->to_length(); - if (length.is_percentage()) - return clamp(length.raw_value() / 100.0f, 0.0f, 1.0f); - } + if (value->is_percentage()) + return clamp(value->as_percentage().percentage().as_fraction(), 0.0f, 1.0f); return 1.0f; }
1b866bbf42a46afff276f503c1f09844ef5d924a
2020-02-06 18:36:30
Sergey Bugaev
kernel: Fix sys$waitid(P_ALL, WNOHANG) return value
false
Fix sys$waitid(P_ALL, WNOHANG) return value
kernel
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index c1a3092f821a..86d5749dd6f4 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -2314,7 +2314,7 @@ KResultOr<siginfo_t> Process::do_waitid(idtype_t idtype, int id, int options) // FIXME: Figure out what WNOHANG should do with stopped children. if (idtype == P_ALL) { InterruptDisabler disabler; - siginfo_t siginfo; + siginfo_t siginfo = { 0 }; for_each_child([&siginfo](Process& process) { if (process.is_dead()) siginfo = reap(process);
2f790cf78ff781543f27f4136138e3ced7f133ce
2021-09-06 05:25:27
Andreas Kling
kernel: Make MM.commit_user_physical_pages() return KResultOr
false
Make MM.commit_user_physical_pages() return KResultOr
kernel
diff --git a/Kernel/Memory/AnonymousVMObject.cpp b/Kernel/Memory/AnonymousVMObject.cpp index 8789eaae55e0..f332823b89a4 100644 --- a/Kernel/Memory/AnonymousVMObject.cpp +++ b/Kernel/Memory/AnonymousVMObject.cpp @@ -34,9 +34,7 @@ KResultOr<NonnullRefPtr<VMObject>> AnonymousVMObject::try_clone() dbgln_if(COMMIT_DEBUG, "Cloning {:p}, need {} committed cow pages", this, new_cow_pages_needed); - auto committed_pages = MM.commit_user_physical_pages(new_cow_pages_needed); - if (!committed_pages.has_value()) - return ENOMEM; + auto committed_pages = TRY(MM.commit_user_physical_pages(new_cow_pages_needed)); // Create or replace the committed cow pages. When cloning a previously // cloned vmobject, we want to essentially "fork", leaving us and the @@ -44,8 +42,7 @@ KResultOr<NonnullRefPtr<VMObject>> AnonymousVMObject::try_clone() // one would keep the one it still has. This ensures that the original // one and this one, as well as the clone have sufficient resources // to cow all pages as needed - auto new_shared_committed_cow_pages = try_make_ref_counted<SharedCommittedCowPages>(committed_pages.release_value()); - + auto new_shared_committed_cow_pages = try_make_ref_counted<SharedCommittedCowPages>(move(committed_pages)); if (!new_shared_committed_cow_pages) return ENOMEM; @@ -79,9 +76,7 @@ KResultOr<NonnullRefPtr<AnonymousVMObject>> AnonymousVMObject::try_create_with_s { Optional<CommittedPhysicalPageSet> committed_pages; if (strategy == AllocationStrategy::Reserve || strategy == AllocationStrategy::AllocateNow) { - committed_pages = MM.commit_user_physical_pages(ceil_div(size, static_cast<size_t>(PAGE_SIZE))); - if (!committed_pages.has_value()) - return ENOMEM; + committed_pages = TRY(MM.commit_user_physical_pages(ceil_div(size, static_cast<size_t>(PAGE_SIZE)))); } return adopt_nonnull_ref_or_enomem(new (nothrow) AnonymousVMObject(size, strategy, move(committed_pages))); @@ -100,9 +95,7 @@ KResultOr<NonnullRefPtr<AnonymousVMObject>> AnonymousVMObject::try_create_purgea { Optional<CommittedPhysicalPageSet> committed_pages; if (strategy == AllocationStrategy::Reserve || strategy == AllocationStrategy::AllocateNow) { - committed_pages = MM.commit_user_physical_pages(ceil_div(size, static_cast<size_t>(PAGE_SIZE))); - if (!committed_pages.has_value()) - return ENOMEM; + committed_pages = TRY(MM.commit_user_physical_pages(ceil_div(size, static_cast<size_t>(PAGE_SIZE)))); } auto vmobject = adopt_ref_if_nonnull(new (nothrow) AnonymousVMObject(size, strategy, move(committed_pages))); @@ -242,9 +235,7 @@ KResult AnonymousVMObject::set_volatile(bool is_volatile, bool& was_purged) return KSuccess; } - m_unused_committed_pages = MM.commit_user_physical_pages(committed_pages_needed); - if (!m_unused_committed_pages.has_value()) - return ENOMEM; + m_unused_committed_pages = TRY(MM.commit_user_physical_pages(committed_pages_needed)); for (auto& page : m_physical_pages) { if (page->is_shared_zero_page()) diff --git a/Kernel/Memory/MemoryManager.cpp b/Kernel/Memory/MemoryManager.cpp index 3f65dd290cf3..a3f921a50cc9 100644 --- a/Kernel/Memory/MemoryManager.cpp +++ b/Kernel/Memory/MemoryManager.cpp @@ -69,9 +69,9 @@ UNMAP_AFTER_INIT MemoryManager::MemoryManager() protect_kernel_image(); // We're temporarily "committing" to two pages that we need to allocate below - auto committed_pages = commit_user_physical_pages(2); + auto committed_pages = commit_user_physical_pages(2).release_value(); - m_shared_zero_page = committed_pages->take_one(); + m_shared_zero_page = committed_pages.take_one(); // We're wasting a page here, we just need a special tag (physical // address) so that we know when we need to lazily allocate a page @@ -79,7 +79,7 @@ UNMAP_AFTER_INIT MemoryManager::MemoryManager() // than potentially failing if no pages are available anymore. // By using a tag we don't have to query the VMObject for every page // whether it was committed or not - m_lazy_committed_page = committed_pages->take_one(); + m_lazy_committed_page = committed_pages.take_one(); } UNMAP_AFTER_INIT MemoryManager::~MemoryManager() @@ -763,12 +763,12 @@ OwnPtr<Region> MemoryManager::allocate_kernel_region_with_vmobject(VMObject& vmo return allocate_kernel_region_with_vmobject(range.value(), vmobject, name, access, cacheable); } -Optional<CommittedPhysicalPageSet> MemoryManager::commit_user_physical_pages(size_t page_count) +KResultOr<CommittedPhysicalPageSet> MemoryManager::commit_user_physical_pages(size_t page_count) { VERIFY(page_count > 0); SpinlockLocker lock(s_mm_lock); if (m_system_memory_info.user_physical_pages_uncommitted < page_count) - return {}; + return ENOMEM; m_system_memory_info.user_physical_pages_uncommitted -= page_count; m_system_memory_info.user_physical_pages_committed += page_count; diff --git a/Kernel/Memory/MemoryManager.h b/Kernel/Memory/MemoryManager.h index 39f73443b044..2c0fac7375ca 100644 --- a/Kernel/Memory/MemoryManager.h +++ b/Kernel/Memory/MemoryManager.h @@ -171,7 +171,7 @@ class MemoryManager { Yes }; - Optional<CommittedPhysicalPageSet> commit_user_physical_pages(size_t page_count); + KResultOr<CommittedPhysicalPageSet> commit_user_physical_pages(size_t page_count); void uncommit_user_physical_pages(Badge<CommittedPhysicalPageSet>, size_t page_count); NonnullRefPtr<PhysicalPage> allocate_committed_user_physical_page(Badge<CommittedPhysicalPageSet>, ShouldZeroFill = ShouldZeroFill::Yes);
c2be38e50f7c91960bd899dc7f2b6a5028a38bf6
2020-08-23 00:22:19
asynts
ak: TestSuite: Terminate when ASSERT_NOT_REACHED is called.
false
TestSuite: Terminate when ASSERT_NOT_REACHED is called.
ak
diff --git a/AK/TestSuite.h b/AK/TestSuite.h index b1769ba1170b..6098c3b42fb8 100644 --- a/AK/TestSuite.h +++ b/AK/TestSuite.h @@ -40,11 +40,17 @@ fprintf(stderr, "\033[31;1mFAIL\033[0m: %s:%d: RELEASE_ASSERT(%s) failed\n", __FILE__, __LINE__, #x); \ } -#define ASSERT_NOT_REACHED() \ - fprintf(stderr, "\033[31;1mFAIL\033[0m: %s:%d: ASSERT_NOT_REACHED() called\n", __FILE__, __LINE__); +#define ASSERT_NOT_REACHED() \ + { \ + fprintf(stderr, "\033[31;1mFAIL\033[0m: %s:%d: ASSERT_NOT_REACHED() called\n", __FILE__, __LINE__); \ + abort(); \ + } -#define TODO \ - fprintf(stderr, "\033[31;1mFAIL\033[0m: %s:%d: TODO() called\n", __FILE__, __LINE__); +#define TODO() \ + { \ + fprintf(stderr, "\033[31;1mFAIL\033[0m: %s:%d: TODO() called\n", __FILE__, __LINE__); \ + abort(); \ + } #include <stdio.h>
1c7ec9c77023a668ac8e8365b5536836248487c0
2024-02-11 22:21:50
Tommy van der Vorst
libweb: Ignore repeat(auto-fit/auto-fill, auto) as it is not allowed
false
Ignore repeat(auto-fit/auto-fill, auto) as it is not allowed
libweb
diff --git a/Tests/LibWeb/Layout/expected/grid/repeat-auto-fit-fill-cannot-have-auto.txt b/Tests/LibWeb/Layout/expected/grid/repeat-auto-fit-fill-cannot-have-auto.txt new file mode 100644 index 000000000000..357927746836 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/grid/repeat-auto-fit-fill-cannot-have-auto.txt @@ -0,0 +1,62 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x50 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x34 children: not-inline + BlockContainer <div> at (8,8) content-size 784x34 children: not-inline + BlockContainer <(anonymous)> at (8,8) content-size 784x0 children: inline + TextNode <#text> + Box <div.four> at (8,8) content-size 784x34 [GFC] children: not-inline + BlockContainer <(anonymous)> (not painted) [BFC] children: inline + TextNode <#text> + BlockContainer <div> at (8,8) content-size 196x17 [BFC] children: inline + frag 0 from TextNode start: 0, length: 1, rect: [8,8 14.265625x17] baseline: 13.296875 + "A" + TextNode <#text> + BlockContainer <(anonymous)> (not painted) [BFC] children: inline + TextNode <#text> + BlockContainer <div> at (204,8) content-size 196x17 [BFC] children: inline + frag 0 from TextNode start: 0, length: 1, rect: [204,8 9.34375x17] baseline: 13.296875 + "B" + TextNode <#text> + BlockContainer <(anonymous)> (not painted) [BFC] children: inline + TextNode <#text> + BlockContainer <div> at (400,8) content-size 196x17 [BFC] children: inline + frag 0 from TextNode start: 0, length: 1, rect: [400,8 10.3125x17] baseline: 13.296875 + "C" + TextNode <#text> + BlockContainer <(anonymous)> (not painted) [BFC] children: inline + TextNode <#text> + BlockContainer <div> at (596,8) content-size 196x17 [BFC] children: inline + frag 0 from TextNode start: 0, length: 1, rect: [596,8 11.140625x17] baseline: 13.296875 + "D" + TextNode <#text> + BlockContainer <(anonymous)> (not painted) [BFC] children: inline + TextNode <#text> + BlockContainer <div> at (8,25) content-size 196x17 [BFC] children: inline + frag 0 from TextNode start: 0, length: 1, rect: [8,25 11.859375x17] baseline: 13.296875 + "E" + TextNode <#text> + BlockContainer <(anonymous)> (not painted) [BFC] children: inline + TextNode <#text> + BlockContainer <(anonymous)> at (8,42) content-size 784x0 children: inline + TextNode <#text> + BlockContainer <(anonymous)> at (8,42) content-size 784x0 children: inline + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x50] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x34] + PaintableWithLines (BlockContainer<DIV>) [8,8 784x34] + PaintableWithLines (BlockContainer(anonymous)) [8,8 784x0] + PaintableBox (Box<DIV>.four) [8,8 784x34] + PaintableWithLines (BlockContainer<DIV>) [8,8 196x17] + TextPaintable (TextNode<#text>) + PaintableWithLines (BlockContainer<DIV>) [204,8 196x17] + TextPaintable (TextNode<#text>) + PaintableWithLines (BlockContainer<DIV>) [400,8 196x17] + TextPaintable (TextNode<#text>) + PaintableWithLines (BlockContainer<DIV>) [596,8 196x17] + TextPaintable (TextNode<#text>) + PaintableWithLines (BlockContainer<DIV>) [8,25 196x17] + TextPaintable (TextNode<#text>) + PaintableWithLines (BlockContainer(anonymous)) [8,42 784x0] + PaintableWithLines (BlockContainer(anonymous)) [8,42 784x0] diff --git a/Tests/LibWeb/Layout/input/grid/repeat-auto-fit-fill-cannot-have-auto.html b/Tests/LibWeb/Layout/input/grid/repeat-auto-fit-fill-cannot-have-auto.html new file mode 100644 index 000000000000..8c3026f89f03 --- /dev/null +++ b/Tests/LibWeb/Layout/input/grid/repeat-auto-fit-fill-cannot-have-auto.html @@ -0,0 +1,17 @@ +<!DOCTYPE html> +<style> + .four { + display: grid; + grid-template-columns: repeat(4, 1fr); + grid-template-rows: repeat(auto-fit, auto); /* 'auto' not allowed here, line should be ignored */ + } +</style> +<div> +<div class="four"> + <div>A</div> + <div>B</div> + <div>C</div> + <div>D</div> + <div>E</div> +</div> +</div> diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index 264803ae3d88..f38249cb95fd 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -5,6 +5,7 @@ * Copyright (c) 2021, Tobias Christiansen <[email protected]> * Copyright (c) 2022, MacDue <[email protected]> * Copyright (c) 2024, Shannon Booth <[email protected]> + * Copyright (c) 2024, Tommy van der Vorst <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -5469,9 +5470,18 @@ Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& com // The repeat() notation can’t be nested. if (track_sizing_function.value().is_repeat()) return {}; + // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes. - if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit)) + // Note that 'auto' is also an intrinsic size (and thus not permitted) but we can't use + // track_sizing_function.is_auto(..) to check for it, as it requires AvailableSize, which is why there is + // a separate check for it below. + // https://www.w3.org/TR/css-grid-2/#repeat-syntax + // https://www.w3.org/TR/css-grid-2/#intrinsic-sizing-function + if (track_sizing_function.value().is_default() + && (track_sizing_function.value().grid_size().is_flexible_length() || token.is_ident("auto"sv)) + && (is_auto_fill || is_auto_fit)) return {}; + repeat_params.append(track_sizing_function.value()); part_two_tokens.skip_whitespace(); }
f6c52f622dd42a371cfd9b8a621c642b3ee2575b
2023-09-20 02:21:31
Kemal Zebari
ak: Number the spec step comments in `URL::serialize_path()`
false
Number the spec step comments in `URL::serialize_path()`
ak
diff --git a/AK/URL.cpp b/AK/URL.cpp index de14fa611039..f5be7ee34904 100644 --- a/AK/URL.cpp +++ b/AK/URL.cpp @@ -263,21 +263,21 @@ bool URL::is_special_scheme(StringView scheme) // https://url.spec.whatwg.org/#url-path-serializer DeprecatedString URL::serialize_path(ApplyPercentDecoding apply_percent_decoding) const { - // If url has an opaque path, then return url’s path. + // 1. If url has an opaque path, then return url’s path. // FIXME: Reimplement this step once we modernize the URL implementation to meet the spec. if (cannot_be_a_base_url()) return m_paths[0]; - // Let output be the empty string. + // 2. Let output be the empty string. StringBuilder output; - // For each segment of url’s path: append U+002F (/) followed by segment to output. + // 3. For each segment of url’s path: append U+002F (/) followed by segment to output. for (auto const& segment : m_paths) { output.append('/'); output.append(apply_percent_decoding == ApplyPercentDecoding::Yes ? percent_decode(segment) : segment); } - // Return output. + // 4. Return output. return output.to_deprecated_string(); }
d99b1a9ea036d7051e06efd202b28c09b51a59bc
2019-06-21 02:55:25
Andreas Kling
libhtml: Add the outline of a CSS stylesheet object graph.
false
Add the outline of a CSS stylesheet object graph.
libhtml
diff --git a/LibHTML/CSS/Selector.cpp b/LibHTML/CSS/Selector.cpp new file mode 100644 index 000000000000..de7a87d1d42c --- /dev/null +++ b/LibHTML/CSS/Selector.cpp @@ -0,0 +1,9 @@ +#include <LibHTML/CSS/Selector.h> + +Selector::Selector() +{ +} + +Selector::~Selector() +{ +} diff --git a/LibHTML/CSS/Selector.h b/LibHTML/CSS/Selector.h new file mode 100644 index 000000000000..cc87e3465396 --- /dev/null +++ b/LibHTML/CSS/Selector.h @@ -0,0 +1,21 @@ +#pragma once + +#include <AK/AKString.h> +#include <AK/Vector.h> + +class Selector { +public: + Selector(); + ~Selector(); + + struct Component { + enum class Type { Invalid, TagName, Id, Class }; + Type type { Type::Invalid }; + String value; + }; + + const Vector<Component>& components() const { return m_components; } + +private: + Vector<Component> m_components; +}; diff --git a/LibHTML/CSS/StyleDeclaration.cpp b/LibHTML/CSS/StyleDeclaration.cpp new file mode 100644 index 000000000000..187c6ab76694 --- /dev/null +++ b/LibHTML/CSS/StyleDeclaration.cpp @@ -0,0 +1,9 @@ +#include <LibHTML/CSS/StyleDeclaration.h> + +StyleDeclaration::StyleDeclaration() +{ +} + +StyleDeclaration::~StyleDeclaration() +{ +} diff --git a/LibHTML/CSS/StyleDeclaration.h b/LibHTML/CSS/StyleDeclaration.h new file mode 100644 index 000000000000..558e08492583 --- /dev/null +++ b/LibHTML/CSS/StyleDeclaration.h @@ -0,0 +1,17 @@ +#pragma once + +#include <AK/AKString.h> +#include <LibHTML/CSS/StyleValue.h> + +class StyleDeclaration { +public: + StyleDeclaration(); + ~StyleDeclaration(); + + const String& property_name() const { return m_property_name; } + const StyleValue& value() const { return *m_value; } + +public: + String m_property_name; + RetainPtr<StyleValue> m_value; +}; diff --git a/LibHTML/CSS/StyleRule.cpp b/LibHTML/CSS/StyleRule.cpp new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/LibHTML/CSS/StyleRule.h b/LibHTML/CSS/StyleRule.h new file mode 100644 index 000000000000..657d851d951a --- /dev/null +++ b/LibHTML/CSS/StyleRule.h @@ -0,0 +1,15 @@ +#pragma once + +#include <AK/Vector.h> +#include <LibHTML/CSS/Selector.h> +#include <LibHTML/CSS/StyleDeclaration.h> + +class StyleRule { +public: + StyleRule(); + ~StyleRule(); + +private: + Vector<Selector> m_selectors; + Vector<StyleDeclaration> m_declarations; +}; diff --git a/LibHTML/CSS/StyleSheet.cpp b/LibHTML/CSS/StyleSheet.cpp new file mode 100644 index 000000000000..840b46835b55 --- /dev/null +++ b/LibHTML/CSS/StyleSheet.cpp @@ -0,0 +1,9 @@ +#include <LibHTML/CSS/StyleSheet.h> + +StyleSheet::StyleSheet() +{ +} + +StyleSheet::~StyleSheet() +{ +} diff --git a/LibHTML/CSS/StyleSheet.h b/LibHTML/CSS/StyleSheet.h new file mode 100644 index 000000000000..7089b59e671c --- /dev/null +++ b/LibHTML/CSS/StyleSheet.h @@ -0,0 +1,15 @@ +#pragma once + +#include <AK/Vector.h> +#include <LibHTML/CSS/StyleRule.h> + +class StyleSheet { +public: + StyleSheet(); + ~StyleSheet(); + + const Vector<StyleRule>& rules() const { return m_rules; } + +private: + Vector<StyleRule> m_rules; +}; diff --git a/LibHTML/CSS/StyleValue.cpp b/LibHTML/CSS/StyleValue.cpp new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/LibHTML/CSS/StyleValue.h b/LibHTML/CSS/StyleValue.h new file mode 100644 index 000000000000..1796f86b0bc2 --- /dev/null +++ b/LibHTML/CSS/StyleValue.h @@ -0,0 +1,23 @@ +#pragma once + +#include <AK/Retainable.h> + +class StyleValue : public Retainable<StyleValue> { +public: + virtual ~StyleValue(); + + enum Type { + Invalid, + Inherit, + Initial, + Primitive, + }; + + Type type() const { return m_type; } + +protected: + explicit StyleValue(Type); + +private: + Type m_type { Type::Invalid }; +}; diff --git a/LibHTML/Makefile b/LibHTML/Makefile index 1b068adc31e9..1e3039fb72ef 100644 --- a/LibHTML/Makefile +++ b/LibHTML/Makefile @@ -6,6 +6,11 @@ LIBHTML_OBJS = \ DOM/Element.o \ DOM/Document.o \ DOM/Text.o \ + CSS/Selector.o \ + CSS/StyleSheet.o \ + CSS/StyleRule.o \ + CSS/StyleDeclaration.o \ + CSS/StyleValue.o \ Parser/Parser.o \ Layout/LayoutNode.o \ Layout/LayoutText.o \
81b9a2e4a12087806eb82c582c6eb130805ab0fa
2022-06-15 22:19:20
Linus Groh
libjs: Mark a call of CreateDateDurationRecord as fallible
false
Mark a call of CreateDateDurationRecord as fallible
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp index 0470fe5b2c5f..1b3efe7f81bf 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp @@ -757,8 +757,8 @@ ThrowCompletionOr<DateDurationRecord> unbalance_duration_relative(GlobalObject& } } - // 12. Return ! CreateDateDurationRecord(years, months, weeks, days). - return create_date_duration_record(years, months, weeks, days); + // 12. Return ? CreateDateDurationRecord(years, months, weeks, days). + return create_date_duration_record(global_object, years, months, weeks, days); } // 7.5.20 BalanceDurationRelative ( years, months, weeks, days, largestUnit, relativeTo ), https://tc39.es/proposal-temporal/#sec-temporal-balancedurationrelative
21ccbc2167dc426f825867ac87d79928c2acdd4f
2020-12-27 05:46:56
Andreas Kling
kernel: Expose process executable paths in /proc/all
false
Expose process executable paths in /proc/all
kernel
diff --git a/Kernel/FileSystem/ProcFS.cpp b/Kernel/FileSystem/ProcFS.cpp index 3d281305c25e..a81cbf575d3c 100644 --- a/Kernel/FileSystem/ProcFS.cpp +++ b/Kernel/FileSystem/ProcFS.cpp @@ -872,6 +872,7 @@ static OwnPtr<KBuffer> procfs$all(InodeIdentifier) process_object.add("ppid", process.ppid().value()); process_object.add("nfds", process.number_of_open_file_descriptors()); process_object.add("name", process.name()); + process_object.add("executable", process.executable() ? process.executable()->absolute_path() : ""); process_object.add("tty", process.tty() ? process.tty()->tty_name() : "notty"); process_object.add("amount_virtual", process.amount_virtual()); process_object.add("amount_resident", process.amount_resident()); diff --git a/Kernel/Process.h b/Kernel/Process.h index aebd5dc3f8c2..879b8db96cd0 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -391,10 +391,8 @@ class Process u32 m_ticks_in_kernel_for_dead_children { 0 }; Custody& current_directory(); - Custody* executable() - { - return m_executable.ptr(); - } + Custody* executable() { return m_executable.ptr(); } + const Custody* executable() const { return m_executable.ptr(); } int number_of_open_file_descriptors() const; int max_open_file_descriptors() const diff --git a/Libraries/LibCore/ProcessStatisticsReader.cpp b/Libraries/LibCore/ProcessStatisticsReader.cpp index 5a0ff949c6d2..948e25aa3c72 100644 --- a/Libraries/LibCore/ProcessStatisticsReader.cpp +++ b/Libraries/LibCore/ProcessStatisticsReader.cpp @@ -64,6 +64,7 @@ HashMap<pid_t, Core::ProcessStatistics> ProcessStatisticsReader::get_all() process.ppid = process_object.get("ppid").to_u32(); process.nfds = process_object.get("nfds").to_u32(); process.name = process_object.get("name").to_string(); + process.executable = process_object.get("executable").to_string(); process.tty = process_object.get("tty").to_string(); process.pledge = process_object.get("pledge").to_string(); process.veil = process_object.get("veil").to_string(); diff --git a/Libraries/LibCore/ProcessStatisticsReader.h b/Libraries/LibCore/ProcessStatisticsReader.h index 9c3bd93a80ff..0e4765d90631 100644 --- a/Libraries/LibCore/ProcessStatisticsReader.h +++ b/Libraries/LibCore/ProcessStatisticsReader.h @@ -66,6 +66,7 @@ struct ProcessStatistics { pid_t ppid; unsigned nfds; String name; + String executable; String tty; String pledge; String veil;
95b49691c50fb84e2692eedbd121fa109af94c28
2021-03-04 03:38:25
Elliot Maisl
documentation: Add instruction about entitlements in BuildInstructions
false
Add instruction about entitlements in BuildInstructions
documentation
diff --git a/Documentation/BuildInstructions.md b/Documentation/BuildInstructions.md index cd52af800965..522f984296ca 100644 --- a/Documentation/BuildInstructions.md +++ b/Documentation/BuildInstructions.md @@ -113,6 +113,23 @@ Notes: - bash is needed because the default version installed on macOS doesn't support globstar - If you install some commercial EXT2 macOS fs handler instead of osxfuse and fuse-ext2, you will need to `brew install e2fsprogs` to obtain `mke2fs` anyway. - As of 2020-08-06, you might need to tell the build system about your newer host compiler. Once you've built the toolchain, navigate to `Build/`, `rm -rf *`, then run `cmake .. -G Ninja -DCMAKE_C_COMPILER=gcc-10 -DCMAKE_CXX_COMPILER=g++-10`, then continue with `ninja install` as usual. +- If you are on macOS Big Sur, you will need to manually enable QEMU's acceleration before running Serenity, by creating a new file called `entitlements.xml` in the `Build/` folder, with the content below, and then run the command: `codesign -s - --entitlements entitlements.xml --force /usr/local/bin/qemu-system-x86_64`; otherwise the run command will fail. + +<details> +<summary>Content for 'entitlements.xml'.</summary> + +```xml +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" + "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>com.apple.security.hypervisor</key> + <true/> +</dict> +</plist> +``` +</details> #### OpenBSD prerequisites ```
629068c2a7eb02db37ffb4fe8d536306ee71e156
2024-07-10 10:35:52
rmg-x
libweb: Ensure normal line-height on `HTMLInputElement`
false
Ensure normal line-height on `HTMLInputElement`
libweb
diff --git a/Tests/LibWeb/Layout/expected/css-line-height-zero.txt b/Tests/LibWeb/Layout/expected/css-line-height-zero.txt new file mode 100644 index 000000000000..622f303c9c4e --- /dev/null +++ b/Tests/LibWeb/Layout/expected/css-line-height-zero.txt @@ -0,0 +1,19 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x37 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x21 children: inline + frag 0 from BlockContainer start: 0, length: 0, rect: [9,9 191.875x19] baseline: 13.296875 + BlockContainer <input> at (9,9) content-size 191.875x19 inline-block [BFC] children: not-inline + Box <div> at (11,10) content-size 187.875x17 flex-container(row) [FFC] children: not-inline + BlockContainer <div> at (11,10) content-size 187.875x17 flex-item [BFC] children: inline + frag 0 from TextNode start: 0, length: 11, rect: [11,10 91.953125x17] baseline: 13.296875 + "Hello World" + TextNode <#text> + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x37] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x21] + PaintableWithLines (BlockContainer<INPUT>) [8,8 193.875x21] + PaintableBox (Box<DIV>) [9,9 191.875x19] + PaintableWithLines (BlockContainer<DIV>) [11,10 187.875x17] + TextPaintable (TextNode<#text>) diff --git a/Tests/LibWeb/Layout/input/css-line-height-zero.html b/Tests/LibWeb/Layout/input/css-line-height-zero.html new file mode 100644 index 000000000000..76faff47c20d --- /dev/null +++ b/Tests/LibWeb/Layout/input/css-line-height-zero.html @@ -0,0 +1,5 @@ +<!DOCTYPE html><html><head><style> + input { + line-height: 0; + } + </style></head><body><input type="text" value="Hello World"> diff --git a/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp index bd5a57efdec5..890bc5e05b0c 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp @@ -127,6 +127,14 @@ void HTMLInputElement::adjust_computed_style(CSS::StyleProperties& style) if (style.property(CSS::PropertyID::Width)->has_auto()) style.set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length(size(), CSS::Length::Type::Ch))); } + + // NOTE: The following line-height check is done for web compatability and usability reasons. + // FIXME: The "normal" line-height value should be calculated but assume 1.0 for now. + double normal_line_height = 1.0; + double current_line_height = style.line_height().to_double(); + + if (is_single_line() && current_line_height < normal_line_height) + style.set_property(CSS::PropertyID::LineHeight, CSS::IdentifierStyleValue::create(CSS::ValueID::Normal)); } void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
86290c0e4efdbc0618d232a509f59ff8a08f9fc5
2021-04-12 21:17:59
Egor Ananyin
libweb: Set border width to zero if style is none
false
Set border width to zero if style is none
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp index 0706e23fe521..48dccbcbcdae 100644 --- a/Userland/Libraries/LibWeb/Layout/Node.cpp +++ b/Userland/Libraries/LibWeb/Layout/Node.cpp @@ -307,9 +307,12 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& specified_style) computed_values.set_padding(specified_style.length_box(CSS::PropertyID::PaddingLeft, CSS::PropertyID::PaddingTop, CSS::PropertyID::PaddingRight, CSS::PropertyID::PaddingBottom, CSS::Length::make_px(0))); auto do_border_style = [&](CSS::BorderData& border, CSS::PropertyID width_property, CSS::PropertyID color_property, CSS::PropertyID style_property) { - border.width = specified_style.length_or_fallback(width_property, {}).resolved_or_zero(*this, 0).to_px(*this); border.color = specified_style.color_or_fallback(color_property, document(), Color::Transparent); border.line_style = specified_style.line_style(style_property).value_or(CSS::LineStyle::None); + if (border.line_style == CSS::LineStyle::None) + border.width = 0; + else + border.width = specified_style.length_or_fallback(width_property, {}).resolved_or_zero(*this, 0).to_px(*this); }; do_border_style(computed_values.border_left(), CSS::PropertyID::BorderLeftWidth, CSS::PropertyID::BorderLeftColor, CSS::PropertyID::BorderLeftStyle);
832127121be9102e8bd6916449b1e493ae78e378
2021-06-09 23:34:25
Jelle Raaijmakers
ports: Update SQLite to version 3.35.5
false
Update SQLite to version 3.35.5
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index 91cd4852777d..950fb47dc6d2 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -123,7 +123,7 @@ Please make sure to keep this list up to date when adding and updating ports. :^ | [`SDL2_ttf`](SDL2_ttf/) | SDL2\_ttf (TrueType Font add-on for SDL2) | 2.0.15 | https://www.libsdl.org/projects/SDL_ttf/ | | [`sed`](sed/) | GNU sed | 4.2.1 | https://www.gnu.org/software/sed/ | | [`sl`](sl/) | Steam Locomotive (SL) | | https://github.com/mtoyoda/sl | -| [`sqlite`](sqlite/) | SQLite | 3350300 | https://www.sqlite.org/ | +| [`sqlite`](sqlite/) | SQLite | 3350500 | https://www.sqlite.org/ | | [`stpuzzles`](stpuzzles/) | Simon Tatham's Portable Puzzle Collection | | https://www.chiark.greenend.org.uk/~sgtatham/puzzles/ | | [`stress-ng`](stress-ng/) | stress-ng | 0.11.23 | https://github.com/ColinIanKing/stress-ng | | [`Super-Mario`](Super-Mario/) | Super-Mario Clone | | https://github.com/Bennyhwanggggg/Super-Mario-Clone-Cpp | diff --git a/Ports/sqlite/package.sh b/Ports/sqlite/package.sh index f0672d68525c..82e00096d287 100755 --- a/Ports/sqlite/package.sh +++ b/Ports/sqlite/package.sh @@ -1,7 +1,7 @@ #!/usr/bin/env -S bash ../.port_include.sh port=sqlite useconfigure="true" -version="3350300" -files="https://www.sqlite.org/2021/sqlite-autoconf-${version}.tar.gz sqlite-autoconf-${version}.tar.gz ecbccdd440bdf32c0e1bb3611d635239e3b5af268248d130d0445a32daf0274b" +version="3350500" +files="https://www.sqlite.org/2021/sqlite-autoconf-${version}.tar.gz sqlite-autoconf-${version}.tar.gz f52b72a5c319c3e516ed7a92e123139a6e87af08a2dc43d7757724f6132e6db0" auth_type=sha256 workdir="sqlite-autoconf-${version}"
f4ddca0a73fb2d911a7c068cc38524806ff8d748
2020-07-10 23:59:44
Andreas Kling
userspaceemulator: Warn in SoftMMU if accessing unknown memory
false
Warn in SoftMMU if accessing unknown memory
userspaceemulator
diff --git a/DevTools/UserspaceEmulator/SoftMMU.cpp b/DevTools/UserspaceEmulator/SoftMMU.cpp index 1de7fcde35d0..cc3174a3e20d 100644 --- a/DevTools/UserspaceEmulator/SoftMMU.cpp +++ b/DevTools/UserspaceEmulator/SoftMMU.cpp @@ -48,6 +48,7 @@ u8 SoftMMU::read8(u32 address) { auto* region = find_region(address); if (!region) { + warn() << "SoftMMU::read8: No region for @" << (const void*)address; TODO(); } @@ -58,6 +59,7 @@ u16 SoftMMU::read16(u32 address) { auto* region = find_region(address); if (!region) { + warn() << "SoftMMU::read16: No region for @" << (const void*)address; TODO(); } @@ -68,6 +70,7 @@ u32 SoftMMU::read32(u32 address) { auto* region = find_region(address); if (!region) { + warn() << "SoftMMU::read32: No region for @" << (const void*)address; TODO(); } @@ -78,6 +81,7 @@ void SoftMMU::write8(u32 address, u8 value) { auto* region = find_region(address); if (!region) { + warn() << "SoftMMU::write8: No region for @" << (const void*)address; TODO(); } @@ -88,6 +92,7 @@ void SoftMMU::write16(u32 address, u16 value) { auto* region = find_region(address); if (!region) { + warn() << "SoftMMU::write16: No region for @" << (const void*)address; TODO(); } @@ -98,6 +103,7 @@ void SoftMMU::write32(u32 address, u32 value) { auto* region = find_region(address); if (!region) { + warn() << "SoftMMU::write32: No region for @" << (const void*)address; TODO(); }
821ae3a4798b01eeca44304b4145f899011d1c1b
2022-02-10 19:39:39
davidot
libjs: Add tests for Set.prototype.keys which is an alias for values
false
Add tests for Set.prototype.keys which is an alias for values
libjs
diff --git a/Userland/Libraries/LibJS/Tests/builtins/Set/Set.prototype.values.js b/Userland/Libraries/LibJS/Tests/builtins/Set/Set.prototype.values.js index 2b6a0db26261..3dc85cde029e 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/Set/Set.prototype.values.js +++ b/Userland/Libraries/LibJS/Tests/builtins/Set/Set.prototype.values.js @@ -12,3 +12,20 @@ test("basic functionality", () => { expect(it.next()).toEqual({ value: undefined, done: true }); expect(it.next()).toEqual({ value: undefined, done: true }); }); + +describe("keys is an alias for values", () => { + test("length", () => { + expect(Set.prototype.keys.length).toBe(0); + }); + + test("basic functionality", () => { + const a = new Set([1, 2, 3]); + const it = a.keys(); + expect(it.next()).toEqual({ value: 1, done: false }); + expect(it.next()).toEqual({ value: 2, done: false }); + expect(it.next()).toEqual({ value: 3, done: false }); + expect(it.next()).toEqual({ value: undefined, done: true }); + expect(it.next()).toEqual({ value: undefined, done: true }); + expect(it.next()).toEqual({ value: undefined, done: true }); + }); +});
b19fe744ab7dbdb66e59853d427e38890646bb14
2021-08-13 00:40:44
Daniel Bertalan
libweb: Remove pointless type casts
false
Remove pointless type casts
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp b/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp index 936d77a414bb..dd98da083e69 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleResolver.cpp @@ -68,8 +68,6 @@ Vector<MatchingRule> StyleResolver::collect_matching_rules(DOM::Element const& e size_t style_sheet_index = 0; for_each_stylesheet([&](auto& sheet) { - if (!is<CSSStyleSheet>(sheet)) - return; size_t rule_index = 0; static_cast<CSSStyleSheet const&>(sheet).for_each_effective_style_rule([&](auto& rule) { size_t selector_index = 0; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLFormElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLFormElement.cpp index 1d94ea1f908a..156f521157cc 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLFormElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLFormElement.cpp @@ -97,8 +97,7 @@ void HTMLFormElement::submit_form(RefPtr<HTMLElement> submitter, bool from_submi Vector<URLQueryParam> parameters; - for_each_in_inclusive_subtree_of_type<HTMLInputElement>([&](auto& node) { - auto& input = verify_cast<HTMLInputElement>(node); + for_each_in_inclusive_subtree_of_type<HTMLInputElement>([&](auto& input) { if (!input.name().is_null() && (input.type() != "submit" || &input == submitter)) parameters.append({ input.name(), input.value() }); return IterationDecision::Continue;
9d2377ff6055d07d16d3d9fa90fa79aa9716ce50
2022-06-15 22:19:20
Linus Groh
libjs: Only call CanonicalizeTimeZoneName on valid time zone IDs
false
Only call CanonicalizeTimeZoneName on valid time zone IDs
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp index 224ef04e4c3a..4248f74ef8e9 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp @@ -450,12 +450,12 @@ ThrowCompletionOr<Object*> to_temporal_time_zone(GlobalObject& global_object, Va // TimeZoneIANAName for the returned [[Name]] slot, not TimeZoneUTCOffsetName. // So when we provide a numeric time zone offset, this branch won't be executed, // and if we provide an IANA name, it won't be a valid TimeZoneNumericUTCOffset. - // This should be fixed by: https://github.com/tc39/proposal-temporal/pull/1941 + // This should be fixed by: https://github.com/tc39/proposal-temporal/pull/2200 // 4. If parseResult.[[Name]] is not undefined, then if (parse_result.name.has_value()) { // a. Let name be parseResult.[[Name]]. - auto& name = *parse_result.name; + auto name = parse_result.name.release_value(); // b. If ParseText(StringToCodePoints(name, TimeZoneNumericUTCOffset)) is not a List of errors, then if (is_valid_time_zone_numeric_utc_offset_syntax(name)) { @@ -468,10 +468,13 @@ ThrowCompletionOr<Object*> to_temporal_time_zone(GlobalObject& global_object, Va // i. If IsValidTimeZoneName(name) is false, throw a RangeError exception. if (!is_valid_time_zone_name(name)) return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneName, name); + + // ii. Set name to ! CanonicalizeTimeZoneName(name). + name = canonicalize_time_zone_name(name); } - // c. Return ! CreateTemporalTimeZone(! CanonicalizeTimeZoneName(name)). - return MUST(create_temporal_time_zone(global_object, canonicalize_time_zone_name(name))); + // c. Return ! CreateTemporalTimeZone(name). + return MUST(create_temporal_time_zone(global_object, name)); } // 5. If parseResult.[[Z]] is true, return ! CreateTemporalTimeZone("UTC").
558fd5b1661070caa08e0f3f1f00f661e7226001
2022-01-06 16:00:04
Jelle Raaijmakers
libcore: Make `EventLoop::pump()` return event count
false
Make `EventLoop::pump()` return event count
libcore
diff --git a/Userland/Libraries/LibCore/EventLoop.cpp b/Userland/Libraries/LibCore/EventLoop.cpp index 7859a9429d19..40b560874725 100644 --- a/Userland/Libraries/LibCore/EventLoop.cpp +++ b/Userland/Libraries/LibCore/EventLoop.cpp @@ -379,7 +379,7 @@ void EventLoop::spin_until(Function<bool()> goal_condition) pump(); } -void EventLoop::pump(WaitMode mode) +size_t EventLoop::pump(WaitMode mode) { wait_for_event(mode); @@ -389,6 +389,7 @@ void EventLoop::pump(WaitMode mode) events = move(m_queued_events); } + size_t processed_events = 0; for (size_t i = 0; i < events.size(); ++i) { auto& queued_event = events.at(i); auto receiver = queued_event.receiver.strong_ref(); @@ -400,7 +401,6 @@ void EventLoop::pump(WaitMode mode) switch (event.type()) { case Event::Quit: VERIFY_NOT_REACHED(); - return; default: dbgln_if(EVENTLOOP_DEBUG, "Event type {} with no receiver :(", event.type()); break; @@ -412,6 +412,7 @@ void EventLoop::pump(WaitMode mode) NonnullRefPtr<Object> protector(*receiver); receiver->dispatch_event(event); } + ++processed_events; if (m_exit_requested) { Threading::MutexLocker locker(m_private->lock); @@ -422,9 +423,11 @@ void EventLoop::pump(WaitMode mode) new_event_queue.unchecked_append(move(events[i])); new_event_queue.extend(move(m_queued_events)); m_queued_events = move(new_event_queue); - return; + break; } } + + return processed_events; } void EventLoop::post_event(Object& receiver, NonnullOwnPtr<Event>&& event) diff --git a/Userland/Libraries/LibCore/EventLoop.h b/Userland/Libraries/LibCore/EventLoop.h index 9b1a660e800c..672b8b3f2d76 100644 --- a/Userland/Libraries/LibCore/EventLoop.h +++ b/Userland/Libraries/LibCore/EventLoop.h @@ -42,7 +42,7 @@ class EventLoop { // processe events, generally called by exec() in a loop. // this should really only be used for integrating with other event loops - void pump(WaitMode = WaitMode::WaitForEvents); + size_t pump(WaitMode = WaitMode::WaitForEvents); void spin_until(Function<bool()>);
41d2c674d764314c2930bcf4bfcf2992bf6b5cb8
2019-07-16 14:33:38
Robin Burchell
ak: Add a new TestSuite.h from my own work, adapted to match the existing one a bit
false
Add a new TestSuite.h from my own work, adapted to match the existing one a bit
ak
diff --git a/AK/TestSuite.h b/AK/TestSuite.h new file mode 100644 index 000000000000..73f166d0c4c2 --- /dev/null +++ b/AK/TestSuite.h @@ -0,0 +1,241 @@ +#pragma once + +#include "AKString.h" +#include "Function.h" +#include "NonnullRefPtrVector.h" +#include <chrono> + +namespace AK { + +class TestElapsedTimer { + typedef std::chrono::high_resolution_clock clock; + +public: + TestElapsedTimer() { restart(); } + void restart() { m_started = clock::now(); } + int64_t elapsed() + { + auto end = clock::now(); + auto elapsed = end - m_started; + return std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count(); + } + +private: + std::chrono::time_point<clock> m_started; +}; + +class TestException { +public: + TestException(const String& file, int line, const String& s) + : file(file) + , line(line) + , reason(s) + { + } + + String to_string() const + { + String outfile = file; + // ### + //auto slash = file.lastIndexOf("/"); + //if (slash > 0) { + // outfile = outfile.right(outfile.length() - slash - 1); + //} + return String::format("%s:%d: %s", outfile.characters(), line, reason.characters()); + } + +private: + String file; + int line = 0; + String reason; +}; + +typedef AK::Function<void()> TestFunction; + +class TestCase : public RefCounted<TestCase> { +public: + TestCase(const String& name, TestFunction&& fn, bool is_benchmark) + : m_name(name) + , m_function(move(fn)) + , m_is_benchmark(is_benchmark) + { + } + + bool is_benchmark() const { return m_is_benchmark; } + const String& name() const { return m_name; } + const TestFunction& func() const { return m_function; } + +private: + String m_name; + TestFunction m_function; + bool m_is_benchmark; +}; + +class TestSuite { +public: + static TestSuite* instance() + { + if (s_global == nullptr) + s_global = new TestSuite(); + return s_global; + } + void run(const NonnullRefPtrVector<TestCase>& tests); + void main(const String& suite_name, int argc, char** argv); + NonnullRefPtrVector<TestCase> find_cases(const String& search, bool find_tests, bool find_benchmarks); + void add_case(const NonnullRefPtr<TestCase>& test_case) + { + m_cases.append(test_case); + } + +private: + static TestSuite* s_global; + NonnullRefPtrVector<TestCase> m_cases; + uint64_t m_testtime = 0; + uint64_t m_benchtime = 0; + String m_suite_name; +}; + +void TestSuite::main(const String& suite_name, int argc, char** argv) +{ + m_suite_name = suite_name; + bool find_tests = true; + bool find_benchmarks = true; + + String search_string; + for (int i = 1; i < argc; i++) { + if (!String(argv[i]).starts_with("--")) { + search_string = argv[i]; + } else if (String(argv[i]) == String("--bench")) { + find_tests = false; + } else if (String(argv[i]) == String("--test")) { + find_benchmarks = false; + } else if (String(argv[i]) == String("--help")) { + dbg() << "Available tests for " << suite_name << ":"; + const auto& tests = find_cases("*", true, false); + for (const auto& t : tests) { + dbg() << "\t" << t.name(); + } + dbg() << "Available benchmarks for " << suite_name << ":"; + const auto& benches = find_cases("*", false, true); + for (const auto& t : benches) { + dbg() << "\t" << t.name(); + } + exit(0); + } + } + + const auto& matches = find_cases(search_string, find_tests, find_benchmarks); + if (matches.size() == 0) { + dbg() << "0 matches when searching for " << search_string << " (out of " << m_cases.size() << ")"; + exit(1); + } + dbg() << "Running " << matches.size() << " cases out of " << m_cases.size(); + run(matches); +} + +NonnullRefPtrVector<TestCase> TestSuite::find_cases(const String& search, bool find_tests, bool find_benchmarks) +{ + NonnullRefPtrVector<TestCase> matches; + for (const auto& t : m_cases) { + if (!search.is_empty() && !t.name().matches(search, String::CaseSensitivity::CaseInsensitive)) { + continue; + } + + if (!find_tests && !t.is_benchmark()) { + continue; + } + if (!find_benchmarks && t.is_benchmark()) { + continue; + } + + matches.append(t); + } + return matches; +} + +void TestSuite::run(const NonnullRefPtrVector<TestCase>& tests) +{ + int test_count = 0; + int benchmark_count = 0; + TestElapsedTimer global_timer; + for (const auto& t : tests) { + dbg() << "START Running " << (t.is_benchmark() ? "benchmark" : "test") << " " << t.name(); + TestElapsedTimer timer; + try { + t.func(); + } catch (const TestException& t) { + fprintf(stderr, "\033[31;1mFAIL\033[0m: %s\n", t.to_string().characters()); + exit(1); + } + auto time = timer.elapsed(); + fprintf(stderr, "\033[32;1mPASS\033[0m: %d ms running %s %s\n", (int)time, (t.is_benchmark() ? "benchmark" : "test"), t.name().characters()); + if (t.is_benchmark()) { + m_benchtime += time; + benchmark_count++; + } else { + m_testtime += time; + test_count++; + } + } + dbg() << "Finished " << test_count << " tests and " << benchmark_count << " benchmarks in " << (int)global_timer.elapsed() << " ms (" + << (int)m_testtime << " tests, " << (int)m_benchtime << " benchmarks, " << int(global_timer.elapsed() - (m_testtime + m_benchtime)) << " other)"; +} + +} + +using AK::TestCase; +using AK::TestException; +using AK::TestSuite; + +#define xstr(s) ___str(s) +#define ___str(s) #s + +#define TESTCASE_TYPE_NAME(x) TestCase_##x + +/*! Define a test case function. */ +#define TEST_CASE(x) \ + static void x(); \ + struct TESTCASE_TYPE_NAME(x) { \ + TESTCASE_TYPE_NAME(x) \ + () { TestSuite::instance()->add_case(adopt(*new TestCase(___str(x), x, false))); } \ + }; \ + static struct TESTCASE_TYPE_NAME(x) TESTCASE_TYPE_NAME(x); \ + static void x() + +#define BENCHMARK_TYPE_NAME(x) TestCase_##x + +#define BENCHMARK_CASE(x) \ + static void x(); \ + struct BENCHMARK_TYPE_NAME(x) { \ + BENCHMARK_TYPE_NAME(x) \ + () { TestSuite::instance()->add_case(adopt(*new TestCase(___str(x), x, true))); } \ + }; \ + static struct BENCHMARK_TYPE_NAME(x) BENCHMARK_TYPE_NAME(x); \ + static void x() + +/*! Define the main function of the testsuite. All TEST_CASE functions will be executed. */ +#define TEST_MAIN(SuiteName) \ + TestSuite* TestSuite::s_global = nullptr; \ + template<size_t N> \ + constexpr size_t compiletime_lenof(const char(&)[N]) \ + { \ + return N - 1; \ + } \ + int main(int argc, char** argv) \ + { \ + static_assert(compiletime_lenof(___str(SuiteName)) != 0, "Set SuiteName"); \ + TestSuite::instance()->main(___str(SuiteName), argc, argv); \ + } + +#define assertEqual(one, two) \ + do { \ + auto ___aev1 = one; \ + auto ___aev2 = two; \ + if (___aev1 != ___aev2) { \ + const auto& msg = String::format("\033[31;1mFAIL\033[0m: assertEqual(" ___str(one) ", " ___str(two) ") failed"); \ + } \ + } while (0) + +#define EXPECT_EQ(one, two) assertEqual(one, two) + +#define EXPECT(one) assertEqual(one, true) diff --git a/AK/Tests/Makefile b/AK/Tests/Makefile index ecfc22750e11..04acb7a27036 100644 --- a/AK/Tests/Makefile +++ b/AK/Tests/Makefile @@ -4,20 +4,20 @@ all: $(PROGRAMS) CXXFLAGS = -std=c++17 -Wall -Wextra -TestString: TestString.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp TestHelpers.h - $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestString.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp +TestString: TestString.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../TestSuite.h ../LogStream.cpp + $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestString.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../LogStream.cpp -TestQueue: TestQueue.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp TestHelpers.h - $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestQueue.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp +TestQueue: TestQueue.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../TestSuite.h ../LogStream.cpp + $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestQueue.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../LogStream.cpp -TestVector: TestVector.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp TestHelpers.h - $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestVector.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp +TestVector: TestVector.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../TestSuite.h ../LogStream.cpp + $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestVector.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../LogStream.cpp -TestHashMap: TestHashMap.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp TestHelpers.h - $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestHashMap.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp +TestHashMap: TestHashMap.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../TestSuite.h ../LogStream.cpp + $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestHashMap.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../LogStream.cpp -TestJSON: TestJSON.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp TestHelpers.h ../JsonObject.cpp ../JsonValue.cpp ../JsonArray.cpp ../JsonParser.cpp - $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestJSON.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../JsonObject.cpp ../JsonValue.cpp ../JsonArray.cpp ../JsonParser.cpp +TestJSON: TestJSON.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../TestSuite.h ../LogStream.cpp ../JsonObject.cpp ../JsonValue.cpp ../JsonArray.cpp ../JsonParser.cpp + $(CXX) $(CXXFLAGS) -I../ -I../../ -o $@ TestJSON.cpp ../String.cpp ../StringImpl.cpp ../StringBuilder.cpp ../StringView.cpp ../LogStream.cpp ../JsonObject.cpp ../JsonValue.cpp ../JsonArray.cpp ../JsonParser.cpp clean: rm -f $(PROGRAMS) diff --git a/AK/Tests/TestHashMap.cpp b/AK/Tests/TestHashMap.cpp index 55455b1d16a8..06ada6445947 100644 --- a/AK/Tests/TestHashMap.cpp +++ b/AK/Tests/TestHashMap.cpp @@ -1,27 +1,46 @@ -#include "TestHelpers.h" +#include <AK/TestSuite.h> #include <AK/AKString.h> #include <AK/HashMap.h> -typedef HashMap<int, int> IntIntMap; - -int main() +TEST_CASE(construct) { + typedef HashMap<int, int> IntIntMap; EXPECT(IntIntMap().is_empty()); - EXPECT(IntIntMap().size() == 0); + EXPECT_EQ(IntIntMap().size(), 0); +} +TEST_CASE(populate) +{ HashMap<int, String> number_to_string; number_to_string.set(1, "One"); number_to_string.set(2, "Two"); number_to_string.set(3, "Three"); - + EXPECT_EQ(number_to_string.is_empty(), false); EXPECT_EQ(number_to_string.size(), 3); +} + +TEST_CASE(range_loop) +{ + HashMap<int, String> number_to_string; + number_to_string.set(1, "One"); + number_to_string.set(2, "Two"); + number_to_string.set(3, "Three"); int loop_counter = 0; for (auto& it : number_to_string) { - EXPECT(!it.value.is_null()); + EXPECT_EQ(it.value.is_null(), false); ++loop_counter; } + EXPECT_EQ(loop_counter, 3); +} + +TEST_CASE(map_remove) +{ + HashMap<int, String> number_to_string; + number_to_string.set(1, "One"); + number_to_string.set(2, "Two"); + number_to_string.set(3, "Three"); number_to_string.remove(1); EXPECT_EQ(number_to_string.size(), 2); @@ -30,16 +49,16 @@ int main() number_to_string.remove(3); EXPECT_EQ(number_to_string.size(), 1); EXPECT(number_to_string.find(3) == number_to_string.end()); + EXPECT(number_to_string.find(2) != number_to_string.end()); +} - EXPECT_EQ(loop_counter, 3); - - { - HashMap<String, int, CaseInsensitiveStringTraits> casemap; - EXPECT_EQ(String("nickserv").to_lowercase(), String("NickServ").to_lowercase()); - casemap.set("nickserv", 3); - casemap.set("NickServ", 3); - EXPECT_EQ(casemap.size(), 1); - } - - return 0; +TEST_CASE(case_insensitive) +{ + HashMap<String, int, CaseInsensitiveStringTraits> casemap; + EXPECT_EQ(String("nickserv").to_lowercase(), String("NickServ").to_lowercase()); + casemap.set("nickserv", 3); + casemap.set("NickServ", 3); + EXPECT_EQ(casemap.size(), 1); } + +TEST_MAIN(HashMap) diff --git a/AK/Tests/TestHelpers.h b/AK/Tests/TestHelpers.h deleted file mode 100644 index 311eb6ad1f97..000000000000 --- a/AK/Tests/TestHelpers.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include <stdio.h> -#include <AK/AKString.h> - -#define LOG_FAIL(cond) \ - fprintf(stderr, "\033[31;1mFAIL\033[0m: " #cond "\n") - -#define LOG_PASS(cond) \ - fprintf(stderr, "\033[32;1mPASS\033[0m: " #cond "\n") - -#define LOG_FAIL_EQ(cond, expected_value, actual_value) \ - fprintf(stderr, "\033[31;1mFAIL\033[0m: " #cond " should be " #expected_value ", got "); \ - stringify_for_test(actual_value); \ - fprintf(stderr, "\n") - -#define LOG_PASS_EQ(cond, expected_value) \ - fprintf(stderr, "\033[32;1mPASS\033[0m: " #cond " should be " #expected_value " and it is\n") - -#define EXPECT_EQ(expr, expected_value) \ - do { \ - auto result = (expr); \ - if (!(result == expected_value)) { \ - LOG_FAIL_EQ(expr, expected_value, result); \ - } else { \ - LOG_PASS_EQ(expr, expected_value); \ - } \ - } while(0) - -#define EXPECT(cond) \ - do { \ - if (!(cond)) { \ - LOG_FAIL(cond); \ - } else { \ - LOG_PASS(cond); \ - } \ - } while(0) - -inline void stringify_for_test(int value) -{ - fprintf(stderr, "%d", value); -} - -inline void stringify_for_test(unsigned value) -{ - fprintf(stderr, "%u", value); -} - -inline void stringify_for_test(const char* value) -{ - fprintf(stderr, "%s", value); -} - -inline void stringify_for_test(char value) -{ - fprintf(stderr, "%c", value); -} - -inline void stringify_for_test(const AK::String& string) -{ - stringify_for_test(string.characters()); -} - -inline void stringify_for_test(const AK::StringImpl& string) -{ - stringify_for_test(string.characters()); -} - diff --git a/AK/Tests/TestJSON.cpp b/AK/Tests/TestJSON.cpp index 72fb007de563..875ba6b99aaf 100644 --- a/AK/Tests/TestJSON.cpp +++ b/AK/Tests/TestJSON.cpp @@ -1,4 +1,4 @@ -#include "TestHelpers.h" +#include <AK/TestSuite.h> #include <AK/AKString.h> #include <AK/HashMap.h> #include <AK/JsonArray.h> @@ -6,9 +6,7 @@ #include <AK/JsonValue.h> #include <AK/StringBuilder.h> -typedef HashMap<int, int> IntIntMap; - -int main() +TEST_CASE(load_form) { FILE* fp = fopen("../../Base/home/anon/test.frm", "r"); ASSERT(fp); @@ -42,6 +40,6 @@ int main() //dbgprintf("Set property %s.%s to '%s'\n", widget_class.characters(), property_name.characters(), property_value.serialized().characters()); }); }); - - return 0; } + +TEST_MAIN(JSON) diff --git a/AK/Tests/TestQueue.cpp b/AK/Tests/TestQueue.cpp index a604074215bb..23d30f5de2f9 100644 --- a/AK/Tests/TestQueue.cpp +++ b/AK/Tests/TestQueue.cpp @@ -1,12 +1,15 @@ -#include "TestHelpers.h" +#include <AK/TestSuite.h> #include <AK/AKString.h> #include <AK/Queue.h> -int main() +TEST_CASE(construct) { EXPECT(Queue<int>().is_empty()); EXPECT(Queue<int>().size() == 0); +} +TEST_CASE(populate_int) +{ Queue<int> ints; ints.enqueue(1); ints.enqueue(2); @@ -18,7 +21,10 @@ int main() EXPECT_EQ(ints.size(), 1); EXPECT_EQ(ints.dequeue(), 3); EXPECT_EQ(ints.size(), 0); +} +TEST_CASE(populate_string) +{ Queue<String> strings; strings.enqueue("ABC"); strings.enqueue("DEF"); @@ -26,6 +32,12 @@ int main() EXPECT_EQ(strings.dequeue(), "ABC"); EXPECT_EQ(strings.dequeue(), "DEF"); EXPECT(strings.is_empty()); +} + +TEST_CASE(order) +{ + Queue<String> strings; + EXPECT(strings.is_empty()); for (int i = 0; i < 10000; ++i) { strings.enqueue(String::number(i)); @@ -38,6 +50,6 @@ int main() } EXPECT(strings.is_empty()); - - return 0; } + +TEST_MAIN(Queue) diff --git a/AK/Tests/TestString.cpp b/AK/Tests/TestString.cpp index 808d0904bee4..a8a926d1ec85 100644 --- a/AK/Tests/TestString.cpp +++ b/AK/Tests/TestString.cpp @@ -1,7 +1,7 @@ -#include "TestHelpers.h" +#include <AK/TestSuite.h> #include <AK/AKString.h> -int main() +TEST_CASE(construct_empty) { EXPECT(String().is_null()); EXPECT(String().is_empty()); @@ -9,22 +9,29 @@ int main() EXPECT(!String("").is_null()); EXPECT(String("").is_empty()); - EXPECT(String("").characters()); + EXPECT(String("").characters() != nullptr); EXPECT(String("").impl() == String::empty().impl()); +} +TEST_CASE(construct_contents) +{ String test_string = "ABCDEF"; EXPECT(!test_string.is_empty()); EXPECT(!test_string.is_null()); EXPECT_EQ(test_string.length(), 6); EXPECT_EQ(test_string.length(), (int)strlen(test_string.characters())); - EXPECT(test_string.characters()); + EXPECT(test_string.characters() != nullptr); EXPECT(!strcmp(test_string.characters(), "ABCDEF")); EXPECT(test_string == "ABCDEF"); EXPECT(test_string != "ABCDE"); EXPECT(test_string != "ABCDEFG"); +} +TEST_CASE(compare) +{ + String test_string = "ABCDEF"; EXPECT("a" < String("b")); EXPECT(!("a" > String("b"))); EXPECT("b" > String("a")); @@ -33,36 +40,70 @@ int main() EXPECT(!("a" >= String("b"))); EXPECT("a" <= String("a")); EXPECT(!("b" <= String("a"))); +} +TEST_CASE(index_access) +{ + String test_string = "ABCDEF"; EXPECT_EQ(test_string[0], 'A'); EXPECT_EQ(test_string[1], 'B'); +} +TEST_CASE(starts_with) +{ + String test_string = "ABCDEF"; EXPECT(test_string.starts_with("AB")); EXPECT(test_string.starts_with("ABCDEF")); EXPECT(!test_string.starts_with("DEF")); +} +TEST_CASE(ends_with) +{ + String test_string = "ABCDEF"; EXPECT(test_string.ends_with("EF")); EXPECT(test_string.ends_with("ABCDEF")); EXPECT(!test_string.ends_with("ABC")); +} +TEST_CASE(copy_string) +{ + String test_string = "ABCDEF"; auto test_string_copy = test_string; EXPECT_EQ(test_string, test_string_copy); EXPECT_EQ(test_string.characters(), test_string_copy.characters()); +} +TEST_CASE(move_string) +{ + String test_string = "ABCDEF"; + auto test_string_copy = test_string; auto test_string_move = move(test_string_copy); EXPECT_EQ(test_string, test_string_move); EXPECT(test_string_copy.is_null()); +} +TEST_CASE(repeated) +{ EXPECT_EQ(String::repeated('x', 0), ""); EXPECT_EQ(String::repeated('x', 1), "x"); EXPECT_EQ(String::repeated('x', 2), "xx"); +} +TEST_CASE(to_int) +{ bool ok; EXPECT(String("123").to_int(ok) == 123 && ok); EXPECT(String("-123").to_int(ok) == -123 && ok); +} +TEST_CASE(to_lowercase) +{ EXPECT(String("ABC").to_lowercase() == "abc"); - EXPECT(String("AbC").to_uppercase() == "ABC"); +} - return 0; +TEST_CASE(to_uppercase) +{ + EXPECT(String("AbC").to_uppercase() == "ABC"); } + +TEST_MAIN(String) diff --git a/AK/Tests/TestVector.cpp b/AK/Tests/TestVector.cpp index d8f8fa405c86..ad281d3b0c1f 100644 --- a/AK/Tests/TestVector.cpp +++ b/AK/Tests/TestVector.cpp @@ -1,12 +1,15 @@ -#include "TestHelpers.h" +#include <AK/TestSuite.h> #include <AK/AKString.h> #include <AK/Vector.h> -int main() +TEST_CASE(construct) { EXPECT(Vector<int>().is_empty()); EXPECT(Vector<int>().size() == 0); +} +TEST_CASE(ints) +{ Vector<int> ints; ints.append(1); ints.append(2); @@ -21,7 +24,10 @@ int main() ints.clear(); EXPECT_EQ(ints.size(), 0); +} +TEST_CASE(strings) +{ Vector<String> strings; strings.append("ABC"); strings.append("DEF"); @@ -40,22 +46,23 @@ int main() ++loop_counter; } EXPECT_EQ(loop_counter, 2); +} - { - Vector<String> strings; - strings.append("abc"); - strings.append("def"); - strings.append("ghi"); - - strings.insert_before_matching("f-g", [](auto& entry) { - return "f-g" < entry; - }); +TEST_CASE(strings_insert_ordered) +{ + Vector<String> strings; + strings.append("abc"); + strings.append("def"); + strings.append("ghi"); - EXPECT_EQ(strings[0], "abc"); - EXPECT_EQ(strings[1], "def"); - EXPECT_EQ(strings[2], "f-g"); - EXPECT_EQ(strings[3], "ghi"); - } + strings.insert_before_matching("f-g", [](auto& entry) { + return "f-g" < entry; + }); - return 0; + EXPECT_EQ(strings[0], "abc"); + EXPECT_EQ(strings[1], "def"); + EXPECT_EQ(strings[2], "f-g"); + EXPECT_EQ(strings[3], "ghi"); } + +TEST_MAIN(Vector)
104b51b9122f0cb142a07bd9a1dc2106fe817519
2022-10-07 17:23:27
matcool
libunicode: Fix Hangul syllable composition for specific cases
false
Fix Hangul syllable composition for specific cases
libunicode
diff --git a/Tests/LibUnicode/TestUnicodeNormalization.cpp b/Tests/LibUnicode/TestUnicodeNormalization.cpp index 8157b6d9660d..daef39d7652a 100644 --- a/Tests/LibUnicode/TestUnicodeNormalization.cpp +++ b/Tests/LibUnicode/TestUnicodeNormalization.cpp @@ -63,6 +63,7 @@ TEST_CASE(normalize_nfc) EXPECT_EQ(normalize("\u1103\u1161\u11B0"sv, NormalizationForm::NFC), "닭"sv); EXPECT_EQ(normalize("\u1100\uAC00\u11A8"sv, NormalizationForm::NFC), "\u1100\uAC01"sv); + EXPECT_EQ(normalize("\u1103\u1161\u11B0\u11B0"sv, NormalizationForm::NFC), "닭\u11B0"); } TEST_CASE(normalize_nfkd) diff --git a/Userland/Libraries/LibUnicode/Normalize.cpp b/Userland/Libraries/LibUnicode/Normalize.cpp index 8f5a59f7c3ca..bc1ab70221e5 100644 --- a/Userland/Libraries/LibUnicode/Normalize.cpp +++ b/Userland/Libraries/LibUnicode/Normalize.cpp @@ -111,7 +111,8 @@ static u32 combine_hangul_code_points(u32 a, u32 b) auto const leading_vowel_index = leading_index * HANGUL_BLOCK_COUNT + vowel_index * HANGUL_TRAILING_COUNT; return HANGUL_SYLLABLE_BASE + leading_vowel_index; } - if (is_hangul_code_point(a) && is_hangul_trailing(b)) { + // LV characters are the first in each "T block", so use this check to avoid combining LVT with T. + if (is_hangul_code_point(a) && (a - HANGUL_SYLLABLE_BASE) % HANGUL_TRAILING_COUNT == 0 && is_hangul_trailing(b)) { return a + b - HANGUL_TRAILING_BASE; } return 0;
db48dfcaaf48581531a0557a1c133acf27d84342
2019-09-07 00:04:21
Andreas Kling
ports: Add "nyancat" port :^)
false
Add "nyancat" port :^)
ports
diff --git a/Ports/nyancat/nyancat.sh b/Ports/nyancat/nyancat.sh new file mode 100755 index 000000000000..d0af68ec88eb --- /dev/null +++ b/Ports/nyancat/nyancat.sh @@ -0,0 +1,16 @@ +#!/bin/sh +PORT_DIR=nyancat +fetch() { + run_fetch_git "https://github.com/klange/nyancat.git" + run_patch serenity-changes.patch -p1 +} +configure() { + echo +} +build() { + run_make +} +install() { + run_make_install DESTDIR="$SERENITY_ROOT"/Root +} +. ../.port_include.sh diff --git a/Ports/nyancat/serenity-changes.patch b/Ports/nyancat/serenity-changes.patch new file mode 100644 index 000000000000..0a54a900eb1a --- /dev/null +++ b/Ports/nyancat/serenity-changes.patch @@ -0,0 +1,29 @@ +diff --git a/Makefile b/Makefile +index 1dd50ef..e435044 100644 +--- a/Makefile ++++ b/Makefile +@@ -33,7 +33,9 @@ distcheck: $(distdir).tar.gz + @echo "*** Package $(distdir).tar.gz is ready for distribution." + + install: all +- install src/nyancat /usr/bin/${package} +- gzip -9 -c < nyancat.1 > /usr/share/man/man1/nyancat.1.gz ++ mkdir -p ${DESTDIR}/usr/bin ++ install src/nyancat ${DESTDIR}/usr/bin/${package} ++ mkdir -p ${DESTDIR}/usr/share/man/man1 ++ gzip -9 -c < nyancat.1 > ${DESTDIR}/usr/share/man/man1/nyancat.1.gz + + .PHONY: FORCE all clean check dist distcheck install +diff --git a/src/nyancat.c b/src/nyancat.c +index 537225c..f2965c1 100644 +--- a/src/nyancat.c ++++ b/src/nyancat.c +@@ -901,7 +901,7 @@ int main(int argc, char ** argv) { + * The \033[0m prevents the Apple ][ from flipping everything, but + * makes the whole nyancat less bright on the vt220 + */ +- printf("\033[1;37mYou have nyaned for %0.0f seconds!\033[J\033[0m", diff); ++ printf("\033[1;37mYou have nyaned for %d seconds!\033[J\033[0m", (int)diff); + } + /* Reset the last color so that the escape sequences rewrite */ + last = 0;
bc44753adb8787ce654eb7243d6c038b0337e65b
2021-07-13 04:30:07
Marcin Gasperowicz
base: Change Marcin to nooga in fortunes database
false
Change Marcin to nooga in fortunes database
base
diff --git a/Base/res/fortunes.json b/Base/res/fortunes.json index 7c7cb1fbb3ba..fcd94050e014 100644 --- a/Base/res/fortunes.json +++ b/Base/res/fortunes.json @@ -87,7 +87,7 @@ }, { "quote": "we started with dialup and \"web 2.0\" and ended up with touchscreen smartphones sucking broadband out of thin air", - "author": "Marcin", + "author": "nooga", "url": "https://discord.com/channels/830522505605283862/830525235803586570/864277610510549002", "utc_time": 1626130562 }
9d50191dca5dab48cbbc9975e731e439c3441afd
2022-10-06 20:45:28
Andreas Kling
libweb: Tidy up FormattingContext::creates_block_formatting_context()
false
Tidy up FormattingContext::creates_block_formatting_context()
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Display.h b/Userland/Libraries/LibWeb/CSS/Display.h index 41064f674d1c..ba57ecaffe29 100644 --- a/Userland/Libraries/LibWeb/CSS/Display.h +++ b/Userland/Libraries/LibWeb/CSS/Display.h @@ -108,6 +108,7 @@ class Display { bool is_block_outside() const { return is_outside_and_inside() && outside() == Outside::Block; } bool is_inline_outside() const { return is_outside_and_inside() && outside() == Outside::Inline; } + bool is_inline_block() const { return is_inline_outside() && is_flow_root_inside(); } bool is_list_item() const { return is_outside_and_inside() && m_value.outside_inside.list_item == ListItem::Yes; } Inside inside() const diff --git a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp index fc8ade26d57b..11ce15d274d0 100644 --- a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp @@ -30,53 +30,73 @@ FormattingContext::FormattingContext(Type type, LayoutState& state, Box const& c FormattingContext::~FormattingContext() = default; +// https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context bool FormattingContext::creates_block_formatting_context(Box const& box) { + // NOTE: This function uses MDN as a reference, not because it's authoritative, + // but because they've gathered all the conditions in one convenient location. + + // The root element of the document (<html>). if (box.is_root_element()) return true; + + // Floats (elements where float isn't none). if (box.is_floating()) return true; + + // Absolutely positioned elements (elements where position is absolute or fixed). if (box.is_absolutely_positioned()) return true; - if (box.is_inline_block()) + + // Inline-blocks (elements with display: inline-block). + if (box.display().is_inline_block()) return true; - if (is<TableCellBox>(box)) + + // Table cells (elements with display: table-cell, which is the default for HTML table cells). + if (box.display().is_table_cell()) return true; - if (box.display().is_flex_inside()) - return false; + // Table captions (elements with display: table-caption, which is the default for HTML table captions). + if (box.display().is_table_caption()) + return true; + + // FIXME: Anonymous table cells implicitly created by the elements with display: table, table-row, table-row-group, table-header-group, table-footer-group + // (which is the default for HTML tables, table rows, table bodies, table headers, and table footers, respectively), or inline-table. + + // Block elements where overflow has a value other than visible and clip. CSS::Overflow overflow_x = box.computed_values().overflow_x(); if ((overflow_x != CSS::Overflow::Visible) && (overflow_x != CSS::Overflow::Clip)) return true; - CSS::Overflow overflow_y = box.computed_values().overflow_y(); if ((overflow_y != CSS::Overflow::Visible) && (overflow_y != CSS::Overflow::Clip)) return true; - auto display = box.display(); - - if (display.is_flow_root_inside()) + // display: flow-root. + if (box.display().is_flow_root_inside()) return true; + // FIXME: Elements with contain: layout, content, or paint. + if (box.parent()) { auto parent_display = box.parent()->display(); + + // Flex items (direct children of the element with display: flex or inline-flex) if they are neither flex nor grid nor table containers themselves. if (parent_display.is_flex_inside()) { - // FIXME: Flex items (direct children of the element with display: flex or inline-flex) if they are neither flex nor grid nor table containers themselves. - if (!display.is_flex_inside()) + if (!box.display().is_flex_inside()) return true; } + // Grid items (direct children of the element with display: grid or inline-grid) if they are neither flex nor grid nor table containers themselves. if (parent_display.is_grid_inside()) { - if (!display.is_grid_inside()) { + if (!box.display().is_grid_inside()) { return true; } } } - // FIXME: table-caption - // FIXME: anonymous table cells - // FIXME: Elements with contain: layout, content, or paint. - // FIXME: multicol - // FIXME: column-span: all + // FIXME: Multicol containers (elements where column-count or column-width isn't auto, including elements with column-count: 1). + + // FIXME: column-span: all should always create a new formatting context, even when the column-span: all element isn't contained by a multicol container (Spec change, Chrome bug). + return false; }
c17056cf099b107d52724d6785105cc1d9a1f4ca
2021-01-09 23:52:23
Andrew Kaster
meta: Unify build-and-test jobs using a matrix build
false
Unify build-and-test jobs using a matrix build
meta
diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 9aac425b421f..c8975f0d5225 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -10,10 +10,24 @@ env: jobs: build_and_test: - runs-on: ubuntu-20.04 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-20.04 + allow-test-failure: false + # There sure is a lot of logic here, is there a better way? + # TODO: Make IRC notifications its own job/workflow? + should-notify-irc: ${{ github.repository == 'SerenityOS/serenity' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/master')) }} + - os: macos-10.15 + allow-test-failure: true + should-notify-irc: false steps: - uses: actions/checkout@v2 + # Set default Python to python 3.x, and set Python path such that pip install works properly + - uses: actions/setup-python@v2 # === OS SETUP === @@ -23,7 +37,8 @@ jobs: - name: Purge interfering packages # Remove GCC 9 and clang-format 10 (installed by default) run: sudo apt-get purge -y gcc-9 g++-9 libstdc++-9-dev clang-format-10 - - name: Install dependencies + if: ${{ runner.os == 'Linux' }} + - name: "Install Ubuntu dependencies" # These packages are already part of the ubuntu-20.04 image: # cmake gcc-10 g++-10 shellcheck libgmp-dev # These aren't: @@ -34,17 +49,30 @@ jobs: sudo apt-get install clang-format-11 libstdc++-10-dev libmpfr-dev libmpc-dev ninja-build npm # If we ever do any qemu-emulation on Github Actions, we should re-enable this: # e2fsprogs qemu-system-i386 qemu-utils - - name: Install prettier - run: sudo npm install -g prettier + if: ${{ runner.os == 'Linux' }} - name: Use GCC 10 instead run: sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 60 --slave /usr/bin/g++ g++ /usr/bin/g++-10 + if: ${{ runner.os == 'Linux' }} + + - name: Install macOS dependencies + run: brew install coreutils ninja + if: ${{ runner.os == 'macOS' }} + + - name: Install JS dependencies + run: sudo npm install -g prettier + - name: Install Python dependencies + # The setup-python action set default python to python3.x. Note that we are not using system python here. + run: | + python -m pip install --upgrade pip + pip install flake8 requests - name: Check versions - run: set +e; g++ --version; g++-10 --version; clang-format --version; clang-format-11 --version; prettier --version; python --version; python3 --version; ninja --version + run: set +e; g++ --version; g++-10 --version; clang-format --version; clang-format-11 --version; prettier --version; python --version; python3 --version; ninja --version; flake8 --version # === PREPARE FOR BUILDING === - name: Lint (Phase 1/2) run: ${{ github.workspace }}/Meta/lint-ci.sh + if: ${{ runner.os == 'Linux' }} - name: Toolchain cache uses: actions/cache@v2 with: @@ -66,7 +94,7 @@ jobs: run: | mkdir -p Build cd Build - cmake .. -GNinja -DBUILD_LAGOM=ON -DENABLE_ALL_THE_DEBUG_MACROS=ON + cmake .. -GNinja -DBUILD_LAGOM=ON -DENABLE_ALL_THE_DEBUG_MACROS=ON -DCMAKE_C_COMPILER=gcc-10 -DCMAKE_CXX_COMPILER=g++-10 # === ACTUALLY BUILD AND TEST === @@ -84,14 +112,14 @@ jobs: run: ./check-symbols.sh - name: Run CMake tests working-directory: ${{ github.workspace }}/Build - run: CTEST_OUTPUT_ON_FAILURE=1 ninja test + run: CTEST_OUTPUT_ON_FAILURE=1 ninja test || ${{ matrix.allow-test-failure }} timeout-minutes: 2 - name: Run JS tests working-directory: ${{ github.workspace }}/Build/Meta/Lagom - run: DISABLE_DBG_OUTPUT=1 ./test-js + run: DISABLE_DBG_OUTPUT=1 ./test-js || ${{ matrix.allow-test-failure }} - name: Run LibCompress tests working-directory: ${{ github.workspace }}/Build/Meta/Lagom - run: DISABLE_DBG_OUTPUT=1 ./test-compress + run: ./test-compress # Run analysis last, so contributors get lint/test feedback ASAP. - name: Perform post build CodeQL Analysis @@ -107,14 +135,14 @@ jobs: ${{ toJSON(github.event) }} EOF - name: Generate IRC message - # I really dislike putting so much logic here, but I can't come up with something better. - if: github.repository == 'SerenityOS/serenity' && !cancelled() && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == 'refs/heads/master')) + if: matrix.should-notify-irc == true && !cancelled() run: | ${{ github.workspace }}/Meta/notify_irc.py <<"EOF" ["${{ github.actor }}", ${{ github.run_id }}, "${{ job.status }}", ${{ toJSON(github.event) }} ] EOF + build_lagom_with_fuzzers: runs-on: ubuntu-20.04 @@ -145,51 +173,3 @@ jobs: - name: Build Lagom with Fuzzers working-directory: ${{ github.workspace }}/Meta/Lagom/Build run: cmake --build . - build_and_test_on_macos: - runs-on: macos-10.15 - - steps: - - uses: actions/checkout@v2 - - - name: Install dependencies - run: brew install coreutils ninja - - name: Check versions - run: set +e; g++ --version; g++-10 --version; clang --version; clang++ --version; python --version; python3 --version; ninja --version - - name: Toolchain cache - uses: actions/cache@v2 - with: - path: ${{ github.workspace }}/Toolchain/Cache/ - # This assumes that *ALL* LibC headers have an impact on the Toolchain. - # This is wrong, and causes more Toolchain rebuilds than necessary. - # However, we want to avoid false cache hits at all costs. - key: ${{ runner.os }}-toolchain-i686-${{ hashFiles('Libraries/LibC/**/*.h', 'Toolchain/Patches/*.patch', 'Toolchain/BuildIt.sh') }} - - name: Restore or regenerate Toolchain - run: TRY_USE_LOCAL_TOOLCHAIN=y ${{ github.workspace }}/Toolchain/BuildIt.sh - - # TODO: ccache - # https://cristianadam.eu/20200113/speeding-up-c-plus-plus-github-actions-using-ccache/ - # https://github.com/cristianadam/HelloWorld/blob/master/.github/workflows/build_cmake.yml - - name: Create build environment - working-directory: ${{ github.workspace }} - # Note that this needs to run *even if* the Toolchain was built, - # in order to set options like BUILD_LAGOM. - run: | - mkdir -p Build - cd Build - cmake .. -GNinja -DBUILD_LAGOM=ON -DENABLE_ALL_THE_DEBUG_MACROS=ON -DCMAKE_C_COMPILER=gcc-10 -DCMAKE_CXX_COMPILER=g++-10 - - # === ACTUALLY BUILD AND TEST === - - - name: Build Serenity and Tests - working-directory: ${{ github.workspace }}/Build - run: cmake --build . - - name: Run CMake tests - working-directory: ${{ github.workspace }}/Build - # FIXME: Fix tests on MacOS - run: CTEST_OUTPUT_ON_FAILURE=1 ninja test || true - continue-on-error: true - timeout-minutes: 2 - - name: Run JS tests - working-directory: ${{ github.workspace }}/Build/Meta/Lagom - # FIXME: Fix tests on MacOS - run: DISABLE_DBG_OUTPUT=1 ./test-js || true
93357a8b704d00425f627b3342ff76ea0a2855b0
2023-07-05 23:12:39
Nico Weber
libpdf: Fix a typo in a function name
false
Fix a typo in a function name
libpdf
diff --git a/Userland/Libraries/LibPDF/Document.h b/Userland/Libraries/LibPDF/Document.h index 91243643c3af..d195d7bba00c 100644 --- a/Userland/Libraries/LibPDF/Document.h +++ b/Userland/Libraries/LibPDF/Document.h @@ -119,10 +119,10 @@ class Document final return cast_to<T>(TRY(resolve(value))); } - /// Whether this Document is reasdy to resolve references, which is usually + /// Whether this Document is ready to resolve references, which is usually /// true, except just before the XRef table is parsed (and while the linearization /// dict is being read). - bool can_resolve_refefences() { return m_parser->can_resolve_references(); } + bool can_resolve_references() { return m_parser->can_resolve_references(); } private: explicit Document(NonnullRefPtr<DocumentParser> const& parser); diff --git a/Userland/Libraries/LibPDF/Parser.cpp b/Userland/Libraries/LibPDF/Parser.cpp index 3f878bd8c59c..3cc22ece2d65 100644 --- a/Userland/Libraries/LibPDF/Parser.cpp +++ b/Userland/Libraries/LibPDF/Parser.cpp @@ -446,7 +446,7 @@ PDFErrorOr<NonnullRefPtr<StreamObject>> Parser::parse_stream(NonnullRefPtr<DictO ReadonlyBytes bytes; auto maybe_length = dict->get(CommonNames::Length); - if (maybe_length.has_value() && m_document->can_resolve_refefences()) { + if (maybe_length.has_value() && m_document->can_resolve_references()) { // The PDF writer has kindly provided us with the direct length of the stream m_reader.save(); auto length = TRY(m_document->resolve_to<int>(maybe_length.value()));
5ff816abbf6060f674e65b7deabd212cdced08a6
2022-02-11 17:15:38
Andreas Kling
libweb: Remove unused CascadeOrigin::Any
false
Remove unused CascadeOrigin::Any
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp index ae9df126d63c..6dfd4783a37a 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp @@ -57,12 +57,12 @@ static StyleSheet& quirks_mode_stylesheet() template<typename Callback> void StyleComputer::for_each_stylesheet(CascadeOrigin cascade_origin, Callback callback) const { - if (cascade_origin == CascadeOrigin::Any || cascade_origin == CascadeOrigin::UserAgent) { + if (cascade_origin == CascadeOrigin::UserAgent) { callback(default_stylesheet()); if (document().in_quirks_mode()) callback(quirks_mode_stylesheet()); } - if (cascade_origin == CascadeOrigin::Any || cascade_origin == CascadeOrigin::Author) { + if (cascade_origin == CascadeOrigin::Author) { for (auto const& sheet : document().style_sheets().sheets()) { callback(sheet); } diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.h b/Userland/Libraries/LibWeb/CSS/StyleComputer.h index 799dc05be4f3..f0524093f17d 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.h +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.h @@ -64,7 +64,7 @@ class StyleComputer { Transition, }; - Vector<MatchingRule> collect_matching_rules(DOM::Element const&, CascadeOrigin = CascadeOrigin::Any) const; + Vector<MatchingRule> collect_matching_rules(DOM::Element const&, CascadeOrigin) const; void invalidate_rule_cache();
5966f181f516061dbbcf6ff4dd6e82924cd81a0c
2023-01-25 01:17:11
Aliaksandr Kalenik
libweb: Avoid division by zero in `distribute_width_to_columns`
false
Avoid division by zero in `distribute_width_to_columns`
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp index 6ca60960c4c0..de232faf31e6 100644 --- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp @@ -289,6 +289,9 @@ void TableFormattingContext::distribute_width_to_columns() } } + if (total_preferred_width_increment == 0) + return; + for (auto& column : m_columns) { if (column.type == column_type) { CSSPixels preferred_width_increment = column_preferred_width(column) - column.min_width;
8ed28890e4d9ab7b93d435a85735b4605d0f778c
2022-08-06 18:12:37
Linus Groh
libjs: Correct BalanceDurationRelative algorithm
false
Correct BalanceDurationRelative algorithm
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp index fc4eb4e7b7b9..a8a419fb14a6 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp @@ -794,8 +794,8 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(GlobalObject& gl // a. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneYear). auto move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_year)); - // b. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // b. Let newRelativeTo be moveResult.[[RelativeTo]]. + auto* new_relative_to = move_result.relative_to.cell(); // c. Let oneYearDays be moveResult.[[Days]]. auto one_year_days = move_result.days; @@ -808,21 +808,24 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(GlobalObject& gl // ii. Set years to years + sign. years += sign; - // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneYear). + // iii. Set relativeTo to newRelativeTo. + relative_to = new_relative_to; + + // iv. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneYear). move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_year)); - // iv. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // v. Set newRelativeTo to moveResult.[[RelativeTo]]. + new_relative_to = move_result.relative_to.cell(); - // v. Set oneYearDays to moveResult.[[Days]]. + // vi. Set oneYearDays to moveResult.[[Days]]. one_year_days = move_result.days; } // e. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth). move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_month)); - // f. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // f. Set newRelativeTo to moveResult.[[RelativeTo]]. + new_relative_to = move_result.relative_to.cell(); // g. Let oneMonthDays be moveResult.[[Days]]. auto one_month_days = move_result.days; @@ -835,21 +838,24 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(GlobalObject& gl // ii. Set months to months + sign. months += sign; - // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth). + // iii. Set relativeTo to newRelativeTo. + relative_to = new_relative_to; + + // iv. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth). move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_month)); - // iv. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // v. Set newRelativeTo to moveResult.[[RelativeTo]]. + new_relative_to = move_result.relative_to.cell(); - // v. Set oneMonthDays to moveResult.[[Days]]. + // vi. Set oneMonthDays to moveResult.[[Days]]. one_month_days = move_result.days; } // i. Let dateAdd be ? GetMethod(calendar, "dateAdd"). auto* date_add = TRY(Value(&calendar).get_method(global_object, vm.names.dateAdd)); - // j. Let newRelativeTo be ? CalendarDateAdd(calendar, relativeTo, oneYear, undefined, dateAdd). - auto* new_relative_to = TRY(calendar_date_add(global_object, calendar, relative_to, *one_year, nullptr, date_add)); + // j. Set newRelativeTo to ? CalendarDateAdd(calendar, relativeTo, oneYear, undefined, dateAdd). + new_relative_to = TRY(calendar_date_add(global_object, calendar, relative_to, *one_year, nullptr, date_add)); // k. Let dateUntil be ? GetMethod(calendar, "dateUntil"). auto* date_until = TRY(Value(&calendar).get_method(global_object, vm.names.dateUntil)); @@ -898,8 +904,8 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(GlobalObject& gl // a. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneMonth). auto move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_month)); - // b. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // b. Let newRelativeTo be moveResult.[[RelativeTo]]. + auto* new_relative_to = move_result.relative_to.cell(); // c. Let oneMonthDays be moveResult.[[Days]]. auto one_month_days = move_result.days; @@ -912,13 +918,16 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(GlobalObject& gl // ii. Set months to months + sign. months += sign; - // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth). + // iii. Set relativeTo to newRelativeTo. + relative_to = new_relative_to; + + // iv. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth). move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_month)); - // iv. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // v. Set newRelativeTo to moveResult.[[RelativeTo]]. + new_relative_to = move_result.relative_to.cell(); - // v. Set oneMonthDays to moveResult.[[Days]]. + // vi. Set oneMonthDays to moveResult.[[Days]]. one_month_days = move_result.days; } } @@ -930,8 +939,8 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(GlobalObject& gl // b. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneWeek). auto move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_week)); - // c. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // c. Let newRelativeTo be moveResult.[[RelativeTo]]. + auto* new_relative_to = move_result.relative_to.cell(); // d. Let oneWeekDays be moveResult.[[Days]]. auto one_week_days = move_result.days; @@ -944,13 +953,16 @@ ThrowCompletionOr<DateDurationRecord> balance_duration_relative(GlobalObject& gl // ii. Set weeks to weeks + sign. weeks += sign; - // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneWeek). + // iii. Set relativeTo to newRelativeTo. + relative_to = new_relative_to; + + // iv. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneWeek). move_result = TRY(move_relative_date(global_object, calendar, *relative_to, *one_week)); - // iv. Set relativeTo to moveResult.[[RelativeTo]]. - relative_to = move_result.relative_to.cell(); + // v. Set newRelativeTo to moveResult.[[RelativeTo]]. + new_relative_to = move_result.relative_to.cell(); - // v. Set oneWeekDays to moveResult.[[Days]]. + // vi. Set oneWeekDays to moveResult.[[Days]]. one_week_days = move_result.days; } }
03ddda79793a2731855d6f3132fcb8027694dd75
2021-11-11 13:57:00
Andreas Kling
libwasm: Fix broken build after merging un-rebased Validator changes
false
Fix broken build after merging un-rebased Validator changes
libwasm
diff --git a/Userland/Libraries/LibWasm/AbstractMachine/Validator.cpp b/Userland/Libraries/LibWasm/AbstractMachine/Validator.cpp index e3a280d4fc51..857ca555be34 100644 --- a/Userland/Libraries/LibWasm/AbstractMachine/Validator.cpp +++ b/Userland/Libraries/LibWasm/AbstractMachine/Validator.cpp @@ -24,7 +24,7 @@ ErrorOr<void, ValidationError> Validator::validate(Module& module) if (result.is_error()) return; for (auto& export_ : section.entries()) { - if (seen_export_names.try_set(export_.name()) != AK::HashSetResult::InsertedNewEntry) + if (seen_export_names.try_set(export_.name()).release_value_but_fixme_should_propagate_errors() != AK::HashSetResult::InsertedNewEntry) result = Errors::duplicate_export_name(export_.name()); return; }
8d8ec6365b37f3c3347874f887ce0ca8bc034ca8
2021-09-02 12:39:12
Mustafa Quraish
pixelpaint: Allow changing colors temporarily without palette
false
Allow changing colors temporarily without palette
pixelpaint
diff --git a/Userland/Applications/PixelPaint/PaletteWidget.cpp b/Userland/Applications/PixelPaint/PaletteWidget.cpp index 9c2c706bce82..9395a3c04d70 100644 --- a/Userland/Applications/PixelPaint/PaletteWidget.cpp +++ b/Userland/Applications/PixelPaint/PaletteWidget.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> * Copyright (c) 2021, Felix Rauch <[email protected]> + * Copyright (c) 2021, Mustafa Quraish <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -61,6 +62,34 @@ class ColorWidget : public GUI::Frame { Color m_color; }; +class SelectedColorWidget : public GUI::Frame { + C_OBJECT(SelectedColorWidget); + +public: + virtual ~SelectedColorWidget() override { } + + virtual void mousedown_event(GUI::MouseEvent& event) override + { + if (event.button() != GUI::MouseButton::Left || !on_color_change) + return; + + auto dialog = GUI::ColorPicker::construct(m_color, window()); + if (dialog->exec() == GUI::Dialog::ExecOK) + on_color_change(dialog->color()); + } + + void set_background_color(Color const& color) + { + auto pal = palette(); + pal.set_color(ColorRole::Background, color); + set_palette(pal); + update(); + } + + Function<void(Color const&)> on_color_change; + Color m_color = Color::White; +}; + PaletteWidget::PaletteWidget() { set_frame_shape(Gfx::FrameShape::Panel); @@ -70,11 +99,17 @@ PaletteWidget::PaletteWidget() set_fixed_height(35); - m_secondary_color_widget = add<GUI::Frame>(); + m_secondary_color_widget = add<SelectedColorWidget>(); + m_secondary_color_widget->on_color_change = [&](auto& color) { + set_secondary_color(color); + }; m_secondary_color_widget->set_relative_rect({ 0, 2, 60, 33 }); m_secondary_color_widget->set_fill_with_background_color(true); - m_primary_color_widget = add<GUI::Frame>(); + m_primary_color_widget = add<SelectedColorWidget>(); + m_primary_color_widget->on_color_change = [&](auto& color) { + set_primary_color(color); + }; auto rect = Gfx::IntRect(0, 0, 35, 17).centered_within(m_secondary_color_widget->relative_rect()); m_primary_color_widget->set_relative_rect(rect); m_primary_color_widget->set_fill_with_background_color(true); @@ -127,19 +162,13 @@ PaletteWidget::~PaletteWidget() void PaletteWidget::set_primary_color(Color color) { m_editor->set_primary_color(color); - auto pal = m_primary_color_widget->palette(); - pal.set_color(ColorRole::Background, color); - m_primary_color_widget->set_palette(pal); - m_primary_color_widget->update(); + m_primary_color_widget->set_background_color(color); } void PaletteWidget::set_secondary_color(Color color) { m_editor->set_secondary_color(color); - auto pal = m_secondary_color_widget->palette(); - pal.set_color(ColorRole::Background, color); - m_secondary_color_widget->set_palette(pal); - m_secondary_color_widget->update(); + m_secondary_color_widget->set_background_color(color); } void PaletteWidget::display_color_list(Vector<Color> const& colors) diff --git a/Userland/Applications/PixelPaint/PaletteWidget.h b/Userland/Applications/PixelPaint/PaletteWidget.h index b90e5d8b4263..4e8a48a9b0a8 100644 --- a/Userland/Applications/PixelPaint/PaletteWidget.h +++ b/Userland/Applications/PixelPaint/PaletteWidget.h @@ -1,6 +1,7 @@ /* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> * Copyright (c) 2021, Felix Rauch <[email protected]> + * Copyright (c) 2021, Mustafa Quraish <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -14,6 +15,7 @@ namespace PixelPaint { class ImageEditor; +class SelectedColorWidget; class PaletteWidget final : public GUI::Frame { C_OBJECT(PaletteWidget); @@ -41,8 +43,8 @@ class PaletteWidget final : public GUI::Frame { explicit PaletteWidget(); ImageEditor* m_editor { nullptr }; - RefPtr<GUI::Frame> m_primary_color_widget; - RefPtr<GUI::Frame> m_secondary_color_widget; + RefPtr<SelectedColorWidget> m_primary_color_widget; + RefPtr<SelectedColorWidget> m_secondary_color_widget; RefPtr<GUI::Widget> m_color_container; };
6305ef197ff1678ee0f29bd15919aa15f1e7f39f
2022-07-27 01:24:30
Kenneth Myhra
libweb: Fix const issue on type() accessor for the Blob interface
false
Fix const issue on type() accessor for the Blob interface
libweb
diff --git a/Userland/Libraries/LibWeb/FileAPI/Blob.h b/Userland/Libraries/LibWeb/FileAPI/Blob.h index 9c78ced66a48..40b01498e9c4 100644 --- a/Userland/Libraries/LibWeb/FileAPI/Blob.h +++ b/Userland/Libraries/LibWeb/FileAPI/Blob.h @@ -41,7 +41,7 @@ class Blob static DOM::ExceptionOr<NonnullRefPtr<Blob>> create_with_global_object(Bindings::WindowObject&, Optional<Vector<BlobPart>> const& blob_parts = {}, Optional<BlobPropertyBag> const& options = {}); u64 size() const { return m_byte_buffer.size(); } - String type() const& { return m_type; } + String const& type() const { return m_type; } DOM::ExceptionOr<NonnullRefPtr<Blob>> slice(Optional<i64> start = {}, Optional<i64> end = {}, Optional<String> const& content_type = {});
b281fa2b24189c85e01fa1044e13701dbb02fcde
2024-10-31 14:22:24
stelar7
libweb: Implement X25519.importKey
false
Implement X25519.importKey
libweb
diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp index 0e68b9f1d554..9457cbc93baf 100644 --- a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp +++ b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp @@ -7,6 +7,7 @@ #include <AK/Base64.h> #include <AK/QuickSort.h> +#include <LibCrypto/ASN1/ASN1.h> #include <LibCrypto/ASN1/DER.h> #include <LibCrypto/Authentication/HMAC.h> #include <LibCrypto/Cipher/AES.h> @@ -168,6 +169,11 @@ static WebIDL::ExceptionOr<Structure> parse_an_ASN1_structure(JS::Realm& realm, if (maybe_private_key.is_error()) return WebIDL::DataError::create(realm, MUST(String::formatted("Error parsing privateKeyInfo: {}", maybe_private_key.release_error()))); structure = maybe_private_key.release_value(); + } else if constexpr (IsSame<Structure, StringView>) { + auto read_result = decoder.read<StringView>(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::OctetString); + if (read_result.is_error()) + return WebIDL::DataError::create(realm, MUST(String::formatted("Read of kind OctetString failed: {}", read_result.error()))); + structure = read_result.release_value(); } else { static_assert(DependentFalse<Structure>, "Don't know how to parse ASN.1 structure type"); } @@ -2464,4 +2470,243 @@ WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<Crypto return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) }; } +WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> X25519::import_key([[maybe_unused]] Web::Crypto::AlgorithmParams const& params, Bindings::KeyFormat key_format, CryptoKey::InternalKeyData key_data, bool extractable, Vector<Bindings::KeyUsage> const& usages) +{ + // NOTE: This is a parameter to the function + // 1. Let keyData be the key data to be imported. + + auto& vm = m_realm->vm(); + JS::GCPtr<CryptoKey> key = nullptr; + + // 2. If format is "spki": + if (key_format == Bindings::KeyFormat::Spki) { + // 1. If usages is not empty then throw a SyntaxError. + if (!usages.is_empty()) + return WebIDL::SyntaxError::create(m_realm, "Usages must be empty"_string); + + // 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData. + // 3. If an error occurred while parsing, then throw a DataError. + auto spki = TRY(parse_a_subject_public_key_info(m_realm, key_data.get<ByteBuffer>())); + + // 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki + // is not equal to the id-X25519 object identifier defined in [RFC8410], then throw a DataError. + if (spki.algorithm.identifier != TLS::x25519_oid) + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + + // 5. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError. + if (static_cast<u16>(spki.algorithm.ec_parameters) != 0) + return WebIDL::DataError::create(m_realm, "Invalid algorithm parameters"_string); + + // 6. Let publicKey be the X25519 public key identified by the subjectPublicKey field of spki. + auto public_key = spki.raw_key; + + // 7. Let key be a new CryptoKey associated with the relevant global object of this [HTML], and that represents publicKey. + key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key }); + + // 8. Set the [[type]] internal slot of key to "public" + key->set_type(Bindings::KeyType::Public); + + // 9. Let algorithm be a new KeyAlgorithm. + auto algorithm = KeyAlgorithm::create(m_realm); + + // 10. Set the name attribute of algorithm to "X25519". + algorithm->set_name("X25519"_string); + + // 11. Set the [[algorithm]] internal slot of key to algorithm. + key->set_algorithm(algorithm); + } + + // 2. If format is "pkcs8": + else if (key_format == Bindings::KeyFormat::Pkcs8) { + // 1. If usages contains an entry which is not "deriveKey" or "deriveBits" then throw a SyntaxError. + for (auto const& usage : usages) { + if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) { + return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage)))); + } + } + + // 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData. + // 3. If an error occurred while parsing, then throw a DataError. + auto private_key_info = TRY(parse_a_private_key_info(m_realm, key_data.get<ByteBuffer>())); + + // 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo + // is not equal to the id-X25519 object identifier defined in [RFC8410], then throw a DataError. + if (private_key_info.algorithm.identifier != TLS::x25519_oid) + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + + // 5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present, then throw a DataError. + if (static_cast<u16>(private_key_info.algorithm.ec_parameters) != 0) + return WebIDL::DataError::create(m_realm, "Invalid algorithm parameters"_string); + + // 6. Let curvePrivateKey be the result of performing the parse an ASN.1 structure algorithm, + // with data as the privateKey field of privateKeyInfo, + // structure as the ASN.1 CurvePrivateKey structure specified in Section 7 of [RFC8410], and + // exactData set to true. + // 7. If an error occurred while parsing, then throw a DataError. + auto curve_private_key = TRY(parse_an_ASN1_structure<StringView>(m_realm, private_key_info.raw_key, true)); + auto curve_private_key_bytes = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(curve_private_key.bytes())); + + // 8. Let key be a new CryptoKey associated with the relevant global object of this [HTML], + // and that represents the X25519 private key identified by curvePrivateKey. + key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { curve_private_key_bytes }); + + // 9. Set the [[type]] internal slot of key to "private" + key->set_type(Bindings::KeyType::Private); + + // 10. Let algorithm be a new KeyAlgorithm. + auto algorithm = KeyAlgorithm::create(m_realm); + + // 11. Set the name attribute of algorithm to "X25519". + algorithm->set_name("X25519"_string); + + // 12. Set the [[algorithm]] internal slot of key to algorithm. + key->set_algorithm(algorithm); + } + + // 2. If format is "jwk": + else if (key_format == Bindings::KeyFormat::Jwk) { + // 1. If keyData is a JsonWebKey dictionary: Let jwk equal keyData. + // Otherwise: Throw a DataError. + if (!key_data.has<Bindings::JsonWebKey>()) + return WebIDL::DataError::create(m_realm, "keyData is not a JsonWebKey dictionary"_string); + auto& jwk = key_data.get<Bindings::JsonWebKey>(); + + // 2. If the d field is present and if usages contains an entry which is not "deriveKey" or "deriveBits" then throw a SyntaxError. + if (jwk.d.has_value() && !usages.is_empty()) { + for (auto const& usage : usages) { + if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) { + return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage)))); + } + } + } + + // 3. If the d field is not present and if usages is not empty then throw a SyntaxError. + if (!jwk.d.has_value() && !usages.is_empty()) + return WebIDL::SyntaxError::create(m_realm, "Usages must be empty if d is missing"_string); + + // 4. If the kty field of jwk is not "OKP", then throw a DataError. + if (jwk.kty != "OKP"sv) + return WebIDL::DataError::create(m_realm, "Invalid key type"_string); + + // 5. If the crv field of jwk is not "X25519", then throw a DataError. + if (jwk.crv != "X25519"sv) + return WebIDL::DataError::create(m_realm, "Invalid curve"_string); + + // 6. If usages is non-empty and the use field of jwk is present and is not equal to "enc" then throw a DataError. + if (!usages.is_empty() && jwk.use.has_value() && jwk.use.value() != "enc"sv) + return WebIDL::DataError::create(m_realm, "Invalid use"_string); + + // 7. If the key_ops field of jwk is present, and is invalid according to the requirements of JSON Web Key [JWK], + // or it does not contain all of the specified usages values, then throw a DataError. + if (jwk.key_ops.has_value()) { + for (auto const& usage : usages) { + if (!jwk.key_ops->contains_slow(Bindings::idl_enum_to_string(usage))) + return WebIDL::DataError::create(m_realm, MUST(String::formatted("Missing key_ops field: {}", Bindings::idl_enum_to_string(usage)))); + } + } + + // 8. If the ext field of jwk is present and has the value false and extractable is true, then throw a DataError. + if (jwk.ext.has_value() && !jwk.ext.value() && extractable) + return WebIDL::DataError::create(m_realm, "Invalid extractable"_string); + + // 9. If the d field is present: + if (jwk.d.has_value()) { + // 1. If jwk does not meet the requirements of the JWK private key format described in Section 2 of [RFC8037], then throw a DataError. + // o The parameter "kty" MUST be "OKP". + if (jwk.kty != "OKP"sv) + return WebIDL::DataError::create(m_realm, "Invalid key type"_string); + + // // https://www.iana.org/assignments/jose/jose.xhtml#web-key-elliptic-curve + // o The parameter "crv" MUST be present and contain the subtype of the key (from the "JSON Web Elliptic Curve" registry). + if (jwk.crv != "X25519"sv) + return WebIDL::DataError::create(m_realm, "Invalid curve"_string); + + // o The parameter "x" MUST be present and contain the public key encoded using the base64url [RFC4648] encoding. + if (!jwk.x.has_value()) + return WebIDL::DataError::create(m_realm, "Missing x field"_string); + + // o The parameter "d" MUST be present for private keys and contain the private key encoded using the base64url encoding. + // This parameter MUST NOT be present for public keys. + if (!jwk.d.has_value()) + return WebIDL::DataError::create(m_realm, "Missing d field"_string); + + // 2. Let key be a new CryptoKey object that represents the X25519 private key identified by interpreting jwk according to Section 2 of [RFC8037]. + auto private_key_base_64 = jwk.d.value(); + auto private_key = TRY_OR_THROW_OOM(vm, decode_base64(private_key_base_64)); + key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key }); + + // 3. Set the [[type]] internal slot of Key to "private". + key->set_type(Bindings::KeyType::Private); + } + // 9. Otherwise: + else { + // 1. If jwk does not meet the requirements of the JWK public key format described in Section 2 of [RFC8037], then throw a DataError. + // o The parameter "kty" MUST be "OKP". + if (jwk.kty != "OKP"sv) + return WebIDL::DataError::create(m_realm, "Invalid key type"_string); + + // https://www.iana.org/assignments/jose/jose.xhtml#web-key-elliptic-curve + // o The parameter "crv" MUST be present and contain the subtype of the key (from the "JSON Web Elliptic Curve" registry). + if (jwk.crv != "X25519"sv) + return WebIDL::DataError::create(m_realm, "Invalid curve"_string); + + // o The parameter "x" MUST be present and contain the public key encoded using the base64url [RFC4648] encoding. + if (!jwk.x.has_value()) + return WebIDL::DataError::create(m_realm, "Missing x field"_string); + + // o The parameter "d" MUST be present for private keys and contain the private key encoded using the base64url encoding. + // This parameter MUST NOT be present for public keys. + if (jwk.d.has_value()) + return WebIDL::DataError::create(m_realm, "Present d field"_string); + + // 2. Let key be a new CryptoKey object that represents the X25519 public key identified by interpreting jwk according to Section 2 of [RFC8037]. + auto public_key_base_64 = jwk.x.value(); + auto public_key = TRY_OR_THROW_OOM(vm, decode_base64(public_key_base_64)); + key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key }); + + // 3. Set the [[type]] internal slot of Key to "public". + key->set_type(Bindings::KeyType::Public); + } + + // 10. Let algorithm be a new instance of a KeyAlgorithm object. + auto algorithm = KeyAlgorithm::create(m_realm); + + // 11. Set the name attribute of algorithm to "X25519". + algorithm->set_name("X25519"_string); + + // 12. Set the [[algorithm]] internal slot of key to algorithm. + key->set_algorithm(algorithm); + } + + // 2. If format is "raw": + else if (key_format == Bindings::KeyFormat::Raw) { + // 1. If usages is not empty then throw a SyntaxError. + if (!usages.is_empty()) + return WebIDL::SyntaxError::create(m_realm, "Usages must be empty"_string); + + // 2. Let algorithm be a new KeyAlgorithm object. + auto algorithm = KeyAlgorithm::create(m_realm); + + // 3. Set the name attribute of algorithm to "X25519". + algorithm->set_name("X25519"_string); + + // 4. Let key be a new CryptoKey associated with the relevant global object of this [HTML], and representing the key data provided in keyData. + key = CryptoKey::create(m_realm, key_data); + + // 5. Set the [[type]] internal slot of key to "public" + key->set_type(Bindings::KeyType::Public); + + // 6. Set the [[algorithm]] internal slot of key to algorithm. + key->set_algorithm(algorithm); + } + + // 2. Otherwise: throw a NotSupportedError. + else { + return WebIDL::NotSupportedError::create(m_realm, "Invalid key format"_string); + } + + // 3. Return key + return JS::NonnullGCPtr { *key }; +} + } diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h index 319d33042f24..39e21e4b7575 100644 --- a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h +++ b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.h @@ -441,6 +441,7 @@ class X25519 : public AlgorithmMethods { public: virtual WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> derive_bits(AlgorithmParams const&, JS::NonnullGCPtr<CryptoKey>, Optional<u32>) override; virtual WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> generate_key(AlgorithmParams const&, bool, Vector<Bindings::KeyUsage> const&) override; + virtual WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> import_key(AlgorithmParams const&, Bindings::KeyFormat, CryptoKey::InternalKeyData, bool, Vector<Bindings::KeyUsage> const&) override; static NonnullOwnPtr<AlgorithmMethods> create(JS::Realm& realm) { return adopt_own(*new X25519(realm)); } diff --git a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp index c02742b5de64..1ff67bd238fd 100644 --- a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp +++ b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp @@ -814,6 +814,7 @@ SupportedAlgorithmsMap supported_algorithms() // https://wicg.github.io/webcrypto-secure-curves/#x25519 define_an_algorithm<X25519, EcdhKeyDerivePrams>("deriveBits"_string, "X25519"_string); define_an_algorithm<X25519>("generateKey"_string, "X25519"_string); + define_an_algorithm<X25519>("importKey"_string, "X25519"_string); return internal_object; }
631447da574ec6421c77d37da54ad04b50102688
2021-11-10 20:43:10
Ben Wiederhake
kernel: Fix TOCTOU in fstatvfs
false
Fix TOCTOU in fstatvfs
kernel
diff --git a/Kernel/Process.h b/Kernel/Process.h index bb26b29d3c54..c6e3ae645363 100644 --- a/Kernel/Process.h +++ b/Kernel/Process.h @@ -535,7 +535,7 @@ class Process final ErrorOr<void> do_exec(NonnullRefPtr<OpenFileDescription> main_program_description, NonnullOwnPtrVector<KString> arguments, NonnullOwnPtrVector<KString> environment, RefPtr<OpenFileDescription> interpreter_description, Thread*& new_main_thread, u32& prev_flags, const ElfW(Ehdr) & main_program_header); ErrorOr<FlatPtr> do_write(OpenFileDescription&, const UserOrKernelBuffer&, size_t); - ErrorOr<FlatPtr> do_statvfs(StringView path, statvfs* buf); + ErrorOr<FlatPtr> do_statvfs(FileSystem const& path, Custody const*, statvfs* buf); ErrorOr<RefPtr<OpenFileDescription>> find_elf_interpreter_for_executable(StringView path, ElfW(Ehdr) const& main_executable_header, size_t main_executable_header_size, size_t file_size); diff --git a/Kernel/Syscalls/statvfs.cpp b/Kernel/Syscalls/statvfs.cpp index 678ac6f44877..c0478a3985c1 100644 --- a/Kernel/Syscalls/statvfs.cpp +++ b/Kernel/Syscalls/statvfs.cpp @@ -10,12 +10,8 @@ namespace Kernel { -ErrorOr<FlatPtr> Process::do_statvfs(StringView path, statvfs* buf) +ErrorOr<FlatPtr> Process::do_statvfs(FileSystem const& fs, Custody const* custody, statvfs* buf) { - auto custody = TRY(VirtualFileSystem::the().resolve_path(path, current_directory(), nullptr, 0)); - auto& inode = custody->inode(); - auto& fs = inode.fs(); - statvfs kernelbuf = {}; kernelbuf.f_bsize = static_cast<u64>(fs.block_size()); @@ -34,29 +30,8 @@ ErrorOr<FlatPtr> Process::do_statvfs(StringView path, statvfs* buf) kernelbuf.f_namemax = 255; - Custody* current_custody = custody; - - while (current_custody) { - VirtualFileSystem::the().for_each_mount([&kernelbuf, &current_custody](auto& mount) { - if (&current_custody->inode() == &mount.guest()) { - int mountflags = mount.flags(); - int flags = 0; - if (mountflags & MS_RDONLY) - flags = flags | ST_RDONLY; - if (mountflags & MS_NOSUID) - flags = flags | ST_NOSUID; - - kernelbuf.f_flag = flags; - current_custody = nullptr; - return IterationDecision::Break; - } - return IterationDecision::Continue; - }); - - if (current_custody) { - current_custody = current_custody->parent(); - } - } + if (custody) + kernelbuf.f_flag = custody->mount_flags(); TRY(copy_to_user(buf, &kernelbuf)); return 0; @@ -69,7 +44,12 @@ ErrorOr<FlatPtr> Process::sys$statvfs(Userspace<const Syscall::SC_statvfs_params auto params = TRY(copy_typed_from_user(user_params)); auto path = TRY(get_syscall_path_argument(params.path)); - return do_statvfs(path->view(), params.buf); + + auto custody = TRY(VirtualFileSystem::the().resolve_path(path->view(), current_directory(), nullptr, 0)); + auto& inode = custody->inode(); + auto const& fs = inode.fs(); + + return do_statvfs(fs, custody, params.buf); } ErrorOr<FlatPtr> Process::sys$fstatvfs(int fd, statvfs* buf) @@ -78,9 +58,12 @@ ErrorOr<FlatPtr> Process::sys$fstatvfs(int fd, statvfs* buf) REQUIRE_PROMISE(stdio); auto description = TRY(fds().open_file_description(fd)); - auto absolute_path = TRY(description->original_absolute_path()); - // FIXME: TOCTOU bug! The file connected to the fd may or may not have been moved, and the name possibly taken by a different file. - return do_statvfs(absolute_path->view(), buf); + auto inode = description->inode(); + if (inode == nullptr) + return ENOENT; + + // FIXME: The custody that we pass in might be outdated. However, this only affects the mount flags. + return do_statvfs(inode->fs(), description->custody(), buf); } }
29d74632c773048987e0a5a708911eed68645770
2025-02-17 01:35:59
InvalidUsernameException
libweb: Move `z-index` to table wrapper box
false
Move `z-index` to table wrapper box
libweb
diff --git a/Libraries/LibWeb/CSS/ComputedValues.h b/Libraries/LibWeb/CSS/ComputedValues.h index 4cdad61c9d63..ed65144655ea 100644 --- a/Libraries/LibWeb/CSS/ComputedValues.h +++ b/Libraries/LibWeb/CSS/ComputedValues.h @@ -188,6 +188,7 @@ class InitialValues { static CSS::Isolation isolation() { return CSS::Isolation::Auto; } static CSS::Containment contain() { return {}; } static CSS::MixBlendMode mix_blend_mode() { return CSS::MixBlendMode::Normal; } + static Optional<int> z_index() { return OptionalNone(); } // https://www.w3.org/TR/SVG/geometry.html static LengthPercentage cx() { return CSS::Length::make_px(0); } diff --git a/Libraries/LibWeb/Layout/Node.cpp b/Libraries/LibWeb/Layout/Node.cpp index 3516d9889468..0d9a896d6863 100644 --- a/Libraries/LibWeb/Layout/Node.cpp +++ b/Libraries/LibWeb/Layout/Node.cpp @@ -1043,6 +1043,11 @@ void NodeWithStyle::reset_table_box_computed_values_used_by_wrapper_to_init_valu mutable_computed_values.set_clear(CSS::InitialValues::clear()); mutable_computed_values.set_inset(CSS::InitialValues::inset()); mutable_computed_values.set_margin(CSS::InitialValues::margin()); + // AD-HOC: + // To match other browsers, z-index needs to be moved to the wrapper box as well, + // even if the spec does not mention that: https://github.com/w3c/csswg-drafts/issues/11689 + // Note that there may be more properties that need to be added to this list. + mutable_computed_values.set_z_index(CSS::InitialValues::z_index()); } void NodeWithStyle::transfer_table_box_computed_values_to_wrapper_computed_values(CSS::ComputedValues& wrapper_computed_values) @@ -1060,6 +1065,12 @@ void NodeWithStyle::transfer_table_box_computed_values_to_wrapper_computed_value mutable_wrapper_computed_values.set_float(computed_values().float_()); mutable_wrapper_computed_values.set_clear(computed_values().clear()); mutable_wrapper_computed_values.set_margin(computed_values().margin()); + // AD-HOC: + // To match other browsers, z-index needs to be moved to the wrapper box as well, + // even if the spec does not mention that: https://github.com/w3c/csswg-drafts/issues/11689 + // Note that there may be more properties that need to be added to this list. + mutable_wrapper_computed_values.set_z_index(computed_values().z_index()); + reset_table_box_computed_values_used_by_wrapper_to_init_values(); } diff --git a/Tests/LibWeb/Ref/expected/tables-width-z-index-ref.html b/Tests/LibWeb/Ref/expected/tables-width-z-index-ref.html new file mode 100644 index 000000000000..5f3a0c4ad87a --- /dev/null +++ b/Tests/LibWeb/Ref/expected/tables-width-z-index-ref.html @@ -0,0 +1,26 @@ +<!DOCTYPE html> +<style> +div { + background-color: green; + position: fixed; + width: 100px; + height: 100px; +} +.offset-0 { top: 10px; } +.offset-1 { top: 120px; } +.offset-2 { top: 230px; } +.offset-3 { top: 340px; } +.offset-4 { top: 450px; } +.offset-5 { top: 560px; } +.offset-6 { top: 670px; } +.offset-7 { top: 780px; } +</style> + +<div class="offset-0"></div> +<div class="offset-1"></div> +<div class="offset-2"></div> +<div class="offset-3"></div> +<div class="offset-4"></div> +<div class="offset-5"></div> +<div class="offset-6"></div> +<div class="offset-7"></div> diff --git a/Tests/LibWeb/Ref/input/tables-with-z-index.html b/Tests/LibWeb/Ref/input/tables-with-z-index.html new file mode 100644 index 000000000000..3efa27b32e4d --- /dev/null +++ b/Tests/LibWeb/Ref/input/tables-with-z-index.html @@ -0,0 +1,44 @@ +<!DOCTYPE html> +<link rel="match" value="../expected/tables-with-z-index-ref.html"> +<style> +div, table { width: 100px; height: 100px; } +.table { display: table; } +.red { background-color: red; } +.green { background-color: green; } +.fixed { position: fixed; } +.absolute { position: absolute; } +.offset-0 { top: 10px; } +.offset-1 { top: 120px; } +.offset-2 { top: 230px; } +.offset-3 { top: 340px; } +.offset-4 { top: 450px; } +.offset-5 { top: 560px; } +.offset-6 { top: 670px; } +.offset-7 { top: 780px; } +.z-index-1 { z-index: 1; } +.z-index-2 { z-index: 2; } +</style> + +<div class="red fixed offset-0 z-index-1"></div> +<div class="table green fixed offset-0 z-index-2"></div> + +<div class="table green fixed offset-1 z-index-1"></div> +<div class="red fixed offset-1"></div> + +<div class="red fixed offset-2 z-index-1"></div> +<table class="green fixed offset-2 z-index-2"></table> + +<table class="green fixed offset-3 z-index-1"></table> +<div class="red fixed offset-3"></div> + +<div class="red absolute offset-4 z-index-1"></div> +<div class="table green absolute offset-4 z-index-2"></div> + +<div class="table green absolute offset-5 z-index-1"></div> +<div class="red absolute offset-5"></div> + +<div class="red absolute offset-6 z-index-1"></div> +<table class="green absolute offset-6 z-index-2"></table> + +<table class="green absolute offset-7 z-index-1"></table> +<div class="red absolute offset-7"></div>
244b243d22d9c0a7da29d16bd023f95388da8fdf
2020-06-21 16:07:34
Andreas Kling
libweb: Add EventTarget.removeEventListener()
false
Add EventTarget.removeEventListener()
libweb
diff --git a/Libraries/LibWeb/DOM/EventTarget.cpp b/Libraries/LibWeb/DOM/EventTarget.cpp index 1af0b18458ba..4f543feb6113 100644 --- a/Libraries/LibWeb/DOM/EventTarget.cpp +++ b/Libraries/LibWeb/DOM/EventTarget.cpp @@ -42,4 +42,11 @@ void EventTarget::add_event_listener(const FlyString& event_name, NonnullRefPtr< m_listeners.append({ event_name, move(listener) }); } +void EventTarget::remove_event_listener(const FlyString& event_name, NonnullRefPtr<EventListener> listener) +{ + m_listeners.remove_first_matching([&](auto& entry) { + return entry.event_name == event_name && &entry.listener->function() == &listener->function(); + }); +} + } diff --git a/Libraries/LibWeb/DOM/EventTarget.h b/Libraries/LibWeb/DOM/EventTarget.h index b322336b57cb..17e421ec824b 100644 --- a/Libraries/LibWeb/DOM/EventTarget.h +++ b/Libraries/LibWeb/DOM/EventTarget.h @@ -44,6 +44,7 @@ class EventTarget { void unref() { unref_event_target(); } void add_event_listener(const FlyString& event_name, NonnullRefPtr<EventListener>); + void remove_event_listener(const FlyString& event_name, NonnullRefPtr<EventListener>); virtual void dispatch_event(NonnullRefPtr<Event>) = 0; diff --git a/Libraries/LibWeb/DOM/EventTarget.idl b/Libraries/LibWeb/DOM/EventTarget.idl index 32c6c76370bc..13debb223551 100644 --- a/Libraries/LibWeb/DOM/EventTarget.idl +++ b/Libraries/LibWeb/DOM/EventTarget.idl @@ -1,5 +1,6 @@ interface EventTarget { void addEventListener(DOMString type, EventListener? callback); + void removeEventListener(DOMString type, EventListener? callback); }
83aa868c17483e7ed37686461b5e2f9e8566e8c3
2020-02-24 15:57:03
Liav A
kernel: Update PATAChannel class to use the PCI::Device class
false
Update PATAChannel class to use the PCI::Device class
kernel
diff --git a/Kernel/Devices/PATAChannel.h b/Kernel/Devices/PATAChannel.h index 02da8e6bf65f..ba8264ab5f6e 100644 --- a/Kernel/Devices/PATAChannel.h +++ b/Kernel/Devices/PATAChannel.h @@ -38,9 +38,9 @@ #include <AK/OwnPtr.h> #include <AK/RefPtr.h> -#include <Kernel/IRQHandler.h> #include <Kernel/Lock.h> #include <Kernel/PCI/Access.h> +#include <Kernel/PCI/Device.h> #include <Kernel/VM/PhysicalPage.h> #include <Kernel/WaitQueue.h> #include <LibBareMetal/Memory/PhysicalAddress.h> @@ -54,7 +54,7 @@ struct PhysicalRegionDescriptor { }; class PATADiskDevice; -class PATAChannel final : public IRQHandler { +class PATAChannel final : public PCI::Device { friend class PATADiskDevice; AK_MAKE_ETERNAL public: @@ -65,7 +65,7 @@ class PATAChannel final : public IRQHandler { public: static OwnPtr<PATAChannel> create(ChannelType type, bool force_pio); - PATAChannel(ChannelType type, bool force_pio); + PATAChannel(PCI::Address address, ChannelType type, bool force_pio); virtual ~PATAChannel() override; RefPtr<PATADiskDevice> master_device() { return m_master; }; @@ -73,7 +73,7 @@ class PATAChannel final : public IRQHandler { private: //^ IRQHandler - virtual void handle_irq() override; + virtual void handle_irq(RegisterState&) override; void initialize(bool force_pio); void detect_disks(); @@ -92,7 +92,6 @@ class PATAChannel final : public IRQHandler { WaitQueue m_irq_queue; - PCI::Address m_pci_address; PhysicalRegionDescriptor& prdt() { return *reinterpret_cast<PhysicalRegionDescriptor*>(m_prdt_page->paddr().offset(0xc0000000).as_ptr()); } RefPtr<PhysicalPage> m_prdt_page; RefPtr<PhysicalPage> m_dma_buffer_page; @@ -102,5 +101,4 @@ class PATAChannel final : public IRQHandler { RefPtr<PATADiskDevice> m_master; RefPtr<PATADiskDevice> m_slave; }; - }
107ca2e4ba8f88f39f58c4a92d238ea642aa0d39
2020-05-06 22:49:02
Matthew Olsson
libjs: Add function call spreading
false
Add function call spreading
libjs
diff --git a/Libraries/LibJS/AST.cpp b/Libraries/LibJS/AST.cpp index 7c67f6097fe9..a3537577e9f6 100644 --- a/Libraries/LibJS/AST.cpp +++ b/Libraries/LibJS/AST.cpp @@ -137,12 +137,28 @@ Value CallExpression::execute(Interpreter& interpreter) const arguments.values().append(function.bound_arguments()); for (size_t i = 0; i < m_arguments.size(); ++i) { - auto value = m_arguments[i].execute(interpreter); - if (interpreter.exception()) - return {}; - arguments.append(value); + auto value = m_arguments[i].value->execute(interpreter); if (interpreter.exception()) return {}; + if (m_arguments[i].is_spread) { + // FIXME: Support generic iterables + Vector<Value> iterables; + if (value.is_string()) { + for (auto ch : value.as_string().string()) + iterables.append(Value(js_string(interpreter, String::format("%c", ch)))); + } else if (value.is_object() && value.as_object().is_array()) { + iterables = static_cast<const Array&>(value.as_object()).elements(); + } else if (value.is_object() && value.as_object().is_string_object()) { + for (auto ch : static_cast<const StringObject&>(value.as_object()).primitive_string().string()) + iterables.append(Value(js_string(interpreter, String::format("%c", ch)))); + } else { + interpreter.throw_exception<TypeError>(String::format("%s is not iterable", value.to_string())); + } + for (auto& value : iterables) + arguments.append(value); + } else { + arguments.append(value); + } } auto& call_frame = interpreter.push_call_frame(); @@ -657,7 +673,7 @@ void CallExpression::dump(int indent) const printf("CallExpression %s\n", is_new_expression() ? "[new]" : ""); m_callee->dump(indent + 1); for (auto& argument : m_arguments) - argument.dump(indent + 1); + argument.value->dump(indent + 1); } void StringLiteral::dump(int indent) const diff --git a/Libraries/LibJS/AST.h b/Libraries/LibJS/AST.h index 92308db809f2..af753de8302f 100644 --- a/Libraries/LibJS/AST.h +++ b/Libraries/LibJS/AST.h @@ -567,7 +567,12 @@ class ThisExpression final : public Expression { class CallExpression : public Expression { public: - CallExpression(NonnullRefPtr<Expression> callee, NonnullRefPtrVector<Expression> arguments = {}) + struct Argument { + NonnullRefPtr<Expression> value; + bool is_spread; + }; + + CallExpression(NonnullRefPtr<Expression> callee, Vector<Argument> arguments = {}) : m_callee(move(callee)) , m_arguments(move(arguments)) { @@ -586,12 +591,12 @@ class CallExpression : public Expression { ThisAndCallee compute_this_and_callee(Interpreter&) const; NonnullRefPtr<Expression> m_callee; - const NonnullRefPtrVector<Expression> m_arguments; + const Vector<Argument> m_arguments; }; class NewExpression final : public CallExpression { public: - NewExpression(NonnullRefPtr<Expression> callee, NonnullRefPtrVector<Expression> arguments = {}) + NewExpression(NonnullRefPtr<Expression> callee, Vector<Argument> arguments = {}) : CallExpression(move(callee), move(arguments)) { } diff --git a/Libraries/LibJS/Parser.cpp b/Libraries/LibJS/Parser.cpp index 309350c7a11d..05568e7dd431 100644 --- a/Libraries/LibJS/Parser.cpp +++ b/Libraries/LibJS/Parser.cpp @@ -777,10 +777,15 @@ NonnullRefPtr<CallExpression> Parser::parse_call_expression(NonnullRefPtr<Expres { consume(TokenType::ParenOpen); - NonnullRefPtrVector<Expression> arguments; + Vector<CallExpression::Argument> arguments; - while (match_expression()) { - arguments.append(parse_expression(0)); + while (match_expression() || match(TokenType::TripleDot)) { + if (match(TokenType::TripleDot)) { + consume(); + arguments.append({ parse_expression(0), true }); + } else { + arguments.append({ parse_expression(0), false }); + } if (!match(TokenType::Comma)) break; consume(); @@ -798,12 +803,17 @@ NonnullRefPtr<NewExpression> Parser::parse_new_expression() // FIXME: Support full expressions as the callee as well. auto callee = create_ast_node<Identifier>(consume(TokenType::Identifier).value()); - NonnullRefPtrVector<Expression> arguments; + Vector<CallExpression::Argument> arguments; if (match(TokenType::ParenOpen)) { consume(TokenType::ParenOpen); - while (match_expression()) { - arguments.append(parse_expression(0)); + while (match_expression() || match(TokenType::TripleDot)) { + if (match(TokenType::TripleDot)) { + consume(); + arguments.append({ parse_expression(0), true }); + } else { + arguments.append({ parse_expression(0), false }); + } if (!match(TokenType::Comma)) break; consume(); diff --git a/Libraries/LibJS/Tests/function-spread.js b/Libraries/LibJS/Tests/function-spread.js new file mode 100644 index 000000000000..f7d7d2ea2f48 --- /dev/null +++ b/Libraries/LibJS/Tests/function-spread.js @@ -0,0 +1,27 @@ +load("test-common.js"); + +try { + const sum = (a, b, c) => a + b + c; + const a = [1, 2, 3]; + + assert(sum(...a) === 6); + assert(sum(1, ...a) === 4); + assert(sum(...a, 10) === 6); + + const foo = (a, b, c) => c; + + const o = { bar: [1, 2, 3] }; + assert(foo(...o.bar) === 3); + assert(foo(..."abc") === "c"); + + assertThrowsError(() => { + [...1]; + }, { + error: TypeError, + message: "1 is not iterable", + }); + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}
cbc450c24e67cfbf31b4b8f5f481ecc42cae596c
2021-02-28 19:57:53
Tom
kernel: Fix KUBSAN warnings due to unaligned APIC variables
false
Fix KUBSAN warnings due to unaligned APIC variables
kernel
diff --git a/Kernel/Arch/i386/Boot/boot.S b/Kernel/Arch/i386/Boot/boot.S index b55acf9caec9..f9630206e0d5 100644 --- a/Kernel/Arch/i386/Boot/boot.S +++ b/Kernel/Arch/i386/Boot/boot.S @@ -378,6 +378,7 @@ apic_ap_start32_2: .global apic_ap_start_size apic_ap_start_size: .2byte end_apic_ap_start - apic_ap_start +.align 4 ap_cpu_id: .4byte 0x0 ap_cpu_gdt:
ca02c433d2371db9b660ad4559176391301cb805
2023-04-04 00:24:36
MacDue
libweb: Add getter for separator to StyleValueList
false
Add getter for separator to StyleValueList
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h b/Userland/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h index 2006ef1820da..1ab22f6a7f77 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h @@ -34,6 +34,8 @@ class StyleValueList final : public StyleValueWithDefaultOperators<StyleValueLis bool properties_equal(StyleValueList const& other) const { return m_properties == other.m_properties; } + Separator separator() const { return m_properties.separator; } + private: StyleValueList(StyleValueVector&& values, Separator separator) : StyleValueWithDefaultOperators(Type::ValueList)
addfa1e82e9208139377c56fd5f1a7580a90ad4d
2021-07-10 17:03:08
Ali Mohammad Pur
libregex: Make the bytecode transformation functions static
false
Make the bytecode transformation functions static
libregex
diff --git a/Userland/Libraries/LibRegex/RegexByteCode.h b/Userland/Libraries/LibRegex/RegexByteCode.h index 4ab85fd9674b..d53ab64462e6 100644 --- a/Userland/Libraries/LibRegex/RegexByteCode.h +++ b/Userland/Libraries/LibRegex/RegexByteCode.h @@ -347,7 +347,7 @@ class ByteCode : public Vector<ByteCodeValueType> { // LABEL _END = alterantive_bytecode.size } - void insert_bytecode_repetition_min_max(ByteCode& bytecode_to_repeat, size_t minimum, Optional<size_t> maximum, bool greedy = true) + static void transform_bytecode_repetition_min_max(ByteCode& bytecode_to_repeat, size_t minimum, Optional<size_t> maximum, bool greedy = true) { ByteCode new_bytecode; new_bytecode.insert_bytecode_repetition_n(bytecode_to_repeat, minimum); @@ -381,7 +381,7 @@ class ByteCode : public Vector<ByteCodeValueType> { extend(bytecode_to_repeat); } - void insert_bytecode_repetition_min_one(ByteCode& bytecode_to_repeat, bool greedy) + static void transform_bytecode_repetition_min_one(ByteCode& bytecode_to_repeat, bool greedy) { // LABEL _START = -bytecode_to_repeat.size() // REGEXP @@ -395,7 +395,7 @@ class ByteCode : public Vector<ByteCodeValueType> { bytecode_to_repeat.empend(-(bytecode_to_repeat.size() + 1)); // Jump to the _START label } - void insert_bytecode_repetition_any(ByteCode& bytecode_to_repeat, bool greedy) + static void transform_bytecode_repetition_any(ByteCode& bytecode_to_repeat, bool greedy) { // LABEL _START // FORKJUMP _END (FORKSTAY -> Greedy) @@ -423,7 +423,7 @@ class ByteCode : public Vector<ByteCodeValueType> { bytecode_to_repeat = move(bytecode); } - void insert_bytecode_repetition_zero_or_one(ByteCode& bytecode_to_repeat, bool greedy) + static void transform_bytecode_repetition_zero_or_one(ByteCode& bytecode_to_repeat, bool greedy) { // FORKJUMP _END (FORKSTAY -> Greedy) // REGEXP diff --git a/Userland/Libraries/LibRegex/RegexParser.cpp b/Userland/Libraries/LibRegex/RegexParser.cpp index a3a271036fa3..f40a6865087f 100644 --- a/Userland/Libraries/LibRegex/RegexParser.cpp +++ b/Userland/Libraries/LibRegex/RegexParser.cpp @@ -232,7 +232,7 @@ ALWAYS_INLINE bool PosixExtendedParser::parse_repetition_symbol(ByteCode& byteco maybe_maximum = value.value(); } - bytecode_to_repeat.insert_bytecode_repetition_min_max(bytecode_to_repeat, minimum, maybe_maximum); + ByteCode::transform_bytecode_repetition_min_max(bytecode_to_repeat, minimum, maybe_maximum); consume(TokenType::RightCurly, Error::MismatchingBrace); return !has_error(); @@ -245,7 +245,7 @@ ALWAYS_INLINE bool PosixExtendedParser::parse_repetition_symbol(ByteCode& byteco consume(); // Note: don't touch match_length_minimum, it's already correct - bytecode_to_repeat.insert_bytecode_repetition_min_one(bytecode_to_repeat, !nongreedy); + ByteCode::transform_bytecode_repetition_min_one(bytecode_to_repeat, !nongreedy); return !has_error(); } else if (match(TokenType::Asterisk)) { @@ -256,7 +256,7 @@ ALWAYS_INLINE bool PosixExtendedParser::parse_repetition_symbol(ByteCode& byteco if (nongreedy) consume(); - bytecode_to_repeat.insert_bytecode_repetition_any(bytecode_to_repeat, !nongreedy); + ByteCode::transform_bytecode_repetition_any(bytecode_to_repeat, !nongreedy); return !has_error(); @@ -268,7 +268,7 @@ ALWAYS_INLINE bool PosixExtendedParser::parse_repetition_symbol(ByteCode& byteco if (nongreedy) consume(); - bytecode_to_repeat.insert_bytecode_repetition_zero_or_one(bytecode_to_repeat, !nongreedy); + ByteCode::transform_bytecode_repetition_zero_or_one(bytecode_to_repeat, !nongreedy); return !has_error(); } @@ -956,21 +956,20 @@ bool ECMA262Parser::parse_quantifier(ByteCode& stack, size_t& match_length_minim ungreedy = true; } - ByteCode new_bytecode; switch (repetition_mark) { case Repetition::OneOrMore: - new_bytecode.insert_bytecode_repetition_min_one(stack, !ungreedy); + ByteCode::transform_bytecode_repetition_min_one(stack, !ungreedy); break; case Repetition::ZeroOrMore: - new_bytecode.insert_bytecode_repetition_any(stack, !ungreedy); + ByteCode::transform_bytecode_repetition_any(stack, !ungreedy); match_length_minimum = 0; break; case Repetition::Optional: - new_bytecode.insert_bytecode_repetition_zero_or_one(stack, !ungreedy); + ByteCode::transform_bytecode_repetition_zero_or_one(stack, !ungreedy); match_length_minimum = 0; break; case Repetition::Explicit: - new_bytecode.insert_bytecode_repetition_min_max(stack, repeat_min.value(), repeat_max, !ungreedy); + ByteCode::transform_bytecode_repetition_min_max(stack, repeat_min.value(), repeat_max, !ungreedy); match_length_minimum *= repeat_min.value(); break; case Repetition::None:
b3fdeef5d727c2063d0daba15be8b44a2143d855
2024-10-14 20:50:57
Bastian Neumann
libweb: Do not accept malformed xml namespace
false
Do not accept malformed xml namespace
libweb
diff --git a/Userland/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp b/Userland/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp index a3dc5b48ddd8..d2b3c42e1d19 100644 --- a/Userland/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp +++ b/Userland/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp @@ -108,8 +108,16 @@ void XMLDocumentBuilder::element_start(const XML::Name& name, HashMap<XML::Name, // https://www.w3.org/TR/2006/REC-xml-names11-20060816/#ns-decl if (attribute.key == "xmlns" || attribute.key.starts_with("xmlns:"sv)) { auto name = attribute.key; - // The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace name http://www.w3.org/2000/xmlns/. - MUST(node->set_attribute_ns(Namespace::XMLNS, MUST(FlyString::from_deprecated_fly_string(name)), MUST(String::from_byte_string(attribute.value)))); + if (!name.is_one_of("xmlns:"sv, "xmlns:xmlns"sv)) { + // The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace name http://www.w3.org/2000/xmlns/. + MUST(node->set_attribute_ns(Namespace::XMLNS, MUST(FlyString::from_deprecated_fly_string(name)), MUST(String::from_byte_string(attribute.value)))); + } else { + m_has_error = true; + } + } else if (attribute.key.contains(":"sv)) { + if (!attribute.key.starts_with("xml:"sv)) { + m_has_error = true; + } } MUST(node->set_attribute(MUST(FlyString::from_deprecated_fly_string(attribute.key)), MUST(String::from_byte_string(attribute.value)))); }
90b12a41c8ec484b3fa4fc9b4c037b0c0c27bf7b
2020-12-05 01:36:27
Andreas Kling
libweb: Make LineBox take incoming fragment size as floats
false
Make LineBox take incoming fragment size as floats
libweb
diff --git a/Libraries/LibWeb/Layout/LineBox.cpp b/Libraries/LibWeb/Layout/LineBox.cpp index 8d2c3d63da0a..b4415ae11b3d 100644 --- a/Libraries/LibWeb/Layout/LineBox.cpp +++ b/Libraries/LibWeb/Layout/LineBox.cpp @@ -33,7 +33,7 @@ namespace Web::Layout { -void LineBox::add_fragment(Node& layout_node, int start, int length, int width, int height, LineBoxFragment::Type fragment_type) +void LineBox::add_fragment(Node& layout_node, int start, int length, float width, float height, LineBoxFragment::Type fragment_type) { bool text_align_is_justify = layout_node.style().text_align() == CSS::TextAlign::Justify; if (!text_align_is_justify && !m_fragments.is_empty() && &m_fragments.last().layout_node() == &layout_node) { diff --git a/Libraries/LibWeb/Layout/LineBox.h b/Libraries/LibWeb/Layout/LineBox.h index 5bfb71abec07..cc821d9d6ec9 100644 --- a/Libraries/LibWeb/Layout/LineBox.h +++ b/Libraries/LibWeb/Layout/LineBox.h @@ -38,7 +38,7 @@ class LineBox { float width() const { return m_width; } - void add_fragment(Node& layout_node, int start, int length, int width, int height, LineBoxFragment::Type = LineBoxFragment::Type::Normal); + void add_fragment(Node& layout_node, int start, int length, float width, float height, LineBoxFragment::Type = LineBoxFragment::Type::Normal); const NonnullOwnPtrVector<LineBoxFragment>& fragments() const { return m_fragments; } NonnullOwnPtrVector<LineBoxFragment>& fragments() { return m_fragments; }
efb69508f48645e1dc84d89e49ea8636fe4d95e9
2021-12-22 13:32:36
Idan Horowitz
libc: Add the netinet/if_ether.h header and define ETH_ALEN
false
Add the netinet/if_ether.h header and define ETH_ALEN
libc
diff --git a/Userland/Libraries/LibC/netinet/if_ether.h b/Userland/Libraries/LibC/netinet/if_ether.h new file mode 100644 index 000000000000..4b0f390c4290 --- /dev/null +++ b/Userland/Libraries/LibC/netinet/if_ether.h @@ -0,0 +1,9 @@ +/* + * Copyright (c) 2021, Idan Horowitz <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#define ETH_ALEN 6 // Length of an ethernet address (MAC) in bytes
e4037968423d4d68d099c3ece324fa32ba1122f9
2021-11-02 22:23:22
thislooksfun
libgui: Abstract out some duplicated logic for suggesting properties
false
Abstract out some duplicated logic for suggesting properties
libgui
diff --git a/Userland/Libraries/LibGUI/GMLAutocompleteProvider.cpp b/Userland/Libraries/LibGUI/GMLAutocompleteProvider.cpp index 982762d820a0..30793d8a3c08 100644 --- a/Userland/Libraries/LibGUI/GMLAutocompleteProvider.cpp +++ b/Userland/Libraries/LibGUI/GMLAutocompleteProvider.cpp @@ -122,6 +122,25 @@ void GMLAutocompleteProvider::provide_completions(Function<void(Vector<Entry>)> }; Vector<GUI::AutocompleteProvider::Entry> class_entries, identifier_entries; + + auto register_class_properties_matching_pattern = [&](String pattern, size_t partial_input_length) { + auto class_name = class_names.last(); + + // FIXME: Don't show properties that are already specified in the scope. + auto registration = Core::ObjectClassRegistration::find(class_name); + if (registration && (registration->is_derived_from(widget_class) || registration->is_derived_from(layout_class))) { + if (auto instance = registration->construct()) { + for (auto& it : instance->properties()) { + if (!it.value->is_readonly() && it.key.matches(pattern)) + identifier_entries.empend(String::formatted("{}: ", it.key), partial_input_length, Language::Unspecified, it.key); + } + } + } + + if (can_have_declared_layout(class_names.last()) && "layout"sv.matches(pattern)) + identifier_entries.empend("layout: ", partial_input_length, Language::Unspecified, "layout"); + }; + switch (state) { case Free: if (last_seen_token && last_seen_token->m_end.column != cursor.column() && last_seen_token->m_end.line == cursor.line()) { @@ -171,18 +190,8 @@ void GMLAutocompleteProvider::provide_completions(Function<void(Vector<Entry>)> // TODO: Maybe suggest a colon? break; } - auto fuzzy_identifier_string = make_fuzzy(identifier_string); - auto registration = Core::ObjectClassRegistration::find(class_names.last()); - if (registration && (registration->is_derived_from(widget_class) || registration->is_derived_from(layout_class))) { - if (auto instance = registration->construct()) { - for (auto& it : instance->properties()) { - if (it.key.matches(fuzzy_identifier_string)) - identifier_entries.empend(String::formatted("{}: ", it.key), identifier_string.length(), Language::Unspecified, it.key); - } - } - } - if (can_have_declared_layout(class_names.last()) && "layout"sv.matches(fuzzy_identifier_string)) - identifier_entries.empend("layout: ", identifier_string.length(), Language::Unspecified, "layout"); + + register_class_properties_matching_pattern(make_fuzzy(identifier_string), identifier_string.length()); break; } case AfterClassName: { @@ -193,19 +202,8 @@ void GMLAutocompleteProvider::provide_completions(Function<void(Vector<Entry>)> break; } } - if (!class_names.is_empty()) { - auto registration = Core::ObjectClassRegistration::find(class_names.last()); - if (registration && (registration->is_derived_from(widget_class) || registration->is_derived_from(layout_class))) { - if (auto instance = registration->construct()) { - for (auto& it : instance->properties()) { - if (!it.value->is_readonly()) - identifier_entries.empend(String::formatted("{}: ", it.key), 0u, Language::Unspecified, it.key); - } - } - } - } - if (can_have_declared_layout(class_names.last())) - identifier_entries.empend("layout: ", 0u, Language::Unspecified, "layout"); + if (!class_names.is_empty()) + register_class_properties_matching_pattern("*", 0u); Core::ObjectClassRegistration::for_each([&](const Core::ObjectClassRegistration& registration) { if (!registration.is_derived_from(widget_class))
a05fd28b7b2f3ab954f30714e7fcd995e7981eba
2023-12-18 03:42:34
Bastiaan van der Plaat
libweb: Move use pseudo element styles from TreeBuilder to StyleComputer
false
Move use pseudo element styles from TreeBuilder to StyleComputer
libweb
diff --git a/Tests/LibWeb/Layout/expected/element-use-pseudo-element.txt b/Tests/LibWeb/Layout/expected/element-use-pseudo-element.txt new file mode 100644 index 000000000000..2eb3401e8900 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/element-use-pseudo-element.txt @@ -0,0 +1,17 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x600 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x21.84375 children: inline + line 0 width: 300, height: 21.84375, bottom: 21.84375, baseline: 16.921875 + frag 0 from BlockContainer start: 0, length: 0, rect: [8,12 300x12] + BlockContainer <progress#a> at (8,12) content-size 300x12 inline-block [BFC] children: not-inline + BlockContainer <div> at (9,13) content-size 298x12 children: not-inline + BlockContainer <div> at (9,13) content-size 298x12 children: not-inline + TextNode <#text> + TextNode <#text> + +ViewportPaintable (Viewport<#document>) [0,0 800x600] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x600] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x21.84375] + PaintableWithLines (BlockContainer<PROGRESS>#a) [8,12 300x12] overflow: [8,12 300x14] + PaintableWithLines (BlockContainer<DIV>) [8,12 300x14] + PaintableWithLines (BlockContainer<DIV>) [9,13 298x12] diff --git a/Tests/LibWeb/Layout/input/element-use-pseudo-element.html b/Tests/LibWeb/Layout/input/element-use-pseudo-element.html new file mode 100644 index 000000000000..d94848d5404f --- /dev/null +++ b/Tests/LibWeb/Layout/input/element-use-pseudo-element.html @@ -0,0 +1,9 @@ +<style> + * { + font: 20px 'SerenitySans'; + } +</style> +<progress id="a"></progress> +<script> + a.style.backgroundColor = 'red'; // Trigger style invalidation +</script> diff --git a/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp index 9596f9dedbd5..792922821e56 100644 --- a/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp +++ b/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp @@ -59,11 +59,6 @@ String PropertyOwningCSSStyleDeclaration::item(size_t index) const return MUST(String::from_utf8(CSS::string_from_property_id(m_properties[index].property_id))); } -CSS::PropertyID PropertyOwningCSSStyleDeclaration::property_id_by_index(size_t index) const -{ - return m_properties[index].property_id; -} - JS::NonnullGCPtr<ElementInlineCSSStyleDeclaration> ElementInlineCSSStyleDeclaration::create(DOM::Element& element, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties) { auto& realm = element.realm(); diff --git a/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.h b/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.h index 864ccfda362d..b485a6169dbf 100644 --- a/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.h +++ b/Userland/Libraries/LibWeb/CSS/CSSStyleDeclaration.h @@ -24,7 +24,6 @@ class CSSStyleDeclaration : public Bindings::PlatformObject { virtual size_t length() const = 0; virtual String item(size_t index) const = 0; - virtual CSS::PropertyID property_id_by_index(size_t index) const = 0; virtual Optional<StyleProperty> property(PropertyID) const = 0; @@ -64,7 +63,6 @@ class PropertyOwningCSSStyleDeclaration : public CSSStyleDeclaration { virtual size_t length() const override; virtual String item(size_t index) const override; - virtual CSS::PropertyID property_id_by_index(size_t index) const override; virtual Optional<StyleProperty> property(PropertyID) const override; diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp index a8246800f8fd..0b2f71d216c3 100644 --- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp +++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.cpp @@ -82,11 +82,6 @@ String ResolvedCSSStyleDeclaration::item(size_t index) const return MUST(String::from_utf8(string_from_property_id(property_id))); } -CSS::PropertyID ResolvedCSSStyleDeclaration::property_id_by_index(size_t index) const -{ - return static_cast<PropertyID>(index + to_underlying(first_longhand_property_id)); -} - static NonnullRefPtr<StyleValue const> style_value_for_background_property(Layout::NodeWithStyle const& layout_node, Function<NonnullRefPtr<StyleValue const>(BackgroundLayerData const&)> callback, Function<NonnullRefPtr<StyleValue const>()> default_value) { auto const& background_layers = layout_node.background_layers(); diff --git a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h index 8682e0ff48d3..422f82d1a3e8 100644 --- a/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h +++ b/Userland/Libraries/LibWeb/CSS/ResolvedCSSStyleDeclaration.h @@ -21,7 +21,6 @@ class ResolvedCSSStyleDeclaration final : public CSSStyleDeclaration { virtual size_t length() const override; virtual String item(size_t index) const override; - virtual CSS::PropertyID property_id_by_index(size_t index) const override; virtual Optional<StyleProperty> property(PropertyID) const override; virtual WebIDL::ExceptionOr<void> set_property(PropertyID, StringView css_text, StringView priority) override; diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp index 79a295befbc7..8dcb2a31fac8 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp @@ -2136,6 +2136,20 @@ ErrorOr<RefPtr<StyleProperties>> StyleComputer::compute_style_impl(DOM::Element& { build_rule_cache_if_needed(); + // Special path for elements that use pseudo element as style selector + if (element.use_pseudo_element().has_value()) { + auto& parent_element = verify_cast<HTML::HTMLElement>(*element.root().parent_or_shadow_host()); + auto style = TRY(compute_style(parent_element, *element.use_pseudo_element())); + + // Merge back inline styles + if (element.has_attribute(HTML::AttributeNames::style)) { + auto* inline_style = parse_css_style_attribute(CSS::Parser::ParsingContext(document()), *element.get_attribute(HTML::AttributeNames::style), element); + for (auto const& property : inline_style->properties()) + style->set_property(property.property_id, property.value); + } + return style; + } + auto style = StyleProperties::create(); // 1. Perform the cascade. This produces the "specified style" bool did_match_any_pseudo_element_rules = false; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLMeterElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLMeterElement.cpp index d42c1daf8dfb..e677cdbbd3fd 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLMeterElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLMeterElement.cpp @@ -55,7 +55,6 @@ WebIDL::ExceptionOr<void> HTMLMeterElement::set_value(double value) { TRY(set_attribute(HTML::AttributeNames::value, MUST(String::number(value)))); update_meter_value_element(); - document().invalidate_layout(); return {}; } @@ -74,7 +73,6 @@ WebIDL::ExceptionOr<void> HTMLMeterElement::set_min(double value) { TRY(set_attribute(HTML::AttributeNames::min, MUST(String::number(value)))); update_meter_value_element(); - document().invalidate_layout(); return {}; } @@ -96,7 +94,6 @@ WebIDL::ExceptionOr<void> HTMLMeterElement::set_max(double value) { TRY(set_attribute(HTML::AttributeNames::max, MUST(String::number(value)))); update_meter_value_element(); - document().invalidate_layout(); return {}; } @@ -120,7 +117,6 @@ WebIDL::ExceptionOr<void> HTMLMeterElement::set_low(double value) { TRY(set_attribute(HTML::AttributeNames::low, MUST(String::number(value)))); update_meter_value_element(); - document().invalidate_layout(); return {}; } @@ -144,7 +140,6 @@ WebIDL::ExceptionOr<void> HTMLMeterElement::set_high(double value) { TRY(set_attribute(HTML::AttributeNames::high, MUST(String::number(value)))); update_meter_value_element(); - document().invalidate_layout(); return {}; } @@ -168,7 +163,6 @@ WebIDL::ExceptionOr<void> HTMLMeterElement::set_optimum(double value) { TRY(set_attribute(HTML::AttributeNames::optimum, MUST(String::number(value)))); update_meter_value_element(); - document().invalidate_layout(); return {}; } diff --git a/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp index c5ac8a5a547f..bf394a134e89 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp @@ -53,7 +53,6 @@ WebIDL::ExceptionOr<void> HTMLProgressElement::set_value(double value) TRY(set_attribute(HTML::AttributeNames::value, MUST(String::number(value)))); update_progress_value_element(); - document().invalidate_layout(); return {}; } @@ -74,7 +73,6 @@ WebIDL::ExceptionOr<void> HTMLProgressElement::set_max(double value) TRY(set_attribute(HTML::AttributeNames::max, MUST(String::number(value)))); update_progress_value_element(); - document().invalidate_layout(); return {}; } diff --git a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp index 3cb37b854531..3b61ce936e66 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLSelectElement.cpp @@ -213,7 +213,6 @@ WebIDL::ExceptionOr<void> HTMLSelectElement::set_value(String const& value) for (auto const& option_element : list_of_options()) option_element->set_selected(option_element->value() == value); update_inner_text_element(); - document().invalidate_layout(); // When the user agent is to send select update notifications, queue an element task on the user interaction task source given the select element to run these steps: queue_an_element_task(HTML::Task::Source::UserInteraction, [this] { @@ -323,7 +322,6 @@ void HTMLSelectElement::form_associated_element_was_inserted() if (options.size() > 0) { options.at(0)->set_selected(true); update_inner_text_element(); - document().invalidate_layout(); } } }); diff --git a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp index 47ef98f662ed..4e490935474a 100644 --- a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp +++ b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp @@ -313,32 +313,10 @@ ErrorOr<void> TreeBuilder::create_layout_tree(DOM::Node& dom_node, TreeBuilder:: if (is<DOM::Element>(dom_node)) { auto& element = static_cast<DOM::Element&>(dom_node); - - // Special path for elements that use pseudo element as style selector. - if (element.use_pseudo_element().has_value()) { - // Get base psuedo element selector style properties - auto& parent_element = verify_cast<HTML::HTMLElement>(*element.root().parent_or_shadow_host()); - style = TRY(style_computer.compute_style(parent_element, *element.use_pseudo_element())); - - // Merge back inline styles - auto const* inline_style = element.inline_style(); - if (inline_style) { - auto const& computed_style = element.computed_css_values(); - for (size_t i = 0; i < inline_style->length(); i++) { - auto property_id = inline_style->property_id_by_index(i); - if (auto property = computed_style->maybe_null_property(property_id); property) - style->set_property(property_id, *property); - } - } - display = style->display(); - } - // Common path: this is a regular DOM element. Style should be present already, thanks to Document::update_style(). - else { - element.clear_pseudo_element_nodes({}); - VERIFY(!element.needs_style_update()); - style = element.computed_css_values(); - display = style->display(); - } + element.clear_pseudo_element_nodes({}); + VERIFY(!element.needs_style_update()); + style = element.computed_css_values(); + display = style->display(); if (display.is_none()) return {}; layout_node = element.create_layout_node(*style);
b1fe6c3f6848f68b540b2f4d472fdacaf2243782
2022-07-01 03:30:05
Idan Horowitz
libjs: Implement the PartitionDurationFormatPattern abstract operation
false
Implement the PartitionDurationFormatPattern abstract operation
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp index cbc698c0149f..bb48da575039 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp @@ -4,8 +4,15 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/Intl/DurationFormat.h> +#include <LibJS/Runtime/Intl/ListFormat.h> +#include <LibJS/Runtime/Intl/ListFormatConstructor.h> +#include <LibJS/Runtime/Intl/NumberFormatConstructor.h> +#include <LibJS/Runtime/Intl/PluralRules.h> +#include <LibJS/Runtime/Intl/PluralRulesConstructor.h> +#include <LibJS/Runtime/Intl/RelativeTimeFormat.h> #include <LibJS/Runtime/Temporal/AbstractOperations.h> namespace JS::Intl { @@ -232,4 +239,213 @@ ThrowCompletionOr<DurationUnitOptions> get_duration_unit_options(GlobalObject& g return DurationUnitOptions { .style = move(style), .display = display.as_string().string() }; } +// FIXME: LibUnicode currently only exposes unit patterns converted to an ECMA402 NumberFormat-specific format, +// since DurationFormat only needs a tiny subset of it, it's much easier to just convert it to the expected format +// here, but at some point we should split the the NumberFormat exporter to export both formats of the data. +static String convert_number_format_pattern_to_duration_format_template(Unicode::NumberFormat const& number_format) +{ + auto result = number_format.zero_format.replace("{number}", "{0}"); + + for (size_t i = 0; i < number_format.identifiers.size(); ++i) + result = result.replace(String::formatted("{{unitIdentifier:{}}}", i), number_format.identifiers[i]); + + return result; +} + +// 1.1.3 PartitionDurationFormatPattern ( durationFormat, duration ), https://tc39.es/proposal-intl-duration-format/#sec-partitiondurationformatpattern +ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(GlobalObject& global_object, DurationFormat const& duration_format, Temporal::DurationRecord const& duration) +{ + auto& vm = global_object.vm(); + + // 1. Let result be a new empty List. + Vector<PatternPartition> result; + + // 2. For each row in Table 1, except the header row, in table order, do + for (size_t i = 0; i < duration_instances_components.size(); ++i) { + auto const& duration_instances_component = duration_instances_components[i]; + + // a. Let styleSlot be the Style Slot value. + auto style_slot = duration_instances_component.get_style_slot; + + decltype(DurationInstanceComponent::get_style_slot) next_style_slot = nullptr; + // FIXME: Missing spec step - If this is not the last row + if (i < duration_instances_components.size() - 1) { + // b. Let nextStyleSlot be the Style Slot value of the next row. + next_style_slot = duration_instances_components[i + 1].get_style_slot; + } + + // c. Let displaySlot be the Display Slot value. + auto display_slot = duration_instances_component.get_display_slot; + + // d. Let valueSlot be the Value Slot value. + auto value_slot = duration_instances_component.value_slot; + + // e. Let unit be the Unit value. + auto unit = duration_instances_component.unit; + + // f. Let style be the current value of the styleSlot slot of durationFormat. + auto style = (duration_format.*style_slot)(); + + DurationFormat::ValueStyle next_style = DurationFormat::ValueStyle::Long; + // FIXME: Missing spec step - If this is not the last row + if (next_style_slot) { + // g. Let nextStyle be the current value of the nextStyleSlot slot of durationFormat. + next_style = (duration_format.*next_style_slot)(); + } + + // h. Let nfOpts be ! OrdinaryObjectCreate(null). + auto* number_format_options = Object::create(global_object, nullptr); + + // i. Let value be 0. + auto value = Value(0); + + // j. Let done be false. + auto done = false; + + // k. If unit is "seconds", "milliseconds" or "microseconds" and nextStyle is "numeric", then + if (unit.is_one_of("seconds"sv, "milliseconds"sv, "microseconds"sv) && next_style == DurationFormat::ValueStyle::Numeric) { + // i. Set value to duration.[[Microseconds]] + duration.[[Nanoseconds]] / 1000. + auto value_number = duration.microseconds + (duration.nanoseconds / 1000); + + // ii. If unit is "seconds" or "milliseconds", then + if (unit.is_one_of("seconds"sv, "milliseconds"sv)) { + // 1. Set value to duration.[[Milliseconds]] + value / 1000. + value_number = duration.milliseconds + (value_number / 1000); + + // 2. If unit is "seconds", then + if (unit == "seconds"sv) { + // a. Set value to duration.[[Seconds]] + value / 1000. + value_number = duration.seconds + (value_number / 1000); + } + } + value = Value(value_number); + + // iii. Perform ! CreateDataPropertyOrThrow(nfOpts, "maximumFractionDigits", durationFormat.[[FractionalDigits]]). + MUST(number_format_options->create_data_property_or_throw(vm.names.maximumFractionDigits, duration_format.has_fractional_digits() ? Value(duration_format.fractional_digits()) : js_undefined())); + + // iv. Set done to true. + done = true; + } + // l. Else, + else { + // i. Set value to the current value of the valueSlot slot of duration. + value = Value(duration.*value_slot); + } + + // m. If style is "2-digit", then + if (style == DurationFormat::ValueStyle::TwoDigit) { + // i. Perform ! CreateDataPropertyOrThrow(nfOpts, "minimumIntegerDigits", 2). + MUST(number_format_options->create_data_property_or_throw(vm.names.minimumIntegerDigits, Value(2))); + } + + // FIXME: Missing spec step - Let display be the current value of the displaySlot slot of durationFormat. + auto display = (duration_format.*display_slot)(); + + // n. If value is +0𝔽 or -0𝔽 and display is "auto", then + if ((value.is_negative_zero() || value.is_positive_zero()) && display == DurationFormat::Display::Auto) { + // i. Skip to the next iteration. + continue; + } + + // o. Let nf be ? Construct(%NumberFormat%, « durationFormat.[[Locale]], nfOpts »). + auto* number_format = static_cast<Intl::NumberFormat*>(TRY(construct(global_object, *global_object.intl_number_format_constructor(), js_string(vm, duration_format.locale()), number_format_options))); + + // FIXME: durationFormat.[[NumberFormat]] is not a thing, the spec likely means 'nf' in this case + // p. Let num be ! FormatNumeric(durationFormat.[[NumberFormat]], value). + auto number = format_numeric(global_object, *number_format, value); + + // q. Let dataLocale be durationFormat.[[DataLocale]]. + auto const& data_locale = duration_format.data_locale(); + + // r. Let dataLocaleData be the current value of the dataLocale slot of %DurationFormat%.[[LocaleData]]. + + // s. If style is "2-digit" or "numeric", then + if (style == DurationFormat::ValueStyle::TwoDigit || style == DurationFormat::ValueStyle::Numeric) { + // i. Append the new Record { [[Type]]: unit, [[Value]]: num} to the end of result. + result.append({ unit, number }); + + // ii. If unit is "hours" or "minutes", then + if (unit.is_one_of("hours"sv, "minutes"sv)) { + // 1. Let separator be dataLocaleData.[[formats]].[[digital]].[[separator]]. + auto separator = Unicode::get_number_system_symbol(data_locale, duration_format.numbering_system(), Unicode::NumericSymbol::TimeSeparator).value_or(":"sv); + + // 2. Append the new Record { [[Type]]: "literal", [[Value]]: separator} to the end of result. + result.append({ "literal", separator }); + } + } + + // t. Else, + else { + // i. Let pr be ? Construct(%PluralRules%, « durationFormat.[[Locale]] »). + // ii. Let prv be ! ResolvePlural(pr, value). + // FIXME: Use ResolvePlural when Intl.PluralRules is implemented. + auto formats = Unicode::get_unit_formats(data_locale, duration_instances_component.unit_singular, static_cast<Unicode::Style>(style)); + auto pattern = Unicode::select_pattern_with_plurality(formats, value.as_double()).release_value(); + + // iii. Let template be the current value of the prv slot of the unit slot of the style slot of dataLocaleData.[[formats]]. + auto template_ = convert_number_format_pattern_to_duration_format_template(pattern); + + // FIXME: MakePartsList takes a list, not a string, so likely missing spec step: Let fv be ! PartitionNumberPattern(nf, value). + auto formatted_value = partition_number_pattern(global_object, *number_format, value); + + // FIXME: Spec issue - see above, fv instead of num + // iv. Let parts be ! MakePartsList(template, unit, num). + auto parts = make_parts_list(template_, unit, formatted_value); + + // v. Let concat be an empty String. + StringBuilder concat; + + // vi. For each element part in parts, in List order, do + for (auto const& part : parts) { + // 1. Set concat to the string-concatenation of concat and part.[[Value]]. + concat.append(part.value); + + // FIXME: It's not clear why this step is here, the unit is functional, it should not be part of the final formatted text + // 2. If part has a [[Unit]] field, then + // if (!part.unit.is_null()) { + // // a. Set concat to the string-concatenation of concat and part.[[Unit]]. + // concat.append(part.unit); + // } + } + + // vii. Append the new Record { [[Type]]: unit, [[Value]]: concat } to the end of result. + result.append({ unit, concat.build() }); + } + + // u. If done is true, then + if (done) { + // i. Stop iteration. + break; + } + } + + // 3. Let lf be ? Construct(%ListFormat%, « durationFormat.[[Locale]] »). + auto* list_format = static_cast<Intl::ListFormat*>(TRY(construct(global_object, *global_object.intl_list_format_constructor(), js_string(vm, duration_format.locale())))); + + // FIXME: CreatePartsFromList expects a list of strings and creates a list of Pattern Partition records, but we already created a list of Pattern Partition records + // so we try to hack something together from it that looks mostly right + Vector<String> string_result; + bool merge = false; + for (size_t i = 0; i < result.size(); ++i) { + auto const& part = result[i]; + if (part.type == "literal") { + string_result.last() = String::formatted("{}{}", string_result.last(), part.value); + merge = true; + continue; + } + if (merge) { + string_result.last() = String::formatted("{}{}", string_result.last(), part.value); + merge = false; + continue; + } + string_result.append(part.value); + } + + // 4. Set result to ! CreatePartsFromList(lf, result). + auto final_result = create_parts_from_list(*list_format, string_result); + + // 5. Return result. + return final_result; +} + } diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.h b/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.h index ea59c2b60f09..4654155ec2fd 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.h @@ -32,6 +32,9 @@ class DurationFormat final : public Object { Numeric, TwoDigit }; + static_assert(to_underlying(ValueStyle::Long) == to_underlying(Unicode::Style::Long)); + static_assert(to_underlying(ValueStyle::Short) == to_underlying(Unicode::Style::Short)); + static_assert(to_underlying(ValueStyle::Narrow) == to_underlying(Unicode::Style::Narrow)); enum class Display { Auto, @@ -61,63 +64,83 @@ class DurationFormat final : public Object { String style_string() const { return style_to_string(m_style); } void set_years_style(StringView years_style) { m_years_style = date_style_from_string(years_style); } + ValueStyle years_style() const { return m_years_style; } StringView years_style_string() const { return value_style_to_string(m_years_style); } void set_years_display(StringView years_display) { m_years_display = display_from_string(years_display); } + Display years_display() const { return m_years_display; } StringView years_display_string() const { return display_to_string(m_years_display); } void set_months_style(StringView months_style) { m_months_style = date_style_from_string(months_style); } + ValueStyle months_style() const { return m_months_style; } StringView months_style_string() const { return value_style_to_string(m_months_style); } void set_months_display(StringView months_display) { m_months_display = display_from_string(months_display); } + Display months_display() const { return m_months_display; } StringView months_display_string() const { return display_to_string(m_months_display); } void set_weeks_style(StringView weeks_style) { m_weeks_style = date_style_from_string(weeks_style); } + ValueStyle weeks_style() const { return m_weeks_style; } StringView weeks_style_string() const { return value_style_to_string(m_weeks_style); } void set_weeks_display(StringView weeks_display) { m_weeks_display = display_from_string(weeks_display); } + Display weeks_display() const { return m_weeks_display; } StringView weeks_display_string() const { return display_to_string(m_weeks_display); } void set_days_style(StringView days_style) { m_days_style = date_style_from_string(days_style); } + ValueStyle days_style() const { return m_days_style; } StringView days_style_string() const { return value_style_to_string(m_days_style); } void set_days_display(StringView days_display) { m_days_display = display_from_string(days_display); } + Display days_display() const { return m_days_display; } StringView days_display_string() const { return display_to_string(m_days_display); } void set_hours_style(StringView hours_style) { m_hours_style = time_style_from_string(hours_style); } + ValueStyle hours_style() const { return m_hours_style; } StringView hours_style_string() const { return value_style_to_string(m_hours_style); } void set_hours_display(StringView hours_display) { m_hours_display = display_from_string(hours_display); } + Display hours_display() const { return m_hours_display; } StringView hours_display_string() const { return display_to_string(m_hours_display); } void set_minutes_style(StringView minutes_style) { m_minutes_style = time_style_from_string(minutes_style); } + ValueStyle minutes_style() const { return m_minutes_style; } StringView minutes_style_string() const { return value_style_to_string(m_minutes_style); } void set_minutes_display(StringView minutes_display) { m_minutes_display = display_from_string(minutes_display); } + Display minutes_display() const { return m_minutes_display; } StringView minutes_display_string() const { return display_to_string(m_minutes_display); } void set_seconds_style(StringView seconds_style) { m_seconds_style = time_style_from_string(seconds_style); } + ValueStyle seconds_style() const { return m_seconds_style; } StringView seconds_style_string() const { return value_style_to_string(m_seconds_style); } void set_seconds_display(StringView seconds_display) { m_seconds_display = display_from_string(seconds_display); } + Display seconds_display() const { return m_seconds_display; } StringView seconds_display_string() const { return display_to_string(m_seconds_display); } void set_milliseconds_style(StringView milliseconds_style) { m_milliseconds_style = sub_second_style_from_string(milliseconds_style); } + ValueStyle milliseconds_style() const { return m_milliseconds_style; } StringView milliseconds_style_string() const { return value_style_to_string(m_milliseconds_style); } void set_milliseconds_display(StringView milliseconds_display) { m_milliseconds_display = display_from_string(milliseconds_display); } + Display milliseconds_display() const { return m_milliseconds_display; } StringView milliseconds_display_string() const { return display_to_string(m_milliseconds_display); } void set_microseconds_style(StringView microseconds_style) { m_microseconds_style = sub_second_style_from_string(microseconds_style); } + ValueStyle microseconds_style() const { return m_microseconds_style; } StringView microseconds_style_string() const { return value_style_to_string(m_microseconds_style); } void set_microseconds_display(StringView microseconds_display) { m_microseconds_display = display_from_string(microseconds_display); } + Display microseconds_display() const { return m_microseconds_display; } StringView microseconds_display_string() const { return display_to_string(m_microseconds_display); } void set_nanoseconds_style(StringView nanoseconds_style) { m_nanoseconds_style = sub_second_style_from_string(nanoseconds_style); } + ValueStyle nanoseconds_style() const { return m_nanoseconds_style; } StringView nanoseconds_style_string() const { return value_style_to_string(m_nanoseconds_style); } void set_nanoseconds_display(StringView nanoseconds_display) { m_nanoseconds_display = display_from_string(nanoseconds_display); } + Display nanoseconds_display() const { return m_nanoseconds_display; } StringView nanoseconds_display_string() const { return display_to_string(m_nanoseconds_display); } void set_fractional_digits(Optional<u8> fractional_digits) { m_fractional_digits = move(fractional_digits); } @@ -163,9 +186,12 @@ class DurationFormat final : public Object { struct DurationInstanceComponent { double Temporal::DurationRecord::*value_slot; + DurationFormat::ValueStyle (DurationFormat::*get_style_slot)() const; void (DurationFormat::*set_style_slot)(StringView); + DurationFormat::Display (DurationFormat::*get_display_slot)() const; void (DurationFormat::*set_display_slot)(StringView); StringView unit; + StringView unit_singular; Span<StringView const> values; StringView digital_default; }; @@ -175,16 +201,16 @@ static constexpr AK::Array<StringView, 3> date_values = { "long"sv, "short"sv, " static constexpr AK::Array<StringView, 5> time_values = { "long"sv, "short"sv, "narrow"sv, "numeric"sv, "2-digit"sv }; static constexpr AK::Array<StringView, 4> sub_second_values = { "long"sv, "short"sv, "narrow"sv, "numeric"sv }; static constexpr AK::Array<DurationInstanceComponent, 10> duration_instances_components { - DurationInstanceComponent { &Temporal::DurationRecord::years, &DurationFormat::set_years_style, &DurationFormat::set_years_display, "years"sv, date_values, "narrow"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::months, &DurationFormat::set_months_style, &DurationFormat::set_months_display, "months"sv, date_values, "narrow"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::weeks, &DurationFormat::set_weeks_style, &DurationFormat::set_weeks_display, "weeks"sv, date_values, "narrow"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::days, &DurationFormat::set_days_style, &DurationFormat::set_days_display, "days"sv, date_values, "narrow"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::hours, &DurationFormat::set_hours_style, &DurationFormat::set_hours_display, "hours"sv, time_values, "numeric"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::minutes, &DurationFormat::set_minutes_style, &DurationFormat::set_minutes_display, "minutes"sv, time_values, "numeric"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::seconds, &DurationFormat::set_seconds_style, &DurationFormat::set_seconds_display, "seconds"sv, time_values, "numeric"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::milliseconds, &DurationFormat::set_milliseconds_style, &DurationFormat::set_milliseconds_display, "milliseconds"sv, sub_second_values, "numeric"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::microseconds, &DurationFormat::set_microseconds_style, &DurationFormat::set_microseconds_display, "microseconds"sv, sub_second_values, "numeric"sv }, - DurationInstanceComponent { &Temporal::DurationRecord::nanoseconds, &DurationFormat::set_nanoseconds_style, &DurationFormat::set_nanoseconds_display, "nanoseconds"sv, sub_second_values, "numeric"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::years, &DurationFormat::years_style, &DurationFormat::set_years_style, &DurationFormat::years_display, &DurationFormat::set_years_display, "years"sv, "year"sv, date_values, "narrow"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::months, &DurationFormat::months_style, &DurationFormat::set_months_style, &DurationFormat::months_display, &DurationFormat::set_months_display, "months"sv, "month"sv, date_values, "narrow"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::weeks, &DurationFormat::weeks_style, &DurationFormat::set_weeks_style, &DurationFormat::weeks_display, &DurationFormat::set_weeks_display, "weeks"sv, "week"sv, date_values, "narrow"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::days, &DurationFormat::days_style, &DurationFormat::set_days_style, &DurationFormat::days_display, &DurationFormat::set_days_display, "days"sv, "day"sv, date_values, "narrow"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::hours, &DurationFormat::hours_style, &DurationFormat::set_hours_style, &DurationFormat::hours_display, &DurationFormat::set_hours_display, "hours"sv, "hour"sv, time_values, "numeric"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::minutes, &DurationFormat::minutes_style, &DurationFormat::set_minutes_style, &DurationFormat::minutes_display, &DurationFormat::set_minutes_display, "minutes"sv, "minute"sv, time_values, "numeric"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::seconds, &DurationFormat::seconds_style, &DurationFormat::set_seconds_style, &DurationFormat::seconds_display, &DurationFormat::set_seconds_display, "seconds"sv, "second"sv, time_values, "numeric"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::milliseconds, &DurationFormat::milliseconds_style, &DurationFormat::set_milliseconds_style, &DurationFormat::milliseconds_display, &DurationFormat::set_milliseconds_display, "milliseconds"sv, "millisecond"sv, sub_second_values, "numeric"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::microseconds, &DurationFormat::microseconds_style, &DurationFormat::set_microseconds_style, &DurationFormat::microseconds_display, &DurationFormat::set_microseconds_display, "microseconds"sv, "microsecond"sv, sub_second_values, "numeric"sv }, + DurationInstanceComponent { &Temporal::DurationRecord::nanoseconds, &DurationFormat::nanoseconds_style, &DurationFormat::set_nanoseconds_style, &DurationFormat::nanoseconds_display, &DurationFormat::set_nanoseconds_display, "nanoseconds"sv, "nanosecond"sv, sub_second_values, "numeric"sv }, }; struct DurationUnitOptions { @@ -194,5 +220,6 @@ struct DurationUnitOptions { ThrowCompletionOr<Temporal::DurationRecord> to_duration_record(GlobalObject& global_object, Value input); ThrowCompletionOr<DurationUnitOptions> get_duration_unit_options(GlobalObject& global_object, String const& unit, Object const& options, StringView base_style, Span<StringView const> styles_list, StringView digital_base, Optional<String> const& previous_style); +ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(GlobalObject& global_object, DurationFormat const& duration_format, Temporal::DurationRecord const& duration); }
d42abb3c7bc14d882320b03e048ace62c155692a
2022-01-04 19:10:00
Tobias Christiansen
pixelpaint: Use the wrapped filters for the Filter Gallery
false
Use the wrapped filters for the Filter Gallery
pixelpaint
diff --git a/Userland/Applications/PixelPaint/FilterGallery.cpp b/Userland/Applications/PixelPaint/FilterGallery.cpp index 97cc33dd111f..bdbfd27e6f74 100644 --- a/Userland/Applications/PixelPaint/FilterGallery.cpp +++ b/Userland/Applications/PixelPaint/FilterGallery.cpp @@ -25,30 +25,41 @@ FilterGallery::FilterGallery(GUI::Window* parent_window, ImageEditor* editor) if (!main_widget.load_from_gml(filter_gallery_gml)) VERIFY_NOT_REACHED(); - auto filter_tree = main_widget.find_descendant_of_type_named<GUI::TreeView>("tree_view"); + m_filter_tree = main_widget.find_descendant_of_type_named<GUI::TreeView>("tree_view"); auto apply_button = main_widget.find_descendant_of_type_named<GUI::Button>("apply_button"); auto cancel_button = main_widget.find_descendant_of_type_named<GUI::Button>("cancel_button"); - auto config_widget = main_widget.find_descendant_of_type_named<GUI::Widget>("config_widget"); + m_config_widget = main_widget.find_descendant_of_type_named<GUI::Widget>("config_widget"); - VERIFY(filter_tree); + VERIFY(m_filter_tree); VERIFY(apply_button); VERIFY(cancel_button); - VERIFY(config_widget); + VERIFY(m_config_widget); auto filter_model = FilterModel::create(editor); - filter_tree->set_model(filter_model); - filter_tree->expand_tree(); + m_filter_tree->set_model(filter_model); + m_filter_tree->expand_tree(); - apply_button->on_click = [this, filter_tree](auto) { - auto selected_index = filter_tree->selection().first(); + m_filter_tree->on_selection_change = [this]() { + auto selected_index = m_filter_tree->selection().first(); if (!selected_index.is_valid()) - done(ExecResult::ExecAborted); + return; auto selected_filter = static_cast<const FilterModel::FilterInfo*>(selected_index.internal_data()); if (selected_filter->type != FilterModel::FilterInfo::Type::Filter) + return; + + m_selected_filter = selected_filter->filter; + + m_selected_filter_config_widget = m_selected_filter->get_settings_widget(); + m_config_widget->remove_all_children(); + m_config_widget->add_child(*m_selected_filter_config_widget); + }; + + apply_button->on_click = [this](auto) { + if (!m_selected_filter) done(ExecResult::ExecAborted); - selected_filter->apply_filter(); + m_selected_filter->apply(); done(ExecResult::ExecOK); }; diff --git a/Userland/Applications/PixelPaint/FilterGallery.h b/Userland/Applications/PixelPaint/FilterGallery.h index 8fe642a06128..39ddcea58412 100644 --- a/Userland/Applications/PixelPaint/FilterGallery.h +++ b/Userland/Applications/PixelPaint/FilterGallery.h @@ -6,6 +6,7 @@ #pragma once +#include "Filters/Filter.h" #include "ImageEditor.h" #include <LibGUI/Dialog.h> @@ -16,6 +17,10 @@ class FilterGallery final : public GUI::Dialog { private: FilterGallery(GUI::Window* parent_window, ImageEditor*); + GUI::TreeView* m_filter_tree { nullptr }; + GUI::Widget* m_config_widget { nullptr }; + RefPtr<GUI::Widget> m_selected_filter_config_widget { nullptr }; + Filter* m_selected_filter { nullptr }; }; } diff --git a/Userland/Applications/PixelPaint/FilterModel.cpp b/Userland/Applications/PixelPaint/FilterModel.cpp index 835737044978..fef27ba6ce17 100644 --- a/Userland/Applications/PixelPaint/FilterModel.cpp +++ b/Userland/Applications/PixelPaint/FilterModel.cpp @@ -7,144 +7,39 @@ #include "FilterModel.h" #include "FilterParams.h" +#include "Filters/BoxBlur3.h" +#include "Filters/BoxBlur5.h" +#include "Filters/GaussBlur3.h" +#include "Filters/GaussBlur5.h" +#include "Filters/Grayscale.h" +#include "Filters/Invert.h" +#include "Filters/LaplaceCardinal.h" +#include "Filters/LaplaceDiagonal.h" +#include "Filters/Sharpen.h" #include "Layer.h" #include <LibGUI/FileIconProvider.h> -#include <LibGfx/Filters/LaplacianFilter.h> namespace PixelPaint { FilterModel::FilterModel(ImageEditor* editor) { auto spatial_category = FilterInfo::create_category("Spatial"); - auto edge_detect_category = FilterInfo::create_category("Edge Detect", spatial_category); - auto laplace_cardinal_filter = FilterInfo::create_filter( - "Laplacian (Cardinal)", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::LaplacianFilter filter; - if (auto parameters = PixelPaint::FilterParameters<Gfx::LaplacianFilter>::get(false)) { - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - } - }, - edge_detect_category); - auto laplace_diagonal_filter = FilterInfo::create_filter( - "Laplacian (Diagonal)", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::LaplacianFilter filter; - if (auto parameters = PixelPaint::FilterParameters<Gfx::LaplacianFilter>::get(true)) { - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - } - }, - edge_detect_category); + auto edge_detect_category = FilterInfo::create_category("Edge Detection", spatial_category); + auto laplace_cardinal_filter = FilterInfo::create_filter<Filters::LaplaceCardinal>(editor, edge_detect_category); + auto laplace_diagonal_filter = FilterInfo::create_filter<Filters::LaplaceDiagonal>(editor, edge_detect_category); auto blur_category = FilterInfo::create_category("Blur & Sharpen", spatial_category); - auto gaussian_blur_filter_3 = FilterInfo::create_filter( - "Gaussian Blur (3x3)", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::SpatialGaussianBlurFilter<3> filter; - if (auto parameters = PixelPaint::FilterParameters<Gfx::SpatialGaussianBlurFilter<3>>::get()) { - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - } - }, - blur_category); - auto gaussian_blur_filter_5 = FilterInfo::create_filter( - "Gaussian Blur (5x5)", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::SpatialGaussianBlurFilter<5> filter; - if (auto parameters = PixelPaint::FilterParameters<Gfx::SpatialGaussianBlurFilter<3>>::get()) { - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - } - }, - blur_category); - auto box_blur_filter_3 = FilterInfo::create_filter( - "Box Blur (3x3)", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::BoxBlurFilter<3> filter; - if (auto parameters = PixelPaint::FilterParameters<Gfx::BoxBlurFilter<3>>::get()) { - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - } - }, - blur_category); - auto box_blur_filter_5 = FilterInfo::create_filter( - "Box Blur (5x5)", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::BoxBlurFilter<5> filter; - if (auto parameters = PixelPaint::FilterParameters<Gfx::BoxBlurFilter<3>>::get()) { - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - } - }, - blur_category); - auto sharpen_filter = FilterInfo::create_filter( - "Sharpen", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::SharpenFilter filter; - if (auto parameters = PixelPaint::FilterParameters<Gfx::SharpenFilter>::get()) { - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect(), *parameters); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - } - }, - blur_category); + auto gaussian_blur_filter_3 = FilterInfo::create_filter<Filters::GaussBlur3>(editor, blur_category); + auto gaussian_blur_filter_5 = FilterInfo::create_filter<Filters::GaussBlur5>(editor, blur_category); + auto box_blur_filter_3 = FilterInfo::create_filter<Filters::BoxBlur3>(editor, blur_category); + auto box_blur_filter_5 = FilterInfo::create_filter<Filters::BoxBlur5>(editor, blur_category); + auto sharpen_filter = FilterInfo::create_filter<Filters::Sharpen>(editor, blur_category); m_filters.append(spatial_category); auto color_category = FilterInfo::create_category("Color"); - auto grayscale_filter = FilterInfo::create_filter( - "Grayscale", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::GrayscaleFilter filter; - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect()); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - }, - color_category); - auto invert_filter = FilterInfo::create_filter( - "Invert", [editor]() { - if (!editor) - return; - if (auto* layer = editor->active_layer()) { - Gfx::InvertFilter filter; - filter.apply(layer->bitmap(), layer->rect(), layer->bitmap(), layer->rect()); - layer->did_modify_bitmap(layer->rect()); - editor->did_complete_action(); - } - }, - color_category); + auto grayscale_filter = FilterInfo::create_filter<Filters::Grayscale>(editor, color_category); + auto invert_filter = FilterInfo::create_filter<Filters::Invert>(editor, color_category); m_filters.append(color_category); diff --git a/Userland/Applications/PixelPaint/FilterModel.h b/Userland/Applications/PixelPaint/FilterModel.h index 01a7c25d2d8e..e63363d858da 100644 --- a/Userland/Applications/PixelPaint/FilterModel.h +++ b/Userland/Applications/PixelPaint/FilterModel.h @@ -6,6 +6,7 @@ #pragma once +#include "Filters/Filter.h" #include "ImageEditor.h" #include <AK/NonnullRefPtr.h> #include <LibGUI/Model.h> @@ -24,19 +25,21 @@ class FilterModel final : public GUI::Model { String text; - Function<void()> apply_filter; + Filter* filter { nullptr }; NonnullRefPtrVector<FilterInfo> children; FilterInfo* parent; - static NonnullRefPtr<FilterInfo> create_filter(String const& text, Function<void()> apply_filter, FilterInfo* parent = nullptr) + template<typename FilterType> + static NonnullRefPtr<FilterInfo> create_filter(ImageEditor* editor, FilterInfo* parent = nullptr) { - auto filter = adopt_ref(*new FilterInfo(Type::Filter, text, parent)); - filter->ref(); - filter->apply_filter = move(apply_filter); + auto filter = static_cast<Filter*>(new FilterType(editor)); + auto filter_info = adopt_ref(*new FilterInfo(Type::Filter, filter->filter_name(), parent)); + filter_info->filter = filter; + filter_info->ref(); if (parent) - parent->children.append(filter); - return filter; + parent->children.append(filter_info); + return filter_info; } static NonnullRefPtr<FilterInfo> create_category(String const& text, FilterInfo* parent = nullptr)
97a4c627cba98a0fb496621b7b805cfb7d5ffe55
2021-04-18 20:32:40
FalseHonesty
kernel: Add debug register handling
false
Add debug register handling
kernel
diff --git a/Kernel/Arch/i386/CPU.cpp b/Kernel/Arch/i386/CPU.cpp index 93c22c19883c..f47f0da7f291 100644 --- a/Kernel/Arch/i386/CPU.cpp +++ b/Kernel/Arch/i386/CPU.cpp @@ -855,18 +855,69 @@ FlatPtr read_cr4() return cr4; } -FlatPtr read_dr6() +void read_debug_registers_into(DebugRegisterState& state) { - FlatPtr dr6; + state.dr0 = read_dr0(); + state.dr1 = read_dr1(); + state.dr2 = read_dr2(); + state.dr3 = read_dr3(); + state.dr6 = read_dr6(); + state.dr7 = read_dr7(); +} + +void write_debug_registers_from(const DebugRegisterState& state) +{ + write_dr0(state.dr0); + write_dr1(state.dr1); + write_dr2(state.dr2); + write_dr3(state.dr3); + write_dr6(state.dr6); + write_dr7(state.dr7); +} + +void clear_debug_registers() +{ + write_dr0(0); + write_dr1(0); + write_dr2(0); + write_dr3(0); + write_dr7(1 << 10); // Bit 10 is reserved and must be set to 1. +} + #if ARCH(I386) - asm("mov %%dr6, %%eax" - : "=a"(dr6)); +# define DEFINE_DEBUG_REGISTER(index) \ + FlatPtr read_dr##index() \ + { \ + FlatPtr value; \ + asm("mov %%dr" #index ", %%eax" \ + : "=a"(value)); \ + return value; \ + } \ + void write_dr##index(FlatPtr value) \ + { \ + asm volatile("mov %%eax, %%dr" #index ::"a"(value)); \ + } #else - asm("mov %%dr6, %%rax" - : "=a"(dr6)); +# define DEFINE_DEBUG_REGISTER(index) \ + FlatPtr read_dr##index() \ + { \ + FlatPtr value; \ + asm("mov %%dr" #index ", %%rax" \ + : "=a"(value)); \ + return value; \ + } \ + void write_dr##index(FlatPtr value) \ + { \ + asm volatile("mov %%rax, %%dr" #index ::"a"(value)); \ + } #endif - return dr6; -} + +DEFINE_DEBUG_REGISTER(0); +DEFINE_DEBUG_REGISTER(1); +DEFINE_DEBUG_REGISTER(2); +DEFINE_DEBUG_REGISTER(3); +DEFINE_DEBUG_REGISTER(6); +DEFINE_DEBUG_REGISTER(7); #define XCR_XFEATURE_ENABLED_MASK 0 @@ -1391,6 +1442,15 @@ extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread) set_fs(to_tss.fs); set_gs(to_tss.gs); + if (from_thread->process().is_traced()) + read_debug_registers_into(from_thread->debug_register_state()); + + if (to_thread->process().is_traced()) { + write_debug_registers_from(to_thread->debug_register_state()); + } else { + clear_debug_registers(); + } + auto& processor = Processor::current(); auto& tls_descriptor = processor.get_gdt_entry(GDT_SELECTOR_TLS); tls_descriptor.set_base(to_thread->thread_specific_data()); @@ -1404,7 +1464,6 @@ extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread) asm volatile("fxrstor %0" ::"m"(to_thread->fpu_state())); - // TODO: debug registers // TODO: ioperm? } diff --git a/Kernel/Arch/x86/CPU.h b/Kernel/Arch/x86/CPU.h index a747b8f30764..d4dd8ace1aae 100644 --- a/Kernel/Arch/x86/CPU.h +++ b/Kernel/Arch/x86/CPU.h @@ -430,6 +430,15 @@ struct [[gnu::packed]] RegisterState { FlatPtr userspace_ss; }; +struct [[gnu::packed]] DebugRegisterState { + FlatPtr dr0; + FlatPtr dr1; + FlatPtr dr2; + FlatPtr dr3; + FlatPtr dr6; + FlatPtr dr7; +}; + #if ARCH(I386) # define REGISTER_STATE_SIZE (19 * 4) #else @@ -476,7 +485,21 @@ void write_cr3(FlatPtr); void write_cr4(FlatPtr); void write_xcr0(u64); +void read_debug_registers_into(DebugRegisterState&); +void write_debug_registers_from(const DebugRegisterState&); +void clear_debug_registers(); +FlatPtr read_dr0(); +void write_dr0(FlatPtr); +FlatPtr read_dr1(); +void write_dr1(FlatPtr); +FlatPtr read_dr2(); +void write_dr2(FlatPtr); +FlatPtr read_dr3(); +void write_dr3(FlatPtr); FlatPtr read_dr6(); +void write_dr6(FlatPtr); +FlatPtr read_dr7(); +void write_dr7(FlatPtr); static inline bool is_kernel_mode() { diff --git a/Kernel/Thread.h b/Kernel/Thread.h index 9bc1f3366280..6a7078c5a6a1 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -763,6 +763,9 @@ class Thread RegisterState& get_register_dump_from_stack(); const RegisterState& get_register_dump_from_stack() const { return const_cast<Thread*>(this)->get_register_dump_from_stack(); } + DebugRegisterState& debug_register_state() { return m_debug_register_state; } + const DebugRegisterState& debug_register_state() const { return m_debug_register_state; } + TSS& tss() { return m_tss; } const TSS& tss() const { return m_tss; } State state() const { return m_state; } @@ -1200,6 +1203,7 @@ class Thread NonnullRefPtr<Process> m_process; ThreadID m_tid { -1 }; TSS m_tss {}; + DebugRegisterState m_debug_register_state {}; TrapFrame* m_current_trap { nullptr }; u32 m_saved_critical { 1 }; IntrusiveListNode<Thread> m_ready_queue_node;
32a01a60e7cc482c9d2fd837c8d91833c2255740
2023-02-16 15:48:53
Timothy Flynn
libunicode: Remove non-iterative text segmentation algorithms
false
Remove non-iterative text segmentation algorithms
libunicode
diff --git a/Userland/Libraries/LibUnicode/Segmentation.h b/Userland/Libraries/LibUnicode/Segmentation.h index 126e5db78c99..95a0ed321a28 100644 --- a/Userland/Libraries/LibUnicode/Segmentation.h +++ b/Userland/Libraries/LibUnicode/Segmentation.h @@ -12,7 +12,6 @@ #include <AK/IterationDecision.h> #include <AK/Optional.h> #include <AK/Types.h> -#include <AK/Vector.h> namespace Unicode { @@ -22,19 +21,6 @@ void for_each_grapheme_segmentation_boundary(Utf8View const&, SegmentationCallba void for_each_grapheme_segmentation_boundary(Utf16View const&, SegmentationCallback); void for_each_grapheme_segmentation_boundary(Utf32View const&, SegmentationCallback); -template<typename ViewType> -Vector<size_t> find_grapheme_segmentation_boundaries(ViewType const& view) -{ - Vector<size_t> boundaries; - - for_each_grapheme_segmentation_boundary(view, [&](auto boundary) { - boundaries.append(boundary); - return IterationDecision::Continue; - }); - - return boundaries; -} - template<typename ViewType> Optional<size_t> next_grapheme_segmentation_boundary(ViewType const& view, size_t index) { @@ -73,19 +59,6 @@ void for_each_word_segmentation_boundary(Utf8View const&, SegmentationCallback); void for_each_word_segmentation_boundary(Utf16View const&, SegmentationCallback); void for_each_word_segmentation_boundary(Utf32View const&, SegmentationCallback); -template<typename ViewType> -Vector<size_t> find_word_segmentation_boundaries(ViewType const& view) -{ - Vector<size_t> boundaries; - - for_each_word_segmentation_boundary(view, [&](auto boundary) { - boundaries.append(boundary); - return IterationDecision::Continue; - }); - - return boundaries; -} - template<typename ViewType> Optional<size_t> next_word_segmentation_boundary(ViewType const& view, size_t index) { @@ -124,19 +97,6 @@ void for_each_sentence_segmentation_boundary(Utf8View const&, SegmentationCallba void for_each_sentence_segmentation_boundary(Utf16View const&, SegmentationCallback); void for_each_sentence_segmentation_boundary(Utf32View const&, SegmentationCallback); -template<typename ViewType> -Vector<size_t> find_sentence_segmentation_boundaries(ViewType const& view) -{ - Vector<size_t> boundaries; - - for_each_sentence_segmentation_boundary(view, [&](auto boundary) { - boundaries.append(boundary); - return IterationDecision::Continue; - }); - - return boundaries; -} - template<typename ViewType> Optional<size_t> next_sentence_segmentation_boundary(ViewType const& view, size_t index) {
68bf6db673e3a0070b5c47d7ab997d82d31e1526
2021-08-30 01:49:42
Andreas Kling
kernel: Rename Spinlock::is_owned_by_current_thread()
false
Rename Spinlock::is_owned_by_current_thread()
kernel
diff --git a/Kernel/Arch/x86/common/Interrupts.cpp b/Kernel/Arch/x86/common/Interrupts.cpp index 6fdbf516574b..e24bad36b5eb 100644 --- a/Kernel/Arch/x86/common/Interrupts.cpp +++ b/Kernel/Arch/x86/common/Interrupts.cpp @@ -463,7 +463,7 @@ extern "C" void handle_interrupt(TrapFrame*) __attribute__((used)); extern "C" UNMAP_AFTER_INIT void pre_init_finished(void) { - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); // Because init_finished() will wait on the other APs, we need // to release the scheduler lock so that the other APs can also get diff --git a/Kernel/Interrupts/APIC.cpp b/Kernel/Interrupts/APIC.cpp index 88bd33b42303..352e967ca868 100644 --- a/Kernel/Interrupts/APIC.cpp +++ b/Kernel/Interrupts/APIC.cpp @@ -459,7 +459,7 @@ UNMAP_AFTER_INIT void APIC::init_finished(u32 cpu) VERIFY(cpu < m_processor_enabled_cnt); // Since we're waiting on other APs here, we shouldn't have the // scheduler lock - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); // Notify the BSP that we are done initializing. It will unmap the startup data at P8000 m_apic_ap_count.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel); diff --git a/Kernel/Locking/Spinlock.h b/Kernel/Locking/Spinlock.h index a3abb4d12e46..2c1808185a11 100644 --- a/Kernel/Locking/Spinlock.h +++ b/Kernel/Locking/Spinlock.h @@ -100,7 +100,7 @@ class RecursiveSpinlock { return m_lock.load(AK::memory_order_relaxed) != 0; } - [[nodiscard]] ALWAYS_INLINE bool is_locked_by_current_thread() const + [[nodiscard]] ALWAYS_INLINE bool is_locked_by_current_processor() const { return m_lock.load(AK::memory_order_relaxed) == FlatPtr(&Processor::current()); } diff --git a/Kernel/Memory/MemoryManager.cpp b/Kernel/Memory/MemoryManager.cpp index 3c9ed6848bf9..8fb08caa675f 100644 --- a/Kernel/Memory/MemoryManager.cpp +++ b/Kernel/Memory/MemoryManager.cpp @@ -508,8 +508,8 @@ PhysicalAddress MemoryManager::get_physical_address(PhysicalPage const& physical PageTableEntry* MemoryManager::pte(PageDirectory& page_directory, VirtualAddress vaddr) { VERIFY_INTERRUPTS_DISABLED(); - VERIFY(s_mm_lock.is_locked_by_current_thread()); - VERIFY(page_directory.get_lock().is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); + VERIFY(page_directory.get_lock().is_locked_by_current_processor()); u32 page_directory_table_index = (vaddr.get() >> 30) & 0x1ff; u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff; u32 page_table_index = (vaddr.get() >> 12) & 0x1ff; @@ -525,8 +525,8 @@ PageTableEntry* MemoryManager::pte(PageDirectory& page_directory, VirtualAddress PageTableEntry* MemoryManager::ensure_pte(PageDirectory& page_directory, VirtualAddress vaddr) { VERIFY_INTERRUPTS_DISABLED(); - VERIFY(s_mm_lock.is_locked_by_current_thread()); - VERIFY(page_directory.get_lock().is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); + VERIFY(page_directory.get_lock().is_locked_by_current_processor()); u32 page_directory_table_index = (vaddr.get() >> 30) & 0x1ff; u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff; u32 page_table_index = (vaddr.get() >> 12) & 0x1ff; @@ -567,8 +567,8 @@ PageTableEntry* MemoryManager::ensure_pte(PageDirectory& page_directory, Virtual void MemoryManager::release_pte(PageDirectory& page_directory, VirtualAddress vaddr, bool is_last_release) { VERIFY_INTERRUPTS_DISABLED(); - VERIFY(s_mm_lock.is_locked_by_current_thread()); - VERIFY(page_directory.get_lock().is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); + VERIFY(page_directory.get_lock().is_locked_by_current_processor()); u32 page_directory_table_index = (vaddr.get() >> 30) & 0x1ff; u32 page_directory_index = (vaddr.get() >> 21) & 0x1ff; u32 page_table_index = (vaddr.get() >> 12) & 0x1ff; @@ -622,7 +622,7 @@ Region* MemoryManager::kernel_region_from_vaddr(VirtualAddress vaddr) Region* MemoryManager::find_user_region_from_vaddr_no_lock(AddressSpace& space, VirtualAddress vaddr) { - VERIFY(space.get_lock().is_locked_by_current_thread()); + VERIFY(space.get_lock().is_locked_by_current_processor()); return space.find_region_containing({ vaddr, 1 }); } @@ -953,7 +953,7 @@ void MemoryManager::flush_tlb(PageDirectory const* page_directory, VirtualAddres PageDirectoryEntry* MemoryManager::quickmap_pd(PageDirectory& directory, size_t pdpt_index) { - VERIFY(s_mm_lock.is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); auto& mm_data = get_data(); auto& pte = boot_pd_kernel_pt1023[(KERNEL_QUICKMAP_PD - KERNEL_PT1024_BASE) / PAGE_SIZE]; auto pd_paddr = directory.m_directory_pages[pdpt_index]->paddr(); @@ -979,7 +979,7 @@ PageDirectoryEntry* MemoryManager::quickmap_pd(PageDirectory& directory, size_t PageTableEntry* MemoryManager::quickmap_pt(PhysicalAddress pt_paddr) { - VERIFY(s_mm_lock.is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); auto& mm_data = get_data(); auto& pte = ((PageTableEntry*)boot_pd_kernel_pt1023)[(KERNEL_QUICKMAP_PT - KERNEL_PT1024_BASE) / PAGE_SIZE]; if (pte.physical_page_base() != pt_paddr.get()) { @@ -1005,7 +1005,7 @@ PageTableEntry* MemoryManager::quickmap_pt(PhysicalAddress pt_paddr) u8* MemoryManager::quickmap_page(PhysicalAddress const& physical_address) { VERIFY_INTERRUPTS_DISABLED(); - VERIFY(s_mm_lock.is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); auto& mm_data = get_data(); mm_data.m_quickmap_prev_flags = mm_data.m_quickmap_in_use.lock(); @@ -1026,7 +1026,7 @@ u8* MemoryManager::quickmap_page(PhysicalAddress const& physical_address) void MemoryManager::unquickmap_page() { VERIFY_INTERRUPTS_DISABLED(); - VERIFY(s_mm_lock.is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); auto& mm_data = get_data(); VERIFY(mm_data.m_quickmap_in_use.is_locked()); VirtualAddress vaddr(KERNEL_QUICKMAP_PER_CPU_BASE + Processor::current_id() * PAGE_SIZE); @@ -1039,7 +1039,7 @@ void MemoryManager::unquickmap_page() bool MemoryManager::validate_user_stack_no_lock(AddressSpace& space, VirtualAddress vaddr) const { - VERIFY(space.get_lock().is_locked_by_current_thread()); + VERIFY(space.get_lock().is_locked_by_current_processor()); if (!is_user_address(vaddr)) return false; diff --git a/Kernel/Memory/Region.cpp b/Kernel/Memory/Region.cpp index e91a8056f5f8..035eb854631e 100644 --- a/Kernel/Memory/Region.cpp +++ b/Kernel/Memory/Region.cpp @@ -174,7 +174,7 @@ void Region::set_should_cow(size_t page_index, bool cow) bool Region::map_individual_page_impl(size_t page_index) { - VERIFY(m_page_directory->get_lock().is_locked_by_current_thread()); + VERIFY(m_page_directory->get_lock().is_locked_by_current_processor()); auto page_vaddr = vaddr_from_page_index(page_index); bool user_allowed = page_vaddr.get() >= 0x00800000 && is_user_address(page_vaddr); @@ -253,7 +253,7 @@ void Region::unmap(ShouldDeallocateVirtualRange deallocate_range) void Region::set_page_directory(PageDirectory& page_directory) { VERIFY(!m_page_directory || m_page_directory == &page_directory); - VERIFY(s_mm_lock.is_locked_by_current_thread()); + VERIFY(s_mm_lock.is_locked_by_current_processor()); m_page_directory = page_directory; } @@ -394,8 +394,8 @@ PageFaultResponse Region::handle_inode_fault(size_t page_index_in_region) { VERIFY_INTERRUPTS_DISABLED(); VERIFY(vmobject().is_inode()); - VERIFY(!s_mm_lock.is_locked_by_current_thread()); - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!s_mm_lock.is_locked_by_current_processor()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); auto& inode_vmobject = static_cast<InodeVMObject&>(vmobject()); diff --git a/Kernel/Scheduler.cpp b/Kernel/Scheduler.cpp index f6f3c74fe259..6dfd27a246a4 100644 --- a/Kernel/Scheduler.cpp +++ b/Kernel/Scheduler.cpp @@ -163,7 +163,7 @@ bool Scheduler::dequeue_runnable_thread(Thread& thread, bool check_affinity) void Scheduler::enqueue_runnable_thread(Thread& thread) { - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); if (thread.is_idle_thread()) return; auto priority = thread_priority_to_priority_index(thread.priority()); @@ -266,7 +266,7 @@ bool Scheduler::yield() bool Scheduler::context_switch(Thread* thread) { - if (Memory::s_mm_lock.is_locked_by_current_thread()) { + if (Memory::s_mm_lock.is_locked_by_current_processor()) { PANIC("In context switch while holding Memory::s_mm_lock"); } @@ -320,7 +320,7 @@ bool Scheduler::context_switch(Thread* thread) void Scheduler::enter_current(Thread& prev_thread, bool is_first) { - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); // We already recorded the scheduled time when entering the trap, so this merely accounts for the kernel time since then auto scheduler_time = Scheduler::current_time(); @@ -362,7 +362,7 @@ void Scheduler::prepare_after_exec() { // This is called after exec() when doing a context "switch" into // the new process. This is called from Processor::assume_context - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); VERIFY(!Processor::current_in_scheduler()); Processor::set_current_in_scheduler(true); @@ -372,7 +372,7 @@ void Scheduler::prepare_for_idle_loop() { // This is called when the CPU finished setting up the idle loop // and is about to run it. We need to acquire he scheduler lock - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); g_scheduler_lock.lock(); VERIFY(!Processor::current_in_scheduler()); diff --git a/Kernel/Syscall.cpp b/Kernel/Syscall.cpp index c9b267425c66..1579f862b729 100644 --- a/Kernel/Syscall.cpp +++ b/Kernel/Syscall.cpp @@ -236,7 +236,7 @@ NEVER_INLINE void syscall_handler(TrapFrame* trap) // Check if we're supposed to return to userspace or just die. current_thread->die_if_needed(); - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); } } diff --git a/Kernel/Syscalls/execve.cpp b/Kernel/Syscalls/execve.cpp index 0ac2b90fc3f7..cf9eb5e329f3 100644 --- a/Kernel/Syscalls/execve.cpp +++ b/Kernel/Syscalls/execve.cpp @@ -922,7 +922,7 @@ KResult Process::exec(String path, Vector<String> arguments, Vector<String> envi // We need to enter the scheduler lock before changing the state // and it will be released after the context switch into that // thread. We should also still be in our critical section - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); VERIFY(Processor::in_critical() == 1); g_scheduler_lock.lock(); current_thread->set_state(Thread::State::Running); diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index 747f844038f8..22b93e5a3971 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -160,7 +160,7 @@ void Thread::block(Kernel::Mutex& lock, SpinlockLocker<Spinlock<u8>>& lock_lock, VERIFY(!Processor::current_in_irq()); VERIFY(this == Thread::current()); ScopedCritical critical; - VERIFY(!Memory::s_mm_lock.is_locked_by_current_thread()); + VERIFY(!Memory::s_mm_lock.is_locked_by_current_processor()); SpinlockLocker block_lock(m_block_lock); @@ -198,7 +198,7 @@ void Thread::block(Kernel::Mutex& lock, SpinlockLocker<Spinlock<u8>>& lock_lock, for (;;) { // Yield to the scheduler, and wait for us to resume unblocked. - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); VERIFY(Processor::in_critical()); if (&lock != &big_lock && big_lock.is_locked_by_current_thread()) { // We're locking another lock and already hold the big lock... @@ -239,8 +239,8 @@ u32 Thread::unblock_from_lock(Kernel::Mutex& lock) SpinlockLocker block_lock(m_block_lock); VERIFY(m_blocking_lock == &lock); VERIFY(!Processor::current_in_irq()); - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); - VERIFY(m_block_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); + VERIFY(m_block_lock.is_locked_by_current_processor()); VERIFY(m_blocking_lock == &lock); dbgln_if(THREAD_DEBUG, "Thread {} unblocked from Mutex {}", *this, &lock); m_blocking_lock = nullptr; @@ -285,8 +285,8 @@ void Thread::unblock_from_blocker(Blocker& blocker) void Thread::unblock(u8 signal) { VERIFY(!Processor::current_in_irq()); - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); - VERIFY(m_block_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); + VERIFY(m_block_lock.is_locked_by_current_processor()); if (m_state != Thread::Blocked) return; if (m_blocking_lock) @@ -402,7 +402,7 @@ void Thread::exit(void* exit_value) void Thread::yield_without_releasing_big_lock(VerifyLockNotHeld verify_lock_not_held) { - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); VERIFY(verify_lock_not_held == VerifyLockNotHeld::No || !process().big_lock().is_locked_by_current_thread()); // Disable interrupts here. This ensures we don't accidentally switch contexts twice InterruptDisabler disable; @@ -414,7 +414,7 @@ void Thread::yield_without_releasing_big_lock(VerifyLockNotHeld verify_lock_not_ void Thread::yield_and_release_relock_big_lock() { - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); // Disable interrupts here. This ensures we don't accidentally switch contexts twice InterruptDisabler disable; Scheduler::yield(); // flag a switch @@ -612,7 +612,7 @@ u32 Thread::pending_signals() const u32 Thread::pending_signals_for_state() const { - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); constexpr u32 stopped_signal_mask = (1 << (SIGCONT - 1)) | (1 << (SIGKILL - 1)) | (1 << (SIGTRAP - 1)); if (is_handling_page_fault()) return 0; @@ -709,7 +709,7 @@ void Thread::send_urgent_signal_to_self(u8 signal) DispatchSignalResult Thread::dispatch_one_pending_signal() { - VERIFY(m_lock.is_locked_by_current_thread()); + VERIFY(m_lock.is_locked_by_current_processor()); u32 signal_candidates = pending_signals_for_state() & ~m_signal_mask; if (signal_candidates == 0) return DispatchSignalResult::Continue; @@ -816,7 +816,7 @@ void Thread::resume_from_stopped() { VERIFY(is_stopped()); VERIFY(m_stop_state != State::Invalid); - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); if (m_stop_state == Blocked) { SpinlockLocker block_lock(m_block_lock); if (m_blocker || m_blocking_lock) { @@ -834,7 +834,7 @@ void Thread::resume_from_stopped() DispatchSignalResult Thread::dispatch_signal(u8 signal) { VERIFY_INTERRUPTS_DISABLED(); - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); VERIFY(signal > 0 && signal <= 32); VERIFY(process().is_user_process()); VERIFY(this == Thread::current()); @@ -1047,7 +1047,7 @@ RefPtr<Thread> Thread::clone(Process& process) void Thread::set_state(State new_state, u8 stop_signal) { State previous_state; - VERIFY(g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(g_scheduler_lock.is_locked_by_current_processor()); if (new_state == m_state) return; @@ -1162,7 +1162,7 @@ String Thread::backtrace() auto& process = const_cast<Process&>(this->process()); auto stack_trace = Processor::capture_stack_trace(*this); - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); ProcessPagingScope paging_scope(process); for (auto& frame : stack_trace) { if (Memory::is_user_range(VirtualAddress(frame), sizeof(FlatPtr) * 2)) { diff --git a/Kernel/Thread.h b/Kernel/Thread.h index 01a3bee63d49..c7b3b56b2c2c 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -193,7 +193,7 @@ class Thread StringView name() const { // NOTE: Whoever is calling this needs to be holding our lock while reading the name. - VERIFY(m_lock.is_locked_by_current_thread()); + VERIFY(m_lock.is_locked_by_current_processor()); return m_name ? m_name->view() : StringView {}; } @@ -839,7 +839,7 @@ class Thread VERIFY(!Processor::current_in_irq()); VERIFY(this == Thread::current()); ScopedCritical critical; - VERIFY(!Memory::s_mm_lock.is_locked_by_current_thread()); + VERIFY(!Memory::s_mm_lock.is_locked_by_current_processor()); SpinlockLocker block_lock(m_block_lock); // We need to hold m_block_lock so that nobody can unblock a blocker as soon @@ -878,8 +878,8 @@ class Thread // threads to die. In that case timer_was_added = TimerQueue::the().add_timer_without_id(*m_block_timer, block_timeout.clock_id(), block_timeout.absolute_time(), [&]() { VERIFY(!Processor::current_in_irq()); - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); - VERIFY(!m_block_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); + VERIFY(!m_block_lock.is_locked_by_current_processor()); // NOTE: this may execute on the same or any other processor! SpinlockLocker scheduler_lock(g_scheduler_lock); SpinlockLocker block_lock(m_block_lock); @@ -907,7 +907,7 @@ class Thread auto previous_locked = unlock_process_if_locked(lock_count_to_restore); for (;;) { // Yield to the scheduler, and wait for us to resume unblocked. - VERIFY(!g_scheduler_lock.is_locked_by_current_thread()); + VERIFY(!g_scheduler_lock.is_locked_by_current_processor()); VERIFY(Processor::in_critical()); yield_without_releasing_big_lock(); VERIFY(Processor::in_critical()); diff --git a/Kernel/ThreadBlockers.cpp b/Kernel/ThreadBlockers.cpp index 246e13077d24..2a2e2236c0bd 100644 --- a/Kernel/ThreadBlockers.cpp +++ b/Kernel/ThreadBlockers.cpp @@ -162,7 +162,7 @@ Thread::FutexBlocker::~FutexBlocker() void Thread::FutexBlocker::finish_requeue(FutexQueue& futex_queue) { - VERIFY(m_lock.is_locked_by_current_thread()); + VERIFY(m_lock.is_locked_by_current_processor()); set_blocker_set_raw_locked(&futex_queue); // We can now release the lock m_lock.unlock(m_relock_flags);
89641d90db7149fc2305cccb37682e55e8587fb3
2021-07-07 23:30:42
Linus Groh
libcrypto: Add operator>() to UnsignedBigInteger and SignedBigInteger
false
Add operator>() to UnsignedBigInteger and SignedBigInteger
libcrypto
diff --git a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp index 3873da32ceb0..a15a45403c7f 100644 --- a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp +++ b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.cpp @@ -202,6 +202,11 @@ bool SignedBigInteger::operator<(const UnsignedBigInteger& other) const return m_unsigned_data < other; } +bool SignedBigInteger::operator>(const UnsignedBigInteger& other) const +{ + return *this != other && !(*this < other); +} + FLATTEN SignedBigInteger SignedBigInteger::shift_left(size_t num_bits) const { return SignedBigInteger { m_unsigned_data.shift_left(num_bits), m_sign }; @@ -261,4 +266,9 @@ bool SignedBigInteger::operator<(const SignedBigInteger& other) const return m_unsigned_data < other.m_unsigned_data; } +bool SignedBigInteger::operator>(const SignedBigInteger& other) const +{ + return *this != other && !(*this < other); +} + } diff --git a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h index 9e0416d607ec..b3adcdb8bb4f 100644 --- a/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h +++ b/Userland/Libraries/LibCrypto/BigInt/SignedBigInteger.h @@ -121,10 +121,12 @@ class SignedBigInteger { bool operator==(const SignedBigInteger& other) const; bool operator!=(const SignedBigInteger& other) const; bool operator<(const SignedBigInteger& other) const; + bool operator>(const SignedBigInteger& other) const; bool operator==(const UnsignedBigInteger& other) const; bool operator!=(const UnsignedBigInteger& other) const; bool operator<(const UnsignedBigInteger& other) const; + bool operator>(const UnsignedBigInteger& other) const; private: bool m_sign { false }; diff --git a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp index 501a563337f2..135bcf5270e4 100644 --- a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp +++ b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.cpp @@ -332,6 +332,11 @@ bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const return false; } +bool UnsignedBigInteger::operator>(const UnsignedBigInteger& other) const +{ + return *this != other && !(*this < other); +} + } void AK::Formatter<Crypto::UnsignedBigInteger>::format(FormatBuilder& fmtbuilder, const Crypto::UnsignedBigInteger& value) diff --git a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h index 80f8cf393b4e..e37c9e95b497 100644 --- a/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h +++ b/Userland/Libraries/LibCrypto/BigInt/UnsignedBigInteger.h @@ -98,6 +98,7 @@ class UnsignedBigInteger { bool operator==(const UnsignedBigInteger& other) const; bool operator!=(const UnsignedBigInteger& other) const; bool operator<(const UnsignedBigInteger& other) const; + bool operator>(const UnsignedBigInteger& other) const; private: friend class UnsignedBigIntegerAlgorithms;