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
f464ae84ce5b1acd355a43b37156fcab476ac3e7
2022-01-12 19:25:19
Itamar
cmake: Add HACKSTUDIO_BUILD option for building from Hack Studio
false
Add HACKSTUDIO_BUILD option for building from Hack Studio
cmake
diff --git a/CMakeLists.txt b/CMakeLists.txt index 728b1d69eddc..db125297306a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,13 +47,17 @@ if(CCACHE_PROGRAM) set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_PROGRAM}" CACHE FILEPATH "Path to a compiler launcher program, e.g. ccache") endif() -# FIXME: With cmake 3.18, we can change unzip/untar steps to use -# file(ARCHIVE_EXTRACT) instead -find_program(UNZIP unzip REQUIRED) -find_program(TAR tar REQUIRED) +if (NOT HACKSTUDIO_BUILD) -# Host tools, required to generate files for the build -find_package(Lagom CONFIG REQUIRED) + # FIXME: With cmake 3.18, we can change unzip/untar steps to use + # file( ARCHIVE_EXTRACT) instead + find_program(UNZIP unzip REQUIRED) + find_program(TAR tar REQUIRED) + + # Host tools, required to generate files for the build + find_package(Lagom CONFIG REQUIRED) + +endif() # Meta target to run all code-gen steps in the build. add_custom_target(all_generated) @@ -109,11 +113,15 @@ add_custom_target(install-ports USES_TERMINAL ) -add_custom_target(configure-components - COMMAND "$<TARGET_FILE:Lagom::ConfigureComponents>" - USES_TERMINAL -) -add_dependencies(configure-components Lagom::ConfigureComponents) +if (NOT HACKSTUDIO_BUILD) + + add_custom_target(configure-components + COMMAND "$<TARGET_FILE:Lagom::ConfigureComponents>" + USES_TERMINAL + ) + add_dependencies(configure-components Lagom::ConfigureComponents) + +endif() set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -251,6 +259,11 @@ serenity_component( RECOMMENDED ) +if (HACKSTUDIO_BUILD) + include(${HACKSTUDIO_BUILD_CMAKE_FILE}) + return() +endif() + add_subdirectory(AK) add_subdirectory(Kernel) if(NOT "${SERENITY_ARCH}" STREQUAL "aarch64") diff --git a/Meta/CMake/common_options.cmake b/Meta/CMake/common_options.cmake index 3a1f9ef409a7..eb516be7fc9b 100644 --- a/Meta/CMake/common_options.cmake +++ b/Meta/CMake/common_options.cmake @@ -12,3 +12,5 @@ serenity_option(ENABLE_COMPILETIME_HEADER_CHECK OFF CACHE BOOL "Enable compileti serenity_option(ENABLE_TIME_ZONE_DATABASE_DOWNLOAD ON CACHE BOOL "Enable download of the IANA Time Zone Database at build time") serenity_option(ENABLE_UNICODE_DATABASE_DOWNLOAD ON CACHE BOOL "Enable download of Unicode UCD and CLDR files at build time") serenity_option(INCLUDE_WASM_SPEC_TESTS OFF CACHE BOOL "Download and include the WebAssembly spec testsuite") + +serenity_option(HACKSTUDIO_BUILD OFF CACHE BOOL "Automatically enabled when building from HackStudio")
687d32b712f96c49c8b48a668cff4c37e42ebe1c
2025-03-19 19:23:00
Sam Atkins
libweb: Remove ElementInlineCSSStyleDeclaration entirely
false
Remove ElementInlineCSSStyleDeclaration entirely
libweb
diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp b/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp index 4cd7de609cba..1bec03e8f17b 100644 --- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp +++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp @@ -23,7 +23,6 @@ namespace Web::CSS { GC_DEFINE_ALLOCATOR(CSSStyleDeclaration); GC_DEFINE_ALLOCATOR(PropertyOwningCSSStyleDeclaration); -GC_DEFINE_ALLOCATOR(ElementInlineCSSStyleDeclaration); CSSStyleDeclaration::CSSStyleDeclaration(JS::Realm& realm, Computed computed, Readonly readonly) : PlatformObject(realm) @@ -43,14 +42,21 @@ void CSSStyleDeclaration::initialize(JS::Realm& realm) GC::Ref<PropertyOwningCSSStyleDeclaration> PropertyOwningCSSStyleDeclaration::create(JS::Realm& realm, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties) { - return realm.create<PropertyOwningCSSStyleDeclaration>(realm, move(properties), move(custom_properties)); + return realm.create<PropertyOwningCSSStyleDeclaration>(realm, nullptr, move(properties), move(custom_properties)); } -PropertyOwningCSSStyleDeclaration::PropertyOwningCSSStyleDeclaration(JS::Realm& realm, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties) +GC::Ref<PropertyOwningCSSStyleDeclaration> PropertyOwningCSSStyleDeclaration::create_element_inline_style(JS::Realm& realm, GC::Ref<DOM::Element> element, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties) +{ + return realm.create<PropertyOwningCSSStyleDeclaration>(realm, element, move(properties), move(custom_properties)); +} + +PropertyOwningCSSStyleDeclaration::PropertyOwningCSSStyleDeclaration(JS::Realm& realm, GC::Ptr<DOM::Element> element, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties) : CSSStyleDeclaration(realm, Computed::No, Readonly::No) , m_properties(move(properties)) , m_custom_properties(move(custom_properties)) { + if (element) + set_owner_node(DOM::ElementReference { *element }); } void PropertyOwningCSSStyleDeclaration::visit_edges(Visitor& visitor) @@ -69,18 +75,6 @@ String PropertyOwningCSSStyleDeclaration::item(size_t index) const return CSS::string_from_property_id(m_properties[index].property_id).to_string(); } -GC::Ref<ElementInlineCSSStyleDeclaration> ElementInlineCSSStyleDeclaration::create(DOM::Element& element, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties) -{ - auto& realm = element.realm(); - return realm.create<ElementInlineCSSStyleDeclaration>(element, move(properties), move(custom_properties)); -} - -ElementInlineCSSStyleDeclaration::ElementInlineCSSStyleDeclaration(DOM::Element& element, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties) - : PropertyOwningCSSStyleDeclaration(element.realm(), move(properties), move(custom_properties)) -{ - set_owner_node(DOM::ElementReference { element }); -} - size_t PropertyOwningCSSStyleDeclaration::length() const { return m_properties.size(); @@ -210,7 +204,7 @@ WebIDL::ExceptionOr<String> PropertyOwningCSSStyleDeclaration::remove_property(S } // https://drafts.csswg.org/cssom/#update-style-attribute-for -void ElementInlineCSSStyleDeclaration::update_style_attribute() +void CSSStyleDeclaration::update_style_attribute() { // 1. Assert: declaration block’s computed flag is unset. VERIFY(!is_computed()); @@ -640,9 +634,21 @@ String PropertyOwningCSSStyleDeclaration::serialized() const return MUST(builder.to_string()); } +// https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-csstext WebIDL::ExceptionOr<void> PropertyOwningCSSStyleDeclaration::set_css_text(StringView css_text) { - dbgln("(STUBBED) PropertyOwningCSSStyleDeclaration::set_css_text(css_text='{}')", css_text); + // 1. If the readonly flag is set, then throw a NoModificationAllowedError exception. + if (is_readonly()) { + return WebIDL::NoModificationAllowedError::create(realm(), "Cannot modify properties: CSSStyleDeclaration is read-only."_string); + } + + // 2. Empty the declarations. + // 3. Parse the given value and, if the return value is not the empty list, insert the items in the list into the declarations, in specified order. + set_declarations_from_text(css_text); + + // 4. Update style attribute for the CSS declaration block. + update_style_attribute(); + return {}; } @@ -658,40 +664,14 @@ void PropertyOwningCSSStyleDeclaration::set_the_declarations(Vector<StylePropert m_custom_properties = move(custom_properties); } -void ElementInlineCSSStyleDeclaration::set_declarations_from_text(StringView css_text) +void PropertyOwningCSSStyleDeclaration::set_declarations_from_text(StringView css_text) { - // FIXME: What do we do if the element is null? - auto element = owner_node(); - if (!element.has_value()) { - dbgln("FIXME: Returning from ElementInlineCSSStyleDeclaration::declarations_from_text as element is null."); - return; - } - empty_the_declarations(); - auto style = parse_css_style_attribute(Parser::ParsingParams(element->element().document()), css_text); + auto parsing_params = owner_node().has_value() + ? Parser::ParsingParams(owner_node()->element().document()) + : Parser::ParsingParams(); + auto style = parse_css_style_attribute(parsing_params, css_text); set_the_declarations(style.properties, style.custom_properties); } -// https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-csstext -WebIDL::ExceptionOr<void> ElementInlineCSSStyleDeclaration::set_css_text(StringView css_text) -{ - // FIXME: What do we do if the element is null? - if (!owner_node().has_value()) { - dbgln("FIXME: Returning from ElementInlineCSSStyleDeclaration::set_css_text as element is null."); - return {}; - } - - // 1. If the computed flag is set, then throw a NoModificationAllowedError exception. - // NOTE: See ResolvedCSSStyleDeclaration. - - // 2. Empty the declarations. - // 3. Parse the given value and, if the return value is not the empty list, insert the items in the list into the declarations, in specified order. - set_declarations_from_text(css_text); - - // 4. Update style attribute for the CSS declaration block. - update_style_attribute(); - - return {}; -} - } diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h index 08b78acdd712..0092fa13cc6b 100644 --- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h +++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h @@ -84,6 +84,8 @@ class CSSStyleDeclaration virtual CSSStyleDeclaration& generated_style_properties_to_css_style_declaration() override { return *this; } + void update_style_attribute(); + private: // ^PlatformObject virtual Optional<JS::Value> item_value(size_t index) const override; @@ -109,12 +111,13 @@ class PropertyOwningCSSStyleDeclaration : public CSSStyleDeclaration { WEB_PLATFORM_OBJECT(PropertyOwningCSSStyleDeclaration, CSSStyleDeclaration); GC_DECLARE_ALLOCATOR(PropertyOwningCSSStyleDeclaration); - friend class ElementInlineCSSStyleDeclaration; - public: [[nodiscard]] static GC::Ref<PropertyOwningCSSStyleDeclaration> create(JS::Realm&, Vector<StyleProperty>, HashMap<FlyString, StyleProperty> custom_properties); + [[nodiscard]] static GC::Ref<PropertyOwningCSSStyleDeclaration> + create_element_inline_style(JS::Realm&, GC::Ref<DOM::Element>, Vector<StyleProperty>, HashMap<FlyString, StyleProperty> custom_properties); + virtual ~PropertyOwningCSSStyleDeclaration() override = default; virtual size_t length() const override; @@ -133,10 +136,10 @@ class PropertyOwningCSSStyleDeclaration : public CSSStyleDeclaration { virtual String serialized() const final override; virtual WebIDL::ExceptionOr<void> set_css_text(StringView) override; -protected: - PropertyOwningCSSStyleDeclaration(JS::Realm&, Vector<StyleProperty>, HashMap<FlyString, StyleProperty>); + void set_declarations_from_text(StringView); - virtual void update_style_attribute() { } +protected: + PropertyOwningCSSStyleDeclaration(JS::Realm&, GC::Ptr<DOM::Element> owner_node, Vector<StyleProperty>, HashMap<FlyString, StyleProperty>); void empty_the_declarations(); void set_the_declarations(Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties); @@ -150,23 +153,4 @@ class PropertyOwningCSSStyleDeclaration : public CSSStyleDeclaration { HashMap<FlyString, StyleProperty> m_custom_properties; }; -class ElementInlineCSSStyleDeclaration final : public PropertyOwningCSSStyleDeclaration { - WEB_PLATFORM_OBJECT(ElementInlineCSSStyleDeclaration, PropertyOwningCSSStyleDeclaration); - GC_DECLARE_ALLOCATOR(ElementInlineCSSStyleDeclaration); - -public: - [[nodiscard]] static GC::Ref<ElementInlineCSSStyleDeclaration> create(DOM::Element&, Vector<StyleProperty>, HashMap<FlyString, StyleProperty> custom_properties); - - virtual ~ElementInlineCSSStyleDeclaration() override = default; - - void set_declarations_from_text(StringView); - - virtual WebIDL::ExceptionOr<void> set_css_text(StringView) override; - -private: - ElementInlineCSSStyleDeclaration(DOM::Element&, Vector<StyleProperty> properties, HashMap<FlyString, StyleProperty> custom_properties); - - virtual void update_style_attribute() override; -}; - } diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp index 3479b2a0733f..10f137cd7f8b 100644 --- a/Libraries/LibWeb/DOM/Element.cpp +++ b/Libraries/LibWeb/DOM/Element.cpp @@ -921,7 +921,7 @@ void Element::set_shadow_root(GC::Ptr<ShadowRoot> shadow_root) CSS::CSSStyleDeclaration* Element::style_for_bindings() { if (!m_inline_style) - m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this, {}, {}); + m_inline_style = CSS::PropertyOwningCSSStyleDeclaration::create_element_inline_style(realm(), *this, {}, {}); return m_inline_style; } @@ -3524,7 +3524,7 @@ void Element::attribute_changed(FlyString const& local_name, Optional<String> co if (m_inline_style && m_inline_style->is_updating()) return; if (!m_inline_style) - m_inline_style = CSS::ElementInlineCSSStyleDeclaration::create(*this, {}, {}); + m_inline_style = CSS::PropertyOwningCSSStyleDeclaration::create_element_inline_style(realm(), *this, {}, {}); m_inline_style->set_declarations_from_text(*value); set_needs_style_update(true); } diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h index 29bc2052a740..d2fba9fe53e0 100644 --- a/Libraries/LibWeb/DOM/Element.h +++ b/Libraries/LibWeb/DOM/Element.h @@ -211,8 +211,8 @@ class Element void reset_animated_css_properties(); - GC::Ptr<CSS::ElementInlineCSSStyleDeclaration> inline_style() { return m_inline_style; } - GC::Ptr<CSS::ElementInlineCSSStyleDeclaration const> inline_style() const { return m_inline_style; } + GC::Ptr<CSS::PropertyOwningCSSStyleDeclaration> inline_style() { return m_inline_style; } + GC::Ptr<CSS::PropertyOwningCSSStyleDeclaration const> inline_style() const { return m_inline_style; } CSS::CSSStyleDeclaration* style_for_bindings(); @@ -499,7 +499,7 @@ class Element FlyString m_html_uppercased_qualified_name; GC::Ptr<NamedNodeMap> m_attributes; - GC::Ptr<CSS::ElementInlineCSSStyleDeclaration> m_inline_style; + GC::Ptr<CSS::PropertyOwningCSSStyleDeclaration> m_inline_style; GC::Ptr<DOMTokenList> m_class_list; GC::Ptr<ShadowRoot> m_shadow_root; diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h index a0b41e4c5afe..b3f539a1089e 100644 --- a/Libraries/LibWeb/Forward.h +++ b/Libraries/LibWeb/Forward.h @@ -189,7 +189,6 @@ class Display; class DisplayStyleValue; class EasingStyleValue; class EdgeStyleValue; -class ElementInlineCSSStyleDeclaration; class ExplicitGridTrack; class FilterValueListStyleValue; class FitContentStyleValue; diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/cssom.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/cssom.txt index 75f7d9a0f11e..8c2bfc74d148 100644 --- a/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/cssom.txt +++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/cssom.txt @@ -2,8 +2,7 @@ Harness status: OK Found 13 tests -12 Pass -1 Fail +13 Pass Pass CSSStyleRule is a CSSGroupingRule Pass Simple CSSOM manipulation of subrules Pass Simple CSSOM manipulation of subrules 1 @@ -13,7 +12,7 @@ Pass Simple CSSOM manipulation of subrules 4 Pass Simple CSSOM manipulation of subrules 5 Pass Simple CSSOM manipulation of subrules 6 Pass Simple CSSOM manipulation of subrules 7 -Fail Simple CSSOM manipulation of subrules 8 +Pass Simple CSSOM manipulation of subrules 8 Pass Simple CSSOM manipulation of subrules 9 Pass Simple CSSOM manipulation of subrules 10 Pass Mutating the selectorText of outer rule invalidates inner rules \ No newline at end of file diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/nested-declarations-cssom-whitespace.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/nested-declarations-cssom-whitespace.txt index 828018cd0512..2d94c4eb7495 100644 --- a/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/nested-declarations-cssom-whitespace.txt +++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-nesting/nested-declarations-cssom-whitespace.txt @@ -2,6 +2,7 @@ Harness status: OK Found 2 tests -2 Fail -Fail Empty CSSNestedDeclarations do not affect outer serialization +1 Pass +1 Fail +Pass Empty CSSNestedDeclarations do not affect outer serialization Fail Empty CSSNestedDeclarations do not affect outer serialization (nested grouping rule) \ No newline at end of file
50920b05953a6bc2aacb07d291d503052caadf15
2024-06-05 10:33:42
Aliaksandr Kalenik
libweb: Scroll into viewport from a task in set_focused_element()
false
Scroll into viewport from a task in set_focused_element()
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 47e60c54529a..b3bb3b90bc47 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -1906,10 +1906,12 @@ void Document::set_focused_element(Element* element) // Scroll the viewport if necessary to make the newly focused element visible. if (m_focused_element) { - ScrollIntoViewOptions scroll_options; - scroll_options.block = Bindings::ScrollLogicalPosition::Nearest; - scroll_options.inline_ = Bindings::ScrollLogicalPosition::Nearest; - (void)m_focused_element->scroll_into_view(scroll_options); + m_focused_element->queue_an_element_task(HTML::Task::Source::UserInteraction, [&]() { + ScrollIntoViewOptions scroll_options; + scroll_options.block = Bindings::ScrollLogicalPosition::Nearest; + scroll_options.inline_ = Bindings::ScrollLogicalPosition::Nearest; + (void)m_focused_element->scroll_into_view(scroll_options); + }); } }
da23456f9e37e98ca286b741a5ba9c80d1cf198d
2022-12-25 20:28:58
Andreas Kling
ladybird: Try decoding images with Qt if LibGfx fails us
false
Try decoding images with Qt if LibGfx fails us
ladybird
diff --git a/Ladybird/WebView.cpp b/Ladybird/WebView.cpp index 88f2f6f0f1db..e3d808c1b53a 100644 --- a/Ladybird/WebView.cpp +++ b/Ladybird/WebView.cpp @@ -833,6 +833,59 @@ void WebView::resizeEvent(QResizeEvent* event) m_page_client->set_viewport_rect(rect); } +static Optional<Web::ImageDecoding::DecodedImage> decode_image_with_qt(ReadonlyBytes data) +{ + auto image = QImage::fromData(data.data(), static_cast<int>(data.size())); + if (image.isNull()) + return {}; + image = image.convertToFormat(QImage::Format::Format_ARGB32); + auto bitmap = MUST(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, Gfx::IntSize(image.width(), image.height()))); + for (int y = 0; y < image.height(); ++y) { + memcpy(bitmap->scanline_u8(y), image.scanLine(y), image.width() * 4); + } + Vector<Web::ImageDecoding::Frame> frames; + + frames.append(Web::ImageDecoding::Frame { + bitmap, + }); + return Web::ImageDecoding::DecodedImage { + false, + 0, + move(frames), + }; +} + +static Optional<Web::ImageDecoding::DecodedImage> decode_image_with_libgfx(ReadonlyBytes data) +{ + auto decoder = Gfx::ImageDecoder::try_create(data); + + if (!decoder || !decoder->frame_count()) { + return {}; + } + + bool had_errors = false; + Vector<Web::ImageDecoding::Frame> frames; + for (size_t i = 0; i < decoder->frame_count(); ++i) { + auto frame_or_error = decoder->frame(i); + if (frame_or_error.is_error()) { + frames.append({ {}, 0 }); + had_errors = true; + } else { + auto frame = frame_or_error.release_value(); + frames.append({ move(frame.image), static_cast<size_t>(frame.duration) }); + } + } + + if (had_errors) + return {}; + + return Web::ImageDecoding::DecodedImage { + decoder->is_animated(), + static_cast<u32>(decoder->loop_count()), + move(frames), + }; +} + class HeadlessImageDecoderClient : public Web::ImageDecoding::Decoder { public: static NonnullRefPtr<HeadlessImageDecoderClient> create() @@ -844,30 +897,10 @@ class HeadlessImageDecoderClient : public Web::ImageDecoding::Decoder { virtual Optional<Web::ImageDecoding::DecodedImage> decode_image(ReadonlyBytes data) override { - auto decoder = Gfx::ImageDecoder::try_create(data); - - if (!decoder) - return Web::ImageDecoding::DecodedImage { false, 0, Vector<Web::ImageDecoding::Frame> {} }; - - if (!decoder->frame_count()) - return Web::ImageDecoding::DecodedImage { false, 0, Vector<Web::ImageDecoding::Frame> {} }; - - Vector<Web::ImageDecoding::Frame> frames; - for (size_t i = 0; i < decoder->frame_count(); ++i) { - auto frame_or_error = decoder->frame(i); - if (frame_or_error.is_error()) { - frames.append({ {}, 0 }); - } else { - auto frame = frame_or_error.release_value(); - frames.append({ move(frame.image), static_cast<size_t>(frame.duration) }); - } - } - - return Web::ImageDecoding::DecodedImage { - decoder->is_animated(), - static_cast<u32>(decoder->loop_count()), - frames, - }; + auto image = decode_image_with_libgfx(data); + if (image.has_value()) + return image; + return decode_image_with_qt(data); } private:
189fa68c0b3deacd5e3655922328ef4743afb937
2020-02-18 00:34:05
Andreas Kling
libgui: Expose GUI::Menu::menu_id() and also allow forced realization
false
Expose GUI::Menu::menu_id() and also allow forced realization
libgui
diff --git a/Libraries/LibGUI/Menu.h b/Libraries/LibGUI/Menu.h index aa9956c88689..d8ebb1dd932e 100644 --- a/Libraries/LibGUI/Menu.h +++ b/Libraries/LibGUI/Menu.h @@ -39,7 +39,14 @@ class Menu final : public Core::Object { explicit Menu(const StringView& name = ""); virtual ~Menu() override; + void realize_menu_if_needed() + { + if (menu_id() == -1) + realize_menu(); + } + static Menu* from_menu_id(int); + int menu_id() const { return m_menu_id; } const String& name() const { return m_name; } @@ -55,7 +62,6 @@ class Menu final : public Core::Object { private: friend class MenuBar; - int menu_id() const { return m_menu_id; } int realize_menu(); void unrealize_menu(); void realize_if_needed();
25516e351e46104ff445216e7835aaab9f9b9535
2024-10-10 02:37:13
Jelle Raaijmakers
libweb: Clear grapheme segmenter when invalidating TextNode text
false
Clear grapheme segmenter when invalidating TextNode text
libweb
diff --git a/Tests/LibWeb/Ref/reference/textnode-segmenter-invalidation.html b/Tests/LibWeb/Ref/reference/textnode-segmenter-invalidation.html new file mode 100644 index 000000000000..bccaed44b695 --- /dev/null +++ b/Tests/LibWeb/Ref/reference/textnode-segmenter-invalidation.html @@ -0,0 +1,2 @@ +<!DOCTYPE html><textarea>a +b</textarea> diff --git a/Tests/LibWeb/Ref/textnode-segmenter-invalidation.html b/Tests/LibWeb/Ref/textnode-segmenter-invalidation.html new file mode 100644 index 000000000000..d1088abb2057 --- /dev/null +++ b/Tests/LibWeb/Ref/textnode-segmenter-invalidation.html @@ -0,0 +1,9 @@ +<!DOCTYPE html> +<head><link rel="match" href="reference/textnode-segmenter-invalidation.html" /></head> +<textarea id="output"></textarea> +<script> + document.addEventListener('DOMContentLoaded', () => { + document.body.offsetWidth // Force layout + document.getElementById('output').value = 'a\nb'; + }); +</script> diff --git a/Userland/Libraries/LibWeb/Layout/TextNode.cpp b/Userland/Libraries/LibWeb/Layout/TextNode.cpp index e015b4aa34d4..6030a81ce510 100644 --- a/Userland/Libraries/LibWeb/Layout/TextNode.cpp +++ b/Userland/Libraries/LibWeb/Layout/TextNode.cpp @@ -304,6 +304,7 @@ static ErrorOr<String> apply_text_transform(String const& string, CSS::TextTrans void TextNode::invalidate_text_for_rendering() { m_text_for_rendering = {}; + m_grapheme_segmenter.clear(); } String const& TextNode::text_for_rendering() const
3a65e9107e3e34e0b067240771b9fe38b5651d6e
2020-04-11 22:26:15
Andreas Kling
libgui: Respect Model::Role::BackgroundColor
false
Respect Model::Role::BackgroundColor
libgui
diff --git a/Libraries/LibGUI/TableView.cpp b/Libraries/LibGUI/TableView.cpp index 30204b608758..75787305644f 100644 --- a/Libraries/LibGUI/TableView.cpp +++ b/Libraries/LibGUI/TableView.cpp @@ -131,6 +131,11 @@ void TableView::paint_event(PaintEvent& event) text_color = is_focused() ? palette().selection_text() : palette().inactive_selection_text(); else text_color = model()->data(cell_index, Model::Role::ForegroundColor).to_color(palette().color(foreground_role())); + auto cell_background_color = model()->data(cell_index, Model::Role::BackgroundColor); + if (cell_background_color.is_valid()) { + // FIXME: If all cells on a row provide a color, we should really fill the whole row! + painter.fill_rect(cell_rect, cell_background_color.to_color(background_color)); + } painter.draw_text(cell_rect, data.to_string(), font, column_metadata.text_alignment, text_color, Gfx::TextElision::Right); } }
ac98a48177bd8b628a8eb29d1f719df4468b22a0
2020-10-16 00:10:35
Linus Groh
libweb: Fix EventDispatcher::dispatch()
false
Fix EventDispatcher::dispatch()
libweb
diff --git a/Libraries/LibWeb/DOM/EventDispatcher.cpp b/Libraries/LibWeb/DOM/EventDispatcher.cpp index eb3e212db9aa..173fef805fb7 100644 --- a/Libraries/LibWeb/DOM/EventDispatcher.cpp +++ b/Libraries/LibWeb/DOM/EventDispatcher.cpp @@ -27,6 +27,8 @@ #include <LibJS/Runtime/Function.h> #include <LibWeb/Bindings/EventTargetWrapper.h> #include <LibWeb/Bindings/EventTargetWrapperFactory.h> +#include <LibWeb/Bindings/EventWrapper.h> +#include <LibWeb/Bindings/EventWrapperFactory.h> #include <LibWeb/Bindings/ScriptExecutionContext.h> #include <LibWeb/DOM/Event.h> #include <LibWeb/DOM/EventDispatcher.h> @@ -44,9 +46,10 @@ void EventDispatcher::dispatch(EventTarget& target, NonnullRefPtr<Event> event) auto& function = listener.listener->function(); auto& global_object = function.global_object(); auto* this_value = Bindings::wrap(global_object, target); + auto* wrapped_event = Bindings::wrap(global_object, *event); auto& vm = global_object.vm(); - (void)vm.call(function, this_value, Bindings::wrap(global_object, target)); + (void)vm.call(function, this_value, wrapped_event); if (vm.exception()) vm.clear_exception(); }
329cd946ac3947c902ee647ea32862a5c8d53a7f
2024-11-14 16:22:18
Jelle Raaijmakers
libweb: Implement Web Crypto HMAC algorithm
false
Implement Web Crypto HMAC algorithm
libweb
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp index 70f523a2dc46..05910b6849a8 100644 --- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp +++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp @@ -302,9 +302,10 @@ static WebIDL::ExceptionOr<void> validate_jwk_key_ops(JS::Realm& realm, Bindings return {}; } -static WebIDL::ExceptionOr<ByteBuffer> generate_aes_key(JS::VM& vm, u16 const size_in_bits) +static WebIDL::ExceptionOr<ByteBuffer> generate_random_key(JS::VM& vm, u16 const size_in_bits) { auto key_buffer = TRY_OR_THROW_OOM(vm, ByteBuffer::create_uninitialized(size_in_bits / 8)); + // FIXME: Use a cryptographically secure random generator fill_with_random(key_buffer); return key_buffer; } @@ -606,6 +607,48 @@ JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> EcdhKeyDerivePrams::from_v return adopt_own<AlgorithmParams>(*new EcdhKeyDerivePrams { name, key }); } +HmacImportParams::~HmacImportParams() = default; + +JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> HmacImportParams::from_value(JS::VM& vm, JS::Value value) +{ + auto& object = value.as_object(); + + auto name_value = TRY(object.get("name")); + auto name = TRY(name_value.to_string(vm)); + + auto hash_value = TRY(object.get("hash")); + auto hash = TRY(hash_algorithm_identifier_from_value(vm, hash_value)); + + auto maybe_length = Optional<WebIDL::UnsignedLong> {}; + if (MUST(object.has_property("length"))) { + auto length_value = TRY(object.get("length")); + maybe_length = TRY(length_value.to_u32(vm)); + } + + return adopt_own<AlgorithmParams>(*new HmacImportParams { name, hash, maybe_length }); +} + +HmacKeyGenParams::~HmacKeyGenParams() = default; + +JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> HmacKeyGenParams::from_value(JS::VM& vm, JS::Value value) +{ + auto& object = value.as_object(); + + auto name_value = TRY(object.get("name")); + auto name = TRY(name_value.to_string(vm)); + + auto hash_value = TRY(object.get("hash")); + auto hash = TRY(hash_algorithm_identifier_from_value(vm, hash_value)); + + auto maybe_length = Optional<WebIDL::UnsignedLong> {}; + if (MUST(object.has_property("length"))) { + auto length_value = TRY(object.get("length")); + maybe_length = TRY(length_value.to_u32(vm)); + } + + return adopt_own<AlgorithmParams>(*new HmacKeyGenParams { name, hash, maybe_length }); +} + // https://w3c.github.io/webcrypto/#rsa-oaep-operations WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> RSAOAEP::encrypt(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& plaintext) { @@ -1395,7 +1438,7 @@ WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<Crypto } // 3. Generate an AES key of length equal to the length member of normalizedAlgorithm. - auto key_buffer = TRY(generate_aes_key(m_realm->vm(), bits)); + auto key_buffer = TRY(generate_random_key(m_realm->vm(), bits)); // 4. If the key generation step fails, then throw an OperationError. // Note: Cannot happen in our implementation; and if we OOM, then allocating the Exception is probably going to crash anyway. @@ -1721,7 +1764,7 @@ WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<Crypto // 3. Generate an AES key of length equal to the length member of normalizedAlgorithm. // 4. If the key generation step fails, then throw an OperationError. - auto key_buffer = TRY(generate_aes_key(m_realm->vm(), bits)); + auto key_buffer = TRY(generate_random_key(m_realm->vm(), bits)); // 5. Let key be a new CryptoKey object representing the generated AES key. auto key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_buffer }); @@ -2144,7 +2187,7 @@ WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<Crypto // 3. Generate an AES key of length equal to the length member of normalizedAlgorithm. // 4. If the key generation step fails, then throw an OperationError. - auto key_buffer = TRY(generate_aes_key(m_realm->vm(), bits)); + auto key_buffer = TRY(generate_random_key(m_realm->vm(), bits)); // 5. Let key be a new CryptoKey object representing the generated AES key. auto key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_buffer }); @@ -2815,8 +2858,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> X25519::derive_bits(Algor // Otherwise: Return an octet string containing the first length bits of secret. auto slice = TRY_OR_THROW_OOM(realm.vm(), secret.slice(0, length / 8)); - auto result = TRY_OR_THROW_OOM(realm.vm(), ByteBuffer::copy(slice)); - return JS::ArrayBuffer::create(realm, move(result)); + return JS::ArrayBuffer::create(realm, move(slice)); } WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> X25519::generate_key([[maybe_unused]] AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages) @@ -3208,7 +3250,8 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> X25519::export_key(Bindings::K // 6. Set the key_ops attribute of jwk to the usages attribute of key. auto key_ops = Vector<String> {}; auto key_usages = verify_cast<JS::Array>(key->usages()); - for (auto i = 0; i < 10; ++i) { + auto key_usages_length = MUST(MUST(key_usages->get(vm.names.length)).to_length(vm)); + for (auto i = 0u; i < key_usages_length; ++i) { auto usage = key_usages->get(i); if (!usage.has_value()) break; @@ -3248,4 +3291,427 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> X25519::export_key(Bindings::K return JS::NonnullGCPtr { *result }; } +static WebIDL::ExceptionOr<ByteBuffer> hmac_calculate_message_digest(JS::Realm& realm, JS::GCPtr<KeyAlgorithm> hash, ReadonlyBytes key, ReadonlyBytes message) +{ + auto calculate_digest = [&]<typename T>() -> ByteBuffer { + ::Crypto::Authentication::HMAC<T> hmac(key); + auto digest = hmac.process(message); + return MUST(ByteBuffer::copy(digest.bytes())); + }; + auto hash_name = hash->name(); + if (hash_name.equals_ignoring_ascii_case("SHA-1"sv)) + return calculate_digest.operator()<::Crypto::Hash::SHA1>(); + if (hash_name.equals_ignoring_ascii_case("SHA-256"sv)) + return calculate_digest.operator()<::Crypto::Hash::SHA256>(); + if (hash_name.equals_ignoring_ascii_case("SHA-384"sv)) + return calculate_digest.operator()<::Crypto::Hash::SHA384>(); + if (hash_name.equals_ignoring_ascii_case("SHA-512"sv)) + return calculate_digest.operator()<::Crypto::Hash::SHA512>(); + return WebIDL::NotSupportedError::create(realm, "Invalid algorithm"_string); +} + +static WebIDL::ExceptionOr<WebIDL::UnsignedLong> hmac_hash_block_size(JS::Realm& realm, HashAlgorithmIdentifier hash) +{ + auto hash_name = TRY(hash.name(realm.vm())); + if (hash_name.equals_ignoring_ascii_case("SHA-1"sv)) + return ::Crypto::Hash::SHA1::digest_size(); + if (hash_name.equals_ignoring_ascii_case("SHA-256"sv)) + return ::Crypto::Hash::SHA256::digest_size(); + if (hash_name.equals_ignoring_ascii_case("SHA-384"sv)) + return ::Crypto::Hash::SHA384::digest_size(); + if (hash_name.equals_ignoring_ascii_case("SHA-512"sv)) + return ::Crypto::Hash::SHA512::digest_size(); + return WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid hash function '{}'", hash_name))); +} + +// https://w3c.github.io/webcrypto/#hmac-operations +WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> HMAC::sign(AlgorithmParams const&, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& message) +{ + // 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of + // [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash + // function identified by the hash attribute of the [[algorithm]] internal slot of key and + // message as the input data text. + auto const& key_data = key->handle().get<ByteBuffer>(); + auto const& algorithm = verify_cast<HmacKeyAlgorithm>(*key->algorithm()); + auto mac = TRY(hmac_calculate_message_digest(m_realm, algorithm.hash(), key_data.bytes(), message.bytes())); + + // 2. Return the result of creating an ArrayBuffer containing mac. + return JS::ArrayBuffer::create(m_realm, move(mac)); +} + +// https://w3c.github.io/webcrypto/#hmac-operations +WebIDL::ExceptionOr<JS::Value> HMAC::verify(AlgorithmParams const&, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& signature, ByteBuffer const& message) +{ + // 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of + // [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash + // function identified by the hash attribute of the [[algorithm]] internal slot of key and + // message as the input data text. + auto const& key_data = key->handle().get<ByteBuffer>(); + auto const& algorithm = verify_cast<HmacKeyAlgorithm>(*key->algorithm()); + auto mac = TRY(hmac_calculate_message_digest(m_realm, algorithm.hash(), key_data.bytes(), message.bytes())); + + // 2. Return true if mac is equal to signature and false otherwise. + return mac == signature; +} + +// https://w3c.github.io/webcrypto/#hmac-operations +WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> HMAC::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& usages) +{ + // 1. If usages contains any entry which is not "sign" or "verify", then throw a SyntaxError. + for (auto const& usage : usages) { + if (usage != Bindings::KeyUsage::Sign && usage != Bindings::KeyUsage::Verify) + return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage)))); + } + + // 2. If the length member of normalizedAlgorithm is not present: + auto const& normalized_algorithm = static_cast<HmacKeyGenParams const&>(params); + WebIDL::UnsignedLong length; + if (!normalized_algorithm.length.has_value()) { + // Let length be the block size in bits of the hash function identified by the hash member + // of normalizedAlgorithm. + length = TRY(hmac_hash_block_size(m_realm, normalized_algorithm.hash)); + } + + // Otherwise, if the length member of normalizedAlgorithm is non-zero: + else if (normalized_algorithm.length.value() != 0) { + // Let length be equal to the length member of normalizedAlgorithm. + length = normalized_algorithm.length.value(); + } + + // Otherwise: + else { + // throw an OperationError. + return WebIDL::OperationError::create(m_realm, "Invalid length"_string); + } + + // 3. Generate a key of length length bits. + auto key_data = MUST(generate_random_key(m_realm->vm(), length)); + + // 4. If the key generation step fails, then throw an OperationError. + // NOTE: Currently key generation must succeed + + // 5. Let key be a new CryptoKey object representing the generated key. + auto key = CryptoKey::create(m_realm, move(key_data)); + + // 6. Let algorithm be a new HmacKeyAlgorithm. + auto algorithm = HmacKeyAlgorithm::create(m_realm); + + // 7. Set the name attribute of algorithm to "HMAC". + algorithm->set_name("HMAC"_string); + + // 8. Let hash be a new KeyAlgorithm. + auto hash = KeyAlgorithm::create(m_realm); + + // 9. Set the name attribute of hash to equal the name member of the hash member of normalizedAlgorithm. + hash->set_name(TRY(normalized_algorithm.hash.name(m_realm->vm()))); + + // 10. Set the hash attribute of algorithm to hash. + algorithm->set_hash(hash); + + // 11. Set the [[type]] internal slot of key to "secret". + key->set_type(Bindings::KeyType::Secret); + + // 12. Set the [[algorithm]] internal slot of key to algorithm. + key->set_algorithm(algorithm); + + // 13. Set the [[extractable]] internal slot of key to be extractable. + key->set_extractable(extractable); + + // 14. Set the [[usages]] internal slot of key to be usages. + key->set_usages(usages); + + // 15. Return key. + return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { key }; +} + +// https://w3c.github.io/webcrypto/#hmac-operations +WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> HMAC::import_key(Web::Crypto::AlgorithmParams const& params, Bindings::KeyFormat key_format, CryptoKey::InternalKeyData key_data, bool extractable, Vector<Bindings::KeyUsage> const& usages) +{ + auto& vm = m_realm->vm(); + auto const& normalized_algorithm = static_cast<HmacImportParams const&>(params); + + // 1. Let keyData be the key data to be imported. + // 2. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError. + for (auto const& usage : usages) { + if (usage != Bindings::KeyUsage::Sign && usage != Bindings::KeyUsage::Verify) + return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage)))); + } + + // 3. Let hash be a new KeyAlgorithm. + auto hash = KeyAlgorithm::create(m_realm); + + // 4. If format is "raw": + AK::ByteBuffer data; + if (key_format == Bindings::KeyFormat::Raw) { + // 4.1. Let data be the octet string contained in keyData. + data = key_data.get<ByteBuffer>(); + + // 4.2. Set hash to equal the hash member of normalizedAlgorithm. + hash->set_name(TRY(normalized_algorithm.hash.name(vm))); + } + + // 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, "Data is not a JsonWebKey dictionary"_string); + auto jwk = key_data.get<Bindings::JsonWebKey>(); + + // 2. If the kty field of jwk is not "oct", then throw a DataError. + if (jwk.kty != "oct"sv) + return WebIDL::DataError::create(m_realm, "Invalid key type"_string); + + // 3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], + // then throw a DataError. + // 4. Let data be the octet string obtained by decoding the k field of jwk. + data = TRY(parse_jwk_symmetric_key(m_realm, jwk)); + + // 5. Set the hash to equal the hash member of normalizedAlgorithm. + hash->set_name(TRY(normalized_algorithm.hash.name(vm))); + + // 6. If the name attribute of hash is "SHA-1": + auto hash_name = hash->name(); + if (hash_name.equals_ignoring_ascii_case("SHA-1"sv)) { + // If the alg field of jwk is present and is not "HS1", then throw a DataError. + if (jwk.alg.has_value() && jwk.alg != "HS1"sv) + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + } + + // If the name attribute of hash is "SHA-256": + else if (hash_name.equals_ignoring_ascii_case("SHA-256"sv)) { + // If the alg field of jwk is present and is not "HS256", then throw a DataError. + if (jwk.alg.has_value() && jwk.alg != "HS256"sv) + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + } + + // If the name attribute of hash is "SHA-384": + else if (hash_name.equals_ignoring_ascii_case("SHA-384"sv)) { + // If the alg field of jwk is present and is not "HS384", then throw a DataError. + if (jwk.alg.has_value() && jwk.alg != "HS384"sv) + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + } + + // If the name attribute of hash is "SHA-512": + else if (hash_name.equals_ignoring_ascii_case("SHA-512"sv)) { + // If the alg field of jwk is present and is not "HS512", then throw a DataError. + if (jwk.alg.has_value() && jwk.alg != "HS512"sv) + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + } + + // FIXME: Otherwise, if the name attribute of hash is defined in another applicable specification: + else { + // FIXME: Perform any key import steps defined by other applicable specifications, passing format, + // jwk and hash and obtaining hash. + dbgln("Hash algorithm '{}' not supported", hash_name); + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + } + + // 7. If usages is non-empty and the use field of jwk is present and is not "sign", then + // throw a DataError. + if (!usages.is_empty() && jwk.use.has_value() && jwk.use != "sign"sv) + return WebIDL::DataError::create(m_realm, "Invalid use in JsonWebKey"_string); + + // 8. If the key_ops field of jwk is present, and is invalid according to the requirements + // of JSON Web Key [JWK] or does not contain all of the specified usages values, then + // throw a DataError. + TRY(validate_jwk_key_ops(m_realm, jwk, usages)); + + // 9. 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 && extractable) + return WebIDL::DataError::create(m_realm, "Invalid ext field"_string); + } + + // Otherwise: + else { + // throw a NotSupportedError. + return WebIDL::NotSupportedError::create(m_realm, "Invalid key format"_string); + } + + // 5. Let length be equivalent to the length, in octets, of data, multiplied by 8. + auto length = data.size() * 8; + + // 6. If length is zero then throw a DataError. + if (length == 0) + return WebIDL::DataError::create(m_realm, "No data provided"_string); + + // 7. If the length member of normalizedAlgorithm is present: + if (normalized_algorithm.length.has_value()) { + // If the length member of normalizedAlgorithm is greater than length: + auto normalized_algorithm_length = normalized_algorithm.length.value(); + if (normalized_algorithm_length > length) { + // throw a DataError. + return WebIDL::DataError::create(m_realm, "Invalid data size"_string); + } + + // If the length member of normalizedAlgorithm, is less than or equal to length minus eight: + if (normalized_algorithm_length <= length - 8) { + // throw a DataError. + return WebIDL::DataError::create(m_realm, "Invalid data size"_string); + } + + // Otherwise: + // Set length equal to the length member of normalizedAlgorithm. + length = normalized_algorithm_length; + } + + // 8. Let key be a new CryptoKey object representing an HMAC key with the first length bits of data. + auto length_in_bytes = length / 8; + if (data.size() > length_in_bytes) + data = MUST(data.slice(0, length_in_bytes)); + auto key = CryptoKey::create(m_realm, move(data)); + + // 9. Set the [[type]] internal slot of key to "secret". + key->set_type(Bindings::KeyType::Secret); + + // 10. Let algorithm be a new HmacKeyAlgorithm. + auto algorithm = HmacKeyAlgorithm::create(m_realm); + + // 11. Set the name attribute of algorithm to "HMAC". + algorithm->set_name("HMAC"_string); + + // 12. Set the length attribute of algorithm to length. + algorithm->set_length(length); + + // 13. Set the hash attribute of algorithm to hash. + algorithm->set_hash(hash); + + // 14. Set the [[algorithm]] internal slot of key to algorithm. + key->set_algorithm(algorithm); + + // 15. Return key. + return key; +} + +// https://w3c.github.io/webcrypto/#hmac-operations +WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> HMAC::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key) +{ + auto& vm = m_realm->vm(); + + // 1. If the underlying cryptographic key material represented by the [[handle]] internal slot + // of key cannot be accessed, then throw an OperationError. + // NOTE: In our impl this is always accessible + + // 2. Let bits be the raw bits of the key represented by [[handle]] internal slot of key. + // 3. Let data be an octet string containing bits. + auto data = key->handle().get<ByteBuffer>(); + + // 4. If format is "raw": + JS::GCPtr<JS::Object> result; + if (format == Bindings::KeyFormat::Raw) { + // Let result be the result of creating an ArrayBuffer containing data. + result = JS::ArrayBuffer::create(m_realm, data); + } + + // If format is "jwk": + else if (format == Bindings::KeyFormat::Jwk) { + // Let jwk be a new JsonWebKey dictionary. + Bindings::JsonWebKey jwk {}; + + // Set the kty attribute of jwk to the string "oct". + jwk.kty = "oct"_string; + + // Set the k attribute of jwk to be a string containing data, encoded according to Section + // 6.4 of JSON Web Algorithms [JWA]. + jwk.k = MUST(encode_base64url(data, AK::OmitPadding::Yes)); + + // Let algorithm be the [[algorithm]] internal slot of key. + auto const& algorithm = verify_cast<HmacKeyAlgorithm>(*key->algorithm()); + + // Let hash be the hash attribute of algorithm. + auto hash = algorithm.hash(); + + // If the name attribute of hash is "SHA-1": + auto hash_name = hash->name(); + if (hash_name.equals_ignoring_ascii_case("SHA-1"sv)) { + // Set the alg attribute of jwk to the string "HS1". + jwk.alg = "HS1"_string; + } + // If the name attribute of hash is "SHA-256": + else if (hash_name.equals_ignoring_ascii_case("SHA-256"sv)) { + // Set the alg attribute of jwk to the string "HS256". + jwk.alg = "HS256"_string; + } + // If the name attribute of hash is "SHA-384": + else if (hash_name.equals_ignoring_ascii_case("SHA-384"sv)) { + // Set the alg attribute of jwk to the string "HS384". + jwk.alg = "HS384"_string; + } + // If the name attribute of hash is "SHA-512": + else if (hash_name.equals_ignoring_ascii_case("SHA-512"sv)) { + // Set the alg attribute of jwk to the string "HS512". + jwk.alg = "HS512"_string; + } + + // FIXME: Otherwise, the name attribute of hash is defined in another applicable + // specification: + else { + // FIXME: Perform any key export steps defined by other applicable specifications, + // passing format and key and obtaining alg. + // FIXME: Set the alg attribute of jwk to alg. + dbgln("Hash algorithm '{}' not supported", hash_name); + return WebIDL::DataError::create(m_realm, "Invalid algorithm"_string); + } + + // Set the key_ops attribute of jwk to equal the usages attribute of key. + auto key_usages = verify_cast<JS::Array>(key->usages()); + auto key_usages_length = MUST(MUST(key_usages->get(vm.names.length)).to_length(vm)); + for (auto i = 0u; i < key_usages_length; ++i) { + auto usage = key_usages->get(i); + if (!usage.has_value()) + break; + + auto usage_string = TRY(usage.value().to_string(vm)); + jwk.key_ops->append(usage_string); + } + + // Set the ext attribute of jwk to equal the [[extractable]] internal slot of key. + jwk.ext = key->extractable(); + + // Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL]. + result = TRY(jwk.to_object(m_realm)); + } + + // Otherwise: + else { + // throw a NotSupportedError. + return WebIDL::NotSupportedError::create(m_realm, "Invalid key format"_string); + } + + // 5. Return result. + return JS::NonnullGCPtr { *result }; +} + +// https://w3c.github.io/webcrypto/#hmac-operations +WebIDL::ExceptionOr<JS::Value> HMAC::get_key_length(AlgorithmParams const& params) +{ + auto const& normalized_derived_key_algorithm = static_cast<HmacImportParams const&>(params); + WebIDL::UnsignedLong length; + + // 1. If the length member of normalizedDerivedKeyAlgorithm is not present: + if (!normalized_derived_key_algorithm.length.has_value()) { + // Let length be the block size in bits of the hash function identified by the hash member of + // normalizedDerivedKeyAlgorithm. + length = TRY(hmac_hash_block_size(m_realm, normalized_derived_key_algorithm.hash)); + } + + // Otherwise, if the length member of normalizedDerivedKeyAlgorithm is non-zero: + else if (normalized_derived_key_algorithm.length.value() > 0) { + // Let length be equal to the length member of normalizedDerivedKeyAlgorithm. + length = normalized_derived_key_algorithm.length.value(); + } + + // Otherwise: + else { + // throw a TypeError. + return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid key length"sv }; + } + + // 2. Return length. + return JS::Value(length); +} + } diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h index 7daf7ba59fed..9a3de6f3cc24 100644 --- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h +++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h @@ -1,6 +1,7 @@ /* * Copyright (c) 2024, Andrew Kaster <[email protected]> * Copyright (c) 2024, stelar7 <[email protected]> + * Copyright (c) 2024, Jelle Raaijmakers <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -17,6 +18,7 @@ #include <LibWeb/Crypto/CryptoKey.h> #include <LibWeb/WebIDL/Buffers.h> #include <LibWeb/WebIDL/ExceptionOr.h> +#include <LibWeb/WebIDL/Types.h> namespace Web::Crypto { @@ -260,6 +262,40 @@ struct AesDerivedKeyParams : public AlgorithmParams { static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::VM&, JS::Value); }; +// https://w3c.github.io/webcrypto/#hmac-importparams +struct HmacImportParams : public AlgorithmParams { + virtual ~HmacImportParams() override; + + HmacImportParams(String name, HashAlgorithmIdentifier hash, Optional<WebIDL::UnsignedLong> length) + : AlgorithmParams(move(name)) + , hash(move(hash)) + , length(length) + { + } + + HashAlgorithmIdentifier hash; + Optional<WebIDL::UnsignedLong> length; + + static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::VM&, JS::Value); +}; + +// https://w3c.github.io/webcrypto/#hmac-keygen-params +struct HmacKeyGenParams : public AlgorithmParams { + virtual ~HmacKeyGenParams() override; + + HmacKeyGenParams(String name, HashAlgorithmIdentifier hash, Optional<WebIDL::UnsignedLong> length) + : AlgorithmParams(move(name)) + , hash(move(hash)) + , length(length) + { + } + + HashAlgorithmIdentifier hash; + Optional<WebIDL::UnsignedLong> length; + + static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::VM&, JS::Value); +}; + class AlgorithmMethods { public: virtual ~AlgorithmMethods(); @@ -489,6 +525,24 @@ class X25519 : public AlgorithmMethods { } }; +class HMAC : public AlgorithmMethods { +public: + virtual WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> sign(AlgorithmParams const&, JS::NonnullGCPtr<CryptoKey>, ByteBuffer const&) override; + virtual WebIDL::ExceptionOr<JS::Value> verify(AlgorithmParams const&, JS::NonnullGCPtr<CryptoKey>, ByteBuffer const&, ByteBuffer const&) 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; + virtual WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> export_key(Bindings::KeyFormat, JS::NonnullGCPtr<CryptoKey>) override; + virtual WebIDL::ExceptionOr<JS::Value> get_key_length(AlgorithmParams const&) override; + + static NonnullOwnPtr<AlgorithmMethods> create(JS::Realm& realm) { return adopt_own(*new HMAC(realm)); } + +private: + explicit HMAC(JS::Realm& realm) + : AlgorithmMethods(realm) + { + } +}; + struct EcdhKeyDerivePrams : public AlgorithmParams { virtual ~EcdhKeyDerivePrams() override; diff --git a/Libraries/LibWeb/Crypto/KeyAlgorithms.cpp b/Libraries/LibWeb/Crypto/KeyAlgorithms.cpp index 3d5541f8b463..f07143a0ed98 100644 --- a/Libraries/LibWeb/Crypto/KeyAlgorithms.cpp +++ b/Libraries/LibWeb/Crypto/KeyAlgorithms.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) 2023, stelar7 <[email protected]> * Copyright (c) 2024, Andrew Kaster <[email protected]> + * Copyright (c) 2024, Jelle Raaijmakers <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -18,6 +19,7 @@ JS_DEFINE_ALLOCATOR(RsaKeyAlgorithm); JS_DEFINE_ALLOCATOR(RsaHashedKeyAlgorithm); JS_DEFINE_ALLOCATOR(EcKeyAlgorithm); JS_DEFINE_ALLOCATOR(AesKeyAlgorithm); +JS_DEFINE_ALLOCATOR(HmacKeyAlgorithm); template<typename T> static JS::ThrowCompletionOr<T*> impl_from(JS::VM& vm, StringView Name) @@ -209,4 +211,38 @@ JS_DEFINE_NATIVE_FUNCTION(AesKeyAlgorithm::length_getter) return length; } +JS::NonnullGCPtr<HmacKeyAlgorithm> HmacKeyAlgorithm::create(JS::Realm& realm) +{ + return realm.create<HmacKeyAlgorithm>(realm); +} + +HmacKeyAlgorithm::HmacKeyAlgorithm(JS::Realm& realm) + : KeyAlgorithm(realm) +{ +} + +void HmacKeyAlgorithm::initialize(JS::Realm& realm) +{ + Base::initialize(realm); + define_native_accessor(realm, "hash", hash_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable); +} + +void HmacKeyAlgorithm::visit_edges(JS::Cell::Visitor& visitor) +{ + Base::visit_edges(visitor); + visitor.visit(m_hash); +} + +JS_DEFINE_NATIVE_FUNCTION(HmacKeyAlgorithm::hash_getter) +{ + auto* impl = TRY(impl_from<HmacKeyAlgorithm>(vm, "HmacKeyAlgorithm"sv)); + return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->hash(); })); +} + +JS_DEFINE_NATIVE_FUNCTION(HmacKeyAlgorithm::length_getter) +{ + auto* impl = TRY(impl_from<HmacKeyAlgorithm>(vm, "HmacKeyAlgorithm"sv)); + return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->length(); })); +} + } diff --git a/Libraries/LibWeb/Crypto/KeyAlgorithms.h b/Libraries/LibWeb/Crypto/KeyAlgorithms.h index 1618dbedbcc5..78fb92be2872 100644 --- a/Libraries/LibWeb/Crypto/KeyAlgorithms.h +++ b/Libraries/LibWeb/Crypto/KeyAlgorithms.h @@ -1,6 +1,7 @@ /* * Copyright (c) 2023, stelar7 <[email protected]> * Copyright (c) 2024, Andrew Kaster <[email protected]> + * Copyright (c) 2024, Jelle Raaijmakers <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -145,4 +146,34 @@ struct AesKeyAlgorithm : public KeyAlgorithm { u16 m_length; }; +// https://w3c.github.io/webcrypto/#HmacKeyAlgorithm-dictionary +struct HmacKeyAlgorithm : public KeyAlgorithm { + JS_OBJECT(HmacKeyAlgorithm, KeyAlgorithm); + JS_DECLARE_ALLOCATOR(HmacKeyAlgorithm); + +public: + static JS::NonnullGCPtr<HmacKeyAlgorithm> create(JS::Realm&); + + virtual ~HmacKeyAlgorithm() override = default; + + JS::GCPtr<KeyAlgorithm> hash() const { return m_hash; } + void set_hash(JS::GCPtr<KeyAlgorithm> hash) { m_hash = hash; } + + WebIDL::UnsignedLong length() const { return m_length; } + void set_length(WebIDL::UnsignedLong length) { m_length = length; } + +protected: + HmacKeyAlgorithm(JS::Realm&); + + virtual void initialize(JS::Realm&) override; + virtual void visit_edges(Visitor&) override; + +private: + JS_DECLARE_NATIVE_FUNCTION(hash_getter); + JS_DECLARE_NATIVE_FUNCTION(length_getter); + + JS::GCPtr<KeyAlgorithm> m_hash; + WebIDL::UnsignedLong m_length; +}; + } diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp index 1e72bf8ed098..e99bad25d6e8 100644 --- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp +++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp @@ -830,12 +830,12 @@ SupportedAlgorithmsMap supported_algorithms() // FIXME: define_an_algorithm<AesKw, AesDerivedKeyParams>("get key length"_string, "AES-KW"_string); // https://w3c.github.io/webcrypto/#hmac-registration - // FIXME: define_an_algorithm<HMAC>("sign"_string, "HMAC"_string); - // FIXME: define_an_algorithm<HMAC>("verify"_string, "HMAC"_string); - // FIXME: define_an_algorithm<HMAC, HmacKeyGenParams>("generateKey"_string, "HMAC"_string); - // FIXME: define_an_algorithm<HMAC, HmacImportParams>("importKey"_string, "HMAC"_string); - // FIXME: define_an_algorithm<HMAC>("exportKey"_string, "HMAC"_string); - // FIXME: define_an_algorithm<HMAC, HmacImportParams>("get key length"_string, "HMAC"_string); + define_an_algorithm<HMAC>("sign"_string, "HMAC"_string); + define_an_algorithm<HMAC>("verify"_string, "HMAC"_string); + define_an_algorithm<HMAC, HmacKeyGenParams>("generateKey"_string, "HMAC"_string); + define_an_algorithm<HMAC, HmacImportParams>("importKey"_string, "HMAC"_string); + define_an_algorithm<HMAC>("exportKey"_string, "HMAC"_string); + define_an_algorithm<HMAC, HmacImportParams>("get key length"_string, "HMAC"_string); // https://w3c.github.io/webcrypto/#sha-registration define_an_algorithm<SHA>("digest"_string, "SHA-1"_string); diff --git a/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.txt new file mode 100644 index 000000000000..3afc8357e422 --- /dev/null +++ b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.txt @@ -0,0 +1,51 @@ +Summary + +Harness status: OK + +Rerun + +Found 41 tests + +41 Pass +Details +Result Test Name MessagePass setup +Pass HMAC with SHA-1 verification +Pass HMAC with SHA-256 verification +Pass HMAC with SHA-384 verification +Pass HMAC with SHA-512 verification +Pass HMAC with SHA-1 verification with altered signature after call +Pass HMAC with SHA-256 verification with altered signature after call +Pass HMAC with SHA-384 verification with altered signature after call +Pass HMAC with SHA-512 verification with altered signature after call +Pass HMAC with SHA-1 with altered plaintext after call +Pass HMAC with SHA-256 with altered plaintext after call +Pass HMAC with SHA-384 with altered plaintext after call +Pass HMAC with SHA-512 with altered plaintext after call +Pass HMAC with SHA-1 no verify usage +Pass HMAC with SHA-256 no verify usage +Pass HMAC with SHA-384 no verify usage +Pass HMAC with SHA-512 no verify usage +Pass HMAC with SHA-1 round trip +Pass HMAC with SHA-256 round trip +Pass HMAC with SHA-384 round trip +Pass HMAC with SHA-512 round trip +Pass HMAC with SHA-1 signing with wrong algorithm name +Pass HMAC with SHA-256 signing with wrong algorithm name +Pass HMAC with SHA-384 signing with wrong algorithm name +Pass HMAC with SHA-512 signing with wrong algorithm name +Pass HMAC with SHA-1 verifying with wrong algorithm name +Pass HMAC with SHA-256 verifying with wrong algorithm name +Pass HMAC with SHA-384 verifying with wrong algorithm name +Pass HMAC with SHA-512 verifying with wrong algorithm name +Pass HMAC with SHA-1 verification failure due to wrong plaintext +Pass HMAC with SHA-256 verification failure due to wrong plaintext +Pass HMAC with SHA-384 verification failure due to wrong plaintext +Pass HMAC with SHA-512 verification failure due to wrong plaintext +Pass HMAC with SHA-1 verification failure due to wrong signature +Pass HMAC with SHA-256 verification failure due to wrong signature +Pass HMAC with SHA-384 verification failure due to wrong signature +Pass HMAC with SHA-512 verification failure due to wrong signature +Pass HMAC with SHA-1 verification failure due to short signature +Pass HMAC with SHA-256 verification failure due to short signature +Pass HMAC with SHA-384 verification failure due to short signature +Pass HMAC with SHA-512 verification failure due to short signature diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.html b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.html new file mode 100644 index 000000000000..7d9c80d49f06 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.html @@ -0,0 +1,17 @@ +<!doctype html> +<meta charset=utf-8> +<title>WebCryptoAPI: sign() and verify() Using HMAC</title> +<meta name="timeout" content="long"> +<script> +self.GLOBAL = { + isWindow: function() { return true; }, + isWorker: function() { return false; }, + isShadowRealm: function() { return false; }, +}; +</script> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="hmac_vectors.js"></script> +<script src="hmac.js"></script> +<div id=log></div> +<script src="../../WebCryptoAPI/sign_verify/hmac.https.any.js"></script> diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.js b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.js new file mode 100644 index 000000000000..419bab050699 --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.https.any.js @@ -0,0 +1,6 @@ +// META: title=WebCryptoAPI: sign() and verify() Using HMAC +// META: script=hmac_vectors.js +// META: script=hmac.js +// META: timeout=long + +run_test(); diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.js b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.js new file mode 100644 index 000000000000..f5e2ad2769cd --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac.js @@ -0,0 +1,351 @@ + +function run_test() { + setup({explicit_done: true}); + + var subtle = self.crypto.subtle; // Change to test prefixed implementations + + // When are all these tests really done? When all the promises they use have resolved. + var all_promises = []; + + // Source file hmac_vectors.js provides the getTestVectors method + // for the algorithm that drives these tests. + var testVectors = getTestVectors(); + + // Test verification first, because signing tests rely on that working + testVectors.forEach(function(vector) { + var promise = importVectorKeys(vector, ["verify", "sign"]) + .then(function(vector) { + promise_test(function(test) { + var operation = subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, vector.signature, vector.plaintext) + .then(function(is_verified) { + assert_true(is_verified, "Signature verified"); + }, function(err) { + assert_unreached("Verification should not throw error " + vector.name + ": " + err.message + "'"); + }); + + return operation; + }, vector.name + " verification"); + + }, function(err) { + // We need a failed test if the importVectorKey operation fails, so + // we know we never tested verification. + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " verification"); + }); + + all_promises.push(promise); + }); + + // Test verification with an altered buffer after call + testVectors.forEach(function(vector) { + var promise = importVectorKeys(vector, ["verify", "sign"]) + .then(function(vector) { + promise_test(function(test) { + var signature = copyBuffer(vector.signature); + var operation = subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, signature, vector.plaintext) + .then(function(is_verified) { + assert_true(is_verified, "Signature is not verified"); + }, function(err) { + assert_unreached("Verification should not throw error " + vector.name + ": " + err.message + "'"); + }); + + signature[0] = 255 - signature[0]; + return operation; + }, vector.name + " verification with altered signature after call"); + }, function(err) { + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " verification with altered signature after call"); + }); + + all_promises.push(promise); + }); + + // Check for successful verification even if plaintext is altered after call. + testVectors.forEach(function(vector) { + var promise = importVectorKeys(vector, ["verify", "sign"]) + .then(function(vector) { + promise_test(function(test) { + var plaintext = copyBuffer(vector.plaintext); + var operation = subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, vector.signature, plaintext) + .then(function(is_verified) { + assert_true(is_verified, "Signature verified"); + }, function(err) { + assert_unreached("Verification should not throw error " + vector.name + ": " + err.message + "'"); + }); + + plaintext[0] = 255 - plaintext[0]; + return operation; + }, vector.name + " with altered plaintext after call"); + }, function(err) { + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " with altered plaintext"); + }); + + all_promises.push(promise); + }); + + // Check for failures due to no "verify" usage. + testVectors.forEach(function(originalVector) { + var vector = Object.assign({}, originalVector); + + var promise = importVectorKeys(vector, ["sign"]) + .then(function(vector) { + promise_test(function(test) { + return subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, vector.signature, vector.plaintext) + .then(function(plaintext) { + assert_unreached("Should have thrown error for no verify usage in " + vector.name + ": " + err.message + "'"); + }, function(err) { + assert_equals(err.name, "InvalidAccessError", "Should throw InvalidAccessError instead of '" + err.message + "'"); + }); + }, vector.name + " no verify usage"); + }, function(err) { + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " no verify usage"); + }); + + all_promises.push(promise); + }); + + // Check for successful signing and verification. + testVectors.forEach(function(vector) { + var promise = importVectorKeys(vector, ["verify", "sign"]) + .then(function(vectors) { + promise_test(function(test) { + return subtle.sign({name: "HMAC", hash: vector.hash}, vector.key, vector.plaintext) + .then(function(signature) { + assert_true(equalBuffers(signature, vector.signature), "Signing did not give the expected output"); + // Can we get the verify the new signature? + return subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, signature, vector.plaintext) + .then(function(is_verified) { + assert_true(is_verified, "Round trip verifies"); + return signature; + }, function(err) { + assert_unreached("verify error for test " + vector.name + ": " + err.message + "'"); + }); + }); + }, vector.name + " round trip"); + + }, function(err) { + // We need a failed test if the importVectorKey operation fails, so + // we know we never tested signing or verifying + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " round trip"); + }); + + all_promises.push(promise); + }); + + // Test signing with the wrong algorithm + testVectors.forEach(function(vector) { + // Want to get the key for the wrong algorithm + var promise = subtle.generateKey({name: "ECDSA", namedCurve: "P-256", hash: "SHA-256"}, false, ["sign", "verify"]) + .then(function(wrongKey) { + return importVectorKeys(vector, ["verify", "sign"]) + .then(function(vectors) { + promise_test(function(test) { + var operation = subtle.sign({name: "HMAC", hash: vector.hash}, wrongKey.privateKey, vector.plaintext) + .then(function(signature) { + assert_unreached("Signing should not have succeeded for " + vector.name); + }, function(err) { + assert_equals(err.name, "InvalidAccessError", "Should have thrown InvalidAccessError instead of '" + err.message + "'"); + }); + + return operation; + }, vector.name + " signing with wrong algorithm name"); + + }, function(err) { + // We need a failed test if the importVectorKey operation fails, so + // we know we never tested verification. + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " signing with wrong algorithm name"); + }); + }, function(err) { + promise_test(function(test) { + assert_unreached("Generate wrong key for test " + vector.name + " failed: '" + err.message + "'"); + }, "generate wrong key step: " + vector.name + " signing with wrong algorithm name"); + }); + + all_promises.push(promise); + }); + + // Test verification with the wrong algorithm + testVectors.forEach(function(vector) { + // Want to get the key for the wrong algorithm + var promise = subtle.generateKey({name: "ECDSA", namedCurve: "P-256", hash: "SHA-256"}, false, ["sign", "verify"]) + .then(function(wrongKey) { + return importVectorKeys(vector, ["verify", "sign"]) + .then(function(vector) { + promise_test(function(test) { + var operation = subtle.verify({name: "HMAC", hash: vector.hash}, wrongKey.publicKey, vector.signature, vector.plaintext) + .then(function(signature) { + assert_unreached("Verifying should not have succeeded for " + vector.name); + }, function(err) { + assert_equals(err.name, "InvalidAccessError", "Should have thrown InvalidAccessError instead of '" + err.message + "'"); + }); + + return operation; + }, vector.name + " verifying with wrong algorithm name"); + + }, function(err) { + // We need a failed test if the importVectorKey operation fails, so + // we know we never tested verification. + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " verifying with wrong algorithm name"); + }); + }, function(err) { + promise_test(function(test) { + assert_unreached("Generate wrong key for test " + vector.name + " failed: '" + err.message + "'"); + }, "generate wrong key step: " + vector.name + " verifying with wrong algorithm name"); + }); + + all_promises.push(promise); + }); + + // Verification should fail if the plaintext is changed + testVectors.forEach(function(vector) { + var promise = importVectorKeys(vector, ["verify", "sign"]) + .then(function(vector) { + var plaintext = copyBuffer(vector.plaintext); + plaintext[0] = 255 - plaintext[0]; + promise_test(function(test) { + var operation = subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, vector.signature, plaintext) + .then(function(is_verified) { + assert_false(is_verified, "Signature is NOT verified"); + }, function(err) { + assert_unreached("Verification should not throw error " + vector.name + ": " + err.message + "'"); + }); + + return operation; + }, vector.name + " verification failure due to wrong plaintext"); + + }, function(err) { + // We need a failed test if the importVectorKey operation fails, so + // we know we never tested verification. + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " verification failure due to wrong plaintext"); + }); + + all_promises.push(promise); + }); + + // Verification should fail if the signature is changed + testVectors.forEach(function(vector) { + var promise = importVectorKeys(vector, ["verify", "sign"]) + .then(function(vector) { + var signature = copyBuffer(vector.signature); + signature[0] = 255 - signature[0]; + promise_test(function(test) { + var operation = subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, signature, vector.plaintext) + .then(function(is_verified) { + assert_false(is_verified, "Signature is NOT verified"); + }, function(err) { + assert_unreached("Verification should not throw error " + vector.name + ": " + err.message + "'"); + }); + + return operation; + }, vector.name + " verification failure due to wrong signature"); + + }, function(err) { + // We need a failed test if the importVectorKey operation fails, so + // we know we never tested verification. + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " verification failure due to wrong signature"); + }); + + all_promises.push(promise); + }); + + // Verification should fail if the signature is wrong length + testVectors.forEach(function(vector) { + var promise = importVectorKeys(vector, ["verify", "sign"]) + .then(function(vector) { + var signature = vector.signature.slice(1); // Drop first byte + promise_test(function(test) { + var operation = subtle.verify({name: "HMAC", hash: vector.hash}, vector.key, signature, vector.plaintext) + .then(function(is_verified) { + assert_false(is_verified, "Signature is NOT verified"); + }, function(err) { + assert_unreached("Verification should not throw error " + vector.name + ": " + err.message + "'"); + }); + + return operation; + }, vector.name + " verification failure due to short signature"); + + }, function(err) { + // We need a failed test if the importVectorKey operation fails, so + // we know we never tested verification. + promise_test(function(test) { + assert_unreached("importVectorKeys failed for " + vector.name + ". Message: ''" + err.message + "''"); + }, "importVectorKeys step: " + vector.name + " verification failure due to short signature"); + }); + + all_promises.push(promise); + }); + + + + promise_test(function() { + return Promise.all(all_promises) + .then(function() {done();}) + .catch(function() {done();}) + }, "setup"); + + // A test vector has all needed fields for signing and verifying, EXCEPT that the + // key field may be null. This function replaces that null with the Correct + // CryptoKey object. + // + // Returns a Promise that yields an updated vector on success. + function importVectorKeys(vector, keyUsages) { + if (vector.key !== null) { + return new Promise(function(resolve, reject) { + resolve(vector); + }); + } else { + return subtle.importKey("raw", vector.keyBuffer, {name: "HMAC", hash: vector.hash}, false, keyUsages) + .then(function(key) { + vector.key = key; + return vector; + }); + } + } + + // Returns a copy of the sourceBuffer it is sent. + function copyBuffer(sourceBuffer) { + var source = new Uint8Array(sourceBuffer); + var copy = new Uint8Array(sourceBuffer.byteLength) + + for (var i=0; i<source.byteLength; i++) { + copy[i] = source[i]; + } + + return copy; + } + + function equalBuffers(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + + var aBytes = new Uint8Array(a); + var bBytes = new Uint8Array(b); + + for (var i=0; i<a.byteLength; i++) { + if (aBytes[i] !== bBytes[i]) { + return false; + } + } + + return true; + } + + return; +} diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac_vectors.js b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac_vectors.js new file mode 100644 index 000000000000..de9642b181cc --- /dev/null +++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/sign_verify/hmac_vectors.js @@ -0,0 +1,39 @@ + +function getTestVectors() { + var plaintext = new Uint8Array([95, 77, 186, 79, 50, 12, 12, 232, 118, 114, 90, 252, 229, 251, 210, 91, 248, 62, 90, 113, 37, 160, 140, 175, 231, 60, 62, 186, 196, 33, 119, 157, 249, 213, 93, 24, 12, 58, 233, 148, 38, 69, 225, 216, 47, 238, 140, 157, 41, 75, 60, 177, 160, 138, 153, 49, 32, 27, 60, 14, 129, 252, 71, 202, 207, 131, 21, 162, 175, 102, 50, 65, 19, 195, 182, 98, 48, 195, 70, 8, 196, 244, 89, 54, 52, 206, 2, 178, 103, 54, 34, 119, 240, 168, 64, 202, 116, 188, 61, 26, 98, 54, 149, 44, 94, 215, 170, 248, 168, 254, 203, 221, 250, 117, 132, 230, 151, 140, 234, 93, 42, 91, 159, 183, 241, 180, 140, 139, 11, 229, 138, 48, 82, 2, 117, 77, 131, 118, 16, 115, 116, 121, 60, 240, 38, 170, 238, 83, 0, 114, 125, 131, 108, 215, 30, 113, 179, 69, 221, 178, 228, 68, 70, 255, 197, 185, 1, 99, 84, 19, 137, 13, 145, 14, 163, 128, 152, 74, 144, 25, 16, 49, 50, 63, 22, 219, 204, 157, 107, 225, 104, 184, 72, 133, 56, 76, 160, 62, 18, 96, 10, 193, 194, 72, 2, 138, 243, 114, 108, 201, 52, 99, 136, 46, 168, 192, 42, 171]); + + var raw = { + "SHA-1": new Uint8Array([71, 162, 7, 70, 209, 113, 121, 219, 101, 224, 167, 157, 237, 255, 199, 253, 241, 129, 8, 27]), + "SHA-256": new Uint8Array([229, 136, 236, 8, 17, 70, 61, 118, 114, 65, 223, 16, 116, 180, 122, 228, 7, 27, 81, 242, 206, 54, 83, 123, 166, 156, 205, 195, 253, 194, 183, 168]), + "SHA-384": new Uint8Array([107, 29, 162, 142, 171, 31, 88, 42, 217, 113, 142, 255, 224, 94, 35, 213, 253, 44, 152, 119, 162, 217, 68, 63, 144, 190, 192, 147, 190, 206, 46, 167, 210, 53, 76, 208, 189, 197, 225, 71, 210, 233, 0, 147, 115, 73, 68, 136]), + "SHA-512": new Uint8Array([93, 204, 53, 148, 67, 170, 246, 82, 250, 19, 117, 214, 179, 230, 31, 220, 242, 155, 180, 162, 139, 213, 211, 220, 250, 64, 248, 47, 144, 107, 178, 128, 4, 85, 219, 3, 181, 211, 31, 185, 114, 161, 90, 109, 1, 3, 162, 78, 86, 209, 86, 161, 25, 192, 229, 161, 233, 42, 68, 195, 197, 101, 124, 249]) + }; + + var signatures = { + "SHA-1": new Uint8Array([5, 51, 144, 42, 153, 248, 82, 78, 229, 10, 240, 29, 56, 222, 220, 225, 51, 217, 140, 160]), + "SHA-256": new Uint8Array([133, 164, 12, 234, 46, 7, 140, 40, 39, 163, 149, 63, 251, 102, 194, 123, 41, 26, 71, 43, 13, 112, 160, 0, 11, 69, 216, 35, 128, 62, 235, 84]), + "SHA-384": new Uint8Array([33, 124, 61, 80, 240, 186, 154, 109, 110, 174, 30, 253, 215, 165, 24, 254, 46, 56, 128, 181, 130, 164, 13, 6, 30, 144, 153, 193, 224, 38, 239, 88, 130, 84, 139, 93, 92, 236, 221, 85, 152, 217, 155, 107, 111, 48, 87, 255]), + "SHA-512": new Uint8Array([97, 251, 39, 140, 63, 251, 12, 206, 43, 241, 207, 114, 61, 223, 216, 239, 31, 147, 28, 12, 97, 140, 37, 144, 115, 36, 96, 89, 57, 227, 249, 162, 198, 244, 175, 105, 11, 218, 52, 7, 220, 47, 87, 112, 246, 160, 164, 75, 149, 77, 100, 163, 50, 227, 238, 8, 33, 171, 248, 43, 127, 62, 153, 193]) + }; + + // Each test vector has the following fields: + // name - a unique name for this vector + // keyBuffer - an arrayBuffer with the key data + // key - a CryptoKey object for the keyBuffer. INITIALLY null! You must fill this in first to use it! + // hashName - the hash function to sign with + // plaintext - the text to encrypt + // signature - the expected signature + var vectors = []; + Object.keys(raw).forEach(function(hashName) { + vectors.push({ + name: "HMAC with " + hashName, + hash: hashName, + keyBuffer: raw[hashName], + key: null, + plaintext: plaintext, + signature: signatures[hashName] + }); + }); + + return vectors; +}
babe924da1576297aa6d3c5e9b4e924e6a99e388
2023-07-09 13:46:28
Lucas CHOLLET
libgfx: Provide a default implementation for `ImageDecoder::initialize`
false
Provide a default implementation for `ImageDecoder::initialize`
libgfx
diff --git a/Userland/Libraries/LibGfx/ImageFormats/ImageDecoder.h b/Userland/Libraries/LibGfx/ImageFormats/ImageDecoder.h index 88aa91c76002..e9498e492437 100644 --- a/Userland/Libraries/LibGfx/ImageFormats/ImageDecoder.h +++ b/Userland/Libraries/LibGfx/ImageFormats/ImageDecoder.h @@ -31,7 +31,7 @@ class ImageDecoderPlugin { virtual IntSize size() = 0; - virtual ErrorOr<void> initialize() = 0; + virtual ErrorOr<void> initialize() { return {}; } virtual bool is_animated() = 0; virtual size_t loop_count() = 0;
67cfb64d070b2f19bc04dd5967d2fdb8c0b7b1e8
2025-03-06 21:30:53
Luke Wilde
libweb: Separate adding to performance buffers and queueing to observers
false
Separate adding to performance buffers and queueing to observers
libweb
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp index e334051634f8..ce192ee89fed 100644 --- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp +++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp @@ -435,24 +435,44 @@ void WindowOrWorkerGlobalScopeMixin::queue_performance_entry(GC::Ref<Performance observer->append_to_observer_buffer({}, new_entry); } + // AD-HOC: Steps 6-9 are not here because other engines do not add to the performance entry buffer when queuing + // the performance observer task. The users of the Performance Timeline specification also do not expect + // this function to add to the entry buffer, instead queuing the observer task, then adding to the entry + // buffer separately. + + // 10. Queue the PerformanceObserver task with relevantGlobal as input. + queue_the_performance_observer_task(); +} + +// https://www.w3.org/TR/performance-timeline/#dfn-queue-a-performanceentry +// AD-HOC: This is a separate function because the users of this specification queues PerformanceObserver tasks and add +// to the entry buffer separately. +void WindowOrWorkerGlobalScopeMixin::add_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry, CheckIfPerformanceBufferIsFull check_if_performance_buffer_is_full) +{ // 6. Let tuple be the relevant performance entry tuple of entryType and relevantGlobal. - auto& tuple = relevant_performance_entry_tuple(entry_type); + auto& tuple = relevant_performance_entry_tuple(new_entry->entry_type()); + + // AD-HOC: We have a custom flag to always append to the buffer by default, as other performance specs do this by default + // (either they don't have a limit, or they check the limit themselves). This flag allows compatibility for specs + // that rely do and don't rely on this. + bool is_buffer_full = false; + auto should_add = PerformanceTimeline::ShouldAddEntry::Yes; - // 7. Let isBufferFull be the return value of the determine if a performance entry buffer is full algorithm with tuple - // as input. - bool is_buffer_full = tuple.is_full(); + if (check_if_performance_buffer_is_full == CheckIfPerformanceBufferIsFull::Yes) { + // 7. Let isBufferFull be the return value of the determine if a performance entry buffer is full algorithm with tuple + // as input. + is_buffer_full = tuple.is_full(); - // 8. Let shouldAdd be the result of should add entry with newEntry as input. - auto should_add = new_entry->should_add_entry(); + // 8. Let shouldAdd be the result of should add entry with newEntry as input. + should_add = new_entry->should_add_entry(); + } // 9. If isBufferFull is false and shouldAdd is true, append newEntry to tuple's performance entry buffer. if (!is_buffer_full && should_add == PerformanceTimeline::ShouldAddEntry::Yes) tuple.performance_entry_buffer.append(new_entry); - - // 10. Queue the PerformanceObserver task with relevantGlobal as input. - queue_the_performance_observer_task(); } + void WindowOrWorkerGlobalScopeMixin::clear_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type) { auto& tuple = relevant_performance_entry_tuple(entry_type); diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h index a593755a55ff..154574f992c0 100644 --- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h +++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h @@ -47,8 +47,14 @@ class WindowOrWorkerGlobalScopeMixin { void clear_interval(i32); void clear_map_of_active_timers(); + enum class CheckIfPerformanceBufferIsFull { + No, + Yes, + }; + PerformanceTimeline::PerformanceEntryTuple& relevant_performance_entry_tuple(FlyString const& entry_type); void queue_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry); + void add_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry, CheckIfPerformanceBufferIsFull check_if_performance_buffer_is_full = CheckIfPerformanceBufferIsFull::No); void clear_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type); void remove_entries_from_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type, String entry_name); diff --git a/Libraries/LibWeb/HighResolutionTime/Performance.cpp b/Libraries/LibWeb/HighResolutionTime/Performance.cpp index 08aa5b947d92..d9be79f28e01 100644 --- a/Libraries/LibWeb/HighResolutionTime/Performance.cpp +++ b/Libraries/LibWeb/HighResolutionTime/Performance.cpp @@ -89,7 +89,7 @@ WebIDL::ExceptionOr<GC::Ref<UserTiming::PerformanceMark>> Performance::mark(Stri window_or_worker().queue_performance_entry(entry); // 3. Add entry to the performance entry buffer. - // FIXME: This seems to be a holdover from moving to the `queue` structure for PerformanceObserver, as this would cause a double append. + window_or_worker().add_performance_entry(entry); // 4. Return entry. return entry; @@ -309,7 +309,7 @@ WebIDL::ExceptionOr<GC::Ref<UserTiming::PerformanceMeasure>> Performance::measur window_or_worker().queue_performance_entry(entry); // 11. Add entry to the performance entry buffer. - // FIXME: This seems to be a holdover from moving to the `queue` structure for PerformanceObserver, as this would cause a double append. + window_or_worker().add_performance_entry(entry); // 12. Return entry. return entry;
dcf3bdcb9a3f7f906c6d73f43de6e9867acc5a7d
2023-09-29 16:51:43
Sam Atkins
libweb: Use correct realm when focusing HTMLTextAreaElement
false
Use correct realm when focusing HTMLTextAreaElement
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTextAreaElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLTextAreaElement.cpp index be0ddb447bf0..01ce0b44868c 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLTextAreaElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLTextAreaElement.cpp @@ -56,7 +56,7 @@ void HTMLTextAreaElement::did_receive_focus() return; if (!m_text_node) return; - browsing_context->set_cursor_position(DOM::Position::create(*vm().current_realm(), *m_text_node, 0)); + browsing_context->set_cursor_position(DOM::Position::create(realm(), *m_text_node, 0)); } void HTMLTextAreaElement::did_lose_focus()
229188b815beb4fe6c8d947b73840b841a7c976b
2022-01-28 02:05:38
Lenny Maiorani
libgl: Set rasterizer material state without copying
false
Set rasterizer material state without copying
libgl
diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.cpp b/Userland/Libraries/LibGL/SoftwareGLContext.cpp index 1c531a73a9b3..565d66ac0e7c 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.cpp +++ b/Userland/Libraries/LibGL/SoftwareGLContext.cpp @@ -3158,22 +3158,8 @@ void SoftwareGLContext::sync_light_state() m_rasterizer.set_light_state(light_id, current_light_state); } - auto update_material_state = [&](SoftGPU::Face face, SoftGPU::Material const& current_material_state) { - SoftGPU::Material material; - - material.ambient = current_material_state.ambient; - material.diffuse = current_material_state.diffuse; - material.specular = current_material_state.specular; - material.emissive = current_material_state.emissive; - material.shininess = current_material_state.shininess; - material.ambient_color_index = current_material_state.ambient_color_index; - material.diffuse_color_index = current_material_state.diffuse_color_index; - material.specular_color_index = current_material_state.specular_color_index; - - m_rasterizer.set_material_state(face, material); - }; - update_material_state(SoftGPU::Face::Front, m_material_states[Face::Front]); - update_material_state(SoftGPU::Face::Back, m_material_states[Face::Back]); + m_rasterizer.set_material_state(SoftGPU::Face::Front, m_material_states[Face::Front]); + m_rasterizer.set_material_state(SoftGPU::Face::Back, m_material_states[Face::Back]); } void SoftwareGLContext::sync_device_texcoord_config()
a4e8a091880ab02d94c27a26956446a58b74e7f0
2021-12-21 23:24:36
Ali Mohammad Pur
libc: Implement getwchar()
false
Implement getwchar()
libc
diff --git a/Userland/Libraries/LibC/wchar.h b/Userland/Libraries/LibC/wchar.h index ae9bb5ed9165..64ff1183fe85 100644 --- a/Userland/Libraries/LibC/wchar.h +++ b/Userland/Libraries/LibC/wchar.h @@ -73,5 +73,6 @@ size_t wcsspn(const wchar_t* wcs, const wchar_t* accept); wint_t fgetwc(FILE* stream); wint_t getwc(FILE* stream); +wint_t getwchar(void); __END_DECLS diff --git a/Userland/Libraries/LibC/wstdio.cpp b/Userland/Libraries/LibC/wstdio.cpp index de41056abbd9..f0c04f1c9202 100644 --- a/Userland/Libraries/LibC/wstdio.cpp +++ b/Userland/Libraries/LibC/wstdio.cpp @@ -56,4 +56,9 @@ wint_t getwc(FILE* stream) { return fgetwc(stream); } + +wint_t getwchar() +{ + return getwc(stdin); +} }
015622bc22efec9f086aeae7f36333b526ce0451
2024-01-15 03:36:37
Jelle Raaijmakers
kernel: Set correct KeyCode count
false
Set correct KeyCode count
kernel
diff --git a/Kernel/API/KeyCode.h b/Kernel/API/KeyCode.h index c7f191f515f5..cd1ddd85608d 100644 --- a/Kernel/API/KeyCode.h +++ b/Kernel/API/KeyCode.h @@ -152,7 +152,7 @@ enum KeyCode : u8 { Key_Shift = Key_LeftShift, }; -int const key_code_count = Key_Menu; +size_t const key_code_count = Key_Menu + 1; enum KeyModifier { Mod_None = 0x00, diff --git a/Userland/Applications/Piano/MainWidget.cpp b/Userland/Applications/Piano/MainWidget.cpp index a97b99a62c96..d0d7e842b89a 100644 --- a/Userland/Applications/Piano/MainWidget.cpp +++ b/Userland/Applications/Piano/MainWidget.cpp @@ -189,7 +189,7 @@ void MainWidget::turn_off_pressed_keys() { if (m_keys_widget->mouse_note() != -1) m_track_manager.keyboard()->set_keyboard_note_in_active_octave(m_keys_widget->mouse_note(), DSP::Keyboard::Switch::Off); - for (int i = 0; i < key_code_count; ++i) { + for (size_t i = 0u; i < key_code_count; ++i) { if (m_keys_pressed[i]) note_key_action(i, DSP::Keyboard::Switch::Off); } @@ -199,7 +199,7 @@ void MainWidget::turn_on_pressed_keys() { if (m_keys_widget->mouse_note() != -1) m_track_manager.keyboard()->set_keyboard_note_in_active_octave(m_keys_widget->mouse_note(), DSP::Keyboard::Switch::On); - for (int i = 0; i < key_code_count; ++i) { + for (size_t i = 0u; i < key_code_count; ++i) { if (m_keys_pressed[i]) note_key_action(i, DSP::Keyboard::Switch::On); }
78fa430ca15f286f57a965cd5652b64fb2b86170
2022-01-11 03:33:24
Daniel Bertalan
ports: Update bash port to version 5.1.16
false
Update bash port to version 5.1.16
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index 9314ab137c55..4f5e84a3c769 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -6,7 +6,7 @@ Please make sure to keep this list up to date when adding and updating ports. :^ |----------------------------------------|-----------------------------------------------------------------|--------------------------|--------------------------------------------------------------------------------| | [`Another-World`](Another-World/) | Another World Bytecode Interpreter | | https://github.com/fabiensanglard/Another-World-Bytecode-Interpreter | | [`angband`](angband/) | Angband | 4.2.3 | https://rephial.org | -| [`bash`](bash/) | GNU Bash | 5.1.8 | https://www.gnu.org/software/bash/ | +| [`bash`](bash/) | GNU Bash | 5.1.16 | https://www.gnu.org/software/bash/ | | [`bass`](bass/) | Beneath a Steel Sky | cd-1.2 | https://www.scummvm.org/games | | [`bc`](bc/) | bc | 5.1.1 | https://github.com/gavinhoward/bc | | [`binutils`](binutils/) | GNU Binutils | 2.37 | https://www.gnu.org/software/binutils/ | diff --git a/Ports/bash/package.sh b/Ports/bash/package.sh index 33b0a081c4db..da7b3e8f2bd6 100755 --- a/Ports/bash/package.sh +++ b/Ports/bash/package.sh @@ -1,9 +1,9 @@ #!/usr/bin/env -S bash ../.port_include.sh port=bash -version=5.1.8 +version=5.1.16 useconfigure=true configopts=("--disable-nls" "--without-bash-malloc") -files="https://ftpmirror.gnu.org/gnu/bash/bash-${version}.tar.gz bash-${version}.tar.gz 0cfb5c9bb1a29f800a97bd242d19511c997a1013815b805e0fdd32214113d6be" +files="https://ftpmirror.gnu.org/gnu/bash/bash-${version}.tar.gz bash-${version}.tar.gz 5bac17218d3911834520dad13cd1f85ab944e1c09ae1aba55906be1f8192f558" auth_type="sha256" build() { diff --git a/Ports/bash/patches/remove-conflicting-declaration-in-glob.patch b/Ports/bash/patches/remove-conflicting-declaration-in-glob.patch deleted file mode 100644 index 1543a7356596..000000000000 --- a/Ports/bash/patches/remove-conflicting-declaration-in-glob.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- bash-5.1.8.serenity/lib/glob/glob.c 2020-10-30 18:49:00.000000000 +0000 -+++ bash-5.1.8/lib/glob/glob.c 2021-07-29 17:11:22.146328629 +0100 -@@ -122,7 +122,7 @@ - #else - # define dequote_pathname udequote_pathname - #endif --static void dequote_pathname PARAMS((char *)); -+//static void dequote_pathname PARAMS((char *)); - static int glob_testdir PARAMS((char *, int)); - static char **glob_dir_to_array PARAMS((char *, char **, int)); -
c1e0047b4849acd9d45f7a28952421767fb46a37
2020-08-15 03:35:45
Andreas Kling
libgui: When focusing a TextEditor via keyboard, select all contents
false
When focusing a TextEditor via keyboard, select all contents
libgui
diff --git a/Libraries/LibGUI/TextEditor.cpp b/Libraries/LibGUI/TextEditor.cpp index 0e5a93594b19..31c6c60e8f35 100644 --- a/Libraries/LibGUI/TextEditor.cpp +++ b/Libraries/LibGUI/TextEditor.cpp @@ -1147,8 +1147,10 @@ void TextEditor::set_cursor(const TextPosition& a_position) m_highlighter->cursor_did_change(); } -void TextEditor::focusin_event(FocusEvent&) +void TextEditor::focusin_event(FocusEvent& event) { + if (event.source() == FocusSource::Keyboard) + select_all(); m_cursor_state = true; update_cursor(); start_timer(500);
dba0840942feb13295ca3f7e9ec8e1c155c447ae
2022-01-12 19:39:09
Idan Horowitz
kernel: Remove outdated FIXME comment in sys$sethostname
false
Remove outdated FIXME comment in sys$sethostname
kernel
diff --git a/Kernel/Syscalls/hostname.cpp b/Kernel/Syscalls/hostname.cpp index 1d841890877e..da30c4d2bcb1 100644 --- a/Kernel/Syscalls/hostname.cpp +++ b/Kernel/Syscalls/hostname.cpp @@ -32,11 +32,10 @@ ErrorOr<FlatPtr> Process::sys$sethostname(Userspace<const char*> buffer, size_t if (length > 64) return ENAMETOOLONG; auto new_name = TRY(try_copy_kstring_from_user(buffer, length)); - return hostname().with_exclusive([&](auto& name) -> ErrorOr<FlatPtr> { - // FIXME: Use KString instead of String here. + hostname().with_exclusive([&](auto& name) { name = new_name->view(); - return 0; }); + return 0; } }
2b61193b7190e652eca966e5231d55069b409965
2023-09-09 22:53:57
kleines Filmröllchen
libaudio: Account for garbage shifts in several places in FLAC loader
false
Account for garbage shifts in several places in FLAC loader
libaudio
diff --git a/Userland/Libraries/LibAudio/FlacLoader.cpp b/Userland/Libraries/LibAudio/FlacLoader.cpp index b9d37d790ec8..4a2eb9459a95 100644 --- a/Userland/Libraries/LibAudio/FlacLoader.cpp +++ b/Userland/Libraries/LibAudio/FlacLoader.cpp @@ -806,7 +806,7 @@ ErrorOr<void, LoaderError> FlacLoaderPlugin::decode_custom_lpc(Vector<i64>& deco // These considerations are not in the original FLAC spec, but have been added to the IETF standard: https://datatracker.ietf.org/doc/html/draft-ietf-cellar-flac-03#appendix-A.3 sample.saturating_add(Checked<i64>::saturating_mul(static_cast<i64>(coefficients[t]), static_cast<i64>(decoded[i - t - 1]))); } - decoded[i] += sample.value() >> lpc_shift; + decoded[i] += lpc_shift >= 0 ? (sample.value() >> lpc_shift) : (sample.value() << -lpc_shift); } return {}; @@ -945,8 +945,10 @@ ALWAYS_INLINE ErrorOr<Vector<i64>, LoaderError> FlacLoaderPlugin::decode_rice_pa // escape code for unencoded binary partition if (k == (1 << partition_type) - 1) { u8 unencoded_bps = TRY(bit_input.read_bits<u8>(5)); - for (size_t r = 0; r < residual_sample_count; ++r) { - rice_partition[r] = sign_extend(TRY(bit_input.read_bits<u32>(unencoded_bps)), unencoded_bps); + if (unencoded_bps != 0) { + for (size_t r = 0; r < residual_sample_count; ++r) { + rice_partition[r] = sign_extend(TRY(bit_input.read_bits<u32>(unencoded_bps)), unencoded_bps); + } } } else { for (size_t r = 0; r < residual_sample_count; ++r) {
b91be8b9fd06b9253dc5931318cae308f87a8375
2020-09-30 23:35:24
AnotherTest
shell: Make 'editor' a member of Shell, and provide a LibShell
false
Make 'editor' a member of Shell, and provide a LibShell
shell
diff --git a/Shell/Builtin.cpp b/Shell/Builtin.cpp index 129af8e008d1..cae341ed4d2a 100644 --- a/Shell/Builtin.cpp +++ b/Shell/Builtin.cpp @@ -34,7 +34,6 @@ #include <unistd.h> extern char** environ; -extern RefPtr<Line::Editor> editor; int Shell::builtin_alias(int argc, const char** argv) { @@ -418,8 +417,8 @@ int Shell::builtin_disown(int argc, const char** argv) int Shell::builtin_history(int, const char**) { - for (size_t i = 0; i < editor->history().size(); ++i) { - printf("%6zu %s\n", i, editor->history()[i].characters()); + for (size_t i = 0; i < m_editor->history().size(); ++i) { + printf("%6zu %s\n", i, m_editor->history()[i].characters()); } return 0; } diff --git a/Shell/CMakeLists.txt b/Shell/CMakeLists.txt index db4bbe128b9c..706bc5eae1bf 100644 --- a/Shell/CMakeLists.txt +++ b/Shell/CMakeLists.txt @@ -6,8 +6,14 @@ set(SOURCES NodeVisitor.cpp Parser.cpp Shell.cpp +) + +serenity_lib(LibShell shell) +target_link_libraries(LibShell LibCore LibLine) + +set(SOURCES main.cpp ) serenity_bin(Shell) -target_link_libraries(Shell LibCore LibLine) +target_link_libraries(Shell LibShell) diff --git a/Shell/Shell.cpp b/Shell/Shell.cpp index 12142cef2ed3..4a837bc6e8d9 100644 --- a/Shell/Shell.cpp +++ b/Shell/Shell.cpp @@ -48,15 +48,67 @@ #include <sys/mman.h> #include <sys/stat.h> #include <sys/utsname.h> +#include <sys/wait.h> #include <termios.h> #include <unistd.h> static bool s_disable_hyperlinks = false; -extern RefPtr<Line::Editor> editor; extern char** environ; //#define SH_DEBUG +void Shell::setup_signals() +{ + Core::EventLoop::register_signal(SIGCHLD, [this](int) { + Vector<u64> disowned_jobs; + for (auto& it : jobs) { + auto job_id = it.key; + auto& job = *it.value; + int wstatus = 0; + auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED); + if (child_pid < 0) { + if (errno == ECHILD) { + // The child process went away before we could process its death, just assume it exited all ok. + // FIXME: This should never happen, the child should stay around until we do the waitpid above. + dbg() << "Child process gone, cannot get exit code for " << job_id; + child_pid = job.pid(); + } else { + ASSERT_NOT_REACHED(); + } + } +#ifndef __serenity__ + if (child_pid == 0) { + // Linux: if child didn't "change state", but existed. + continue; + } +#endif + if (child_pid == job.pid()) { + if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) { + job.set_signalled(WTERMSIG(wstatus)); + } else if (WIFEXITED(wstatus)) { + job.set_has_exit(WEXITSTATUS(wstatus)); + } else if (WIFSTOPPED(wstatus)) { + job.unblock(); + job.set_is_suspended(true); + } + } + if (job.should_be_disowned()) + disowned_jobs.append(job_id); + } + for (auto job_id : disowned_jobs) + jobs.remove(job_id); + }); + + Core::EventLoop::register_signal(SIGTSTP, [this](auto) { + auto job = current_job(); + kill_job(job, SIGTSTP); + if (job) { + job->set_is_suspended(true); + job->unblock(); + } + }); +} + void Shell::print_path(const String& path) { if (s_disable_hyperlinks || !m_is_interactive) { @@ -942,7 +994,7 @@ void Shell::load_history() while (history_file->can_read_line()) { auto b = history_file->read_line(1024); // skip the newline and terminating bytes - editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2)); + m_editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2)); } } @@ -952,7 +1004,7 @@ void Shell::save_history() if (file_or_error.is_error()) return; auto& file = *file_or_error.value(); - for (const auto& line : editor->history()) { + for (const auto& line : m_editor->history()) { file.write(line); file.write("\n"); } @@ -1079,9 +1131,9 @@ void Shell::highlight(Line::Editor& editor) const ast->highlight_in_editor(editor, const_cast<Shell&>(*this)); } -Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor) +Vector<Line::CompletionSuggestion> Shell::complete() { - auto line = editor.line(editor.cursor()); + auto line = m_editor->line(m_editor->cursor()); Parser parser(line); @@ -1133,7 +1185,7 @@ Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, cons // since we are not suggesting anything starting with // `/foo/', but rather just `bar...' auto token_length = escape_token(token).length(); - editor->suggest(token_length, original_token.length() - token_length); + m_editor->suggest(token_length, original_token.length() - token_length); // only suggest dot-files if path starts with a dot Core::DirIterator files(path, @@ -1170,7 +1222,7 @@ Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& na return complete_path("", name, offset); String completion = *match; - editor->suggest(escape_token(name).length(), 0); + m_editor->suggest(escape_token(name).length(), 0); // Now that we have a program name starting with our token, we look at // other program names starting with our token and cut off any mismatching @@ -1195,7 +1247,7 @@ Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, Vector<Line::CompletionSuggestion> suggestions; auto pattern = offset ? name.substring_view(0, offset) : ""; - editor->suggest(offset); + m_editor->suggest(offset); // Look at local variables. for (auto& frame : m_local_frames) { @@ -1227,7 +1279,7 @@ Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size Vector<Line::CompletionSuggestion> suggestions; auto pattern = offset ? name.substring_view(0, offset) : ""; - editor->suggest(offset); + m_editor->suggest(offset); Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir); @@ -1249,7 +1301,7 @@ Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_ while (start < option.length() && option[start] == '-' && start < 2) ++start; auto option_pattern = offset > start ? option.substring_view(start, offset - start) : ""; - editor->suggest(offset); + m_editor->suggest(offset); Vector<Line::CompletionSuggestion> suggestions; @@ -1288,8 +1340,8 @@ Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_ void Shell::bring_cursor_to_beginning_of_a_line() const { struct winsize ws; - if (editor) { - ws = editor->terminal_size(); + if (m_editor) { + ws = m_editor->terminal_size(); } else { if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) { // Very annoying assumptions. @@ -1321,7 +1373,7 @@ bool Shell::read_single_line() { restore_ios(); bring_cursor_to_beginning_of_a_line(); - auto line_result = editor->get_line(prompt()); + auto line_result = m_editor->get_line(prompt()); if (line_result.is_error()) { if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) { @@ -1347,7 +1399,7 @@ bool Shell::read_single_line() run_command(m_complete_line_builder.string_view()); - editor->add_to_history(m_complete_line_builder.build()); + m_editor->add_to_history(m_complete_line_builder.build()); m_complete_line_builder.clear(); return true; } @@ -1361,7 +1413,8 @@ void Shell::custom_event(Core::CustomEvent& event) } } -Shell::Shell() +Shell::Shell(Line::Editor& editor) + : m_editor(editor) { uid = getuid(); tcsetpgrp(0, getpgrp()); @@ -1493,3 +1546,52 @@ void Shell::save_to(JsonObject& object) } object.set("jobs", move(job_objects)); } + +void FileDescriptionCollector::collect() +{ + for (auto fd : m_fds) + close(fd); + m_fds.clear(); +} + +FileDescriptionCollector::~FileDescriptionCollector() +{ + collect(); +} + +void FileDescriptionCollector::add(int fd) +{ + m_fds.append(fd); +} + +SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings) +{ + for (auto& rewiring : intended_rewirings) { + int new_fd = dup(rewiring.source_fd); + if (new_fd < 0) { + if (errno != EBADF) + perror("dup"); + // The fd that will be overwritten isn't open right now, + // it will be cleaned up by the exec()-side collector + // and we have nothing to do here, so just ignore this error. + continue; + } + + auto flags = fcntl(new_fd, F_GETFL); + auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC); + ASSERT(rc == 0); + + m_saves.append({ rewiring.source_fd, new_fd }); + m_collector.add(new_fd); + } +} + +SavedFileDescriptors::~SavedFileDescriptors() +{ + for (auto& save : m_saves) { + if (dup2(save.saved, save.original) < 0) { + perror("dup2(~SavedFileDescriptors)"); + continue; + } + } +} diff --git a/Shell/Shell.h b/Shell/Shell.h index fb8e410e36db..8cf661d84a1e 100644 --- a/Shell/Shell.h +++ b/Shell/Shell.h @@ -137,7 +137,7 @@ class Shell : public Core::Object { static Vector<StringView> split_path(const StringView&); void highlight(Line::Editor&) const; - Vector<Line::CompletionSuggestion> complete(const Line::Editor&); + Vector<Line::CompletionSuggestion> complete(); Vector<Line::CompletionSuggestion> complete_path(const String& base, const String&, size_t offset); Vector<Line::CompletionSuggestion> complete_program_name(const String&, size_t offset); Vector<Line::CompletionSuggestion> complete_variable(const String&, size_t offset); @@ -196,7 +196,7 @@ class Shell : public Core::Object { #undef __ENUMERATE_SHELL_OPTION private: - Shell(); + Shell(Line::Editor&); virtual ~Shell() override; // FIXME: Port to Core::Property @@ -248,6 +248,8 @@ class Shell : public Core::Object { bool m_is_subshell { false }; bool m_should_format_live { false }; + + RefPtr<Line::Editor> m_editor; }; static constexpr bool is_word_character(char c) diff --git a/Shell/main.cpp b/Shell/main.cpp index 6572e317b28c..98295bb48028 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -39,108 +39,6 @@ RefPtr<Line::Editor> editor; Shell* s_shell; -void FileDescriptionCollector::collect() -{ - for (auto fd : m_fds) - close(fd); - m_fds.clear(); -} - -FileDescriptionCollector::~FileDescriptionCollector() -{ - collect(); -} - -void FileDescriptionCollector::add(int fd) -{ - m_fds.append(fd); -} - -SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings) -{ - for (auto& rewiring : intended_rewirings) { - int new_fd = dup(rewiring.source_fd); - if (new_fd < 0) { - if (errno != EBADF) - perror("dup"); - // The fd that will be overwritten isn't open right now, - // it will be cleaned up by the exec()-side collector - // and we have nothing to do here, so just ignore this error. - continue; - } - - auto flags = fcntl(new_fd, F_GETFL); - auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC); - ASSERT(rc == 0); - - m_saves.append({ rewiring.source_fd, new_fd }); - m_collector.add(new_fd); - } -} - -SavedFileDescriptors::~SavedFileDescriptors() -{ - for (auto& save : m_saves) { - if (dup2(save.saved, save.original) < 0) { - perror("dup2(~SavedFileDescriptors)"); - continue; - } - } -} - -void Shell::setup_signals() -{ - Core::EventLoop::register_signal(SIGCHLD, [](int) { - auto& jobs = s_shell->jobs; - Vector<u64> disowned_jobs; - for (auto& it : jobs) { - auto job_id = it.key; - auto& job = *it.value; - int wstatus = 0; - auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED); - if (child_pid < 0) { - if (errno == ECHILD) { - // The child process went away before we could process its death, just assume it exited all ok. - // FIXME: This should never happen, the child should stay around until we do the waitpid above. - dbg() << "Child process gone, cannot get exit code for " << job_id; - child_pid = job.pid(); - } else { - ASSERT_NOT_REACHED(); - } - } -#ifndef __serenity__ - if (child_pid == 0) { - // Linux: if child didn't "change state", but existed. - continue; - } -#endif - if (child_pid == job.pid()) { - if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) { - job.set_signalled(WTERMSIG(wstatus)); - } else if (WIFEXITED(wstatus)) { - job.set_has_exit(WEXITSTATUS(wstatus)); - } else if (WIFSTOPPED(wstatus)) { - job.unblock(); - job.set_is_suspended(true); - } - } - if (job.should_be_disowned()) - disowned_jobs.append(job_id); - } - for (auto job_id : disowned_jobs) - jobs.remove(job_id); - }); - - Core::EventLoop::register_signal(SIGTSTP, [](auto) { - auto job = s_shell->current_job(); - s_shell->kill_job(job, SIGTSTP); - if (job) { - job->set_is_suspended(true); - job->unblock(); - } - }); -} - int main(int argc, char** argv) { Core::EventLoop loop; @@ -163,6 +61,11 @@ int main(int argc, char** argv) s_shell->save_history(); }); + editor = Line::Editor::construct(); + + auto shell = Shell::construct(*editor); + s_shell = shell.ptr(); + s_shell->setup_signals(); #ifndef __serenity__ @@ -179,11 +82,6 @@ int main(int argc, char** argv) } #endif - editor = Line::Editor::construct(); - - auto shell = Shell::construct(); - s_shell = shell.ptr(); - editor->initialize(); shell->termios = editor->termios(); shell->default_termios = editor->default_termios(); @@ -200,8 +98,8 @@ int main(int argc, char** argv) } shell->highlight(editor); }; - editor->on_tab_complete = [&](const Line::Editor& editor) { - return shell->complete(editor); + editor->on_tab_complete = [&](const Line::Editor&) { + return shell->complete(); }; const char* command_to_run = nullptr;
3a5e78780ea6eb9f0b13c8d413a2a2ecb69782e0
2024-09-28 18:11:26
Aliaksandr Kalenik
libweb: Implement "The percentage height calculation quirk" in BFC
false
Implement "The percentage height calculation quirk" in BFC
libweb
diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/percentage-height-in-quirks-mode.txt b/Tests/LibWeb/Layout/expected/block-and-inline/percentage-height-in-quirks-mode.txt new file mode 100644 index 000000000000..7947568edfed --- /dev/null +++ b/Tests/LibWeb/Layout/expected/block-and-inline/percentage-height-in-quirks-mode.txt @@ -0,0 +1,9 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x616 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x600 children: not-inline + BlockContainer <div> at (8,8) content-size 784x600 children: not-inline + +ViewportPaintable (Viewport<#document>) [0,0 800x600] overflow: [0,0 800x616] + PaintableWithLines (BlockContainer<HTML>) [0,0 800x616] + PaintableWithLines (BlockContainer<BODY>) [8,8 784x600] + PaintableWithLines (BlockContainer<DIV>) [8,8 784x600] diff --git a/Tests/LibWeb/Layout/input/block-and-inline/percentage-height-in-quirks-mode.html b/Tests/LibWeb/Layout/input/block-and-inline/percentage-height-in-quirks-mode.html new file mode 100644 index 000000000000..00f538e76888 --- /dev/null +++ b/Tests/LibWeb/Layout/input/block-and-inline/percentage-height-in-quirks-mode.html @@ -0,0 +1,6 @@ +<style> +div { + background-color: crimson; + height: 100%; +} +</style><div></div> \ No newline at end of file diff --git a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp index 85dafe1d8f48..d0ffc1579af8 100644 --- a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp @@ -600,6 +600,41 @@ CSSPixels BlockFormattingContext::compute_auto_height_for_block_level_element(Bo return 0; } +static CSSPixels containing_block_height_to_resolve_percentage_in_quirks_mode(Box const& box, LayoutState const& state) +{ + // https://quirks.spec.whatwg.org/#the-percentage-height-calculation-quirk + auto const* containing_block = box.containing_block(); + while (containing_block) { + // 1. Let element be the nearest ancestor containing block of element, if there is one. + // Otherwise, return the initial containing block. + if (containing_block->is_viewport()) { + return state.get(*containing_block).content_height(); + } + + // 2. If element has a computed value of the display property that is table-cell, then return a + // UA-defined value. + if (containing_block->display().is_table_cell()) { + // FIXME: Likely UA-defined value should not be 0. + return 0; + } + + // 3. If element has a computed value of the height property that is not auto, then return element. + if (!containing_block->computed_values().height().is_auto()) { + return state.get(*containing_block).content_height(); + } + + // 4. If element has a computed value of the position property that is absolute, or if element is a + // not a block container or a table wrapper box, then return element. + if (containing_block->is_absolutely_positioned() || !is<BlockContainer>(*containing_block) || is<TableWrapper>(*containing_block)) { + return state.get(*containing_block).content_height(); + } + + // 5. Jump to the first step. + containing_block = containing_block->containing_block(); + } + VERIFY_NOT_REACHED(); +} + void BlockFormattingContext::layout_block_level_box(Box const& box, BlockContainer const& block_container, CSSPixels& bottom_of_lowest_margin_box, AvailableSpace const& available_space) { auto& box_state = m_state.get_mutable(box); @@ -672,11 +707,27 @@ void BlockFormattingContext::layout_block_level_box(Box const& box, BlockContain place_block_level_element_in_normal_flow_horizontally(box, available_space); - resolve_used_height_if_not_treated_as_auto(box, available_space); + AvailableSpace available_space_for_height_resolution = available_space; + auto is_grid_or_flex_container = box.display().is_grid_inside() || box.display().is_flex_inside(); + auto is_table_box = box.display().is_table_row() || box.display().is_table_row_group() || box.display().is_table_header_group() || box.display().is_table_footer_group() || box.display().is_table_cell() || box.display().is_table_caption(); + // NOTE: Spec doesn't mention this but quirk application needs to be skipped for grid and flex containers. + // See https://github.com/w3c/csswg-drafts/issues/5545 + if (box.document().in_quirks_mode() && box.computed_values().height().is_percentage() && !is_table_box && !is_grid_or_flex_container) { + // In quirks mode, for the purpose of calculating the height of an element, if the + // computed value of the position property of element is relative or static, the specified value + // for the height property of element is a <percentage>, and element does not have a computed + // value of the display property that is table-row, table-row-group, table-header-group, + // table-footer-group, table-cell or table-caption, the containing block of element must be + // calculated using the following algorithm, aborting on the first step that returns a value: + auto height = containing_block_height_to_resolve_percentage_in_quirks_mode(box, m_state); + available_space_for_height_resolution.height = AvailableSize::make_definite(height); + } + + resolve_used_height_if_not_treated_as_auto(box, available_space_for_height_resolution); // NOTE: Flex containers with `auto` height are treated as `max-content`, so we can compute their height early. if (box.is_replaced_box() || box.display().is_flex_inside()) { - resolve_used_height_if_treated_as_auto(box, available_space); + resolve_used_height_if_treated_as_auto(box, available_space_for_height_resolution); } // Before we insert the children of a list item we need to know the location of the marker. @@ -726,7 +777,7 @@ void BlockFormattingContext::layout_block_level_box(Box const& box, BlockContain // Tables already set their height during the independent formatting context run. When multi-line text cells are involved, using different // available space here than during the independent formatting context run can result in different line breaks and thus a different height. if (!box.display().is_table_inside()) { - resolve_used_height_if_treated_as_auto(box, available_space, independent_formatting_context); + resolve_used_height_if_treated_as_auto(box, available_space_for_height_resolution, independent_formatting_context); } if (independent_formatting_context || !margins_collapse_through(box, m_state)) {
09f76098b06804efb1f82f2244338ad4a97c9cfb
2024-07-02 06:45:22
Harm133
documentation: Fix dead link in Qt creator page
false
Fix dead link in Qt creator page
documentation
diff --git a/Documentation/QtCreatorConfiguration.md b/Documentation/QtCreatorConfiguration.md index 343e20f80240..a9beed92b71a 100644 --- a/Documentation/QtCreatorConfiguration.md +++ b/Documentation/QtCreatorConfiguration.md @@ -2,7 +2,7 @@ ## Setup -First, make sure you have a working toolchain and can build and run Ladybird. Go [here](BuildInstructions.md) for instructions for setting that up. +First, make sure you have a working toolchain and can build and run Ladybird. Go [here](BuildInstructionsLadybird.md) for instructions for setting that up. * Install [Qt Creator](https://www.qt.io/offline-installers). You don't need the entire Qt setup, just click 'Qt Creator' on the left side, and install that. * Open Qt Creator, select `File -> New File or Project...`
30e27f6483b0b709fb0b729a9cabd5bece9d53e3
2021-08-05 22:49:40
Linus Groh
libjs: Implement Temporal.ZonedDateTime.prototype.monthCode
false
Implement Temporal.ZonedDateTime.prototype.monthCode
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp index e827e4a833ca..49372020e8fc 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp @@ -34,6 +34,7 @@ void ZonedDateTimePrototype::initialize(GlobalObject& global_object) define_native_accessor(vm.names.timeZone, time_zone_getter, {}, Attribute::Configurable); define_native_accessor(vm.names.year, year_getter, {}, Attribute::Configurable); define_native_accessor(vm.names.month, month_getter, {}, Attribute::Configurable); + define_native_accessor(vm.names.monthCode, month_code_getter, {}, Attribute::Configurable); } static ZonedDateTime* typed_this(GlobalObject& global_object) @@ -129,4 +130,31 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::month_getter) return Value(calendar_month(global_object, calendar, *temporal_date_time)); } +// 6.3.7 get Temporal.ZonedDateTime.prototype.monthCode, https://tc39.es/proposal-temporal/#sec-get-temporal.zoneddatetime.prototype.monthcode +JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::month_code_getter) +{ + // 1. Let zonedDateTime be the this value. + // 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]). + auto* zoned_date_time = typed_this(global_object); + if (vm.exception()) + return {}; + + // 3. Let timeZone be zonedDateTime.[[TimeZone]]. + auto& time_zone = zoned_date_time->time_zone(); + + // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). + auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()); + + // 5. Let calendar be zonedDateTime.[[Calendar]]. + auto& calendar = zoned_date_time->calendar(); + + // 6. Let temporalDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, calendar). + auto* temporal_date_time = builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *instant, calendar); + if (vm.exception()) + return {}; + + // 7. Return ? CalendarMonthCode(calendar, temporalDateTime). + return js_string(vm, calendar_month_code(global_object, calendar, *temporal_date_time)); +} + } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h index 20667cbba21b..190b0e5f3376 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h @@ -23,6 +23,7 @@ class ZonedDateTimePrototype final : public Object { JS_DECLARE_NATIVE_FUNCTION(time_zone_getter); JS_DECLARE_NATIVE_FUNCTION(year_getter); JS_DECLARE_NATIVE_FUNCTION(month_getter); + JS_DECLARE_NATIVE_FUNCTION(month_code_getter); }; } diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/ZonedDateTime/ZonedDateTime.prototype.monthCode.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/ZonedDateTime/ZonedDateTime.prototype.monthCode.js new file mode 100644 index 000000000000..223cc3d157bb --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/ZonedDateTime/ZonedDateTime.prototype.monthCode.js @@ -0,0 +1,15 @@ +describe("correct behavior", () => { + test("basic functionality", () => { + const timeZone = new Temporal.TimeZone("UTC"); + const zonedDateTime = new Temporal.ZonedDateTime(1625614921000000000n, timeZone); + expect(zonedDateTime.monthCode).toBe("M07"); + }); +}); + +test("errors", () => { + test("this value must be a Temporal.ZonedDateTime object", () => { + expect(() => { + Reflect.get(Temporal.ZonedDateTime.prototype, "monthCode", "foo"); + }).toThrowWithMessage(TypeError, "Not a Temporal.ZonedDateTime"); + }); +});
10b93506ad0f075b024b5b7172f664296abbc035
2021-10-31 21:50:37
Idan Horowitz
tests: Convert test-wasm functions to ThrowCompletionOr
false
Convert test-wasm functions to ThrowCompletionOr
tests
diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cpp index e9243f8f4d8c..f761a7424354 100644 --- a/Tests/LibWasm/test-wasm.cpp +++ b/Tests/LibWasm/test-wasm.cpp @@ -60,8 +60,8 @@ class WebAssemblyModule final : public JS::Object { ~WebAssemblyModule() override = default; private: - JS_DECLARE_OLD_NATIVE_FUNCTION(get_export); - JS_DECLARE_OLD_NATIVE_FUNCTION(wasm_invoke); + JS_DECLARE_NATIVE_FUNCTION(get_export); + JS_DECLARE_NATIVE_FUNCTION(wasm_invoke); static HashMap<Wasm::Linker::Name, Wasm::ExternValue> const& spec_test_namespace() { @@ -143,19 +143,17 @@ TESTJS_GLOBAL_FUNCTION(compare_typed_arrays, compareTypedArrays) void WebAssemblyModule::initialize(JS::GlobalObject& global_object) { Base::initialize(global_object); - define_old_native_function("getExport", get_export, 1, JS::default_attributes); - define_old_native_function("invoke", wasm_invoke, 1, JS::default_attributes); + define_native_function("getExport", get_export, 1, JS::default_attributes); + define_native_function("invoke", wasm_invoke, 1, JS::default_attributes); } -JS_DEFINE_OLD_NATIVE_FUNCTION(WebAssemblyModule::get_export) +JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export) { - auto name = TRY_OR_DISCARD(vm.argument(0).to_string(global_object)); + auto name = TRY(vm.argument(0).to_string(global_object)); auto this_value = vm.this_value(global_object); - auto* object = TRY_OR_DISCARD(this_value.to_object(global_object)); - if (!is<WebAssemblyModule>(object)) { - vm.throw_exception<JS::TypeError>(global_object, "Not a WebAssemblyModule"); - return {}; - } + auto* object = TRY(this_value.to_object(global_object)); + if (!is<WebAssemblyModule>(object)) + return vm.throw_completion<JS::TypeError>(global_object, "Not a WebAssemblyModule"); auto instance = static_cast<WebAssemblyModule*>(object); for (auto& entry : instance->module_instance().exports()) { if (entry.name() == name) { @@ -173,49 +171,41 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(WebAssemblyModule::get_export) [&](const auto& ref) -> JS::Value { return JS::Value(static_cast<double>(ref.address.value())); }); }); } - vm.throw_exception<JS::TypeError>(global_object, String::formatted("'{}' does not refer to a function or a global", name)); - return {}; + return vm.throw_completion<JS::TypeError>(global_object, String::formatted("'{}' does not refer to a function or a global", name)); } } - vm.throw_exception<JS::TypeError>(global_object, String::formatted("'{}' could not be found", name)); - return {}; + return vm.throw_completion<JS::TypeError>(global_object, String::formatted("'{}' could not be found", name)); } -JS_DEFINE_OLD_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke) +JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke) { - auto address = static_cast<unsigned long>(TRY_OR_DISCARD(vm.argument(0).to_double(global_object))); + auto address = static_cast<unsigned long>(TRY(vm.argument(0).to_double(global_object))); Wasm::FunctionAddress function_address { address }; auto function_instance = WebAssemblyModule::machine().store().get(function_address); - if (!function_instance) { - vm.throw_exception<JS::TypeError>(global_object, "Invalid function address"); - return {}; - } + if (!function_instance) + return vm.throw_completion<JS::TypeError>(global_object, "Invalid function address"); const Wasm::FunctionType* type { nullptr }; function_instance->visit([&](auto& value) { type = &value.type(); }); - if (!type) { - vm.throw_exception<JS::TypeError>(global_object, "Invalid function found at given address"); - return {}; - } + if (!type) + return vm.throw_completion<JS::TypeError>(global_object, "Invalid function found at given address"); Vector<Wasm::Value> arguments; - if (type->parameters().size() + 1 > vm.argument_count()) { - vm.throw_exception<JS::TypeError>(global_object, String::formatted("Expected {} arguments for call, but found {}", type->parameters().size() + 1, vm.argument_count())); - return {}; - } + if (type->parameters().size() + 1 > vm.argument_count()) + return vm.throw_completion<JS::TypeError>(global_object, String::formatted("Expected {} arguments for call, but found {}", type->parameters().size() + 1, vm.argument_count())); size_t index = 1; for (auto& param : type->parameters()) { auto argument = vm.argument(index++); double double_value = 0; if (!argument.is_bigint()) - double_value = TRY_OR_DISCARD(argument.to_double(global_object)); + double_value = TRY(argument.to_double(global_object)); switch (param.kind()) { case Wasm::ValueType::Kind::I32: arguments.append(Wasm::Value(param, static_cast<u64>(double_value))); break; case Wasm::ValueType::Kind::I64: if (argument.is_bigint()) { - auto value = TRY_OR_DISCARD(argument.to_bigint_int64(global_object)); + auto value = TRY(argument.to_bigint_int64(global_object)); arguments.append(Wasm::Value(param, bit_cast<u64>(value))); } else { arguments.append(Wasm::Value(param, static_cast<u64>(double_value))); @@ -243,10 +233,8 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke) } auto result = WebAssemblyModule::machine().invoke(function_address, arguments); - if (result.is_trap()) { - vm.throw_exception<JS::TypeError>(global_object, String::formatted("Execution trapped: {}", result.trap().reason)); - return {}; - } + if (result.is_trap()) + return vm.throw_completion<JS::TypeError>(global_object, String::formatted("Execution trapped: {}", result.trap().reason)); if (result.values().is_empty()) return JS::js_null();
33026bcefeebb82441d62910572ff98803e146a2
2023-05-20 00:42:15
Ben Wiederhake
libcore: Remove recursive copy API from DeprecatedFile
false
Remove recursive copy API from DeprecatedFile
libcore
diff --git a/Userland/Libraries/LibCore/DeprecatedFile.cpp b/Userland/Libraries/LibCore/DeprecatedFile.cpp index 46740bd3ef6b..d0cdefec2fde 100644 --- a/Userland/Libraries/LibCore/DeprecatedFile.cpp +++ b/Userland/Libraries/LibCore/DeprecatedFile.cpp @@ -24,11 +24,6 @@ # include <serenity.h> #endif -// On Linux distros that use glibc `basename` is defined as a macro that expands to `__xpg_basename`, so we undefine it -#if defined(AK_OS_LINUX) && defined(basename) -# undef basename -#endif - namespace Core { ErrorOr<NonnullRefPtr<DeprecatedFile>> DeprecatedFile::open(DeprecatedString filename, OpenMode mode, mode_t permissions) @@ -181,196 +176,6 @@ DeprecatedString DeprecatedFile::absolute_path(DeprecatedString const& path) return LexicalPath::canonicalized_path(full_path.string()); } -static DeprecatedString get_duplicate_name(DeprecatedString const& path, int duplicate_count) -{ - if (duplicate_count == 0) { - return path; - } - LexicalPath lexical_path(path); - StringBuilder duplicated_name; - duplicated_name.append('/'); - auto& parts = lexical_path.parts_view(); - for (size_t i = 0; i < parts.size() - 1; ++i) { - duplicated_name.appendff("{}/", parts[i]); - } - auto prev_duplicate_tag = DeprecatedString::formatted("({})", duplicate_count); - auto title = lexical_path.title(); - if (title.ends_with(prev_duplicate_tag)) { - // remove the previous duplicate tag "(n)" so we can add a new tag. - title = title.substring_view(0, title.length() - prev_duplicate_tag.length()); - } - duplicated_name.appendff("{} ({})", title, duplicate_count); - if (!lexical_path.extension().is_empty()) { - duplicated_name.appendff(".{}", lexical_path.extension()); - } - return duplicated_name.to_deprecated_string(); -} - -ErrorOr<void, DeprecatedFile::CopyError> DeprecatedFile::copy_file_or_directory(DeprecatedString const& dst_path, DeprecatedString const& src_path, RecursionMode recursion_mode, LinkMode link_mode, AddDuplicateFileMarker add_duplicate_file_marker, PreserveMode preserve_mode) -{ - if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes) { - int duplicate_count = 0; - while (access(get_duplicate_name(dst_path, duplicate_count).characters(), F_OK) == 0) { - ++duplicate_count; - } - if (duplicate_count != 0) { - return copy_file_or_directory(get_duplicate_name(dst_path, duplicate_count), src_path, RecursionMode::Allowed, LinkMode::Disallowed, AddDuplicateFileMarker::Yes, preserve_mode); - } - } - - auto source_or_error = DeprecatedFile::open(src_path, OpenMode::ReadOnly); - if (source_or_error.is_error()) - return CopyError { errno, false }; - - auto& source = *source_or_error.value(); - - struct stat src_stat; - if (fstat(source.fd(), &src_stat) < 0) - return CopyError { errno, false }; - - if (source.is_directory()) { - if (recursion_mode == RecursionMode::Disallowed) - return CopyError { errno, true }; - return copy_directory(dst_path, src_path, src_stat); - } - - if (link_mode == LinkMode::Allowed) { - if (link(src_path.characters(), dst_path.characters()) < 0) - return CopyError { errno, false }; - - return {}; - } - - return copy_file(dst_path, src_stat, source, preserve_mode); -} - -ErrorOr<void, DeprecatedFile::CopyError> DeprecatedFile::copy_file(DeprecatedString const& dst_path, struct stat const& src_stat, DeprecatedFile& source, PreserveMode preserve_mode) -{ - int dst_fd = creat(dst_path.characters(), 0666); - if (dst_fd < 0) { - if (errno != EISDIR) - return CopyError { errno, false }; - - auto dst_dir_path = DeprecatedString::formatted("{}/{}", dst_path, LexicalPath::basename(source.filename())); - dst_fd = creat(dst_dir_path.characters(), 0666); - if (dst_fd < 0) - return CopyError { errno, false }; - } - - ScopeGuard close_fd_guard([dst_fd]() { ::close(dst_fd); }); - - if (src_stat.st_size > 0) { - if (ftruncate(dst_fd, src_stat.st_size) < 0) - return CopyError { errno, false }; - } - - for (;;) { - char buffer[32768]; - ssize_t nread = ::read(source.fd(), buffer, sizeof(buffer)); - if (nread < 0) { - return CopyError { errno, false }; - } - if (nread == 0) - break; - ssize_t remaining_to_write = nread; - char* bufptr = buffer; - while (remaining_to_write) { - ssize_t nwritten = ::write(dst_fd, bufptr, remaining_to_write); - if (nwritten < 0) - return CopyError { errno, false }; - - VERIFY(nwritten > 0); - remaining_to_write -= nwritten; - bufptr += nwritten; - } - } - - auto my_umask = umask(0); - umask(my_umask); - // NOTE: We don't copy the set-uid and set-gid bits unless requested. - if (!has_flag(preserve_mode, PreserveMode::Permissions)) - my_umask |= 06000; - - if (fchmod(dst_fd, src_stat.st_mode & ~my_umask) < 0) - return CopyError { errno, false }; - - if (has_flag(preserve_mode, PreserveMode::Ownership)) { - if (fchown(dst_fd, src_stat.st_uid, src_stat.st_gid) < 0) - return CopyError { errno, false }; - } - - if (has_flag(preserve_mode, PreserveMode::Timestamps)) { - struct timespec times[2] = { -#ifdef AK_OS_MACOS - src_stat.st_atimespec, - src_stat.st_mtimespec, -#else - src_stat.st_atim, - src_stat.st_mtim, -#endif - }; - if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0) - return CopyError { errno, false }; - } - - return {}; -} - -ErrorOr<void, DeprecatedFile::CopyError> DeprecatedFile::copy_directory(DeprecatedString const& dst_path, DeprecatedString const& src_path, struct stat const& src_stat, LinkMode link, PreserveMode preserve_mode) -{ - if (mkdir(dst_path.characters(), 0755) < 0) - return CopyError { errno, false }; - - DeprecatedString src_rp = DeprecatedFile::real_path_for(src_path); - src_rp = DeprecatedString::formatted("{}/", src_rp); - DeprecatedString dst_rp = DeprecatedFile::real_path_for(dst_path); - dst_rp = DeprecatedString::formatted("{}/", dst_rp); - - if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp)) - return CopyError { errno, false }; - - DirIterator di(src_path, DirIterator::SkipParentAndBaseDir); - if (di.has_error()) - return CopyError { errno, false }; - - while (di.has_next()) { - DeprecatedString filename = di.next_path(); - auto result = copy_file_or_directory( - DeprecatedString::formatted("{}/{}", dst_path, filename), - DeprecatedString::formatted("{}/{}", src_path, filename), - RecursionMode::Allowed, link, AddDuplicateFileMarker::Yes, preserve_mode); - if (result.is_error()) - return result.release_error(); - } - - auto my_umask = umask(0); - umask(my_umask); - - if (chmod(dst_path.characters(), src_stat.st_mode & ~my_umask) < 0) - return CopyError { errno, false }; - - if (has_flag(preserve_mode, PreserveMode::Ownership)) { - if (chown(dst_path.characters(), src_stat.st_uid, src_stat.st_gid) < 0) - return CopyError { errno, false }; - } - - if (has_flag(preserve_mode, PreserveMode::Timestamps)) { - struct timespec times[2] = { -#ifdef AK_OS_MACOS - src_stat.st_atimespec, - src_stat.st_mtimespec, -#else - src_stat.st_atim, - src_stat.st_mtim, -#endif - }; - if (utimensat(AT_FDCWD, dst_path.characters(), times, 0) < 0) - return CopyError { errno, false }; - } - - return {}; -} - Optional<DeprecatedString> DeprecatedFile::resolve_executable_from_environment(StringView filename) { if (filename.is_empty()) diff --git a/Userland/Libraries/LibCore/DeprecatedFile.h b/Userland/Libraries/LibCore/DeprecatedFile.h index f94cacb8fc81..488286d14c78 100644 --- a/Userland/Libraries/LibCore/DeprecatedFile.h +++ b/Userland/Libraries/LibCore/DeprecatedFile.h @@ -35,41 +35,6 @@ class DeprecatedFile final : public IODevice { static DeprecatedString current_working_directory(); static DeprecatedString absolute_path(DeprecatedString const& path); - enum class RecursionMode { - Allowed, - Disallowed - }; - - enum class LinkMode { - Allowed, - Disallowed - }; - - enum class AddDuplicateFileMarker { - Yes, - No, - }; - - enum class PreserveMode { - Nothing = 0, - Permissions = (1 << 0), - Ownership = (1 << 1), - Timestamps = (1 << 2), - }; - - struct CopyError : public Error { - CopyError(int error_code, bool t) - : Error(error_code) - , tried_recursing(t) - { - } - bool tried_recursing; - }; - - static ErrorOr<void, CopyError> copy_file(DeprecatedString const& dst_path, struct stat const& src_stat, DeprecatedFile& source, PreserveMode = PreserveMode::Nothing); - static ErrorOr<void, CopyError> copy_directory(DeprecatedString const& dst_path, DeprecatedString const& src_path, struct stat const& src_stat, LinkMode = LinkMode::Disallowed, PreserveMode = PreserveMode::Nothing); - static ErrorOr<void, CopyError> copy_file_or_directory(DeprecatedString const& dst_path, DeprecatedString const& src_path, RecursionMode = RecursionMode::Allowed, LinkMode = LinkMode::Disallowed, AddDuplicateFileMarker = AddDuplicateFileMarker::Yes, PreserveMode = PreserveMode::Nothing); - static DeprecatedString real_path_for(DeprecatedString const& filename); virtual bool open(OpenMode) override; @@ -96,6 +61,4 @@ class DeprecatedFile final : public IODevice { ShouldCloseFileDescriptor m_should_close_file_descriptor { ShouldCloseFileDescriptor::Yes }; }; -AK_ENUM_BITWISE_OPERATORS(DeprecatedFile::PreserveMode); - }
c8db8d61527830bad820b568c0f76169abaf1709
2022-02-17 02:51:37
Idan Horowitz
libcrypto: Exclude class_name() methods from the Kernel
false
Exclude class_name() methods from the Kernel
libcrypto
diff --git a/Userland/Libraries/LibCrypto/Authentication/GHash.cpp b/Userland/Libraries/LibCrypto/Authentication/GHash.cpp index 737f46868e9f..de06e63087c4 100644 --- a/Userland/Libraries/LibCrypto/Authentication/GHash.cpp +++ b/Userland/Libraries/LibCrypto/Authentication/GHash.cpp @@ -9,7 +9,6 @@ #include <AK/MemoryStream.h> #include <AK/Types.h> #include <LibCrypto/Authentication/GHash.h> -#include <LibCrypto/BigInt/UnsignedBigInteger.h> namespace { diff --git a/Userland/Libraries/LibCrypto/Authentication/GHash.h b/Userland/Libraries/LibCrypto/Authentication/GHash.h index 5225d906d968..0bfc8274cd38 100644 --- a/Userland/Libraries/LibCrypto/Authentication/GHash.h +++ b/Userland/Libraries/LibCrypto/Authentication/GHash.h @@ -7,10 +7,14 @@ #pragma once #include <AK/ByteReader.h> -#include <AK/String.h> +#include <AK/Endian.h> #include <AK/Types.h> #include <LibCrypto/Hash/HashFunction.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + namespace Crypto { namespace Authentication { @@ -44,7 +48,12 @@ class GHash final { constexpr static size_t digest_size() { return TagType::Size; } - String class_name() const { return "GHash"; } +#ifndef KERNEL + String class_name() const + { + return "GHash"; + } +#endif TagType process(ReadonlyBytes aad, ReadonlyBytes cipher); diff --git a/Userland/Libraries/LibCrypto/Authentication/HMAC.h b/Userland/Libraries/LibCrypto/Authentication/HMAC.h index c1abba39561f..8c80602dbe35 100644 --- a/Userland/Libraries/LibCrypto/Authentication/HMAC.h +++ b/Userland/Libraries/LibCrypto/Authentication/HMAC.h @@ -7,12 +7,15 @@ #pragma once #include <AK/ByteBuffer.h> -#include <AK/String.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> #include <AK/Types.h> #include <AK/Vector.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + constexpr static auto IPAD = 0x36; constexpr static auto OPAD = 0x5c; @@ -70,6 +73,7 @@ class HMAC { m_outer_hasher.update(m_key_data + m_inner_hasher.block_size(), m_outer_hasher.block_size()); } +#ifndef KERNEL String class_name() const { StringBuilder builder; @@ -77,6 +81,7 @@ class HMAC { builder.append(m_inner_hasher.class_name()); return builder.build(); } +#endif private: void derive_key(const u8* key, size_t length) diff --git a/Userland/Libraries/LibCrypto/Cipher/AES.h b/Userland/Libraries/LibCrypto/Cipher/AES.h index 796c65316796..654475f61dbf 100644 --- a/Userland/Libraries/LibCrypto/Cipher/AES.h +++ b/Userland/Libraries/LibCrypto/Cipher/AES.h @@ -119,7 +119,12 @@ class AESCipher final : public Cipher<AESCipherKey, AESCipherBlock> { virtual void encrypt_block(const BlockType& in, BlockType& out) override; virtual void decrypt_block(const BlockType& in, BlockType& out) override; - virtual String class_name() const override { return "AES"; } +#ifndef KERNEL + virtual String class_name() const override + { + return "AES"; + } +#endif protected: AESCipherKey m_key; diff --git a/Userland/Libraries/LibCrypto/Cipher/Cipher.h b/Userland/Libraries/LibCrypto/Cipher/Cipher.h index 436ff6e2f24f..d8ab4d1aacbd 100644 --- a/Userland/Libraries/LibCrypto/Cipher/Cipher.h +++ b/Userland/Libraries/LibCrypto/Cipher/Cipher.h @@ -111,7 +111,9 @@ class Cipher { virtual void encrypt_block(const BlockType& in, BlockType& out) = 0; virtual void decrypt_block(const BlockType& in, BlockType& out) = 0; +#ifndef KERNEL virtual String class_name() const = 0; +#endif protected: virtual ~Cipher() = default; diff --git a/Userland/Libraries/LibCrypto/Cipher/Mode/CBC.h b/Userland/Libraries/LibCrypto/Cipher/Mode/CBC.h index a32a0874e313..9cc3210a7e84 100644 --- a/Userland/Libraries/LibCrypto/Cipher/Mode/CBC.h +++ b/Userland/Libraries/LibCrypto/Cipher/Mode/CBC.h @@ -6,11 +6,14 @@ #pragma once -#include <AK/String.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> #include <LibCrypto/Cipher/Mode/Mode.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + namespace Crypto { namespace Cipher { @@ -26,6 +29,7 @@ class CBC : public Mode<T> { { } +#ifndef KERNEL virtual String class_name() const override { StringBuilder builder; @@ -33,8 +37,12 @@ class CBC : public Mode<T> { builder.append("_CBC"); return builder.build(); } +#endif - virtual size_t IV_length() const override { return IVSizeInBits / 8; } + virtual size_t IV_length() const override + { + return IVSizeInBits / 8; + } virtual void encrypt(ReadonlyBytes in, Bytes& out, ReadonlyBytes ivec = {}, Bytes* ivec_out = nullptr) override { diff --git a/Userland/Libraries/LibCrypto/Cipher/Mode/CTR.h b/Userland/Libraries/LibCrypto/Cipher/Mode/CTR.h index 8a0d55708315..979ca281ed47 100644 --- a/Userland/Libraries/LibCrypto/Cipher/Mode/CTR.h +++ b/Userland/Libraries/LibCrypto/Cipher/Mode/CTR.h @@ -6,11 +6,14 @@ #pragma once -#include <AK/String.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> #include <LibCrypto/Cipher/Mode/Mode.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + namespace Crypto { namespace Cipher { @@ -101,6 +104,7 @@ class CTR : public Mode<T> { { } +#ifndef KERNEL virtual String class_name() const override { StringBuilder builder; @@ -108,8 +112,12 @@ class CTR : public Mode<T> { builder.append("_CTR"); return builder.build(); } +#endif - virtual size_t IV_length() const override { return IVSizeInBits / 8; } + virtual size_t IV_length() const override + { + return IVSizeInBits / 8; + } virtual void encrypt(ReadonlyBytes in, Bytes& out, ReadonlyBytes ivec = {}, Bytes* ivec_out = nullptr) override { diff --git a/Userland/Libraries/LibCrypto/Cipher/Mode/GCM.h b/Userland/Libraries/LibCrypto/Cipher/Mode/GCM.h index d5cb048ba92f..b50713bd69c9 100644 --- a/Userland/Libraries/LibCrypto/Cipher/Mode/GCM.h +++ b/Userland/Libraries/LibCrypto/Cipher/Mode/GCM.h @@ -7,13 +7,16 @@ #pragma once #include <AK/OwnPtr.h> -#include <AK/String.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> #include <LibCrypto/Authentication/GHash.h> #include <LibCrypto/Cipher/Mode/CTR.h> #include <LibCrypto/Verification.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + namespace Crypto { namespace Cipher { @@ -40,6 +43,7 @@ class GCM : public CTR<T, IncrementFunction> { m_ghash = Authentication::GHash(m_auth_key); } +#ifndef KERNEL virtual String class_name() const override { StringBuilder builder; @@ -47,8 +51,12 @@ class GCM : public CTR<T, IncrementFunction> { builder.append("_GCM"); return builder.build(); } +#endif - virtual size_t IV_length() const override { return IVSizeInBits / 8; } + virtual size_t IV_length() const override + { + return IVSizeInBits / 8; + } // FIXME: This overload throws away the auth stuff, think up a better way to return more than a single bytebuffer. virtual void encrypt(ReadonlyBytes in, Bytes& out, ReadonlyBytes ivec = {}, Bytes* = nullptr) override diff --git a/Userland/Libraries/LibCrypto/Cipher/Mode/Mode.h b/Userland/Libraries/LibCrypto/Cipher/Mode/Mode.h index 0daf56eac6c3..6546c5a9c86e 100644 --- a/Userland/Libraries/LibCrypto/Cipher/Mode/Mode.h +++ b/Userland/Libraries/LibCrypto/Cipher/Mode/Mode.h @@ -35,8 +35,14 @@ class Mode { return ByteBuffer::create_uninitialized(input_size + T::block_size() - remainder); } +#ifndef KERNEL virtual String class_name() const = 0; - T& cipher() { return m_cipher; } +#endif + + T& cipher() + { + return m_cipher; + } protected: virtual void prune_padding(Bytes& data) diff --git a/Userland/Libraries/LibCrypto/Hash/HashFunction.h b/Userland/Libraries/LibCrypto/Hash/HashFunction.h index a803b1650b5d..ff73aa6e61e6 100644 --- a/Userland/Libraries/LibCrypto/Hash/HashFunction.h +++ b/Userland/Libraries/LibCrypto/Hash/HashFunction.h @@ -51,7 +51,9 @@ class HashFunction { virtual void reset() = 0; +#ifndef KERNEL virtual String class_name() const = 0; +#endif protected: virtual ~HashFunction() = default; diff --git a/Userland/Libraries/LibCrypto/Hash/HashManager.h b/Userland/Libraries/LibCrypto/Hash/HashManager.h index 4c31ecdf4a9f..28a9bf4e9e65 100644 --- a/Userland/Libraries/LibCrypto/Hash/HashManager.h +++ b/Userland/Libraries/LibCrypto/Hash/HashManager.h @@ -191,12 +191,14 @@ class Manager final : public HashFunction<0, 0, MultiHashDigestVariant> { [&](auto& hash) { hash.reset(); }); } +#ifndef KERNEL virtual String class_name() const override { return m_algorithm.visit( [&](const Empty&) -> String { return "UninitializedHashManager"; }, [&](const auto& hash) { return hash.class_name(); }); } +#endif inline bool is(HashKind kind) const { diff --git a/Userland/Libraries/LibCrypto/Hash/MD5.h b/Userland/Libraries/LibCrypto/Hash/MD5.h index 6e9127695387..9c55b38b86a1 100644 --- a/Userland/Libraries/LibCrypto/Hash/MD5.h +++ b/Userland/Libraries/LibCrypto/Hash/MD5.h @@ -6,10 +6,13 @@ #pragma once -#include <AK/String.h> #include <AK/Types.h> #include <LibCrypto/Hash/HashFunction.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + namespace Crypto { namespace Hash { @@ -53,7 +56,12 @@ class MD5 final : public HashFunction<512, 128> { virtual DigestType digest() override; virtual DigestType peek() override; - virtual String class_name() const override { return "MD5"; } +#ifndef KERNEL + virtual String class_name() const override + { + return "MD5"; + } +#endif inline static DigestType hash(const u8* data, size_t length) { diff --git a/Userland/Libraries/LibCrypto/Hash/SHA1.h b/Userland/Libraries/LibCrypto/Hash/SHA1.h index 8b3f57439001..8fcbfc7f5684 100644 --- a/Userland/Libraries/LibCrypto/Hash/SHA1.h +++ b/Userland/Libraries/LibCrypto/Hash/SHA1.h @@ -6,9 +6,12 @@ #pragma once -#include <AK/String.h> #include <LibCrypto/Hash/HashFunction.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + namespace Crypto { namespace Hash { @@ -49,10 +52,13 @@ class SHA1 final : public HashFunction<512, 160> { inline static DigestType hash(const ByteBuffer& buffer) { return hash(buffer.data(), buffer.size()); } inline static DigestType hash(StringView buffer) { return hash((const u8*)buffer.characters_without_null_termination(), buffer.length()); } +#ifndef KERNEL virtual String class_name() const override { return "SHA1"; } +#endif + inline virtual void reset() override { m_data_length = 0; diff --git a/Userland/Libraries/LibCrypto/Hash/SHA2.h b/Userland/Libraries/LibCrypto/Hash/SHA2.h index 5421b2bdf036..584e22984579 100644 --- a/Userland/Libraries/LibCrypto/Hash/SHA2.h +++ b/Userland/Libraries/LibCrypto/Hash/SHA2.h @@ -6,10 +6,13 @@ #pragma once -#include <AK/String.h> #include <AK/StringBuilder.h> #include <LibCrypto/Hash/HashFunction.h> +#ifndef KERNEL +# include <AK/String.h> +#endif + namespace Crypto { namespace Hash { @@ -97,10 +100,12 @@ class SHA256 final : public HashFunction<512, 256> { inline static DigestType hash(const ByteBuffer& buffer) { return hash(buffer.data(), buffer.size()); } inline static DigestType hash(StringView buffer) { return hash((const u8*)buffer.characters_without_null_termination(), buffer.length()); } +#ifndef KERNEL virtual String class_name() const override { return String::formatted("SHA{}", DigestSize * 8); } +#endif inline virtual void reset() override { @@ -147,10 +152,12 @@ class SHA384 final : public HashFunction<1024, 384> { inline static DigestType hash(const ByteBuffer& buffer) { return hash(buffer.data(), buffer.size()); } inline static DigestType hash(StringView buffer) { return hash((const u8*)buffer.characters_without_null_termination(), buffer.length()); } +#ifndef KERNEL virtual String class_name() const override { return String::formatted("SHA{}", DigestSize * 8); } +#endif inline virtual void reset() override { @@ -197,10 +204,12 @@ class SHA512 final : public HashFunction<1024, 512> { inline static DigestType hash(const ByteBuffer& buffer) { return hash(buffer.data(), buffer.size()); } inline static DigestType hash(StringView buffer) { return hash((const u8*)buffer.characters_without_null_termination(), buffer.length()); } +#ifndef KERNEL virtual String class_name() const override { return String::formatted("SHA{}", DigestSize * 8); } +#endif inline virtual void reset() override { diff --git a/Userland/Libraries/LibCrypto/PK/PK.h b/Userland/Libraries/LibCrypto/PK/PK.h index 75159db4c0f5..4483339b3693 100644 --- a/Userland/Libraries/LibCrypto/PK/PK.h +++ b/Userland/Libraries/LibCrypto/PK/PK.h @@ -7,7 +7,10 @@ #pragma once #include <AK/ByteBuffer.h> -#include <AK/String.h> + +#ifndef KERNEL +# include <AK/String.h> +#endif namespace Crypto { namespace PK { @@ -33,7 +36,9 @@ class PKSystem { virtual void sign(ReadonlyBytes in, Bytes& out) = 0; virtual void verify(ReadonlyBytes in, Bytes& out) = 0; +#ifndef KERNEL virtual String class_name() const = 0; +#endif virtual size_t output_size() const = 0; diff --git a/Userland/Libraries/LibCrypto/PK/RSA.h b/Userland/Libraries/LibCrypto/PK/RSA.h index 48a0cae3bf57..23dc1b3bd5b6 100644 --- a/Userland/Libraries/LibCrypto/PK/RSA.h +++ b/Userland/Libraries/LibCrypto/PK/RSA.h @@ -160,9 +160,17 @@ class RSA : public PKSystem<RSAPrivateKey<IntegerType>, RSAPublicKey<IntegerType virtual void sign(ReadonlyBytes in, Bytes& out) override; virtual void verify(ReadonlyBytes in, Bytes& out) override; - virtual String class_name() const override { return "RSA"; } +#ifndef KERNEL + virtual String class_name() const override + { + return "RSA"; + } +#endif - virtual size_t output_size() const override { return m_public_key.length(); } + virtual size_t output_size() const override + { + return m_public_key.length(); + } void import_public_key(ReadonlyBytes, bool pem = true); void import_private_key(ReadonlyBytes, bool pem = true); @@ -204,8 +212,16 @@ class RSA_PKCS1_EME : public RSA { virtual void sign(ReadonlyBytes, Bytes&) override; virtual void verify(ReadonlyBytes, Bytes&) override; - virtual String class_name() const override { return "RSA_PKCS1-EME"; } - virtual size_t output_size() const override { return m_public_key.length(); } +#ifndef KERNEL + virtual String class_name() const override + { + return "RSA_PKCS1-EME"; + } +#endif + virtual size_t output_size() const override + { + return m_public_key.length(); + } }; } }
18d45d10822219d0e86233ae112f549512f98452
2020-04-04 02:28:05
Andreas Kling
libweb: Add ResourceLoader::load_sync()
false
Add ResourceLoader::load_sync()
libweb
diff --git a/Libraries/LibWeb/ResourceLoader.cpp b/Libraries/LibWeb/ResourceLoader.cpp index daf2b813ebe3..47fa1741ee5f 100644 --- a/Libraries/LibWeb/ResourceLoader.cpp +++ b/Libraries/LibWeb/ResourceLoader.cpp @@ -25,6 +25,7 @@ */ #include <AK/SharedBuffer.h> +#include <LibCore/EventLoop.h> #include <LibCore/File.h> #include <LibProtocol/Client.h> #include <LibProtocol/Download.h> @@ -45,6 +46,24 @@ ResourceLoader::ResourceLoader() { } +void ResourceLoader::load_sync(const URL& url, Function<void(const ByteBuffer&)> success_callback, Function<void(const String&)> error_callback) +{ + Core::EventLoop loop; + + load( + url, + [&](auto& data) { + success_callback(data); + loop.quit(0); + }, + [&](auto& string) { + error_callback(string); + loop.quit(0); + }); + + loop.exec(); +} + void ResourceLoader::load(const URL& url, Function<void(const ByteBuffer&)> success_callback, Function<void(const String&)> error_callback) { if (url.protocol() == "file") { diff --git a/Libraries/LibWeb/ResourceLoader.h b/Libraries/LibWeb/ResourceLoader.h index 26f122bbf6c6..4a98b1659192 100644 --- a/Libraries/LibWeb/ResourceLoader.h +++ b/Libraries/LibWeb/ResourceLoader.h @@ -42,6 +42,7 @@ class ResourceLoader : public Core::Object { static ResourceLoader& the(); void load(const URL&, Function<void(const ByteBuffer&)> success_callback, Function<void(const String&)> error_callback = nullptr); + void load_sync(const URL&, Function<void(const ByteBuffer&)> success_callback, Function<void(const String&)> error_callback = nullptr); Function<void()> on_load_counter_change;
4fb96afafc6e87b75d2e310f949b0ca7b337b050
2020-10-24 20:04:01
Linus Groh
libjs: Support LegacyOctalEscapeSequence in string literals
false
Support LegacyOctalEscapeSequence in string literals
libjs
diff --git a/Libraries/LibJS/Parser.cpp b/Libraries/LibJS/Parser.cpp index 806d4aa73b98..d8ab3f7a40b4 100644 --- a/Libraries/LibJS/Parser.cpp +++ b/Libraries/LibJS/Parser.cpp @@ -836,23 +836,41 @@ NonnullRefPtr<ArrayExpression> Parser::parse_array_expression() return create_ast_node<ArrayExpression>(move(elements)); } -NonnullRefPtr<StringLiteral> Parser::parse_string_literal(Token token) +NonnullRefPtr<StringLiteral> Parser::parse_string_literal(Token token, bool in_template_literal) { auto status = Token::StringValueStatus::Ok; auto string = token.string_value(status); if (status != Token::StringValueStatus::Ok) { String message; - if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) { + if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) { + m_parser_state.m_string_legacy_octal_escape_sequence_in_scope = true; + if (in_template_literal) + message = "Octal escape sequence not allowed in template literal"; + else if (m_parser_state.m_strict_mode) + message = "Octal escape sequence in string literal not allowed in strict mode"; + } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) { auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal"; message = String::formatted("Malformed {} escape sequence", type); } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) { message = "Unicode code_point must not be greater than 0x10ffff in escape sequence"; + } else { + ASSERT_NOT_REACHED(); } if (!message.is_empty()) syntax_error(message, token.line_number(), token.line_column()); } + // It is possible for string literals to precede a Use Strict Directive that places the + // enclosing code in strict mode, and implementations must take care to not use this + // extended definition of EscapeSequence with such literals. For example, attempting to + // parse the following source text must fail: + // + // function invalid() { "\7"; "use strict"; } + + if (m_parser_state.m_string_legacy_octal_escape_sequence_in_scope && string == "use strict") + syntax_error("Octal escape sequence in string literal not allowed in strict mode"); + if (m_parser_state.m_use_strict_directive == UseStrictDirectiveState::Looking) { if (string == "use strict" && token.type() != TokenType::TemplateLiteralString) { m_parser_state.m_use_strict_directive = UseStrictDirectiveState::Found; @@ -884,7 +902,7 @@ NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged) while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) { if (match(TokenType::TemplateLiteralString)) { auto token = consume(); - expressions.append(parse_string_literal(token)); + expressions.append(parse_string_literal(token, true)); if (is_tagged) raw_strings.append(create_ast_node<StringLiteral>(token.value())); } else if (match(TokenType::TemplateLiteralExprStart)) { @@ -1249,6 +1267,7 @@ NonnullRefPtr<BlockStatement> Parser::parse_block_statement(bool& is_strict) first = false; } m_parser_state.m_strict_mode = initial_strict_mode_state; + m_parser_state.m_string_legacy_octal_escape_sequence_in_scope = false; consume(TokenType::CurlyClose); block->add_variables(m_parser_state.m_let_scopes.last()); block->add_functions(m_parser_state.m_function_scopes.last()); diff --git a/Libraries/LibJS/Parser.h b/Libraries/LibJS/Parser.h index 007e8b6879c7..565f3ff704a2 100644 --- a/Libraries/LibJS/Parser.h +++ b/Libraries/LibJS/Parser.h @@ -87,7 +87,7 @@ class Parser { NonnullRefPtr<RegExpLiteral> parse_regexp_literal(); NonnullRefPtr<ObjectExpression> parse_object_expression(); NonnullRefPtr<ArrayExpression> parse_array_expression(); - NonnullRefPtr<StringLiteral> parse_string_literal(Token token); + NonnullRefPtr<StringLiteral> parse_string_literal(Token token, bool in_template_literal = false); NonnullRefPtr<TemplateLiteral> parse_template_literal(bool is_tagged); NonnullRefPtr<Expression> parse_secondary_expression(NonnullRefPtr<Expression>, int min_precedence, Associativity associate = Associativity::Right); NonnullRefPtr<CallExpression> parse_call_expression(NonnullRefPtr<Expression>); @@ -184,6 +184,7 @@ class Parser { bool m_in_function_context { false }; bool m_in_break_context { false }; bool m_in_continue_context { false }; + bool m_string_legacy_octal_escape_sequence_in_scope { false }; explicit ParserState(Lexer); }; diff --git a/Libraries/LibJS/Tests/string-escapes.js b/Libraries/LibJS/Tests/string-escapes.js index e4abf9ec07a7..d8c75e9055f1 100644 --- a/Libraries/LibJS/Tests/string-escapes.js +++ b/Libraries/LibJS/Tests/string-escapes.js @@ -13,3 +13,32 @@ test("unicode escapes", () => { expect(`\u{1f41e}`).toBe("🐞"); expect("\u00ff").toBe(String.fromCharCode(0xff)); }); + +describe("octal escapes", () => { + test("basic functionality", () => { + expect("\1").toBe("\u0001"); + expect("\2").toBe("\u0002"); + expect("\3").toBe("\u0003"); + expect("\4").toBe("\u0004"); + expect("\5").toBe("\u0005"); + expect("\6").toBe("\u0006"); + expect("\7").toBe("\u0007"); + expect("\8").toBe("8"); + expect("\9").toBe("9"); + expect("\128").toBe("\n8"); + expect("\141bc").toBe("abc"); + expect("f\157o\142a\162").toBe("foobar"); + expect("\123\145\162\145\156\151\164\171\117\123").toBe("SerenityOS"); + }); + + test("syntax error in template literal", () => { + expect("`\\123`").not.toEval(); + }); + + test("syntax error in strict mode", () => { + expect("'use strict'; '\\123'").not.toEval(); + expect('"use strict"; "\\123"').not.toEval(); + // Special case, string literal precedes use strict directive + expect("'\\123'; somethingElse; 'use strict'").not.toEval(); + }); +}); diff --git a/Libraries/LibJS/Token.cpp b/Libraries/LibJS/Token.cpp index 0921ee9e1417..57190ef487a9 100644 --- a/Libraries/LibJS/Token.cpp +++ b/Libraries/LibJS/Token.cpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, Stephan Unverwerth <[email protected]> + * Copyright (c) 2020, Linus Groh <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -103,8 +104,19 @@ String Token::string_value(StringValueStatus& status) const { ASSERT(type() == TokenType::StringLiteral || type() == TokenType::TemplateLiteralString); auto is_template = type() == TokenType::TemplateLiteralString; + auto offset = is_template ? 0 : 1; - auto offset = type() == TokenType::TemplateLiteralString ? 0 : 1; + size_t i; + + auto lookahead = [&]<typename T>(T fn, size_t distance = 1) -> bool { + if (i + distance >= m_value.length() - offset) + return false; + return fn(m_value[i + distance]); + }; + + auto is_octal_digit = [](char c) { + return c >= '0' && c <= '7'; + }; auto encoding_failure = [&status](StringValueStatus parse_status) -> String { status = parse_status; @@ -112,7 +124,7 @@ String Token::string_value(StringValueStatus& status) const }; StringBuilder builder; - for (size_t i = offset; i < m_value.length() - offset; ++i) { + for (i = offset; i < m_value.length() - offset; ++i) { if (m_value[i] == '\\' && i + 1 < m_value.length() - offset) { i++; switch (m_value[i]) { @@ -134,9 +146,6 @@ String Token::string_value(StringValueStatus& status) const case 'v': builder.append('\v'); break; - case '0': - builder.append((char)0); - break; case '\'': builder.append('\''); break; @@ -200,9 +209,43 @@ String Token::string_value(StringValueStatus& status) const builder.append(m_value[i]); break; } + if (m_value[i] == '0' && !lookahead(isdigit)) { + builder.append((char)0); + break; + } - // FIXME: Also parse octal. Should anything else generate a syntax error? - builder.append(m_value[i]); + // In non-strict mode LegacyOctalEscapeSequence is allowed in strings: + // https://tc39.es/ecma262/#sec-additional-syntax-string-literals + String octal_str; + + // OctalDigit [lookahead ∉ OctalDigit] + if (is_octal_digit(m_value[i]) && !lookahead(is_octal_digit)) { + status = StringValueStatus::LegacyOctalEscapeSequence; + octal_str = String(&m_value[i], 1); + } + // ZeroToThree OctalDigit [lookahead ∉ OctalDigit] + else if (m_value[i] >= '0' && m_value[i] <= '3' && lookahead(is_octal_digit) && !lookahead(is_octal_digit, 2)) { + status = StringValueStatus::LegacyOctalEscapeSequence; + octal_str = String(m_value.substring_view(i, 2)); + i++; + } + // FourToSeven OctalDigit + else if (m_value[i] >= '4' && m_value[i] <= '7' && lookahead(is_octal_digit)) { + status = StringValueStatus::LegacyOctalEscapeSequence; + octal_str = String(m_value.substring_view(i, 2)); + i++; + } + // ZeroToThree OctalDigit OctalDigit + else if (m_value[i] >= '0' && m_value[i] <= '3' && lookahead(is_octal_digit) && lookahead(is_octal_digit, 2)) { + status = StringValueStatus::LegacyOctalEscapeSequence; + octal_str = String(m_value.substring_view(i, 3)); + i += 2; + } + + if (status == StringValueStatus::LegacyOctalEscapeSequence) + builder.append_code_point(strtoul(octal_str.characters(), nullptr, 8)); + else + builder.append(m_value[i]); } } else { builder.append(m_value[i]); diff --git a/Libraries/LibJS/Token.h b/Libraries/LibJS/Token.h index 3b967f97756e..b9d4bb0d60f1 100644 --- a/Libraries/LibJS/Token.h +++ b/Libraries/LibJS/Token.h @@ -208,6 +208,7 @@ class Token { MalformedHexEscape, MalformedUnicodeEscape, UnicodeEscapeOverflow, + LegacyOctalEscapeSequence, }; String string_value(StringValueStatus& status) const;
55f7ddfb8c0ed45d5576675eae0616b8e5befeca
2020-08-27 14:07:31
Andreas Kling
libgui: Don't make views sort by column 0 by default
false
Don't make views sort by column 0 by default
libgui
diff --git a/Libraries/LibGUI/AbstractView.h b/Libraries/LibGUI/AbstractView.h index a60e81346f3d..273f7f50f236 100644 --- a/Libraries/LibGUI/AbstractView.h +++ b/Libraries/LibGUI/AbstractView.h @@ -117,7 +117,7 @@ class AbstractView : public ScrollableWidget { ModelIndex m_hovered_index; ModelIndex m_last_valid_hovered_index; - int m_key_column { 0 }; + int m_key_column { -1 }; SortOrder m_sort_order; private:
c6f1962919506019c4c586a4ee94d50fc4e979b6
2020-06-04 01:22:40
Hüseyin ASLITÜRK
libgui: Add scancode value to KeyEvent
false
Add scancode value to KeyEvent
libgui
diff --git a/Libraries/LibGUI/Event.h b/Libraries/LibGUI/Event.h index b8dbe6d73e3e..93eef75d5b01 100644 --- a/Libraries/LibGUI/Event.h +++ b/Libraries/LibGUI/Event.h @@ -267,10 +267,11 @@ enum MouseButton : u8 { class KeyEvent final : public Event { public: - KeyEvent(Type type, KeyCode key, u8 modifiers) + KeyEvent(Type type, KeyCode key, u8 modifiers, u32 scancode) : Event(type) , m_key(key) , m_modifiers(modifiers) + , m_scancode(scancode) { } @@ -281,6 +282,7 @@ class KeyEvent final : public Event { bool logo() const { return m_modifiers & Mod_Logo; } u8 modifiers() const { return m_modifiers; } String text() const { return m_text; } + u32 scancode() const { return m_scancode; } String to_string() const; @@ -288,6 +290,7 @@ class KeyEvent final : public Event { friend class WindowServerConnection; KeyCode m_key { 0 }; u8 m_modifiers { 0 }; + u32 m_scancode { 0 }; String m_text; }; diff --git a/Libraries/LibGUI/WindowServerConnection.cpp b/Libraries/LibGUI/WindowServerConnection.cpp index afa94e5768ca..ed8c584dbc44 100644 --- a/Libraries/LibGUI/WindowServerConnection.cpp +++ b/Libraries/LibGUI/WindowServerConnection.cpp @@ -129,7 +129,7 @@ void WindowServerConnection::handle(const Messages::WindowClient::KeyDown& messa if (!window) return; - auto key_event = make<KeyEvent>(Event::KeyDown, (KeyCode) message.key(), message.modifiers()); + auto key_event = make<KeyEvent>(Event::KeyDown, (KeyCode) message.key(), message.modifiers(), message.scancode()); if (message.character() != '\0') { char ch = message.character(); key_event->m_text = String(&ch, 1); @@ -188,7 +188,7 @@ void WindowServerConnection::handle(const Messages::WindowClient::KeyUp& message if (!window) return; - auto key_event = make<KeyEvent>(Event::KeyUp, (KeyCode) message.key(), message.modifiers()); + auto key_event = make<KeyEvent>(Event::KeyUp, (KeyCode) message.key(), message.modifiers(), message.scancode()); if (message.character() != '\0') { char ch = message.character(); key_event->m_text = String(&ch, 1);
ccd491594fcb83141a7d7f24c2db650d877ac8e4
2021-05-22 19:22:11
Itamar
libgui: Increase width of Autocomplete suggestions box
false
Increase width of Autocomplete suggestions box
libgui
diff --git a/Userland/Libraries/LibGUI/AutocompleteProvider.cpp b/Userland/Libraries/LibGUI/AutocompleteProvider.cpp index ba881d037aaf..b0fc9ae2bbe2 100644 --- a/Userland/Libraries/LibGUI/AutocompleteProvider.cpp +++ b/Userland/Libraries/LibGUI/AutocompleteProvider.cpp @@ -84,7 +84,7 @@ AutocompleteBox::AutocompleteBox(TextEditor& editor) { m_popup_window = GUI::Window::construct(m_editor->window()); m_popup_window->set_window_type(GUI::WindowType::Tooltip); - m_popup_window->set_rect(0, 0, 200, 100); + m_popup_window->set_rect(0, 0, 300, 100); m_suggestion_view = m_popup_window->set_main_widget<GUI::TableView>(); m_suggestion_view->set_column_headers_visible(false);
b253bca8073751310fa8583cfd7fe912f55f14a5
2022-02-24 03:23:30
Linus Groh
ak: Add optional format string parameter to String{,Builder}::join()
false
Add optional format string parameter to String{,Builder}::join()
ak
diff --git a/AK/String.h b/AK/String.h index 27f7799fa7a2..1449f7e1273d 100644 --- a/AK/String.h +++ b/AK/String.h @@ -102,10 +102,10 @@ class String { [[nodiscard]] static String roman_number_from(size_t value); template<class SeparatorType, class CollectionType> - [[nodiscard]] static String join(const SeparatorType& separator, const CollectionType& collection) + [[nodiscard]] static String join(const SeparatorType& separator, const CollectionType& collection, StringView fmtstr = "{}"sv) { StringBuilder builder; - builder.join(separator, collection); + builder.join(separator, collection, fmtstr); return builder.build(); } diff --git a/AK/StringBuilder.h b/AK/StringBuilder.h index 6abf6d99a298..869c20446ce0 100644 --- a/AK/StringBuilder.h +++ b/AK/StringBuilder.h @@ -70,7 +70,7 @@ class StringBuilder { void trim(size_t count) { m_buffer.resize(m_buffer.size() - count); } template<class SeparatorType, class CollectionType> - void join(SeparatorType const& separator, CollectionType const& collection) + void join(SeparatorType const& separator, CollectionType const& collection, StringView fmtstr = "{}"sv) { bool first = true; for (auto& item : collection) { @@ -78,7 +78,7 @@ class StringBuilder { first = false; else append(separator); - appendff("{}", item); + appendff(fmtstr, item); } }
8e6b386ff73f67abe0b5d31a0944dec1977a0ba6
2023-07-15 15:29:39
Kenneth Myhra
libweb: Add AO initialize_readable_stream()
false
Add AO initialize_readable_stream()
libweb
diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp index 2e39925f6133..af3d9a72bd29 100644 --- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp +++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.cpp @@ -1178,6 +1178,20 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStream>> create_writable_stream(JS: return stream; } +// https://streams.spec.whatwg.org/#initialize-readable-stream +void initialize_readable_stream(ReadableStream& stream) +{ + // 1. Set stream.[[state]] to "readable". + stream.set_state(ReadableStream::State::Readable); + + // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined. + stream.set_reader({}); + stream.set_stored_error({}); + + // 3. Set stream.[[disturbed]] to false. + stream.set_disturbed(false); +} + // https://streams.spec.whatwg.org/#initialize-writable-stream void initialize_writable_stream(WritableStream& stream) { diff --git a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h index 27b8d744238b..f45f5c55cf22 100644 --- a/Userland/Libraries/LibWeb/Streams/AbstractOperations.h +++ b/Userland/Libraries/LibWeb/Streams/AbstractOperations.h @@ -91,6 +91,7 @@ void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamC bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const&); WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStream>> create_writable_stream(JS::Realm& realm, StartAlgorithm&& start_algorithm, WriteAlgorithm&& write_algorithm, CloseAlgorithm&& close_algorithm, AbortAlgorithm&& abort_algorithm, double high_water_mark, SizeAlgorithm&& size_algorithm); +void initialize_readable_stream(ReadableStream&); void initialize_writable_stream(WritableStream&); WebIDL::ExceptionOr<JS::NonnullGCPtr<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(WritableStream&);
65df30d00c1356054df197205ac1544603406250
2021-12-12 03:37:21
Jose Flores
piano: Add track controls to the player widget
false
Add track controls to the player widget
piano
diff --git a/Userland/Applications/Piano/MainWidget.cpp b/Userland/Applications/Piano/MainWidget.cpp index 8e7a1a4bd274..571a86de986f 100644 --- a/Userland/Applications/Piano/MainWidget.cpp +++ b/Userland/Applications/Piano/MainWidget.cpp @@ -56,15 +56,15 @@ MainWidget::~MainWidget() { } -void MainWidget::add_actions(GUI::Menu& menu) +void MainWidget::add_track_actions(GUI::Menu& menu) { menu.add_action(GUI::Action::create("&Add Track", { Mod_Ctrl, Key_T }, [&](auto&) { - m_track_manager.add_track(); + m_player_widget->add_track(); })); menu.add_action(GUI::Action::create("&Next Track", { Mod_Ctrl, Key_N }, [&](auto&) { turn_off_pressed_keys(); - m_track_manager.next_track(); + m_player_widget->next_track(); turn_on_pressed_keys(); m_knobs_widget->update_knobs(); diff --git a/Userland/Applications/Piano/MainWidget.h b/Userland/Applications/Piano/MainWidget.h index e40c8ff87c27..e71a8572c0b5 100644 --- a/Userland/Applications/Piano/MainWidget.h +++ b/Userland/Applications/Piano/MainWidget.h @@ -25,7 +25,7 @@ class MainWidget final : public GUI::Widget { public: virtual ~MainWidget() override; - void add_actions(GUI::Menu&); + void add_track_actions(GUI::Menu&); void set_octave_and_ensure_note_change(Direction); void set_octave_and_ensure_note_change(int); diff --git a/Userland/Applications/Piano/PlayerWidget.cpp b/Userland/Applications/Piano/PlayerWidget.cpp index e8f931bd148e..50201e9747e6 100644 --- a/Userland/Applications/Piano/PlayerWidget.cpp +++ b/Userland/Applications/Piano/PlayerWidget.cpp @@ -11,6 +11,9 @@ #include "TrackManager.h" #include <LibGUI/BoxLayout.h> #include <LibGUI/Button.h> +#include <LibGUI/ComboBox.h> +#include <LibGUI/ItemListModel.h> +#include <LibGUI/Label.h> PlayerWidget::PlayerWidget(TrackManager& manager, AudioPlayerLoop& loop) : m_track_manager(manager) @@ -18,11 +21,45 @@ PlayerWidget::PlayerWidget(TrackManager& manager, AudioPlayerLoop& loop) { set_layout<GUI::HorizontalBoxLayout>(); set_fill_with_background_color(true); + m_track_number_choices.append("1"); m_play_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/play.png").release_value_but_fixme_should_propagate_errors(); m_pause_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/pause.png").release_value_but_fixme_should_propagate_errors(); m_back_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-back.png").release_value_but_fixme_should_propagate_errors(); // Go back a note m_next_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-forward.png").release_value_but_fixme_should_propagate_errors(); // Advance a note + m_add_track_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/plus.png").release_value_but_fixme_should_propagate_errors(); + m_next_track_icon = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-last.png").release_value_but_fixme_should_propagate_errors(); + + RefPtr<GUI::Label> label = add<GUI::Label>("Track"); + label->set_max_width(75); + + m_track_dropdown = add<GUI::ComboBox>(); + m_track_dropdown->set_max_width(75); + m_track_dropdown->set_model(*GUI::ItemListModel<String>::create(m_track_number_choices)); + m_track_dropdown->set_only_allow_values_from_model(true); + m_track_dropdown->set_model_column(0); + m_track_dropdown->set_selected_index(0); + m_track_dropdown->on_change = [this]([[maybe_unused]] auto name, GUI::ModelIndex model_index) { + m_track_manager.set_current_track(model_index.row()); + }; + + m_add_track_button = add<GUI::Button>(); + m_add_track_button->set_icon(*m_add_track_icon); + m_add_track_button->set_fixed_width(30); + m_add_track_button->set_tooltip("Add Track"); + m_add_track_button->set_focus_policy(GUI::FocusPolicy::NoFocus); + m_add_track_button->on_click = [this](unsigned) { + add_track(); + }; + + m_next_track_button = add<GUI::Button>(); + m_next_track_button->set_icon(*m_next_track_icon); + m_next_track_button->set_fixed_width(30); + m_next_track_button->set_tooltip("Next Track"); + m_next_track_button->set_focus_policy(GUI::FocusPolicy::NoFocus); + m_next_track_button->on_click = [this](unsigned) { + next_track(); + }; m_play_button = add<GUI::Button>(); m_play_button->set_icon(*m_pause_icon); @@ -61,3 +98,17 @@ PlayerWidget::PlayerWidget(TrackManager& manager, AudioPlayerLoop& loop) PlayerWidget::~PlayerWidget() { } + +void PlayerWidget::add_track() +{ + m_track_manager.add_track(); + auto latest_track_count = m_track_manager.track_count(); + auto latest_track_string = String::number(latest_track_count); + m_track_number_choices.append(latest_track_string); + m_track_dropdown->set_selected_index(latest_track_count - 1); +} + +void PlayerWidget::next_track() +{ + m_track_dropdown->set_selected_index(m_track_manager.next_track_index()); +} diff --git a/Userland/Applications/Piano/PlayerWidget.h b/Userland/Applications/Piano/PlayerWidget.h index 3152578b30c8..19a619839266 100644 --- a/Userland/Applications/Piano/PlayerWidget.h +++ b/Userland/Applications/Piano/PlayerWidget.h @@ -16,18 +16,27 @@ class PlayerWidget final : public GUI::Toolbar { public: virtual ~PlayerWidget() override; + void add_track(); + void next_track(); + private: explicit PlayerWidget(TrackManager&, AudioPlayerLoop&); TrackManager& m_track_manager; AudioPlayerLoop& m_audio_loop; + Vector<String> m_track_number_choices; RefPtr<Gfx::Bitmap> m_play_icon; RefPtr<Gfx::Bitmap> m_pause_icon; RefPtr<Gfx::Bitmap> m_back_icon; RefPtr<Gfx::Bitmap> m_next_icon; + RefPtr<Gfx::Bitmap> m_add_track_icon; + RefPtr<Gfx::Bitmap> m_next_track_icon; + RefPtr<GUI::ComboBox> m_track_dropdown; RefPtr<GUI::Button> m_play_button; RefPtr<GUI::Button> m_back_button; RefPtr<GUI::Button> m_next_button; + RefPtr<GUI::Button> m_add_track_button; + RefPtr<GUI::Button> m_next_track_button; }; diff --git a/Userland/Applications/Piano/TrackManager.cpp b/Userland/Applications/Piano/TrackManager.cpp index 5e2537c77f9d..705af0f56bfb 100644 --- a/Userland/Applications/Piano/TrackManager.cpp +++ b/Userland/Applications/Piano/TrackManager.cpp @@ -90,8 +90,11 @@ void TrackManager::add_track() m_tracks.append(make<Track>(m_time)); } -void TrackManager::next_track() +int TrackManager::next_track_index() { - if (++m_current_track >= m_tracks.size()) - m_current_track = 0; + auto next_track_index = m_current_track + 1; + if (next_track_index >= m_tracks.size()) + return 0; + else + return next_track_index; } diff --git a/Userland/Applications/Piano/TrackManager.h b/Userland/Applications/Piano/TrackManager.h index 08893cc22f3d..4b315ea11822 100644 --- a/Userland/Applications/Piano/TrackManager.h +++ b/Userland/Applications/Piano/TrackManager.h @@ -27,6 +27,12 @@ class TrackManager { Span<const Sample> buffer() const { return m_current_front_buffer; } int octave() const { return m_octave; } int octave_base() const { return (m_octave - octave_min) * 12; } + int track_count() { return m_tracks.size(); }; + void set_current_track(size_t track_index) + { + VERIFY((int)track_index < track_count()); + m_current_track = track_index; + } int time() const { return m_time; } void time_forward(int amount); @@ -38,7 +44,7 @@ class TrackManager { void set_octave(Direction); void set_octave(int octave); void add_track(); - void next_track(); + int next_track_index(); private: Vector<NonnullOwnPtr<Track>> m_tracks; diff --git a/Userland/Applications/Piano/main.cpp b/Userland/Applications/Piano/main.cpp index c5927129da51..c9433d71bab9 100644 --- a/Userland/Applications/Piano/main.cpp +++ b/Userland/Applications/Piano/main.cpp @@ -73,7 +73,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) })); auto& edit_menu = window->add_menu("&Edit"); - main_widget.add_actions(edit_menu); + main_widget.add_track_actions(edit_menu); auto& help_menu = window->add_menu("&Help"); help_menu.add_action(GUI::CommonActions::make_about_action("Piano", app_icon, window));
d9895ec12dbf51066fdc873920803121d7499844
2021-09-30 04:19:53
Linus Groh
libjs: Convert internal_has_property() to ThrowCompletionOr
false
Convert internal_has_property() to ThrowCompletionOr
libjs
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp index 921bcd378bd2..5243a796e72b 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp @@ -1403,7 +1403,7 @@ class @wrapper_class@ : public @wrapper_base_class@ { if (interface.extended_attributes.contains("CustomHasProperty")) { generator.append(R"~~~( - virtual bool internal_has_property(JS::PropertyName const&) const override; + virtual JS::ThrowCompletionOr<bool> internal_has_property(JS::PropertyName const&) const override; )~~~"); } diff --git a/Userland/Libraries/LibJS/Runtime/Object.cpp b/Userland/Libraries/LibJS/Runtime/Object.cpp index bff0be6cd1e6..cee28b6580df 100644 --- a/Userland/Libraries/LibJS/Runtime/Object.cpp +++ b/Userland/Libraries/LibJS/Runtime/Object.cpp @@ -261,7 +261,7 @@ bool Object::has_property(PropertyName const& property_name) const VERIFY(property_name.is_valid()); // 3. Return ? O.[[HasProperty]](P). - return internal_has_property(property_name); + return TRY_OR_DISCARD(internal_has_property(property_name)); } // 7.3.12 HasOwnProperty ( O, P ), https://tc39.es/ecma262/#sec-hasownproperty @@ -616,25 +616,30 @@ ThrowCompletionOr<bool> Object::internal_define_own_property(PropertyName const& } // 10.1.7 [[HasProperty]] ( P ), https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-hasproperty-p -bool Object::internal_has_property(PropertyName const& property_name) const +ThrowCompletionOr<bool> Object::internal_has_property(PropertyName const& property_name) const { + auto& vm = this->vm(); + // 1. Assert: IsPropertyKey(P) is true. VERIFY(property_name.is_valid()); // 2. Let hasOwn be ? O.[[GetOwnProperty]](P). - auto has_own = TRY_OR_DISCARD(internal_get_own_property(property_name)); + auto has_own = TRY(internal_get_own_property(property_name)); // 3. If hasOwn is not undefined, return true. if (has_own.has_value()) return true; // 4. Let parent be ? O.[[GetPrototypeOf]](). - auto* parent = TRY_OR_DISCARD(internal_get_prototype_of()); + auto* parent = TRY(internal_get_prototype_of()); // 5. If parent is not null, then if (parent) { // a. Return ? parent.[[HasProperty]](P). - return parent->internal_has_property(property_name); + auto result = parent->internal_has_property(property_name); + if (auto* exception = vm.exception()) + return throw_completion(exception->value()); + return result; } // 6. Return false. diff --git a/Userland/Libraries/LibJS/Runtime/Object.h b/Userland/Libraries/LibJS/Runtime/Object.h index a34cd26c2343..a02b7395efad 100644 --- a/Userland/Libraries/LibJS/Runtime/Object.h +++ b/Userland/Libraries/LibJS/Runtime/Object.h @@ -97,7 +97,7 @@ class Object : public Cell { virtual ThrowCompletionOr<bool> internal_prevent_extensions(); virtual ThrowCompletionOr<Optional<PropertyDescriptor>> internal_get_own_property(PropertyName const&) const; virtual ThrowCompletionOr<bool> internal_define_own_property(PropertyName const&, PropertyDescriptor const&); - virtual bool internal_has_property(PropertyName const&) const; + virtual ThrowCompletionOr<bool> internal_has_property(PropertyName const&) const; virtual Value internal_get(PropertyName const&, Value receiver) const; virtual bool internal_set(PropertyName const&, Value value, Value receiver); virtual bool internal_delete(PropertyName const&); diff --git a/Userland/Libraries/LibJS/Runtime/ProxyObject.cpp b/Userland/Libraries/LibJS/Runtime/ProxyObject.cpp index cb77da735c95..398e3d46c4b2 100644 --- a/Userland/Libraries/LibJS/Runtime/ProxyObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ProxyObject.cpp @@ -416,7 +416,7 @@ ThrowCompletionOr<bool> ProxyObject::internal_define_own_property(PropertyName c } // 10.5.7 [[HasProperty]] ( P ), https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p -bool ProxyObject::internal_has_property(PropertyName const& property_name) const +ThrowCompletionOr<bool> ProxyObject::internal_has_property(PropertyName const& property_name) const { auto& vm = this->vm(); auto& global_object = this->global_object(); @@ -427,16 +427,14 @@ bool ProxyObject::internal_has_property(PropertyName const& property_name) const // 2. Let handler be O.[[ProxyHandler]]. // 3. If handler is null, throw a TypeError exception. - if (m_is_revoked) { - vm.throw_exception<TypeError>(global_object, ErrorType::ProxyRevoked); - return {}; - } + if (m_is_revoked) + return vm.throw_completion<TypeError>(global_object, ErrorType::ProxyRevoked); // 4. Assert: Type(handler) is Object. // 5. Let target be O.[[ProxyTarget]]. // 6. Let trap be ? GetMethod(handler, "has"). - auto trap = TRY_OR_DISCARD(Value(&m_handler).get_method(global_object, vm.names.has)); + auto trap = TRY(Value(&m_handler).get_method(global_object, vm.names.has)); // 7. If trap is undefined, then if (!trap) { @@ -445,31 +443,27 @@ bool ProxyObject::internal_has_property(PropertyName const& property_name) const } // 8. Let booleanTrapResult be ! ToBoolean(? Call(trap, handler, « target, P »)). - auto trap_result = TRY_OR_DISCARD(vm.call(*trap, &m_handler, &m_target, property_name_to_value(vm, property_name))).to_boolean(); + auto trap_result = TRY(vm.call(*trap, &m_handler, &m_target, property_name_to_value(vm, property_name))).to_boolean(); // 9. If booleanTrapResult is false, then if (!trap_result) { // a. Let targetDesc be ? target.[[GetOwnProperty]](P). - auto target_descriptor = TRY_OR_DISCARD(m_target.internal_get_own_property(property_name)); + auto target_descriptor = TRY(m_target.internal_get_own_property(property_name)); // b. If targetDesc is not undefined, then if (target_descriptor.has_value()) { // i. If targetDesc.[[Configurable]] is false, throw a TypeError exception. - if (!*target_descriptor->configurable) { - vm.throw_exception<TypeError>(global_object, ErrorType::ProxyHasExistingNonConfigurable); - return {}; - } + if (!*target_descriptor->configurable) + return vm.throw_completion<TypeError>(global_object, ErrorType::ProxyHasExistingNonConfigurable); // ii. Let extensibleTarget be ? IsExtensible(target). auto extensible_target = m_target.is_extensible(); - if (vm.exception()) - return {}; + if (auto* exception = vm.exception()) + return throw_completion(exception->value()); // iii. If extensibleTarget is false, throw a TypeError exception. - if (!extensible_target) { - vm.throw_exception<TypeError>(global_object, ErrorType::ProxyHasExistingNonExtensible); - return false; - } + if (!extensible_target) + return vm.throw_completion<TypeError>(global_object, ErrorType::ProxyHasExistingNonExtensible); } } diff --git a/Userland/Libraries/LibJS/Runtime/ProxyObject.h b/Userland/Libraries/LibJS/Runtime/ProxyObject.h index e54025f47eff..1b9bfec70ec8 100644 --- a/Userland/Libraries/LibJS/Runtime/ProxyObject.h +++ b/Userland/Libraries/LibJS/Runtime/ProxyObject.h @@ -41,7 +41,7 @@ class ProxyObject final : public FunctionObject { virtual ThrowCompletionOr<bool> internal_prevent_extensions() override; virtual ThrowCompletionOr<Optional<PropertyDescriptor>> internal_get_own_property(PropertyName const&) const override; virtual ThrowCompletionOr<bool> internal_define_own_property(PropertyName const&, PropertyDescriptor const&) override; - virtual bool internal_has_property(PropertyName const&) const override; + virtual ThrowCompletionOr<bool> internal_has_property(PropertyName const&) const override; virtual Value internal_get(PropertyName const&, Value receiver) const override; virtual bool internal_set(PropertyName const&, Value value, Value receiver) override; virtual bool internal_delete(PropertyName const&) override; diff --git a/Userland/Libraries/LibJS/Runtime/ReflectObject.cpp b/Userland/Libraries/LibJS/Runtime/ReflectObject.cpp index 262d40f171f9..3ac12b423609 100644 --- a/Userland/Libraries/LibJS/Runtime/ReflectObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ReflectObject.cpp @@ -231,7 +231,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::has) return {}; // 3. Return ? target.[[HasProperty]](key). - return Value(target.as_object().internal_has_property(key)); + return Value(TRY_OR_DISCARD(target.as_object().internal_has_property(key))); } // 28.1.9 Reflect.isExtensible ( target ), https://tc39.es/ecma262/#sec-reflect.isextensible diff --git a/Userland/Libraries/LibJS/Runtime/TypedArray.h b/Userland/Libraries/LibJS/Runtime/TypedArray.h index f9be919cd20f..e86b59048b18 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArray.h +++ b/Userland/Libraries/LibJS/Runtime/TypedArray.h @@ -228,7 +228,7 @@ class TypedArray : public TypedArrayBase { } // 10.4.5.2 [[HasProperty]] ( P ), https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-hasproperty-p - virtual bool internal_has_property(PropertyName const& property_name) const override + virtual ThrowCompletionOr<bool> internal_has_property(PropertyName const& property_name) const override { // 1. Assert: IsPropertyKey(P) is true. VERIFY(property_name.is_valid()); diff --git a/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp b/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp index d00c808204f5..9707b9358701 100644 --- a/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp +++ b/Userland/Libraries/LibWeb/Bindings/CSSStyleDeclarationWrapperCustom.cpp @@ -4,12 +4,13 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include <LibJS/Runtime/Completion.h> #include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h> #include <LibWeb/DOM/Element.h> namespace Web::Bindings { -bool CSSStyleDeclarationWrapper::internal_has_property(JS::PropertyName const& name) const +JS::ThrowCompletionOr<bool> CSSStyleDeclarationWrapper::internal_has_property(JS::PropertyName const& name) const { if (!name.is_string()) return Base::internal_has_property(name); diff --git a/Userland/Services/WebContent/ConsoleGlobalObject.cpp b/Userland/Services/WebContent/ConsoleGlobalObject.cpp index 59427ecaf27b..66f26b921dcb 100644 --- a/Userland/Services/WebContent/ConsoleGlobalObject.cpp +++ b/Userland/Services/WebContent/ConsoleGlobalObject.cpp @@ -70,9 +70,9 @@ JS::ThrowCompletionOr<bool> ConsoleGlobalObject::internal_define_own_property(JS return m_window_object->internal_define_own_property(property_name, descriptor); } -bool ConsoleGlobalObject::internal_has_property(JS::PropertyName const& property_name) const +JS::ThrowCompletionOr<bool> ConsoleGlobalObject::internal_has_property(JS::PropertyName const& property_name) const { - return Object::internal_has_property(property_name) || m_window_object->internal_has_property(property_name); + return TRY(Object::internal_has_property(property_name)) || TRY(m_window_object->internal_has_property(property_name)); } JS::Value ConsoleGlobalObject::internal_get(JS::PropertyName const& property_name, JS::Value receiver) const diff --git a/Userland/Services/WebContent/ConsoleGlobalObject.h b/Userland/Services/WebContent/ConsoleGlobalObject.h index ab03375236dd..1ff4832ff854 100644 --- a/Userland/Services/WebContent/ConsoleGlobalObject.h +++ b/Userland/Services/WebContent/ConsoleGlobalObject.h @@ -29,7 +29,7 @@ class ConsoleGlobalObject final : public JS::GlobalObject { virtual JS::ThrowCompletionOr<bool> internal_prevent_extensions() override; virtual JS::ThrowCompletionOr<Optional<JS::PropertyDescriptor>> internal_get_own_property(JS::PropertyName const& name) const override; virtual JS::ThrowCompletionOr<bool> internal_define_own_property(JS::PropertyName const& name, JS::PropertyDescriptor const& descriptor) override; - virtual bool internal_has_property(JS::PropertyName const& name) const override; + virtual JS::ThrowCompletionOr<bool> internal_has_property(JS::PropertyName const& name) const override; virtual JS::Value internal_get(JS::PropertyName const&, JS::Value) const override; virtual bool internal_set(JS::PropertyName const&, JS::Value value, JS::Value receiver) override; virtual bool internal_delete(JS::PropertyName const& name) override;
4a2b718ba2f857a1ca43e58cc0c68dad7b88e9ae
2021-11-08 05:05:27
Andreas Kling
libcore: Use ErrorOr<T> for Core::File::copy_file()
false
Use ErrorOr<T> for Core::File::copy_file()
libcore
diff --git a/Userland/Applications/FileManager/main.cpp b/Userland/Applications/FileManager/main.cpp index 7f3a91628a15..1e7f1e98b7c3 100644 --- a/Userland/Applications/FileManager/main.cpp +++ b/Userland/Applications/FileManager/main.cpp @@ -1169,7 +1169,7 @@ int run_in_windowed_mode(String initial_location, String entry_focused_on_init) continue; if (auto result = Core::File::copy_file_or_directory(url_to_copy.path(), new_path); result.is_error()) { - auto error_message = String::formatted("Could not copy {} into {}:\n {}", url_to_copy.to_string(), new_path, result.error().error_code); + auto error_message = String::formatted("Could not copy {} into {}:\n {}", url_to_copy.to_string(), new_path, static_cast<Error const&>(result.error())); GUI::MessageBox::show(window, error_message, "File Manager", GUI::MessageBox::Type::Error); } else { had_accepted_copy = true; diff --git a/Userland/Applications/Spreadsheet/ExportDialog.cpp b/Userland/Applications/Spreadsheet/ExportDialog.cpp index 52321f7e1ca2..62a82f53be28 100644 --- a/Userland/Applications/Spreadsheet/ExportDialog.cpp +++ b/Userland/Applications/Spreadsheet/ExportDialog.cpp @@ -231,7 +231,7 @@ Result<void, String> CSVExportDialogPage::move_into(const String& target) Core::File::AddDuplicateFileMarker::No); if (result.is_error()) - return String { result.error().error_code.string() }; + return String::formatted("{}", static_cast<Error const&>(result.error())); return {}; } diff --git a/Userland/DevTools/HackStudio/ProjectTemplate.cpp b/Userland/DevTools/HackStudio/ProjectTemplate.cpp index 5dcf75336ccf..34a25236241d 100644 --- a/Userland/DevTools/HackStudio/ProjectTemplate.cpp +++ b/Userland/DevTools/HackStudio/ProjectTemplate.cpp @@ -72,7 +72,7 @@ Result<void, String> ProjectTemplate::create_project(const String& name, const S auto result = Core::File::copy_file_or_directory(path, content_path()); dbgln("Copying {} -> {}", content_path(), path); if (result.is_error()) - return String::formatted("Failed to copy template contents. Error code: {}", result.error().error_code); + return String::formatted("Failed to copy template contents. Error code: {}", static_cast<Error const&>(result.error())); } else { dbgln("No template content directory found for '{}', creating an empty directory for the project.", m_id); int rc; diff --git a/Userland/Libraries/LibCore/File.cpp b/Userland/Libraries/LibCore/File.cpp index 7a9803b58f26..64993d68fbef 100644 --- a/Userland/Libraries/LibCore/File.cpp +++ b/Userland/Libraries/LibCore/File.cpp @@ -347,7 +347,7 @@ static String get_duplicate_name(String const& path, int duplicate_count) return duplicated_name.build(); } -Result<void, File::CopyError> File::copy_file_or_directory(String const& dst_path, String const& src_path, RecursionMode recursion_mode, LinkMode link_mode, AddDuplicateFileMarker add_duplicate_file_marker, PreserveMode preserve_mode) +ErrorOr<void, File::CopyError> File::copy_file_or_directory(String const& dst_path, String const& src_path, RecursionMode recursion_mode, LinkMode link_mode, AddDuplicateFileMarker add_duplicate_file_marker, PreserveMode preserve_mode) { if (add_duplicate_file_marker == AddDuplicateFileMarker::Yes) { int duplicate_count = 0; @@ -361,23 +361,23 @@ Result<void, File::CopyError> File::copy_file_or_directory(String const& dst_pat auto source_or_error = File::open(src_path, OpenMode::ReadOnly); if (source_or_error.is_error()) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; auto& source = *source_or_error.value(); struct stat src_stat; if (fstat(source.fd(), &src_stat) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; if (source.is_directory()) { if (recursion_mode == RecursionMode::Disallowed) - return CopyError { OSError(errno), true }; + return CopyError { errno, true }; return copy_directory(dst_path, src_path, src_stat); } if (link_mode == LinkMode::Allowed) { if (link(src_path.characters(), dst_path.characters()) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; return {}; } @@ -385,31 +385,31 @@ Result<void, File::CopyError> File::copy_file_or_directory(String const& dst_pat return copy_file(dst_path, src_stat, source, preserve_mode); } -Result<void, File::CopyError> File::copy_file(String const& dst_path, struct stat const& src_stat, File& source, PreserveMode preserve_mode) +ErrorOr<void, File::CopyError> File::copy_file(String const& dst_path, struct stat const& src_stat, File& source, PreserveMode preserve_mode) { int dst_fd = creat(dst_path.characters(), 0666); if (dst_fd < 0) { if (errno != EISDIR) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; auto dst_dir_path = String::formatted("{}/{}", dst_path, LexicalPath::basename(source.filename())); dst_fd = creat(dst_dir_path.characters(), 0666); if (dst_fd < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; } ScopeGuard close_fd_guard([dst_fd]() { ::close(dst_fd); }); if (src_stat.st_size > 0) { if (ftruncate(dst_fd, src_stat.st_size) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; } for (;;) { char buffer[32768]; ssize_t nread = ::read(source.fd(), buffer, sizeof(buffer)); if (nread < 0) { - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; } if (nread == 0) break; @@ -418,7 +418,7 @@ Result<void, File::CopyError> File::copy_file(String const& dst_path, struct sta while (remaining_to_write) { ssize_t nwritten = ::write(dst_fd, bufptr, remaining_to_write); if (nwritten < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; VERIFY(nwritten > 0); remaining_to_write -= nwritten; @@ -433,27 +433,27 @@ Result<void, File::CopyError> File::copy_file(String const& dst_path, struct sta my_umask |= 06000; if (fchmod(dst_fd, src_stat.st_mode & ~my_umask) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; if (preserve_mode == PreserveMode::PermissionsOwnershipTimestamps) { if (fchown(dst_fd, src_stat.st_uid, src_stat.st_gid) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; // FIXME: Implement utimens() and use it here. struct utimbuf timbuf; timbuf.actime = src_stat.st_atime; timbuf.modtime = src_stat.st_mtime; if (utime(dst_path.characters(), &timbuf) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; } return {}; } -Result<void, File::CopyError> File::copy_directory(String const& dst_path, String const& src_path, struct stat const& src_stat, LinkMode link, PreserveMode preserve_mode) +ErrorOr<void, File::CopyError> File::copy_directory(String const& dst_path, String const& src_path, struct stat const& src_stat, LinkMode link, PreserveMode preserve_mode) { if (mkdir(dst_path.characters(), 0755) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; String src_rp = File::real_path_for(src_path); src_rp = String::formatted("{}/", src_rp); @@ -461,11 +461,11 @@ Result<void, File::CopyError> File::copy_directory(String const& dst_path, Strin dst_rp = String::formatted("{}/", dst_rp); if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp)) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; DirIterator di(src_path, DirIterator::SkipDots); if (di.has_error()) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; while (di.has_next()) { String filename = di.next_path(); @@ -481,18 +481,18 @@ Result<void, File::CopyError> File::copy_directory(String const& dst_path, Strin umask(my_umask); if (chmod(dst_path.characters(), src_stat.st_mode & ~my_umask) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; if (preserve_mode == PreserveMode::PermissionsOwnershipTimestamps) { if (chown(dst_path.characters(), src_stat.st_uid, src_stat.st_gid) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; // FIXME: Implement utimens() and use it here. struct utimbuf timbuf; timbuf.actime = src_stat.st_atime; timbuf.modtime = src_stat.st_atime; if (utime(dst_path.characters(), &timbuf) < 0) - return CopyError { OSError(errno), false }; + return CopyError { errno, false }; } return {}; diff --git a/Userland/Libraries/LibCore/File.h b/Userland/Libraries/LibCore/File.h index 87603881d01a..b36668785e77 100644 --- a/Userland/Libraries/LibCore/File.h +++ b/Userland/Libraries/LibCore/File.h @@ -6,6 +6,7 @@ #pragma once +#include <AK/Error.h> #include <AK/OSError.h> #include <AK/Result.h> #include <AK/String.h> @@ -59,14 +60,18 @@ class File final : public IODevice { PermissionsOwnershipTimestamps, }; - struct CopyError { - OSError error_code; + struct CopyError : public Error { + CopyError(int error_code, bool t) + : Error(error_code) + , tried_recursing(t) + { + } bool tried_recursing; }; - static Result<void, CopyError> copy_file(String const& dst_path, struct stat const& src_stat, File& source, PreserveMode = PreserveMode::Nothing); - static Result<void, CopyError> copy_directory(String const& dst_path, String const& src_path, struct stat const& src_stat, LinkMode = LinkMode::Disallowed, PreserveMode = PreserveMode::Nothing); - static Result<void, CopyError> copy_file_or_directory(String const& dst_path, String const& src_path, RecursionMode = RecursionMode::Allowed, LinkMode = LinkMode::Disallowed, AddDuplicateFileMarker = AddDuplicateFileMarker::Yes, PreserveMode = PreserveMode::Nothing); + static ErrorOr<void, CopyError> copy_file(String const& dst_path, struct stat const& src_stat, File& source, PreserveMode = PreserveMode::Nothing); + static ErrorOr<void, CopyError> copy_directory(String const& dst_path, String const& src_path, struct stat const& src_stat, LinkMode = LinkMode::Disallowed, PreserveMode = PreserveMode::Nothing); + static ErrorOr<void, CopyError> copy_file_or_directory(String const& dst_path, String const& src_path, RecursionMode = RecursionMode::Allowed, LinkMode = LinkMode::Disallowed, AddDuplicateFileMarker = AddDuplicateFileMarker::Yes, PreserveMode = PreserveMode::Nothing); static String real_path_for(String const& filename); static String read_link(String const& link_path); diff --git a/Userland/Utilities/cp.cpp b/Userland/Utilities/cp.cpp index b27b033476b3..b5b1cfa66805 100644 --- a/Userland/Utilities/cp.cpp +++ b/Userland/Utilities/cp.cpp @@ -61,7 +61,7 @@ int main(int argc, char** argv) if (result.error().tried_recursing) warnln("cp: -R not specified; omitting directory '{}'", source); else - warnln("cp: unable to copy '{}' to '{}': {}", source, destination_path, result.error().error_code); + warnln("cp: unable to copy '{}' to '{}': {}", source, destination_path, static_cast<Error const&>(result.error())); return 1; } diff --git a/Userland/Utilities/mv.cpp b/Userland/Utilities/mv.cpp index 1e917f69b72c..29f607d2be5d 100644 --- a/Userland/Utilities/mv.cpp +++ b/Userland/Utilities/mv.cpp @@ -74,7 +74,7 @@ int main(int argc, char** argv) Core::File::AddDuplicateFileMarker::No); if (result.is_error()) { - warnln("mv: could not move '{}': {}", old_path, result.error().error_code); + warnln("mv: could not move '{}': {}", old_path, static_cast<Error const&>(result.error())); return 1; } rc = unlink(old_path); diff --git a/Userland/Utilities/usermod.cpp b/Userland/Utilities/usermod.cpp index 7b7065951727..53e425b893e1 100644 --- a/Userland/Utilities/usermod.cpp +++ b/Userland/Utilities/usermod.cpp @@ -125,7 +125,7 @@ int main(int argc, char** argv) Core::File::AddDuplicateFileMarker::No); if (result.is_error()) { - warnln("usermod: could not move directory {} : {}", target_account.home_directory().characters(), result.error().error_code); + warnln("usermod: could not move directory {} : {}", target_account.home_directory().characters(), static_cast<Error const&>(result.error())); return 1; } rc = unlink(target_account.home_directory().characters());
f3070118b1fabda4a35f283a3bcf8086e32a25a9
2024-06-25 22:52:35
Andreas Kling
libweb: Add "allow declarative shadow roots" flag to Document
false
Add "allow declarative shadow roots" flag to Document
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 0848ba215ad8..bb5408dba608 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -288,7 +288,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Document>> Document::create_and_initialize( // URL: creationURL // current document readiness: "loading" // about base URL: navigationParams's about base URL - // FIXME: allow declarative shadow roots: true + // allow declarative shadow roots: true auto document = HTML::HTMLDocument::create(window->realm()); document->m_type = type; document->m_content_type = move(content_type); @@ -300,6 +300,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Document>> Document::create_and_initialize( document->set_url(*creation_url); document->m_readiness = HTML::DocumentReadyState::Loading; document->m_about_base_url = navigation_params.about_base_url; + document->set_allow_declarative_shadow_roots(true); document->m_window = window; @@ -5209,4 +5210,16 @@ Vector<JS::Handle<DOM::Range>> Document::find_matching_text(String const& query, return matches; } +// https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots +bool Document::allow_declarative_shadow_roots() const +{ + return m_allow_declarative_shadow_roots; +} + +// https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots +void Document::set_allow_declarative_shadow_roots(bool allow) +{ + m_allow_declarative_shadow_roots = allow; +} + } diff --git a/Userland/Libraries/LibWeb/DOM/Document.h b/Userland/Libraries/LibWeb/DOM/Document.h index a81bd639e726..67b3b8f03453 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.h +++ b/Userland/Libraries/LibWeb/DOM/Document.h @@ -400,6 +400,9 @@ class Document bool is_fully_active() const; bool is_active() const; + [[nodiscard]] bool allow_declarative_shadow_roots() const; + void set_allow_declarative_shadow_roots(bool); + JS::NonnullGCPtr<HTML::History> history(); JS::NonnullGCPtr<HTML::History> history() const; @@ -929,6 +932,9 @@ class Document // instead they generate boxes as if they were siblings of the root element. OrderedHashTable<JS::NonnullGCPtr<Element>> m_top_layer_elements; OrderedHashTable<JS::NonnullGCPtr<Element>> m_top_layer_pending_removals; + + // https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots + bool m_allow_declarative_shadow_roots { false }; }; template<> diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp index adf52dc91992..722f6890bd23 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp @@ -246,6 +246,9 @@ WebIDL::ExceptionOr<BrowsingContext::BrowsingContextAndDocument> BrowsingContext // about base URL: creatorBaseURL document->set_about_base_url(creator_base_url); + // allow declarative shadow roots: true + document->set_allow_declarative_shadow_roots(true); + // 16. If creator is non-null, then: if (creator) { // 1. Set document's referrer to the serialization of creator's URL.
71840c1bf41c972a75a4155dc0440d9a5ca0a263
2021-07-11 17:41:53
Gunnar Beutner
texteditor: Open files with ReadOnly when we're just reading them
false
Open files with ReadOnly when we're just reading them
texteditor
diff --git a/Userland/Applications/TextEditor/MainWidget.cpp b/Userland/Applications/TextEditor/MainWidget.cpp index ab490a1185fc..8ed368b6ec8a 100644 --- a/Userland/Applications/TextEditor/MainWidget.cpp +++ b/Userland/Applications/TextEditor/MainWidget.cpp @@ -260,7 +260,7 @@ MainWidget::MainWidget() }); m_open_action = GUI::CommonActions::make_open_action([this](auto&) { - auto fd_response = m_file_system_access_client->prompt_open_file(Core::StandardPaths::home_directory(), Core::OpenMode::ReadWrite); + auto fd_response = m_file_system_access_client->prompt_open_file(Core::StandardPaths::home_directory(), Core::OpenMode::ReadOnly); if (fd_response.error() != 0) { if (fd_response.error() != -1) diff --git a/Userland/Applications/TextEditor/main.cpp b/Userland/Applications/TextEditor/main.cpp index e0d31805c9ed..9ac38cbffe9b 100644 --- a/Userland/Applications/TextEditor/main.cpp +++ b/Userland/Applications/TextEditor/main.cpp @@ -107,7 +107,7 @@ int main(int argc, char** argv) if (file_to_edit) { // A file name was passed, parse any possible line and column numbers included. FileArgument parsed_argument(file_to_edit); - auto file = Core::File::open(file_to_edit_full_path, Core::OpenMode::ReadWrite); + auto file = Core::File::open(file_to_edit_full_path, Core::OpenMode::ReadOnly); if (file.is_error()) return 1;
15498453897bbb3496793e26ddf11d2a00ba6b72
2021-08-15 15:06:36
Linus Groh
libjs: Implement Temporal.PlainMonthDay.prototype.getISOFields()
false
Implement Temporal.PlainMonthDay.prototype.getISOFields()
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.cpp index 8df4dd72f0bf..a5edb3ec6068 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.cpp @@ -33,6 +33,7 @@ void PlainMonthDayPrototype::initialize(GlobalObject& global_object) u8 attr = Attribute::Writable | Attribute::Configurable; define_native_function(vm.names.valueOf, value_of, 0, attr); + define_native_function(vm.names.getISOFields, get_iso_fields, 0, attr); } static PlainMonthDay* typed_this(GlobalObject& global_object) @@ -101,4 +102,32 @@ JS_DEFINE_NATIVE_FUNCTION(PlainMonthDayPrototype::value_of) return {}; } +// 10.3.13 Temporal.PlainMonthDay.prototype.getISOFields ( ), https://tc39.es/proposal-temporal/#sec-temporal.plainmonthday.prototype.getisofields +JS_DEFINE_NATIVE_FUNCTION(PlainMonthDayPrototype::get_iso_fields) +{ + // 1. Let monthDay be the this value. + // 2. Perform ? RequireInternalSlot(monthDay, [[InitializedTemporalMonthDay]]). + auto* month_day = typed_this(global_object); + if (vm.exception()) + return {}; + + // 3. Let fields be ! OrdinaryObjectCreate(%Object.prototype%). + auto* fields = Object::create(global_object, global_object.object_prototype()); + + // 4. Perform ! CreateDataPropertyOrThrow(fields, "calendar", monthDay.[[Calendar]]). + fields->create_data_property_or_throw(vm.names.calendar, Value(&month_day->calendar())); + + // 5. Perform ! CreateDataPropertyOrThrow(fields, "isoDay", 𝔽(monthDay.[[ISODay]])). + fields->create_data_property_or_throw(vm.names.isoDay, Value(month_day->iso_day())); + + // 6. Perform ! CreateDataPropertyOrThrow(fields, "isoMonth", 𝔽(monthDay.[[ISOMonth]])). + fields->create_data_property_or_throw(vm.names.isoMonth, Value(month_day->iso_month())); + + // 7. Perform ! CreateDataPropertyOrThrow(fields, "isoYear", 𝔽(monthDay.[[ISOYear]])). + fields->create_data_property_or_throw(vm.names.isoYear, Value(month_day->iso_year())); + + // 8. Return fields. + return fields; +} + } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.h index 1a3d09f13e6c..d20c1ea6b210 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayPrototype.h @@ -23,6 +23,7 @@ class PlainMonthDayPrototype final : public Object { JS_DECLARE_NATIVE_FUNCTION(month_code_getter); JS_DECLARE_NATIVE_FUNCTION(day_getter); JS_DECLARE_NATIVE_FUNCTION(value_of); + JS_DECLARE_NATIVE_FUNCTION(get_iso_fields); }; } diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/PlainMonthDay/PlainMonthDay.prototype.getISOFields.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/PlainMonthDay/PlainMonthDay.prototype.getISOFields.js new file mode 100644 index 000000000000..29feff968f36 --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/PlainMonthDay/PlainMonthDay.prototype.getISOFields.js @@ -0,0 +1,27 @@ +describe("normal behavior", () => { + test("length is 0", () => { + expect(Temporal.PlainMonthDay.prototype.getISOFields).toHaveLength(0); + }); + + test("basic functionality", () => { + const calendar = new Temporal.Calendar("iso8601"); + const plainMonthDay = new Temporal.PlainMonthDay(7, 6, calendar, 2021); + const fields = plainMonthDay.getISOFields(); + expect(fields).toEqual({ calendar, isoDay: 6, isoMonth: 7, isoYear: 2021 }); + // Test field order + expect(Object.getOwnPropertyNames(fields)).toEqual([ + "calendar", + "isoDay", + "isoMonth", + "isoYear", + ]); + }); +}); + +describe("errors", () => { + test("this value must be a Temporal.PlainMonthDay object", () => { + expect(() => { + Temporal.PlainMonthDay.prototype.getISOFields.call("foo"); + }).toThrowWithMessage(TypeError, "Not a Temporal.PlainMonthDay"); + }); +});
cb6e75e89012a0c6b19c39243c46fc912d50751d
2024-02-08 19:35:13
Dan Klishch
jsspeccompiler: Mostly get rid of ParseError in AlgorithmStep
false
Mostly get rid of ParseError in AlgorithmStep
jsspeccompiler
diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.cpp b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.cpp index cc37ebbbc6a8..0c3e57b67e9d 100644 --- a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.cpp @@ -33,6 +33,18 @@ LogicalLocation& SpecificationParsingContext::current_logical_scope() return *m_current_logical_scope; } +template<typename Func> +auto SpecificationParsingContext::with_new_step_list_nesting_level(Func&& func) +{ + TemporaryChange change(m_step_list_nesting_level, m_step_list_nesting_level + 1); + return func(); +} + +int SpecificationParsingContext::step_list_nesting_level() const +{ + return m_step_list_nesting_level; +} + Location SpecificationParsingContext::file_scope() const { return { .filename = m_translation_unit->filename() }; @@ -48,20 +60,38 @@ Location SpecificationParsingContext::location_from_xml_offset(XML::Offset offse }; } -ParseErrorOr<AlgorithmStep> AlgorithmStep::create(SpecificationParsingContext& ctx, XML::Node const* node) +Optional<AlgorithmStep> AlgorithmStep::create(SpecificationParsingContext& ctx, XML::Node const* element) { - VERIFY(node->as_element().name == tag_li); + VERIFY(element->as_element().name == tag_li); + + auto tokenization_result = tokenize_tree(element, true); + if (tokenization_result.is_error()) { + ctx.diag().error(ctx.location_from_xml_offset(tokenization_result.error()->offset()), + "{}", tokenization_result.error()->to_string()); + return {}; + } - auto [tokens, substeps] = TRY(tokenize_tree(node, true)); - AlgorithmStep result { .m_tokens = move(tokens), .m_node = node }; + auto [tokens, substeps] = tokenization_result.release_value(); + AlgorithmStep result { .m_tokens = move(tokens), .m_node = element }; if (substeps) { - auto step_list = AlgorithmStepList::create(ctx, substeps); + // FIXME: Remove this once macOS Lagom CI updates to Clang >= 16. + auto substeps_copy = substeps; + + auto step_list = ctx.with_new_step_list_nesting_level([&] { + return AlgorithmStepList::create(ctx, substeps_copy); + }); if (step_list.has_value()) result.m_substeps = step_list->m_expression; } - result.m_expression = TRY(result.parse()); + auto parse_result = result.parse(); + if (parse_result.is_error()) { + ctx.diag().error(ctx.location_from_xml_offset(parse_result.error()->offset()), + "{}", parse_result.error()->to_string()); + return {}; + } + result.m_expression = parse_result.release_value(); return result; } @@ -84,21 +114,25 @@ Optional<AlgorithmStepList> AlgorithmStepList::create(SpecificationParsingContex Vector<Tree> step_expressions; bool all_steps_parsed = true; + int step_number = 0; + + auto const& parent_scope = ctx.current_logical_scope(); for (auto const& child : element->as_element().children) { child->content.visit( [&](XML::Node::Element const& element) { if (element.name == tag_li) { - auto step_creation_result = AlgorithmStep::create(ctx, child); - if (step_creation_result.is_error()) { - // TODO: Integrate backtracing parser errors better - ctx.diag().error(ctx.location_from_xml_offset(step_creation_result.error()->offset()), - "{}", step_creation_result.error()->to_string()); + auto step_creation_result = ctx.with_new_logical_scope([&] { + update_logical_scope_for_step(ctx, parent_scope, step_number); + return AlgorithmStep::create(ctx, child); + }); + if (!step_creation_result.has_value()) { all_steps_parsed = false; } else { steps.append(step_creation_result.release_value()); step_expressions.append(steps.last().m_expression); } + ++step_number; return; } @@ -121,6 +155,31 @@ Optional<AlgorithmStepList> AlgorithmStepList::create(SpecificationParsingContex return result; } +void AlgorithmStepList::update_logical_scope_for_step(SpecificationParsingContext& ctx, LogicalLocation const& parent_scope, int step_number) +{ + int nesting_level = ctx.step_list_nesting_level(); + String list_step_number; + + if (nesting_level == 0 || nesting_level == 3) { + list_step_number = MUST(String::formatted("{}", step_number + 1)); + } else if (nesting_level == 1 || nesting_level == 4) { + if (step_number < 26) + list_step_number = String::from_code_point('a' + step_number); + else + list_step_number = MUST(String::formatted("{}", step_number + 1)); + } else { + list_step_number = MUST(String::from_byte_string(ByteString::roman_number_from(step_number + 1).to_lowercase())); + } + + auto& scope = ctx.current_logical_scope(); + scope.section = parent_scope.section; + + if (parent_scope.step.is_empty()) + scope.step = list_step_number; + else + scope.step = MUST(String::formatted("{}.{}", parent_scope.step, list_step_number)); +} + Optional<Algorithm> Algorithm::create(SpecificationParsingContext& ctx, XML::Node const* element) { VERIFY(element->as_element().name == tag_emu_alg); diff --git a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.h b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.h index a3fb5b70a2a0..2a4629b20c9e 100644 --- a/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.h +++ b/Meta/Lagom/Tools/CodeGenerators/JSSpecCompiler/Parser/SpecParser.h @@ -33,12 +33,17 @@ class SpecificationParsingContext { auto with_new_logical_scope(Func&& func); LogicalLocation& current_logical_scope(); + template<typename Func> + auto with_new_step_list_nesting_level(Func&& func); + int step_list_nesting_level() const; + Location file_scope() const; Location location_from_xml_offset(XML::Offset offset) const; private: TranslationUnitRef m_translation_unit; RefPtr<LogicalLocation> m_current_logical_scope; + int m_step_list_nesting_level = 0; }; class AlgorithmStepList { @@ -47,11 +52,14 @@ class AlgorithmStepList { Vector<AlgorithmStep> m_steps; Tree m_expression = error_tree; + +private: + static void update_logical_scope_for_step(SpecificationParsingContext& ctx, LogicalLocation const& parent_scope, int step_number); }; class AlgorithmStep { public: - static ParseErrorOr<AlgorithmStep> create(SpecificationParsingContext& ctx, XML::Node const* node); + static Optional<AlgorithmStep> create(SpecificationParsingContext& ctx, XML::Node const* node); ParseErrorOr<Tree> parse();
21bfa02dd283e3c8199519901d128a7f2340a172
2021-10-22 04:49:04
Andreas Kling
kernel: Remove unused InodeIdentifier::to_string()
false
Remove unused InodeIdentifier::to_string()
kernel
diff --git a/Kernel/FileSystem/InodeIdentifier.h b/Kernel/FileSystem/InodeIdentifier.h index 080d2f274644..8cee21a3fbf6 100644 --- a/Kernel/FileSystem/InodeIdentifier.h +++ b/Kernel/FileSystem/InodeIdentifier.h @@ -8,7 +8,6 @@ #include <AK/ByteBuffer.h> #include <AK/DistinctNumeric.h> -#include <AK/String.h> #include <AK/Types.h> namespace Kernel { @@ -45,8 +44,6 @@ class InodeIdentifier { return m_fsid != other.m_fsid || m_index != other.m_index; } - String to_string() const { return String::formatted("{}:{}", m_fsid, m_index); } - private: u32 m_fsid { 0 }; InodeIndex m_index { 0 };
6c87d3afa95121cdecb41552b9571253b3dca31b
2019-07-09 18:34:45
Andreas Kling
kernel: Move i8253.cpp => Arch/i386/PIT.cpp
false
Move i8253.cpp => Arch/i386/PIT.cpp
kernel
diff --git a/Kernel/i8253.cpp b/Kernel/Arch/i386/PIT.cpp similarity index 98% rename from Kernel/i8253.cpp rename to Kernel/Arch/i386/PIT.cpp index ab91e192be8a..d1a523da08a2 100644 --- a/Kernel/i8253.cpp +++ b/Kernel/Arch/i386/PIT.cpp @@ -1,6 +1,6 @@ #include <Kernel/Arch/i386/CPU.h> #include <Kernel/Arch/i386/PIC.h> -#include <Kernel/i8253.h> +#include <Kernel/Arch/i386/PIT.h> #include <Kernel/IO.h> #include <Kernel/Scheduler.h> diff --git a/Kernel/i8253.h b/Kernel/Arch/i386/PIT.h similarity index 100% rename from Kernel/i8253.h rename to Kernel/Arch/i386/PIT.h diff --git a/Kernel/Makefile b/Kernel/Makefile index 129c5d71fe0c..cd4c04c6c55c 100644 --- a/Kernel/Makefile +++ b/Kernel/Makefile @@ -7,7 +7,7 @@ KERNEL_OBJS = \ Arch/i386/CPU.o \ Process.o \ Thread.o \ - i8253.o \ + Arch/i386/PIT.o \ Devices/KeyboardDevice.o \ CMOS.o \ Arch/i386/PIC.o \ diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 0d8035cc7db9..d1b89230b697 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -5,6 +5,7 @@ #include <AK/Time.h> #include <AK/Types.h> #include <Kernel/Arch/i386/CPU.h> +#include <Kernel/Arch/i386/PIT.h> #include <Kernel/Devices/NullDevice.h> #include <Kernel/FileSystem/Custody.h> #include <Kernel/FileSystem/FIFO.h> @@ -22,7 +23,6 @@ #include <Kernel/Syscall.h> #include <Kernel/TTY/MasterPTY.h> #include <Kernel/VM/MemoryManager.h> -#include <Kernel/i8253.h> #include <Kernel/kmalloc.h> #include <LibC/errno_numbers.h> #include <LibC/signal_numbers.h> diff --git a/Kernel/Scheduler.cpp b/Kernel/Scheduler.cpp index 8f06e76c559e..59ae380be054 100644 --- a/Kernel/Scheduler.cpp +++ b/Kernel/Scheduler.cpp @@ -1,11 +1,11 @@ #include <AK/TemporaryChange.h> #include <Kernel/Alarm.h> +#include <Kernel/Arch/i386/PIT.h> #include <Kernel/Devices/PCSpeaker.h> #include <Kernel/FileSystem/FileDescription.h> #include <Kernel/Process.h> #include <Kernel/RTC.h> #include <Kernel/Scheduler.h> -#include <Kernel/i8253.h> //#define LOG_EVERY_CONTEXT_SWITCH //#define SCHEDULER_DEBUG diff --git a/Kernel/init.cpp b/Kernel/init.cpp index d0696845ca59..f68aaef4c3ff 100644 --- a/Kernel/init.cpp +++ b/Kernel/init.cpp @@ -2,11 +2,11 @@ #include "Process.h" #include "RTC.h" #include "Scheduler.h" -#include "i8253.h" #include "kmalloc.h" #include <AK/Types.h> #include <Kernel/Arch/i386/CPU.h> #include <Kernel/Arch/i386/PIC.h> +#include <Kernel/Arch/i386/PIT.h> #include <Kernel/Devices/BXVGADevice.h> #include <Kernel/Devices/DebugLogDevice.h> #include <Kernel/Devices/DiskPartition.h>
23ea1f1a3e16b4114e3b5521d51c7e8f19d4e8f9
2021-10-29 23:59:24
Idan Horowitz
libjs: Convert MathObject functions to ThrowCompletionOr
false
Convert MathObject functions to ThrowCompletionOr
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/MathObject.cpp b/Userland/Libraries/LibJS/Runtime/MathObject.cpp index 078e2467a7d8..562cee40df2e 100644 --- a/Userland/Libraries/LibJS/Runtime/MathObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/MathObject.cpp @@ -24,41 +24,41 @@ void MathObject::initialize(GlobalObject& global_object) auto& vm = this->vm(); Object::initialize(global_object); u8 attr = Attribute::Writable | Attribute::Configurable; - define_old_native_function(vm.names.abs, abs, 1, attr); - define_old_native_function(vm.names.random, random, 0, attr); - define_old_native_function(vm.names.sqrt, sqrt, 1, attr); - define_old_native_function(vm.names.floor, floor, 1, attr); - define_old_native_function(vm.names.ceil, ceil, 1, attr); - define_old_native_function(vm.names.round, round, 1, attr); - define_old_native_function(vm.names.max, max, 2, attr); - define_old_native_function(vm.names.min, min, 2, attr); - define_old_native_function(vm.names.trunc, trunc, 1, attr); - define_old_native_function(vm.names.sin, sin, 1, attr); - define_old_native_function(vm.names.cos, cos, 1, attr); - define_old_native_function(vm.names.tan, tan, 1, attr); - define_old_native_function(vm.names.pow, pow, 2, attr); - define_old_native_function(vm.names.exp, exp, 1, attr); - define_old_native_function(vm.names.expm1, expm1, 1, attr); - define_old_native_function(vm.names.sign, sign, 1, attr); - define_old_native_function(vm.names.clz32, clz32, 1, attr); - define_old_native_function(vm.names.acos, acos, 1, attr); - define_old_native_function(vm.names.acosh, acosh, 1, attr); - define_old_native_function(vm.names.asin, asin, 1, attr); - define_old_native_function(vm.names.asinh, asinh, 1, attr); - define_old_native_function(vm.names.atan, atan, 1, attr); - define_old_native_function(vm.names.atanh, atanh, 1, attr); - define_old_native_function(vm.names.log1p, log1p, 1, attr); - define_old_native_function(vm.names.cbrt, cbrt, 1, attr); - define_old_native_function(vm.names.atan2, atan2, 2, attr); - define_old_native_function(vm.names.fround, fround, 1, attr); - define_old_native_function(vm.names.hypot, hypot, 2, attr); - define_old_native_function(vm.names.imul, imul, 2, attr); - define_old_native_function(vm.names.log, log, 1, attr); - define_old_native_function(vm.names.log2, log2, 1, attr); - define_old_native_function(vm.names.log10, log10, 1, attr); - define_old_native_function(vm.names.sinh, sinh, 1, attr); - define_old_native_function(vm.names.cosh, cosh, 1, attr); - define_old_native_function(vm.names.tanh, tanh, 1, attr); + define_native_function(vm.names.abs, abs, 1, attr); + define_native_function(vm.names.random, random, 0, attr); + define_native_function(vm.names.sqrt, sqrt, 1, attr); + define_native_function(vm.names.floor, floor, 1, attr); + define_native_function(vm.names.ceil, ceil, 1, attr); + define_native_function(vm.names.round, round, 1, attr); + define_native_function(vm.names.max, max, 2, attr); + define_native_function(vm.names.min, min, 2, attr); + define_native_function(vm.names.trunc, trunc, 1, attr); + define_native_function(vm.names.sin, sin, 1, attr); + define_native_function(vm.names.cos, cos, 1, attr); + define_native_function(vm.names.tan, tan, 1, attr); + define_native_function(vm.names.pow, pow, 2, attr); + define_native_function(vm.names.exp, exp, 1, attr); + define_native_function(vm.names.expm1, expm1, 1, attr); + define_native_function(vm.names.sign, sign, 1, attr); + define_native_function(vm.names.clz32, clz32, 1, attr); + define_native_function(vm.names.acos, acos, 1, attr); + define_native_function(vm.names.acosh, acosh, 1, attr); + define_native_function(vm.names.asin, asin, 1, attr); + define_native_function(vm.names.asinh, asinh, 1, attr); + define_native_function(vm.names.atan, atan, 1, attr); + define_native_function(vm.names.atanh, atanh, 1, attr); + define_native_function(vm.names.log1p, log1p, 1, attr); + define_native_function(vm.names.cbrt, cbrt, 1, attr); + define_native_function(vm.names.atan2, atan2, 2, attr); + define_native_function(vm.names.fround, fround, 1, attr); + define_native_function(vm.names.hypot, hypot, 2, attr); + define_native_function(vm.names.imul, imul, 2, attr); + define_native_function(vm.names.log, log, 1, attr); + define_native_function(vm.names.log2, log2, 1, attr); + define_native_function(vm.names.log10, log10, 1, attr); + define_native_function(vm.names.sinh, sinh, 1, attr); + define_native_function(vm.names.cosh, cosh, 1, attr); + define_native_function(vm.names.tanh, tanh, 1, attr); // 21.3.1 Value Properties of the Math Object, https://tc39.es/ecma262/#sec-value-properties-of-the-math-object define_direct_property(vm.names.E, Value(M_E), 0); @@ -79,9 +79,9 @@ MathObject::~MathObject() } // 21.3.2.1 Math.abs ( x ), https://tc39.es/ecma262/#sec-math.abs -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::abs) +JS_DEFINE_NATIVE_FUNCTION(MathObject::abs) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); if (number.is_negative_zero()) @@ -92,34 +92,34 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::abs) } // 21.3.2.27 Math.random ( ), https://tc39.es/ecma262/#sec-math.random -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::random) +JS_DEFINE_NATIVE_FUNCTION(MathObject::random) { double r = (double)get_random<u32>() / (double)UINT32_MAX; return Value(r); } // 21.3.2.32 Math.sqrt ( x ), https://tc39.es/ecma262/#sec-math.sqrt -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::sqrt) +JS_DEFINE_NATIVE_FUNCTION(MathObject::sqrt) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::sqrt(number.as_double())); } // 21.3.2.16 Math.floor ( x ), https://tc39.es/ecma262/#sec-math.floor -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::floor) +JS_DEFINE_NATIVE_FUNCTION(MathObject::floor) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::floor(number.as_double())); } // 21.3.2.10 Math.ceil ( x ), https://tc39.es/ecma262/#sec-math.ceil -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::ceil) +JS_DEFINE_NATIVE_FUNCTION(MathObject::ceil) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); auto number_double = number.as_double(); @@ -129,9 +129,9 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::ceil) } // 21.3.2.28 Math.round ( x ), https://tc39.es/ecma262/#sec-math.round -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::round) +JS_DEFINE_NATIVE_FUNCTION(MathObject::round) { - auto value = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double(); + auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); double integer = ::ceil(value); if (integer - 0.5 > value) integer--; @@ -139,11 +139,11 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::round) } // 21.3.2.24 Math.max ( ...args ), https://tc39.es/ecma262/#sec-math.max -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::max) +JS_DEFINE_NATIVE_FUNCTION(MathObject::max) { Vector<Value> coerced; for (size_t i = 0; i < vm.argument_count(); ++i) - coerced.append(TRY_OR_DISCARD(vm.argument(i).to_number(global_object))); + coerced.append(TRY(vm.argument(i).to_number(global_object))); auto highest = js_negative_infinity(); for (auto& number : coerced) { @@ -156,11 +156,11 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::max) } // 21.3.2.25 Math.min ( ...args ), https://tc39.es/ecma262/#sec-math.min -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::min) +JS_DEFINE_NATIVE_FUNCTION(MathObject::min) { Vector<Value> coerced; for (size_t i = 0; i < vm.argument_count(); ++i) - coerced.append(TRY_OR_DISCARD(vm.argument(i).to_number(global_object))); + coerced.append(TRY(vm.argument(i).to_number(global_object))); auto lowest = js_infinity(); for (auto& number : coerced) { @@ -173,9 +173,9 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::min) } // 21.3.2.35 Math.trunc ( x ), https://tc39.es/ecma262/#sec-math.trunc -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::trunc) +JS_DEFINE_NATIVE_FUNCTION(MathObject::trunc) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); if (number.as_double() < 0) @@ -184,37 +184,37 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::trunc) } // 21.3.2.30 Math.sin ( x ), https://tc39.es/ecma262/#sec-math.sin -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::sin) +JS_DEFINE_NATIVE_FUNCTION(MathObject::sin) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::sin(number.as_double())); } // 21.3.2.12 Math.cos ( x ), https://tc39.es/ecma262/#sec-math.cos -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::cos) +JS_DEFINE_NATIVE_FUNCTION(MathObject::cos) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::cos(number.as_double())); } // 21.3.2.33 Math.tan ( x ), https://tc39.es/ecma262/#sec-math.tan -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::tan) +JS_DEFINE_NATIVE_FUNCTION(MathObject::tan) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::tan(number.as_double())); } // 21.3.2.26 Math.pow ( base, exponent ), https://tc39.es/ecma262/#sec-math.pow -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::pow) +JS_DEFINE_NATIVE_FUNCTION(MathObject::pow) { - auto base = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); - auto exponent = TRY_OR_DISCARD(vm.argument(1).to_number(global_object)); + auto base = TRY(vm.argument(0).to_number(global_object)); + auto exponent = TRY(vm.argument(1).to_number(global_object)); if (exponent.is_nan()) return js_nan(); if (exponent.is_positive_zero() || exponent.is_negative_zero()) @@ -265,27 +265,27 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::pow) } // 21.3.2.14 Math.exp ( x ), https://tc39.es/ecma262/#sec-math.exp -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::exp) +JS_DEFINE_NATIVE_FUNCTION(MathObject::exp) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::exp(number.as_double())); } // 21.3.2.15 Math.expm1 ( x ), https://tc39.es/ecma262/#sec-math.expm1 -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::expm1) +JS_DEFINE_NATIVE_FUNCTION(MathObject::expm1) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::expm1(number.as_double())); } // 21.3.2.29 Math.sign ( x ), https://tc39.es/ecma262/#sec-math.sign -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::sign) +JS_DEFINE_NATIVE_FUNCTION(MathObject::sign) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_positive_zero()) return Value(0); if (number.is_negative_zero()) @@ -298,18 +298,18 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::sign) } // 21.3.2.11 Math.clz32 ( x ), https://tc39.es/ecma262/#sec-math.clz32 -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::clz32) +JS_DEFINE_NATIVE_FUNCTION(MathObject::clz32) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_u32(global_object)); + auto number = TRY(vm.argument(0).to_u32(global_object)); if (number == 0) return Value(32); return Value(__builtin_clz(number)); } // 21.3.2.2 Math.acos ( x ), https://tc39.es/ecma262/#sec-math.acos -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::acos) +JS_DEFINE_NATIVE_FUNCTION(MathObject::acos) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan() || number.as_double() > 1 || number.as_double() < -1) return js_nan(); if (number.as_double() == 1) @@ -318,33 +318,33 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::acos) } // 21.3.2.3 Math.acosh ( x ), https://tc39.es/ecma262/#sec-math.acosh -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::acosh) +JS_DEFINE_NATIVE_FUNCTION(MathObject::acosh) { - auto value = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double(); + auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); if (value < 1) return js_nan(); return Value(::acosh(value)); } // 21.3.2.4 Math.asin ( x ), https://tc39.es/ecma262/#sec-math.asin -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::asin) +JS_DEFINE_NATIVE_FUNCTION(MathObject::asin) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero()) return number; return Value(::asin(number.as_double())); } // 21.3.2.5 Math.asinh ( x ), https://tc39.es/ecma262/#sec-math.asinh -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::asinh) +JS_DEFINE_NATIVE_FUNCTION(MathObject::asinh) { - return Value(::asinh(TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double())); + return Value(::asinh(TRY(vm.argument(0).to_number(global_object)).as_double())); } // 21.3.2.6 Math.atan ( x ), https://tc39.es/ecma262/#sec-math.atan -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::atan) +JS_DEFINE_NATIVE_FUNCTION(MathObject::atan) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan() || number.is_positive_zero() || number.is_negative_zero()) return number; if (number.is_positive_infinity()) @@ -355,36 +355,36 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::atan) } // 21.3.2.7 Math.atanh ( x ), https://tc39.es/ecma262/#sec-math.atanh -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::atanh) +JS_DEFINE_NATIVE_FUNCTION(MathObject::atanh) { - auto value = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double(); + auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); if (value > 1 || value < -1) return js_nan(); return Value(::atanh(value)); } // 21.3.2.21 Math.log1p ( x ), https://tc39.es/ecma262/#sec-math.log1p -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::log1p) +JS_DEFINE_NATIVE_FUNCTION(MathObject::log1p) { - auto value = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double(); + auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); if (value < -1) return js_nan(); return Value(::log1p(value)); } // 21.3.2.9 Math.cbrt ( x ), https://tc39.es/ecma262/#sec-math.cbrt -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::cbrt) +JS_DEFINE_NATIVE_FUNCTION(MathObject::cbrt) { - return Value(::cbrt(TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double())); + return Value(::cbrt(TRY(vm.argument(0).to_number(global_object)).as_double())); } // 21.3.2.8 Math.atan2 ( y, x ), https://tc39.es/ecma262/#sec-math.atan2 -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::atan2) +JS_DEFINE_NATIVE_FUNCTION(MathObject::atan2) { auto constexpr three_quarters_pi = M_PI_4 + M_PI_2; - auto y = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); - auto x = TRY_OR_DISCARD(vm.argument(1).to_number(global_object)); + auto y = TRY(vm.argument(0).to_number(global_object)); + auto x = TRY(vm.argument(1).to_number(global_object)); if (y.is_nan() || x.is_nan()) return js_nan(); @@ -438,20 +438,20 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::atan2) } // 21.3.2.17 Math.fround ( x ), https://tc39.es/ecma262/#sec-math.fround -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::fround) +JS_DEFINE_NATIVE_FUNCTION(MathObject::fround) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value((float)number.as_double()); } // 21.3.2.18 Math.hypot ( ...args ), https://tc39.es/ecma262/#sec-math.hypot -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::hypot) +JS_DEFINE_NATIVE_FUNCTION(MathObject::hypot) { Vector<Value> coerced; for (size_t i = 0; i < vm.argument_count(); ++i) - coerced.append(TRY_OR_DISCARD(vm.argument(i).to_number(global_object))); + coerced.append(TRY(vm.argument(i).to_number(global_object))); for (auto& number : coerced) { if (number.is_positive_infinity() || number.is_negative_infinity()) @@ -475,62 +475,62 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::hypot) } // 21.3.2.19 Math.imul ( x, y ), https://tc39.es/ecma262/#sec-math.imul -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::imul) +JS_DEFINE_NATIVE_FUNCTION(MathObject::imul) { - auto a = TRY_OR_DISCARD(vm.argument(0).to_u32(global_object)); - auto b = TRY_OR_DISCARD(vm.argument(1).to_u32(global_object)); + auto a = TRY(vm.argument(0).to_u32(global_object)); + auto b = TRY(vm.argument(1).to_u32(global_object)); return Value(static_cast<i32>(a * b)); } // 21.3.2.20 Math.log ( x ), https://tc39.es/ecma262/#sec-math.log -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::log) +JS_DEFINE_NATIVE_FUNCTION(MathObject::log) { - auto value = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double(); + auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); if (value < 0) return js_nan(); return Value(::log(value)); } // 21.3.2.23 Math.log2 ( x ), https://tc39.es/ecma262/#sec-math.log2 -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::log2) +JS_DEFINE_NATIVE_FUNCTION(MathObject::log2) { - auto value = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double(); + auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); if (value < 0) return js_nan(); return Value(::log2(value)); } // 21.3.2.22 Math.log10 ( x ), https://tc39.es/ecma262/#sec-math.log10 -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::log10) +JS_DEFINE_NATIVE_FUNCTION(MathObject::log10) { - auto value = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)).as_double(); + auto value = TRY(vm.argument(0).to_number(global_object)).as_double(); if (value < 0) return js_nan(); return Value(::log10(value)); } // 21.3.2.31 Math.sinh ( x ), https://tc39.es/ecma262/#sec-math.sinh -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::sinh) +JS_DEFINE_NATIVE_FUNCTION(MathObject::sinh) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::sinh(number.as_double())); } // 21.3.2.13 Math.cosh ( x ), https://tc39.es/ecma262/#sec-math.cosh -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::cosh) +JS_DEFINE_NATIVE_FUNCTION(MathObject::cosh) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); return Value(::cosh(number.as_double())); } // 21.3.2.34 Math.tanh ( x ), https://tc39.es/ecma262/#sec-math.tanh -JS_DEFINE_OLD_NATIVE_FUNCTION(MathObject::tanh) +JS_DEFINE_NATIVE_FUNCTION(MathObject::tanh) { - auto number = TRY_OR_DISCARD(vm.argument(0).to_number(global_object)); + auto number = TRY(vm.argument(0).to_number(global_object)); if (number.is_nan()) return js_nan(); if (number.is_positive_infinity()) diff --git a/Userland/Libraries/LibJS/Runtime/MathObject.h b/Userland/Libraries/LibJS/Runtime/MathObject.h index a1b8961677b0..16b139f65adc 100644 --- a/Userland/Libraries/LibJS/Runtime/MathObject.h +++ b/Userland/Libraries/LibJS/Runtime/MathObject.h @@ -19,41 +19,41 @@ class MathObject final : public Object { virtual ~MathObject() override; private: - JS_DECLARE_OLD_NATIVE_FUNCTION(abs); - JS_DECLARE_OLD_NATIVE_FUNCTION(random); - JS_DECLARE_OLD_NATIVE_FUNCTION(sqrt); - JS_DECLARE_OLD_NATIVE_FUNCTION(floor); - JS_DECLARE_OLD_NATIVE_FUNCTION(ceil); - JS_DECLARE_OLD_NATIVE_FUNCTION(round); - JS_DECLARE_OLD_NATIVE_FUNCTION(max); - JS_DECLARE_OLD_NATIVE_FUNCTION(min); - JS_DECLARE_OLD_NATIVE_FUNCTION(trunc); - JS_DECLARE_OLD_NATIVE_FUNCTION(sin); - JS_DECLARE_OLD_NATIVE_FUNCTION(cos); - JS_DECLARE_OLD_NATIVE_FUNCTION(tan); - JS_DECLARE_OLD_NATIVE_FUNCTION(pow); - JS_DECLARE_OLD_NATIVE_FUNCTION(exp); - JS_DECLARE_OLD_NATIVE_FUNCTION(expm1); - JS_DECLARE_OLD_NATIVE_FUNCTION(sign); - JS_DECLARE_OLD_NATIVE_FUNCTION(clz32); - JS_DECLARE_OLD_NATIVE_FUNCTION(acos); - JS_DECLARE_OLD_NATIVE_FUNCTION(acosh); - JS_DECLARE_OLD_NATIVE_FUNCTION(asin); - JS_DECLARE_OLD_NATIVE_FUNCTION(asinh); - JS_DECLARE_OLD_NATIVE_FUNCTION(atan); - JS_DECLARE_OLD_NATIVE_FUNCTION(atanh); - JS_DECLARE_OLD_NATIVE_FUNCTION(log1p); - JS_DECLARE_OLD_NATIVE_FUNCTION(cbrt); - JS_DECLARE_OLD_NATIVE_FUNCTION(atan2); - JS_DECLARE_OLD_NATIVE_FUNCTION(fround); - JS_DECLARE_OLD_NATIVE_FUNCTION(hypot); - JS_DECLARE_OLD_NATIVE_FUNCTION(imul); - JS_DECLARE_OLD_NATIVE_FUNCTION(log); - JS_DECLARE_OLD_NATIVE_FUNCTION(log2); - JS_DECLARE_OLD_NATIVE_FUNCTION(log10); - JS_DECLARE_OLD_NATIVE_FUNCTION(sinh); - JS_DECLARE_OLD_NATIVE_FUNCTION(cosh); - JS_DECLARE_OLD_NATIVE_FUNCTION(tanh); + JS_DECLARE_NATIVE_FUNCTION(abs); + JS_DECLARE_NATIVE_FUNCTION(random); + JS_DECLARE_NATIVE_FUNCTION(sqrt); + JS_DECLARE_NATIVE_FUNCTION(floor); + JS_DECLARE_NATIVE_FUNCTION(ceil); + JS_DECLARE_NATIVE_FUNCTION(round); + JS_DECLARE_NATIVE_FUNCTION(max); + JS_DECLARE_NATIVE_FUNCTION(min); + JS_DECLARE_NATIVE_FUNCTION(trunc); + JS_DECLARE_NATIVE_FUNCTION(sin); + JS_DECLARE_NATIVE_FUNCTION(cos); + JS_DECLARE_NATIVE_FUNCTION(tan); + JS_DECLARE_NATIVE_FUNCTION(pow); + JS_DECLARE_NATIVE_FUNCTION(exp); + JS_DECLARE_NATIVE_FUNCTION(expm1); + JS_DECLARE_NATIVE_FUNCTION(sign); + JS_DECLARE_NATIVE_FUNCTION(clz32); + JS_DECLARE_NATIVE_FUNCTION(acos); + JS_DECLARE_NATIVE_FUNCTION(acosh); + JS_DECLARE_NATIVE_FUNCTION(asin); + JS_DECLARE_NATIVE_FUNCTION(asinh); + JS_DECLARE_NATIVE_FUNCTION(atan); + JS_DECLARE_NATIVE_FUNCTION(atanh); + JS_DECLARE_NATIVE_FUNCTION(log1p); + JS_DECLARE_NATIVE_FUNCTION(cbrt); + JS_DECLARE_NATIVE_FUNCTION(atan2); + JS_DECLARE_NATIVE_FUNCTION(fround); + JS_DECLARE_NATIVE_FUNCTION(hypot); + JS_DECLARE_NATIVE_FUNCTION(imul); + JS_DECLARE_NATIVE_FUNCTION(log); + JS_DECLARE_NATIVE_FUNCTION(log2); + JS_DECLARE_NATIVE_FUNCTION(log10); + JS_DECLARE_NATIVE_FUNCTION(sinh); + JS_DECLARE_NATIVE_FUNCTION(cosh); + JS_DECLARE_NATIVE_FUNCTION(tanh); }; }
80642b4f9d9eee618a8ce9008721ddccb3adb88f
2021-11-18 02:50:01
Sam Atkins
libweb: Implement background-position and background-origin :^)
false
Implement background-position and background-origin :^)
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp b/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp index 1708274a1b42..e32c6ea921f4 100644 --- a/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp +++ b/Userland/Libraries/LibWeb/Painting/BackgroundPainting.cpp @@ -60,8 +60,25 @@ void paint_background(PaintContext& context, Layout::NodeWithStyleAndBoxModelMet // FIXME: Size Gfx::IntRect image_rect { border_rect.x(), border_rect.y(), image.width(), image.height() }; - // FIXME: Origin - // FIXME: Position + // Origin + auto background_positioning_area = get_box(layer.origin); + int space_x = background_positioning_area.width() - image_rect.width(); + int space_y = background_positioning_area.height() - image_rect.height(); + + // Position + int offset_x = layer.position_offset_x.resolved_or_zero(layout_node, space_x).to_px(layout_node); + if (layer.position_edge_x == CSS::PositionEdge::Right) { + image_rect.set_right_without_resize(background_positioning_area.right() - offset_x); + } else { + image_rect.set_left(background_positioning_area.left() + offset_x); + } + + int offset_y = layer.position_offset_y.resolved_or_zero(layout_node, space_y).to_px(layout_node); + if (layer.position_edge_y == CSS::PositionEdge::Bottom) { + image_rect.set_bottom_without_resize(background_positioning_area.bottom() - offset_y); + } else { + image_rect.set_top(background_positioning_area.top() + offset_y); + } // Repetition bool repeat_x = false;
a69d77081a1405a47c11bcae5d25459c5c7d3b3c
2022-01-12 16:53:27
Lady Gegga
base: Add Chakma characters to font Katica Regular 10
false
Add Chakma characters to font Katica Regular 10
base
diff --git a/Base/res/fonts/KaticaRegular10.font b/Base/res/fonts/KaticaRegular10.font index c0a001c23592..690a8299f61c 100644 Binary files a/Base/res/fonts/KaticaRegular10.font and b/Base/res/fonts/KaticaRegular10.font differ
febc8a5ac70b9d5638a9e5a3940d1b055230e5d4
2021-01-02 00:07:36
Andreas Kling
userspaceemulator: Remove hand-rolled is_foo() helpers in favor of RTTI
false
Remove hand-rolled is_foo() helpers in favor of RTTI
userspaceemulator
diff --git a/DevTools/UserspaceEmulator/Emulator.cpp b/DevTools/UserspaceEmulator/Emulator.cpp index 0f7b9948cbc1..5a6c091f372d 100644 --- a/DevTools/UserspaceEmulator/Emulator.cpp +++ b/DevTools/UserspaceEmulator/Emulator.cpp @@ -280,7 +280,7 @@ const MmapRegion* Emulator::find_text_region(FlatPtr address) { const MmapRegion* matching_region = nullptr; mmu().for_each_region([&](auto& region) { - if (!region.is_mmap()) + if (!is<MmapRegion>(region)) return IterationDecision::Continue; const auto& mmap_region = static_cast<const MmapRegion&>(region); if (!(mmap_region.is_executable() && address >= mmap_region.base() && address < mmap_region.base() + mmap_region.size())) @@ -1045,7 +1045,7 @@ FlatPtr Emulator::virt$mremap(FlatPtr params_addr) mmu().copy_from_vm(&params, params_addr, sizeof(params)); if (auto* region = mmu().find_region({ m_cpu.ds(), params.old_address })) { - if (!region->is_mmap()) + if (!is<MmapRegion>(*region)) return -EINVAL; ASSERT(region->size() == params.old_size); auto& mmap_region = *(MmapRegion*)region; @@ -1094,7 +1094,7 @@ u32 Emulator::virt$unveil(u32) u32 Emulator::virt$mprotect(FlatPtr base, size_t size, int prot) { if (auto* region = mmu().find_region({ m_cpu.ds(), base })) { - if (!region->is_mmap()) + if (!is<MmapRegion>(*region)) return -EINVAL; ASSERT(region->size() == size); auto& mmap_region = *(MmapRegion*)region; diff --git a/DevTools/UserspaceEmulator/MallocTracer.cpp b/DevTools/UserspaceEmulator/MallocTracer.cpp index 9661e615a55b..c2ead0409d85 100644 --- a/DevTools/UserspaceEmulator/MallocTracer.cpp +++ b/DevTools/UserspaceEmulator/MallocTracer.cpp @@ -45,7 +45,7 @@ template<typename Callback> inline void MallocTracer::for_each_mallocation(Callback callback) const { m_emulator.mmu().for_each_region([&](auto& region) { - if (region.is_mmap() && static_cast<const MmapRegion&>(region).is_malloc_block()) { + if (is<MmapRegion>(region) && static_cast<const MmapRegion&>(region).is_malloc_block()) { auto* malloc_data = static_cast<MmapRegion&>(region).malloc_metadata(); for (auto& mallocation : malloc_data->mallocations) { if (mallocation.used && callback(mallocation) == IterationDecision::Break) @@ -62,7 +62,7 @@ void MallocTracer::target_did_malloc(Badge<SoftCPU>, FlatPtr address, size_t siz return; auto* region = m_emulator.mmu().find_region({ 0x23, address }); ASSERT(region); - ASSERT(region->is_mmap()); + ASSERT(is<MmapRegion>(*region)); auto& mmap_region = static_cast<MmapRegion&>(*region); // Mark the containing mmap region as a malloc block! @@ -145,7 +145,7 @@ void MallocTracer::target_did_realloc(Badge<SoftCPU>, FlatPtr address, size_t si return; auto* region = m_emulator.mmu().find_region({ 0x23, address }); ASSERT(region); - ASSERT(region->is_mmap()); + ASSERT(is<MmapRegion>(*region)); auto& mmap_region = static_cast<MmapRegion&>(*region); ASSERT(mmap_region.is_malloc_block()); @@ -334,7 +334,7 @@ bool MallocTracer::is_reachable(const Mallocation& mallocation) const if (!region.is_readable()) return IterationDecision::Continue; // Skip malloc blocks - if (region.is_mmap() && static_cast<const MmapRegion&>(region).is_malloc_block()) + if (is<MmapRegion>(region) && static_cast<const MmapRegion&>(region).is_malloc_block()) return IterationDecision::Continue; size_t pointers_in_region = region.size() / sizeof(u32); diff --git a/DevTools/UserspaceEmulator/MallocTracer.h b/DevTools/UserspaceEmulator/MallocTracer.h index 9741542f7616..53da97acf102 100644 --- a/DevTools/UserspaceEmulator/MallocTracer.h +++ b/DevTools/UserspaceEmulator/MallocTracer.h @@ -95,7 +95,7 @@ class MallocTracer { ALWAYS_INLINE Mallocation* MallocTracer::find_mallocation(const Region& region, FlatPtr address) { - if (!region.is_mmap()) + if (!is<MmapRegion>(region)) return nullptr; if (!static_cast<const MmapRegion&>(region).is_malloc_block()) return nullptr; diff --git a/DevTools/UserspaceEmulator/MmapRegion.h b/DevTools/UserspaceEmulator/MmapRegion.h index 51c2a8e37006..75a42340ab23 100644 --- a/DevTools/UserspaceEmulator/MmapRegion.h +++ b/DevTools/UserspaceEmulator/MmapRegion.h @@ -65,7 +65,6 @@ class MmapRegion final : public Region { private: MmapRegion(u32 base, u32 size, int prot); - virtual bool is_mmap() const override { return true; } u8* m_data { nullptr }; u8* m_shadow_data { nullptr }; diff --git a/DevTools/UserspaceEmulator/Region.h b/DevTools/UserspaceEmulator/Region.h index b75f37f5177f..ffb15cf94194 100644 --- a/DevTools/UserspaceEmulator/Region.h +++ b/DevTools/UserspaceEmulator/Region.h @@ -27,6 +27,7 @@ #pragma once #include "ValueWithShadow.h" +#include <AK/TypeCasts.h> #include <AK/Types.h> namespace UserspaceEmulator { @@ -54,8 +55,6 @@ class Region { virtual ValueWithShadow<u64> read64(u32 offset) = 0; virtual u8* cacheable_ptr([[maybe_unused]] u32 offset) { return nullptr; } - virtual bool is_shared_buffer() const { return false; } - virtual bool is_mmap() const { return false; } bool is_stack() const { return m_stack; } void set_stack(bool b) { m_stack = b; } diff --git a/DevTools/UserspaceEmulator/SharedBufferRegion.h b/DevTools/UserspaceEmulator/SharedBufferRegion.h index 1d56b81ca271..b3c7d68d5c26 100644 --- a/DevTools/UserspaceEmulator/SharedBufferRegion.h +++ b/DevTools/UserspaceEmulator/SharedBufferRegion.h @@ -49,8 +49,6 @@ class SharedBufferRegion final : public Region { virtual u8* data() override { return m_data; } virtual u8* shadow_data() override { return m_shadow_data; } - bool is_shared_buffer() const override { return true; } - int shbuf_id() const { return m_shbuf_id; } int allow_all(); diff --git a/DevTools/UserspaceEmulator/SoftMMU.cpp b/DevTools/UserspaceEmulator/SoftMMU.cpp index 04e2242136cb..50da131f1cd6 100644 --- a/DevTools/UserspaceEmulator/SoftMMU.cpp +++ b/DevTools/UserspaceEmulator/SoftMMU.cpp @@ -44,7 +44,7 @@ void SoftMMU::add_region(NonnullOwnPtr<Region> region) ASSERT(!find_region({ 0x23, region->base() })); // FIXME: More sanity checks pls - if (region->is_shared_buffer()) + if (is<SharedBufferRegion>(*region)) m_shbuf_regions.set(static_cast<SharedBufferRegion*>(region.ptr())->shbuf_id(), region.ptr()); size_t first_page_in_region = region->base() / PAGE_SIZE; @@ -63,7 +63,7 @@ void SoftMMU::remove_region(Region& region) m_page_to_region_map[first_page_in_region + i] = nullptr; } - if (region.is_shared_buffer()) + if (is<SharedBufferRegion>(region)) m_shbuf_regions.remove(static_cast<SharedBufferRegion&>(region).shbuf_id()); m_regions.remove_first_matching([&](auto& entry) { return entry.ptr() == &region; }); } @@ -253,7 +253,7 @@ bool SoftMMU::fast_fill_memory8(X86::LogicalAddress address, size_t size, ValueW if (!region->contains(address.offset() + size - 1)) return false; - if (region->is_mmap() && static_cast<const MmapRegion&>(*region).is_malloc_block()) { + if (is<MmapRegion>(*region) && static_cast<const MmapRegion&>(*region).is_malloc_block()) { if (auto* tracer = m_emulator.malloc_tracer()) { // FIXME: Add a way to audit an entire range of memory instead of looping here! for (size_t i = 0; i < size; ++i) { @@ -278,7 +278,7 @@ bool SoftMMU::fast_fill_memory32(X86::LogicalAddress address, size_t count, Valu if (!region->contains(address.offset() + (count * sizeof(u32)) - 1)) return false; - if (region->is_mmap() && static_cast<const MmapRegion&>(*region).is_malloc_block()) { + if (is<MmapRegion>(*region) && static_cast<const MmapRegion&>(*region).is_malloc_block()) { if (auto* tracer = m_emulator.malloc_tracer()) { // FIXME: Add a way to audit an entire range of memory instead of looping here! for (size_t i = 0; i < count; ++i) {
11aac6fdceb9a3904ad3eb51d887c63a6dc91b74
2020-03-09 19:07:08
howar6hill
libjs: Remove superfluous explicit in AST.h (#1395)
false
Remove superfluous explicit in AST.h (#1395)
libjs
diff --git a/Libraries/LibJS/AST.h b/Libraries/LibJS/AST.h index b6a4d85560bc..a5ce6571cc66 100644 --- a/Libraries/LibJS/AST.h +++ b/Libraries/LibJS/AST.h @@ -129,7 +129,7 @@ class ReturnStatement : public ASTNode { class IfStatement : public ASTNode { public: - explicit IfStatement(NonnullOwnPtr<Expression> predicate, NonnullOwnPtr<ScopeNode> consequent, NonnullOwnPtr<ScopeNode> alternate) + IfStatement(NonnullOwnPtr<Expression> predicate, NonnullOwnPtr<ScopeNode> consequent, NonnullOwnPtr<ScopeNode> alternate) : m_predicate(move(predicate)) , m_consequent(move(consequent)) , m_alternate(move(alternate))
981758a8b10f4189b34c30d4e096d452a2f077ed
2021-01-06 19:28:48
Andreas Kling
libweb: Use the specified CSS values from element in more places
false
Use the specified CSS values from element in more places
libweb
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp index 2a0c3e0b8834..2746e67eb20f 100644 --- a/Libraries/LibWeb/DOM/Element.cpp +++ b/Libraries/LibWeb/DOM/Element.cpp @@ -198,14 +198,12 @@ void Element::recompute_style() { set_needs_style_update(false); ASSERT(parent()); - auto* parent_layout_node = parent()->layout_node(); - if (!parent_layout_node) - return; - ASSERT(parent_layout_node); - auto style = document().style_resolver().resolve_style(*this, &parent_layout_node->specified_style()); - m_specified_css_values = style; + auto old_specified_css_values = m_specified_css_values; + auto* parent_specified_css_values = parent()->is_element() ? downcast<Element>(*parent()).specified_css_values() : nullptr; + auto new_specified_css_values = document().style_resolver().resolve_style(*this, parent_specified_css_values); + m_specified_css_values = new_specified_css_values; if (!layout_node()) { - if (style->display() == CSS::Display::None) + if (new_specified_css_values->display() == CSS::Display::None) return; // We need a new layout tree here! Layout::TreeBuilder tree_builder; @@ -217,11 +215,13 @@ void Element::recompute_style() if (is<Layout::WidgetBox>(layout_node())) return; - auto diff = compute_style_difference(layout_node()->specified_style(), *style, document()); + auto diff = StyleDifference::NeedsRelayout; + if (old_specified_css_values) + diff = compute_style_difference(*old_specified_css_values, *new_specified_css_values, document()); if (diff == StyleDifference::None) return; - layout_node()->set_specified_style(*style); - layout_node()->apply_style(*style); + layout_node()->set_specified_style(*new_specified_css_values); + layout_node()->apply_style(*new_specified_css_values); if (diff == StyleDifference::NeedsRelayout) { document().force_layout(); return; @@ -233,6 +233,7 @@ void Element::recompute_style() NonnullRefPtr<CSS::StyleProperties> Element::computed_style() { + // FIXME: This implementation is not doing anything it's supposed to. auto properties = m_specified_css_values->clone(); if (layout_node() && layout_node()->has_style()) { CSS::PropertyID box_model_metrics[] = { @@ -250,7 +251,7 @@ NonnullRefPtr<CSS::StyleProperties> Element::computed_style() CSS::PropertyID::BorderRightWidth, }; for (CSS::PropertyID id : box_model_metrics) { - auto prop = layout_node()->specified_style().property(id); + auto prop = m_specified_css_values->property(id); if (prop.has_value()) properties->set_property(id, prop.value()); } diff --git a/Libraries/LibWeb/Dump.cpp b/Libraries/LibWeb/Dump.cpp index 5b4cf9ca6f2d..f8f83ebc87e4 100644 --- a/Libraries/LibWeb/Dump.cpp +++ b/Libraries/LibWeb/Dump.cpp @@ -242,13 +242,13 @@ void dump_tree(StringBuilder& builder, const Layout::Node& layout_node, bool sho } } - if (show_specified_style) { + if (show_specified_style && layout_node.dom_node() && layout_node.dom_node()->is_element() && downcast<DOM::Element>(layout_node.dom_node())->specified_css_values()) { struct NameAndValue { String name; String value; }; Vector<NameAndValue> properties; - layout_node.specified_style().for_each_property([&](auto property_id, auto& value) { + downcast<DOM::Element>(*layout_node.dom_node()).specified_css_values()->for_each_property([&](auto property_id, auto& value) { properties.append({ CSS::string_from_property_id(property_id), value.to_string() }); }); quick_sort(properties, [](auto& a, auto& b) { return a.name < b.name; });
5e4739e371e6e638205c3735e584e5b1e5c9f865
2021-10-07 04:22:40
Ben Wiederhake
libtls: Add missing headers to CipherSuite.h
false
Add missing headers to CipherSuite.h
libtls
diff --git a/Userland/Libraries/LibTLS/CipherSuite.h b/Userland/Libraries/LibTLS/CipherSuite.h index cd7a5d75819c..3680cedf2393 100644 --- a/Userland/Libraries/LibTLS/CipherSuite.h +++ b/Userland/Libraries/LibTLS/CipherSuite.h @@ -6,6 +6,8 @@ #pragma once +#include <AK/Types.h> + namespace TLS { enum class CipherSuite {
e5afe7a8a35452118d64671f32370d80bf7c7f48
2021-06-21 15:51:03
Daniel Bertalan
libc: Add P_tmpdir macro
false
Add P_tmpdir macro
libc
diff --git a/Userland/Libraries/LibC/stdio.h b/Userland/Libraries/LibC/stdio.h index b4ff5a8e7568..ecd1393fc9b5 100644 --- a/Userland/Libraries/LibC/stdio.h +++ b/Userland/Libraries/LibC/stdio.h @@ -30,6 +30,7 @@ __BEGIN_DECLS #define _IONBF 2 #define L_tmpnam 256 +#define P_tmpdir "/tmp" extern FILE* stdin; extern FILE* stdout;
578318ca0f389f58e283e531ef83e5794b97517f
2021-09-29 23:34:20
Marcus Nilsson
browser: Use CommonActions where possible and various fixes
false
Use CommonActions where possible and various fixes
browser
diff --git a/Userland/Applications/Browser/BookmarksBarWidget.cpp b/Userland/Applications/Browser/BookmarksBarWidget.cpp index da12d7e7537e..60552fff6ebc 100644 --- a/Userland/Applications/Browser/BookmarksBarWidget.cpp +++ b/Userland/Applications/Browser/BookmarksBarWidget.cpp @@ -135,10 +135,10 @@ BookmarksBarWidget::BookmarksBarWidget(const String& bookmarks_file, bool enable on_bookmark_click(m_context_menu_url, Mod_Ctrl); })); m_context_menu->add_separator(); - m_context_menu->add_action(GUI::Action::create("&Edit", [this](auto&) { + m_context_menu->add_action(GUI::Action::create("&Edit...", [this](auto&) { edit_bookmark(m_context_menu_url); })); - m_context_menu->add_action(GUI::Action::create("&Delete", [this](auto&) { + m_context_menu->add_action(GUI::CommonActions::make_delete_action([this](auto&) { remove_bookmark(m_context_menu_url); })); diff --git a/Userland/Applications/Browser/BrowserWindow.cpp b/Userland/Applications/Browser/BrowserWindow.cpp index 08c184ff6377..6e3d463b701b 100644 --- a/Userland/Applications/Browser/BrowserWindow.cpp +++ b/Userland/Applications/Browser/BrowserWindow.cpp @@ -125,12 +125,10 @@ void BrowserWindow::build_menus() auto& file_menu = add_menu("&File"); file_menu.add_action(WindowActions::the().create_new_tab_action()); - auto close_tab_action = GUI::Action::create( - "&Close Tab", { Mod_Ctrl, Key_W }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/close-tab.png"), [this](auto&) { - active_tab().on_tab_close_request(active_tab()); - }, + auto close_tab_action = GUI::CommonActions::make_close_tab_action([this](auto&) { + active_tab().on_tab_close_request(active_tab()); + }, this); - close_tab_action->set_status_tip("Close current tab"); file_menu.add_action(close_tab_action); file_menu.add_separator(); @@ -220,7 +218,7 @@ void BrowserWindow::build_menus() auto& settings_menu = add_menu("&Settings"); m_change_homepage_action = GUI::Action::create( - "Set Homepage URL", [this](auto&) { + "Set Homepage URL...", [this](auto&) { auto homepage_url = Config::read_string("Browser", "Preferences", "Home", "about:blank"); if (GUI::InputBox::show(this, homepage_url, "Enter URL", "Change homepage URL") == GUI::InputBox::ExecOK) { if (URL(homepage_url).is_valid()) { @@ -237,7 +235,7 @@ void BrowserWindow::build_menus() m_search_engine_actions.set_exclusive(true); auto& search_engine_menu = settings_menu.add_submenu("&Search Engine"); - + search_engine_menu.set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find.png")); bool search_engine_set = false; auto add_search_engine = [&](auto& name, auto& url_format) { auto action = GUI::Action::create_checkable( diff --git a/Userland/Applications/Browser/Tab.cpp b/Userland/Applications/Browser/Tab.cpp index 02d7733f9bd3..46db749e8b16 100644 --- a/Userland/Applications/Browser/Tab.cpp +++ b/Userland/Applications/Browser/Tab.cpp @@ -324,10 +324,10 @@ Tab::Tab(BrowserWindow& window) }; m_tab_context_menu = GUI::Menu::construct(); - m_tab_context_menu->add_action(GUI::Action::create("&Reload Tab", [this](auto&) { + m_tab_context_menu->add_action(GUI::CommonActions::make_reload_action([this](auto&) { this->window().reload_action().activate(); })); - m_tab_context_menu->add_action(GUI::Action::create("&Close Tab", [this](auto&) { + m_tab_context_menu->add_action(GUI::CommonActions::make_close_tab_action([this](auto&) { on_tab_close_request(*this); })); m_tab_context_menu->add_action(GUI::Action::create("&Duplicate Tab", [this](auto&) { diff --git a/Userland/Libraries/LibGUI/Action.h b/Userland/Libraries/LibGUI/Action.h index 8a472161001f..dd4ea7af8166 100644 --- a/Userland/Libraries/LibGUI/Action.h +++ b/Userland/Libraries/LibGUI/Action.h @@ -40,6 +40,7 @@ NonnullRefPtr<Action> make_help_action(Function<void(Action&)>, Core::Object* pa NonnullRefPtr<Action> make_go_back_action(Function<void(Action&)>, Core::Object* parent = nullptr); NonnullRefPtr<Action> make_go_forward_action(Function<void(Action&)>, Core::Object* parent = nullptr); NonnullRefPtr<Action> make_go_home_action(Function<void(Action&)> callback, Core::Object* parent = nullptr); +NonnullRefPtr<Action> make_close_tab_action(Function<void(Action&)> callback, Core::Object* parent = nullptr); NonnullRefPtr<Action> make_reload_action(Function<void(Action&)>, Core::Object* parent = nullptr); NonnullRefPtr<Action> make_select_all_action(Function<void(Action&)>, Core::Object* parent = nullptr); NonnullRefPtr<Action> make_rename_action(Function<void(Action&)>, Core::Object* parent = nullptr); diff --git a/Userland/Libraries/LibGUI/CommonActions.cpp b/Userland/Libraries/LibGUI/CommonActions.cpp index 259cb5b3a797..484ede03cae8 100644 --- a/Userland/Libraries/LibGUI/CommonActions.cpp +++ b/Userland/Libraries/LibGUI/CommonActions.cpp @@ -136,6 +136,13 @@ NonnullRefPtr<Action> make_go_home_action(Function<void(Action&)> callback, Core return Action::create("Go &Home", { Mod_Alt, Key_Home }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-home.png"), move(callback), parent); } +NonnullRefPtr<Action> make_close_tab_action(Function<void(Action&)> callback, Core::Object* parent) +{ + auto action = Action::create("&Close Tab", { Mod_Ctrl, Key_W }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/close-tab.png"), move(callback), parent); + action->set_status_tip("Close current tab"); + return action; +} + NonnullRefPtr<Action> make_reload_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("&Reload", { Mod_Ctrl, Key_R }, Key_F5, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/reload.png"), move(callback), parent);
587d4663a339200a82b518d74c9400f4b77c8380
2021-08-31 00:12:40
Timothy Flynn
ak: Return early from swap() when swapping the same object
false
Return early from swap() when swapping the same object
ak
diff --git a/AK/StdLibExtras.h b/AK/StdLibExtras.h index d93ff3834c08..39263ece0265 100644 --- a/AK/StdLibExtras.h +++ b/AK/StdLibExtras.h @@ -99,6 +99,8 @@ constexpr T ceil_div(T a, U b) template<typename T, typename U> inline void swap(T& a, U& b) { + if (&a == &b) + return; U tmp = move((U&)a); a = (T &&) move(b); b = move(tmp); diff --git a/Tests/AK/CMakeLists.txt b/Tests/AK/CMakeLists.txt index 61cb63a14ef6..ba5f1fb7c021 100644 --- a/Tests/AK/CMakeLists.txt +++ b/Tests/AK/CMakeLists.txt @@ -51,6 +51,7 @@ set(AK_TEST_SOURCES TestSourceLocation.cpp TestSpan.cpp TestStack.cpp + TestStdLibExtras.cpp TestString.cpp TestStringUtils.cpp TestStringView.cpp diff --git a/Tests/AK/TestStdLibExtras.cpp b/Tests/AK/TestStdLibExtras.cpp new file mode 100644 index 000000000000..6a371cfcacf5 --- /dev/null +++ b/Tests/AK/TestStdLibExtras.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021, Tim Flynn <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibTest/TestSuite.h> + +#include <AK/Optional.h> +#include <AK/StdLibExtras.h> +#include <AK/StringView.h> +#include <AK/Variant.h> +#include <AK/Vector.h> + +TEST_CASE(swap) +{ + int i = 4; + int j = 6; + + swap(i, j); + + EXPECT_EQ(i, 6); + EXPECT_EQ(j, 4); +} + +TEST_CASE(swap_same_value) +{ + + int i = 4; + swap(i, i); + EXPECT_EQ(i, 4); +} + +TEST_CASE(swap_same_complex_object) +{ + struct Type1 { + StringView foo; + }; + struct Type2 { + Optional<Type1> foo; + Vector<Type1> bar; + }; + + Variant<Type1, Type2> value1 { Type1 { "hello"sv } }; + Variant<Type1, Type2> value2 { Type2 { {}, { { "goodbye"sv } } } }; + + swap(value1, value2); + + EXPECT(value1.has<Type2>()); + EXPECT(value2.has<Type1>()); + + swap(value1, value1); + + EXPECT(value1.has<Type2>()); + EXPECT(value2.has<Type1>()); +}
6af4d35e8e62b21ad1332a787e46a9082ad77e63
2021-02-18 12:15:22
Tom
windowserver: Apply the backing bitmap's scale when alpha hit-testing
false
Apply the backing bitmap's scale when alpha hit-testing
windowserver
diff --git a/Userland/Services/WindowServer/Window.cpp b/Userland/Services/WindowServer/Window.cpp index 30937dea1445..8887125f6c16 100644 --- a/Userland/Services/WindowServer/Window.cpp +++ b/Userland/Services/WindowServer/Window.cpp @@ -916,7 +916,8 @@ bool Window::hit_test(const Gfx::IntPoint& point, bool include_frame) const u8 threshold = alpha_hit_threshold() * 255; if (threshold == 0 || !m_backing_store || !m_backing_store->has_alpha_channel()) return true; - auto color = m_backing_store->get_pixel(point.translated(-rect().location())); + auto relative_point = point.translated(-rect().location()) * m_backing_store->scale(); + auto color = m_backing_store->get_pixel(relative_point); return color.alpha() >= threshold; } diff --git a/Userland/Services/WindowServer/WindowFrame.cpp b/Userland/Services/WindowServer/WindowFrame.cpp index 19231b52de2a..12640b66c562 100644 --- a/Userland/Services/WindowServer/WindowFrame.cpp +++ b/Userland/Services/WindowServer/WindowFrame.cpp @@ -560,16 +560,16 @@ bool WindowFrame::hit_test(const Gfx::IntPoint& point) const auto relative_point = point.translated(-render_rect().location()); if (point.y() < window_rect.y()) { if (m_top_bottom) - alpha = m_top_bottom->get_pixel(relative_point).alpha(); + alpha = m_top_bottom->get_pixel(relative_point * m_top_bottom->scale()).alpha(); } else if (point.y() > window_rect.bottom()) { if (m_top_bottom) - alpha = m_top_bottom->get_pixel(relative_point.x(), m_bottom_y + point.y() - window_rect.bottom() - 1).alpha(); + alpha = m_top_bottom->get_pixel(relative_point.x() * m_top_bottom->scale(), m_bottom_y * m_top_bottom->scale() + point.y() - window_rect.bottom() - 1).alpha(); } else if (point.x() < window_rect.x()) { if (m_left_right) - alpha = m_left_right->get_pixel(relative_point.x(), relative_point.y() - m_bottom_y).alpha(); + alpha = m_left_right->get_pixel(relative_point.x() * m_left_right->scale(), (relative_point.y() - m_bottom_y) * m_left_right->scale()).alpha(); } else if (point.x() > window_rect.right()) { if (m_left_right) - alpha = m_left_right->get_pixel(m_right_x + point.x() - window_rect.right() - 1, relative_point.y() - m_bottom_y).alpha(); + alpha = m_left_right->get_pixel(m_right_x * m_left_right->scale() + point.x() - window_rect.right() - 1, (relative_point.y() - m_bottom_y) * m_left_right->scale()).alpha(); } else { return false; }
ae21b8ee566b171938ca132572d0373148b83f2f
2020-05-27 14:49:38
Sergey Bugaev
base: Replace TTYServer with text mode Shell
false
Replace TTYServer with text mode Shell
base
diff --git a/Base/etc/SystemServer.ini b/Base/etc/SystemServer.ini index c33bcd742d7a..d81a5ccd41be 100644 --- a/Base/etc/SystemServer.ini +++ b/Base/etc/SystemServer.ini @@ -1,8 +1,3 @@ -[TTYServer] -# NOTE: We don't start anything on tty0 since that's the "active" TTY while WindowServer is up. -Arguments=tty1 -StdIO=/dev/tty1 - [ProtocolServer] Socket=/tmp/portal/protocol SocketPermissions=660 @@ -10,6 +5,7 @@ Lazy=1 Priority=low KeepAlive=1 User=protocol +BootModes=text,graphical [LookupServer] Socket=/tmp/portal/lookup @@ -18,11 +14,13 @@ Lazy=1 Priority=low KeepAlive=1 User=lookup +BootModes=text,graphical [DHCPClient] Priority=low KeepAlive=1 User=root +BootModes=text,graphical [NotificationServer] Socket=/tmp/portal/notify @@ -37,6 +35,7 @@ Socket=/tmp/portal/launch SocketPermissions=600 Lazy=1 User=anon +BootModes=text,graphical [WindowServer] Socket=/tmp/portal/window @@ -109,3 +108,17 @@ User=anon [Terminal] User=anon WorkingDirectory=/home/anon + +[Shell@tty0] +Executable=/bin/Shell +StdIO=/dev/tty0 +Environment=TERM=xterm +KeepAlive=1 +BootModes=text + +[Shell@tty1] +Executable=/bin/Shell +StdIO=/dev/tty1 +Environment=TERM=xterm +KeepAlive=1 +BootModes=text diff --git a/Base/usr/share/man/man5/SystemServer.md b/Base/usr/share/man/man5/SystemServer.md index 3e5ceb957df6..a5cede161fca 100644 --- a/Base/usr/share/man/man5/SystemServer.md +++ b/Base/usr/share/man/man5/SystemServer.md @@ -50,12 +50,13 @@ Priority=low KeepAlive=1 User=anon -# Spawn the TTYServer on /dev/tty1 once on startup with a high priority, -# additionally passing it "tty1" as an argument. -[TTYServer] -Arguments=tty1 -StdIO=/dev/tty1 -Priority=high +# Launch the Shell on /dev/tty0 on startup when booting in text mode. +[Shell@tty0] +Executable=/bin/Shell +StdIO=/dev/tty0 +Environment=TERM=xterm +KeepAlive=1 +BootModes=text ``` ## See also diff --git a/Services/CMakeLists.txt b/Services/CMakeLists.txt index 4a2b261d06e5..61f03a3e921c 100644 --- a/Services/CMakeLists.txt +++ b/Services/CMakeLists.txt @@ -9,6 +9,5 @@ add_subdirectory(SystemMenu) add_subdirectory(SystemServer) add_subdirectory(Taskbar) add_subdirectory(TelnetServer) -add_subdirectory(TTYServer) add_subdirectory(WebServer) add_subdirectory(WindowServer) diff --git a/Services/TTYServer/CMakeLists.txt b/Services/TTYServer/CMakeLists.txt deleted file mode 100644 index 69753bbea81a..000000000000 --- a/Services/TTYServer/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -set(SOURCES - main.cpp -) - -serenity_bin(TTYServer) -target_link_libraries(TTYServer LibC) diff --git a/Services/TTYServer/main.cpp b/Services/TTYServer/main.cpp deleted file mode 100644 index 79e43ca84b5e..000000000000 --- a/Services/TTYServer/main.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2018-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 <AK/Assertions.h> -#include <AK/LogStream.h> -#include <stdio.h> -#include <stdlib.h> -#include <sys/wait.h> -#include <unistd.h> - -int main(int argc, char** argv) -{ - if (pledge("stdio tty proc exec", nullptr) < 0) { - perror("pledge"); - return 1; - } - - if (unveil("/bin/Shell", "x") < 0) { - perror("unveil"); - return 1; - } - - unveil(nullptr, nullptr); - - if (argc < 2) - return -1; - - dbgprintf("Starting console server on %s\n", argv[1]); - - while (true) { - dbgprintf("Running shell on %s\n", argv[1]); - - auto child = fork(); - if (!child) { - int rc = execl("/bin/Shell", "Shell", nullptr); - ASSERT(rc < 0); - perror("execl"); - exit(127); - } else { - int wstatus; - waitpid(child, &wstatus, 0); - dbgprintf("Shell on %s exited with code %d\n", argv[1], WEXITSTATUS(wstatus)); - } - } -}
f7c4165dde9cc1f3c84fbc49c8496dea3a898491
2024-08-22 17:51:13
Timothy Flynn
libweb: Make the drag data store reference counted
false
Make the drag data store reference counted
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/DataTransfer.cpp b/Userland/Libraries/LibWeb/HTML/DataTransfer.cpp index 8cd25b622845..a569403d5433 100644 --- a/Userland/Libraries/LibWeb/HTML/DataTransfer.cpp +++ b/Userland/Libraries/LibWeb/HTML/DataTransfer.cpp @@ -76,7 +76,7 @@ void DataTransfer::set_effect_allowed(FlyString effect_allowed) // On setting, if drag data store's mode is the read/write mode and the new value is one of "none", "copy", "copyLink", // "copyMove", "link", "linkMove", "move", "all", or "uninitialized", then the attribute's current value must be set // to the new value. Otherwise, it must be left unchanged. - if (m_associated_drag_data_store.has_value() && m_associated_drag_data_store->mode() == DragDataStore::Mode::ReadWrite) + if (m_associated_drag_data_store && m_associated_drag_data_store->mode() == DragDataStore::Mode::ReadWrite) set_effect_allowed_internal(move(effect_allowed)); } @@ -109,7 +109,7 @@ ReadonlySpan<String> DataTransfer::types() const String DataTransfer::get_data(String const& format_argument) const { // 1. If the DataTransfer object is no longer associated with a drag data store, then return the empty string. - if (!m_associated_drag_data_store.has_value()) + if (!m_associated_drag_data_store) return {}; // 2. If the drag data store's mode is the protected mode, then return the empty string. @@ -165,7 +165,7 @@ JS::NonnullGCPtr<FileAPI::FileList> DataTransfer::files() const // 2. If the DataTransfer object is no longer associated with a drag data store, the FileList is empty. Return // the empty list L. - if (!m_associated_drag_data_store.has_value()) + if (!m_associated_drag_data_store) return files; // 3. If the drag data store's mode is the protected mode, return the empty list L. @@ -195,9 +195,9 @@ JS::NonnullGCPtr<FileAPI::FileList> DataTransfer::files() const return files; } -void DataTransfer::associate_with_drag_data_store(DragDataStore& drag_data_store) +void DataTransfer::associate_with_drag_data_store(NonnullRefPtr<DragDataStore> drag_data_store) { - m_associated_drag_data_store = drag_data_store; + m_associated_drag_data_store = move(drag_data_store); update_data_transfer_types_list(); } @@ -214,7 +214,7 @@ void DataTransfer::update_data_transfer_types_list() Vector<String> types; // 2. If the DataTransfer object is still associated with a drag data store, then: - if (m_associated_drag_data_store.has_value()) { + if (m_associated_drag_data_store) { bool contains_file = false; // 1. For each item in the DataTransfer object's drag data store item list whose kind is text, add an entry to L diff --git a/Userland/Libraries/LibWeb/HTML/DataTransfer.h b/Userland/Libraries/LibWeb/HTML/DataTransfer.h index 0bdeacb2cb79..c6d327ab6fdf 100644 --- a/Userland/Libraries/LibWeb/HTML/DataTransfer.h +++ b/Userland/Libraries/LibWeb/HTML/DataTransfer.h @@ -55,7 +55,7 @@ class DataTransfer : public Bindings::PlatformObject { String get_data(String const& format) const; JS::NonnullGCPtr<FileAPI::FileList> files() const; - void associate_with_drag_data_store(DragDataStore& drag_data_store); + void associate_with_drag_data_store(NonnullRefPtr<DragDataStore> drag_data_store); void disassociate_with_drag_data_store(); private: @@ -79,7 +79,7 @@ class DataTransfer : public Bindings::PlatformObject { Vector<String> m_types; // https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface:drag-data-store-3 - Optional<DragDataStore&> m_associated_drag_data_store; + RefPtr<DragDataStore> m_associated_drag_data_store; }; } diff --git a/Userland/Libraries/LibWeb/HTML/DragDataStore.cpp b/Userland/Libraries/LibWeb/HTML/DragDataStore.cpp index 9c1572c9e70b..8cdfd4a175a8 100644 --- a/Userland/Libraries/LibWeb/HTML/DragDataStore.cpp +++ b/Userland/Libraries/LibWeb/HTML/DragDataStore.cpp @@ -9,6 +9,11 @@ namespace Web::HTML { +NonnullRefPtr<DragDataStore> DragDataStore::create() +{ + return adopt_ref(*new DragDataStore()); +} + DragDataStore::DragDataStore() : m_allowed_effects_state(DataTransferEffect::uninitialized) { diff --git a/Userland/Libraries/LibWeb/HTML/DragDataStore.h b/Userland/Libraries/LibWeb/HTML/DragDataStore.h index 7df8e7a75c27..ddc6bb8a65fa 100644 --- a/Userland/Libraries/LibWeb/HTML/DragDataStore.h +++ b/Userland/Libraries/LibWeb/HTML/DragDataStore.h @@ -9,6 +9,8 @@ #include <AK/ByteBuffer.h> #include <AK/ByteString.h> #include <AK/FlyString.h> +#include <AK/NonnullRefPtr.h> +#include <AK/RefCounted.h> #include <AK/String.h> #include <AK/Vector.h> #include <LibGfx/Bitmap.h> @@ -33,7 +35,7 @@ struct DragDataStoreItem { }; // https://html.spec.whatwg.org/multipage/dnd.html#drag-data-store -class DragDataStore { +class DragDataStore : public RefCounted<DragDataStore> { public: enum class Mode { ReadWrite, @@ -41,7 +43,7 @@ class DragDataStore { Protected, }; - DragDataStore(); + static NonnullRefPtr<DragDataStore> create(); ~DragDataStore(); void add_item(DragDataStoreItem item) { m_item_list.append(move(item)); } @@ -55,6 +57,8 @@ class DragDataStore { void set_allowed_effects_state(FlyString allowed_effects_state) { m_allowed_effects_state = move(allowed_effects_state); } private: + DragDataStore(); + // https://html.spec.whatwg.org/multipage/dnd.html#drag-data-store-item-list Vector<DragDataStoreItem> m_item_list; diff --git a/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp b/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp index 717aaa5466cf..8f2fa3db2429 100644 --- a/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp +++ b/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.cpp @@ -51,7 +51,7 @@ bool DragAndDropEventHandler::handle_drag_start( // 2. Create a drag data store. All the DND events fired subsequently by the steps in this section must use this drag // data store. - m_drag_data_store.emplace(); + m_drag_data_store = HTML::DragDataStore::create(); // 3. Establish which DOM node is the source node, as follows: // @@ -185,7 +185,7 @@ bool DragAndDropEventHandler::handle_drag_move( unsigned buttons, unsigned modifiers) { - if (!m_drag_data_store.has_value()) + if (!has_ongoing_drag_and_drop_operation()) return false; auto fire_a_drag_and_drop_event = [&](JS::GCPtr<DOM::EventTarget> target, FlyString const& name, JS::GCPtr<DOM::EventTarget> related_target = nullptr) { @@ -361,7 +361,7 @@ bool DragAndDropEventHandler::handle_drag_end( unsigned buttons, unsigned modifiers) { - if (!m_drag_data_store.has_value()) + if (!has_ongoing_drag_and_drop_operation()) return false; auto fire_a_drag_and_drop_event = [&](JS::GCPtr<DOM::EventTarget> target, FlyString const& name, JS::GCPtr<DOM::EventTarget> related_target = nullptr) { diff --git a/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.h b/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.h index 995b1de91849..b96b3b98f9d5 100644 --- a/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.h +++ b/Userland/Libraries/LibWeb/Page/DragAndDropEventHandler.h @@ -18,7 +18,7 @@ class DragAndDropEventHandler { public: void visit_edges(JS::Cell::Visitor& visitor) const; - bool has_ongoing_drag_and_drop_operation() const { return m_drag_data_store.has_value(); } + bool has_ongoing_drag_and_drop_operation() const { return !m_drag_data_store.is_null(); } bool handle_drag_start(JS::Realm&, CSSPixelPoint screen_position, CSSPixelPoint page_offset, CSSPixelPoint client_offset, CSSPixelPoint offset, unsigned button, unsigned buttons, unsigned modifiers, Vector<HTML::SelectedFile> files); bool handle_drag_move(JS::Realm&, JS::NonnullGCPtr<DOM::Document>, JS::NonnullGCPtr<DOM::Node>, CSSPixelPoint screen_position, CSSPixelPoint page_offset, CSSPixelPoint client_offset, CSSPixelPoint offset, unsigned button, unsigned buttons, unsigned modifiers); @@ -49,7 +49,7 @@ class DragAndDropEventHandler { void reset(); - Optional<HTML::DragDataStore> m_drag_data_store; + RefPtr<HTML::DragDataStore> m_drag_data_store; // https://html.spec.whatwg.org/multipage/dnd.html#source-node JS::GCPtr<DOM::EventTarget> m_source_node;
791e881892c7fa55b4f4ed5b885ac3f156276ca2
2022-04-14 00:54:48
SimonFJ20
libgui: Rename function to make intention clearer
false
Rename function to make intention clearer
libgui
diff --git a/Userland/DevTools/Playground/main.cpp b/Userland/DevTools/Playground/main.cpp index 2be6b6f02090..57e374fe3531 100644 --- a/Userland/DevTools/Playground/main.cpp +++ b/Userland/DevTools/Playground/main.cpp @@ -227,7 +227,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) TRY(edit_menu->try_add_action(GUI::Action::create("&Format GML", { Mod_Ctrl | Mod_Shift, Key_I }, [&](auto&) { auto formatted_gml_or_error = GUI::GML::format_gml(editor->text()); if (!formatted_gml_or_error.is_error()) { - editor->replace_all_text_while_keeping_undo_stack(formatted_gml_or_error.release_value()); + editor->replace_all_text_without_resetting_undo_stack(formatted_gml_or_error.release_value()); } else { GUI::MessageBox::show( window, diff --git a/Userland/Libraries/LibGUI/TextEditor.cpp b/Userland/Libraries/LibGUI/TextEditor.cpp index 0ea96cc6165f..93cf86c055b6 100644 --- a/Userland/Libraries/LibGUI/TextEditor.cpp +++ b/Userland/Libraries/LibGUI/TextEditor.cpp @@ -1446,14 +1446,14 @@ void TextEditor::insert_at_cursor_or_replace_selection(StringView text) } } -void TextEditor::replace_all_text_while_keeping_undo_stack(StringView text) +void TextEditor::replace_all_text_without_resetting_undo_stack(StringView text) { auto start = GUI::TextPosition(0, 0); auto last_line_index = line_count() - 1; auto end = GUI::TextPosition(last_line_index, line(last_line_index).length()); auto range = GUI::TextRange(start, end); auto normalized_range = range.normalized(); - execute<ReplaceAllTextCommand>(text, range); + execute<ReplaceAllTextCommand>(text, range, "GML Playground Format Text"); did_change(); set_cursor(normalized_range.start()); update(); diff --git a/Userland/Libraries/LibGUI/TextEditor.h b/Userland/Libraries/LibGUI/TextEditor.h index cb4d2f58ffa7..1bd5b1401afd 100644 --- a/Userland/Libraries/LibGUI/TextEditor.h +++ b/Userland/Libraries/LibGUI/TextEditor.h @@ -123,7 +123,7 @@ class TextEditor TextRange normalized_selection() const { return m_selection.normalized(); } void insert_at_cursor_or_replace_selection(StringView); - void replace_all_text_while_keeping_undo_stack(StringView text); + void replace_all_text_without_resetting_undo_stack(StringView text); bool write_to_file(String const& path); bool write_to_file(Core::File&); bool has_selection() const { return m_selection.is_valid(); }
3d855a801ba401a4b027e8a7cc3c1d4e59050806
2021-10-26 03:08:28
Ben Wiederhake
systemserver: Rename 'BootModes' config option to 'SystemModes'
false
Rename 'BootModes' config option to 'SystemModes'
systemserver
diff --git a/Base/etc/SystemServer.ini b/Base/etc/SystemServer.ini index 76d55e423455..9a36c684f544 100644 --- a/Base/etc/SystemServer.ini +++ b/Base/etc/SystemServer.ini @@ -9,7 +9,7 @@ SocketPermissions=600 Lazy=1 Priority=low User=anon -BootModes=text,graphical,self-test +SystemModes=text,graphical,self-test MultiInstance=1 AcceptSocketConnections=1 @@ -19,7 +19,7 @@ SocketPermissions=660 Lazy=1 Priority=low User=anon -BootModes=text,graphical,self-test +SystemModes=text,graphical,self-test MultiInstance=1 AcceptSocketConnections=1 @@ -28,7 +28,7 @@ Socket=/tmp/portal/webcontent SocketPermissions=600 Lazy=1 User=anon -BootModes=graphical +SystemModes=graphical MultiInstance=1 AcceptSocketConnections=1 @@ -37,7 +37,7 @@ Socket=/tmp/portal/image SocketPermissions=600 Lazy=1 User=anon -BootModes=graphical +SystemModes=graphical MultiInstance=1 AcceptSocketConnections=1 @@ -47,7 +47,7 @@ SocketPermissions=600 Lazy=1 Priority=low User=anon -BootModes=text,graphical,self-test +SystemModes=text,graphical,self-test MultiInstance=1 AcceptSocketConnections=1 @@ -57,13 +57,13 @@ SocketPermissions=660 Priority=low KeepAlive=1 User=lookup -BootModes=text,graphical,self-test +SystemModes=text,graphical,self-test [DHCPClient] Priority=low KeepAlive=1 User=root -BootModes=text,graphical,self-test +SystemModes=text,graphical,self-test [NotificationServer] Socket=/tmp/portal/notify @@ -78,7 +78,7 @@ Socket=/tmp/portal/launch SocketPermissions=600 Lazy=1 User=anon -BootModes=text,graphical +SystemModes=text,graphical [WindowServer] Socket=/tmp/portal/window,/tmp/portal/wm @@ -105,21 +105,21 @@ Socket=/tmp/portal/audio Priority=high KeepAlive=1 User=anon -BootModes=text,graphical +SystemModes=text,graphical [Shell@tty0] Executable=/bin/Shell StdIO=/dev/tty0 Environment=TERM=xterm KeepAlive=1 -BootModes=text +SystemModes=text [Shell@tty1] Executable=/bin/Shell StdIO=/dev/tty1 Environment=TERM=xterm KeepAlive=1 -BootModes=text +SystemModes=text [CppLanguageServer] Socket=/tmp/portal/language/cpp @@ -158,7 +158,7 @@ StdIO=/dev/ttyS0 Environment=DO_SHUTDOWN_AFTER_TESTS=1 TERM=xterm PATH=/bin:/usr/bin:/usr/local/bin TESTS_ONLY=1 UBSAN_OPTIONS=halt_on_error=1 User=anon WorkingDirectory=/home/anon -BootModes=self-test +SystemModes=self-test [SpiceAgent] KeepAlive=0 diff --git a/Base/usr/share/man/man5/SystemServer.md b/Base/usr/share/man/man5/SystemServer.md index 558b0de0234b..a00a49d475c9 100644 --- a/Base/usr/share/man/man5/SystemServer.md +++ b/Base/usr/share/man/man5/SystemServer.md @@ -28,7 +28,7 @@ describing how to launch and manage this service. * `SocketPermissions` - comma-separated list of (octal) file system permissions for the socket file. The default permissions are 0600. If the number of socket permissions defined is less than the number of sockets defined, then the last defined permission will be used for the remainder of the items in `Socket`. * `User` - a name of the user to run the service as. This impacts what UID, GID (and extra GIDs) the service processes have. By default, services are run as root. * `WorkingDirectory` - the working directory in which the service is spawned. By default, services are spawned in the root (`"/"`) directory. -* `BootModes` - a comma-separated list of boot modes the service should be enabled in. By default, services are only enabled in the "graphical" mode. The current system mode is read from the [kernel command line](../man7/boot_parameters.md#options), and is assumed to be "graphical" if not specified there. +* `SystemModes` - a comma-separated list of system modes in which the service should be enabled. By default, services are only enabled in the "graphical" mode. The current system mode is read from the [kernel command line](../man7/boot_parameters.md#options), and is assumed to be "graphical" if not specified there. * `Environment` - a space-separated list of "variable=value" pairs to set in the environment for the service. * `MultiInstance` - whether multiple instances of the service can be running simultaneously. * `AcceptSocketConnections` - whether SystemServer should accept connections on the socket, and spawn an instance of the service for each client connection. @@ -76,7 +76,7 @@ Executable=/bin/Shell StdIO=/dev/tty0 Environment=TERM=xterm KeepAlive=1 -BootModes=text +SystemModes=text # Launch WindowManager with two sockets: one for main windowing operations, and # one for window management operations. Both sockets get file permissions as 660. diff --git a/Documentation/RunningTests.md b/Documentation/RunningTests.md index 64d9aed40554..2479018f5cdb 100644 --- a/Documentation/RunningTests.md +++ b/Documentation/RunningTests.md @@ -101,7 +101,7 @@ StdIO=/dev/ttyS0 Environment=DO_SHUTDOWN_AFTER_TESTS=1 TERM=xterm PATH=/usr/local/bin:/usr/bin:/bin User=anon WorkingDirectory=/home/anon -BootModes=self-test +SystemModes=self-test ``` `/dev/ttyS0` is used as stdio because that serial port is connected when qemu is run with `-display none` and diff --git a/Userland/Services/SystemServer/Service.cpp b/Userland/Services/SystemServer/Service.cpp index e4da86bf7293..3431f0760623 100644 --- a/Userland/Services/SystemServer/Service.cpp +++ b/Userland/Services/SystemServer/Service.cpp @@ -314,7 +314,7 @@ Service::Service(const Core::ConfigFile& config, const StringView& name) m_working_directory = config.read_entry(name, "WorkingDirectory"); m_environment = config.read_entry(name, "Environment").split(' '); - m_boot_modes = config.read_entry(name, "BootModes", "graphical").split(','); + m_system_modes = config.read_entry(name, "SystemModes", "graphical").split(','); m_multi_instance = config.read_bool_entry(name, "MultiInstance"); m_accept_socket_connections = config.read_bool_entry(name, "AcceptSocketConnections"); @@ -366,14 +366,14 @@ void Service::save_to(JsonObject& json) extra_args.append(arg); json.set("extra_arguments", move(extra_args)); - JsonArray boot_modes; - for (String& mode : m_boot_modes) - boot_modes.append(mode); - json.set("boot_modes", boot_modes); + JsonArray system_modes; + for (String& mode : m_system_modes) + system_modes.append(mode); + json.set("system_modes", system_modes); JsonArray environment; for (String& env : m_environment) - boot_modes.append(env); + system_modes.append(env); json.set("environment", environment); JsonArray sockets; @@ -406,5 +406,5 @@ void Service::save_to(JsonObject& json) bool Service::is_enabled() const { extern String g_system_mode; - return m_boot_modes.contains_slow(g_system_mode); + return m_system_modes.contains_slow(g_system_mode); } diff --git a/Userland/Services/SystemServer/Service.h b/Userland/Services/SystemServer/Service.h index a9ad00939f49..07a0c7adfa44 100644 --- a/Userland/Services/SystemServer/Service.h +++ b/Userland/Services/SystemServer/Service.h @@ -61,8 +61,8 @@ class Service final : public Core::Object { String m_user; // The working directory in which to spawn the service. String m_working_directory; - // Boot modes to run this service in. By default, this is the graphical mode. - Vector<String> m_boot_modes; + // System modes in which to run this service. By default, this is the graphical mode. + Vector<String> m_system_modes; // Whether several instances of this service can run at once. bool m_multi_instance { false }; // Environment variables to pass to the service.
dabdd484f796054566c6369c936060ce8602436b
2019-11-21 02:17:12
Andreas Kling
libvt: Add a context menu to TerminalWidget
false
Add a context menu to TerminalWidget
libvt
diff --git a/Libraries/LibVT/TerminalWidget.cpp b/Libraries/LibVT/TerminalWidget.cpp index e00142faff1a..e1f07f745957 100644 --- a/Libraries/LibVT/TerminalWidget.cpp +++ b/Libraries/LibVT/TerminalWidget.cpp @@ -8,6 +8,7 @@ #include <LibGUI/GAction.h> #include <LibGUI/GApplication.h> #include <LibGUI/GClipboard.h> +#include <LibGUI/GMenu.h> #include <LibGUI/GPainter.h> #include <LibGUI/GScrollBar.h> #include <LibGUI/GWindow.h> @@ -654,3 +655,13 @@ void TerminalWidget::beep() }; force_repaint(); } + +void TerminalWidget::context_menu_event(GContextMenuEvent& event) +{ + if (!m_context_menu) { + m_context_menu = make<GMenu>(); + m_context_menu->add_action(copy_action()); + m_context_menu->add_action(paste_action()); + } + m_context_menu->popup(event.screen_position()); +} diff --git a/Libraries/LibVT/TerminalWidget.h b/Libraries/LibVT/TerminalWidget.h index 3c56ac1e1b62..ee28c597ca27 100644 --- a/Libraries/LibVT/TerminalWidget.h +++ b/Libraries/LibVT/TerminalWidget.h @@ -72,6 +72,7 @@ class TerminalWidget final : public GFrame virtual void doubleclick_event(GMouseEvent&) override; virtual void focusin_event(CEvent&) override; virtual void focusout_event(CEvent&) override; + virtual void context_menu_event(GContextMenuEvent&) override; // ^TerminalClient virtual void beep() override; @@ -128,5 +129,7 @@ class TerminalWidget final : public GFrame RefPtr<GAction> m_copy_action; RefPtr<GAction> m_paste_action; + OwnPtr<GMenu> m_context_menu; + CElapsedTimer m_triple_click_timer; };
8bfee015bc7d79c7fc3c89edbc88eba503e8ab37
2020-04-05 21:49:56
Andreas Kling
libjs: Make Object::to_string() call the "toString" property if present
false
Make Object::to_string() call the "toString" property if present
libjs
diff --git a/Libraries/LibJS/Runtime/Object.cpp b/Libraries/LibJS/Runtime/Object.cpp index c29c7f85d161..6598a3af760e 100644 --- a/Libraries/LibJS/Runtime/Object.cpp +++ b/Libraries/LibJS/Runtime/Object.cpp @@ -205,6 +205,14 @@ Value Object::to_primitive(PreferredType preferred_type) const Value Object::to_string() const { + auto to_string_property = get("toString"); + if (to_string_property.has_value() + && to_string_property.value().is_object() + && to_string_property.value().as_object().is_function()) { + auto& to_string_function = static_cast<Function&>(to_string_property.value().as_object()); + return const_cast<Object*>(this)->interpreter().call(&to_string_function, const_cast<Object*>(this)); + } return js_string(heap(), String::format("[object %s]", class_name())); } + } diff --git a/Libraries/LibJS/Runtime/ObjectPrototype.cpp b/Libraries/LibJS/Runtime/ObjectPrototype.cpp index 92e06048b238..c70c59025363 100644 --- a/Libraries/LibJS/Runtime/ObjectPrototype.cpp +++ b/Libraries/LibJS/Runtime/ObjectPrototype.cpp @@ -61,7 +61,7 @@ Value ObjectPrototype::to_string(Interpreter& interpreter) auto* this_object = interpreter.this_value().to_object(interpreter.heap()); if (!this_object) return {}; - return Value(this_object->to_string()); + return js_string(interpreter, String::format("[object %s]", this_object->class_name())); } Value ObjectPrototype::value_of(Interpreter& interpreter) diff --git a/Libraries/LibJS/Tests/Array.prototype.toString.js b/Libraries/LibJS/Tests/Array.prototype.toString.js index e9ace65d26e7..7b33f21183e2 100644 --- a/Libraries/LibJS/Tests/Array.prototype.toString.js +++ b/Libraries/LibJS/Tests/Array.prototype.toString.js @@ -3,6 +3,9 @@ try { assert(a.toString() === '1,2,3'); assert([].toString() === ''); assert([5].toString() === '5'); + + assert("rgb(" + [10, 11, 12] + ")" === "rgb(10,11,12)"); + console.log("PASS"); } catch (e) { console.log("FAIL: " + e); diff --git a/Libraries/LibJS/Tests/function-TypeError.js b/Libraries/LibJS/Tests/function-TypeError.js index 1939e01f0695..2909c802e3cb 100644 --- a/Libraries/LibJS/Tests/function-TypeError.js +++ b/Libraries/LibJS/Tests/function-TypeError.js @@ -41,7 +41,7 @@ try { new isNaN(); } catch(e) { assert(e.name === "TypeError"); - assert(e.message === "[object NativeFunction] is not a constructor"); + assert(e.message === "function () {\n [NativeFunction]\n} is not a constructor"); } console.log("PASS");
14fff5df06afb574e2a1a2df8c9f1c1ea5668f66
2021-06-19 13:08:26
Matthew Olsson
libjs: Implement more IteratorOperations and organize file
false
Implement more IteratorOperations and organize file
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp b/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp index 79d76212c024..dca658cee3f2 100644 --- a/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp @@ -69,6 +69,18 @@ Object* iterator_next(Object& iterator, Value value) return &result.as_object(); } +// 7.4.3 IteratorComplete ( iterResult ), https://tc39.es/ecma262/#sec-iteratorcomplete +bool iterator_complete(GlobalObject& global_object, Object& iterator_result) +{ + return iterator_result.get(global_object.vm().names.done).value_or(Value(false)).to_boolean(); +} + +// 7.4.4 IteratorValue ( iterResult ), https://tc39.es/ecma262/#sec-iteratorvalue +Value iterator_value(GlobalObject& global_object, Object& iterator_result) +{ + return iterator_result.get(global_object.vm().names.value).value_or(js_undefined()); +} + // 7.4.6 IteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-iteratorclose void iterator_close(Object& iterator) { @@ -104,6 +116,16 @@ void iterator_close(Object& iterator) restore_completion(); // Return Completion(completion). } +// 7.4.8 CreateIterResultObject ( value, done ), https://tc39.es/ecma262/#sec-createiterresultobject +Value create_iterator_result_object(GlobalObject& global_object, Value value, bool done) +{ + auto& vm = global_object.vm(); + auto* object = Object::create(global_object, global_object.object_prototype()); + object->define_property(vm.names.value, value); + object->define_property(vm.names.done, Value(done)); + return object; +} + // 7.4.10 IterableToList ( items [ , method ] ), https://tc39.es/ecma262/#sec-iterabletolist MarkedValueList iterable_to_list(GlobalObject& global_object, Value iterable, Value method) { @@ -120,16 +142,6 @@ MarkedValueList iterable_to_list(GlobalObject& global_object, Value iterable, Va return values; } -// 7.4.8 CreateIterResultObject ( value, done ), https://tc39.es/ecma262/#sec-createiterresultobject -Value create_iterator_result_object(GlobalObject& global_object, Value value, bool done) -{ - auto& vm = global_object.vm(); - auto* object = Object::create(global_object, global_object.object_prototype()); - object->define_property(vm.names.value, value); - object->define_property(vm.names.done, Value(done)); - return object; -} - void get_iterator_values(GlobalObject& global_object, Value value, AK::Function<IterationDecision(Value)> callback, Value method, CloseOnAbrupt close_on_abrupt) { auto& vm = global_object.vm(); diff --git a/Userland/Libraries/LibJS/Runtime/IteratorOperations.h b/Userland/Libraries/LibJS/Runtime/IteratorOperations.h index 8671efd69516..8afcbda06768 100644 --- a/Userland/Libraries/LibJS/Runtime/IteratorOperations.h +++ b/Userland/Libraries/LibJS/Runtime/IteratorOperations.h @@ -19,12 +19,11 @@ enum class IteratorHint { }; Object* get_iterator(GlobalObject&, Value value, IteratorHint hint = IteratorHint::Sync, Value method = {}); -bool is_iterator_complete(Object& iterator_result); -Value create_iterator_result_object(GlobalObject&, Value value, bool done); - Object* iterator_next(Object& iterator, Value value = {}); +bool iterator_complete(GlobalObject&, Object& iterator_result); +Value iterator_value(GlobalObject&, Object& iterator_result); void iterator_close(Object& iterator); - +Value create_iterator_result_object(GlobalObject&, Value value, bool done); MarkedValueList iterable_to_list(GlobalObject&, Value iterable, Value method = {}); enum class CloseOnAbrupt {
815d39886f4f0e835bb6300682bafc7dc266ac2b
2020-12-27 15:39:30
Brian Gianforcaro
kernel: Tag more methods and types as [[nodiscard]]
false
Tag more methods and types as [[nodiscard]]
kernel
diff --git a/Kernel/Random.h b/Kernel/Random.h index 5fe130d1c38e..db4c29b4c3fe 100644 --- a/Kernel/Random.h +++ b/Kernel/Random.h @@ -87,12 +87,12 @@ class FortunaPRNG { m_pools[pool].update(reinterpret_cast<const u8*>(&event_data), sizeof(T)); } - bool is_seeded() const + [[nodiscard]] bool is_seeded() const { return m_reseed_number > 0; } - bool is_ready() const + [[nodiscard]] bool is_ready() const { return is_seeded() || m_p0_len >= reseed_threshold; } diff --git a/Kernel/SpinLock.h b/Kernel/SpinLock.h index e2bf8e5daa53..42da93492cce 100644 --- a/Kernel/SpinLock.h +++ b/Kernel/SpinLock.h @@ -58,7 +58,7 @@ class SpinLock { Processor::current().leave_critical(prev_flags); } - ALWAYS_INLINE bool is_locked() const + [[nodiscard]] ALWAYS_INLINE bool is_locked() const { return m_lock.load(AK::memory_order_relaxed) != 0; } @@ -105,12 +105,12 @@ class RecursiveSpinLock { Processor::current().leave_critical(prev_flags); } - ALWAYS_INLINE bool is_locked() const + [[nodiscard]] ALWAYS_INLINE bool is_locked() const { return m_lock.load(AK::memory_order_relaxed) != 0; } - ALWAYS_INLINE bool own_lock() const + [[nodiscard]] ALWAYS_INLINE bool own_lock() const { return m_lock.load(AK::memory_order_relaxed) == FlatPtr(&Processor::current()); } @@ -126,7 +126,8 @@ class RecursiveSpinLock { }; template<typename LockType> -class ScopedSpinLock { +class NO_DISCARD ScopedSpinLock { + AK_MAKE_NONCOPYABLE(ScopedSpinLock); public: @@ -175,7 +176,7 @@ class ScopedSpinLock { m_have_lock = false; } - ALWAYS_INLINE bool have_lock() const + [[nodiscard]] ALWAYS_INLINE bool have_lock() const { return m_have_lock; } diff --git a/Kernel/Thread.h b/Kernel/Thread.h index 6c44968f9452..cd852f9958ab 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -113,7 +113,7 @@ class Thread m_is_joinable = false; } - bool is_joinable() const + [[nodiscard]] bool is_joinable() const { ScopedSpinLock lock(m_lock); return m_is_joinable; @@ -181,7 +181,7 @@ class Thread return m_type != type; } - bool was_interrupted() const + [[nodiscard]] bool was_interrupted() const { switch (m_type) { case InterruptedBySignal: @@ -192,7 +192,7 @@ class Thread } } - bool timed_out() const + [[nodiscard]] bool timed_out() const { return m_type == InterruptedByTimeout; } @@ -330,7 +330,7 @@ class Thread { return m_was_interrupted_by_signal; } - bool was_interrupted() const + [[nodiscard]] bool was_interrupted() const { return m_was_interrupted_by_death || m_was_interrupted_by_signal != 0; } @@ -734,10 +734,10 @@ class Thread void resume_from_stopped(); - bool should_be_stopped() const; - bool is_stopped() const { return m_state == Stopped; } - bool is_blocked() const { return m_state == Blocked; } - bool is_in_block() const + [[nodiscard]] bool should_be_stopped() const; + [[nodiscard]] bool is_stopped() const { return m_state == Stopped; } + [[nodiscard]] bool is_blocked() const { return m_state == Blocked; } + [[nodiscard]] bool is_in_block() const { ScopedSpinLock lock(m_block_lock); return m_in_block; @@ -932,7 +932,7 @@ class Thread // Tell this thread to unblock if needed, // gracefully unwind the stack and die. void set_should_die(); - bool should_die() const { return m_should_die; } + [[nodiscard]] bool should_die() const { return m_should_die; } void die_if_needed(); void exit(void* = nullptr); @@ -946,7 +946,7 @@ class Thread void set_state(State, u8 = 0); - bool is_initialized() const { return m_initialized; } + [[nodiscard]] bool is_initialized() const { return m_initialized; } void set_initialized(bool initialized) { m_initialized = initialized; } void send_urgent_signal_to_self(u8 signal); @@ -963,11 +963,11 @@ class Thread DispatchSignalResult try_dispatch_one_pending_signal(u8 signal); DispatchSignalResult dispatch_signal(u8 signal); void check_dispatch_pending_signal(); - bool has_unmasked_pending_signals() const { return m_have_any_unmasked_pending_signals.load(AK::memory_order_consume); } + [[nodiscard]] bool has_unmasked_pending_signals() const { return m_have_any_unmasked_pending_signals.load(AK::memory_order_consume); } void terminate_due_to_signal(u8 signal); - bool should_ignore_signal(u8 signal) const; - bool has_signal_handler(u8 signal) const; - bool has_pending_signal(u8 signal) const; + [[nodiscard]] bool should_ignore_signal(u8 signal) const; + [[nodiscard]] bool has_signal_handler(u8 signal) const; + [[nodiscard]] bool has_pending_signal(u8 signal) const; u32 pending_signals() const; u32 pending_signals_for_state() const; @@ -1030,12 +1030,13 @@ class Thread { m_is_active.store(active, AK::memory_order_release); } - bool is_active() const + + [[nodiscard]] bool is_active() const { return m_is_active.load(AK::MemoryOrder::memory_order_acquire); } - bool is_finalizable() const + [[nodiscard]] bool is_finalizable() const { // We can't finalize as long as this thread is still running // Note that checking for Running state here isn't sufficient @@ -1060,7 +1061,7 @@ class Thread template<typename Callback> static IterationDecision for_each(Callback); - static bool is_runnable_state(Thread::State state) + [[nodiscard]] static bool is_runnable_state(Thread::State state) { return state == Thread::State::Running || state == Thread::State::Runnable; }
7baaa34490585740c4500efcc5cc033932f04d26
2021-01-09 16:32:07
Andreas Kling
libgui: Make SortingProxyModel proxy accepts_drag()
false
Make SortingProxyModel proxy accepts_drag()
libgui
diff --git a/Libraries/LibGUI/FileSystemModel.cpp b/Libraries/LibGUI/FileSystemModel.cpp index f5ed18c63773..a7e2b858525d 100644 --- a/Libraries/LibGUI/FileSystemModel.cpp +++ b/Libraries/LibGUI/FileSystemModel.cpp @@ -589,7 +589,7 @@ String FileSystemModel::column_name(int column) const ASSERT_NOT_REACHED(); } -bool FileSystemModel::accepts_drag(const ModelIndex& index, const Vector<String>& mime_types) +bool FileSystemModel::accepts_drag(const ModelIndex& index, const Vector<String>& mime_types) const { if (!index.is_valid()) return false; diff --git a/Libraries/LibGUI/FileSystemModel.h b/Libraries/LibGUI/FileSystemModel.h index f2c0ea4e7be5..2ef60bd708fe 100644 --- a/Libraries/LibGUI/FileSystemModel.h +++ b/Libraries/LibGUI/FileSystemModel.h @@ -147,7 +147,7 @@ class FileSystemModel virtual ModelIndex parent_index(const ModelIndex&) const override; virtual ModelIndex index(int row, int column = 0, const ModelIndex& parent = ModelIndex()) const override; virtual StringView drag_data_type() const override { return "text/uri-list"; } - virtual bool accepts_drag(const ModelIndex&, const Vector<String>& mime_types) override; + virtual bool accepts_drag(const ModelIndex&, const Vector<String>& mime_types) const override; virtual bool is_column_sortable(int column_index) const override { return column_index != Column::Icon; } virtual bool is_editable(const ModelIndex&) const override; virtual bool is_searchable() const override { return true; } diff --git a/Libraries/LibGUI/Model.cpp b/Libraries/LibGUI/Model.cpp index a1e4180a9bd9..59685bf7434e 100644 --- a/Libraries/LibGUI/Model.cpp +++ b/Libraries/LibGUI/Model.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2018-2021, Andreas Kling <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -71,7 +71,7 @@ ModelIndex Model::index(int row, int column, const ModelIndex&) const return create_index(row, column); } -bool Model::accepts_drag(const ModelIndex&, const Vector<String>&) +bool Model::accepts_drag(const ModelIndex&, const Vector<String>&) const { return false; } diff --git a/Libraries/LibGUI/Model.h b/Libraries/LibGUI/Model.h index 5402edcb312c..c3dad9572f5d 100644 --- a/Libraries/LibGUI/Model.h +++ b/Libraries/LibGUI/Model.h @@ -82,7 +82,7 @@ class Model : public RefCounted<Model> { virtual bool is_searchable() const { return false; } virtual void set_data(const ModelIndex&, const Variant&) { } virtual int tree_column() const { return 0; } - virtual bool accepts_drag(const ModelIndex&, const Vector<String>& mime_types); + virtual bool accepts_drag(const ModelIndex&, const Vector<String>& mime_types) const; virtual Vector<ModelIndex, 1> matches(const StringView&, unsigned = MatchesFlag::AllMatching, const ModelIndex& = ModelIndex()) { return {}; } virtual bool is_column_sortable([[maybe_unused]] int column_index) const { return true; } diff --git a/Libraries/LibGUI/SortingProxyModel.cpp b/Libraries/LibGUI/SortingProxyModel.cpp index 0ebe1693748b..a0618ae410c4 100644 --- a/Libraries/LibGUI/SortingProxyModel.cpp +++ b/Libraries/LibGUI/SortingProxyModel.cpp @@ -63,6 +63,11 @@ void SortingProxyModel::model_did_update(unsigned flags) invalidate(flags); } +bool SortingProxyModel::accepts_drag(const ModelIndex& proxy_index, const Vector<String>& mime_types) const +{ + return source().accepts_drag(map_to_source(proxy_index), mime_types); +} + int SortingProxyModel::row_count(const ModelIndex& proxy_index) const { return source().row_count(map_to_source(proxy_index)); diff --git a/Libraries/LibGUI/SortingProxyModel.h b/Libraries/LibGUI/SortingProxyModel.h index c82e29dc5023..3398c6a89f5b 100644 --- a/Libraries/LibGUI/SortingProxyModel.h +++ b/Libraries/LibGUI/SortingProxyModel.h @@ -49,6 +49,7 @@ class SortingProxyModel virtual bool is_searchable() const override; virtual void set_data(const ModelIndex&, const Variant&) override; virtual Vector<ModelIndex, 1> matches(const StringView&, unsigned = MatchesFlag::AllMatching, const ModelIndex& = ModelIndex()) override; + virtual bool accepts_drag(const ModelIndex&, const Vector<String>& mime_types) const override; virtual bool is_column_sortable(int column_index) const override;
f43f4a16e733766fc7956647269414c09c97b70c
2021-04-11 04:48:02
Gunnar Beutner
ports: Fix install actions for the bash port when re-installing the port
false
Fix install actions for the bash port when re-installing the port
ports
diff --git a/Ports/bash/package.sh b/Ports/bash/package.sh index 4447b3aefe15..be9205c10bd1 100755 --- a/Ports/bash/package.sh +++ b/Ports/bash/package.sh @@ -17,5 +17,5 @@ build() { post_install() { mkdir -p "${SERENITY_BUILD_DIR}/Root/bin" - ln -s /usr/local/bin/bash "${SERENITY_BUILD_DIR}/Root/bin/bash" + ln -sf /usr/local/bin/bash "${SERENITY_BUILD_DIR}/Root/bin/bash" }
273b9b4ca17c38bf807ca0857205cf0fd51a7539
2023-03-25 22:26:04
Sam Atkins
libweb: Split FlexStyleValue out of StyleValue.{h,cpp}
false
Split FlexStyleValue out of StyleValue.{h,cpp}
libweb
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 450c8b59acdf..903211490d92 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -74,6 +74,7 @@ set(SOURCES CSS/StyleValues/ColorStyleValue.cpp CSS/StyleValues/ContentStyleValue.cpp CSS/StyleValues/FilterValueListStyleValue.cpp + CSS/StyleValues/FlexStyleValue.cpp CSS/Supports.cpp CSS/SyntaxHighlighter/SyntaxHighlighter.cpp CSS/Time.cpp diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index 1a2883164ad5..be7c45e62890 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -39,6 +39,7 @@ #include <LibWeb/CSS/StyleValues/ColorStyleValue.h> #include <LibWeb/CSS/StyleValues/ContentStyleValue.h> #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h> +#include <LibWeb/CSS/StyleValues/FlexStyleValue.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/Dump.h> #include <LibWeb/Infra/Strings.h> diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp index 61d8a4b754fc..456df1225f49 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp @@ -31,6 +31,7 @@ #include <LibWeb/CSS/StyleValues/BorderStyleValue.h> #include <LibWeb/CSS/StyleValues/ColorStyleValue.h> #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h> +#include <LibWeb/CSS/StyleValues/FlexStyleValue.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Element.h> #include <LibWeb/FontCache.h> diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValue.cpp index f13b0db3a23b..d01661d98c48 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.cpp @@ -21,6 +21,7 @@ #include <LibWeb/CSS/StyleValues/ColorStyleValue.h> #include <LibWeb/CSS/StyleValues/ContentStyleValue.h> #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h> +#include <LibWeb/CSS/StyleValues/FlexStyleValue.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/HTML/BrowsingContext.h> #include <LibWeb/Loader/LoadRequest.h> @@ -1023,11 +1024,6 @@ CalculatedStyleValue::CalculationResult CalculatedStyleValue::CalcNumberSumPartW return value->resolve(layout_node, percentage_basis); } -ErrorOr<String> FlexStyleValue::to_string() const -{ - return String::formatted("{} {} {}", TRY(m_properties.grow->to_string()), TRY(m_properties.shrink->to_string()), TRY(m_properties.basis->to_string())); -} - ErrorOr<String> FlexFlowStyleValue::to_string() const { return String::formatted("{} {}", TRY(m_properties.flex_direction->to_string()), TRY(m_properties.flex_wrap->to_string())); diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h index 1a40817745c9..80ff2ebaae15 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h @@ -661,43 +661,6 @@ class CalculatedStyleValue : public StyleValue { NonnullOwnPtr<CalcSum> m_expression; }; -class FlexStyleValue final : public StyleValueWithDefaultOperators<FlexStyleValue> { -public: - static ValueComparingNonnullRefPtr<FlexStyleValue> create( - ValueComparingNonnullRefPtr<StyleValue> grow, - ValueComparingNonnullRefPtr<StyleValue> shrink, - ValueComparingNonnullRefPtr<StyleValue> basis) - { - return adopt_ref(*new FlexStyleValue(move(grow), move(shrink), move(basis))); - } - virtual ~FlexStyleValue() override = default; - - ValueComparingNonnullRefPtr<StyleValue> grow() const { return m_properties.grow; } - ValueComparingNonnullRefPtr<StyleValue> shrink() const { return m_properties.shrink; } - ValueComparingNonnullRefPtr<StyleValue> basis() const { return m_properties.basis; } - - virtual ErrorOr<String> to_string() const override; - - bool properties_equal(FlexStyleValue const& other) const { return m_properties == other.m_properties; }; - -private: - FlexStyleValue( - ValueComparingNonnullRefPtr<StyleValue> grow, - ValueComparingNonnullRefPtr<StyleValue> shrink, - ValueComparingNonnullRefPtr<StyleValue> basis) - : StyleValueWithDefaultOperators(Type::Flex) - , m_properties { .grow = move(grow), .shrink = move(shrink), .basis = move(basis) } - { - } - - struct Properties { - ValueComparingNonnullRefPtr<StyleValue> grow; - ValueComparingNonnullRefPtr<StyleValue> shrink; - ValueComparingNonnullRefPtr<StyleValue> basis; - bool operator==(Properties const&) const = default; - } m_properties; -}; - class FlexFlowStyleValue final : public StyleValueWithDefaultOperators<FlexFlowStyleValue> { public: static ValueComparingNonnullRefPtr<FlexFlowStyleValue> create(ValueComparingNonnullRefPtr<StyleValue> flex_direction, ValueComparingNonnullRefPtr<StyleValue> flex_wrap) diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/FlexStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/FlexStyleValue.cpp new file mode 100644 index 000000000000..6f4a8c399518 --- /dev/null +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/FlexStyleValue.cpp @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2021, Tobias Christiansen <[email protected]> + * Copyright (c) 2021-2023, Sam Atkins <[email protected]> + * Copyright (c) 2022-2023, MacDue <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "FlexStyleValue.h" + +namespace Web::CSS { + +ErrorOr<String> FlexStyleValue::to_string() const +{ + return String::formatted("{} {} {}", TRY(m_properties.grow->to_string()), TRY(m_properties.shrink->to_string()), TRY(m_properties.basis->to_string())); +} + +} diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/FlexStyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValues/FlexStyleValue.h new file mode 100644 index 000000000000..18c8591060dd --- /dev/null +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/FlexStyleValue.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2021, Tobias Christiansen <[email protected]> + * Copyright (c) 2021-2023, Sam Atkins <[email protected]> + * Copyright (c) 2022-2023, MacDue <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <LibWeb/CSS/StyleValue.h> + +namespace Web::CSS { + +class FlexStyleValue final : public StyleValueWithDefaultOperators<FlexStyleValue> { +public: + static ValueComparingNonnullRefPtr<FlexStyleValue> create( + ValueComparingNonnullRefPtr<StyleValue> grow, + ValueComparingNonnullRefPtr<StyleValue> shrink, + ValueComparingNonnullRefPtr<StyleValue> basis) + { + return adopt_ref(*new FlexStyleValue(move(grow), move(shrink), move(basis))); + } + virtual ~FlexStyleValue() override = default; + + ValueComparingNonnullRefPtr<StyleValue> grow() const { return m_properties.grow; } + ValueComparingNonnullRefPtr<StyleValue> shrink() const { return m_properties.shrink; } + ValueComparingNonnullRefPtr<StyleValue> basis() const { return m_properties.basis; } + + virtual ErrorOr<String> to_string() const override; + + bool properties_equal(FlexStyleValue const& other) const { return m_properties == other.m_properties; }; + +private: + FlexStyleValue( + ValueComparingNonnullRefPtr<StyleValue> grow, + ValueComparingNonnullRefPtr<StyleValue> shrink, + ValueComparingNonnullRefPtr<StyleValue> basis) + : StyleValueWithDefaultOperators(Type::Flex) + , m_properties { .grow = move(grow), .shrink = move(shrink), .basis = move(basis) } + { + } + + struct Properties { + ValueComparingNonnullRefPtr<StyleValue> grow; + ValueComparingNonnullRefPtr<StyleValue> shrink; + ValueComparingNonnullRefPtr<StyleValue> basis; + bool operator==(Properties const&) const = default; + } m_properties; +}; + +}
c85f00e373405623ecd255c36ba63c907b44de86
2024-06-08 11:28:58
Matthew Olsson
libweb: Only read enumerable keyframe properties
false
Only read enumerable keyframe properties
libweb
diff --git a/Userland/Libraries/LibWeb/Animations/KeyframeEffect.cpp b/Userland/Libraries/LibWeb/Animations/KeyframeEffect.cpp index 6b32141a22e7..240a995f0fd5 100644 --- a/Userland/Libraries/LibWeb/Animations/KeyframeEffect.cpp +++ b/Userland/Libraries/LibWeb/Animations/KeyframeEffect.cpp @@ -142,7 +142,7 @@ static WebIDL::ExceptionOr<KeyframeType<AL>> process_a_keyframe_like_object(JS:: // 4. Make up a new list animation properties that consists of all of the properties that are in both input // properties and animatable properties, or which are in input properties and conform to the // <custom-property-name> production. - auto input_properties = TRY(keyframe_object.internal_own_property_keys()); + auto input_properties = TRY(keyframe_object.enumerable_own_property_names(JS::Object::PropertyKind::Key)); Vector<String> animation_properties; Optional<JS::Value> all_value;
4ed5287792481fa6e032746cdf472ad75a589fc4
2024-01-13 05:46:19
Sam Atkins
solitaire: Hide solve button when game ends
false
Hide solve button when game ends
solitaire
diff --git a/Userland/Games/Solitaire/main.cpp b/Userland/Games/Solitaire/main.cpp index 86c0569d93cb..4d73afbd9851 100644 --- a/Userland/Games/Solitaire/main.cpp +++ b/Userland/Games/Solitaire/main.cpp @@ -100,6 +100,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) game.start_solving(); solve_button.set_enabled(false); }; + solve_button.set_enabled(false); auto& statusbar = *widget->find_descendant_of_type_named<GUI::Statusbar>("statusbar"); statusbar.set_text(0, "Score: 0"_string); @@ -126,8 +127,6 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) })); game.on_game_start = [&]() { - solve_button.set_enabled(false); - action_bar.set_visible(false); seconds_elapsed = 0; timer->start(); statusbar.set_text(2, "Time: 00:00"_string); @@ -141,6 +140,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) timer->stop(); solve_button.set_enabled(false); + action_bar.set_visible(false); if (reason == Solitaire::GameOverReason::Victory) { if (seconds_elapsed >= 30) {
eb83d2617caa437bfebdb00967bc71c760d1a3a5
2021-09-29 22:27:48
Sam Atkins
libweb: Use a CSSRuleList inside CSSStyleSheet
false
Use a CSSRuleList inside CSSStyleSheet
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.h b/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.h index 3c701ae22813..68c1cf83b480 100644 --- a/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.h +++ b/Userland/Libraries/LibWeb/CSS/CSSStyleSheet.h @@ -10,6 +10,7 @@ #include <AK/TypeCasts.h> #include <LibWeb/CSS/CSSImportRule.h> #include <LibWeb/CSS/CSSRule.h> +#include <LibWeb/CSS/CSSRuleList.h> #include <LibWeb/CSS/StyleSheet.h> #include <LibWeb/Loader/Resource.h> @@ -28,8 +29,8 @@ class CSSStyleSheet final : public StyleSheet { virtual String type() const override { return "text/css"; } - const NonnullRefPtrVector<CSSRule>& rules() const { return m_rules; } - NonnullRefPtrVector<CSSRule>& rules() { return m_rules; } + CSSRuleList const& rules() const { return m_rules; } + CSSRuleList& rules() { return m_rules; } template<typename Callback> void for_each_effective_style_rule(Callback callback) const @@ -66,7 +67,7 @@ class CSSStyleSheet final : public StyleSheet { private: explicit CSSStyleSheet(NonnullRefPtrVector<CSSRule>); - NonnullRefPtrVector<CSSRule> m_rules; + CSSRuleList m_rules; }; } diff --git a/Userland/Libraries/LibWeb/Dump.cpp b/Userland/Libraries/LibWeb/Dump.cpp index 2e63a57bc49b..358c253b36af 100644 --- a/Userland/Libraries/LibWeb/Dump.cpp +++ b/Userland/Libraries/LibWeb/Dump.cpp @@ -523,7 +523,7 @@ void dump_sheet(StringBuilder& builder, CSS::StyleSheet const& sheet) { auto& css_stylesheet = verify_cast<CSS::CSSStyleSheet>(sheet); - builder.appendff("CSSStyleSheet{{{}}}: {} rule(s)\n", &sheet, css_stylesheet.rules().size()); + builder.appendff("CSSStyleSheet{{{}}}: {} rule(s)\n", &sheet, css_stylesheet.rules().length()); for (auto& rule : css_stylesheet.rules()) { dump_rule(builder, rule);
5339b54b5dbe9a26d4e20fb75f5ed20a7fcef495
2023-06-01 09:48:57
Jelle Raaijmakers
libgfx: Improve glyph rendering speed for vector fonts
false
Improve glyph rendering speed for vector fonts
libgfx
diff --git a/Userland/Libraries/LibGfx/Painter.cpp b/Userland/Libraries/LibGfx/Painter.cpp index 39f7414308e8..7f28634f984d 100644 --- a/Userland/Libraries/LibGfx/Painter.cpp +++ b/Userland/Libraries/LibGfx/Painter.cpp @@ -1432,7 +1432,7 @@ FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Font const& f draw_scaled_bitmap(rect.to_rounded<int>(), *glyph.bitmap(), glyph.bitmap()->rect(), 1.0f, ScalingMode::BilinearBlend); } else { blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color { - return pixel.multiply(color); + return color.with_alpha(pixel.alpha()); }); } }
7d055dd0394fc8e91a0006b12a75bc8180875aee
2021-06-30 18:31:25
Idan Horowitz
libjs: Optimize & Bring String.prototype.repeat closer to the spec
false
Optimize & Bring String.prototype.repeat closer to the spec
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp index a94608dbc1c4..ff2f6d673e97 100644 --- a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -167,21 +167,30 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::repeat) auto string = ak_string_from(vm, global_object); if (!string.has_value()) return {}; - if (!vm.argument_count()) - return js_string(vm, String::empty()); - auto count = vm.argument(0).to_integer_or_infinity(global_object); + + auto n = vm.argument(0).to_integer_or_infinity(global_object); if (vm.exception()) return {}; - if (count < 0) { + + if (n < 0) { vm.throw_exception<RangeError>(global_object, ErrorType::StringRepeatCountMustBe, "positive"); return {}; } - if (Value(count).is_infinity()) { + + if (Value(n).is_positive_infinity()) { vm.throw_exception<RangeError>(global_object, ErrorType::StringRepeatCountMustBe, "finite"); return {}; } + + if (n == 0) + return js_string(vm, String::empty()); + + // NOTE: This is an optimization, it is not required by the specification but it produces equivalent behaviour + if (string->is_empty()) + return js_string(vm, String::empty()); + StringBuilder builder; - for (size_t i = 0; i < count; ++i) + for (size_t i = 0; i < n; ++i) builder.append(*string); return js_string(vm, builder.to_string()); }
4cbec00c44d2c512dc055a063578e45e8f58aaa4
2022-07-26 05:23:41
Andreas Kling
libweb: Actually check if percentage used flex basis is definite
false
Actually check if percentage used flex basis is definite
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/ComputedValues.h b/Userland/Libraries/LibWeb/CSS/ComputedValues.h index b81c90da6176..d1554509c05f 100644 --- a/Userland/Libraries/LibWeb/CSS/ComputedValues.h +++ b/Userland/Libraries/LibWeb/CSS/ComputedValues.h @@ -98,8 +98,6 @@ struct TransformOrigin { struct FlexBasisData { CSS::FlexBasis type { CSS::FlexBasis::Auto }; Optional<CSS::LengthPercentage> length_percentage; - - bool is_definite() const { return type == CSS::FlexBasis::LengthPercentage; } }; struct ShadowData { diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp index a089dad29290..7909f9d0c9f7 100644 --- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.cpp @@ -599,8 +599,20 @@ void FlexFormattingContext::determine_flex_base_size_and_hypothetical_main_size( flex_item.flex_base_size = [&] { flex_item.used_flex_basis = used_flex_basis_for_item(flex_item); + flex_item.used_flex_basis_is_definite = [&](CSS::FlexBasisData const& flex_basis) -> bool { + if (flex_basis.type != CSS::FlexBasis::LengthPercentage) + return false; + if (flex_basis.length_percentage->is_auto()) + return false; + if (flex_basis.length_percentage->is_length()) + return true; + if (is_row_layout()) + return m_flex_container_state.has_definite_width(); + return m_flex_container_state.has_definite_height(); + }(flex_item.used_flex_basis); + // A. If the item has a definite used flex basis, that’s the flex base size. - if (flex_item.used_flex_basis.is_definite()) { + if (flex_item.used_flex_basis_is_definite) { return get_pixel_size(m_state, child_box, flex_item.used_flex_basis.length_percentage.value()); } @@ -987,7 +999,7 @@ void FlexFormattingContext::resolve_flexible_lengths() // https://drafts.csswg.org/css-flexbox-1/#definite-sizes // 1. If the flex container has a definite main size, then the post-flexing main sizes of its flex items are treated as definite. // 2. If a flex-item’s flex basis is definite, then its post-flexing main size is also definite. - if (has_definite_main_size(flex_container()) || flex_item->used_flex_basis.is_definite()) { + if (has_definite_main_size(flex_container()) || flex_item->used_flex_basis_is_definite) { set_has_definite_main_size(flex_item->box, true); } } diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h index 27e30c59888d..452149a384ad 100644 --- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h +++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h @@ -43,6 +43,7 @@ class FlexFormattingContext final : public FormattingContext { struct FlexItem { Box& box; CSS::FlexBasisData used_flex_basis {}; + bool used_flex_basis_is_definite { false }; float flex_base_size { 0 }; float hypothetical_main_size { 0 }; float hypothetical_cross_size { 0 };
8c05e78b6cb0d53cd9e08e3133dfa223fcd3e2dc
2020-05-31 02:31:36
AnotherTest
shell: Treat ^D as builtin_exit when not in a continuation
false
Treat ^D as builtin_exit when not in a continuation
shell
diff --git a/Shell/Shell.cpp b/Shell/Shell.cpp index e0098c8fe1f0..f1bcf6562029 100644 --- a/Shell/Shell.cpp +++ b/Shell/Shell.cpp @@ -1719,11 +1719,24 @@ bool Shell::read_single_line() auto line_result = editor->get_line(prompt()); if (line_result.is_error()) { - m_complete_line_builder.clear(); - m_should_continue = ContinuationRequest::Nothing; - m_should_break_current_command = false; - Core::EventLoop::current().quit(line_result.error() == Line::Editor::Error::Eof ? 0 : 1); - return false; + if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) { + // Pretend the user tried to execute builtin_exit() + // but only if there's no continuation. + if (m_should_continue == ContinuationRequest::Nothing) { + m_complete_line_builder.clear(); + run_command("exit"); + return read_single_line(); + } else { + // Ignore the Eof. + return true; + } + } else { + m_complete_line_builder.clear(); + m_should_continue = ContinuationRequest::Nothing; + m_should_break_current_command = false; + Core::EventLoop::current().quit(1); + return false; + } } auto& line = line_result.value();
a84e64ed226155b8364dd49b15fbb2546d255583
2023-05-12 09:17:36
Timothy Flynn
libweb: Implement fetching classic scripts using Fetch infrastructure
false
Implement fetching classic scripts using Fetch infrastructure
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.cpp index 64d0d11a2ba0..a19fda86e3e1 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.cpp @@ -19,7 +19,6 @@ #include <LibWeb/HTML/Scripting/Fetching.h> #include <LibWeb/Infra/CharacterTypes.h> #include <LibWeb/Infra/Strings.h> -#include <LibWeb/Loader/ResourceLoader.h> #include <LibWeb/MimeSniff/MimeType.h> namespace Web::HTML { @@ -48,6 +47,26 @@ void HTMLScriptElement::visit_edges(Cell::Visitor& visitor) visitor.visit(m_preparation_time_document.ptr()); } +void HTMLScriptElement::parse_attribute(DeprecatedFlyString const& name, DeprecatedString const& value) +{ + Base::parse_attribute(name, value); + + if (name == HTML::AttributeNames::crossorigin) + m_crossorigin = cors_setting_attribute_from_keyword(String::from_deprecated_string(value).release_value_but_fixme_should_propagate_errors()); + else if (name == HTML::AttributeNames::referrerpolicy) + m_referrer_policy = ReferrerPolicy::from_string(value); +} + +void HTMLScriptElement::did_remove_attribute(DeprecatedFlyString const& name) +{ + Base::did_remove_attribute(name); + + if (name == HTML::AttributeNames::crossorigin) + m_crossorigin = cors_setting_attribute_from_keyword({}); + else if (name == HTML::AttributeNames::referrerpolicy) + m_referrer_policy.clear(); +} + void HTMLScriptElement::begin_delaying_document_load_event(DOM::Document& document) { // https://html.spec.whatwg.org/multipage/scripting.html#concept-script-script @@ -265,25 +284,57 @@ void HTMLScriptElement::prepare_script() } } - // FIXME: 21. If el has a charset attribute, then let encoding be the result of getting an encoding from the value of the charset attribute. - // If el does not have a charset attribute, or if getting an encoding failed, then let encoding be el's node document's the encoding. + // 21. If el has a charset attribute, then let encoding be the result of getting an encoding from the value of the charset attribute. + // If el does not have a charset attribute, or if getting an encoding failed, then let encoding be el's node document's the encoding. + Optional<String> encoding; - // FIXME: 22. Let classic script CORS setting be the current state of el's crossorigin content attribute. + if (has_attribute(HTML::AttributeNames::charset)) { + auto charset = TextCodec::get_standardized_encoding(attribute(HTML::AttributeNames::charset)); + if (charset.has_value()) + encoding = String::from_utf8(*charset).release_value_but_fixme_should_propagate_errors(); + } - // FIXME: 23. Let module script credentials mode be the CORS settings attribute credentials mode for el's crossorigin content attribute. + if (!encoding.has_value()) { + auto document_encoding = document().encoding_or_default(); + encoding = String::from_deprecated_string(document_encoding).release_value_but_fixme_should_propagate_errors(); + } - // FIXME: 24. Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value. + VERIFY(encoding.has_value()); - // FIXME: 25. If el has an integrity attribute, then let integrity metadata be that attribute's value. - // Otherwise, let integrity metadata be the empty string. + // 22. Let classic script CORS setting be the current state of el's crossorigin content attribute. + auto classic_script_cors_setting = m_crossorigin; - // FIXME: 26. Let referrer policy be the current state of el's referrerpolicy content attribute. + // 23. Let module script credentials mode be the CORS settings attribute credentials mode for el's crossorigin content attribute. + auto module_script_credential_mode = cors_settings_attribute_credentials_mode(m_crossorigin); + + // FIXME: 24. Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value. - // FIXME: 27. Let parser metadata be "parser-inserted" if el is parser-inserted, and "not-parser-inserted" otherwise. + // 25. If el has an integrity attribute, then let integrity metadata be that attribute's value. + // Otherwise, let integrity metadata be the empty string. + String integrity_metadata; + if (has_attribute(HTML::AttributeNames::integrity)) { + auto integrity = attribute(HTML::AttributeNames::integrity); + integrity_metadata = String::from_deprecated_string(integrity).release_value_but_fixme_should_propagate_errors(); + } - // FIXME: 28. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce, - // integrity metadata is integrity metadata, parser metadata is parser metadata, - // credentials mode is module script credentials mode, and referrer policy is referrer policy. + // 26. Let referrer policy be the current state of el's referrerpolicy content attribute. + auto referrer_policy = m_referrer_policy; + + // 27. Let parser metadata be "parser-inserted" if el is parser-inserted, and "not-parser-inserted" otherwise. + auto parser_metadata = is_parser_inserted() + ? Fetch::Infrastructure::Request::ParserMetadata::ParserInserted + : Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted; + + // 28. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce, + // integrity metadata is integrity metadata, parser metadata is parser metadata, + // credentials mode is module script credentials mode, and referrer policy is referrer policy. + ScriptFetchOptions options { + .cryptographic_nonce = {}, // FIXME + .integrity_metadata = move(integrity_metadata), + .parser_metadata = parser_metadata, + .credentials_mode = module_script_credential_mode, + .referrer_policy = move(referrer_policy), + }; // 29. Let settings object be el's node document's relevant settings object. auto& settings_object = document().relevant_settings_object(); @@ -334,29 +385,25 @@ void HTMLScriptElement::prepare_script() // FIXME: 9. If el is currently render-blocking, then set options's render-blocking to true. // 10. Let onComplete given result be the following steps: - // NOTE: This is weaved into usages of onComplete below. It would be better if we set it up here. + OnFetchScriptComplete on_complete = [this](auto result) { + // 1. Mark as ready el given result. + if (result) + mark_as_ready(Result { *result }); + else + mark_as_ready(ResultState::Null {}); + }; // 11. Switch on el's type: // -> "classic" if (m_script_type == ScriptType::Classic) { // Fetch a classic script given url, settings object, options, classic script CORS setting, encoding, and onComplete. - - // FIXME: This is ad-hoc. - auto request = LoadRequest::create_for_url_on_page(url, document().page()); - auto resource = ResourceLoader::the().load_resource(Resource::Type::Generic, request); - set_resource(resource); + fetch_classic_script(*this, url, settings_object, move(options), classic_script_cors_setting, encoding.release_value(), move(on_complete)).release_value_but_fixme_should_propagate_errors(); } // -> "module" else if (m_script_type == ScriptType::Module) { // Fetch an external module script graph given url, settings object, options, and onComplete. // FIXME: Pass options. - fetch_external_module_script_graph(url, settings_object, [this](auto result) { - // 1. Mark as ready el given result. - if (!result) - mark_as_ready(ResultState::Null {}); - else - mark_as_ready(Result(*result)); - }); + fetch_external_module_script_graph(url, settings_object, move(on_complete)); } } @@ -505,34 +552,6 @@ void HTMLScriptElement::prepare_script() } } -void HTMLScriptElement::resource_did_load() -{ - // FIXME: This is all ad-hoc and needs work. - - auto data = resource()->encoded_data(); - - // If the resource has an explicit encoding (i.e from a HTTP Content-Type header) - // we have to re-encode it to UTF-8. - if (resource()->has_encoding()) { - if (auto codec = TextCodec::decoder_for(resource()->encoding().value()); codec.has_value()) { - data = codec->to_utf8(data).release_value_but_fixme_should_propagate_errors().to_deprecated_string().to_byte_buffer(); - } - } - - auto script = ClassicScript::create(resource()->url().to_deprecated_string(), data, document().relevant_settings_object(), AK::URL()); - - // When the chosen algorithm asynchronously completes, set the script's script to the result. At that time, the script is ready. - mark_as_ready(Result(script)); -} - -void HTMLScriptElement::resource_did_fail() -{ - m_failed_to_load = true; - dbgln("HONK! Failed to load script, but ready nonetheless."); - m_result = ResultState::Null {}; - mark_as_ready(m_result); -} - void HTMLScriptElement::inserted() { if (!is_parser_inserted()) { diff --git a/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.h b/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.h index 00ef52832438..3ad4359ebe35 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.h +++ b/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.h @@ -8,15 +8,14 @@ #include <AK/Function.h> #include <LibWeb/DOM/DocumentLoadEventDelayer.h> +#include <LibWeb/HTML/CORSSettingAttribute.h> #include <LibWeb/HTML/HTMLElement.h> #include <LibWeb/HTML/Scripting/Script.h> -#include <LibWeb/Loader/Resource.h> +#include <LibWeb/ReferrerPolicy/ReferrerPolicy.h> namespace Web::HTML { -class HTMLScriptElement final - : public HTMLElement - , public ResourceClient { +class HTMLScriptElement final : public HTMLElement { WEB_PLATFORM_OBJECT(HTMLScriptElement, HTMLElement); public: @@ -60,12 +59,12 @@ class HTMLScriptElement final virtual bool is_html_script_element() const override { return true; } - virtual void resource_did_load() override; - virtual void resource_did_fail() override; - virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override; virtual void visit_edges(Cell::Visitor&) override; + virtual void parse_attribute(DeprecatedFlyString const& name, DeprecatedString const& value) override; + virtual void did_remove_attribute(DeprecatedFlyString const&) override; + // https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element void prepare_script(); @@ -101,6 +100,12 @@ class HTMLScriptElement final // https://html.spec.whatwg.org/multipage/scripting.html#ready-to-be-parser-executed bool m_ready_to_be_parser_executed { false }; + // https://html.spec.whatwg.org/multipage/scripting.html#attr-script-crossorigin + CORSSettingAttribute m_crossorigin { CORSSettingAttribute::NoCORS }; + + // https://html.spec.whatwg.org/multipage/scripting.html#attr-script-referrerpolicy + Optional<ReferrerPolicy::ReferrerPolicy> m_referrer_policy; + bool m_failed_to_load { false }; enum class ScriptType { diff --git a/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.idl b/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.idl index 8b6c73ae8981..f4f4449bdef0 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.idl +++ b/Userland/Libraries/LibWeb/HTML/HTMLScriptElement.idl @@ -10,7 +10,9 @@ interface HTMLScriptElement : HTMLElement { [CEReactions, Reflect] attribute DOMString type; [CEReactions, Reflect=nomodule] attribute boolean noModule; [CEReactions, Reflect] attribute boolean defer; + [CEReactions, Reflect=crossorigin] attribute DOMString? crossOrigin; [CEReactions, Reflect] attribute DOMString integrity; + [CEReactions, Reflect=referrerpolicy] attribute DOMString referrerPolicy; static boolean supports(DOMString type);
729349ce787eaadb105fba9cdaea7c89a692a12d
2021-12-13 02:21:08
Jelle Raaijmakers
libgl: Implement `GL_STENCIL_TEST`
false
Implement `GL_STENCIL_TEST`
libgl
diff --git a/Userland/Libraries/LibGL/GL/gl.h b/Userland/Libraries/LibGL/GL/gl.h index 2be8dc296c7a..de29dc04aecd 100644 --- a/Userland/Libraries/LibGL/GL/gl.h +++ b/Userland/Libraries/LibGL/GL/gl.h @@ -57,6 +57,7 @@ extern "C" { #define GL_CULL_FACE 0x0B44 #define GL_FOG 0x0B60 #define GL_DEPTH_TEST 0x0B71 +#define GL_STENCIL_TEST 0x0B90 #define GL_POLYGON_OFFSET_FILL 0x8037 // Alpha testing diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.cpp b/Userland/Libraries/LibGL/SoftwareGLContext.cpp index efb526cf1e2b..4e751bbbe6d7 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.cpp +++ b/Userland/Libraries/LibGL/SoftwareGLContext.cpp @@ -574,6 +574,9 @@ void SoftwareGLContext::gl_enable(GLenum capability) rasterizer_options.scissor_enabled = true; update_rasterizer_options = true; break; + case GL_STENCIL_TEST: + m_stencil_test_enabled = true; + break; case GL_TEXTURE_1D: m_active_texture_unit->set_texture_1d_enabled(true); break; @@ -630,6 +633,9 @@ void SoftwareGLContext::gl_disable(GLenum capability) rasterizer_options.scissor_enabled = false; update_rasterizer_options = true; break; + case GL_STENCIL_TEST: + m_stencil_test_enabled = false; + break; case GL_TEXTURE_1D: m_active_texture_unit->set_texture_1d_enabled(false); break; @@ -669,6 +675,8 @@ GLboolean SoftwareGLContext::gl_is_enabled(GLenum capability) return rasterizer_options.fog_enabled; case GL_SCISSOR_TEST: return rasterizer_options.scissor_enabled; + case GL_STENCIL_TEST: + return m_stencil_test_enabled; } RETURN_VALUE_WITH_ERROR_IF(true, GL_INVALID_ENUM, 0); @@ -1554,6 +1562,9 @@ void SoftwareGLContext::gl_get_booleanv(GLenum pname, GLboolean* data) case GL_CULL_FACE: *data = m_cull_faces ? GL_TRUE : GL_FALSE; break; + case GL_STENCIL_TEST: + *data = m_stencil_test_enabled ? GL_TRUE : GL_FALSE; + break; case GL_TEXTURE_1D: *data = m_active_texture_unit->texture_1d_enabled() ? GL_TRUE : GL_FALSE; break; diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.h b/Userland/Libraries/LibGL/SoftwareGLContext.h index 6bc51700b38e..4eec2aeb46e5 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.h +++ b/Userland/Libraries/LibGL/SoftwareGLContext.h @@ -164,6 +164,8 @@ class SoftwareGLContext : public GLContext { GLenum m_alpha_test_func = GL_ALWAYS; GLclampf m_alpha_test_ref_value = 0; + bool m_stencil_test_enabled { false }; + GLenum m_current_read_buffer = GL_BACK; GLenum m_current_draw_buffer = GL_BACK;
8a3ca6416d3efeff890b9bdf4ed9782bd17f7f6c
2022-10-06 18:59:38
Andreas Kling
libweb: Make labels be `display: inline-block` in the default UA style
false
Make labels be `display: inline-block` in the default UA style
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Default.css b/Userland/Libraries/LibWeb/CSS/Default.css index ec6ad645a830..f2b417295fac 100644 --- a/Userland/Libraries/LibWeb/CSS/Default.css +++ b/Userland/Libraries/LibWeb/CSS/Default.css @@ -20,6 +20,11 @@ blink { display: inline; } +/* FIXME: This doesn't seem right. */ +label { + display: inline-block; +} + /* FIXME: This is a temporary hack until we can render a native-looking frame for these. */ input, textarea { border: 1px solid -libweb-palette-threed-shadow1;
9fdcede49151b47edca95e4fc0bb8fdada01b794
2019-07-09 18:34:43
Andreas Kling
kernel: Move PIC.cpp into Arch/i386/
false
Move PIC.cpp into Arch/i386/
kernel
diff --git a/Kernel/PIC.cpp b/Kernel/Arch/i386/PIC.cpp similarity index 96% rename from Kernel/PIC.cpp rename to Kernel/Arch/i386/PIC.cpp index 124ca249743d..ae0d48ff0546 100644 --- a/Kernel/PIC.cpp +++ b/Kernel/Arch/i386/PIC.cpp @@ -1,8 +1,8 @@ -#include "PIC.h" -#include "Assertions.h" -#include "IO.h" +#include <AK/Assertions.h> #include <AK/Types.h> #include <Kernel/Arch/i386/CPU.h> +#include <Kernel/Arch/i386/PIC.h> +#include <Kernel/IO.h> // The slave 8259 is connected to the master's IRQ2 line. // This is really only to enhance clarity. @@ -109,3 +109,4 @@ u16 get_irr() } } + diff --git a/Kernel/PIC.h b/Kernel/Arch/i386/PIC.h similarity index 100% rename from Kernel/PIC.h rename to Kernel/Arch/i386/PIC.h diff --git a/Kernel/Devices/KeyboardDevice.cpp b/Kernel/Devices/KeyboardDevice.cpp index 523de6020578..3659c2165bee 100644 --- a/Kernel/Devices/KeyboardDevice.cpp +++ b/Kernel/Devices/KeyboardDevice.cpp @@ -1,10 +1,10 @@ -#include "IO.h" -#include "PIC.h" #include <AK/Assertions.h> #include <AK/Types.h> #include <Kernel/Arch/i386/CPU.h> +#include <Kernel/Arch/i386/PIC.h> #include <Kernel/Devices/KeyboardDevice.h> #include <Kernel/TTY/VirtualConsole.h> +#include <Kernel/IO.h> //#define KEYBOARD_DEBUG diff --git a/Kernel/IRQHandler.cpp b/Kernel/IRQHandler.cpp index ea2caa4ebffc..6477b0330aaf 100644 --- a/Kernel/IRQHandler.cpp +++ b/Kernel/IRQHandler.cpp @@ -1,6 +1,6 @@ #include "IRQHandler.h" -#include "PIC.h" #include <Kernel/Arch/i386/CPU.h> +#include <Kernel/Arch/i386/PIC.h> IRQHandler::IRQHandler(u8 irq) : m_irq_number(irq) diff --git a/Kernel/Makefile b/Kernel/Makefile index f4923e2b12fe..129c5d71fe0c 100644 --- a/Kernel/Makefile +++ b/Kernel/Makefile @@ -10,7 +10,7 @@ KERNEL_OBJS = \ i8253.o \ Devices/KeyboardDevice.o \ CMOS.o \ - PIC.o \ + Arch/i386/PIC.o \ Syscall.o \ Devices/IDEDiskDevice.o \ VM/MemoryManager.o \ diff --git a/Kernel/i8253.cpp b/Kernel/i8253.cpp index 38a401a7cd4e..ab91e192be8a 100644 --- a/Kernel/i8253.cpp +++ b/Kernel/i8253.cpp @@ -1,8 +1,8 @@ -#include "i8253.h" -#include "IO.h" -#include "PIC.h" -#include "Scheduler.h" #include <Kernel/Arch/i386/CPU.h> +#include <Kernel/Arch/i386/PIC.h> +#include <Kernel/i8253.h> +#include <Kernel/IO.h> +#include <Kernel/Scheduler.h> #define IRQ_TIMER 0 diff --git a/Kernel/init.cpp b/Kernel/init.cpp index 48b9b0815a2d..d0696845ca59 100644 --- a/Kernel/init.cpp +++ b/Kernel/init.cpp @@ -1,5 +1,4 @@ #include "KSyms.h" -#include "PIC.h" #include "Process.h" #include "RTC.h" #include "Scheduler.h" @@ -7,6 +6,7 @@ #include "kmalloc.h" #include <AK/Types.h> #include <Kernel/Arch/i386/CPU.h> +#include <Kernel/Arch/i386/PIC.h> #include <Kernel/Devices/BXVGADevice.h> #include <Kernel/Devices/DebugLogDevice.h> #include <Kernel/Devices/DiskPartition.h>
dd7eb3d6d8f61549fbd2c3e80cf0b08757c4d3dd
2022-02-26 00:08:31
Andreas Kling
ak: Add String::split_view(Function<bool(char)>)
false
Add String::split_view(Function<bool(char)>)
ak
diff --git a/AK/String.cpp b/AK/String.cpp index 7eeb97cc8e16..1e18bca9a25f 100644 --- a/AK/String.cpp +++ b/AK/String.cpp @@ -7,6 +7,7 @@ #include <AK/ByteBuffer.h> #include <AK/FlyString.h> #include <AK/Format.h> +#include <AK/Function.h> #include <AK/Memory.h> #include <AK/StdLibExtras.h> #include <AK/String.h> @@ -123,7 +124,7 @@ Vector<String> String::split_limit(char separator, size_t limit, bool keep_empty return v; } -Vector<StringView> String::split_view(const char separator, bool keep_empty) const +Vector<StringView> String::split_view(Function<bool(char)> separator, bool keep_empty) const { if (is_empty()) return {}; @@ -132,7 +133,7 @@ Vector<StringView> String::split_view(const char separator, bool keep_empty) con size_t substart = 0; for (size_t i = 0; i < length(); ++i) { char ch = characters()[i]; - if (ch == separator) { + if (separator(ch)) { size_t sublen = i - substart; if (sublen != 0 || keep_empty) v.append(substring_view(substart, sublen)); @@ -145,6 +146,11 @@ Vector<StringView> String::split_view(const char separator, bool keep_empty) con return v; } +Vector<StringView> String::split_view(const char separator, bool keep_empty) const +{ + return split_view([separator](char ch) { return ch == separator; }, keep_empty); +} + ByteBuffer String::to_byte_buffer() const { if (!m_impl) diff --git a/AK/String.h b/AK/String.h index 1449f7e1273d..f7626d07e9dd 100644 --- a/AK/String.h +++ b/AK/String.h @@ -150,6 +150,7 @@ class String { [[nodiscard]] Vector<String> split_limit(char separator, size_t limit, bool keep_empty = false) const; [[nodiscard]] Vector<String> split(char separator, bool keep_empty = false) const; [[nodiscard]] Vector<StringView> split_view(char separator, bool keep_empty = false) const; + [[nodiscard]] Vector<StringView> split_view(Function<bool(char)> separator, bool keep_empty = false) const; [[nodiscard]] Optional<size_t> find(char needle, size_t start = 0) const { return StringUtils::find(*this, needle, start); } [[nodiscard]] Optional<size_t> find(StringView needle, size_t start = 0) const { return StringUtils::find(*this, needle, start); }
0389f01cc8bf7436158e8b48746ed129f68493ca
2024-04-16 23:20:45
Andreas Kling
libweb: Make document.createEvent("hashchangeevent") produce right type
false
Make document.createEvent("hashchangeevent") produce right type
libweb
diff --git a/Tests/LibWeb/Text/expected/DOM/createEvent-hashchangeevent.txt b/Tests/LibWeb/Text/expected/DOM/createEvent-hashchangeevent.txt new file mode 100644 index 000000000000..8ebc2fc8fbc4 --- /dev/null +++ b/Tests/LibWeb/Text/expected/DOM/createEvent-hashchangeevent.txt @@ -0,0 +1 @@ +[object HashChangeEvent] diff --git a/Tests/LibWeb/Text/input/DOM/createEvent-hashchangeevent.html b/Tests/LibWeb/Text/input/DOM/createEvent-hashchangeevent.html new file mode 100644 index 000000000000..43c851a4a2d3 --- /dev/null +++ b/Tests/LibWeb/Text/input/DOM/createEvent-hashchangeevent.html @@ -0,0 +1,7 @@ +<script src="../include.js"></script> +<script> + test(() => { + let e = document.createEvent("hashchangeevent"); + println(e); + }); +</script> diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 1885cee12a3f..4cf2976d474c 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -1624,7 +1624,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Event>> Document::create_event(StringView i } else if (Infra::is_ascii_case_insensitive_match(interface, "focusevent"sv)) { event = UIEvents::FocusEvent::create(realm, FlyString {}); } else if (Infra::is_ascii_case_insensitive_match(interface, "hashchangeevent"sv)) { - event = Event::create(realm, FlyString {}); // FIXME: Create HashChangeEvent + event = HTML::HashChangeEvent::create(realm, FlyString {}, {}); } else if (Infra::is_ascii_case_insensitive_match(interface, "htmlevents"sv)) { event = Event::create(realm, FlyString {}); } else if (Infra::is_ascii_case_insensitive_match(interface, "keyboardevent"sv)) {
71bc9bee0a556e612539fa47424a7e8685875eaa
2021-11-25 03:37:31
Andreas Kling
libcore: Add syscall wrapper for pipe2()
false
Add syscall wrapper for pipe2()
libcore
diff --git a/Userland/Libraries/LibCore/System.cpp b/Userland/Libraries/LibCore/System.cpp index a3d4c1bf3d4e..ab7be608f41b 100644 --- a/Userland/Libraries/LibCore/System.cpp +++ b/Userland/Libraries/LibCore/System.cpp @@ -40,6 +40,14 @@ ErrorOr<void> unveil(StringView path, StringView permissions) int rc = syscall(SC_unveil, &params); HANDLE_SYSCALL_RETURN_VALUE("unveil"sv, rc, {}); } + +ErrorOr<Array<int, 2>> pipe2(int flags) +{ + Array<int, 2> fds; + if (::pipe2(fds.data(), flags) < 0) + return Error::from_syscall("pipe2"sv, -errno); + return fds; +} #endif ErrorOr<void> sigaction(int signal, struct sigaction const* action, struct sigaction* old_action) diff --git a/Userland/Libraries/LibCore/System.h b/Userland/Libraries/LibCore/System.h index 140da81ebb6d..70300ceffa1b 100644 --- a/Userland/Libraries/LibCore/System.h +++ b/Userland/Libraries/LibCore/System.h @@ -15,6 +15,7 @@ namespace Core::System { #ifdef __serenity__ ErrorOr<void> pledge(StringView promises, StringView execpromises); ErrorOr<void> unveil(StringView path, StringView permissions); +ErrorOr<Array<int, 2>> pipe2(int flags); #endif ErrorOr<void> sigaction(int signal, struct sigaction const* action, struct sigaction* old_action);
be1075e673e7a431b7b6e9a1bc4d48a86b89e672
2024-07-15 16:13:50
Aliaksandr Kalenik
libweb: Support radial gradient with asymmetrical size in Skia painter
false
Support radial gradient with asymmetrical size in Skia painter
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/DisplayListPlayerSkia.cpp b/Userland/Libraries/LibWeb/Painting/DisplayListPlayerSkia.cpp index ca850836c82b..5f1214e4c9ab 100644 --- a/Userland/Libraries/LibWeb/Painting/DisplayListPlayerSkia.cpp +++ b/Userland/Libraries/LibWeb/Painting/DisplayListPlayerSkia.cpp @@ -1143,8 +1143,14 @@ CommandResult DisplayListPlayerSkia::paint_radial_gradient(PaintRadialGradient c auto const& rect = command.rect; auto center = to_skia_point(command.center.translated(command.rect.location())); - auto radius = command.size.height(); - auto shader = SkGradientShader::MakeRadial(center, radius, colors.data(), positions.data(), positions.size(), SkTileMode::kClamp, 0); + + auto const size = command.size.to_type<float>(); + SkMatrix matrix; + // Skia does not support specifying of horizontal and vertical radius's separately, + // so instead we apply scale matrix + matrix.setScale(size.width() / size.height(), 1.0f, center.x(), center.y()); + + auto shader = SkGradientShader::MakeRadial(center, size.height(), colors.data(), positions.data(), positions.size(), SkTileMode::kClamp, 0, &matrix); SkPaint paint; paint.setShader(shader);
fcdd7aa99099976f9e83ff0339a37db82a849806
2021-09-01 17:06:26
Andrew Kaster
kernel: Only unlock Mutex once in execve when PT_TRACE_ME is enabled
false
Only unlock Mutex once in execve when PT_TRACE_ME is enabled
kernel
diff --git a/Kernel/Syscalls/execve.cpp b/Kernel/Syscalls/execve.cpp index 4002e0d27937..a8b8f7e7a578 100644 --- a/Kernel/Syscalls/execve.cpp +++ b/Kernel/Syscalls/execve.cpp @@ -628,8 +628,11 @@ KResult Process::do_exec(NonnullRefPtr<FileDescription> main_program_description // Make sure we release the ptrace lock here or the tracer will block forever. ptrace_locker.unlock(); Thread::current()->send_urgent_signal_to_self(SIGSTOP); + } else { + // Unlock regardless before disabling interrupts. + // Ensure we always unlock after checking ptrace status to avoid TOCTOU ptrace issues + ptrace_locker.unlock(); } - ptrace_locker.unlock(); // unlock before disabling interrupts as well // We enter a critical section here because we don't want to get interrupted between do_exec() // and Processor::assume_context() or the next context switch.
1bb4e5c4288dec5116f3938e5eb7816bba181759
2023-05-27 09:17:54
Andreas Kling
libweb: Support fit-content width for block-level boxes
false
Support fit-content width for block-level boxes
libweb
diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/block-with-fit-content-width.txt b/Tests/LibWeb/Layout/expected/block-and-inline/block-with-fit-content-width.txt new file mode 100644 index 000000000000..36f65eca7752 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/block-and-inline/block-with-fit-content-width.txt @@ -0,0 +1,10 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (1,1) content-size 798x37.46875 [BFC] children: not-inline + BlockContainer <body> at (10,10) content-size 780x19.46875 children: not-inline + BlockContainer <div.box> at (11,11) content-size 138.28125x17.46875 children: inline + line 0 width: 138.28125, height: 17.46875, bottom: 17.46875, baseline: 13.53125 + frag 0 from TextNode start: 0, length: 18, rect: [11,11 138.28125x17.46875] + "Well hello friends" + TextNode <#text> + BlockContainer <(anonymous)> at (10,29.46875) content-size 780x0 children: inline + TextNode <#text> diff --git a/Tests/LibWeb/Layout/input/block-and-inline/block-with-fit-content-width.html b/Tests/LibWeb/Layout/input/block-and-inline/block-with-fit-content-width.html new file mode 100644 index 000000000000..9faaaa289812 --- /dev/null +++ b/Tests/LibWeb/Layout/input/block-and-inline/block-with-fit-content-width.html @@ -0,0 +1,8 @@ +<!doctype html><style> +* { border: 1px solid black; } +.box { + background: pink; + display: block; + width: fit-content; +} +</style><div class="box">Well hello friends</div> diff --git a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp index 638300eb23ef..3a7cefe45778 100644 --- a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp @@ -1347,6 +1347,9 @@ CSS::Length FormattingContext::calculate_inner_width(Layout::Box const& box, Ava if (width.is_auto()) { return width.resolved(box, width_of_containing_block_as_length_for_resolve); } + if (width.is_fit_content()) { + return CSS::Length::make_px(calculate_fit_content_width(box, AvailableSpace { available_width, AvailableSize::make_indefinite() })); + } auto& computed_values = box.computed_values(); if (computed_values.box_sizing() == CSS::BoxSizing::BorderBox) {
3e4b1056b5db8d1855b8dd0302e910bdb389982c
2025-01-30 20:30:16
Sam Atkins
libweb: Consistently use navigables for WebDriver BiDi
false
Consistently use navigables for WebDriver BiDi
libweb
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp index f4cda2663e62..8faedbd21aee 100644 --- a/Libraries/LibWeb/DOM/Document.cpp +++ b/Libraries/LibWeb/DOM/Document.cpp @@ -3986,7 +3986,7 @@ void Document::abort() // 3. If document's during-loading navigation ID for WebDriver BiDi is non-null, then: if (m_navigation_id.has_value()) { - // 1. FIXME: Invoke WebDriver BiDi navigation aborted with document's browsing context, + // 1. FIXME: Invoke WebDriver BiDi navigation aborted with document's node navigable, // and new WebDriver BiDi navigation status whose whose id is document's navigation id, // status is "canceled", and url is document's URL. diff --git a/Libraries/LibWeb/HTML/Navigable.cpp b/Libraries/LibWeb/HTML/Navigable.cpp index 6a4c233eb1b4..b979f238cec2 100644 --- a/Libraries/LibWeb/HTML/Navigable.cpp +++ b/Libraries/LibWeb/HTML/Navigable.cpp @@ -1161,13 +1161,10 @@ WebIDL::ExceptionOr<void> Navigable::populate_session_history_entry_document( if (!navigation_params.has<NullOrError>()) VERIFY(navigation_params.has<GC::Ref<NavigationParams>>() && navigation_params.get<GC::Ref<NavigationParams>>()->response); - // 3. Let currentBrowsingContext be navigable's active browsing context. - [[maybe_unused]] auto current_browsing_context = active_browsing_context(); - - // 4. Let documentResource be entry's document state's resource. + // 3. Let documentResource be entry's document state's resource. auto document_resource = entry->document_state()->resource(); - // 5. If navigationParams is null, then: + // 4. If navigationParams is null, then: if (navigation_params.has<NullOrError>()) { // 1. If documentResource is a string, then set navigationParams to the result // of creating navigation params from a srcdoc resource given entry, navigable, @@ -1208,7 +1205,7 @@ WebIDL::ExceptionOr<void> Navigable::populate_session_history_entry_document( if (!active_window()) return {}; - // 6. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps: + // 5. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps: queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), GC::create_function(heap(), [this, entry, navigation_params = move(navigation_params), navigation_id, user_involvement, completion_steps]() mutable { // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed. if (has_been_destroyed()) @@ -1276,7 +1273,7 @@ WebIDL::ExceptionOr<void> Navigable::populate_session_history_entry_document( // 4. If navigationParams is not null, then: if (!navigation_params.has<NullOrError>()) { // FIXME: 1. Run the environment discarding steps for navigationParams's reserved environment. - // FIXME: 2. Invoke WebDriver BiDi navigation failed with currentBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is navigationParams's response's URL. + // FIXME: 2. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is navigationParams's response's URL. } } // FIXME: 5. Otherwise, if navigationParams's response has a `Content-Disposition` @@ -1383,11 +1380,11 @@ WebIDL::ExceptionOr<void> Navigable::navigate(NavigateParams params) // Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to continue these steps. // 8. If navigable's active document's unload counter is greater than 0, - // then invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId, - // status is "canceled", and url is url, and return. + // then invoke WebDriver BiDi navigation failed with navigable and a WebDriver BiDi navigation status whose id + // is navigationId, status is "canceled", and url is url, and return. if (active_document.unload_counter() > 0) { - // FIXME: invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId, - // status is "canceled", and url is url + // FIXME: invoke WebDriver BiDi navigation failed with navigable and a WebDriver BiDi navigation status whose id + // is navigationId, status is "canceled", and url is url return {}; } @@ -1443,26 +1440,23 @@ WebIDL::ExceptionOr<void> Navigable::navigate(NavigateParams params) if (parent() != nullptr) set_delaying_load_events(true); - // 15. Let targetBrowsingContext be navigable's active browsing context. - [[maybe_unused]] auto target_browsing_context = active_browsing_context(); - - // 16. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable. - auto target_snapshot_params = snapshot_target_snapshot_params(); + // 15. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable. + [[maybe_unused]] auto target_snapshot_params = snapshot_target_snapshot_params(); - // FIXME: 17. Invoke WebDriver BiDi navigation started with targetBrowsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is url, and status is "pending". + // FIXME: 16. Invoke WebDriver BiDi navigation started with navigable and a new WebDriver BiDi navigation status whose id is navigationId, status is "pending", and url is url. - // 18. If navigable's ongoing navigation is "traversal", then: + // 17. If navigable's ongoing navigation is "traversal", then: if (ongoing_navigation().has<Traversal>()) { - // FIXME: 1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url. + // FIXME: 1. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url. // 2. Return. return {}; } - // 19. Set the ongoing navigation for navigable to navigationId. + // 18. Set the ongoing navigation for navigable to navigationId. set_ongoing_navigation(navigation_id); - // 20. If url's scheme is "javascript", then: + // 19. If url's scheme is "javascript", then: if (url.scheme() == "javascript"sv) { // 1. Queue a global task on the navigation and traversal task source given navigable's active window to navigate to a javascript: URL given navigable, url, historyHandling, initiatorOriginSnapshot, userInvolvement, and cspNavigationType. VERIFY(active_window()); @@ -1474,7 +1468,7 @@ WebIDL::ExceptionOr<void> Navigable::navigate(NavigateParams params) return {}; } - // 21. If all of the following are true: + // 20. If all of the following are true: // - userInvolvement is not "browser UI"; // - navigable's active document's origin is same origin-domain with sourceDocument's origin; // - navigable's active document's is initial about:blank is false; and @@ -1522,7 +1516,7 @@ WebIDL::ExceptionOr<void> Navigable::navigate(NavigateParams params) active_browsing_context()->page().client().page_did_start_loading(url, false); } - // 22. In parallel, run these steps: + // 21. In parallel, run these steps: Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap(), [this, source_snapshot_params, target_snapshot_params, csp_navigation_type, document_resource, url, navigation_id, referrer_policy, initiator_origin_snapshot, response, history_handling, initiator_base_url_snapshot, user_involvement] { // AD-HOC: Not in the spec but subsequent steps will fail if the navigable doesn't have an active window. if (!active_window()) { @@ -1535,7 +1529,7 @@ WebIDL::ExceptionOr<void> Navigable::navigate(NavigateParams params) // 2. If unloadPromptCanceled is true, or navigable's ongoing navigation is no longer navigationId, then: if (unload_prompt_canceled != TraversableNavigable::CheckIfUnloadingIsCanceledResult::Continue || !ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != navigation_id) { - // FIXME: 1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url. + // FIXME: 1. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url. // 2. Abort these steps. set_delaying_load_events(false); @@ -1696,7 +1690,7 @@ WebIDL::ExceptionOr<void> Navigable::navigate_to_a_fragment(URL::URL const& url, // 1. Finalize a same-document navigation given traversable, navigable, historyEntry, entryToReplace, historyHandling, and userInvolvement. finalize_a_same_document_navigation(*traversable, *this, history_entry, entry_to_replace, history_handling, user_involvement); - // FIXME: 2. Invoke WebDriver BiDi fragment navigated with navigable's active browsing context and a new WebDriver BiDi + // FIXME: 2. Invoke WebDriver BiDi fragment navigated with navigable and a new WebDriver BiDi // navigation status whose id is navigationId, url is url, and status is "complete". (void)navigation_id; }));
f9bed651300642f910835833ea47d797edf1bdd1
2022-03-18 14:43:05
Brian Gianforcaro
soundplayer: Fix read of uninitialized member variables on startup
false
Fix read of uninitialized member variables on startup
soundplayer
diff --git a/Userland/Applications/SoundPlayer/Player.h b/Userland/Applications/SoundPlayer/Player.h index 7466be85f1f4..86c199cf9d70 100644 --- a/Userland/Applications/SoundPlayer/Player.h +++ b/Userland/Applications/SoundPlayer/Player.h @@ -86,9 +86,9 @@ class Player { private: Playlist m_playlist; - PlayState m_play_state; - LoopMode m_loop_mode; - ShuffleMode m_shuffle_mode; + PlayState m_play_state { PlayState::NoFileLoaded }; + LoopMode m_loop_mode { LoopMode::None }; + ShuffleMode m_shuffle_mode { ShuffleMode::None }; Audio::ConnectionFromClient& m_audio_client_connection; PlaybackManager m_playback_manager;
c7f3d72a6ab1b343f3b522e7ff07ceca6f74f7d8
2020-03-30 16:33:53
Tibor Nagy
hackstudio: Add an upscaled 32x32 icon to the About dialog
false
Add an upscaled 32x32 icon to the About dialog
hackstudio
diff --git a/Base/res/icons/32x32/app-hack-studio.png b/Base/res/icons/32x32/app-hack-studio.png new file mode 100644 index 000000000000..0d439cf5df2c Binary files /dev/null and b/Base/res/icons/32x32/app-hack-studio.png differ diff --git a/DevTools/HackStudio/main.cpp b/DevTools/HackStudio/main.cpp index e82a29578c5c..c02b908f4ea1 100644 --- a/DevTools/HackStudio/main.cpp +++ b/DevTools/HackStudio/main.cpp @@ -523,17 +523,15 @@ int main(int argc, char** argv) view_menu->add_action(remove_current_editor_action); menubar->add_menu(move(view_menu)); - auto small_icon = Gfx::Bitmap::load_from_file("/res/icons/16x16/app-hack-studio.png"); - auto help_menu = GUI::Menu::construct("Help"); help_menu->add_action(GUI::Action::create("About", [&](auto&) { - GUI::AboutDialog::show("HackStudio", small_icon, g_window); + GUI::AboutDialog::show("HackStudio", Gfx::Bitmap::load_from_file("/res/icons/32x32/app-hack-studio.png"), g_window); })); menubar->add_menu(move(help_menu)); app.set_menubar(move(menubar)); - g_window->set_icon(small_icon); + g_window->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-hack-studio.png")); g_window->show();
16830a60ec4972b5fd137ab42e2c8fb88285888e
2021-08-28 12:47:00
Simon Danner
libgui: Select common location on Filepicker startup
false
Select common location on Filepicker startup
libgui
diff --git a/Userland/Libraries/LibGUI/FilePicker.cpp b/Userland/Libraries/LibGUI/FilePicker.cpp index 0a33540b3f14..14a629a32fab 100644 --- a/Userland/Libraries/LibGUI/FilePicker.cpp +++ b/Userland/Libraries/LibGUI/FilePicker.cpp @@ -252,6 +252,7 @@ FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& filen } m_location_textbox->set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16)); + m_model->on_complete(); } FilePicker::~FilePicker()
3a2cc1aa2084a3a758418e96e5bc30403a1eff78
2024-11-21 17:46:08
Aliaksandr Kalenik
libweb: Allow custom properties in CSSStyleDeclaration.setProperty()
false
Allow custom properties in CSSStyleDeclaration.setProperty()
libweb
diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp b/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp index 56315c7aa4a4..c95524c7d6d7 100644 --- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp +++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.cpp @@ -102,8 +102,13 @@ Optional<StyleProperty> PropertyOwningCSSStyleDeclaration::property(PropertyID p } // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-setproperty -WebIDL::ExceptionOr<void> PropertyOwningCSSStyleDeclaration::set_property(PropertyID property_id, StringView value, StringView priority) +WebIDL::ExceptionOr<void> PropertyOwningCSSStyleDeclaration::set_property(StringView property_name, StringView value, StringView priority) { + auto maybe_property_id = property_id_from_string(property_name); + if (!maybe_property_id.has_value()) + return {}; + auto property_id = maybe_property_id.value(); + // 1. If the computed flag is set, then throw a NoModificationAllowedError exception. // NOTE: This is handled by the virtual override in ResolvedCSSStyleDeclaration. @@ -146,10 +151,22 @@ WebIDL::ExceptionOr<void> PropertyOwningCSSStyleDeclaration::set_property(Proper } // 9. Otherwise, else { - // let updated be the result of set the CSS declaration property with value component value list, - // with the important flag set if priority is not the empty string, and unset otherwise, - // and with the list of declarations being the declarations. - updated = set_a_css_declaration(property_id, *component_value_list, !priority.is_empty() ? Important::Yes : Important::No); + if (property_id == PropertyID::Custom) { + auto custom_name = FlyString::from_utf8_without_validation(property_name.bytes()); + StyleProperty style_property { + .important = !priority.is_empty() ? Important::Yes : Important::No, + .property_id = property_id, + .value = component_value_list.release_nonnull(), + .custom_name = custom_name, + }; + m_custom_properties.set(custom_name, style_property); + updated = true; + } else { + // let updated be the result of set the CSS declaration property with value component value list, + // with the important flag set if priority is not the empty string, and unset otherwise, + // and with the list of declarations being the declarations. + updated = set_a_css_declaration(property_id, *component_value_list, !priority.is_empty() ? Important::Yes : Important::No); + } } // 10. If updated is true, update style attribute for the CSS declaration block. @@ -291,12 +308,9 @@ StringView CSSStyleDeclaration::get_property_priority(StringView property_name) return maybe_property->important == Important::Yes ? "important"sv : ""sv; } -WebIDL::ExceptionOr<void> CSSStyleDeclaration::set_property(StringView property_name, StringView css_text, StringView priority) +WebIDL::ExceptionOr<void> CSSStyleDeclaration::set_property(PropertyID property_id, StringView css_text, StringView priority) { - auto property_id = property_id_from_string(property_name); - if (!property_id.has_value()) - return {}; - return set_property(property_id.value(), css_text, priority); + return set_property(string_from_property_id(property_id), css_text, priority); } WebIDL::ExceptionOr<String> CSSStyleDeclaration::remove_property(StringView property_name) diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h index 8fb18c23f066..be01254ad407 100644 --- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h +++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h @@ -30,10 +30,10 @@ class CSSStyleDeclaration virtual Optional<StyleProperty> property(PropertyID) const = 0; - virtual WebIDL::ExceptionOr<void> set_property(PropertyID, StringView css_text, StringView priority = ""sv) = 0; + virtual WebIDL::ExceptionOr<void> set_property(PropertyID, StringView css_text, StringView priority = ""sv); virtual WebIDL::ExceptionOr<String> remove_property(PropertyID) = 0; - virtual WebIDL::ExceptionOr<void> set_property(StringView property_name, StringView css_text, StringView priority); + virtual WebIDL::ExceptionOr<void> set_property(StringView property_name, StringView css_text, StringView priority) = 0; virtual WebIDL::ExceptionOr<String> remove_property(StringView property_name); String get_property_value(StringView property) const; @@ -76,7 +76,7 @@ class PropertyOwningCSSStyleDeclaration : public CSSStyleDeclaration { virtual Optional<StyleProperty> property(PropertyID) const override; - virtual WebIDL::ExceptionOr<void> set_property(PropertyID, StringView css_text, StringView priority) override; + virtual WebIDL::ExceptionOr<void> set_property(StringView property_name, StringView css_text, StringView priority) override; virtual WebIDL::ExceptionOr<String> remove_property(PropertyID) override; Vector<StyleProperty> const& properties() const { return m_properties; } diff --git a/Tests/LibWeb/Text/expected/css/CSSStyleDeclaration-custom-properties.txt b/Tests/LibWeb/Text/expected/css/CSSStyleDeclaration-custom-properties.txt new file mode 100644 index 000000000000..1e04124a3a23 --- /dev/null +++ b/Tests/LibWeb/Text/expected/css/CSSStyleDeclaration-custom-properties.txt @@ -0,0 +1 @@ +rgb(255, 0, 0) diff --git a/Tests/LibWeb/Text/input/css/CSSStyleDeclaration-custom-properties.html b/Tests/LibWeb/Text/input/css/CSSStyleDeclaration-custom-properties.html new file mode 100644 index 000000000000..51ba809f88dc --- /dev/null +++ b/Tests/LibWeb/Text/input/css/CSSStyleDeclaration-custom-properties.html @@ -0,0 +1,19 @@ +<!DOCTYPE html> +<script src="../include.js"></script> +<body></body> +<script> + test(() => { + const div = document.createElement('div'); + div.style.setProperty("--redcolor", "red"); + + const nested = document.createElement('div'); + nested.style["backgroundColor"] = "var(--redcolor)"; + nested.style["width"] = "100px"; + nested.style["height"] = "100px"; + div.appendChild(nested); + + document.body.appendChild(div); + + println(getComputedStyle(nested).backgroundColor); + }); +</script> \ No newline at end of file
e4a2bd7a44185bbf4bfc9b887132cde9e2a56c02
2023-07-15 13:53:33
Sam Atkins
libweb: Move RoundingMode to Enums.json
false
Move RoundingMode to Enums.json
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Enums.json b/Userland/Libraries/LibWeb/CSS/Enums.json index 090306c2e500..da2c619d9953 100644 --- a/Userland/Libraries/LibWeb/CSS/Enums.json +++ b/Userland/Libraries/LibWeb/CSS/Enums.json @@ -269,6 +269,12 @@ "round", "space" ], + "rounding-strategy": [ + "down", + "nearest", + "to-zero", + "up" + ], "text-align": [ "center", "justify", diff --git a/Userland/Libraries/LibWeb/CSS/Identifiers.json b/Userland/Libraries/LibWeb/CSS/Identifiers.json index fd822de39d92..052b876bd8b0 100644 --- a/Userland/Libraries/LibWeb/CSS/Identifiers.json +++ b/Userland/Libraries/LibWeb/CSS/Identifiers.json @@ -115,6 +115,7 @@ "distribute", "dotted", "double", + "down", "e-resize", "ease", "ease-in", @@ -202,6 +203,7 @@ "menulist-button", "n-resize", "ne-resize", + "nearest", "nesw-resize", "no-drop", "no-preference", @@ -307,6 +309,7 @@ "text-top", "thick", "thin", + "to-zero", "top", "textarea", "textfield", @@ -318,6 +321,7 @@ "ultra-expanded", "underline", "unsafe", + "up", "upper-alpha", "upper-latin", "upper-roman", diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index c4083b967bdd..895b59eec3ad 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -3923,25 +3923,23 @@ ErrorOr<OwnPtr<CalculationNode>> Parser::parse_round_function(Function const& fu OwnPtr<CalculationNode> node_a = nullptr; OwnPtr<CalculationNode> node_b = nullptr; - auto mode = CalculationNode::RoundingMode::Nearest; + auto strategy = RoundingStrategy::Nearest; if (parameters.size() == 3) { - auto rounding_mode_component = parameters[0][0]; - if (!rounding_mode_component.is(Token::Type::Ident)) { - dbgln_if(CSS_PARSER_DEBUG, "round() mode must be a string"sv); + auto rounding_strategy_component = parameters[0][0]; + if (!rounding_strategy_component.is(Token::Type::Ident)) { + dbgln_if(CSS_PARSER_DEBUG, "round() strategy must be an ident"sv); return nullptr; } - auto mode_string = rounding_mode_component.token().ident(); - if (mode_string.equals_ignoring_ascii_case("nearest"sv)) { - mode = CalculationNode::RoundingMode::Nearest; - } else if (mode_string.equals_ignoring_ascii_case("up"sv)) { - mode = CalculationNode::RoundingMode::Up; - } else if (mode_string.equals_ignoring_ascii_case("down"sv)) { - mode = CalculationNode::RoundingMode::Down; - } else if (mode_string.equals_ignoring_ascii_case("to-zero"sv)) { - mode = CalculationNode::RoundingMode::TowardZero; + auto maybe_value_id = value_id_from_string(rounding_strategy_component.token().ident()); + if (!maybe_value_id.has_value()) { + dbgln_if(CSS_PARSER_DEBUG, "round() strategy must be one of 'nearest', 'up', 'down', or 'to-zero'"sv); + return nullptr; + } + if (auto maybe_strategy = value_id_to_rounding_strategy(maybe_value_id.value()); maybe_strategy.has_value()) { + strategy = maybe_strategy.value(); } else { - dbgln_if(CSS_PARSER_DEBUG, "round() mode must be one of 'nearest', 'up', 'down', or 'to-zero'"sv); + dbgln_if(CSS_PARSER_DEBUG, "round() strategy must be one of 'nearest', 'up', 'down', or 'to-zero'"sv); return nullptr; } @@ -3976,7 +3974,7 @@ ErrorOr<OwnPtr<CalculationNode>> Parser::parse_round_function(Function const& fu return nullptr; } - return TRY(RoundCalculationNode::create(mode, node_a.release_nonnull(), node_b.release_nonnull())); + return TRY(RoundCalculationNode::create(strategy, node_a.release_nonnull(), node_b.release_nonnull())); } ErrorOr<OwnPtr<CalculationNode>> Parser::parse_mod_function(Function const& function) diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp b/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp index 8ebfd289e9f9..1a8053514545 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp @@ -1791,14 +1791,14 @@ ErrorOr<void> ExpCalculationNode::dump(StringBuilder& builder, int indent) const return {}; } -ErrorOr<NonnullOwnPtr<RoundCalculationNode>> RoundCalculationNode::create(RoundingMode mode, NonnullOwnPtr<CalculationNode> x, NonnullOwnPtr<CalculationNode> y) +ErrorOr<NonnullOwnPtr<RoundCalculationNode>> RoundCalculationNode::create(RoundingStrategy strategy, NonnullOwnPtr<CalculationNode> x, NonnullOwnPtr<CalculationNode> y) { - return adopt_nonnull_own_or_enomem(new (nothrow) RoundCalculationNode(mode, move(x), move(y))); + return adopt_nonnull_own_or_enomem(new (nothrow) RoundCalculationNode(strategy, move(x), move(y))); } -RoundCalculationNode::RoundCalculationNode(RoundingMode mode, NonnullOwnPtr<CalculationNode> x, NonnullOwnPtr<CalculationNode> y) +RoundCalculationNode::RoundCalculationNode(RoundingStrategy mode, NonnullOwnPtr<CalculationNode> x, NonnullOwnPtr<CalculationNode> y) : CalculationNode(Type::Round) - , m_mode(mode) + , m_strategy(mode) , m_x(move(x)) , m_y(move(y)) { @@ -1810,20 +1810,7 @@ ErrorOr<String> RoundCalculationNode::to_string() const { StringBuilder builder; builder.append("round("sv); - switch (m_mode) { - case RoundingMode::Nearest: - builder.append("nearest"sv); - break; - case RoundingMode::Up: - builder.append("up"sv); - break; - case RoundingMode::Down: - builder.append("down"sv); - break; - case RoundingMode::TowardZero: - builder.append("toward-zero"sv); - break; - } + builder.append(CSS::to_string(m_strategy)); builder.append(", "sv); builder.append(TRY(m_x->to_string())); builder.append(", "sv); @@ -1868,22 +1855,22 @@ CalculatedStyleValue::CalculationResult RoundCalculationNode::resolve(Optional<L auto upper_b = ceil(node_a_value / node_b_value) * node_b_value; auto lower_b = floor(node_a_value / node_b_value) * node_b_value; - if (m_mode == RoundingMode::Nearest) { + if (m_strategy == RoundingStrategy::Nearest) { auto upper_diff = fabs(upper_b - node_a_value); auto lower_diff = fabs(node_a_value - lower_b); auto rounded_value = upper_diff < lower_diff ? upper_b : lower_b; return to_resolved_type(resolved_type, rounded_value); } - if (m_mode == RoundingMode::Up) { + if (m_strategy == RoundingStrategy::Up) { return to_resolved_type(resolved_type, upper_b); } - if (m_mode == RoundingMode::Down) { + if (m_strategy == RoundingStrategy::Down) { return to_resolved_type(resolved_type, lower_b); } - if (m_mode == RoundingMode::TowardZero) { + if (m_strategy == RoundingStrategy::ToZero) { auto upper_diff = fabs(upper_b); auto lower_diff = fabs(lower_b); auto rounded_value = upper_diff < lower_diff ? upper_b : lower_b; diff --git a/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h index a580d7cfc9cd..601ee524c28d 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h @@ -130,14 +130,6 @@ class CalculationNode { MinusInfinity, }; - // https://drafts.csswg.org/css-values-4/#round-func - enum class RoundingMode { - Nearest, - Up, - Down, - TowardZero - }; - enum class Type { Numeric, // NOTE: Currently, any value with a `var()` or `attr()` function in it is always an @@ -699,7 +691,7 @@ class ExpCalculationNode final : public CalculationNode { class RoundCalculationNode final : public CalculationNode { public: - static ErrorOr<NonnullOwnPtr<RoundCalculationNode>> create(CalculationNode::RoundingMode, NonnullOwnPtr<CalculationNode>, NonnullOwnPtr<CalculationNode>); + static ErrorOr<NonnullOwnPtr<RoundCalculationNode>> create(RoundingStrategy, NonnullOwnPtr<CalculationNode>, NonnullOwnPtr<CalculationNode>); ~RoundCalculationNode(); virtual ErrorOr<String> to_string() const override; @@ -712,8 +704,8 @@ class RoundCalculationNode final : public CalculationNode { virtual ErrorOr<void> dump(StringBuilder&, int indent) const override; private: - RoundCalculationNode(RoundingMode, NonnullOwnPtr<CalculationNode>, NonnullOwnPtr<CalculationNode>); - CalculationNode::RoundingMode m_mode; + RoundCalculationNode(RoundingStrategy, NonnullOwnPtr<CalculationNode>, NonnullOwnPtr<CalculationNode>); + RoundingStrategy m_strategy; NonnullOwnPtr<CalculationNode> m_x; NonnullOwnPtr<CalculationNode> m_y; };
b59e9260db2f4aeda13b2628133e6377f2012e5a
2021-08-28 04:06:52
Linus Groh
libjs: Implement Temporal.ZonedDateTime.prototype.era
false
Implement Temporal.ZonedDateTime.prototype.era
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp index 51aef9e12e11..66b47aee665d 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp @@ -59,6 +59,7 @@ void ZonedDateTimePrototype::initialize(GlobalObject& global_object) define_native_accessor(vm.names.inLeapYear, in_leap_year_getter, {}, Attribute::Configurable); define_native_accessor(vm.names.offsetNanoseconds, offset_nanoseconds_getter, {}, Attribute::Configurable); define_native_accessor(vm.names.offset, offset_getter, {}, Attribute::Configurable); + define_native_accessor(vm.names.era, era_getter, {}, Attribute::Configurable); u8 attr = Attribute::Writable | Attribute::Configurable; define_native_function(vm.names.valueOf, value_of, 0, attr); @@ -704,6 +705,33 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::offset_getter) return js_string(vm, move(*offset_string)); } +// 15.6.10.2 get Temporal.ZonedDateTime.prototype.era, https://tc39.es/proposal-temporal/#sec-get-temporal.zoneddatetime.prototype.era +JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::era_getter) +{ + // 1. Let zonedDateTime be the this value. + // 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]). + auto* zoned_date_time = typed_this(global_object); + if (vm.exception()) + return {}; + + // 3. Let timeZone be zonedDateTime.[[TimeZone]]. + auto& time_zone = zoned_date_time->time_zone(); + + // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). + auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()); + + // 5. Let calendar be zonedDateTime.[[Calendar]]. + auto& calendar = zoned_date_time->calendar(); + + // 6. Let plainDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, calendar). + auto* plain_date_time = builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *instant, calendar); + if (vm.exception()) + return {}; + + // 7. Return ? CalendarEra(calendar, plainDateTime). + return calendar_era(global_object, calendar, *plain_date_time); +} + // 6.3.44 Temporal.ZonedDateTime.prototype.valueOf ( ), https://tc39.es/proposal-temporal/#sec-temporal.zoneddatetime.prototype.valueof JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::value_of) { diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h index e07769543be2..ad01316eeaa3 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.h @@ -45,6 +45,7 @@ class ZonedDateTimePrototype final : public Object { JS_DECLARE_NATIVE_FUNCTION(in_leap_year_getter); JS_DECLARE_NATIVE_FUNCTION(offset_nanoseconds_getter); JS_DECLARE_NATIVE_FUNCTION(offset_getter); + JS_DECLARE_NATIVE_FUNCTION(era_getter); JS_DECLARE_NATIVE_FUNCTION(value_of); JS_DECLARE_NATIVE_FUNCTION(to_instant); JS_DECLARE_NATIVE_FUNCTION(to_plain_date); diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/ZonedDateTime/ZonedDateTime.prototype.era.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/ZonedDateTime/ZonedDateTime.prototype.era.js new file mode 100644 index 000000000000..60beef255f50 --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/ZonedDateTime/ZonedDateTime.prototype.era.js @@ -0,0 +1,26 @@ +describe("correct behavior", () => { + test("basic functionality", () => { + const timeZone = new Temporal.TimeZone("UTC"); + const zonedDateTime = new Temporal.ZonedDateTime(1625614921000000000n, timeZone); + expect(zonedDateTime.era).toBeUndefined(); + }); + + test("calendar with custom era function", () => { + const timeZone = new Temporal.TimeZone("UTC"); + const calendar = { + era() { + return "foo"; + }, + }; + const zonedDateTime = new Temporal.ZonedDateTime(1625614921000000000n, timeZone, calendar); + expect(zonedDateTime.era).toBe("foo"); + }); +}); + +describe("errors", () => { + test("this value must be a Temporal.ZonedDateTime object", () => { + expect(() => { + Reflect.get(Temporal.ZonedDateTime.prototype, "era", "foo"); + }).toThrowWithMessage(TypeError, "Not a Temporal.ZonedDateTime"); + }); +});
edfef8e2f5e27be597642c0d6310521b96ee237d
2022-09-22 03:36:08
Linus Groh
everywhere: Rename WrapperGenerator to BindingsGenerator
false
Rename WrapperGenerator to BindingsGenerator
everywhere
diff --git a/AK/Debug.h.in b/AK/Debug.h.in index df8989659148..868faf037050 100644 --- a/AK/Debug.h.in +++ b/AK/Debug.h.in @@ -18,6 +18,10 @@ #cmakedefine01 BMP_DEBUG #endif +#ifndef BINDINGS_GENERATOR_DEBUG +#cmakedefine01 BINDINGS_GENERATOR_DEBUG +#endif + #ifndef CACHE_DEBUG #cmakedefine01 CACHE_DEBUG #endif @@ -502,10 +506,6 @@ #cmakedefine01 WINDOWMANAGER_DEBUG #endif -#ifndef WRAPPER_GENERATOR_DEBUG -#cmakedefine01 WRAPPER_GENERATOR_DEBUG -#endif - #ifndef WSMESSAGELOOP_DEBUG #cmakedefine01 WSMESSAGELOOP_DEBUG #endif diff --git a/Documentation/Browser/AddNewIDLFile.md b/Documentation/Browser/AddNewIDLFile.md index 7a59a3450058..7f9609d5d85b 100644 --- a/Documentation/Browser/AddNewIDLFile.md +++ b/Documentation/Browser/AddNewIDLFile.md @@ -28,7 +28,7 @@ interface CSSRule { - `#include <LibWeb/Bindings/HTMLDetailsElementPrototype.h>` to the includes list. - `ADD_WINDOW_OBJECT_INTERFACE(HTMLDetailsElement) \` to the macro at the bottom. -4. Add a `libweb_js_wrapper(HTML/HTMLDetailsElement)` call to [`LibWeb/idl_files.cmake`](../../Userland/Libraries/LibWeb/idl_files.cmake) +4. Add a `libweb_js_bindings(HTML/HTMLDetailsElement)` call to [`LibWeb/idl_files.cmake`](../../Userland/Libraries/LibWeb/idl_files.cmake) 5. Forward declare the generated classes in [`LibWeb/Forward.h`](../../Userland/Libraries/LibWeb/Forward.h): - `HTMLDetailsElement` in its namespace. @@ -38,5 +38,5 @@ interface CSSRule { - It must inherit from `public RefCounted<HTMLDetailsElement>` and `public Bindings::Wrappable` - It must have a public `using WrapperType = Bindings::HTMLDetailsElementWrapper;` -8. If your type isn't an Event or Element, you will need to add it to [`is_wrappable_type()`](../../Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp) +8. If your type isn't an Event or Element, you will need to add it to [`is_wrappable_type()`](../../Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp) so that it can be accepted as an IDL parameter, attribute or return type. diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmake index 90924fbc338b..7af4b6e31a05 100644 --- a/Meta/CMake/all_the_debug_macros.cmake +++ b/Meta/CMake/all_the_debug_macros.cmake @@ -237,8 +237,8 @@ set(XML_PARSER_DEBUG ON) # set(DEBUG_STATUS_REGISTER ON) # False positive: DEFINE_DEBUG_REGISTER is used to define read/write methods for debug registers. # set(DEFINE_DEBUG_REGISTER ON) -# Clogs up build: The WrapperGenerator stuff is run at compile time. -# set(WRAPPER_GENERATOR_DEBUG ON) +# Clogs up build: The BindingsGenerator stuff is run at compile time. +# set(BINDINGS_GENERATOR_DEBUG ON) # Immediately finds violations during boot, shouldn't be discoverable by people who aren't working on fixing. # set(KMALLOC_VERIFY_NO_SPINLOCK_HELD ON) # False positive: CONSOLE_OUT_TO_BOCHS_DEBUG_PORT is a flag for ConsoleDevice, not a feature. diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmake index 967d0c9bbada..d4c0fec9cf5e 100644 --- a/Meta/CMake/libweb_generators.cmake +++ b/Meta/CMake/libweb_generators.cmake @@ -90,7 +90,7 @@ function (generate_css_implementation) endfunction() -function (generate_js_wrappers target) +function (generate_js_bindings target) if (CMAKE_CURRENT_BINARY_DIR MATCHES ".*/LibWeb") # Serenity build @@ -104,8 +104,8 @@ function (generate_js_wrappers target) SET(LIBWEB_META_PREFIX "Lagom") endif() - function(libweb_js_wrapper class) - cmake_parse_arguments(PARSE_ARGV 1 LIBWEB_WRAPPER "ITERABLE" "" "") + function(libweb_js_bindings class) + cmake_parse_arguments(PARSE_ARGV 1 LIBWEB_BINDINGS "ITERABLE" "" "") get_filename_component(basename "${class}" NAME) set(BINDINGS_SOURCES "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}Constructor.h" @@ -120,8 +120,8 @@ function (generate_js_wrappers target) prototype-implementation ) - # FIXME: Instead of requiring a manual declaration of iterable wrappers, we should ask WrapperGenerator if it's iterable - if(LIBWEB_WRAPPER_ITERABLE) + # FIXME: Instead of requiring a manual declaration of iterable bindings, we should ask BindingsGenerator if it's iterable + if(LIBWEB_BINDINGS_ITERABLE) list(APPEND BINDINGS_SOURCES "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}IteratorPrototype.h" "${LIBWEB_OUTPUT_FOLDER}Bindings/${basename}IteratorPrototype.cpp" @@ -142,11 +142,11 @@ function (generate_js_wrappers target) list(TRANSFORM include_paths PREPEND -i) add_custom_command( OUTPUT "${bindings_src}" - COMMAND "$<TARGET_FILE:Lagom::WrapperGenerator>" "--${bindings_type}" ${include_paths} "${LIBWEB_INPUT_FOLDER}/${class}.idl" "${LIBWEB_INPUT_FOLDER}" > "${bindings_src}.tmp" + COMMAND "$<TARGET_FILE:Lagom::BindingsGenerator>" "--${bindings_type}" ${include_paths} "${LIBWEB_INPUT_FOLDER}/${class}.idl" "${LIBWEB_INPUT_FOLDER}" > "${bindings_src}.tmp" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${bindings_src}.tmp" "${bindings_src}" COMMAND "${CMAKE_COMMAND}" -E remove "${bindings_src}.tmp" VERBATIM - DEPENDS Lagom::WrapperGenerator + DEPENDS Lagom::BindingsGenerator MAIN_DEPENDENCY ${LIBWEB_INPUT_FOLDER}/${class}.idl ) endforeach() diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt index 09559b85f953..0fa1b4e62f79 100644 --- a/Meta/Lagom/CMakeLists.txt +++ b/Meta/Lagom/CMakeLists.txt @@ -292,7 +292,7 @@ lagom_lib(TimeZone timezone target_compile_definitions(LibTimeZone PRIVATE ENABLE_TIME_ZONE_DATA=$<BOOL:${ENABLE_TIME_ZONE_DATABASE_DOWNLOAD}>) # LibIDL -# This is used by the WrapperGenerator so needs to always be built. +# This is used by the BindingsGenerator so needs to always be built. file(GLOB LIBIDL_SOURCES CONFIGURE_DEPENDS "../../Userland/Libraries/LibIDL/*.cpp") lagom_lib(IDL idl SOURCES ${LIBIDL_SOURCES} @@ -557,7 +557,7 @@ if (BUILD_LAGOM) SOURCES ${LIBWEB_SOURCES} ${LIBWEB_SUBDIR_SOURCES} ${LIBWEB_SUBSUBDIR_SOURCES} ${LIBWEB_SUBSUBSUBDIR_SOURCES} ${LIBWEB_GENERATED_SOURCES} LIBS LibMarkdown LibGemini LibGfx LibGL LibIDL LibJS LibTextCodec LibWasm LibXML ) - generate_js_wrappers(LibWeb) + generate_js_bindings(LibWeb) endif() # WebSocket diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/CMakeLists.txt b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/CMakeLists.txt new file mode 100644 index 000000000000..bfc8a4da0a4e --- /dev/null +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/CMakeLists.txt @@ -0,0 +1,7 @@ +set(SOURCES + IDLGenerators.cpp + main.cpp +) + +lagom_tool(BindingsGenerator LIBS LibIDL) +target_compile_options(BindingsGenerator PUBLIC -g) diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp similarity index 100% rename from Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/IDLGenerators.cpp rename to Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/main.cpp similarity index 98% rename from Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp rename to Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/main.cpp index c43d3580a5c3..72546a958fb2 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/main.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/main.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2020-2021, Andreas Kling <[email protected]> - * Copyright (c) 2021, Linus Groh <[email protected]> + * Copyright (c) 2021-2022, Linus Groh <[email protected]> * Copyright (c) 2021, Luke Wilde <[email protected]> * Copyright (c) 2022, Ali Mohammad Pur <[email protected]> * @@ -107,7 +107,7 @@ int main(int argc, char** argv) interface.fully_qualified_name = interface.name; } - if constexpr (WRAPPER_GENERATOR_DEBUG) { + if constexpr (BINDINGS_GENERATOR_DEBUG) { dbgln("Attributes:"); for (auto& attribute : interface.attributes) { dbgln(" {}{}{} {}", diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt b/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt index 49e512ae26a8..0b9d1f95f68a 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/CMakeLists.txt @@ -6,4 +6,4 @@ lagom_tool(GenerateCSSPropertyID SOURCES GenerateCSSPropertyID.cpp LIB lagom_tool(GenerateCSSTransformFunctions SOURCES GenerateCSSTransformFunctions.cpp LIBS LibMain) lagom_tool(GenerateCSSValueID SOURCES GenerateCSSValueID.cpp LIBS LibMain) -add_subdirectory(WrapperGenerator) +add_subdirectory(BindingsGenerator) diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/CMakeLists.txt b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/CMakeLists.txt deleted file mode 100644 index 2f06043b2fb8..000000000000 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -set(SOURCES - IDLGenerators.cpp - main.cpp -) - -lagom_tool(WrapperGenerator LIBS LibIDL) -target_compile_options(WrapperGenerator PUBLIC -g) diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 7312fe898fe9..47983f1cdeda 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -436,7 +436,7 @@ serenity_lib(LibWeb web) target_link_libraries(LibWeb LibCore LibJS LibMarkdown LibGemini LibGL LibGUI LibGfx LibSoftGPU LibTextCodec LibWasm LibXML LibIDL) link_with_locale_data(LibWeb) -generate_js_wrappers(LibWeb) +generate_js_bindings(LibWeb) -# Note: If you're looking for the calls to "libweb_js_wrapper()", +# Note: If you're looking for the calls to "libweb_js_bindings()", # they have been moved to "idl_files.cmake" diff --git a/Userland/Libraries/LibWeb/Fetch/Headers.cpp b/Userland/Libraries/LibWeb/Fetch/Headers.cpp index a254be9b4589..4195c98aa251 100644 --- a/Userland/Libraries/LibWeb/Fetch/Headers.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Headers.cpp @@ -98,7 +98,7 @@ DOM::ExceptionOr<String> Headers::get(String const& name_string) // 2. Return the result of getting name from this’s header list. auto byte_buffer = TRY_OR_RETURN_OOM(global_object(), m_header_list.get(name)); - // FIXME: Teach WrapperGenerator about Optional<String> + // FIXME: Teach BindingsGenerator about Optional<String> return byte_buffer.has_value() ? String { byte_buffer->span() } : String {}; } diff --git a/Userland/Libraries/LibWeb/Tests/HTML/HTMLTableElement.js b/Userland/Libraries/LibWeb/Tests/HTML/HTMLTableElement.js index 89c2eaf8df0f..82d5d317e512 100644 --- a/Userland/Libraries/LibWeb/Tests/HTML/HTMLTableElement.js +++ b/Userland/Libraries/LibWeb/Tests/HTML/HTMLTableElement.js @@ -63,7 +63,7 @@ describe("HTMLTableElement", () => { let table = page.document.createElement("table"); expect(table).not.toBeNull(); - // We hardcode the default value in a few places, due to the WrapperGenerator's bug with default values + // We hardcode the default value in a few places, due to the BindingsGenerator's bug with default values const defaultValue = -1; expect(table.rows.length).toBe(0); @@ -96,7 +96,7 @@ describe("HTMLTableElement", () => { let table = page.document.createElement("table"); expect(table).not.toBeNull(); - // We hardcode the default value in a few places, due to the WrapperGenerator's bug with default values + // We hardcode the default value in a few places, due to the BindingsGenerator's bug with default values const defaultValue = -1; // deleteRow with an index > number of rows will throw diff --git a/Userland/Libraries/LibWeb/idl_files.cmake b/Userland/Libraries/LibWeb/idl_files.cmake index b0ef6c9f0504..cf3a00541f6b 100644 --- a/Userland/Libraries/LibWeb/idl_files.cmake +++ b/Userland/Libraries/LibWeb/idl_files.cmake @@ -1,190 +1,190 @@ # This file is included from "Meta/CMake/libweb_data.cmake" # It is defined here so that there is no need to go to the Meta directory when adding new idl files -libweb_js_wrapper(Crypto/Crypto) -libweb_js_wrapper(Crypto/SubtleCrypto) -libweb_js_wrapper(CSS/CSSConditionRule) -libweb_js_wrapper(CSS/CSSFontFaceRule) -libweb_js_wrapper(CSS/CSSGroupingRule) -libweb_js_wrapper(CSS/CSSImportRule) -libweb_js_wrapper(CSS/CSSMediaRule) -libweb_js_wrapper(CSS/CSSRule) -libweb_js_wrapper(CSS/CSSRuleList) -libweb_js_wrapper(CSS/CSSStyleDeclaration) -libweb_js_wrapper(CSS/CSSStyleRule) -libweb_js_wrapper(CSS/CSSStyleSheet) -libweb_js_wrapper(CSS/CSSSupportsRule) -libweb_js_wrapper(CSS/MediaList) -libweb_js_wrapper(CSS/MediaQueryList) -libweb_js_wrapper(CSS/MediaQueryListEvent) -libweb_js_wrapper(CSS/Screen) -libweb_js_wrapper(CSS/StyleSheet) -libweb_js_wrapper(CSS/StyleSheetList) -libweb_js_wrapper(DOM/AbstractRange) -libweb_js_wrapper(DOM/Attr) -libweb_js_wrapper(DOM/AbortController) -libweb_js_wrapper(DOM/AbortSignal) -libweb_js_wrapper(DOM/CDATASection) -libweb_js_wrapper(DOM/CharacterData) -libweb_js_wrapper(DOM/Comment) -libweb_js_wrapper(DOM/CustomEvent) -libweb_js_wrapper(DOM/Document) -libweb_js_wrapper(DOM/DocumentFragment) -libweb_js_wrapper(DOM/DocumentType) -libweb_js_wrapper(DOM/DOMException) -libweb_js_wrapper(DOM/DOMImplementation) -libweb_js_wrapper(DOM/DOMTokenList) -libweb_js_wrapper(DOM/Element) -libweb_js_wrapper(DOM/Event) -libweb_js_wrapper(DOM/EventTarget) -libweb_js_wrapper(DOM/HTMLCollection) -libweb_js_wrapper(DOM/MutationRecord) -libweb_js_wrapper(DOM/MutationObserver) -libweb_js_wrapper(DOM/NamedNodeMap) -libweb_js_wrapper(DOM/Node) -libweb_js_wrapper(DOM/NodeIterator) -libweb_js_wrapper(DOM/NodeList) -libweb_js_wrapper(DOM/ProcessingInstruction) -libweb_js_wrapper(DOM/Range) -libweb_js_wrapper(DOM/ShadowRoot) -libweb_js_wrapper(DOM/StaticRange) -libweb_js_wrapper(DOM/Text) -libweb_js_wrapper(DOM/TreeWalker) -libweb_js_wrapper(DOMParsing/XMLSerializer) -libweb_js_wrapper(Encoding/TextDecoder) -libweb_js_wrapper(Encoding/TextEncoder) -libweb_js_wrapper(Fetch/Headers ITERABLE) -libweb_js_wrapper(FileAPI/Blob) -libweb_js_wrapper(FileAPI/File) -libweb_js_wrapper(Geometry/DOMPoint) -libweb_js_wrapper(Geometry/DOMPointReadOnly) -libweb_js_wrapper(Geometry/DOMRect) -libweb_js_wrapper(Geometry/DOMRectList) -libweb_js_wrapper(Geometry/DOMRectReadOnly) -libweb_js_wrapper(HTML/CanvasGradient) -libweb_js_wrapper(HTML/CanvasRenderingContext2D) -libweb_js_wrapper(HTML/CloseEvent) -libweb_js_wrapper(HTML/DOMParser) -libweb_js_wrapper(HTML/DOMStringMap) -libweb_js_wrapper(HTML/ErrorEvent) -libweb_js_wrapper(HTML/History) -libweb_js_wrapper(HTML/HTMLAnchorElement) -libweb_js_wrapper(HTML/HTMLAreaElement) -libweb_js_wrapper(HTML/HTMLAudioElement) -libweb_js_wrapper(HTML/HTMLBaseElement) -libweb_js_wrapper(HTML/HTMLBodyElement) -libweb_js_wrapper(HTML/HTMLBRElement) -libweb_js_wrapper(HTML/HTMLButtonElement) -libweb_js_wrapper(HTML/HTMLCanvasElement) -libweb_js_wrapper(HTML/HTMLDataElement) -libweb_js_wrapper(HTML/HTMLDataListElement) -libweb_js_wrapper(HTML/HTMLDetailsElement) -libweb_js_wrapper(HTML/HTMLDialogElement) -libweb_js_wrapper(HTML/HTMLDirectoryElement) -libweb_js_wrapper(HTML/HTMLDivElement) -libweb_js_wrapper(HTML/HTMLDListElement) -libweb_js_wrapper(HTML/HTMLElement) -libweb_js_wrapper(HTML/HTMLEmbedElement) -libweb_js_wrapper(HTML/HTMLFieldSetElement) -libweb_js_wrapper(HTML/HTMLFontElement) -libweb_js_wrapper(HTML/HTMLFormElement) -libweb_js_wrapper(HTML/HTMLFrameElement) -libweb_js_wrapper(HTML/HTMLFrameSetElement) -libweb_js_wrapper(HTML/HTMLHeadElement) -libweb_js_wrapper(HTML/HTMLHeadingElement) -libweb_js_wrapper(HTML/HTMLHRElement) -libweb_js_wrapper(HTML/HTMLHtmlElement) -libweb_js_wrapper(HTML/HTMLIFrameElement) -libweb_js_wrapper(HTML/HTMLImageElement) -libweb_js_wrapper(HTML/HTMLInputElement) -libweb_js_wrapper(HTML/HTMLLabelElement) -libweb_js_wrapper(HTML/HTMLLegendElement) -libweb_js_wrapper(HTML/HTMLLIElement) -libweb_js_wrapper(HTML/HTMLLinkElement) -libweb_js_wrapper(HTML/HTMLMapElement) -libweb_js_wrapper(HTML/HTMLMarqueeElement) -libweb_js_wrapper(HTML/HTMLMediaElement) -libweb_js_wrapper(HTML/HTMLMenuElement) -libweb_js_wrapper(HTML/HTMLMetaElement) -libweb_js_wrapper(HTML/HTMLMeterElement) -libweb_js_wrapper(HTML/HTMLModElement) -libweb_js_wrapper(HTML/HTMLObjectElement) -libweb_js_wrapper(HTML/HTMLOListElement) -libweb_js_wrapper(HTML/HTMLOptGroupElement) -libweb_js_wrapper(HTML/HTMLOptionElement) -libweb_js_wrapper(HTML/HTMLOptionsCollection) -libweb_js_wrapper(HTML/HTMLOutputElement) -libweb_js_wrapper(HTML/HTMLParagraphElement) -libweb_js_wrapper(HTML/HTMLParamElement) -libweb_js_wrapper(HTML/HTMLPictureElement) -libweb_js_wrapper(HTML/HTMLPreElement) -libweb_js_wrapper(HTML/HTMLProgressElement) -libweb_js_wrapper(HTML/HTMLQuoteElement) -libweb_js_wrapper(HTML/HTMLScriptElement) -libweb_js_wrapper(HTML/HTMLSelectElement) -libweb_js_wrapper(HTML/HTMLSlotElement) -libweb_js_wrapper(HTML/HTMLSourceElement) -libweb_js_wrapper(HTML/HTMLSpanElement) -libweb_js_wrapper(HTML/HTMLStyleElement) -libweb_js_wrapper(HTML/HTMLTableCaptionElement) -libweb_js_wrapper(HTML/HTMLTableCellElement) -libweb_js_wrapper(HTML/HTMLTableColElement) -libweb_js_wrapper(HTML/HTMLTableElement) -libweb_js_wrapper(HTML/HTMLTableRowElement) -libweb_js_wrapper(HTML/HTMLTableSectionElement) -libweb_js_wrapper(HTML/HTMLTemplateElement) -libweb_js_wrapper(HTML/HTMLTextAreaElement) -libweb_js_wrapper(HTML/HTMLTimeElement) -libweb_js_wrapper(HTML/HTMLTitleElement) -libweb_js_wrapper(HTML/HTMLTrackElement) -libweb_js_wrapper(HTML/HTMLUListElement) -libweb_js_wrapper(HTML/HTMLUnknownElement) -libweb_js_wrapper(HTML/HTMLVideoElement) -libweb_js_wrapper(HTML/ImageData) -libweb_js_wrapper(HTML/MessageChannel) -libweb_js_wrapper(HTML/MessageEvent) -libweb_js_wrapper(HTML/MessagePort) -libweb_js_wrapper(HTML/PageTransitionEvent) -libweb_js_wrapper(HTML/Path2D) -libweb_js_wrapper(HTML/PromiseRejectionEvent) -libweb_js_wrapper(HTML/Storage) -libweb_js_wrapper(HTML/SubmitEvent) -libweb_js_wrapper(HTML/TextMetrics) -libweb_js_wrapper(HTML/Worker) -libweb_js_wrapper(HTML/WorkerGlobalScope) -libweb_js_wrapper(HTML/WorkerLocation) -libweb_js_wrapper(HTML/WorkerNavigator) -libweb_js_wrapper(HighResolutionTime/Performance) -libweb_js_wrapper(IntersectionObserver/IntersectionObserver) -libweb_js_wrapper(NavigationTiming/PerformanceTiming) -libweb_js_wrapper(RequestIdleCallback/IdleDeadline) -libweb_js_wrapper(ResizeObserver/ResizeObserver) -libweb_js_wrapper(SVG/SVGAnimatedLength) -libweb_js_wrapper(SVG/SVGClipPathElement) -libweb_js_wrapper(SVG/SVGDefsElement) -libweb_js_wrapper(SVG/SVGElement) -libweb_js_wrapper(SVG/SVGGeometryElement) -libweb_js_wrapper(SVG/SVGGraphicsElement) -libweb_js_wrapper(SVG/SVGCircleElement) -libweb_js_wrapper(SVG/SVGEllipseElement) -libweb_js_wrapper(SVG/SVGLength) -libweb_js_wrapper(SVG/SVGLineElement) -libweb_js_wrapper(SVG/SVGPathElement) -libweb_js_wrapper(SVG/SVGPolygonElement) -libweb_js_wrapper(SVG/SVGPolylineElement) -libweb_js_wrapper(SVG/SVGRectElement) -libweb_js_wrapper(SVG/SVGSVGElement) -libweb_js_wrapper(SVG/SVGTextContentElement) -libweb_js_wrapper(Selection/Selection) -libweb_js_wrapper(UIEvents/FocusEvent) -libweb_js_wrapper(UIEvents/KeyboardEvent) -libweb_js_wrapper(UIEvents/MouseEvent) -libweb_js_wrapper(UIEvents/UIEvent) -libweb_js_wrapper(URL/URL) -libweb_js_wrapper(URL/URLSearchParams ITERABLE) -libweb_js_wrapper(WebGL/WebGLContextEvent) -libweb_js_wrapper(WebGL/WebGLRenderingContext) -libweb_js_wrapper(WebSockets/WebSocket) -libweb_js_wrapper(XHR/ProgressEvent) -libweb_js_wrapper(XHR/XMLHttpRequest) -libweb_js_wrapper(XHR/XMLHttpRequestEventTarget) +libweb_js_bindings(Crypto/Crypto) +libweb_js_bindings(Crypto/SubtleCrypto) +libweb_js_bindings(CSS/CSSConditionRule) +libweb_js_bindings(CSS/CSSFontFaceRule) +libweb_js_bindings(CSS/CSSGroupingRule) +libweb_js_bindings(CSS/CSSImportRule) +libweb_js_bindings(CSS/CSSMediaRule) +libweb_js_bindings(CSS/CSSRule) +libweb_js_bindings(CSS/CSSRuleList) +libweb_js_bindings(CSS/CSSStyleDeclaration) +libweb_js_bindings(CSS/CSSStyleRule) +libweb_js_bindings(CSS/CSSStyleSheet) +libweb_js_bindings(CSS/CSSSupportsRule) +libweb_js_bindings(CSS/MediaList) +libweb_js_bindings(CSS/MediaQueryList) +libweb_js_bindings(CSS/MediaQueryListEvent) +libweb_js_bindings(CSS/Screen) +libweb_js_bindings(CSS/StyleSheet) +libweb_js_bindings(CSS/StyleSheetList) +libweb_js_bindings(DOM/AbstractRange) +libweb_js_bindings(DOM/Attr) +libweb_js_bindings(DOM/AbortController) +libweb_js_bindings(DOM/AbortSignal) +libweb_js_bindings(DOM/CDATASection) +libweb_js_bindings(DOM/CharacterData) +libweb_js_bindings(DOM/Comment) +libweb_js_bindings(DOM/CustomEvent) +libweb_js_bindings(DOM/Document) +libweb_js_bindings(DOM/DocumentFragment) +libweb_js_bindings(DOM/DocumentType) +libweb_js_bindings(DOM/DOMException) +libweb_js_bindings(DOM/DOMImplementation) +libweb_js_bindings(DOM/DOMTokenList) +libweb_js_bindings(DOM/Element) +libweb_js_bindings(DOM/Event) +libweb_js_bindings(DOM/EventTarget) +libweb_js_bindings(DOM/HTMLCollection) +libweb_js_bindings(DOM/MutationRecord) +libweb_js_bindings(DOM/MutationObserver) +libweb_js_bindings(DOM/NamedNodeMap) +libweb_js_bindings(DOM/Node) +libweb_js_bindings(DOM/NodeIterator) +libweb_js_bindings(DOM/NodeList) +libweb_js_bindings(DOM/ProcessingInstruction) +libweb_js_bindings(DOM/Range) +libweb_js_bindings(DOM/ShadowRoot) +libweb_js_bindings(DOM/StaticRange) +libweb_js_bindings(DOM/Text) +libweb_js_bindings(DOM/TreeWalker) +libweb_js_bindings(DOMParsing/XMLSerializer) +libweb_js_bindings(Encoding/TextDecoder) +libweb_js_bindings(Encoding/TextEncoder) +libweb_js_bindings(Fetch/Headers ITERABLE) +libweb_js_bindings(FileAPI/Blob) +libweb_js_bindings(FileAPI/File) +libweb_js_bindings(Geometry/DOMPoint) +libweb_js_bindings(Geometry/DOMPointReadOnly) +libweb_js_bindings(Geometry/DOMRect) +libweb_js_bindings(Geometry/DOMRectList) +libweb_js_bindings(Geometry/DOMRectReadOnly) +libweb_js_bindings(HTML/CanvasGradient) +libweb_js_bindings(HTML/CanvasRenderingContext2D) +libweb_js_bindings(HTML/CloseEvent) +libweb_js_bindings(HTML/DOMParser) +libweb_js_bindings(HTML/DOMStringMap) +libweb_js_bindings(HTML/ErrorEvent) +libweb_js_bindings(HTML/History) +libweb_js_bindings(HTML/HTMLAnchorElement) +libweb_js_bindings(HTML/HTMLAreaElement) +libweb_js_bindings(HTML/HTMLAudioElement) +libweb_js_bindings(HTML/HTMLBaseElement) +libweb_js_bindings(HTML/HTMLBodyElement) +libweb_js_bindings(HTML/HTMLBRElement) +libweb_js_bindings(HTML/HTMLButtonElement) +libweb_js_bindings(HTML/HTMLCanvasElement) +libweb_js_bindings(HTML/HTMLDataElement) +libweb_js_bindings(HTML/HTMLDataListElement) +libweb_js_bindings(HTML/HTMLDetailsElement) +libweb_js_bindings(HTML/HTMLDialogElement) +libweb_js_bindings(HTML/HTMLDirectoryElement) +libweb_js_bindings(HTML/HTMLDivElement) +libweb_js_bindings(HTML/HTMLDListElement) +libweb_js_bindings(HTML/HTMLElement) +libweb_js_bindings(HTML/HTMLEmbedElement) +libweb_js_bindings(HTML/HTMLFieldSetElement) +libweb_js_bindings(HTML/HTMLFontElement) +libweb_js_bindings(HTML/HTMLFormElement) +libweb_js_bindings(HTML/HTMLFrameElement) +libweb_js_bindings(HTML/HTMLFrameSetElement) +libweb_js_bindings(HTML/HTMLHeadElement) +libweb_js_bindings(HTML/HTMLHeadingElement) +libweb_js_bindings(HTML/HTMLHRElement) +libweb_js_bindings(HTML/HTMLHtmlElement) +libweb_js_bindings(HTML/HTMLIFrameElement) +libweb_js_bindings(HTML/HTMLImageElement) +libweb_js_bindings(HTML/HTMLInputElement) +libweb_js_bindings(HTML/HTMLLabelElement) +libweb_js_bindings(HTML/HTMLLegendElement) +libweb_js_bindings(HTML/HTMLLIElement) +libweb_js_bindings(HTML/HTMLLinkElement) +libweb_js_bindings(HTML/HTMLMapElement) +libweb_js_bindings(HTML/HTMLMarqueeElement) +libweb_js_bindings(HTML/HTMLMediaElement) +libweb_js_bindings(HTML/HTMLMenuElement) +libweb_js_bindings(HTML/HTMLMetaElement) +libweb_js_bindings(HTML/HTMLMeterElement) +libweb_js_bindings(HTML/HTMLModElement) +libweb_js_bindings(HTML/HTMLObjectElement) +libweb_js_bindings(HTML/HTMLOListElement) +libweb_js_bindings(HTML/HTMLOptGroupElement) +libweb_js_bindings(HTML/HTMLOptionElement) +libweb_js_bindings(HTML/HTMLOptionsCollection) +libweb_js_bindings(HTML/HTMLOutputElement) +libweb_js_bindings(HTML/HTMLParagraphElement) +libweb_js_bindings(HTML/HTMLParamElement) +libweb_js_bindings(HTML/HTMLPictureElement) +libweb_js_bindings(HTML/HTMLPreElement) +libweb_js_bindings(HTML/HTMLProgressElement) +libweb_js_bindings(HTML/HTMLQuoteElement) +libweb_js_bindings(HTML/HTMLScriptElement) +libweb_js_bindings(HTML/HTMLSelectElement) +libweb_js_bindings(HTML/HTMLSlotElement) +libweb_js_bindings(HTML/HTMLSourceElement) +libweb_js_bindings(HTML/HTMLSpanElement) +libweb_js_bindings(HTML/HTMLStyleElement) +libweb_js_bindings(HTML/HTMLTableCaptionElement) +libweb_js_bindings(HTML/HTMLTableCellElement) +libweb_js_bindings(HTML/HTMLTableColElement) +libweb_js_bindings(HTML/HTMLTableElement) +libweb_js_bindings(HTML/HTMLTableRowElement) +libweb_js_bindings(HTML/HTMLTableSectionElement) +libweb_js_bindings(HTML/HTMLTemplateElement) +libweb_js_bindings(HTML/HTMLTextAreaElement) +libweb_js_bindings(HTML/HTMLTimeElement) +libweb_js_bindings(HTML/HTMLTitleElement) +libweb_js_bindings(HTML/HTMLTrackElement) +libweb_js_bindings(HTML/HTMLUListElement) +libweb_js_bindings(HTML/HTMLUnknownElement) +libweb_js_bindings(HTML/HTMLVideoElement) +libweb_js_bindings(HTML/ImageData) +libweb_js_bindings(HTML/MessageChannel) +libweb_js_bindings(HTML/MessageEvent) +libweb_js_bindings(HTML/MessagePort) +libweb_js_bindings(HTML/PageTransitionEvent) +libweb_js_bindings(HTML/Path2D) +libweb_js_bindings(HTML/PromiseRejectionEvent) +libweb_js_bindings(HTML/Storage) +libweb_js_bindings(HTML/SubmitEvent) +libweb_js_bindings(HTML/TextMetrics) +libweb_js_bindings(HTML/Worker) +libweb_js_bindings(HTML/WorkerGlobalScope) +libweb_js_bindings(HTML/WorkerLocation) +libweb_js_bindings(HTML/WorkerNavigator) +libweb_js_bindings(HighResolutionTime/Performance) +libweb_js_bindings(IntersectionObserver/IntersectionObserver) +libweb_js_bindings(NavigationTiming/PerformanceTiming) +libweb_js_bindings(RequestIdleCallback/IdleDeadline) +libweb_js_bindings(ResizeObserver/ResizeObserver) +libweb_js_bindings(SVG/SVGAnimatedLength) +libweb_js_bindings(SVG/SVGClipPathElement) +libweb_js_bindings(SVG/SVGDefsElement) +libweb_js_bindings(SVG/SVGElement) +libweb_js_bindings(SVG/SVGGeometryElement) +libweb_js_bindings(SVG/SVGGraphicsElement) +libweb_js_bindings(SVG/SVGCircleElement) +libweb_js_bindings(SVG/SVGEllipseElement) +libweb_js_bindings(SVG/SVGLength) +libweb_js_bindings(SVG/SVGLineElement) +libweb_js_bindings(SVG/SVGPathElement) +libweb_js_bindings(SVG/SVGPolygonElement) +libweb_js_bindings(SVG/SVGPolylineElement) +libweb_js_bindings(SVG/SVGRectElement) +libweb_js_bindings(SVG/SVGSVGElement) +libweb_js_bindings(SVG/SVGTextContentElement) +libweb_js_bindings(Selection/Selection) +libweb_js_bindings(UIEvents/FocusEvent) +libweb_js_bindings(UIEvents/KeyboardEvent) +libweb_js_bindings(UIEvents/MouseEvent) +libweb_js_bindings(UIEvents/UIEvent) +libweb_js_bindings(URL/URL) +libweb_js_bindings(URL/URLSearchParams ITERABLE) +libweb_js_bindings(WebGL/WebGLContextEvent) +libweb_js_bindings(WebGL/WebGLRenderingContext) +libweb_js_bindings(WebSockets/WebSocket) +libweb_js_bindings(XHR/ProgressEvent) +libweb_js_bindings(XHR/XMLHttpRequest) +libweb_js_bindings(XHR/XMLHttpRequestEventTarget)
4143f6f906e8bb6059d06b93c2d7659f6fd542c5
2021-11-02 22:23:22
thislooksfun
libgui: Make sure that children are actually widgets
false
Make sure that children are actually widgets
libgui
diff --git a/Userland/Libraries/LibGUI/Widget.cpp b/Userland/Libraries/LibGUI/Widget.cpp index 897e35129e22..cf2b2b3aa60a 100644 --- a/Userland/Libraries/LibGUI/Widget.cpp +++ b/Userland/Libraries/LibGUI/Widget.cpp @@ -1108,6 +1108,7 @@ bool Widget::load_from_json(const JsonObject& json, RefPtr<Core::Object> (*unreg }); } + auto& widget_class = *Core::ObjectClassRegistration::find("GUI::Widget"); auto children = json.get("children"); if (children.is_array()) { for (auto& child_json_value : children.as_array().values()) { @@ -1123,6 +1124,10 @@ bool Widget::load_from_json(const JsonObject& json, RefPtr<Core::Object> (*unreg RefPtr<Core::Object> child; if (auto* registration = Core::ObjectClassRegistration::find(class_name.as_string())) { child = registration->construct(); + if (!child || !registration->is_derived_from(widget_class)) { + dbgln("Invalid widget class: '{}'", class_name.to_string()); + return false; + } } else { child = unregistered_child_handler(class_name.as_string()); }
f4c8f2102f86da4ee798439fa156a5039a5f92f6
2021-10-21 04:56:45
Timothy Flynn
libjs: Retrieve GetIterator's optional 'method' function using GetMethod
false
Retrieve GetIterator's optional 'method' function using GetMethod
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp b/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp index 513a0121e0df..c465b550eebd 100644 --- a/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/IteratorOperations.cpp @@ -6,6 +6,7 @@ #include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/Error.h> +#include <LibJS/Runtime/FunctionObject.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/IteratorOperations.h> @@ -18,8 +19,8 @@ ThrowCompletionOr<Object*> get_iterator(GlobalObject& global_object, Value value if (method.is_empty()) { if (hint == IteratorHint::Async) TODO(); - auto object = TRY(value.to_object(global_object)); - method = TRY(object->get(*vm.well_known_symbol_iterator())); + + method = TRY(value.get_method(global_object, *vm.well_known_symbol_iterator())); } if (!method.is_function())
4cb6eaf5885fa3f961cd0d077ae3625027e019d1
2021-09-17 03:04:24
Linus Groh
libjs: Convert parse_temporal_date_string() to ThrowCompletionOr
false
Convert parse_temporal_date_string() to ThrowCompletionOr
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp index e173712f0468..0a86a2373bc0 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp @@ -860,7 +860,7 @@ ThrowCompletionOr<String> parse_temporal_calendar_string(GlobalObject& global_ob } // 13.38 ParseTemporalDateString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatestring -Optional<TemporalDate> parse_temporal_date_string(GlobalObject& global_object, String const& iso_string) +ThrowCompletionOr<TemporalDate> parse_temporal_date_string(GlobalObject& global_object, String const& iso_string) { // 1. Assert: Type(isoString) is String. @@ -869,7 +869,7 @@ Optional<TemporalDate> parse_temporal_date_string(GlobalObject& global_object, S // TODO // 3. Let result be ? ParseISODateTime(isoString). - auto result = TRY_OR_DISCARD(parse_iso_date_time(global_object, iso_string)); + auto result = TRY(parse_iso_date_time(global_object, iso_string)); // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }. return TemporalDate { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) }; diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h index 851815915add..1af0f62b2e4b 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h @@ -106,7 +106,7 @@ BigInt* round_number_to_increment(GlobalObject&, BigInt const&, u64 increment, S ThrowCompletionOr<ISODateTime> parse_iso_date_time(GlobalObject&, String const& iso_string); ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(GlobalObject&, String const& iso_string); ThrowCompletionOr<String> parse_temporal_calendar_string(GlobalObject&, String const& iso_string); -Optional<TemporalDate> parse_temporal_date_string(GlobalObject&, String const& iso_string); +ThrowCompletionOr<TemporalDate> parse_temporal_date_string(GlobalObject&, String const& iso_string); Optional<ISODateTime> parse_temporal_date_time_string(GlobalObject&, String const& iso_string); Optional<TemporalDuration> parse_temporal_duration_string(GlobalObject&, String const& iso_string); Optional<TemporalTime> parse_temporal_time_string(GlobalObject&, String const& iso_string); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp index c4d71eeb2c2e..5729cf914a7a 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp @@ -139,20 +139,18 @@ PlainDate* to_temporal_date(GlobalObject& global_object, Value item, Object* opt return {}; // 6. Let result be ? ParseTemporalDateString(string). - auto result = parse_temporal_date_string(global_object, string); - if (vm.exception()) - return {}; + auto result = TRY_OR_DISCARD(parse_temporal_date_string(global_object, string)); // 7. Assert: ! IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true. - VERIFY(is_valid_iso_date(result->year, result->month, result->day)); + VERIFY(is_valid_iso_date(result.year, result.month, result.day)); // 8. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]). - auto calendar = to_temporal_calendar_with_iso_default(global_object, result->calendar.has_value() ? js_string(vm, *result->calendar) : js_undefined()); + auto calendar = to_temporal_calendar_with_iso_default(global_object, result.calendar.has_value() ? js_string(vm, *result.calendar) : js_undefined()); if (vm.exception()) return {}; // 9. Return ? CreateTemporalDate(result.[[Year]], result.[[Month]], result.[[Day]], calendar). - return create_temporal_date(global_object, result->year, result->month, result->day, *calendar); + return create_temporal_date(global_object, result.year, result.month, result.day, *calendar); } // 3.5.4 RegulateISODate ( year, month, day, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisodate
ff2a991e197bafcff5a68e85ab06016cf80be5c6
2023-02-22 14:25:33
Kenneth Myhra
libweb: Make factory method of ResizeObserver::ResizeObserver fallible
false
Make factory method of ResizeObserver::ResizeObserver fallible
libweb
diff --git a/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.cpp b/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.cpp index 05360dfca886..c1fc475ba7cc 100644 --- a/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.cpp +++ b/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.cpp @@ -11,11 +11,11 @@ namespace Web::ResizeObserver { // https://drafts.csswg.org/resize-observer/#dom-resizeobserver-resizeobserver -JS::NonnullGCPtr<ResizeObserver> ResizeObserver::construct_impl(JS::Realm& realm, WebIDL::CallbackType* callback) +WebIDL::ExceptionOr<JS::NonnullGCPtr<ResizeObserver>> ResizeObserver::construct_impl(JS::Realm& realm, WebIDL::CallbackType* callback) { // FIXME: Implement (void)callback; - return realm.heap().allocate<ResizeObserver>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors(); + return MUST_OR_THROW_OOM(realm.heap().allocate<ResizeObserver>(realm, realm)); } ResizeObserver::ResizeObserver(JS::Realm& realm) diff --git a/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.h b/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.h index 722e3b9e2e14..5216a6525eff 100644 --- a/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.h +++ b/Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.h @@ -19,7 +19,7 @@ class ResizeObserver : public Bindings::PlatformObject { WEB_PLATFORM_OBJECT(ResizeObserver, Bindings::PlatformObject); public: - static JS::NonnullGCPtr<ResizeObserver> construct_impl(JS::Realm&, WebIDL::CallbackType* callback); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<ResizeObserver>> construct_impl(JS::Realm&, WebIDL::CallbackType* callback); virtual ~ResizeObserver() override;
42518867d7c99b97db1f89a11e8de607c40ce42f
2022-09-28 01:59:44
Lucas CHOLLET
ak: Make ErrorOr::error() const and return a const reference
false
Make ErrorOr::error() const and return a const reference
ak
diff --git a/AK/Error.h b/AK/Error.h index 286cd0a435ed..decae334753f 100644 --- a/AK/Error.h +++ b/AK/Error.h @@ -139,7 +139,7 @@ class [[nodiscard]] ErrorOr<void, ErrorType> { ErrorOr& operator=(ErrorOr&& other) = default; ErrorOr& operator=(ErrorOr const& other) = default; - ErrorType& error() { return m_error.value(); } + ErrorType const& error() const { return m_error.value(); } bool is_error() const { return m_error.has_value(); } ErrorType release_error() { return m_error.release_value(); } void release_value() { }
18cfbb5cb442496331d7a4398d1e79157dede822
2024-03-28 20:04:52
Aliaksandr Kalenik
libweb: Bring initialize_navigable() up to date with the spec
false
Bring initialize_navigable() up to date with the spec
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Navigable.cpp b/Userland/Libraries/LibWeb/HTML/Navigable.cpp index 6aaa22af9642..6c54683756fc 100644 --- a/Userland/Libraries/LibWeb/HTML/Navigable.cpp +++ b/Userland/Libraries/LibWeb/HTML/Navigable.cpp @@ -136,22 +136,23 @@ ErrorOr<void> Navigable::initialize_navigable(JS::NonnullGCPtr<DocumentState> do static int next_id = 0; m_id = TRY(String::number(next_id++)); - // 1. Let entry be a new session history entry, with - JS::NonnullGCPtr<SessionHistoryEntry> entry = *heap().allocate_without_realm<SessionHistoryEntry>(); + // 1. Assert: documentState's document is non-null. + VERIFY(document_state->document()); + // 2. Let entry be a new session history entry, with + JS::NonnullGCPtr<SessionHistoryEntry> entry = *heap().allocate_without_realm<SessionHistoryEntry>(); // URL: document's URL entry->set_url(document_state->document()->url()); - // document state: documentState entry->set_document_state(document_state); - // 2. Set navigable's current session history entry to entry. + // 3. Set navigable's current session history entry to entry. m_current_session_history_entry = entry; - // 3. Set navigable's active session history entry to entry. + // 4. Set navigable's active session history entry to entry. m_active_session_history_entry = entry; - // 4. Set navigable's parent to parent. + // 5. Set navigable's parent to parent. m_parent = parent; return {};
5f645e84d89a727eb9205a4e1c325e7cdc910421
2022-01-13 17:16:12
sin-ack
libcore: Use Error::from_errno in Stream APIs
false
Use Error::from_errno in Stream APIs
libcore
diff --git a/Userland/Libraries/LibCore/Stream.cpp b/Userland/Libraries/LibCore/Stream.cpp index 0f1f3b537110..303c0e5a8f9a 100644 --- a/Userland/Libraries/LibCore/Stream.cpp +++ b/Userland/Libraries/LibCore/Stream.cpp @@ -164,7 +164,7 @@ ErrorOr<size_t> File::read(Bytes buffer) // NOTE: POSIX says that if the fd is not open for reading, the call // will return EBADF. Since we already know whether we can or // can't read the file, let's avoid a syscall. - return EBADF; + return Error::from_errno(EBADF); } ssize_t rc = ::read(m_fd, buffer.data(), buffer.size()); @@ -180,7 +180,7 @@ ErrorOr<size_t> File::write(ReadonlyBytes buffer) { if (!has_flag(m_mode, OpenMode::Write)) { // NOTE: Same deal as Read. - return EBADF; + return Error::from_errno(EBADF); } ssize_t rc = ::write(m_fd, buffer.data(), buffer.size()); @@ -343,7 +343,7 @@ ErrorOr<void> Socket::connect_inet(int fd, SocketAddress const& address) ErrorOr<size_t> PosixSocketHelper::read(Bytes buffer) { if (!is_open()) { - return ENOTCONN; + return Error::from_errno(ENOTCONN); } ssize_t rc = ::recv(m_fd, buffer.data(), buffer.size(), 0); @@ -364,7 +364,7 @@ ErrorOr<size_t> PosixSocketHelper::read(Bytes buffer) ErrorOr<size_t> PosixSocketHelper::write(ReadonlyBytes buffer) { if (!is_open()) { - return ENOTCONN; + return Error::from_errno(ENOTCONN); } ssize_t rc = ::send(m_fd, buffer.data(), buffer.size(), 0); @@ -483,7 +483,7 @@ ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::adopt_fd(int fd) ErrorOr<size_t> PosixSocketHelper::pending_bytes() const { if (!is_open()) { - return ENOTCONN; + return Error::from_errno(ENOTCONN); } int value; diff --git a/Userland/Libraries/LibCore/Stream.h b/Userland/Libraries/LibCore/Stream.h index af409537b159..d940760da618 100644 --- a/Userland/Libraries/LibCore/Stream.h +++ b/Userland/Libraries/LibCore/Stream.h @@ -340,7 +340,7 @@ class UDPSocket final : public Socket { // datagram to be discarded. That's not very nice, so let's bail // early, telling the caller that he should allocate a bigger // buffer. - return EMSGSIZE; + return Error::from_errno(EMSGSIZE); } return m_helper.read(buffer); @@ -469,13 +469,13 @@ class BufferedHelper { static ErrorOr<NonnullOwnPtr<BufferedType<T>>> create_buffered(NonnullOwnPtr<T> stream, size_t buffer_size) { if (!buffer_size) - return EINVAL; + return Error::from_errno(EINVAL); if (!stream->is_open()) - return ENOTCONN; + return Error::from_errno(ENOTCONN); auto maybe_buffer = ByteBuffer::create_uninitialized(buffer_size); if (!maybe_buffer.has_value()) - return ENOMEM; + return Error::from_errno(ENOMEM); return adopt_nonnull_own_or_enomem(new BufferedType<T>(move(stream), maybe_buffer.release_value())); } @@ -486,9 +486,9 @@ class BufferedHelper { ErrorOr<size_t> read(Bytes buffer) { if (!stream().is_open()) - return ENOTCONN; + return Error::from_errno(ENOTCONN); if (!buffer.size()) - return ENOBUFS; + return Error::from_errno(ENOBUFS); // Let's try to take all we can from the buffer first. size_t buffer_nread = 0; @@ -536,10 +536,10 @@ class BufferedHelper { ErrorOr<size_t> read_until_any_of(Bytes buffer, Array<StringView, N> candidates) { if (!stream().is_open()) - return ENOTCONN; + return Error::from_errno(ENOTCONN); if (buffer.is_empty()) - return ENOBUFS; + return Error::from_errno(ENOBUFS); // We fill the buffer through can_read_line. if (!TRY(can_read_line())) @@ -557,7 +557,7 @@ class BufferedHelper { // violating the invariant twice the next time the user attempts // to read, which is No Good. So let's give a descriptive error // to the caller about why it can't read. - return EMSGSIZE; + return Error::from_errno(EMSGSIZE); } m_buffer.span().slice(0, m_buffered_size).copy_to(buffer);
7c2c9b6859a0be132e6851b5425b7da5c13698df
2022-07-14 05:12:26
Linus Groh
libweb: Add definitions from '2.1. URL' in the Fetch spec
false
Add definitions from '2.1. URL' in the Fetch spec
libweb
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 8665b6e69708..3e19af5065f3 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -118,6 +118,7 @@ set(SOURCES Encoding/TextDecoder.cpp Encoding/TextEncoder.cpp Fetch/AbstractOperations.cpp + Fetch/Infrastructure/URL.cpp FontCache.cpp Geometry/DOMRectList.cpp HTML/AttributeNames.cpp diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/URL.cpp b/Userland/Libraries/LibWeb/Fetch/Infrastructure/URL.cpp new file mode 100644 index 000000000000..34ab04bef908 --- /dev/null +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/URL.cpp @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2022, Linus Groh <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/Fetch/Infrastructure/URL.h> + +namespace Web::Fetch { + +// https://fetch.spec.whatwg.org/#is-local +bool is_local_url(AK::URL const& url) +{ + // A URL is local if its scheme is a local scheme. + return any_of(LOCAL_SCHEMES, [&](auto scheme) { return url.scheme() == scheme; }); +} + +} diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/URL.h b/Userland/Libraries/LibWeb/Fetch/Infrastructure/URL.h new file mode 100644 index 000000000000..d2355773982c --- /dev/null +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/URL.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022, Linus Groh <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Array.h> +#include <AK/URL.h> + +namespace Web::Fetch { + +// https://fetch.spec.whatwg.org/#local-scheme +// A local scheme is "about", "blob", or "data". +inline constexpr Array LOCAL_SCHEMES = { + "about"sv, "blob"sv, "data"sv +}; + +// https://fetch.spec.whatwg.org/#http-scheme +// An HTTP(S) scheme is "http" or "https". +inline constexpr Array HTTP_SCHEMES = { + "http"sv, "https"sv +}; + +// https://fetch.spec.whatwg.org/#fetch-scheme +// A fetch scheme is "about", "blob", "data", "file", or an HTTP(S) scheme. +inline constexpr Array FETCH_SCHEMES = { + "about"sv, "blob"sv, "data"sv, "file"sv, "http"sv, "https"sv +}; + +[[nodiscard]] bool is_local_url(AK::URL const&); + +}
bf59d9e82482fc0d76616193e2034d32376474e7
2021-11-12 01:06:36
Ali Mohammad Pur
userland: Include Vector.h in a few places to make HeaderCheck happy
false
Include Vector.h in a few places to make HeaderCheck happy
userland
diff --git a/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h b/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h index 3193c772d430..d80ca5e6e9a1 100644 --- a/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h +++ b/Userland/Libraries/LibCrypto/PK/Code/EMSA_PSS.h @@ -9,6 +9,7 @@ #include <AK/Array.h> #include <AK/Format.h> #include <AK/Random.h> +#include <AK/Vector.h> #include <LibCrypto/PK/Code/Code.h> namespace Crypto { diff --git a/Userland/Libraries/LibJS/Runtime/PropertyAttributes.h b/Userland/Libraries/LibJS/Runtime/PropertyAttributes.h index 8af1a8a4cc5e..a31b0e048f27 100644 --- a/Userland/Libraries/LibJS/Runtime/PropertyAttributes.h +++ b/Userland/Libraries/LibJS/Runtime/PropertyAttributes.h @@ -10,6 +10,7 @@ #include <AK/Format.h> #include <AK/String.h> #include <AK/Types.h> +#include <AK/Vector.h> namespace JS { diff --git a/Userland/Libraries/LibPDF/Command.h b/Userland/Libraries/LibPDF/Command.h index 967687d8539f..01f69aedc075 100644 --- a/Userland/Libraries/LibPDF/Command.h +++ b/Userland/Libraries/LibPDF/Command.h @@ -9,6 +9,7 @@ #include <AK/Format.h> #include <AK/String.h> #include <AK/StringBuilder.h> +#include <AK/Vector.h> #include <LibPDF/Value.h> #define ENUMERATE_COMMANDS(V) \ diff --git a/Userland/Libraries/LibPDF/Reader.h b/Userland/Libraries/LibPDF/Reader.h index ba03af849c32..d9ae301ac8b1 100644 --- a/Userland/Libraries/LibPDF/Reader.h +++ b/Userland/Libraries/LibPDF/Reader.h @@ -11,6 +11,7 @@ #include <AK/ScopeGuard.h> #include <AK/Span.h> #include <AK/String.h> +#include <AK/Vector.h> namespace PDF { diff --git a/Userland/Libraries/LibPDF/XRefTable.h b/Userland/Libraries/LibPDF/XRefTable.h index e6b7a490ca39..5ac0cd355f05 100644 --- a/Userland/Libraries/LibPDF/XRefTable.h +++ b/Userland/Libraries/LibPDF/XRefTable.h @@ -9,6 +9,7 @@ #include <AK/Format.h> #include <AK/RefCounted.h> #include <AK/String.h> +#include <AK/Vector.h> namespace PDF {
3a4a9d4c6b8e1e1defcfaec2c1dbb4eab0aec1f3
2020-09-07 23:09:48
Tom
windowserver: Fix invalidating window frame
false
Fix invalidating window frame
windowserver
diff --git a/Services/WindowServer/Window.cpp b/Services/WindowServer/Window.cpp index df7886bb1c11..aca43ccb56c9 100644 --- a/Services/WindowServer/Window.cpp +++ b/Services/WindowServer/Window.cpp @@ -409,21 +409,25 @@ void Window::invalidate(bool invalidate_frame) Compositor::the().invalidate_window(); } -void Window::invalidate(const Gfx::IntRect& rect) +void Window::invalidate(const Gfx::IntRect& rect, bool with_frame) { if (type() == WindowType::MenuApplet) { AppletManager::the().invalidate_applet(*this, rect); return; } - if (invalidate_no_notify(rect)) + if (invalidate_no_notify(rect, with_frame)) Compositor::the().invalidate_window(); } -bool Window::invalidate_no_notify(const Gfx::IntRect& rect) +bool Window::invalidate_no_notify(const Gfx::IntRect& rect, bool with_frame) { - if (m_invalidated_all || rect.is_empty()) + if (rect.is_empty()) + return false; + if (m_invalidated_all) { + m_invalidated_frame |= with_frame; return false; + } auto outer_rect = frame().rect(); auto inner_rect = rect; @@ -434,6 +438,7 @@ bool Window::invalidate_no_notify(const Gfx::IntRect& rect) return false; m_invalidated = true; + m_invalidated_frame |= with_frame; m_dirty_rects.add(inner_rect.translated(-outer_rect.location())); return true; } diff --git a/Services/WindowServer/Window.h b/Services/WindowServer/Window.h index 8d6d24518521..c093fbed8b0b 100644 --- a/Services/WindowServer/Window.h +++ b/Services/WindowServer/Window.h @@ -168,8 +168,8 @@ class Window final : public Core::Object Gfx::IntSize size() const { return m_rect.size(); } void invalidate(bool with_frame = true); - void invalidate(const Gfx::IntRect&); - bool invalidate_no_notify(const Gfx::IntRect& rect); + void invalidate(const Gfx::IntRect&, bool with_frame = false); + bool invalidate_no_notify(const Gfx::IntRect& rect, bool with_frame = false); void prepare_dirty_rects(); void clear_dirty_rects(); diff --git a/Services/WindowServer/WindowFrame.cpp b/Services/WindowServer/WindowFrame.cpp index b1cd459f2915..2bee4bee3c57 100644 --- a/Services/WindowServer/WindowFrame.cpp +++ b/Services/WindowServer/WindowFrame.cpp @@ -240,7 +240,7 @@ void WindowFrame::invalidate(Gfx::IntRect relative_rect) auto frame_rect = rect(); auto window_rect = m_window.rect(); relative_rect.move_by(frame_rect.x() - window_rect.x(), frame_rect.y() - window_rect.y()); - m_window.invalidate(relative_rect); + m_window.invalidate(relative_rect, true); } void WindowFrame::notify_window_rect_changed(const Gfx::IntRect& old_rect, const Gfx::IntRect& new_rect)
1b13d52a872fa6c3ecb0bd26758e57715b712b44
2022-10-24 19:19:39
Gunnar Beutner
libc: Make 'attributes' parameter for pthread_create const
false
Make 'attributes' parameter for pthread_create const
libc
diff --git a/Userland/Libraries/LibC/pthread.cpp b/Userland/Libraries/LibC/pthread.cpp index 3517e1c22808..d47cd11e0d22 100644 --- a/Userland/Libraries/LibC/pthread.cpp +++ b/Userland/Libraries/LibC/pthread.cpp @@ -121,13 +121,13 @@ static int create_thread(pthread_t* thread, void* (*entry)(void*), void* argumen } // https://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html -int pthread_create(pthread_t* thread, pthread_attr_t* attributes, void* (*start_routine)(void*), void* argument_to_start_routine) +int pthread_create(pthread_t* thread, pthread_attr_t const* attributes, void* (*start_routine)(void*), void* argument_to_start_routine) { if (!thread) return -EINVAL; PthreadAttrImpl default_attributes {}; - PthreadAttrImpl** arg_attributes = reinterpret_cast<PthreadAttrImpl**>(attributes); + PthreadAttrImpl* const* arg_attributes = reinterpret_cast<PthreadAttrImpl* const*>(attributes); PthreadAttrImpl* used_attributes = arg_attributes ? *arg_attributes : &default_attributes; diff --git a/Userland/Libraries/LibC/pthread.h b/Userland/Libraries/LibC/pthread.h index 2f7ff03c2314..f5f76b6dfdc2 100644 --- a/Userland/Libraries/LibC/pthread.h +++ b/Userland/Libraries/LibC/pthread.h @@ -15,7 +15,7 @@ __BEGIN_DECLS -int pthread_create(pthread_t*, pthread_attr_t*, void* (*)(void*), void*); +int pthread_create(pthread_t*, pthread_attr_t const*, void* (*)(void*), void*); void pthread_exit(void*) __attribute__((noreturn)); int pthread_kill(pthread_t, int); void pthread_cleanup_push(void (*)(void*), void*);