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
e983c745f72fa855c40c3eb85cfa6853a9f7f3b2
2020-04-09 17:40:44
Andreas Kling
kernel: Simplify ACPI initialization a bit
false
Simplify ACPI initialization a bit
kernel
diff --git a/Kernel/ACPI/ACPIDynamicParser.cpp b/Kernel/ACPI/ACPIDynamicParser.cpp index 3f70bf6ce6d5..19658f56bb3c 100644 --- a/Kernel/ACPI/ACPIDynamicParser.cpp +++ b/Kernel/ACPI/ACPIDynamicParser.cpp @@ -29,26 +29,13 @@ namespace Kernel { namespace ACPI { -void DynamicParser::initialize(PhysicalAddress rsdp) -{ - if (!StaticParser::is_initialized()) { - new DynamicParser(rsdp); - } -} -void DynamicParser::initialize_without_rsdp() -{ - if (!StaticParser::is_initialized()) { - new DynamicParser(); - } -} DynamicParser::DynamicParser() : IRQHandler(9) - , StaticParser() - { klog() << "ACPI: Dynamic Parsing Enabled, Can parse AML"; } + DynamicParser::DynamicParser(PhysicalAddress rsdp) : IRQHandler(9) , StaticParser(rsdp) diff --git a/Kernel/ACPI/ACPIDynamicParser.h b/Kernel/ACPI/ACPIDynamicParser.h index 0918fecfbf6c..97e35d33b68b 100644 --- a/Kernel/ACPI/ACPIDynamicParser.h +++ b/Kernel/ACPI/ACPIDynamicParser.h @@ -35,12 +35,13 @@ namespace Kernel { namespace ACPI { -class DynamicParser final : public IRQHandler - , StaticParser { -public: - static void initialize(PhysicalAddress rsdp); - static void initialize_without_rsdp(); +class DynamicParser final + : public IRQHandler + , public StaticParser { + friend class Parser; + +public: virtual void enable_aml_interpretation() override; virtual void enable_aml_interpretation(File& dsdt_file) override; virtual void enable_aml_interpretation(u8* physical_dsdt, u32 dsdt_payload_legnth) override; diff --git a/Kernel/ACPI/ACPIParser.cpp b/Kernel/ACPI/ACPIParser.cpp index c17a6366b75b..f72d49176c10 100644 --- a/Kernel/ACPI/ACPIParser.cpp +++ b/Kernel/ACPI/ACPIParser.cpp @@ -29,24 +29,19 @@ namespace Kernel { namespace ACPI { + static Parser* s_acpi_parser; Parser& Parser::the() { - ASSERT(s_acpi_parser != nullptr); + ASSERT(s_acpi_parser); return *s_acpi_parser; } -void Parser::initialize_limited() -{ - if (!Parser::is_initialized()) { - s_acpi_parser = new Parser(false); - } -} - -bool Parser::is_initialized() +void Parser::set_the(Parser& parser) { - return (s_acpi_parser != nullptr); + ASSERT(!s_acpi_parser); + s_acpi_parser = &parser; } Parser::Parser(bool usable) @@ -56,7 +51,6 @@ Parser::Parser(bool usable) } else { klog() << "ACPI: Limited Initialization. Vital functions are disabled by a request"; } - s_acpi_parser = this; } PhysicalAddress Parser::find_table(const char*) diff --git a/Kernel/ACPI/ACPIParser.h b/Kernel/ACPI/ACPIParser.h index 294af5196fdc..133c29d786dc 100644 --- a/Kernel/ACPI/ACPIParser.h +++ b/Kernel/ACPI/ACPIParser.h @@ -35,12 +35,17 @@ namespace Kernel { namespace ACPI { + class Parser { public: static Parser& the(); - static bool is_initialized(); - static void initialize_limited(); + template<typename ParserType> + static void initialize() + { + set_the(*new ParserType); + } + virtual PhysicalAddress find_table(const char* sig); virtual void try_acpi_reboot(); @@ -58,8 +63,12 @@ class Parser { virtual bool is_operable(); protected: - explicit Parser(bool usable); + explicit Parser(bool usable = false); bool m_operable; + +private: + static void set_the(Parser&); }; + } } diff --git a/Kernel/ACPI/ACPIStaticParser.cpp b/Kernel/ACPI/ACPIStaticParser.cpp index f8d1f3a90749..64828c672e14 100644 --- a/Kernel/ACPI/ACPIStaticParser.cpp +++ b/Kernel/ACPI/ACPIStaticParser.cpp @@ -36,24 +36,6 @@ namespace Kernel { namespace ACPI { -void StaticParser::initialize(PhysicalAddress rsdp) -{ - if (!Parser::is_initialized()) { - new StaticParser(rsdp); - } -} -void StaticParser::initialize_without_rsdp() -{ - if (!Parser::is_initialized()) { - new StaticParser(); - } -} - -bool StaticParser::is_initialized() -{ - return Parser::is_initialized(); -} - void StaticParser::locate_static_data() { locate_main_system_description_table(); diff --git a/Kernel/ACPI/ACPIStaticParser.h b/Kernel/ACPI/ACPIStaticParser.h index ba56baa9fe3e..613ba6a8d66e 100644 --- a/Kernel/ACPI/ACPIStaticParser.h +++ b/Kernel/ACPI/ACPIStaticParser.h @@ -32,12 +32,10 @@ namespace Kernel { namespace ACPI { -class StaticParser : Parser { -public: - static void initialize(PhysicalAddress rsdp); - static void initialize_without_rsdp(); - static bool is_initialized(); +class StaticParser : public Parser { + friend class Parser; +public: virtual PhysicalAddress find_table(const char* sig) override; virtual void try_acpi_reboot() override; virtual bool can_reboot() override; diff --git a/Kernel/ACPI/Initialize.cpp b/Kernel/ACPI/Initialize.cpp index 76a93d707ef0..4b7f68f7ce74 100644 --- a/Kernel/ACPI/Initialize.cpp +++ b/Kernel/ACPI/Initialize.cpp @@ -51,13 +51,13 @@ void initialize() { switch (determine_feature_level()) { case FeatureLevel::Enabled: - ACPI::DynamicParser::initialize_without_rsdp(); + Parser::initialize<DynamicParser>(); break; case FeatureLevel::Limited: - ACPI::StaticParser::initialize_without_rsdp(); + Parser::initialize<StaticParser>(); break; case FeatureLevel::Disabled: - ACPI::Parser::initialize_limited(); + Parser::initialize<Parser>(); break; } }
462e223c3dc597cb102225932b2b195975a382e9
2020-01-25 13:39:52
Emanuel Sprung
meta: Fix typo + suggest value of export variable.
false
Fix typo + suggest value of export variable.
meta
diff --git a/Meta/refresh-serenity-qtcreator.sh b/Meta/refresh-serenity-qtcreator.sh index 00ad76b3e8d9..0ddc7a1636cf 100755 --- a/Meta/refresh-serenity-qtcreator.sh +++ b/Meta/refresh-serenity-qtcreator.sh @@ -1,7 +1,7 @@ #!/bin/sh if [ ! -n "$SERENITY_ROOT" ] -then echo "Serenety root not set." +then echo "Serenity root not set. Please set environment variable first. E.g. export SERENITY_ROOT=$(git rev-parse --show-toplevel)" fi cd "$SERENITY_ROOT" || exit 1
d66f143fb7e780ca0b3d1b76e1e65cd0ec5e05b9
2023-02-26 16:51:40
Nico Weber
tests: Add webp size decoding tests for webp
false
Add webp size decoding tests for webp
tests
diff --git a/Tests/LibGfx/TestImageDecoder.cpp b/Tests/LibGfx/TestImageDecoder.cpp index c4b3840121c1..f7b8d6dd6222 100644 --- a/Tests/LibGfx/TestImageDecoder.cpp +++ b/Tests/LibGfx/TestImageDecoder.cpp @@ -17,6 +17,7 @@ #include <LibGfx/PNGLoader.h> #include <LibGfx/PPMLoader.h> #include <LibGfx/TGALoader.h> +#include <LibGfx/WebPLoader.h> #include <LibTest/TestCase.h> #include <stdio.h> #include <string.h> @@ -219,3 +220,74 @@ TEST_CASE(test_targa_top_left_compressed) auto frame = MUST(plugin_decoder->frame(0)); EXPECT(frame.duration == 0); } + +TEST_CASE(test_webp_simple_lossy) +{ + auto file = MUST(Core::MappedFile::map(TEST_INPUT("simple-vp8.webp"sv))); + EXPECT(MUST(Gfx::WebPImageDecoderPlugin::sniff(file->bytes()))); + auto plugin_decoder = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); + EXPECT(plugin_decoder->initialize()); + + EXPECT_EQ(plugin_decoder->frame_count(), 1u); + EXPECT(!plugin_decoder->is_animated()); + EXPECT(!plugin_decoder->loop_count()); + + EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(240, 240)); +} + +TEST_CASE(test_webp_simple_lossless) +{ + auto file = MUST(Core::MappedFile::map(TEST_INPUT("simple-vp8l.webp"sv))); + EXPECT(MUST(Gfx::WebPImageDecoderPlugin::sniff(file->bytes()))); + auto plugin_decoder = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); + EXPECT(plugin_decoder->initialize()); + + EXPECT_EQ(plugin_decoder->frame_count(), 1u); + EXPECT(!plugin_decoder->is_animated()); + EXPECT(!plugin_decoder->loop_count()); + + EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(386, 395)); +} + +TEST_CASE(test_webp_extended_lossy) +{ + auto file = MUST(Core::MappedFile::map(TEST_INPUT("extended-lossy.webp"sv))); + EXPECT(MUST(Gfx::WebPImageDecoderPlugin::sniff(file->bytes()))); + auto plugin_decoder = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); + EXPECT(plugin_decoder->initialize()); + + EXPECT_EQ(plugin_decoder->frame_count(), 1u); + EXPECT(!plugin_decoder->is_animated()); + EXPECT(!plugin_decoder->loop_count()); + + EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(417, 223)); +} + +TEST_CASE(test_webp_extended_lossless) +{ + auto file = MUST(Core::MappedFile::map(TEST_INPUT("extended-lossless.webp"sv))); + EXPECT(MUST(Gfx::WebPImageDecoderPlugin::sniff(file->bytes()))); + auto plugin_decoder = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); + EXPECT(plugin_decoder->initialize()); + + EXPECT_EQ(plugin_decoder->frame_count(), 1u); + EXPECT(!plugin_decoder->is_animated()); + EXPECT(!plugin_decoder->loop_count()); + + EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(417, 223)); +} + +TEST_CASE(test_webp_extended_lossless_animated) +{ + auto file = MUST(Core::MappedFile::map(TEST_INPUT("extended-lossless-animated.webp"sv))); + EXPECT(MUST(Gfx::WebPImageDecoderPlugin::sniff(file->bytes()))); + auto plugin_decoder = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); + EXPECT(plugin_decoder->initialize()); + + // FIXME: These three lines are wrong. + EXPECT_EQ(plugin_decoder->frame_count(), 1u); + EXPECT(!plugin_decoder->is_animated()); + EXPECT(!plugin_decoder->loop_count()); + + EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(990, 1050)); +}
6c6c94f05a0b06bee91edc39e11c0a6725f440c1
2022-11-05 19:42:23
MacDue
libweb: Use relative units for gradients until painting
false
Use relative units for gradients until painting
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/GradientPainting.cpp b/Userland/Libraries/LibWeb/Painting/GradientPainting.cpp index 6725949d7e68..c049eec6f772 100644 --- a/Userland/Libraries/LibWeb/Painting/GradientPainting.cpp +++ b/Userland/Libraries/LibWeb/Painting/GradientPainting.cpp @@ -33,7 +33,7 @@ static float calulate_gradient_length(Gfx::IntSize const& gradient_size, float g return calulate_gradient_length(gradient_size, sin_angle, cos_angle); } -static ColorStopList resolve_color_stop_positions(auto const& color_stop_list, float gradient_length, auto resolve_position_to_float) +static ColorStopList resolve_color_stop_positions(auto const& color_stop_list, auto resolve_position_to_float) { VERIFY(color_stop_list.size() >= 2); ColorStopList resolved_color_stops; @@ -56,7 +56,7 @@ static ColorStopList resolve_color_stop_positions(auto const& color_stop_list, f // 1. If the first color stop does not have a position, set its position to 0%. resolved_color_stops.first().position = 0; // If the last color stop does not have a position, set its position to 100% - resolved_color_stops.last().position = gradient_length; + resolved_color_stops.last().position = 1.0f; // 2. If a color stop or transition hint has a position that is less than the // specified position of any color stop or transition hint before it in the list, @@ -131,8 +131,8 @@ LinearGradientData resolve_linear_gradient_data(Layout::Node const& node, Gfx::F auto gradient_length_px = calulate_gradient_length(gradient_size.to_rounded<int>(), gradient_angle); auto gradient_length = CSS::Length::make_px(gradient_length_px); - auto resolved_color_stops = resolve_color_stop_positions(linear_gradient.color_stop_list(), gradient_length_px, [&](auto const& length_percentage) { - return length_percentage.resolved(node, gradient_length).to_px(node); + auto resolved_color_stops = resolve_color_stop_positions(linear_gradient.color_stop_list(), [&](auto const& length_percentage) { + return length_percentage.resolved(node, gradient_length).to_px(node) / gradient_length_px; }); Optional<float> repeat_length = {}; @@ -145,8 +145,8 @@ LinearGradientData resolve_linear_gradient_data(Layout::Node const& node, Gfx::F ConicGradientData resolve_conic_gradient_data(Layout::Node const& node, CSS::ConicGradientStyleValue const& conic_gradient) { CSS::Angle one_turn(360.0f, CSS::Angle::Type::Deg); - auto resolved_color_stops = resolve_color_stop_positions(conic_gradient.color_stop_list(), one_turn.to_degrees(), [&](auto const& angle_percentage) { - return angle_percentage.resolved(node, one_turn).to_degrees(); + auto resolved_color_stops = resolve_color_stop_positions(conic_gradient.color_stop_list(), [&](auto const& angle_percentage) { + return angle_percentage.resolved(node, one_turn).to_degrees() / one_turn.to_degrees(); }); return { conic_gradient.angle_degrees(), resolved_color_stops }; } @@ -180,36 +180,62 @@ static float color_stop_step(ColorStop const& previous_stop, ColorStop const& ne class GradientLine { public: - GradientLine(int length, int start_offset, Span<ColorStop const> color_stops) + GradientLine(int color_count, Span<ColorStop const> color_stops) + : GradientLine(color_count, color_count, 0, false, color_stops) {}; + + GradientLine(int color_count, int gradient_length, int start_offset, bool repeating, Span<ColorStop const> color_stops) + : m_start_offset { start_offset } + , m_repeating { repeating } { - m_gradient_line_colors.resize(length); + // Note: color_count will be < gradient_length for repeating gradients. + m_gradient_line_colors.resize(color_count); // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in: // https://drafts.csswg.org/css-images/#coloring-gradient-line - for (int loc = 0; loc < length; loc++) { + for (int loc = 0; loc < color_count; loc++) { + auto relative_loc = float(loc + start_offset) / gradient_length; Gfx::Color gradient_color = color_stops[0].color.mixed_with( color_stops[1].color, - color_stop_step( - color_stops[0], - color_stops[1], - loc + start_offset)); + color_stop_step(color_stops[0], color_stops[1], relative_loc)); for (size_t i = 1; i < color_stops.size() - 1; i++) { gradient_color = gradient_color.mixed_with( color_stops[i + 1].color, - color_stop_step( - color_stops[i], - color_stops[i + 1], - loc + start_offset)); + color_stop_step(color_stops[i], color_stops[i + 1], relative_loc)); } m_gradient_line_colors[loc] = gradient_color; } } - Gfx::Color lookup_color(int loc) const + Gfx::Color get_color(int index) const + { + return m_gradient_line_colors[clamp(index, 0, m_gradient_line_colors.size() - 1)]; + } + + Gfx::Color sample_color(float loc) const + { + auto repeat_wrap_if_required = [&](int loc) { + if (m_repeating) + return (loc + m_start_offset) % static_cast<int>(m_gradient_line_colors.size()); + return loc; + }; + auto int_loc = static_cast<int>(loc); + auto blend = loc - int_loc; + // Blend between the two neighbouring colors (this fixes some nasty aliasing issues at small angles) + return get_color(repeat_wrap_if_required(int_loc)).mixed_with(get_color(repeat_wrap_if_required(int_loc + 1)), blend); + } + + void paint_into_rect(Gfx::Painter& painter, Gfx::IntRect const& rect, auto location_transform) { - return m_gradient_line_colors[clamp(loc, 0, m_gradient_line_colors.size() - 1)]; + for (int y = 0; y < rect.height(); y++) { + for (int x = 0; x < rect.width(); x++) { + auto gradient_color = sample_color(location_transform(x, y)); + painter.set_pixel(rect.x() + x, rect.y() + y, gradient_color, gradient_color.alpha() < 255); + } + } } private: + int m_start_offset; + bool m_repeating; Vector<Gfx::Color, 1024> m_gradient_line_colors; }; @@ -220,9 +246,9 @@ void paint_linear_gradient(PaintContext& context, Gfx::IntRect const& gradient_r AK::sincos(angle, sin_angle, cos_angle); // Full length of the gradient - auto length = calulate_gradient_length(gradient_rect.size(), sin_angle, cos_angle); + auto gradient_length_px = round_to<int>(calulate_gradient_length(gradient_rect.size(), sin_angle, cos_angle)); - Gfx::FloatPoint offset { cos_angle * (length / 2), sin_angle * (length / 2) }; + Gfx::FloatPoint offset { cos_angle * (gradient_length_px / 2), sin_angle * (gradient_length_px / 2) }; auto center = gradient_rect.translated(-gradient_rect.location()).center(); auto start_point = center.to_type<float>() - offset; @@ -230,44 +256,28 @@ void paint_linear_gradient(PaintContext& context, Gfx::IntRect const& gradient_r // Rotate gradient line to be horizontal auto rotated_start_point_x = start_point.x() * cos_angle - start_point.y() * -sin_angle; - auto gradient_color_count = round_to<int>(data.repeat_length.value_or(length)); + bool repeating = data.repeat_length.has_value(); + auto gradient_color_count = round_to<int>(data.repeat_length.value_or(1.0f) * gradient_length_px); auto& color_stops = data.color_stops; - auto start_offset = data.repeat_length.has_value() ? color_stops.first().position : 0.0f; + auto start_offset = repeating ? color_stops.first().position : 0.0f; + auto start_offset_px = round_to<int>(start_offset * gradient_length_px); - GradientLine gradient_line(gradient_color_count, round_to<int>(start_offset), color_stops); - - auto repeat_wrap_if_required = [&](float loc) { - if (data.repeat_length.has_value()) - loc = AK::fmod(loc + length, *data.repeat_length); - return loc; - }; - - for (int y = 0; y < gradient_rect.height(); y++) { - for (int x = 0; x < gradient_rect.width(); x++) { - auto loc = repeat_wrap_if_required((x * cos_angle - (gradient_rect.height() - y) * -sin_angle) - rotated_start_point_x - start_offset); - auto blend = loc - static_cast<int>(loc); - // Blend between the two neighbouring colors (this fixes some nasty aliasing issues at small angles) - auto gradient_color = gradient_line.lookup_color(loc).mixed_with(gradient_line.lookup_color(repeat_wrap_if_required(loc + 1)), blend); - context.painter().set_pixel(gradient_rect.x() + x, gradient_rect.y() + y, gradient_color, gradient_color.alpha() < 255); - } - } + GradientLine gradient_line(gradient_color_count, gradient_length_px, start_offset_px, repeating, color_stops); + gradient_line.paint_into_rect(context.painter(), gradient_rect, [&](int x, int y) { + return (x * cos_angle - (gradient_rect.height() - y) * -sin_angle) - rotated_start_point_x; + }); } void paint_conic_gradient(PaintContext& context, Gfx::IntRect const& gradient_rect, ConicGradientData const& data, Gfx::IntPoint position) { // FIXME: Do we need/want sub-degree accuracy for the gradient line? - GradientLine gradient_line(360, 0, data.color_stops); + GradientLine gradient_line(360, data.color_stops); float start_angle = (360.0f - data.start_angle) + 90.0f; - for (int y = 0; y < gradient_rect.height(); y++) { - for (int x = 0; x < gradient_rect.width(); x++) { - auto point = Gfx::IntPoint { x, y } - position; - // FIXME: We could probably get away with some approximation here: - float loc = fmod((AK::atan2(float(point.y()), float(point.x())) * 180.0f / AK::Pi<float> + 360.0f + start_angle), 360.0f); - auto blend = loc - static_cast<int>(loc); - auto gradient_color = gradient_line.lookup_color(loc).mixed_with(gradient_line.lookup_color(loc + 1), blend); - context.painter().set_pixel(gradient_rect.x() + x, gradient_rect.y() + y, gradient_color, gradient_color.alpha() < 255); - } - } + gradient_line.paint_into_rect(context.painter(), gradient_rect, [&](int x, int y) { + auto point = Gfx::IntPoint { x, y } - position; + // FIXME: We could probably get away with some approximation here: + return fmod((AK::atan2(float(point.y()), float(point.x())) * 180.0f / AK::Pi<float> + 360.0f + start_angle), 360.0f); + }); } }
91c210c39a013f57a12202e6d5fc18fad95eac3b
2021-04-26 22:27:57
DexesTTP
libgui: Make common locations configurable
false
Make common locations configurable
libgui
diff --git a/Base/home/anon/.config/CommonLocations.json b/Base/home/anon/.config/CommonLocations.json new file mode 100644 index 000000000000..e9b5ea26963a --- /dev/null +++ b/Base/home/anon/.config/CommonLocations.json @@ -0,0 +1,7 @@ +[ + { "name": "Root", "path": "/" }, + { "name": "Home", "path": "/home/anon" }, + { "name": "Documents", "path": "/home/anon/Documents" }, + { "name": "Desktop", "path": "/home/anon/Desktop" }, + { "name": "Downloads", "path": "/home/anon/Downloads" } +] diff --git a/Userland/Libraries/LibGUI/CMakeLists.txt b/Userland/Libraries/LibGUI/CMakeLists.txt index eba646ac9308..36a6a92b5e0c 100644 --- a/Userland/Libraries/LibGUI/CMakeLists.txt +++ b/Userland/Libraries/LibGUI/CMakeLists.txt @@ -20,6 +20,7 @@ set(SOURCES ColorInput.cpp ColorPicker.cpp ColumnsView.cpp + CommonLocationsProvider.cpp ComboBox.cpp Command.cpp Desktop.cpp diff --git a/Userland/Libraries/LibGUI/CommonLocationsProvider.cpp b/Userland/Libraries/LibGUI/CommonLocationsProvider.cpp new file mode 100644 index 000000000000..2fa15178510e --- /dev/null +++ b/Userland/Libraries/LibGUI/CommonLocationsProvider.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021, Dex♪ <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <AK/JsonArray.h> +#include <AK/JsonObject.h> +#include <AK/LexicalPath.h> +#include <AK/String.h> +#include <AK/Vector.h> +#include <LibCore/ConfigFile.h> +#include <LibCore/File.h> +#include <LibCore/StandardPaths.h> +#include <LibGUI/CommonLocationsProvider.h> +#include <unistd.h> + +namespace GUI { + +static bool s_initialized = false; +static Vector<CommonLocationsProvider::CommonLocation> s_common_locations; + +static void initialize_if_needed() +{ + if (s_initialized) + return; + + auto user_config = String::formatted("{}/CommonLocations.json", Core::StandardPaths::config_directory()); + if (Core::File::exists(user_config)) { + CommonLocationsProvider::load_from_json(user_config); + return; + } + + // Fallback : If the user doesn't have custom locations, use some default ones. + s_common_locations.append({ "Root", "/" }); + s_common_locations.append({ "Home", Core::StandardPaths::home_directory() }); + s_common_locations.append({ "Downloads", Core::StandardPaths::downloads_directory() }); + s_initialized = true; +} + +void CommonLocationsProvider::load_from_json(const String& json_path) +{ + auto file = Core::File::construct(json_path); + if (!file->open(Core::IODevice::ReadOnly)) { + dbgln("Unable to open {}", file->filename()); + return; + } + + auto json = JsonValue::from_string(file->read_all()); + if (!json.has_value()) { + dbgln("Common locations file {} is not a valid JSON file.", file->filename()); + return; + } + if (!json.value().is_array()) { + dbgln("Common locations file {} should contain a JSON array.", file->filename()); + return; + } + + s_common_locations.clear(); + auto contents = json.value().as_array(); + for (auto i = 0; i < contents.size(); ++i) { + auto entry_value = contents.at(i); + if (!entry_value.is_object()) + continue; + auto entry = entry_value.as_object(); + auto name = entry.get("name").to_string(); + auto path = entry.get("path").to_string(); + s_common_locations.append({ name, path }); + } + + s_initialized = true; +} + +const Vector<CommonLocationsProvider::CommonLocation>& CommonLocationsProvider::common_locations() +{ + initialize_if_needed(); + return s_common_locations; +} + +} diff --git a/Userland/Libraries/LibGUI/CommonLocationsProvider.h b/Userland/Libraries/LibGUI/CommonLocationsProvider.h new file mode 100644 index 000000000000..b5d3faff591a --- /dev/null +++ b/Userland/Libraries/LibGUI/CommonLocationsProvider.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021, Dex♪ <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Forward.h> +#include <LibGUI/Forward.h> +#include <sys/types.h> + +namespace GUI { + +class CommonLocationsProvider { +public: + struct CommonLocation { + String name; + String path; + }; + + static void load_from_json(const String& json_path); + static const Vector<CommonLocation>& common_locations(); +}; + +} diff --git a/Userland/Libraries/LibGUI/FilePicker.cpp b/Userland/Libraries/LibGUI/FilePicker.cpp index 27358175226a..1685dcacea7c 100644 --- a/Userland/Libraries/LibGUI/FilePicker.cpp +++ b/Userland/Libraries/LibGUI/FilePicker.cpp @@ -11,6 +11,7 @@ #include <LibGUI/Action.h> #include <LibGUI/BoxLayout.h> #include <LibGUI/Button.h> +#include <LibGUI/CommonLocationsProvider.h> #include <LibGUI/FileIconProvider.h> #include <LibGUI/FilePicker.h> #include <LibGUI/FilePickerDialogGML.h> @@ -207,14 +208,20 @@ FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& file_ } }; - auto& common_locations_frame = *widget.find_descendant_of_type_named<GUI::Frame>("common_locations_frame"); + auto& common_locations_frame = *widget.find_descendant_of_type_named<Frame>("common_locations_frame"); common_locations_frame.set_background_role(Gfx::ColorRole::Tray); - auto add_common_location_button = [&](auto& name, String path) -> GUI::Button& { + m_model->on_complete = [&] { + for (auto location_button : m_common_location_buttons) + location_button.button.set_checked(m_model->root_path() == location_button.path); + }; + + for (auto& location : CommonLocationsProvider::common_locations()) { + String path = location.path; auto& button = common_locations_frame.add<GUI::Button>(); button.set_button_style(Gfx::ButtonStyle::Tray); button.set_foreground_role(Gfx::ColorRole::TrayText); button.set_text_alignment(Gfx::TextAlignment::CenterLeft); - button.set_text(move(name)); + button.set_text(location.name); button.set_icon(FileIconProvider::icon_for_path(path).bitmap_for_size(16)); button.set_fixed_height(22); button.set_checkable(true); @@ -222,26 +229,8 @@ FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& file_ button.on_click = [this, path] { set_path(path); }; - return button; - }; - - auto& root_button = add_common_location_button("Root", "/"); - auto& home_button = add_common_location_button("Home", Core::StandardPaths::home_directory()); - auto& desktop_button = add_common_location_button("Desktop", Core::StandardPaths::desktop_directory()); - - m_model->on_complete = [&] { - if (m_model->root_path() == Core::StandardPaths::home_directory()) { - home_button.set_checked(true); - } else if (m_model->root_path() == Core::StandardPaths::desktop_directory()) { - desktop_button.set_checked(true); - } else if (m_model->root_path() == "/") { - root_button.set_checked(true); - } else { - home_button.set_checked(false); - desktop_button.set_checked(false); - root_button.set_checked(false); - } - }; + m_common_location_buttons.append({ path, button }); + } set_path(path); } diff --git a/Userland/Libraries/LibGUI/FilePicker.h b/Userland/Libraries/LibGUI/FilePicker.h index eeb089d4c443..595a6465221e 100644 --- a/Userland/Libraries/LibGUI/FilePicker.h +++ b/Userland/Libraries/LibGUI/FilePicker.h @@ -59,12 +59,18 @@ class FilePicker final } } + struct CommonLocationButton { + String path; + Button& button; + }; + RefPtr<MultiView> m_view; NonnullRefPtr<FileSystemModel> m_model; LexicalPath m_selected_file; RefPtr<TextBox> m_filename_textbox; RefPtr<TextBox> m_location_textbox; + Vector<CommonLocationButton> m_common_location_buttons; RefPtr<Menu> m_context_menu; Mode m_mode { Mode::Open }; };
203008474602d920c57b3eedc681ffd0a216f3a7
2020-09-26 03:30:50
asynts
ak: Borrow exact format syntax form std::format.
false
Borrow exact format syntax form std::format.
ak
diff --git a/AK/Format.cpp b/AK/Format.cpp index 18a3819c25b9..7052fcadb643 100644 --- a/AK/Format.cpp +++ b/AK/Format.cpp @@ -73,28 +73,32 @@ static void write_escaped_literal(StringBuilder& builder, StringView literal) } } -static size_t parse_number(StringView input) +static bool parse_number(GenericLexer& lexer, size_t& value) { - size_t value = 0; - - for (char ch : input) { - value *= 10; - value += ch - '0'; + value = 0; + + bool consumed_at_least_one = false; + while (!lexer.is_eof()) { + if (lexer.next_is(is_digit)) { + value *= 10; + value += lexer.consume() - '0'; + consumed_at_least_one = true; + } else { + break; + } } - return value; + return consumed_at_least_one; } +constexpr size_t use_next_index = NumericLimits<size_t>::max(); + static bool parse_format_specifier(StringView input, FormatSpecifier& specifier) { - specifier.index = NumericLimits<size_t>::max(); - GenericLexer lexer { input }; - auto index = lexer.consume_while([](char ch) { return StringView { "0123456789" }.contains(ch); }); - - if (index.length() > 0) - specifier.index = parse_number(index); + if (!parse_number(lexer, specifier.index)) + specifier.index = use_next_index; if (!lexer.consume_specific(':')) return lexer.is_eof(); @@ -103,6 +107,20 @@ static bool parse_format_specifier(StringView input, FormatSpecifier& specifier) return true; } +static bool parse_nested_replacement_field(GenericLexer& lexer, size_t& index) +{ + if (!lexer.consume_specific('{')) + return false; + + if (!parse_number(lexer, index)) + index = use_next_index; + + if (!lexer.consume_specific('}')) + ASSERT_NOT_REACHED(); + + return true; +} + } // namespace namespace AK { @@ -137,8 +155,7 @@ void vformat(StringBuilder& builder, StringView fmtstr, AK::Span<const TypeErase ASSERT_NOT_REACHED(); auto& parameter = parameters[specifier.index]; - if (!parameter.formatter(builder, parameter.value, specifier.flags)) - ASSERT_NOT_REACHED(); + parameter.formatter(builder, parameter.value, specifier.flags, parameters); vformat(builder, fmtstr.substring_view(closing + 1), parameters, argument_index); } @@ -149,43 +166,133 @@ void vformat(const LogStream& stream, StringView fmtstr, Span<const TypeErasedPa stream << builder.to_string(); } -bool Formatter<StringView>::parse(StringView flags) +void StandardFormatter::parse(StringView specifier) { - return flags.is_empty(); + GenericLexer lexer { specifier }; + + if (StringView { "<^>" }.contains(lexer.peek(1))) { + ASSERT(!lexer.next_is(is_any_of("{}"))); + m_fill = lexer.consume(); + } + + if (lexer.consume_specific('<')) + m_align = Align::Left; + else if (lexer.consume_specific('^')) + m_align = Align::Center; + else if (lexer.consume_specific('>')) + m_align = Align::Right; + + if (lexer.consume_specific('-')) + m_sign = Sign::NegativeOnly; + else if (lexer.consume_specific('+')) + m_sign = Sign::PositiveAndNegative; + else if (lexer.consume_specific(' ')) + m_sign = Sign::ReserveSpace; + + if (lexer.consume_specific('#')) + m_alternative_form = true; + + if (lexer.consume_specific('0')) + m_zero_pad = true; + + if (size_t index = 0; parse_nested_replacement_field(lexer, index)) + m_width = value_from_arg + index; + else if (size_t width = 0; parse_number(lexer, width)) + m_width = width; + + if (lexer.consume_specific('.')) { + if (size_t index = 0; parse_nested_replacement_field(lexer, index)) + m_precision = value_from_arg + index; + else if (size_t precision = 0; parse_number(lexer, precision)) + m_precision = precision; + } + + if (lexer.consume_specific('b')) + m_mode = Mode::Binary; + else if (lexer.consume_specific('d')) + m_mode = Mode::Decimal; + else if (lexer.consume_specific('o')) + m_mode = Mode::Octal; + else if (lexer.consume_specific('x')) + m_mode = Mode::Hexadecimal; + else if (lexer.consume_specific('c')) + m_mode = Mode::Character; + else if (lexer.consume_specific('s')) + m_mode = Mode::String; + else if (lexer.consume_specific('p')) + m_mode = Mode::Pointer; + + if (!lexer.is_eof()) + dbg() << __PRETTY_FUNCTION__ << " did not consume '" << lexer.remaining() << "'"; + + ASSERT(lexer.is_eof()); } -void Formatter<StringView>::format(StringBuilder& builder, StringView value) + +void Formatter<StringView>::format(StringBuilder& builder, StringView value, Span<const TypeErasedParameter>) { + if (m_align != Align::Default) + TODO(); + if (m_sign != Sign::Default) + ASSERT_NOT_REACHED(); + if (m_alternative_form) + ASSERT_NOT_REACHED(); + if (m_zero_pad) + ASSERT_NOT_REACHED(); + if (m_width != value_not_set) + TODO(); + if (m_precision != value_not_set) + TODO(); + if (m_mode != Mode::Default && m_mode != Mode::String) + ASSERT_NOT_REACHED(); + builder.append(value); } template<typename T> -bool Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type>::parse(StringView flags) +void Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type>::format(StringBuilder& builder, T value, Span<const TypeErasedParameter> parameters) { - GenericLexer lexer { flags }; + if (m_align != Align::Default) + TODO(); + if (m_sign != Sign::Default) + TODO(); + if (m_alternative_form) + TODO(); + if (m_precision != value_not_set) + ASSERT_NOT_REACHED(); + if (m_mode == Mode::Character) + TODO(); + + int base; + if (m_mode == Mode::Binary) + TODO(); + else if (m_mode == Mode::Octal) + TODO(); + else if (m_mode == Mode::Decimal || m_mode == Mode::Default) + base = 10; + else if (m_mode == Mode::Hexadecimal) + base = 16; + else + ASSERT_NOT_REACHED(); - if (lexer.consume_specific('0')) - zero_pad = true; + size_t width = m_width; + if (m_width >= value_from_arg) { + const auto parameter = parameters.at(m_width - value_from_arg); - auto field_width = lexer.consume_while([](char ch) { return StringView { "0123456789" }.contains(ch); }); - if (field_width.length() > 0) - this->field_width = parse_number(field_width); + // FIXME: Totally unsave cast. We should store the type in TypeErasedParameter. For compactness it could be smart to + // find a few addresses that can not be valid function pointers and encode the type information there? + width = *reinterpret_cast<const size_t*>(parameter.value); + } - if (lexer.consume_specific('x')) - hexadecimal = true; + // FIXME: We really need one canonical print implementation that just takes a base. + (void)base; - return lexer.is_eof(); -} -template<typename T> -void Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type>::format(StringBuilder& builder, T value) -{ char* bufptr; - - if (hexadecimal) - PrintfImplementation::print_hex([&](auto, char ch) { builder.append(ch); }, bufptr, value, false, false, false, zero_pad, field_width); + if (m_mode == Mode::Hexadecimal) + PrintfImplementation::print_hex([&](auto, char ch) { builder.append(ch); }, bufptr, value, false, false, false, m_zero_pad, width); else if (IsSame<typename MakeUnsigned<T>::Type, T>::value) - PrintfImplementation::print_u64([&](auto, char ch) { builder.append(ch); }, bufptr, value, false, zero_pad, field_width); + PrintfImplementation::print_u64([&](auto, char ch) { builder.append(ch); }, bufptr, value, false, m_zero_pad, width); else - PrintfImplementation::print_i64([&](auto, char ch) { builder.append(ch); }, bufptr, value, false, zero_pad, field_width); + PrintfImplementation::print_i64([&](auto, char ch) { builder.append(ch); }, bufptr, value, false, m_zero_pad, width); } template struct Formatter<unsigned char, void>; diff --git a/AK/Format.h b/AK/Format.h index dde28aac3c5c..1ab74b599d07 100644 --- a/AK/Format.h +++ b/AK/Format.h @@ -38,35 +38,75 @@ namespace AK { template<typename T, typename = void> struct Formatter; +struct TypeErasedParameter { + const void* value; + void (*formatter)(StringBuilder& builder, const void* value, StringView specifier, Span<const TypeErasedParameter> parameters); +}; + } // namespace AK namespace AK::Detail::Format { template<typename T> -bool format_value(StringBuilder& builder, const void* value, StringView flags) +void format_value(StringBuilder& builder, const void* value, StringView specifier, AK::Span<const TypeErasedParameter> parameters) { Formatter<T> formatter; - if (!formatter.parse(flags)) - return false; - - formatter.format(builder, *static_cast<const T*>(value)); - return true; + formatter.parse(specifier); + formatter.format(builder, *static_cast<const T*>(value), parameters); } } // namespace AK::Detail::Format namespace AK { -struct TypeErasedParameter { - const void* value; - bool (*formatter)(StringBuilder& builder, const void* value, StringView flags); +constexpr size_t max_format_arguments = 256; + +// We use the same format for most types for consistency. This is taken directly from std::format. +// Not all valid options do anything yet. +// https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification +struct StandardFormatter { + enum class Align { + Default, + Left, + Right, + Center, + }; + enum class Sign { + NegativeOnly, + PositiveAndNegative, + ReserveSpace, + Default = NegativeOnly + }; + enum class Mode { + Default, + Binary, + Decimal, + Octal, + Hexadecimal, + Character, + String, + Pointer, + }; + + static constexpr size_t value_not_set = 0; + static constexpr size_t value_from_arg = NumericLimits<size_t>::max() - max_format_arguments; + + Align m_align = Align::Default; + Sign m_sign = Sign::NegativeOnly; + Mode m_mode = Mode::Default; + bool m_alternative_form = false; + char m_fill = ' '; + bool m_zero_pad = false; + size_t m_width = value_not_set; + size_t m_precision = value_not_set; + + void parse(StringView specifier); }; template<> -struct Formatter<StringView> { - bool parse(StringView flags); - void format(StringBuilder& builder, StringView value); +struct Formatter<StringView> : StandardFormatter { + void format(StringBuilder& builder, StringView value, Span<const TypeErasedParameter>); }; template<> struct Formatter<const char*> : Formatter<StringView> { @@ -82,18 +122,14 @@ struct Formatter<String> : Formatter<StringView> { }; template<typename T> -struct Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type> { - bool parse(StringView flags); - void format(StringBuilder&, T value); - - bool zero_pad { false }; - bool hexadecimal { false }; - size_t field_width { 0 }; +struct Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type> : StandardFormatter { + void format(StringBuilder&, T value, Span<const TypeErasedParameter>); }; template<typename... Parameters> Array<TypeErasedParameter, sizeof...(Parameters)> make_type_erased_parameters(const Parameters&... parameters) { + static_assert(sizeof...(Parameters) <= max_format_arguments); return { TypeErasedParameter { &parameters, Detail::Format::format_value<Parameters> }... }; }
ee1379520a68cb169040a3782d9f54412d89845c
2022-04-18 02:30:35
Linus Groh
libjs: Add missing whitespace around namespace curly braces
false
Add missing whitespace around namespace curly braces
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/BooleanObject.cpp b/Userland/Libraries/LibJS/Runtime/BooleanObject.cpp index d8b519795529..948016f9f76e 100644 --- a/Userland/Libraries/LibJS/Runtime/BooleanObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/BooleanObject.cpp @@ -19,4 +19,5 @@ BooleanObject::BooleanObject(bool value, Object& prototype) , m_value(value) { } + } diff --git a/Userland/Libraries/LibJS/Runtime/BooleanObject.h b/Userland/Libraries/LibJS/Runtime/BooleanObject.h index 6b3ef6368b85..a1ed7f6752e3 100644 --- a/Userland/Libraries/LibJS/Runtime/BooleanObject.h +++ b/Userland/Libraries/LibJS/Runtime/BooleanObject.h @@ -9,6 +9,7 @@ #include <LibJS/Runtime/Object.h> namespace JS { + class BooleanObject : public Object { JS_OBJECT(BooleanObject, Object); @@ -23,4 +24,5 @@ class BooleanObject : public Object { private: bool m_value { false }; }; + } diff --git a/Userland/Libraries/LibJS/Runtime/BooleanPrototype.cpp b/Userland/Libraries/LibJS/Runtime/BooleanPrototype.cpp index cee8afe7b826..4d36bcbba9d1 100644 --- a/Userland/Libraries/LibJS/Runtime/BooleanPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/BooleanPrototype.cpp @@ -50,4 +50,5 @@ JS_DEFINE_NATIVE_FUNCTION(BooleanPrototype::value_of) return Value(static_cast<BooleanObject const&>(this_value.as_object()).boolean()); } + } diff --git a/Userland/Libraries/LibJS/Runtime/GeneratorFunctionPrototype.cpp b/Userland/Libraries/LibJS/Runtime/GeneratorFunctionPrototype.cpp index 7b9fe61f9438..aff916cd6f78 100644 --- a/Userland/Libraries/LibJS/Runtime/GeneratorFunctionPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/GeneratorFunctionPrototype.cpp @@ -25,4 +25,5 @@ void GeneratorFunctionPrototype::initialize(GlobalObject& global_object) // 27.3.3.3 GeneratorFunction.prototype [ @@toStringTag ], https://tc39.es/ecma262/#sec-generatorfunction.prototype-@@tostringtag define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(vm, "GeneratorFunction"), Attribute::Configurable); } + } diff --git a/Userland/Libraries/LibJS/Runtime/NumberObject.cpp b/Userland/Libraries/LibJS/Runtime/NumberObject.cpp index f188c0888bf7..8a4313706e3c 100644 --- a/Userland/Libraries/LibJS/Runtime/NumberObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/NumberObject.cpp @@ -19,4 +19,5 @@ NumberObject::NumberObject(double value, Object& prototype) , m_value(value) { } + } diff --git a/Userland/Libraries/LibJS/Runtime/StringIterator.cpp b/Userland/Libraries/LibJS/Runtime/StringIterator.cpp index 1681a57591f9..eb1c931477ce 100644 --- a/Userland/Libraries/LibJS/Runtime/StringIterator.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringIterator.cpp @@ -21,4 +21,5 @@ StringIterator::StringIterator(String string, Object& prototype) , m_iterator(Utf8View(m_string).begin()) { } + } diff --git a/Userland/Libraries/LibJS/Script.cpp b/Userland/Libraries/LibJS/Script.cpp index 74862ddc82ef..c9104cc7c4bd 100644 --- a/Userland/Libraries/LibJS/Script.cpp +++ b/Userland/Libraries/LibJS/Script.cpp @@ -35,4 +35,5 @@ Script::Script(Realm& realm, StringView filename, NonnullRefPtr<Program> parse_n , m_host_defined(host_defined) { } + }
93b9929391e2e797d8ae0ec4b6e30f32ce71f963
2020-09-27 04:32:11
Luke
libc: Add paths.h with some default mail directory for now
false
Add paths.h with some default mail directory for now
libc
diff --git a/Libraries/LibC/paths.h b/Libraries/LibC/paths.h new file mode 100644 index 000000000000..07cfcdbb0d43 --- /dev/null +++ b/Libraries/LibC/paths.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020, The SerenityOS developers. + * 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. + */ + +#pragma once + +// FIXME: This is just a default value to satisfy OpenSSH, feel free to change it. +#define _PATH_MAILDIR "/var/mail"
e1b4aa94db97a4ad46092c76cc045c144abfc395
2025-01-01 16:30:53
sideshowbarker
meta: Fix “shadow-including-ancestors-descendant” generator check
false
Fix “shadow-including-ancestors-descendant” generator check
meta
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp index 60926a92c68f..03e027ef7236 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp @@ -3821,7 +3821,7 @@ JS_DEFINE_NATIVE_FUNCTION(@class_name@::@attribute.getter_callback@) attribute_generator.append(R"~~~( auto const explicitly_set_attr = TRY(throw_dom_exception_if_needed(vm, [&] { return impl->@attribute.cpp_name@(); })); if (explicitly_set_attr) { - if (&impl->shadow_including_root() == &explicitly_set_attr->shadow_including_root()) { + if (&impl->shadow_including_root() == &explicitly_set_attr->root()) { retval = explicitly_set_attr; } else { retval = GC::Ptr<Element> {};
06d76a4717b3678808d6e8339c0f18cbd7ddbb70
2021-01-31 23:36:40
Jean-Baptiste Boric
kernel: Fix PCI bridge enumeration
false
Fix PCI bridge enumeration
kernel
diff --git a/Kernel/FileSystem/ProcFS.cpp b/Kernel/FileSystem/ProcFS.cpp index 7aa5d4deeddc..f09b0fde2ed0 100644 --- a/Kernel/FileSystem/ProcFS.cpp +++ b/Kernel/FileSystem/ProcFS.cpp @@ -363,7 +363,7 @@ static bool procfs$pci(InodeIdentifier, KBufferBuilder& builder) auto obj = array.add_object(); obj.add("seg", address.seg()); obj.add("bus", address.bus()); - obj.add("slot", address.slot()); + obj.add("slot", address.device()); obj.add("function", address.function()); obj.add("vendor_id", id.vendor_id); obj.add("device_id", id.device_id); diff --git a/Kernel/PCI/Access.cpp b/Kernel/PCI/Access.cpp index 4bbe03126570..197f00907b08 100644 --- a/Kernel/PCI/Access.cpp +++ b/Kernel/PCI/Access.cpp @@ -64,7 +64,7 @@ PhysicalID Access::get_physical_id(Address address) const for (auto physical_id : m_physical_ids) { if (physical_id.address().seg() == address.seg() && physical_id.address().bus() == address.bus() - && physical_id.address().slot() == address.slot() + && physical_id.address().device() == address.device() && physical_id.address().function() == address.function()) { return physical_id; } @@ -99,43 +99,43 @@ u16 Access::early_read_type(Address address) return (early_read8_field(address, PCI_CLASS) << 8u) | early_read8_field(address, PCI_SUBCLASS); } -void Access::enumerate_functions(int type, u8 bus, u8 slot, u8 function, Function<void(Address, ID)>& callback) +void Access::enumerate_functions(int type, u8 bus, u8 device, u8 function, Function<void(Address, ID)>& callback, bool recursive) { - dbgln<PCI_DEBUG>("PCI: Enumerating function type={}, bus={}, slot={}, function={}", type, bus, slot, function); - Address address(0, bus, slot, function); + dbgln<PCI_DEBUG>("PCI: Enumerating function type={}, bus={}, device={}, function={}", type, bus, device, function); + Address address(0, bus, device, function); if (type == -1 || type == early_read_type(address)) callback(address, { early_read16_field(address, PCI_VENDOR_ID), early_read16_field(address, PCI_DEVICE_ID) }); - if (early_read_type(address) == PCI_TYPE_BRIDGE) { + if (early_read_type(address) == PCI_TYPE_BRIDGE && recursive) { u8 secondary_bus = early_read8_field(address, PCI_SECONDARY_BUS); #if PCI_DEBUG klog() << "PCI: Found secondary bus: " << secondary_bus; #endif ASSERT(secondary_bus != bus); - enumerate_bus(type, secondary_bus, callback); + enumerate_bus(type, secondary_bus, callback, recursive); } } -void Access::enumerate_slot(int type, u8 bus, u8 slot, Function<void(Address, ID)>& callback) +void Access::enumerate_device(int type, u8 bus, u8 device, Function<void(Address, ID)>& callback, bool recursive) { - dbgln<PCI_DEBUG>("PCI: Enumerating slot type={}, bus={}, slot={}", type, bus, slot); - Address address(0, bus, slot, 0); + dbgln<PCI_DEBUG>("PCI: Enumerating device type={}, bus={}, device={}", type, bus, device); + Address address(0, bus, device, 0); if (early_read16_field(address, PCI_VENDOR_ID) == PCI_NONE) return; - enumerate_functions(type, bus, slot, 0, callback); + enumerate_functions(type, bus, device, 0, callback, recursive); if (!(early_read8_field(address, PCI_HEADER_TYPE) & 0x80)) return; for (u8 function = 1; function < 8; ++function) { - Address address(0, bus, slot, function); + Address address(0, bus, device, function); if (early_read16_field(address, PCI_VENDOR_ID) != PCI_NONE) - enumerate_functions(type, bus, slot, function, callback); + enumerate_functions(type, bus, device, function, callback, recursive); } } -void Access::enumerate_bus(int type, u8 bus, Function<void(Address, ID)>& callback) +void Access::enumerate_bus(int type, u8 bus, Function<void(Address, ID)>& callback, bool recursive) { dbgln<PCI_DEBUG>("PCI: Enumerating bus type={}, bus={}", type, bus); - for (u8 slot = 0; slot < 32; ++slot) - enumerate_slot(type, bus, slot, callback); + for (u8 device = 0; device < 32; ++device) + enumerate_device(type, bus, device, callback, recursive); } void Access::enumerate(Function<void(Address, ID)>& callback) const diff --git a/Kernel/PCI/Access.h b/Kernel/PCI/Access.h index 2b53ceaf594e..ee42c8a0573f 100644 --- a/Kernel/PCI/Access.h +++ b/Kernel/PCI/Access.h @@ -41,9 +41,9 @@ class PCI::Access { void enumerate(Function<void(Address, ID)>&) const; - void enumerate_bus(int type, u8 bus, Function<void(Address, ID)>&); - void enumerate_functions(int type, u8 bus, u8 slot, u8 function, Function<void(Address, ID)>& callback); - void enumerate_slot(int type, u8 bus, u8 slot, Function<void(Address, ID)>& callback); + void enumerate_bus(int type, u8 bus, Function<void(Address, ID)>&, bool recursive); + void enumerate_functions(int type, u8 bus, u8 device, u8 function, Function<void(Address, ID)>& callback, bool recursive); + void enumerate_device(int type, u8 bus, u8 device, Function<void(Address, ID)>& callback, bool recursive); static Access& the(); static bool is_initialized(); diff --git a/Kernel/PCI/Definitions.h b/Kernel/PCI/Definitions.h index 60bb13d868c9..98cc7a67150d 100644 --- a/Kernel/PCI/Definitions.h +++ b/Kernel/PCI/Definitions.h @@ -96,14 +96,14 @@ struct Address { Address(u16 seg) : m_seg(seg) , m_bus(0) - , m_slot(0) + , m_device(0) , m_function(0) { } - Address(u16 seg, u8 bus, u8 slot, u8 function) + Address(u16 seg, u8 bus, u8 device, u8 function) : m_seg(seg) , m_bus(bus) - , m_slot(slot) + , m_device(device) , m_function(function) { } @@ -111,12 +111,12 @@ struct Address { Address(const Address& address) : m_seg(address.seg()) , m_bus(address.bus()) - , m_slot(address.slot()) + , m_device(address.device()) , m_function(address.function()) { } - bool is_null() const { return !m_bus && !m_slot && !m_function; } + bool is_null() const { return !m_bus && !m_device && !m_function; } operator bool() const { return !is_null(); } // Disable default implementations that would use surprising integer promotion. @@ -128,24 +128,24 @@ struct Address { u16 seg() const { return m_seg; } u8 bus() const { return m_bus; } - u8 slot() const { return m_slot; } + u8 device() const { return m_device; } u8 function() const { return m_function; } u32 io_address_for_field(u8 field) const { - return 0x80000000u | (m_bus << 16u) | (m_slot << 11u) | (m_function << 8u) | (field & 0xfc); + return 0x80000000u | (m_bus << 16u) | (m_device << 11u) | (m_function << 8u) | (field & 0xfc); } protected: u32 m_seg { 0 }; u8 m_bus { 0 }; - u8 m_slot { 0 }; + u8 m_device { 0 }; u8 m_function { 0 }; }; inline const LogStream& operator<<(const LogStream& stream, const Address value) { - return stream << "PCI [" << String::formatted("{:04x}:{:02x}:{:02x}:{:02x}", value.seg(), value.bus(), value.slot(), value.function()) << "]"; + return stream << "PCI [" << String::formatted("{:04x}:{:02x}:{:02x}:{:02x}", value.seg(), value.bus(), value.device(), value.function()) << "]"; } struct ChangeableAddress : public Address { @@ -157,17 +157,17 @@ struct ChangeableAddress : public Address { : Address(seg) { } - ChangeableAddress(u16 seg, u8 bus, u8 slot, u8 function) - : Address(seg, bus, slot, function) + ChangeableAddress(u16 seg, u8 bus, u8 device, u8 function) + : Address(seg, bus, device, function) { } void set_seg(u16 seg) { m_seg = seg; } void set_bus(u8 bus) { m_bus = bus; } - void set_slot(u8 slot) { m_slot = slot; } + void set_device(u8 device) { m_device = device; } void set_function(u8 function) { m_function = function; } bool operator==(const Address& address) { - if (m_seg == address.seg() && m_bus == address.bus() && m_slot == address.slot() && m_function == address.function()) + if (m_seg == address.seg() && m_bus == address.bus() && m_device == address.device() && m_function == address.function()) return true; else return false; @@ -176,7 +176,7 @@ struct ChangeableAddress : public Address { { set_seg(address.seg()); set_bus(address.bus()); - set_slot(address.slot()); + set_device(address.device()); set_function(address.function()); return *this; } @@ -252,6 +252,6 @@ struct AK::Formatter<Kernel::PCI::Address> : Formatter<FormatString> { { return Formatter<FormatString>::format( builder, - "PCI [{:04x}:{:02x}:{:02x}:{:02x}]", value.seg(), value.bus(), value.slot(), value.function()); + "PCI [{:04x}:{:02x}:{:02x}:{:02x}]", value.seg(), value.bus(), value.device(), value.function()); } }; diff --git a/Kernel/PCI/IOAccess.cpp b/Kernel/PCI/IOAccess.cpp index 8ca61245b7a7..46b5f66f97c4 100644 --- a/Kernel/PCI/IOAccess.cpp +++ b/Kernel/PCI/IOAccess.cpp @@ -91,15 +91,15 @@ void IOAccess::enumerate_hardware(Function<void(Address, ID)> callback) #endif // Single PCI host controller. if ((read8_field(Address(), PCI_HEADER_TYPE) & 0x80) == 0) { - enumerate_bus(-1, 0, callback); + enumerate_bus(-1, 0, callback, true); return; } // Multiple PCI host controllers. - for (u8 function = 0; function < 8; ++function) { - if (read16_field(Address(0, 0, 0, function), PCI_VENDOR_ID) == PCI_NONE) + for (int bus = 0; bus < 256; ++bus) { + if (read16_field(Address(0, 0, 0, bus), PCI_VENDOR_ID) == PCI_NONE) break; - enumerate_bus(-1, function, callback); + enumerate_bus(-1, bus, callback, false); } } diff --git a/Kernel/PCI/MMIOAccess.cpp b/Kernel/PCI/MMIOAccess.cpp index 56831b5c2139..1d505653ebb0 100644 --- a/Kernel/PCI/MMIOAccess.cpp +++ b/Kernel/PCI/MMIOAccess.cpp @@ -55,7 +55,7 @@ DeviceConfigurationSpaceMapping::DeviceConfigurationSpaceMapping(Address device_ { PhysicalAddress segment_lower_addr = mmio_segment.get_paddr(); PhysicalAddress device_physical_mmio_space = segment_lower_addr.offset( - PCI_MMIO_CONFIG_SPACE_SIZE * m_device_address.function() + (PCI_MMIO_CONFIG_SPACE_SIZE * PCI_MAX_FUNCTIONS_PER_DEVICE) * m_device_address.slot() + (PCI_MMIO_CONFIG_SPACE_SIZE * PCI_MAX_FUNCTIONS_PER_DEVICE * PCI_MAX_DEVICES_PER_BUS) * (m_device_address.bus() - mmio_segment.get_start_bus())); + PCI_MMIO_CONFIG_SPACE_SIZE * m_device_address.function() + (PCI_MMIO_CONFIG_SPACE_SIZE * PCI_MAX_FUNCTIONS_PER_DEVICE) * m_device_address.device() + (PCI_MMIO_CONFIG_SPACE_SIZE * PCI_MAX_FUNCTIONS_PER_DEVICE * PCI_MAX_DEVICES_PER_BUS) * (m_device_address.bus() - mmio_segment.get_start_bus())); m_mapped_region->physical_page_slot(0) = PhysicalPage::create(device_physical_mmio_space, false, false); m_mapped_region->remap(); } @@ -139,7 +139,7 @@ Optional<VirtualAddress> MMIOAccess::get_device_configuration_space(Address addr dbgln<PCI_DEBUG>("PCI Device Configuration Space Mapping: Check if {} was requested", checked_address); if (address.seg() == checked_address.seg() && address.bus() == checked_address.bus() - && address.slot() == checked_address.slot() + && address.device() == checked_address.device() && address.function() == checked_address.function()) { dbgln<PCI_DEBUG>("PCI Device Configuration Space Mapping: Found {}", checked_address); return mapping.vaddr(); @@ -202,7 +202,7 @@ void MMIOAccess::enumerate_hardware(Function<void(Address, ID)> callback) dbgln<PCI_DEBUG>("PCI: Enumerating Memory mapped IO segment {}", seg); // Single PCI host controller. if ((early_read8_field(Address(seg), PCI_HEADER_TYPE) & 0x80) == 0) { - enumerate_bus(-1, 0, callback); + enumerate_bus(-1, 0, callback, true); return; } @@ -210,7 +210,7 @@ void MMIOAccess::enumerate_hardware(Function<void(Address, ID)> callback) for (u8 function = 0; function < 8; ++function) { if (early_read16_field(Address(seg, 0, 0, function), PCI_VENDOR_ID) == PCI_NONE) break; - enumerate_bus(-1, function, callback); + enumerate_bus(-1, function, callback, false); } } }
17a1f51579b07837ba8ccc43cc9672cbab271f09
2021-05-19 12:48:45
DexesTTP
libtls: Move the asn certificate parser to Certificate.cpp
false
Move the asn certificate parser to Certificate.cpp
libtls
diff --git a/Userland/Libraries/LibTLS/CMakeLists.txt b/Userland/Libraries/LibTLS/CMakeLists.txt index 21dcdce4d259..a9fbae4089b7 100644 --- a/Userland/Libraries/LibTLS/CMakeLists.txt +++ b/Userland/Libraries/LibTLS/CMakeLists.txt @@ -1,6 +1,7 @@ add_compile_options(-Wvla) set(SOURCES + Certificate.cpp ClientHandshake.cpp Exchange.cpp Handshake.cpp diff --git a/Userland/Libraries/LibTLS/Certificate.cpp b/Userland/Libraries/LibTLS/Certificate.cpp new file mode 100644 index 000000000000..457e7dd20cb0 --- /dev/null +++ b/Userland/Libraries/LibTLS/Certificate.cpp @@ -0,0 +1,479 @@ +/* + * Copyright (c) 2020, Ali Mohammad Pur <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "Certificate.h" +#include <AK/Debug.h> +#include <LibCrypto/ASN1/ASN1.h> +#include <LibCrypto/ASN1/DER.h> +#include <LibCrypto/ASN1/PEM.h> + +namespace TLS { + +constexpr static Array<int, 4> + common_name_oid { 2, 5, 4, 3 }, + country_name_oid { 2, 5, 4, 6 }, + locality_name_oid { 2, 5, 4, 7 }, + organization_name_oid { 2, 5, 4, 10 }, + organizational_unit_name_oid { 2, 5, 4, 11 }; + +constexpr static Array<int, 7> + rsa_encryption_oid { 1, 2, 840, 113549, 1, 1, 1 }, + rsa_md5_encryption_oid { 1, 2, 840, 113549, 1, 1, 4 }, + rsa_sha1_encryption_oid { 1, 2, 840, 113549, 1, 1, 5 }, + rsa_sha256_encryption_oid { 1, 2, 840, 113549, 1, 1, 11 }, + rsa_sha512_encryption_oid { 1, 2, 840, 113549, 1, 1, 13 }; + +constexpr static Array<int, 4> + subject_alternative_name_oid { 2, 5, 29, 17 }; + +Optional<Certificate> Certificate::parse_asn1(ReadonlyBytes buffer, bool) +{ +#define ENTER_SCOPE_WITHOUT_TYPECHECK(scope) \ + do { \ + if (auto result = decoder.enter(); result.has_value()) { \ + dbgln_if(TLS_DEBUG, "Failed to enter object (" scope "): {}", result.value()); \ + return {}; \ + } \ + } while (0) + +#define ENTER_SCOPE_OR_FAIL(kind_name, scope) \ + do { \ + if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::kind_name) { \ + if constexpr (TLS_DEBUG) { \ + if (tag.is_error()) \ + dbgln(scope " data was invalid: {}", tag.error()); \ + else \ + dbgln(scope " data was not of kind " #kind_name); \ + } \ + return {}; \ + } \ + ENTER_SCOPE_WITHOUT_TYPECHECK(scope); \ + } while (0) + +#define EXIT_SCOPE(scope) \ + do { \ + if (auto error = decoder.leave(); error.has_value()) { \ + dbgln_if(TLS_DEBUG, "Error while exiting scope " scope ": {}", error.value()); \ + return {}; \ + } \ + } while (0) + +#define ENSURE_OBJECT_KIND(_kind_name, scope) \ + do { \ + if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::_kind_name) { \ + if constexpr (TLS_DEBUG) { \ + if (tag.is_error()) \ + dbgln(scope " data was invalid: {}", tag.error()); \ + else \ + dbgln(scope " data was not of kind " #_kind_name ", it was {}", Crypto::ASN1::kind_name(tag.value().kind)); \ + } \ + return {}; \ + } \ + } while (0) + +#define READ_OBJECT_OR_FAIL(kind_name, type_name, value_name, scope) \ + auto value_name##_result = decoder.read<type_name>(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::kind_name); \ + if (value_name##_result.is_error()) { \ + dbgln_if(TLS_DEBUG, scope " read of kind " #kind_name " failed: {}", value_name##_result.error()); \ + return {}; \ + } \ + auto value_name = value_name##_result.release_value(); + +#define DROP_OBJECT_OR_FAIL(scope) \ + do { \ + if (auto error = decoder.drop(); error.has_value()) { \ + dbgln_if(TLS_DEBUG, scope " read failed: {}", error.value()); \ + } \ + } while (0) + + Certificate certificate; + Crypto::ASN1::Decoder decoder { buffer }; + // Certificate ::= Sequence { + // certificate TBSCertificate, + // signature_algorithm AlgorithmIdentifier, + // signature_value BitString + // } + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate"); + + // TBSCertificate ::= Sequence { + // version (0) EXPLICIT Version DEFAULT v1, + // serial_number CertificateSerialNumber, + // signature AlgorithmIdentifier, + // issuer Name, + // validity Validity, + // subject Name, + // subject_public_key_info SubjectPublicKeyInfo, + // issuer_unique_id (1) IMPLICIT UniqueIdentifer OPTIONAL (if present, version > v1), + // subject_unique_id (2) IMPLICIT UniqueIdentiier OPTIONAL (if present, version > v1), + // extensions (3) EXPLICIT Extensions OPTIONAL (if present, version > v2) + // } + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate"); + + // version + { + // Version :: Integer { v1(0), v2(1), v3(2) } (Optional) + if (auto tag = decoder.peek(); !tag.is_error() && tag.value().type == Crypto::ASN1::Type::Constructed) { + ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::version"); + READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::version"); + if (!(value < 3)) { + dbgln_if(TLS_DEBUG, "Certificate::version Invalid value for version: {}", value.to_base10()); + return {}; + } + certificate.version = value.words()[0]; + EXIT_SCOPE("Certificate::version"); + } else { + certificate.version = 0; + } + } + + // serial_number + { + // CertificateSerialNumber :: Integer + READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::serial_number"); + certificate.serial_number = move(value); + } + + auto parse_algorithm_identifier = [&](CertificateKeyAlgorithm& field) -> Optional<bool> { + // AlgorithmIdentifier ::= Sequence { + // algorithm ObjectIdentifier, + // parameters ANY OPTIONAL + // } + ENTER_SCOPE_OR_FAIL(Sequence, "AlgorithmIdentifier"); + READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, identifier, "AlgorithmIdentifier::algorithm"); + if (identifier == rsa_encryption_oid) + field = CertificateKeyAlgorithm ::RSA_RSA; + else if (identifier == rsa_md5_encryption_oid) + field = CertificateKeyAlgorithm ::RSA_MD5; + else if (identifier == rsa_sha1_encryption_oid) + field = CertificateKeyAlgorithm ::RSA_SHA1; + else if (identifier == rsa_sha256_encryption_oid) + field = CertificateKeyAlgorithm ::RSA_SHA256; + else if (identifier == rsa_sha512_encryption_oid) + field = CertificateKeyAlgorithm ::RSA_SHA512; + else + return {}; + + EXIT_SCOPE("AlgorithmIdentifier"); + return true; + }; + + // signature + { + if (!parse_algorithm_identifier(certificate.algorithm).has_value()) + return {}; + } + + auto parse_name = [&](auto& name_struct) -> Optional<bool> { + // Name ::= Choice { + // rdn_sequence RDNSequence + // } // NOTE: since this is the only alternative, there's no index + // RDNSequence ::= Sequence OF RelativeDistinguishedName + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject"); + + // RelativeDistinguishedName ::= Set OF AttributeTypeAndValue + // AttributeTypeAndValue ::= Sequence { + // type AttributeType, + // value AttributeValue + // } + // AttributeType ::= ObjectIdentifier + // AttributeValue ::= Any + while (!decoder.eof()) { + // Parse only the the required fields, and ignore the rest. + ENTER_SCOPE_OR_FAIL(Set, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName"); + while (!decoder.eof()) { + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue"); + ENSURE_OBJECT_KIND(ObjectIdentifier, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type"); + + if (auto type_identifier_or_error = decoder.read<Vector<int>>(); !type_identifier_or_error.is_error()) { + // Figure out what type of identifier this is + auto& identifier = type_identifier_or_error.value(); + if (identifier == common_name_oid) { + READ_OBJECT_OR_FAIL(PrintableString, StringView, name, + "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); + name_struct.subject = name; + } else if (identifier == country_name_oid) { + READ_OBJECT_OR_FAIL(PrintableString, StringView, name, + "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); + name_struct.country = name; + } else if (identifier == locality_name_oid) { + READ_OBJECT_OR_FAIL(PrintableString, StringView, name, + "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); + name_struct.location = name; + } else if (identifier == organization_name_oid) { + READ_OBJECT_OR_FAIL(PrintableString, StringView, name, + "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); + name_struct.entity = name; + } else if (identifier == organizational_unit_name_oid) { + READ_OBJECT_OR_FAIL(PrintableString, StringView, name, + "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); + name_struct.unit = name; + } + } else { + dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type data was invalid: {}", type_identifier_or_error.error()); + return {}; + } + + EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue"); + } + EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName"); + } + + EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject"); + return true; + }; + + // issuer + { + if (!parse_name(certificate.issuer).has_value()) + return {}; + } + + // validity + { + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Validity"); + + auto parse_time = [&](Core::DateTime& datetime) -> Optional<bool> { + // Time ::= Choice { + // utc_time UTCTime, + // general_time GeneralizedTime + // } + auto tag = decoder.peek(); + if (tag.is_error()) { + dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time failed to read tag: {}", tag.error()); + return {}; + }; + + if (tag.value().kind == Crypto::ASN1::Kind::UTCTime) { + READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$"); + auto result = Crypto::ASN1::parse_utc_time(time); + if (!result.has_value()) { + dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid UTC Time: {}", time); + return {}; + } + datetime = result.release_value(); + return true; + } + + if (tag.value().kind == Crypto::ASN1::Kind::GeneralizedTime) { + READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$"); + auto result = Crypto::ASN1::parse_generalized_time(time); + if (!result.has_value()) { + dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid Generalized Time: {}", time); + return {}; + } + datetime = result.release_value(); + return true; + } + + dbgln_if(1, "Unrecognised Time format {}", Crypto::ASN1::kind_name(tag.value().kind)); + return {}; + }; + + if (!parse_time(certificate.not_before).has_value()) + return {}; + + if (!parse_time(certificate.not_after).has_value()) + return {}; + + EXIT_SCOPE("Certificate::TBSCertificate::Validity"); + } + + // subject + { + if (!parse_name(certificate.subject).has_value()) + return {}; + } + + // subject_public_key_info + { + // SubjectPublicKeyInfo ::= Sequence { + // algorithm AlgorithmIdentifier, + // subject_public_key BitString + // } + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::subject_public_key_info"); + + if (!parse_algorithm_identifier(certificate.key_algorithm).has_value()) + return {}; + + READ_OBJECT_OR_FAIL(BitString, const BitmapView, value, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info"); + // Note: Once we support other kinds of keys, make sure to check the kind here! + auto key = Crypto::PK::RSA::parse_rsa_key({ value.data(), value.size_in_bytes() }); + if (!key.public_key.length()) { + dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info: Invalid key"); + return {}; + } + certificate.public_key = move(key.public_key); + EXIT_SCOPE("Certificate::TBSCertificate::subject_public_key_info"); + } + + auto parse_unique_identifier = [&]() -> Optional<bool> { + if (certificate.version == 0) + return true; + + auto tag = decoder.peek(); + if (tag.is_error()) { + dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error()); + return {}; + } + + // The spec says to just ignore these. + if (static_cast<u8>(tag.value().kind) == 1 || static_cast<u8>(tag.value().kind) == 2) + DROP_OBJECT_OR_FAIL("UniqueIdentifier"); + + return true; + }; + + // issuer_unique_identifier + { + if (!parse_unique_identifier().has_value()) + return {}; + } + + // subject_unique_identifier + { + if (!parse_unique_identifier().has_value()) + return {}; + } + + // extensions + { + if (certificate.version == 2) { + auto tag = decoder.peek(); + if (tag.is_error()) { + dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error()); + return {}; + } + if (static_cast<u8>(tag.value().kind) == 3) { + // Extensions ::= Sequence OF Extension + // Extension ::= Sequence { + // extension_id ObjectIdentifier, + // critical Boolean DEFAULT false, + // extension_value OctetString (DER-encoded) + // } + ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::TBSCertificate::Extensions(IMPLICIT)"); + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions"); + + while (!decoder.eof()) { + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension"); + READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, extension_id, "Certificate::TBSCertificate::Extensions::$::Extension::extension_id"); + bool is_critical = false; + if (auto tag = decoder.peek(); !tag.is_error() && tag.value().kind == Crypto::ASN1::Kind::Boolean) { + // Read the 'critical' property + READ_OBJECT_OR_FAIL(Boolean, bool, critical, "Certificate::TBSCertificate::Extensions::$::Extension::critical"); + is_critical = critical; + } + READ_OBJECT_OR_FAIL(OctetString, StringView, extension_value, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value"); + + // Figure out what this extension is. + if (extension_id == subject_alternative_name_oid) { + Crypto::ASN1::Decoder decoder { extension_value.bytes() }; + // SubjectAlternativeName ::= GeneralNames + // GeneralNames ::= Sequence OF GeneralName + // GeneralName ::= CHOICE { + // other_name (0) OtherName, + // rfc_822_name (1) IA5String, + // dns_name (2) IA5String, + // x400Address (3) ORAddress, + // directory_name (4) Name, + // edi_party_name (5) EDIPartyName, + // uri (6) IA5String, + // ip_address (7) OctetString, + // registered_id (8) ObjectIdentifier, + // } + ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName"); + + while (!decoder.eof()) { + auto tag = decoder.peek(); + if (tag.is_error()) { + dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$ could not read tag: {}", tag.error()); + return {}; + } + + auto tag_value = static_cast<u8>(tag.value().kind); + switch (tag_value) { + case 0: + // OtherName + // We don't know how to use this. + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::OtherName"); + break; + case 1: + // RFC 822 name + // We don't know how to use this. + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RFC822Name"); + break; + case 2: { + // DNS Name + READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DNSName"); + certificate.SAN.append(name); + break; + } + case 3: + // x400Address + // We don't know how to use this. + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::X400Adress"); + break; + case 4: + // Directory name + // We don't know how to use this. + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DirectoryName"); + break; + case 5: + // edi party name + // We don't know how to use this. + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::EDIPartyName"); + break; + case 6: { + // URI + READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::URI"); + certificate.SAN.append(name); + break; + } + case 7: + // IP Address + // We can't handle these. + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::IPAddress"); + break; + case 8: + // Registered ID + // We can't handle these. + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RegisteredID"); + break; + default: + dbgln_if(TLS_DEBUG, "Unknown tag in SAN choice {}", tag_value); + if (is_critical) + return {}; + else + DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::???"); + } + } + } + + EXIT_SCOPE("Certificate::TBSCertificate::Extensions::$::Extension"); + } + + EXIT_SCOPE("Certificate::TBSCertificate::Extensions"); + EXIT_SCOPE("Certificate::TBSCertificate::Extensions(IMPLICIT)"); + } + } + } + + // Just ignore the rest of the data for now. + EXIT_SCOPE("Certificate::TBSCertificate"); + EXIT_SCOPE("Certificate"); + + dbgln_if(TLS_DEBUG, "Certificate issued for {} by {}", certificate.subject.subject, certificate.issuer.subject); + + return certificate; + +#undef DROP_OBJECT_OR_FAIL +#undef ENSURE_OBJECT_KIND +#undef ENTER_SCOPE_OR_FAIL +#undef ENTER_SCOPE_WITHOUT_TYPECHECK +#undef EXIT_SCOPE +#undef READ_OBJECT_OR_FAIL +} + +} diff --git a/Userland/Libraries/LibTLS/Certificate.h b/Userland/Libraries/LibTLS/Certificate.h index f5e31ed820d5..2810b3ac4f0e 100644 --- a/Userland/Libraries/LibTLS/Certificate.h +++ b/Userland/Libraries/LibTLS/Certificate.h @@ -8,6 +8,7 @@ #include <AK/ByteBuffer.h> #include <AK/Forward.h> +#include <AK/Optional.h> #include <AK/Singleton.h> #include <AK/Types.h> #include <LibCore/DateTime.h> @@ -25,7 +26,8 @@ enum class CertificateKeyAlgorithm { RSA_SHA512 = 0x0d, }; -struct Certificate { +class Certificate { +public: u16 version { 0 }; CertificateKeyAlgorithm algorithm { CertificateKeyAlgorithm::Unsupported }; CertificateKeyAlgorithm key_algorithm { CertificateKeyAlgorithm::Unsupported }; @@ -51,6 +53,8 @@ struct Certificate { ByteBuffer der {}; ByteBuffer data {}; + static Optional<Certificate> parse_asn1(ReadonlyBytes, bool client_cert = false); + bool is_valid() const; }; diff --git a/Userland/Libraries/LibTLS/TLSv12.cpp b/Userland/Libraries/LibTLS/TLSv12.cpp index 9cb927bf30ed..796232273cdd 100644 --- a/Userland/Libraries/LibTLS/TLSv12.cpp +++ b/Userland/Libraries/LibTLS/TLSv12.cpp @@ -12,7 +12,6 @@ #include <LibCore/FileStream.h> #include <LibCore/Timer.h> #include <LibCrypto/ASN1/ASN1.h> -#include <LibCrypto/ASN1/DER.h> #include <LibCrypto/ASN1/PEM.h> #include <LibCrypto/PK/Code/EMSA_PSS.h> #include <LibTLS/TLSv12.h> @@ -24,470 +23,6 @@ namespace TLS { -constexpr static Array<int, 4> - common_name_oid { 2, 5, 4, 3 }, - country_name_oid { 2, 5, 4, 6 }, - locality_name_oid { 2, 5, 4, 7 }, - organization_name_oid { 2, 5, 4, 10 }, - organizational_unit_name_oid { 2, 5, 4, 11 }; - -constexpr static Array<int, 7> - rsa_encryption_oid { 1, 2, 840, 113549, 1, 1, 1 }, - rsa_md5_encryption_oid { 1, 2, 840, 113549, 1, 1, 4 }, - rsa_sha1_encryption_oid { 1, 2, 840, 113549, 1, 1, 5 }, - rsa_sha256_encryption_oid { 1, 2, 840, 113549, 1, 1, 11 }, - rsa_sha512_encryption_oid { 1, 2, 840, 113549, 1, 1, 13 }; - -constexpr static Array<int, 4> - subject_alternative_name_oid { 2, 5, 29, 17 }; - -Optional<Certificate> TLSv12::parse_asn1(ReadonlyBytes buffer, bool) const -{ -#define ENTER_SCOPE_WITHOUT_TYPECHECK(scope) \ - do { \ - if (auto result = decoder.enter(); result.has_value()) { \ - dbgln_if(TLS_DEBUG, "Failed to enter object (" scope "): {}", result.value()); \ - return {}; \ - } \ - } while (0) - -#define ENTER_SCOPE_OR_FAIL(kind_name, scope) \ - do { \ - if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::kind_name) { \ - if constexpr (TLS_DEBUG) { \ - if (tag.is_error()) \ - dbgln(scope " data was invalid: {}", tag.error()); \ - else \ - dbgln(scope " data was not of kind " #kind_name); \ - } \ - return {}; \ - } \ - ENTER_SCOPE_WITHOUT_TYPECHECK(scope); \ - } while (0) - -#define EXIT_SCOPE(scope) \ - do { \ - if (auto error = decoder.leave(); error.has_value()) { \ - dbgln_if(TLS_DEBUG, "Error while exiting scope " scope ": {}", error.value()); \ - return {}; \ - } \ - } while (0) - -#define ENSURE_OBJECT_KIND(_kind_name, scope) \ - do { \ - if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::_kind_name) { \ - if constexpr (TLS_DEBUG) { \ - if (tag.is_error()) \ - dbgln(scope " data was invalid: {}", tag.error()); \ - else \ - dbgln(scope " data was not of kind " #_kind_name ", it was {}", Crypto::ASN1::kind_name(tag.value().kind)); \ - } \ - return {}; \ - } \ - } while (0) - -#define READ_OBJECT_OR_FAIL(kind_name, type_name, value_name, scope) \ - auto value_name##_result = decoder.read<type_name>(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::kind_name); \ - if (value_name##_result.is_error()) { \ - dbgln_if(TLS_DEBUG, scope " read of kind " #kind_name " failed: {}", value_name##_result.error()); \ - return {}; \ - } \ - auto value_name = value_name##_result.release_value(); - -#define DROP_OBJECT_OR_FAIL(scope) \ - do { \ - if (auto error = decoder.drop(); error.has_value()) { \ - dbgln_if(TLS_DEBUG, scope " read failed: {}", error.value()); \ - } \ - } while (0) - - Certificate certificate; - Crypto::ASN1::Decoder decoder { buffer }; - // Certificate ::= Sequence { - // certificate TBSCertificate, - // signature_algorithm AlgorithmIdentifier, - // signature_value BitString - // } - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate"); - - // TBSCertificate ::= Sequence { - // version (0) EXPLICIT Version DEFAULT v1, - // serial_number CertificateSerialNumber, - // signature AlgorithmIdentifier, - // issuer Name, - // validity Validity, - // subject Name, - // subject_public_key_info SubjectPublicKeyInfo, - // issuer_unique_id (1) IMPLICIT UniqueIdentifer OPTIONAL (if present, version > v1), - // subject_unique_id (2) IMPLICIT UniqueIdentiier OPTIONAL (if present, version > v1), - // extensions (3) EXPLICIT Extensions OPTIONAL (if present, version > v2) - // } - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate"); - - // version - { - // Version :: Integer { v1(0), v2(1), v3(2) } (Optional) - if (auto tag = decoder.peek(); !tag.is_error() && tag.value().type == Crypto::ASN1::Type::Constructed) { - ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::version"); - READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::version"); - if (!(value < 3)) { - dbgln_if(TLS_DEBUG, "Certificate::version Invalid value for version: {}", value.to_base10()); - return {}; - } - certificate.version = value.words()[0]; - EXIT_SCOPE("Certificate::version"); - } else { - certificate.version = 0; - } - } - - // serial_number - { - // CertificateSerialNumber :: Integer - READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::serial_number"); - certificate.serial_number = move(value); - } - - auto parse_algorithm_identifier = [&](CertificateKeyAlgorithm& field) -> Optional<bool> { - // AlgorithmIdentifier ::= Sequence { - // algorithm ObjectIdentifier, - // parameters ANY OPTIONAL - // } - ENTER_SCOPE_OR_FAIL(Sequence, "AlgorithmIdentifier"); - READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, identifier, "AlgorithmIdentifier::algorithm"); - if (identifier == rsa_encryption_oid) - field = CertificateKeyAlgorithm ::RSA_RSA; - else if (identifier == rsa_md5_encryption_oid) - field = CertificateKeyAlgorithm ::RSA_MD5; - else if (identifier == rsa_sha1_encryption_oid) - field = CertificateKeyAlgorithm ::RSA_SHA1; - else if (identifier == rsa_sha256_encryption_oid) - field = CertificateKeyAlgorithm ::RSA_SHA256; - else if (identifier == rsa_sha512_encryption_oid) - field = CertificateKeyAlgorithm ::RSA_SHA512; - else - return {}; - - EXIT_SCOPE("AlgorithmIdentifier"); - return true; - }; - - // signature - { - if (!parse_algorithm_identifier(certificate.algorithm).has_value()) - return {}; - } - - auto parse_name = [&](auto& name_struct) -> Optional<bool> { - // Name ::= Choice { - // rdn_sequence RDNSequence - // } // NOTE: since this is the only alternative, there's no index - // RDNSequence ::= Sequence OF RelativeDistinguishedName - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject"); - - // RelativeDistinguishedName ::= Set OF AttributeTypeAndValue - // AttributeTypeAndValue ::= Sequence { - // type AttributeType, - // value AttributeValue - // } - // AttributeType ::= ObjectIdentifier - // AttributeValue ::= Any - while (!decoder.eof()) { - // Parse only the the required fields, and ignore the rest. - ENTER_SCOPE_OR_FAIL(Set, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName"); - while (!decoder.eof()) { - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue"); - ENSURE_OBJECT_KIND(ObjectIdentifier, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type"); - - if (auto type_identifier_or_error = decoder.read<Vector<int>>(); !type_identifier_or_error.is_error()) { - // Figure out what type of identifier this is - auto& identifier = type_identifier_or_error.value(); - if (identifier == common_name_oid) { - READ_OBJECT_OR_FAIL(PrintableString, StringView, name, - "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); - name_struct.subject = name; - } else if (identifier == country_name_oid) { - READ_OBJECT_OR_FAIL(PrintableString, StringView, name, - "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); - name_struct.country = name; - } else if (identifier == locality_name_oid) { - READ_OBJECT_OR_FAIL(PrintableString, StringView, name, - "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); - name_struct.location = name; - } else if (identifier == organization_name_oid) { - READ_OBJECT_OR_FAIL(PrintableString, StringView, name, - "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); - name_struct.entity = name; - } else if (identifier == organizational_unit_name_oid) { - READ_OBJECT_OR_FAIL(PrintableString, StringView, name, - "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value"); - name_struct.unit = name; - } - } else { - dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type data was invalid: {}", type_identifier_or_error.error()); - return {}; - } - - EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue"); - } - EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName"); - } - - EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject"); - return true; - }; - - // issuer - { - if (!parse_name(certificate.issuer).has_value()) - return {}; - } - - // validity - { - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Validity"); - - auto parse_time = [&](Core::DateTime& datetime) -> Optional<bool> { - // Time ::= Choice { - // utc_time UTCTime, - // general_time GeneralizedTime - // } - auto tag = decoder.peek(); - if (tag.is_error()) { - dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time failed to read tag: {}", tag.error()); - return {}; - }; - - if (tag.value().kind == Crypto::ASN1::Kind::UTCTime) { - READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$"); - auto result = Crypto::ASN1::parse_utc_time(time); - if (!result.has_value()) { - dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid UTC Time: {}", time); - return {}; - } - datetime = result.release_value(); - return true; - } - - if (tag.value().kind == Crypto::ASN1::Kind::GeneralizedTime) { - READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$"); - auto result = Crypto::ASN1::parse_generalized_time(time); - if (!result.has_value()) { - dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid Generalized Time: {}", time); - return {}; - } - datetime = result.release_value(); - return true; - } - - dbgln_if(1, "Unrecognised Time format {}", Crypto::ASN1::kind_name(tag.value().kind)); - return {}; - }; - - if (!parse_time(certificate.not_before).has_value()) - return {}; - - if (!parse_time(certificate.not_after).has_value()) - return {}; - - EXIT_SCOPE("Certificate::TBSCertificate::Validity"); - } - - // subject - { - if (!parse_name(certificate.subject).has_value()) - return {}; - } - - // subject_public_key_info - { - // SubjectPublicKeyInfo ::= Sequence { - // algorithm AlgorithmIdentifier, - // subject_public_key BitString - // } - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::subject_public_key_info"); - - if (!parse_algorithm_identifier(certificate.key_algorithm).has_value()) - return {}; - - READ_OBJECT_OR_FAIL(BitString, const BitmapView, value, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info"); - // Note: Once we support other kinds of keys, make sure to check the kind here! - auto key = Crypto::PK::RSA::parse_rsa_key({ value.data(), value.size_in_bytes() }); - if (!key.public_key.length()) { - dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info: Invalid key"); - return {}; - } - certificate.public_key = move(key.public_key); - EXIT_SCOPE("Certificate::TBSCertificate::subject_public_key_info"); - } - - auto parse_unique_identifier = [&]() -> Optional<bool> { - if (certificate.version == 0) - return true; - - auto tag = decoder.peek(); - if (tag.is_error()) { - dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error()); - return {}; - } - - // The spec says to just ignore these. - if (static_cast<u8>(tag.value().kind) == 1 || static_cast<u8>(tag.value().kind) == 2) - DROP_OBJECT_OR_FAIL("UniqueIdentifier"); - - return true; - }; - - // issuer_unique_identifier - { - if (!parse_unique_identifier().has_value()) - return {}; - } - - // subject_unique_identifier - { - if (!parse_unique_identifier().has_value()) - return {}; - } - - // extensions - { - if (certificate.version == 2) { - auto tag = decoder.peek(); - if (tag.is_error()) { - dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error()); - return {}; - } - if (static_cast<u8>(tag.value().kind) == 3) { - // Extensions ::= Sequence OF Extension - // Extension ::= Sequence { - // extension_id ObjectIdentifier, - // critical Boolean DEFAULT false, - // extension_value OctetString (DER-encoded) - // } - ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::TBSCertificate::Extensions(IMPLICIT)"); - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions"); - - while (!decoder.eof()) { - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension"); - READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, extension_id, "Certificate::TBSCertificate::Extensions::$::Extension::extension_id"); - bool is_critical = false; - if (auto tag = decoder.peek(); !tag.is_error() && tag.value().kind == Crypto::ASN1::Kind::Boolean) { - // Read the 'critical' property - READ_OBJECT_OR_FAIL(Boolean, bool, critical, "Certificate::TBSCertificate::Extensions::$::Extension::critical"); - is_critical = critical; - } - READ_OBJECT_OR_FAIL(OctetString, StringView, extension_value, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value"); - - // Figure out what this extension is. - if (extension_id == subject_alternative_name_oid) { - Crypto::ASN1::Decoder decoder { extension_value.bytes() }; - // SubjectAlternativeName ::= GeneralNames - // GeneralNames ::= Sequence OF GeneralName - // GeneralName ::= CHOICE { - // other_name (0) OtherName, - // rfc_822_name (1) IA5String, - // dns_name (2) IA5String, - // x400Address (3) ORAddress, - // directory_name (4) Name, - // edi_party_name (5) EDIPartyName, - // uri (6) IA5String, - // ip_address (7) OctetString, - // registered_id (8) ObjectIdentifier, - // } - ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName"); - - while (!decoder.eof()) { - auto tag = decoder.peek(); - if (tag.is_error()) { - dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$ could not read tag: {}", tag.error()); - return {}; - } - - auto tag_value = static_cast<u8>(tag.value().kind); - switch (tag_value) { - case 0: - // OtherName - // We don't know how to use this. - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::OtherName"); - break; - case 1: - // RFC 822 name - // We don't know how to use this. - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RFC822Name"); - break; - case 2: { - // DNS Name - READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DNSName"); - certificate.SAN.append(name); - break; - } - case 3: - // x400Address - // We don't know how to use this. - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::X400Adress"); - break; - case 4: - // Directory name - // We don't know how to use this. - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DirectoryName"); - break; - case 5: - // edi party name - // We don't know how to use this. - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::EDIPartyName"); - break; - case 6: { - // URI - READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::URI"); - certificate.SAN.append(name); - break; - } - case 7: - // IP Address - // We can't handle these. - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::IPAddress"); - break; - case 8: - // Registered ID - // We can't handle these. - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RegisteredID"); - break; - default: - dbgln_if(TLS_DEBUG, "Unknown tag in SAN choice {}", tag_value); - if (is_critical) - return {}; - else - DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::???"); - } - } - } - - EXIT_SCOPE("Certificate::TBSCertificate::Extensions::$::Extension"); - } - - EXIT_SCOPE("Certificate::TBSCertificate::Extensions"); - EXIT_SCOPE("Certificate::TBSCertificate::Extensions(IMPLICIT)"); - } - } - } - - // Just ignore the rest of the data for now. - EXIT_SCOPE("Certificate::TBSCertificate"); - EXIT_SCOPE("Certificate"); - - dbgln_if(TLS_DEBUG, "Certificate issued for {} by {}", certificate.subject.subject, certificate.issuer.subject); - - return certificate; - -#undef DROP_OBJECT_OR_FAIL -#undef ENSURE_OBJECT_KIND -#undef ENTER_SCOPE_OR_FAIL -#undef ENTER_SCOPE_WITHOUT_TYPECHECK -#undef EXIT_SCOPE -#undef READ_OBJECT_OR_FAIL -} - ssize_t TLSv12::handle_certificate(ReadonlyBytes buffer) { ssize_t res = 0; @@ -553,7 +88,7 @@ ssize_t TLSv12::handle_certificate(ReadonlyBytes buffer) } remaining -= certificate_size_specific; - auto certificate = parse_asn1(buffer.slice(res_cert, certificate_size_specific), false); + auto certificate = Certificate::parse_asn1(buffer.slice(res_cert, certificate_size_specific), false); if (certificate.has_value()) { if (certificate.value().is_valid()) { m_context.certificates.append(certificate.value()); @@ -883,7 +418,7 @@ bool TLSv12::add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes return false; } - auto maybe_certificate = parse_asn1(decoded_certificate); + auto maybe_certificate = Certificate::parse_asn1(decoded_certificate); if (!maybe_certificate.has_value()) { dbgln("Invalid certificate"); return false; diff --git a/Userland/Libraries/LibTLS/TLSv12.h b/Userland/Libraries/LibTLS/TLSv12.h index 0d2f6276e15d..46a638307433 100644 --- a/Userland/Libraries/LibTLS/TLSv12.h +++ b/Userland/Libraries/LibTLS/TLSv12.h @@ -277,7 +277,6 @@ class TLSv12 : public Core::Socket { m_context.extensions.SNI = sni; } - Optional<Certificate> parse_asn1(ReadonlyBytes, bool client_cert = false) const; bool load_certificates(ReadonlyBytes pem_buffer); bool load_private_key(ReadonlyBytes pem_buffer);
8e05b49089546d96f7fd02ff5c49d327295b88b5
2021-06-17 00:35:18
Idan Horowitz
libjs: Add the String.prototype.codePointAt() method
false
Add the String.prototype.codePointAt() method
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h index 1c97d1c43ca0..445f3e120d95 100644 --- a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h +++ b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h @@ -78,6 +78,7 @@ namespace JS { P(cleanupSome) \ P(clear) \ P(clz32) \ + P(codePointAt) \ P(concat) \ P(configurable) \ P(console) \ diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp index f0d0e3a35328..230498838eb1 100644 --- a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -54,6 +54,7 @@ void StringPrototype::initialize(GlobalObject& global_object) define_native_function(vm.names.charAt, char_at, 1, attr); define_native_function(vm.names.charCodeAt, char_code_at, 1, attr); + define_native_function(vm.names.codePointAt, code_point_at, 1, attr); define_native_function(vm.names.repeat, repeat, 1, attr); define_native_function(vm.names.startsWith, starts_with, 1, attr); define_native_function(vm.names.endsWith, ends_with, 1, attr); @@ -117,16 +118,12 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_at) auto string = ak_string_from(vm, global_object); if (!string.has_value()) return {}; - i32 index = 0; - if (vm.argument_count()) { - index = vm.argument(0).to_i32(global_object); - if (vm.exception()) - return {}; - } - if (index < 0 || index >= static_cast<i32>(string->length())) + auto position = vm.argument(0).to_integer_or_infinity(global_object); + if (vm.exception()) + return {}; + if (position < 0 || position >= string->length()) return js_string(vm, String::empty()); - // FIXME: This should return a character corresponding to the i'th UTF-16 code point. - return js_string(vm, string->substring(index, 1)); + return js_string(vm, string->substring(position, 1)); } // 22.1.3.2 String.prototype.charCodeAt ( pos ), https://tc39.es/ecma262/#sec-string.prototype.charcodeat @@ -135,16 +132,30 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_code_at) auto string = ak_string_from(vm, global_object); if (!string.has_value()) return {}; - i32 index = 0; - if (vm.argument_count()) { - index = vm.argument(0).to_i32(global_object); - if (vm.exception()) - return {}; - } - if (index < 0 || index >= static_cast<i32>(string->length())) + auto position = vm.argument(0).to_integer_or_infinity(global_object); + if (vm.exception()) + return {}; + if (position < 0 || position >= string->length()) return js_nan(); - // FIXME: This should return the i'th UTF-16 code point. - return Value((i32)(*string)[index]); + return Value((*string)[position]); +} + +// 22.1.3.3 String.prototype.codePointAt ( pos ), https://tc39.es/ecma262/#sec-string.prototype.codepointat +JS_DEFINE_NATIVE_FUNCTION(StringPrototype::code_point_at) +{ + auto string = ak_string_from(vm, global_object); + if (!string.has_value()) + return {}; + auto position = vm.argument(0).to_integer_or_infinity(global_object); + if (vm.exception()) + return {}; + auto view = Utf8View(*string); + if (position < 0 || position >= view.length()) + return js_undefined(); + auto it = view.begin(); + for (auto i = 0; i < position; ++i) + ++it; + return Value(*it); } // 22.1.3.16 String.prototype.repeat ( count ), https://tc39.es/ecma262/#sec-string.prototype.repeat diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.h b/Userland/Libraries/LibJS/Runtime/StringPrototype.h index 64d67b11ca3e..16cbaedb42de 100644 --- a/Userland/Libraries/LibJS/Runtime/StringPrototype.h +++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.h @@ -21,6 +21,7 @@ class StringPrototype final : public StringObject { private: JS_DECLARE_NATIVE_FUNCTION(char_at); JS_DECLARE_NATIVE_FUNCTION(char_code_at); + JS_DECLARE_NATIVE_FUNCTION(code_point_at); JS_DECLARE_NATIVE_FUNCTION(repeat); JS_DECLARE_NATIVE_FUNCTION(starts_with); JS_DECLARE_NATIVE_FUNCTION(ends_with);
ea5da0f9b5f515eae12a286ba50c3fbe3cb130e7
2019-10-20 16:25:55
Andreas Kling
libhtml: The CSS parser should tolerate whitespace-only stylesheets
false
The CSS parser should tolerate whitespace-only stylesheets
libhtml
diff --git a/Libraries/LibHTML/Parser/CSSParser.cpp b/Libraries/LibHTML/Parser/CSSParser.cpp index e12cbd20ec4e..5ce42df1cbef 100644 --- a/Libraries/LibHTML/Parser/CSSParser.cpp +++ b/Libraries/LibHTML/Parser/CSSParser.cpp @@ -345,6 +345,10 @@ class CSSParser { void parse_rule() { + consume_whitespace_or_comments(); + if (index >= css.length()) + return; + // FIXME: We ignore @media rules for now. if (next_is("@media")) { while (peek() != '{')
1bcde5d21611863103203c32488c9772a795259d
2023-01-22 06:33:13
Timothy Flynn
libjs: Port ListFormat and PatternPartition to String
false
Port ListFormat and PatternPartition to String
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp index e6255318b97c..ef61ddd8b48e 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp @@ -705,7 +705,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_pattern(VM& vm, StringView auto literal = pattern.substring_view(next_index, *begin_index - next_index); // ii. Append a new Record { [[Type]]: "literal", [[Value]]: literal } as the last element of the list result. - TRY_OR_THROW_OOM(vm, result.try_append({ "literal"sv, literal })); + TRY_OR_THROW_OOM(vm, result.try_append({ "literal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(literal)) })); } // d. Let p be the substring of pattern from position beginIndex, exclusive, to position endIndex, exclusive. @@ -727,7 +727,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_pattern(VM& vm, StringView auto literal = pattern.substring_view(next_index); // b. Append a new Record { [[Type]]: "literal", [[Value]]: literal } as the last element of the list result. - TRY_OR_THROW_OOM(vm, result.try_append({ "literal"sv, literal })); + TRY_OR_THROW_OOM(vm, result.try_append({ "literal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(literal)) })); } // 8. Return result. diff --git a/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.h index 3257eaa54f5c..9334fe10b4c4 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/AbstractOperations.h @@ -6,7 +6,6 @@ #pragma once -#include <AK/DeprecatedString.h> #include <AK/Span.h> #include <AK/String.h> #include <AK/Variant.h> @@ -44,14 +43,14 @@ struct LocaleResult { struct PatternPartition { PatternPartition() = default; - PatternPartition(StringView type_string, DeprecatedString value_string) + PatternPartition(StringView type_string, String value_string) : type(type_string) , value(move(value_string)) { } StringView type; - DeprecatedString value; + String value; }; struct PatternPartitionWithSource : public PatternPartition { diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp index 29f03eb5d6c0..be88a2ea321c 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp @@ -624,7 +624,7 @@ ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, Dat auto formatted_value = MUST_OR_THROW_OOM(format_numeric(vm, *number_format3, Value(value))); // iv. Append a new Record { [[Type]]: "fractionalSecond", [[Value]]: fv } as the last element of result. - result.append({ "fractionalSecond"sv, move(formatted_value) }); + result.append({ "fractionalSecond"sv, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(formatted_value)) }); } // d. Else if p is equal to "dayPeriod", then @@ -640,7 +640,7 @@ ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, Dat formatted_value = *symbol; // iii. Append a new Record { [[Type]]: p, [[Value]]: fv } as the last element of the list result. - result.append({ "dayPeriod"sv, move(formatted_value) }); + result.append({ "dayPeriod"sv, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(formatted_value)) }); } // e. Else if p is equal to "timeZoneName", then @@ -657,7 +657,7 @@ ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, Dat auto formatted_value = ::Locale::format_time_zone(data_locale, value, style, local_time.time_since_epoch()); // iv. Append a new Record { [[Type]]: p, [[Value]]: fv } as the last element of the list result. - result.append({ "timeZoneName"sv, move(formatted_value) }); + result.append({ "timeZoneName"sv, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(formatted_value)) }); } // f. Else if p matches a Property column of the row in Table 6, then @@ -750,7 +750,7 @@ ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, Dat } // xi. Append a new Record { [[Type]]: p, [[Value]]: fv } as the last element of the list result. - result.append({ style_and_value->name, move(formatted_value) }); + result.append({ style_and_value->name, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(formatted_value)) }); } // g. Else if p is equal to "ampm", then @@ -774,7 +774,7 @@ ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, Dat } // iv. Append a new Record { [[Type]]: "dayPeriod", [[Value]]: fv } as the last element of the list result. - result.append({ "dayPeriod"sv, move(formatted_value) }); + result.append({ "dayPeriod"sv, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(formatted_value)) }); } // h. Else if p is equal to "relatedYear", then @@ -799,7 +799,7 @@ ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, Dat // to adhere to the selected locale. This depends on other generated data, so it is deferred to here. else if (part == "decimal"sv) { auto decimal_symbol = ::Locale::get_number_system_symbol(data_locale, date_time_format.numbering_system(), ::Locale::NumericSymbol::Decimal).value_or("."sv); - result.append({ "literal"sv, decimal_symbol }); + result.append({ "literal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(decimal_symbol)) }); } // j. Else, diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp index ee6921ec2962..fd01025baa5b 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/DurationFormat.cpp @@ -448,7 +448,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(VM auto number = MUST_OR_THROW_OOM(format_numeric(vm, *number_format, MathematicalValue(value))); // 5. Append the new Record { [[Type]]: unit, [[Value]]: num} to the end of result. - result.append({ unit, number }); + result.append({ unit, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(number)) }); // 6. If unit is "hours" or "minutes", then if (unit.is_one_of("hours"sv, "minutes"sv)) { @@ -484,7 +484,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(VM auto separator = ::Locale::get_number_system_symbol(data_locale, duration_format.numbering_system(), ::Locale::NumericSymbol::TimeSeparator).value_or(":"sv); // ii. Append the new Record { [[Type]]: "literal", [[Value]]: separator} to the end of result. - result.append({ "literal"sv, separator }); + result.append({ "literal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(separator)) }); } } } @@ -516,7 +516,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(VM } // 8. Append the new Record { [[Type]]: unit, [[Value]]: concat } to the end of result. - result.append({ unit, concat.build() }); + result.append({ unit, TRY_OR_THROW_OOM(vm, concat.to_string()) }); } } } @@ -546,17 +546,17 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_duration_format_pattern(VM // FIXME: CreatePartsFromList expects a list of strings and creates a list of Pattern Partition records, but we already created a list of Pattern Partition records // so we try to hack something together from it that looks mostly right - Vector<DeprecatedString> string_result; + Vector<String> string_result; bool merge = false; for (size_t i = 0; i < result.size(); ++i) { auto const& part = result[i]; if (part.type == "literal") { - string_result.last() = DeprecatedString::formatted("{}{}", string_result.last(), part.value); + string_result.last() = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", string_result.last(), part.value)); merge = true; continue; } if (merge) { - string_result.last() = DeprecatedString::formatted("{}{}", string_result.last(), part.value); + string_result.last() = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", string_result.last(), part.value)); merge = false; continue; } diff --git a/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.cpp index 2b5b0b522c2b..c33914d9bfc0 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.cpp @@ -93,7 +93,7 @@ ThrowCompletionOr<Vector<PatternPartition>> deconstruct_pattern(VM& vm, StringVi } // 13.5.2 CreatePartsFromList ( listFormat, list ), https://tc39.es/ecma402/#sec-createpartsfromlist -ThrowCompletionOr<Vector<PatternPartition>> create_parts_from_list(VM& vm, ListFormat const& list_format, Vector<DeprecatedString> const& list) +ThrowCompletionOr<Vector<PatternPartition>> create_parts_from_list(VM& vm, ListFormat const& list_format, Vector<String> const& list) { auto list_patterns = ::Locale::get_locale_list_patterns(list_format.locale(), list_format.type_string(), list_format.style()); if (!list_patterns.has_value()) @@ -182,7 +182,7 @@ ThrowCompletionOr<Vector<PatternPartition>> create_parts_from_list(VM& vm, ListF } // 13.5.3 FormatList ( listFormat, list ), https://tc39.es/ecma402/#sec-formatlist -ThrowCompletionOr<DeprecatedString> format_list(VM& vm, ListFormat const& list_format, Vector<DeprecatedString> const& list) +ThrowCompletionOr<String> format_list(VM& vm, ListFormat const& list_format, Vector<String> const& list) { // 1. Let parts be ! CreatePartsFromList(listFormat, list). auto parts = MUST_OR_THROW_OOM(create_parts_from_list(vm, list_format, list)); @@ -193,15 +193,15 @@ ThrowCompletionOr<DeprecatedString> format_list(VM& vm, ListFormat const& list_f // 3. For each Record { [[Type]], [[Value]] } part in parts, do for (auto& part : parts) { // a. Set result to the string-concatenation of result and part.[[Value]]. - result.append(move(part.value)); + result.append(part.value); } // 4. Return result. - return result.build(); + return TRY_OR_THROW_OOM(vm, result.to_string()); } // 13.5.4 FormatListToParts ( listFormat, list ), https://tc39.es/ecma402/#sec-formatlisttoparts -ThrowCompletionOr<Array*> format_list_to_parts(VM& vm, ListFormat const& list_format, Vector<DeprecatedString> const& list) +ThrowCompletionOr<Array*> format_list_to_parts(VM& vm, ListFormat const& list_format, Vector<String> const& list) { auto& realm = *vm.current_realm(); @@ -237,19 +237,19 @@ ThrowCompletionOr<Array*> format_list_to_parts(VM& vm, ListFormat const& list_fo } // 13.5.5 StringListFromIterable ( iterable ), https://tc39.es/ecma402/#sec-createstringlistfromiterable -ThrowCompletionOr<Vector<DeprecatedString>> string_list_from_iterable(VM& vm, Value iterable) +ThrowCompletionOr<Vector<String>> string_list_from_iterable(VM& vm, Value iterable) { // 1. If iterable is undefined, then if (iterable.is_undefined()) { // a. Return a new empty List. - return Vector<DeprecatedString> {}; + return Vector<String> {}; } // 2. Let iteratorRecord be ? GetIterator(iterable). auto iterator_record = TRY(get_iterator(vm, iterable)); // 3. Let list be a new empty List. - Vector<DeprecatedString> list; + Vector<String> list; // 4. Let next be true. Object* next = nullptr; @@ -274,7 +274,7 @@ ThrowCompletionOr<Vector<DeprecatedString>> string_list_from_iterable(VM& vm, Va } // iii. Append nextValue to the end of the List list. - list.append(TRY(next_value.as_string().deprecated_string())); + list.append(TRY(next_value.as_string().utf8_string())); } } while (next != nullptr); diff --git a/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.h b/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.h index b5a7fe86456e..790e03c70ec8 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/ListFormat.h @@ -6,7 +6,6 @@ #pragma once -#include <AK/DeprecatedString.h> #include <AK/HashMap.h> #include <AK/String.h> #include <AK/StringView.h> @@ -53,9 +52,9 @@ class ListFormat final : public Object { using Placeables = HashMap<StringView, Variant<PatternPartition, Vector<PatternPartition>>>; ThrowCompletionOr<Vector<PatternPartition>> deconstruct_pattern(VM&, StringView pattern, Placeables); -ThrowCompletionOr<Vector<PatternPartition>> create_parts_from_list(VM&, ListFormat const&, Vector<DeprecatedString> const& list); -ThrowCompletionOr<DeprecatedString> format_list(VM&, ListFormat const&, Vector<DeprecatedString> const& list); -ThrowCompletionOr<Array*> format_list_to_parts(VM&, ListFormat const&, Vector<DeprecatedString> const& list); -ThrowCompletionOr<Vector<DeprecatedString>> string_list_from_iterable(VM&, Value iterable); +ThrowCompletionOr<Vector<PatternPartition>> create_parts_from_list(VM&, ListFormat const&, Vector<String> const& list); +ThrowCompletionOr<String> format_list(VM&, ListFormat const&, Vector<String> const& list); +ThrowCompletionOr<Array*> format_list_to_parts(VM&, ListFormat const&, Vector<String> const& list); +ThrowCompletionOr<Vector<String>> string_list_from_iterable(VM&, Value iterable); } diff --git a/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.cpp index d153870c2d7e..41b46e18dc48 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.cpp @@ -607,7 +607,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_number_pattern(VM& vm, Num // i. Let plusSignSymbol be the ILND String representing the plus sign. auto plus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PlusSign).value_or("+"sv); // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result. - result.append({ "plusSign"sv, plus_sign_symbol }); + result.append({ "plusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(plus_sign_symbol)) }); } // e. Else if p is equal to "minusSign", then @@ -615,7 +615,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_number_pattern(VM& vm, Num // i. Let minusSignSymbol be the ILND String representing the minus sign. auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv); // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result. - result.append({ "minusSign"sv, minus_sign_symbol }); + result.append({ "minusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(minus_sign_symbol)) }); } // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then @@ -623,7 +623,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_number_pattern(VM& vm, Num // i. Let percentSignSymbol be the ILND String representing the percent sign. auto percent_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PercentSign).value_or("%"sv); // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result. - result.append({ "percentSign"sv, percent_sign_symbol }); + result.append({ "percentSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(percent_sign_symbol)) }); } // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then @@ -640,7 +640,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_number_pattern(VM& vm, Num auto unit_identifier = found_pattern.identifiers[*identifier_index]; // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result. - result.append({ "unit"sv, unit_identifier }); + result.append({ "unit"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(unit_identifier)) }); } // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then @@ -651,7 +651,8 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_number_pattern(VM& vm, Num // currency code during GetNumberFormatPattern so that we do not have to do currency // display / plurality lookups more than once. else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) { - result.append({ "currency"sv, number_format.resolve_currency_display() }); + auto currency = number_format.resolve_currency_display(); + result.append({ "currency"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(currency)) }); } // l. Else, @@ -727,12 +728,12 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& v // 2. If x is NaN, then if (number.is_nan()) { // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result. - result.append({ "nan"sv, move(formatted_string) }); + result.append({ "nan"sv, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(formatted_string)) }); } // 3. Else if x is a non-finite Number, then else if (number.is_positive_infinity() || number.is_negative_infinity()) { // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result. - result.append({ "infinity"sv, move(formatted_string) }); + result.append({ "infinity"sv, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(formatted_string)) }); } // 4. Else, else { @@ -797,7 +798,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& v // 6. If the numberFormat.[[UseGrouping]] is false, then if (number_format.use_grouping() == NumberFormat::UseGrouping::False) { // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result. - result.append({ "integer"sv, integer }); + result.append({ "integer"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(integer)) }); } // 7. Else, else { @@ -816,12 +817,12 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& v auto integer_group = groups.take_first(); // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result. - result.append({ "integer"sv, integer_group }); + result.append({ "integer"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(integer_group)) }); // iii. If groups List is not empty, then if (!groups.is_empty()) { // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result. - result.append({ "group"sv, group_sep_symbol }); + result.append({ "group"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(group_sep_symbol)) }); } } } @@ -831,9 +832,9 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& v // a. Let decimalSepSymbol be the ILND String representing the decimal separator. auto decimal_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Decimal).value_or("."sv); // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result. - result.append({ "decimal"sv, decimal_sep_symbol }); + result.append({ "decimal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(decimal_sep_symbol)) }); // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result. - result.append({ "fraction"sv, fraction.release_value() }); + result.append({ "fraction"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(*fraction)) }); } } // iv. Else if p is equal to "compactSymbol", then @@ -848,14 +849,14 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& v auto compact_identifier = number_format.compact_format().identifiers[*identifier_index]; // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result. - result.append({ "compact"sv, compact_identifier }); + result.append({ "compact"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(compact_identifier)) }); } // vi. Else if p is equal to "scientificSeparator", then else if (part == "scientificSeparator"sv) { // 1. Let scientificSeparator be the ILND String representing the exponent separator. auto scientific_separator = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Exponential).value_or("E"sv); // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result. - result.append({ "exponentSeparator"sv, scientific_separator }); + result.append({ "exponentSeparator"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(scientific_separator)) }); } // vii. Else if p is equal to "scientificExponent", then else if (part == "scientificExponent"sv) { @@ -865,7 +866,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& v auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv); // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result. - result.append({ "exponentMinusSign"sv, minus_sign_symbol }); + result.append({ "exponentMinusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(minus_sign_symbol)) }); // c. Let exponent be -exponent. exponent *= -1; @@ -880,7 +881,7 @@ ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& v exponent_result.formatted_string = ::Locale::replace_digits_for_number_system(number_format.numbering_system(), exponent_result.formatted_string); // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result. - result.append({ "exponentInteger"sv, move(exponent_result.formatted_string) }); + result.append({ "exponentInteger"sv, TRY_OR_THROW_OOM(vm, String::from_deprecated_string(exponent_result.formatted_string)) }); } // viii. Else, else { @@ -1746,7 +1747,7 @@ ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pat // 5. If xResult is equal to yResult, then if (start_result == end_result) { // a. Let appxResult be ? FormatApproximately(numberFormat, xResult). - auto approximate_result = format_approximately(number_format, move(start_result)); + auto approximate_result = TRY(format_approximately(vm, number_format, move(start_result))); // b. For each r in appxResult, do for (auto& result : approximate_result) { @@ -1774,7 +1775,7 @@ ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pat // 9. Append a new Record { [[Type]]: "literal", [[Value]]: rangeSeparator, [[Source]]: "shared" } element to result. PatternPartitionWithSource part; part.type = "literal"sv; - part.value = range_separator.value_or(range_separator_symbol); + part.value = TRY_OR_THROW_OOM(vm, String::from_deprecated_string(range_separator.value_or(range_separator_symbol))); part.source = "shared"sv; result.append(move(part)); @@ -1792,7 +1793,7 @@ ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pat } // 1.5.20 FormatApproximately ( numberFormat, result ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatapproximately -Vector<PatternPartitionWithSource> format_approximately(NumberFormat& number_format, Vector<PatternPartitionWithSource> result) +ThrowCompletionOr<Vector<PatternPartitionWithSource>> format_approximately(VM& vm, NumberFormat& number_format, Vector<PatternPartitionWithSource> result) { // 1. Let i be an index into result, determined by an implementation-defined algorithm based on numberFormat and result. // 2. Let approximatelySign be an ILND String value used to signify that a number is approximate. @@ -1801,7 +1802,7 @@ Vector<PatternPartitionWithSource> format_approximately(NumberFormat& number_for // 3. Insert a new Record { [[Type]]: "approximatelySign", [[Value]]: approximatelySign } at index i in result. PatternPartitionWithSource partition; partition.type = "approximatelySign"sv; - partition.value = approximately_sign; + partition.value = TRY_OR_THROW_OOM(vm, String::from_utf8(approximately_sign)); result.insert_before_matching(move(partition), [](auto const& part) { return part.type.is_one_of("integer"sv, "decimal"sv, "plusSign"sv, "minusSign"sv, "percentSign"sv, "currency"sv); diff --git a/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.h b/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.h index 58b2439e3610..7295600ef6a3 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.h @@ -292,7 +292,7 @@ ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM&, Value value NumberFormat::UnsignedRoundingMode get_unsigned_rounding_mode(NumberFormat::RoundingMode, bool is_negative); RoundingDecision apply_unsigned_rounding_mode(MathematicalValue const& x, MathematicalValue const& r1, MathematicalValue const& r2, Optional<NumberFormat::UnsignedRoundingMode> const& unsigned_rounding_mode); ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pattern(VM&, NumberFormat&, MathematicalValue start, MathematicalValue end); -Vector<PatternPartitionWithSource> format_approximately(NumberFormat&, Vector<PatternPartitionWithSource> result); +ThrowCompletionOr<Vector<PatternPartitionWithSource>> format_approximately(VM&, NumberFormat&, Vector<PatternPartitionWithSource> result); Vector<PatternPartitionWithSource> collapse_number_range(Vector<PatternPartitionWithSource> result); ThrowCompletionOr<DeprecatedString> format_numeric_range(VM&, NumberFormat&, MathematicalValue start, MathematicalValue end); ThrowCompletionOr<Array*> format_numeric_range_to_parts(VM&, NumberFormat&, MathematicalValue start, MathematicalValue end); diff --git a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp index 801627e6e5e8..11cdd569c806 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.cpp @@ -148,7 +148,7 @@ ThrowCompletionOr<Vector<PatternPartitionWithUnit>> partition_relative_time_patt VERIFY(patterns.size() == 1); // i. Let result be patterns.[[<valueString>]]. - auto result = patterns[0].pattern.to_deprecated_string(); + auto result = TRY_OR_THROW_OOM(vm, String::from_utf8(patterns[0].pattern)); // ii. Return a List containing the Record { [[Type]]: "literal", [[Value]]: result }. return Vector<PatternPartitionWithUnit> { { "literal"sv, move(result) } }; diff --git a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h index 947573565ace..3e8670aefd1a 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/RelativeTimeFormat.h @@ -74,7 +74,7 @@ class RelativeTimeFormat final : public Object { }; struct PatternPartitionWithUnit : public PatternPartition { - PatternPartitionWithUnit(StringView type, DeprecatedString value, StringView unit_string = {}) + PatternPartitionWithUnit(StringView type, String value, StringView unit_string = {}) : PatternPartition(type, move(value)) , unit(unit_string) {
48f367adbbe79406215600d15ecb747c17bf3a31
2023-10-08 17:41:48
Shannon Booth
libweb: Port get_element_by_id from DeprecatedFlyString
false
Port get_element_by_id from DeprecatedFlyString
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 08c2c577e991..a8be077eccf5 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -1733,7 +1733,7 @@ Document::IndicatedPart Document::determine_the_indicated_part() const return Document::TopOfTheDocument {}; // 3. Let potentialIndicatedElement be the result of finding a potential indicated element given document and fragment. - auto* potential_indicated_element = find_a_potential_indicated_element(fragment.to_deprecated_string()); + auto* potential_indicated_element = find_a_potential_indicated_element(fragment); // 4. If potentialIndicatedElement is not null, then return potentialIndicatedElement. if (potential_indicated_element) @@ -1744,7 +1744,7 @@ Document::IndicatedPart Document::determine_the_indicated_part() const auto decoded_fragment = AK::URL::percent_decode(fragment); // 7. Set potentialIndicatedElement to the result of finding a potential indicated element given document and decodedFragment. - potential_indicated_element = find_a_potential_indicated_element(decoded_fragment); + potential_indicated_element = find_a_potential_indicated_element(MUST(FlyString::from_deprecated_fly_string(decoded_fragment))); // 8. If potentialIndicatedElement is not null, then return potentialIndicatedElement. if (potential_indicated_element) @@ -1759,7 +1759,7 @@ Document::IndicatedPart Document::determine_the_indicated_part() const } // https://html.spec.whatwg.org/multipage/browsing-the-web.html#find-a-potential-indicated-element -Element* Document::find_a_potential_indicated_element(DeprecatedString fragment) const +Element* Document::find_a_potential_indicated_element(FlyString const& fragment) const { // To find a potential indicated element given a Document document and a string fragment, run these steps: @@ -1772,7 +1772,7 @@ Element* Document::find_a_potential_indicated_element(DeprecatedString fragment) // whose value is equal to fragment, then return the first such element in tree order. Element* element_with_name; root().for_each_in_subtree_of_type<Element>([&](Element const& element) { - if (element.name() == fragment) { + if (element.attribute(HTML::AttributeNames::name) == fragment) { element_with_name = const_cast<Element*>(&element); return IterationDecision::Break; } diff --git a/Userland/Libraries/LibWeb/DOM/Document.h b/Userland/Libraries/LibWeb/DOM/Document.h index 8c8c7bfabeee..d416d1c64814 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.h +++ b/Userland/Libraries/LibWeb/DOM/Document.h @@ -554,7 +554,7 @@ class Document void queue_intersection_observer_task(); void queue_an_intersection_observer_entry(IntersectionObserver::IntersectionObserver&, HighResolutionTime::DOMHighResTimeStamp time, JS::NonnullGCPtr<Geometry::DOMRectReadOnly> root_bounds, JS::NonnullGCPtr<Geometry::DOMRectReadOnly> bounding_client_rect, JS::NonnullGCPtr<Geometry::DOMRectReadOnly> intersection_rect, bool is_intersecting, double intersection_ratio, JS::NonnullGCPtr<Element> target); - Element* find_a_potential_indicated_element(DeprecatedString fragment) const; + Element* find_a_potential_indicated_element(FlyString const& fragment) const; OwnPtr<CSS::StyleComputer> m_style_computer; JS::GCPtr<CSS::StyleSheetList> m_style_sheets; diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp index c145996c10a1..57530130288a 100644 --- a/Userland/Libraries/LibWeb/DOM/Element.cpp +++ b/Userland/Libraries/LibWeb/DOM/Element.cpp @@ -1937,7 +1937,7 @@ void Element::scroll(HTML::ScrollToOptions const&) bool Element::id_reference_exists(DeprecatedString const& id_reference) const { - return document().get_element_by_id(id_reference); + return document().get_element_by_id(MUST(FlyString::from_deprecated_fly_string(id_reference))); } void Element::register_intersection_observer(Badge<IntersectionObserver::IntersectionObserver>, IntersectionObserver::IntersectionObserverRegistration registration) diff --git a/Userland/Libraries/LibWeb/DOM/Node.cpp b/Userland/Libraries/LibWeb/DOM/Node.cpp index 875eb60ac808..c60af7f90bb4 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.cpp +++ b/Userland/Libraries/LibWeb/DOM/Node.cpp @@ -1802,7 +1802,7 @@ ErrorOr<String> Node::name_or_description(NameOrDescription target, Document con } // ii. For each IDREF: for (auto const& id_ref : id_list) { - auto node = document.get_element_by_id(id_ref); + auto node = document.get_element_by_id(MUST(FlyString::from_utf8(id_ref))); if (!node) continue; @@ -1922,7 +1922,7 @@ ErrorOr<String> Node::accessible_description(Document const& document) const StringBuilder builder; auto id_list = described_by->bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace); for (auto const& id : id_list) { - if (auto description_element = document.get_element_by_id(id)) { + if (auto description_element = document.get_element_by_id(MUST(FlyString::from_utf8(id)))) { auto description = TRY( description_element->name_or_description(NameOrDescription::Description, document, visited_nodes)); @@ -1943,7 +1943,7 @@ Optional<StringView> Node::first_valid_id(DeprecatedString const& value, Documen { auto id_list = value.split_view(Infra::is_ascii_whitespace); for (auto const& id : id_list) { - if (document.get_element_by_id(id)) + if (document.get_element_by_id(MUST(FlyString::from_utf8(id)))) return id; } return {}; diff --git a/Userland/Libraries/LibWeb/DOM/NonElementParentNode.h b/Userland/Libraries/LibWeb/DOM/NonElementParentNode.h index 0332be2df1ce..d0e3792bbda0 100644 --- a/Userland/Libraries/LibWeb/DOM/NonElementParentNode.h +++ b/Userland/Libraries/LibWeb/DOM/NonElementParentNode.h @@ -19,15 +19,10 @@ template<typename NodeType> class NonElementParentNode { public: JS::GCPtr<Element const> get_element_by_id(FlyString const& id) const - { - return get_element_by_id(id.to_deprecated_fly_string()); - } - - JS::GCPtr<Element const> get_element_by_id(DeprecatedFlyString const& id) const { JS::GCPtr<Element const> found_element; static_cast<NodeType const*>(this)->template for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) { - if (element.deprecated_attribute(HTML::AttributeNames::id) == id) { + if (element.attribute(HTML::AttributeNames::id) == id) { found_element = &element; return IterationDecision::Break; } @@ -37,15 +32,10 @@ class NonElementParentNode { } JS::GCPtr<Element> get_element_by_id(FlyString const& id) - { - return get_element_by_id(id.to_deprecated_fly_string()); - } - - JS::GCPtr<Element> get_element_by_id(DeprecatedFlyString const& id) { JS::GCPtr<Element> found_element; static_cast<NodeType*>(this)->template for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) { - if (element.deprecated_attribute(HTML::AttributeNames::id) == id) { + if (element.attribute(HTML::AttributeNames::id) == id) { found_element = &element; return IterationDecision::Break; } diff --git a/Userland/Libraries/LibWeb/SVG/SVGUseElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGUseElement.cpp index 16e471f1ba0f..066a7c4bcb93 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGUseElement.cpp +++ b/Userland/Libraries/LibWeb/SVG/SVGUseElement.cpp @@ -115,7 +115,7 @@ JS::GCPtr<DOM::Element> SVGUseElement::referenced_element() } // FIXME: Support loading of external svg documents - return document().get_element_by_id(m_referenced_id.value()); + return document().get_element_by_id(MUST(FlyString::from_utf8(m_referenced_id.value()))); } // https://svgwg.org/svg2-draft/struct.html#UseShadowTree
750a6084413384873e85a3bd34a21d9fddce6361
2020-12-29 20:12:30
Linus Groh
libgui: Register TextEditor "mode" property
false
Register TextEditor "mode" property
libgui
diff --git a/Libraries/LibGUI/TextEditor.cpp b/Libraries/LibGUI/TextEditor.cpp index ad5fd82ea231..133db5c567c7 100644 --- a/Libraries/LibGUI/TextEditor.cpp +++ b/Libraries/LibGUI/TextEditor.cpp @@ -55,6 +55,10 @@ TextEditor::TextEditor(Type type) : m_type(type) { REGISTER_STRING_PROPERTY("text", text, set_text); + REGISTER_ENUM_PROPERTY("mode", mode, set_mode, Mode, + { Editable, "Editable" }, + { ReadOnly, "ReadOnly" }, + { DisplayOnly, "DisplayOnly" }); set_focus_policy(GUI::FocusPolicy::StrongFocus); set_accepts_emoji_input(true);
10a2cc3781bcf6640e8e079655289cc88063f238
2024-10-15 02:25:09
Andrew Kaster
tests: Use Swift.String extension instead of manual conversion
false
Use Swift.String extension instead of manual conversion
tests
diff --git a/Tests/LibWeb/TestLibWebSwiftBindings.swift b/Tests/LibWeb/TestLibWebSwiftBindings.swift index 5063c84b2e28..60e666a8c789 100644 --- a/Tests/LibWeb/TestLibWebSwiftBindings.swift +++ b/Tests/LibWeb/TestLibWebSwiftBindings.swift @@ -17,8 +17,7 @@ struct TestLibWebSwiftBindings { #expect(Web.Bindings.NavigationType.Push.rawValue == 0) let end = Web.Bindings.idl_enum_to_string(Web.Bindings.ScrollLogicalPosition.End) - let end_view = end.__bytes_as_string_viewUnsafe().bytes() - let end_string = Swift.String(bytes: end_view, encoding: .utf8)! + let end_string = Swift.String(akString: end)! #expect(end_string == "end") }
41da9a423142ed5a753a64a24ed4263c4f658d9b
2023-06-13 21:17:50
Andreas Kling
libweb: Resolve auto margins on abspos elements in more cases
false
Resolve auto margins on abspos elements in more cases
libweb
diff --git a/Tests/LibWeb/Layout/expected/block-and-inline/abspos-with-auto-margins-in-inline-axis.txt b/Tests/LibWeb/Layout/expected/block-and-inline/abspos-with-auto-margins-in-inline-axis.txt new file mode 100644 index 000000000000..5d0040ca1d32 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/block-and-inline/abspos-with-auto-margins-in-inline-axis.txt @@ -0,0 +1,6 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (1,1) content-size 798x18 [BFC] children: not-inline + BlockContainer <body> at (10,10) content-size 780x0 children: not-inline + BlockContainer <div#foo> at (350,1) content-size 100x100 positioned [BFC] children: not-inline + BlockContainer <div#bar> at (699,101) content-size 100x100 positioned [BFC] children: not-inline + BlockContainer <div#baz> at (1,201) content-size 100x100 positioned [BFC] children: not-inline diff --git a/Tests/LibWeb/Layout/input/block-and-inline/abspos-with-auto-margins-in-inline-axis.html b/Tests/LibWeb/Layout/input/block-and-inline/abspos-with-auto-margins-in-inline-axis.html new file mode 100644 index 000000000000..ef4cf76b7ecb --- /dev/null +++ b/Tests/LibWeb/Layout/input/block-and-inline/abspos-with-auto-margins-in-inline-axis.html @@ -0,0 +1,31 @@ +<!DOCTYPE html><style> + * { + border: 1px solid black; + } + div { + height: 100px; + width: 100px; + position: absolute; + height: 100px; + } + #foo { + margin: auto; + left: 0px; + right: 0px; + top: 0px; + } + #bar { + margin-left: auto; + margin-right: 0px; + left: 0px; + right: 0px; + top: 100px; + } + #baz { + margin-left: 0px; + margin-right: auto; + left: 0px; + right: 0px; + top: 200px; + } +</style><div id=foo></div><div id=bar></div><div id=baz></div> \ No newline at end of file diff --git a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp index 6a7d1081de0b..71564dbc62fe 100644 --- a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp @@ -598,8 +598,34 @@ void FormattingContext::compute_width_for_absolutely_positioned_non_replaced_ele goto Rule3; } + // If none of the three is auto: if (!computed_left.is_auto() && !width.is_auto() && !computed_right.is_auto()) { - // FIXME: This should be solved in a more complicated way. + // If both margin-left and margin-right are auto, + // solve the equation under the extra constraint that the two margins get equal values + // FIXME: unless this would make them negative, in which case when direction of the containing block is ltr (rtl), set margin-left (margin-right) to 0 and solve for margin-right (margin-left). + auto size_available_for_margins = width_of_containing_block - border_left - padding_left - width.to_px(box) - padding_right - border_right - right; + if (margin_left.is_auto() && margin_right.is_auto()) { + margin_left = CSS::Length::make_px(size_available_for_margins / 2); + margin_right = CSS::Length::make_px(size_available_for_margins / 2); + return width; + } + + // If one of margin-left or margin-right is auto, solve the equation for that value. + if (margin_left.is_auto()) { + margin_left = CSS::Length::make_px(size_available_for_margins); + return width; + } + if (margin_right.is_auto()) { + margin_right = CSS::Length::make_px(size_available_for_margins); + return width; + } + // If the values are over-constrained, ignore the value for left + // (in case the direction property of the containing block is rtl) + // or right (in case direction is ltr) and solve for that value. + + // NOTE: At this point we *are* over-constrained since none of margin-left, left, width, right, or margin-right are auto. + // FIXME: Check direction. + right = solve_for_right(); return width; } @@ -995,9 +1021,7 @@ void FormattingContext::layout_absolutely_positioned_element(Box const& box, Ava compute_height_for_absolutely_positioned_element(box, available_space, BeforeOrAfterInsideLayout::After); - box_state.margin_left = box.computed_values().margin().left().to_px(box, width_of_containing_block); box_state.margin_top = box.computed_values().margin().top().to_px(box, width_of_containing_block); - box_state.margin_right = box.computed_values().margin().right().to_px(box, width_of_containing_block); box_state.margin_bottom = box.computed_values().margin().bottom().to_px(box, width_of_containing_block); box_state.border_left = box.computed_values().border_left().width; @@ -1015,13 +1039,6 @@ void FormattingContext::layout_absolutely_positioned_element(Box const& box, Ava box_state.inset_right = computed_right.to_px(box, width_of_containing_block); box_state.inset_bottom = computed_bottom.to_px(box, height_of_containing_block); - if (computed_left.is_auto() && box.computed_values().width().is_auto() && computed_right.is_auto()) { - if (box.computed_values().margin().left().is_auto()) - box_state.margin_left = 0; - if (box.computed_values().margin().right().is_auto()) - box_state.margin_right = 0; - } - auto static_position = calculate_static_position(box); CSSPixelPoint used_offset;
57b7f4ec5b0afd0035e9eaec0141f9d8a865965b
2021-06-28 22:55:35
Leon Albrecht
libjs: Mark FunctionObject::is_ordinary_function() as override
false
Mark FunctionObject::is_ordinary_function() as override
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.h b/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.h index 42929c3135d5..dfdf96cb424b 100644 --- a/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.h +++ b/Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.h @@ -41,7 +41,7 @@ class OrdinaryFunctionObject final : public FunctionObject { virtual bool is_strict_mode() const final { return m_is_strict; } private: - virtual bool is_ordinary_function_object() const { return true; } + virtual bool is_ordinary_function_object() const override { return true; } virtual FunctionEnvironmentRecord* create_environment_record(FunctionObject&) override; virtual void visit_edges(Visitor&) override;
036f68f8573cceb8d7e219ba15bbd374d40e2fca
2022-07-04 11:20:32
djwisdom
ports: Update serenity-theming to latest commit
false
Update serenity-theming to latest commit
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index bd27142b424a..f229551235a8 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -219,7 +219,7 @@ This list is also available at [ports.serenityos.net](https://ports.serenityos.n | [`SDL_sound`](SDL_sound/) | SDL\_sound (Abstract soundfile decoder add-on for SDL 1.2) | 1.0.3 | https://www.icculus.org/SDL_sound/ | | [`SDLPoP`](SDLPoP/) | Prince of Persia game | | https://github.com/NagyD/SDLPoP | | [`sed`](sed/) | GNU sed | 4.8 | https://www.gnu.org/software/sed/ | -| [`serenity-theming`](serenity-theming/) | SerenityOS theming | e4e2f26 | https://github.com/SerenityOS/theming | +| [`serenity-theming`](serenity-theming/) | SerenityOS theming | 6f44f8a | https://github.com/SerenityOS/theming | | [`sfinx`](sfinx/) | Sfinx | 1.1 | https://www.scummvm.org/games/#games-sfinx | | [`sl`](sl/) | Steam Locomotive (SL) | | https://github.com/mtoyoda/sl | | [`soltys`](soltys/) | Soltys | 1.0 | https://www.scummvm.org/games/#games-soltys | diff --git a/Ports/serenity-theming/package.sh b/Ports/serenity-theming/package.sh index 0be575c7f5ba..d754e172e535 100755 --- a/Ports/serenity-theming/package.sh +++ b/Ports/serenity-theming/package.sh @@ -1,8 +1,8 @@ #!/usr/bin/env -S bash ../.port_include.sh port=serenity-theming -version=e4e2f262ea684a435e9dd2a0e4a9dbca78eeb610 +version=6f44f8aa83aa7c512dc315a4bd1d68151442cb03 workdir="theming-${version}" -files="https://github.com/SerenityOS/theming/archive/${version}.zip serenity-theming-${version}.zip fc369c11577f70dc2cf8306678928072b203c0c2bb64a3194c143831737bc0ae" +files="https://github.com/SerenityOS/theming/archive/${version}.zip serenity-theming-${version}.zip 837b1d112a53144123c3cce4456349e7800bafe6817aa02dabe511cffa1ae393" auth_type="sha256" build() {
7f1cd54b8083c55aef569ae1251043c24f64516a
2021-08-26 00:50:54
Jesse Buhagiar
libgl: Implement `glFogfv`
false
Implement `glFogfv`
libgl
diff --git a/Userland/Libraries/LibGL/CMakeLists.txt b/Userland/Libraries/LibGL/CMakeLists.txt index 6cff68532c42..baabd30e7c60 100644 --- a/Userland/Libraries/LibGL/CMakeLists.txt +++ b/Userland/Libraries/LibGL/CMakeLists.txt @@ -7,6 +7,7 @@ set(SOURCES GLBlend.cpp GLColor.cpp GLContext.cpp + GLFog.cpp GLLights.cpp GLLists.cpp GLMat.cpp diff --git a/Userland/Libraries/LibGL/GL/gl.h b/Userland/Libraries/LibGL/GL/gl.h index 43092a2f4139..d165f8124a4b 100644 --- a/Userland/Libraries/LibGL/GL/gl.h +++ b/Userland/Libraries/LibGL/GL/gl.h @@ -374,6 +374,7 @@ GLAPI void glDrawElements(GLenum mode, GLsizei count, GLenum type, const void* i GLAPI void glDepthRange(GLdouble nearVal, GLdouble farVal); GLAPI void glDepthFunc(GLenum func); GLAPI void glPolygonMode(GLenum face, GLenum mode); +GLAPI void glFogfv(GLenum mode, GLfloat* params); #ifdef __cplusplus } diff --git a/Userland/Libraries/LibGL/GLContext.h b/Userland/Libraries/LibGL/GLContext.h index 31bfeb6e9136..30bb6342d12a 100644 --- a/Userland/Libraries/LibGL/GLContext.h +++ b/Userland/Libraries/LibGL/GLContext.h @@ -77,6 +77,7 @@ class GLContext { virtual void gl_depth_range(GLdouble min, GLdouble max) = 0; virtual void gl_depth_func(GLenum func) = 0; virtual void gl_polygon_mode(GLenum face, GLenum mode) = 0; + virtual void gl_fogfv(GLenum pname, GLfloat* params) = 0; virtual void present() = 0; }; diff --git a/Userland/Libraries/LibGL/GLFog.cpp b/Userland/Libraries/LibGL/GLFog.cpp new file mode 100644 index 000000000000..381119c3deca --- /dev/null +++ b/Userland/Libraries/LibGL/GLFog.cpp @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2021, Jesse Buhagiar <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "GL/gl.h" +#include "GLContext.h" + +extern GL::GLContext* g_gl_context; + +void glFogfv(GLenum pname, GLfloat* params) +{ + g_gl_context->gl_fogfv(pname, params); +} diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.cpp b/Userland/Libraries/LibGL/SoftwareGLContext.cpp index b4c7c05357d8..ca73b70c200d 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.cpp +++ b/Userland/Libraries/LibGL/SoftwareGLContext.cpp @@ -1745,6 +1745,26 @@ void SoftwareGLContext::gl_polygon_mode(GLenum face, GLenum mode) m_rasterizer.set_options(options); } +void SoftwareGLContext::gl_fogfv(GLenum pname, GLfloat* params) +{ + RETURN_WITH_ERROR_IF(m_in_draw_state, GL_INVALID_OPERATION); + + auto options = m_rasterizer.options(); + + switch (pname) { + case GL_FOG_COLOR: + // Set rasterizer options fog color + // NOTE: We purposefully don't check for `nullptr` here (as with other calls). The spec states nothing + // about us checking for such things. If the programmer does so and hits SIGSEGV, that's on them. + options.fog_color = FloatVector4 { params[0], params[1], params[2], params[3] }; + break; + default: + RETURN_WITH_ERROR_IF(true, GL_INVALID_ENUM); + } + + m_rasterizer.set_options(options); +} + void SoftwareGLContext::present() { m_rasterizer.blit_to(*m_frontbuffer); diff --git a/Userland/Libraries/LibGL/SoftwareGLContext.h b/Userland/Libraries/LibGL/SoftwareGLContext.h index 1f578b79b0f6..5b84ceafd0e1 100644 --- a/Userland/Libraries/LibGL/SoftwareGLContext.h +++ b/Userland/Libraries/LibGL/SoftwareGLContext.h @@ -87,6 +87,7 @@ class SoftwareGLContext : public GLContext { virtual void gl_depth_range(GLdouble min, GLdouble max) override; virtual void gl_depth_func(GLenum func) override; virtual void gl_polygon_mode(GLenum face, GLenum mode) override; + virtual void gl_fogfv(GLenum pname, GLfloat* params) override; virtual void present() override; private: diff --git a/Userland/Libraries/LibGL/SoftwareRasterizer.h b/Userland/Libraries/LibGL/SoftwareRasterizer.h index 2d19484ddb50..c110f794e946 100644 --- a/Userland/Libraries/LibGL/SoftwareRasterizer.h +++ b/Userland/Libraries/LibGL/SoftwareRasterizer.h @@ -33,6 +33,12 @@ struct RasterizerOptions { float depth_max { 1 }; GLenum depth_func { GL_LESS }; GLenum polygon_mode { GL_FILL }; + FloatVector4 fog_color { + 0.0f, + 0.0f, + 0.0f, + 0.0f, + }; }; class SoftwareRasterizer final {
fd86509ef85a729f0876079a955a37739e919ba4
2023-08-01 11:06:15
Sebastian Zaha
ladybird: Remove unused spawn helper
false
Remove unused spawn helper
ladybird
diff --git a/Ladybird/HelperProcess.cpp b/Ladybird/HelperProcess.cpp index 5c8e1bec3db3..57116233c940 100644 --- a/Ladybird/HelperProcess.cpp +++ b/Ladybird/HelperProcess.cpp @@ -6,23 +6,8 @@ #include "HelperProcess.h" #include "Utilities.h" -#include <AK/String.h> #include <QCoreApplication> -ErrorOr<void> spawn_helper_process(StringView process_name, ReadonlySpan<StringView> arguments, Core::System::SearchInPath search_in_path, Optional<ReadonlySpan<StringView>> environment) -{ - auto paths = TRY(get_paths_for_helper_process(process_name)); - VERIFY(!paths.is_empty()); - ErrorOr<void> result; - for (auto const& path : paths) { - result = Core::System::exec(path, arguments, search_in_path, environment); - if (!result.is_error()) - break; - } - - return result; -} - ErrorOr<Vector<String>> get_paths_for_helper_process(StringView process_name) { auto application_path = TRY(ak_string_from_qstring(QCoreApplication::applicationDirPath())); diff --git a/Ladybird/HelperProcess.h b/Ladybird/HelperProcess.h index 6a42701ec233..9ad4fe10efcc 100644 --- a/Ladybird/HelperProcess.h +++ b/Ladybird/HelperProcess.h @@ -12,5 +12,4 @@ #include <AK/StringView.h> #include <LibCore/System.h> -ErrorOr<void> spawn_helper_process(StringView process_name, ReadonlySpan<StringView> arguments, Core::System::SearchInPath, Optional<ReadonlySpan<StringView>> environment = {}); ErrorOr<Vector<String>> get_paths_for_helper_process(StringView process_name);
85c05578390a8f3c09101a1dae3b57935d0dd018
2020-04-09 17:12:17
Andreas Kling
kernel: Simplify PCI::initialize() a bit more
false
Simplify PCI::initialize() a bit more
kernel
diff --git a/Kernel/PCI/Initializer.cpp b/Kernel/PCI/Initializer.cpp index 2f770f3941df..e893474a4754 100644 --- a/Kernel/PCI/Initializer.cpp +++ b/Kernel/PCI/Initializer.cpp @@ -36,9 +36,6 @@ namespace Kernel { namespace PCI { -static void initialize_pci_mmio_access(PhysicalAddress mcfg); -static void initialize_pci_io_access(); -static void detect_devices(); static bool test_acpi(); static bool test_pci_io(); static bool test_pci_mmio(); @@ -60,25 +57,10 @@ void initialize() bool mmio_allowed = kernel_command_line().lookup("pci_mmio").value_or("off") == "on"; if (detect_optimal_access_type(mmio_allowed) == Access::Type::MMIO) - initialize_pci_mmio_access(ACPI::Parser::the().find_table("MCFG")); + MMIOAccess::initialize(ACPI::Parser::the().find_table("MCFG")); else - initialize_pci_io_access(); -} - -void initialize_pci_mmio_access(PhysicalAddress mcfg) -{ - MMIOAccess::initialize(mcfg); - detect_devices(); -} + IOAccess::initialize(); -void initialize_pci_io_access() -{ - IOAccess::initialize(); - detect_devices(); -} - -void detect_devices() -{ enumerate_all([&](const Address& address, ID id) { klog() << "PCI: Device @ " << String::format("%w", address.seg()) << ":" << String::format("%b", address.bus()) << ":" << String::format("%b", address.slot()) << "." << String::format("%d", address.function()) << " [" << String::format("%w", id.vendor_id) << ":" << String::format("%w", id.device_id) << "]"; E1000NetworkAdapter::detect(address);
618b8574574f8c1404b637d338c67fbba771f692
2022-03-20 20:49:47
Andreas Kling
libweb: Evaluate @media CSS rules when updating style
false
Evaluate @media CSS rules when updating style
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 12016473daaa..3d67b113c955 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -627,6 +627,7 @@ void Document::update_style() return; if (!needs_full_style_update() && !needs_style_update() && !child_needs_style_update()) return; + evaluate_media_rules(); if (update_style_recursively(*this)) invalidate_layout(); m_needs_full_style_update = false; @@ -1375,6 +1376,11 @@ void Document::evaluate_media_queries_and_report_changes() } // Also not in the spec, but this is as good a place as any to evaluate @media rules! + evaluate_media_rules(); +} + +void Document::evaluate_media_rules() +{ bool any_media_queries_changed_match_state = false; for (auto& style_sheet : style_sheets().sheets()) { if (style_sheet.evaluate_media_queries(window())) diff --git a/Userland/Libraries/LibWeb/DOM/Document.h b/Userland/Libraries/LibWeb/DOM/Document.h index 94ce18bcd54d..b55f474fda6d 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.h +++ b/Userland/Libraries/LibWeb/DOM/Document.h @@ -345,6 +345,8 @@ class Document void tear_down_layout_tree(); + void evaluate_media_rules(); + ExceptionOr<void> run_the_document_write_steps(String); void increment_referencing_node_count()
bc5148354f6ad777ed9ba2988bd0547b16956102
2019-04-15 05:53:20
Andreas Kling
libcore: Add a CConfigFile class, a simple INI file parser.
false
Add a CConfigFile class, a simple INI file parser.
libcore
diff --git a/AK/HashMap.h b/AK/HashMap.h index 952777ab34b0..df802f6702b6 100644 --- a/AK/HashMap.h +++ b/AK/HashMap.h @@ -1,8 +1,9 @@ #pragma once -#include "HashTable.h" -#include "StdLibExtras.h" -#include "kstdio.h" +#include <AK/HashTable.h> +#include <AK/StdLibExtras.h> +#include <AK/Vector.h> +#include <AK/kstdio.h> namespace AK { @@ -88,6 +89,23 @@ class HashMap { m_table.remove(it); } + V& ensure(const K& key) + { + auto it = find(key); + if (it == end()) + set(key, V()); + return find(key)->value; + } + + Vector<K> keys() const + { + Vector<K> list; + list.ensure_capacity(size()); + for (auto& it : *this) + list.unchecked_append(it.key); + return list; + } + private: HashTable<Entry, EntryTraits> m_table; }; diff --git a/Games/Minesweeper/Field.cpp b/Games/Minesweeper/Field.cpp index 853f1c975f42..1480a445f843 100644 --- a/Games/Minesweeper/Field.cpp +++ b/Games/Minesweeper/Field.cpp @@ -2,6 +2,7 @@ #include <LibGUI/GButton.h> #include <LibGUI/GLabel.h> #include <AK/HashTable.h> +#include <LibCore/CConfigFile.h> #include <unistd.h> #include <time.h> @@ -30,6 +31,12 @@ Field::Field(GLabel& flag_label, GLabel& time_label, GButton& face_button, GWidg , m_flag_label(flag_label) , m_time_label(time_label) { + auto config = CConfigFile::get_for_app("Minesweeper"); + + m_mine_count = config->read_num_entry("Game", "MineCount", 10); + m_rows = config->read_num_entry("Game", "Rows", 9); + m_columns = config->read_num_entry("Game", "Columns", 9); + m_timer.on_timeout = [this] { m_time_label.set_text(String::format("%u", ++m_seconds_elapsed)); }; diff --git a/LibCore/CConfigFile.cpp b/LibCore/CConfigFile.cpp new file mode 100644 index 000000000000..e4355e6cab2d --- /dev/null +++ b/LibCore/CConfigFile.cpp @@ -0,0 +1,195 @@ +#include <LibCore/CConfigFile.h> +#include <LibCore/CFile.h> +#include <AK/StringBuilder.h> +#include <stdio.h> +#include <pwd.h> +#include <unistd.h> + +Retained<CConfigFile> CConfigFile::get_for_app(const String& app_name) +{ + String home_path; + if (auto* home_env = getenv("HOME")) { + home_path = home_env; + } else { + uid_t uid = getuid(); + if (auto* pwd = getpwuid(uid)) + home_path = pwd->pw_dir; + } + if (home_path.is_empty()) + home_path = String::format("/tmp"); + auto path = String::format("%s/%s.ini", home_path.characters(), app_name.characters()); + return adopt(*new CConfigFile(path)); +} + +CConfigFile::CConfigFile(const String& file_name) + : m_file_name(file_name) +{ + reparse(); +} + +CConfigFile::~CConfigFile() +{ + sync(); +} + +void CConfigFile::reparse() +{ + m_groups.clear(); + + CFile file(m_file_name); + if (!file.open(CIODevice::OpenMode::ReadOnly)) + return; + + HashMap<String, String>* current_group = nullptr; + + while (file.can_read_line()) { + auto line = file.read_line(BUFSIZ); + auto* cp = (const char*)line.pointer(); + + while(*cp && (*cp == ' ' || *cp == '\t' || *cp == '\n')) + ++cp; + + switch (*cp) { + case '\0':// EOL... + case '#': // Comment, skip entire line. + case ';': // -||- + continue; + case '[': { // Start of new group. + StringBuilder builder; + ++cp; // Skip the '[' + while (*cp && (*cp != ']')) + builder.append(*(cp++)); + current_group = &m_groups.ensure(builder.to_string()); + break; + } + default: { // Start of key{ + StringBuilder key_builder; + StringBuilder value_builder; + while (*cp && (*cp != '=')) + key_builder.append(*(cp++)); + ++cp; // Skip the '=' + while (*cp && (*cp != '\n')) + value_builder.append(*(cp++)); + if (!current_group) { + // We're not in a group yet, create one with the name ""... + current_group = &m_groups.ensure(""); + } + current_group->set(key_builder.to_string(), value_builder.to_string()); + } + } + } +} + +String CConfigFile::read_entry(const String& group, const String& key, const String& default_value) const +{ + if (!has_key(group, key)) { + const_cast<CConfigFile&>(*this).write_entry(group, key, default_value); + return default_value; + } + auto it = m_groups.find(group); + auto jt = it->value.find(key); + return jt->value; +} + +int CConfigFile::read_num_entry(const String& group, const String &key, int default_value) const +{ + if (!has_key(group, key)) { + const_cast<CConfigFile&>(*this).write_num_entry(group, key, default_value); + return default_value; + } + + bool ok; + int value = read_entry(group, key).to_uint(ok); + if (!ok) + return default_value; + return value; +} + +bool CConfigFile::read_bool_entry(const String& group, const String &key, bool default_value) const +{ + return read_entry(group, key, default_value ? "1" : "0") == "1"; +} + +void CConfigFile::write_entry(const String& group, const String& key, const String& value) +{ + m_groups.ensure(group).ensure(key) = value; + m_dirty = true; +} + +void CConfigFile::write_num_entry(const String& group, const String& key, int value) +{ + write_entry(group, key, String::format("%d", value)); +} + +bool CConfigFile::sync() +{ + if (!m_dirty) + return true; + + FILE *fp = fopen(m_file_name.characters(), "wb"); + if (!fp) + return false; + + for (auto& it : m_groups) { + fprintf(fp, "[%s]\n", it.key.characters()); + for (auto& jt : it.value) + fprintf(fp, "%s=%s\n", jt.key.characters(), jt.value.characters()); + fprintf(fp, "\n"); + } + + fclose(fp); + + m_dirty = false; + return true; +} + +void CConfigFile::dump() const +{ + for (auto& it : m_groups) { + printf("[%s]\n", it.key.characters()); + for (auto& jt : it.value) + printf("%s=%s\n", jt.key.characters(), jt.value.characters()); + printf("\n"); + } +} + +Vector<String> CConfigFile::groups() const +{ + return m_groups.keys(); +} + +Vector<String> CConfigFile::keys(const String& group) const +{ + auto it = m_groups.find(group); + if (it == m_groups.end()) + return { }; + return it->value.keys(); +} + +bool CConfigFile::has_key(const String& group, const String& key) const +{ + auto it = m_groups.find(group); + if (it == m_groups.end()) + return { }; + return it->value.contains(key); +} + +bool CConfigFile::has_group(const String& group) const +{ + return m_groups.contains(group); +} + +void CConfigFile::remove_group(const String& group) +{ + m_groups.remove(group); + m_dirty = true; +} + +void CConfigFile::remove_entry(const String& group, const String& key) +{ + auto it = m_groups.find(group); + if (it == m_groups.end()) + return; + it->value.remove(key); + m_dirty = true; +} diff --git a/LibCore/CConfigFile.h b/LibCore/CConfigFile.h new file mode 100644 index 000000000000..fa3f5d9f7c22 --- /dev/null +++ b/LibCore/CConfigFile.h @@ -0,0 +1,45 @@ +#pragma once + +#include <AK/Vector.h> +#include <AK/HashMap.h> +#include <AK/AKString.h> +#include <AK/Retainable.h> +#include <AK/RetainPtr.h> + +class CConfigFile : public Retainable<CConfigFile> { +public: + static Retained<CConfigFile> get_for_app(const String& app_name); + ~CConfigFile(); + + bool has_group(const String&) const; + bool has_key(const String& group, const String& key) const; + + Vector<String> groups() const; + Vector<String> keys(const String& group) const; + + String read_entry(const String& group, const String& key, const String& default_vaule = String()) const; + int read_num_entry(const String& group, const String& key, int default_value = 0) const; + bool read_bool_entry(const String& group, const String& key, bool default_value = false) const; + + void write_entry(const String& group, const String& key, const String &value); + void write_num_entry(const String& group, const String& key, int value); + void write_bool_entry(const String& group, const String& key, bool value); + + void dump() const; + + bool is_dirty() const { return m_dirty; } + + bool sync(); + + void remove_group(const String& group); + void remove_entry(const String& group, const String& key); + +private: + explicit CConfigFile(const String& file_name); + + void reparse(); + + String m_file_name; + HashMap<String, HashMap<String, String>> m_groups; + bool m_dirty { false }; +}; diff --git a/LibCore/Makefile b/LibCore/Makefile index 6e5dda7f5acb..8331bb64bdf5 100644 --- a/LibCore/Makefile +++ b/LibCore/Makefile @@ -13,6 +13,7 @@ OBJS = \ CObject.o \ CTimer.o \ CEventLoop.o \ + CConfigFile.o \ CEvent.o LIBRARY = libcore.a
fccd0432a13b17a85cea3dbd48ee7999159f31a9
2021-12-22 13:32:36
Idan Horowitz
kernel: Don't share the bottom 2 MiB of kernel mappings with processes
false
Don't share the bottom 2 MiB of kernel mappings with processes
kernel
diff --git a/Kernel/Memory/PageDirectory.cpp b/Kernel/Memory/PageDirectory.cpp index d75669da6578..0e922005f7d1 100644 --- a/Kernel/Memory/PageDirectory.cpp +++ b/Kernel/Memory/PageDirectory.cpp @@ -125,13 +125,6 @@ ErrorOr<NonnullRefPtr<PageDirectory>> PageDirectory::try_create_for_userspace(Vi MM.unquickmap_page(); } - // Clone bottom 2 MiB of mappings from kernel_page_directory - PageDirectoryEntry buffer; - auto* kernel_pd = MM.quickmap_pd(MM.kernel_page_directory(), 0); - memcpy(&buffer, kernel_pd, sizeof(PageDirectoryEntry)); - auto* new_pd = MM.quickmap_pd(*directory, 0); - memcpy(new_pd, &buffer, sizeof(PageDirectoryEntry)); - cr3_map().insert(directory->cr3(), directory); return directory; }
59795aab41728b6ffda903781b9063f4dc907490
2019-10-09 22:12:08
Andreas Kling
libhtml: Handle CSS declarations that don't end in ';'
false
Handle CSS declarations that don't end in ';'
libhtml
diff --git a/Libraries/LibHTML/Parser/CSSParser.cpp b/Libraries/LibHTML/Parser/CSSParser.cpp index 4166177b7872..17957c3b4286 100644 --- a/Libraries/LibHTML/Parser/CSSParser.cpp +++ b/Libraries/LibHTML/Parser/CSSParser.cpp @@ -114,12 +114,14 @@ class CSSParser { char consume_specific(char ch) { PARSE_ASSERT(peek() == ch); + PARSE_ASSERT(index < css.length()); ++index; return ch; } char consume_one() { + PARSE_ASSERT(index < css.length()); return css[index++]; }; @@ -237,12 +239,12 @@ class CSSParser { bool is_valid_property_name_char(char ch) const { - return !isspace(ch) && ch != ':'; + return ch && !isspace(ch) && ch != ':'; } bool is_valid_property_value_char(char ch) const { - return ch != '!' && ch != ';'; + return ch && ch != '!' && ch != ';'; } Optional<StyleProperty> parse_property() @@ -280,7 +282,7 @@ class CSSParser { consume_whitespace(); is_important = true; } - if (peek() != '}') + if (peek() && peek() != '}') consume_specific(';'); return StyleProperty { parse_css_property_id(property_name), parse_css_value(property_value), is_important };
9d9347cd5aec545ad5c0f48cc637ca3e13970808
2020-12-03 15:21:56
AnotherTest
shell: Fix bad cast to BarewordLiteral
false
Fix bad cast to BarewordLiteral
shell
diff --git a/Shell/Parser.cpp b/Shell/Parser.cpp index e3c43c0ed44e..c6b322755c60 100644 --- a/Shell/Parser.cpp +++ b/Shell/Parser.cpp @@ -1380,7 +1380,7 @@ RefPtr<AST::Node> Parser::parse_glob() auto glob_after = parse_glob(); if (glob_after) { if (glob_after->is_glob()) { - auto glob = static_cast<AST::BarewordLiteral*>(glob_after.ptr()); + auto glob = static_cast<AST::Glob*>(glob_after.ptr()); textbuilder.append(glob->text()); } else if (glob_after->is_bareword()) { auto bareword = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
a64a7940e484a51c6dcbd78d592b2233952dbc5e
2022-02-14 22:09:46
Timothy Flynn
libunicode: Port the UCD generator to the stream API
false
Port the UCD generator to the stream API
libunicode
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp index 338073877a7f..2188d8adbff5 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp @@ -18,7 +18,7 @@ #include <AK/Types.h> #include <AK/Vector.h> #include <LibCore/ArgsParser.h> -#include <LibCore/File.h> +#include <LibCore/Stream.h> // Some code points are excluded from UnicodeData.txt, and instead are part of a "range" of code // points, as indicated by the "name" field. For example: @@ -163,17 +163,21 @@ static CodePointRange parse_code_point_range(StringView list) return code_point_range; } -static void parse_special_casing(Core::File& file, UnicodeData& unicode_data) +static ErrorOr<void> parse_special_casing(Core::Stream::BufferedFile& file, UnicodeData& unicode_data) { - while (file.can_read_line()) { - auto line = file.read_line(); + Array<u8, 1024> buffer; + + while (TRY(file.can_read_line())) { + auto nread = TRY(file.read_line(buffer)); + StringView line { buffer.data(), nread }; + if (line.is_empty() || line.starts_with('#')) continue; if (auto index = line.find('#'); index.has_value()) - line = line.substring(0, *index); + line = line.substring_view(0, *index); - auto segments = line.split(';', true); + auto segments = line.split_view(';', true); VERIFY(segments.size() == 5 || segments.size() == 6); SpecialCasing casing {}; @@ -183,16 +187,16 @@ static void parse_special_casing(Core::File& file, UnicodeData& unicode_data) casing.uppercase_mapping = parse_code_point_list(segments[3]); if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) { - auto conditions = condition.split(' ', true); + auto conditions = condition.split_view(' ', true); VERIFY(conditions.size() == 1 || conditions.size() == 2); if (conditions.size() == 2) { - casing.locale = move(conditions[0]); - casing.condition = move(conditions[1]); + casing.locale = conditions[0]; + casing.condition = conditions[1]; } else if (all_of(conditions[0], is_ascii_lower_alpha)) { - casing.locale = move(conditions[0]); + casing.locale = conditions[0]; } else { - casing.condition = move(conditions[0]); + casing.condition = conditions[0]; } if (!casing.locale.is_empty()) @@ -222,17 +226,23 @@ static void parse_special_casing(Core::File& file, UnicodeData& unicode_data) for (u32 i = 0; i < unicode_data.special_casing.size(); ++i) unicode_data.special_casing[i].index = i; + + return {}; } -static void parse_prop_list(Core::File& file, PropList& prop_list, bool multi_value_property = false) +static ErrorOr<void> parse_prop_list(Core::Stream::BufferedFile& file, PropList& prop_list, bool multi_value_property = false) { - while (file.can_read_line()) { - auto line = file.read_line(); + Array<u8, 1024> buffer; + + while (TRY(file.can_read_line())) { + auto nread = TRY(file.read_line(buffer)); + StringView line { buffer.data(), nread }; + if (line.is_empty() || line.starts_with('#')) continue; if (auto index = line.find('#'); index.has_value()) - line = line.substring(0, *index); + line = line.substring_view(0, *index); auto segments = line.split_view(';', true); VERIFY(segments.size() == 2); @@ -250,11 +260,14 @@ static void parse_prop_list(Core::File& file, PropList& prop_list, bool multi_va code_points.append(code_point_range); } } + + return {}; } -static void parse_alias_list(Core::File& file, PropList const& prop_list, Vector<Alias>& prop_aliases) +static ErrorOr<void> parse_alias_list(Core::Stream::BufferedFile& file, PropList const& prop_list, Vector<Alias>& prop_aliases) { String current_property; + Array<u8, 1024> buffer; auto append_alias = [&](auto alias, auto property) { // Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip. @@ -268,11 +281,13 @@ static void parse_alias_list(Core::File& file, PropList const& prop_list, Vector prop_aliases.append({ property, alias }); }; - while (file.can_read_line()) { - auto line = file.read_line(); + while (TRY(file.can_read_line())) { + auto nread = TRY(file.read_line(buffer)); + StringView line { buffer.data(), nread }; + if (line.is_empty() || line.starts_with('#')) { if (line.ends_with("Properties"sv)) - current_property = line.substring(2); + current_property = line.substring_view(2); continue; } @@ -292,12 +307,18 @@ static void parse_alias_list(Core::File& file, PropList const& prop_list, Vector append_alias(alias, property); } } + + return {}; } -static void parse_name_aliases(Core::File& file, UnicodeData& unicode_data) +static ErrorOr<void> parse_name_aliases(Core::Stream::BufferedFile& file, UnicodeData& unicode_data) { - while (file.can_read_line()) { - auto line = file.read_line(); + Array<u8, 1024> buffer; + + while (TRY(file.can_read_line())) { + auto nread = TRY(file.read_line(buffer)); + StringView line { buffer.data(), nread }; + if (line.is_empty() || line.starts_with('#')) continue; @@ -315,11 +336,14 @@ static void parse_name_aliases(Core::File& file, UnicodeData& unicode_data) unicode_data.code_point_display_name_aliases.set(*code_point, alias); } } + + return {}; } -static void parse_value_alias_list(Core::File& file, StringView desired_category, Vector<String> const& value_list, Vector<Alias>& prop_aliases, bool primary_value_is_first = true) +static ErrorOr<void> parse_value_alias_list(Core::Stream::BufferedFile& file, StringView desired_category, Vector<String> const& value_list, Vector<Alias>& prop_aliases, bool primary_value_is_first = true) { - VERIFY(file.seek(0)); + TRY(file.seek(0, Core::Stream::SeekMode::SetPosition)); + Array<u8, 1024> buffer; auto append_alias = [&](auto alias, auto value) { // Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip. @@ -333,13 +357,15 @@ static void parse_value_alias_list(Core::File& file, StringView desired_category prop_aliases.append({ value, alias }); }; - while (file.can_read_line()) { - auto line = file.read_line(); + while (TRY(file.can_read_line())) { + auto nread = TRY(file.read_line(buffer)); + StringView line { buffer.data(), nread }; + if (line.is_empty() || line.starts_with('#')) continue; if (auto index = line.find('#'); index.has_value()) - line = line.substring(0, *index); + line = line.substring_view(0, *index); auto segments = line.split_view(';', true); auto category = segments[0].trim_whitespace(); @@ -357,17 +383,23 @@ static void parse_value_alias_list(Core::File& file, StringView desired_category append_alias(alias, value); } } + + return {}; } -static void parse_normalization_props(Core::File& file, UnicodeData& unicode_data) +static ErrorOr<void> parse_normalization_props(Core::Stream::BufferedFile& file, UnicodeData& unicode_data) { - while (file.can_read_line()) { - auto line = file.read_line(); + Array<u8, 1024> buffer; + + while (TRY(file.can_read_line())) { + auto nread = TRY(file.read_line(buffer)); + StringView line { buffer.data(), nread }; + if (line.is_empty() || line.starts_with('#')) continue; if (auto index = line.find('#'); index.has_value()) - line = line.substring(0, *index); + line = line.substring_view(0, *index); auto segments = line.split_view(';', true); VERIFY((segments.size() == 2) || (segments.size() == 3)); @@ -395,6 +427,8 @@ static void parse_normalization_props(Core::File& file, UnicodeData& unicode_dat auto& prop_list = unicode_data.prop_list.ensure(property); prop_list.append(move(code_point_range)); } + + return {}; } static void add_canonical_code_point_name(CodePointRange range, StringView name, UnicodeData& unicode_data) @@ -451,7 +485,7 @@ static void add_canonical_code_point_name(CodePointRange range, StringView name, unicode_data.code_point_display_names.append({ range, name }); } -static void parse_unicode_data(Core::File& file, UnicodeData& unicode_data) +static ErrorOr<void> parse_unicode_data(Core::Stream::BufferedFile& file, UnicodeData& unicode_data) { Optional<u32> code_point_range_start; @@ -459,26 +493,30 @@ static void parse_unicode_data(Core::File& file, UnicodeData& unicode_data) Optional<u32> assigned_code_point_range_start = 0; u32 previous_code_point = 0; - while (file.can_read_line()) { - auto line = file.read_line(); + Array<u8, 1024> buffer; + + while (TRY(file.can_read_line())) { + auto nread = TRY(file.read_line(buffer)); + StringView line { buffer.data(), nread }; + if (line.is_empty()) continue; - auto segments = line.split(';', true); + auto segments = line.split_view(';', true); VERIFY(segments.size() == 15); CodePointData data {}; data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value(); - data.name = move(segments[1]); + data.name = segments[1]; data.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value(); - data.bidi_class = move(segments[4]); - data.decomposition_type = move(segments[5]); + data.bidi_class = segments[4]; + data.decomposition_type = segments[5]; data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]); data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]); data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]); data.bidi_mirrored = segments[9] == "Y"sv; - data.unicode_1_name = move(segments[10]); - data.iso_comment = move(segments[11]); + data.unicode_1_name = segments[10]; + data.iso_comment = segments[11]; data.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]); data.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]); data.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]); @@ -537,9 +575,11 @@ static void parse_unicode_data(Core::File& file, UnicodeData& unicode_data) unicode_data.code_point_data.append(move(data)); } + + return {}; } -static void generate_unicode_data_header(Core::File& file, UnicodeData& unicode_data) +static ErrorOr<void> generate_unicode_data_header(Core::Stream::BufferedFile& file, UnicodeData& unicode_data) { StringBuilder builder; SourceGenerator generator { builder }; @@ -619,10 +659,11 @@ struct SpecialCasing { } )~~~"); - VERIFY(file.write(generator.as_string_view())); + TRY(file.write(generator.as_string_view().bytes())); + return {}; } -static void generate_unicode_data_implementation(Core::File& file, UnicodeData const& unicode_data) +static ErrorOr<void> generate_unicode_data_implementation(Core::Stream::BufferedFile& file, UnicodeData const& unicode_data) { StringBuilder builder; SourceGenerator generator { builder }; @@ -973,7 +1014,8 @@ bool code_point_has_@enum_snake@(u32 code_point, @enum_title@ @enum_snake@) } )~~~"); - VERIFY(file.write(generator.as_string_view())); + TRY(file.write(generator.as_string_view().bytes())); + return {}; } static Vector<u32> flatten_code_point_ranges(Vector<CodePointRange> const& code_points) @@ -1143,58 +1185,49 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) args_parser.add_option(sentence_break_path, "Path to SentenceBreakProperty.txt file", "sentence-break-path", 'i', "sentence-break-path"); args_parser.parse(arguments); - auto open_file = [&](StringView path, Core::OpenMode mode = Core::OpenMode::ReadOnly) -> ErrorOr<NonnullRefPtr<Core::File>> { - if (path.is_empty()) { - args_parser.print_usage(stderr, arguments.argv[0]); - return Error::from_string_literal("Must provide all command line options"sv); - } - - return Core::File::open(path, mode); - }; - - auto generated_header_file = TRY(open_file(generated_header_path, Core::OpenMode::ReadWrite)); - auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::OpenMode::ReadWrite)); - auto unicode_data_file = TRY(open_file(unicode_data_path)); - auto derived_general_category_file = TRY(open_file(derived_general_category_path)); - auto special_casing_file = TRY(open_file(special_casing_path)); - auto prop_list_file = TRY(open_file(prop_list_path)); - auto derived_core_prop_file = TRY(open_file(derived_core_prop_path)); - auto derived_binary_prop_file = TRY(open_file(derived_binary_prop_path)); - auto prop_alias_file = TRY(open_file(prop_alias_path)); - auto prop_value_alias_file = TRY(open_file(prop_value_alias_path)); - auto name_alias_file = TRY(open_file(name_alias_path)); - auto scripts_file = TRY(open_file(scripts_path)); - auto script_extensions_file = TRY(open_file(script_extensions_path)); - auto emoji_data_file = TRY(open_file(emoji_data_path)); - auto normalization_file = TRY(open_file(normalization_path)); - auto grapheme_break_file = TRY(open_file(grapheme_break_path)); - auto word_break_file = TRY(open_file(word_break_path)); - auto sentence_break_file = TRY(open_file(sentence_break_path)); + auto generated_header_file = TRY(open_file(generated_header_path, Core::Stream::OpenMode::Write)); + auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::Stream::OpenMode::Write)); + auto unicode_data_file = TRY(open_file(unicode_data_path, Core::Stream::OpenMode::Read)); + auto derived_general_category_file = TRY(open_file(derived_general_category_path, Core::Stream::OpenMode::Read)); + auto special_casing_file = TRY(open_file(special_casing_path, Core::Stream::OpenMode::Read)); + auto prop_list_file = TRY(open_file(prop_list_path, Core::Stream::OpenMode::Read)); + auto derived_core_prop_file = TRY(open_file(derived_core_prop_path, Core::Stream::OpenMode::Read)); + auto derived_binary_prop_file = TRY(open_file(derived_binary_prop_path, Core::Stream::OpenMode::Read)); + auto prop_alias_file = TRY(open_file(prop_alias_path, Core::Stream::OpenMode::Read)); + auto prop_value_alias_file = TRY(open_file(prop_value_alias_path, Core::Stream::OpenMode::Read)); + auto name_alias_file = TRY(open_file(name_alias_path, Core::Stream::OpenMode::Read)); + auto scripts_file = TRY(open_file(scripts_path, Core::Stream::OpenMode::Read)); + auto script_extensions_file = TRY(open_file(script_extensions_path, Core::Stream::OpenMode::Read)); + auto emoji_data_file = TRY(open_file(emoji_data_path, Core::Stream::OpenMode::Read)); + auto normalization_file = TRY(open_file(normalization_path, Core::Stream::OpenMode::Read)); + auto grapheme_break_file = TRY(open_file(grapheme_break_path, Core::Stream::OpenMode::Read)); + auto word_break_file = TRY(open_file(word_break_path, Core::Stream::OpenMode::Read)); + auto sentence_break_file = TRY(open_file(sentence_break_path, Core::Stream::OpenMode::Read)); UnicodeData unicode_data {}; - parse_special_casing(special_casing_file, unicode_data); - parse_prop_list(derived_general_category_file, unicode_data.general_categories); - parse_prop_list(prop_list_file, unicode_data.prop_list); - parse_prop_list(derived_core_prop_file, unicode_data.prop_list); - parse_prop_list(derived_binary_prop_file, unicode_data.prop_list); - parse_prop_list(emoji_data_file, unicode_data.prop_list); - parse_normalization_props(normalization_file, unicode_data); - parse_alias_list(prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases); - parse_prop_list(scripts_file, unicode_data.script_list); - parse_prop_list(script_extensions_file, unicode_data.script_extensions, true); - parse_name_aliases(name_alias_file, unicode_data); - parse_prop_list(grapheme_break_file, unicode_data.grapheme_break_props); - parse_prop_list(word_break_file, unicode_data.word_break_props); - parse_prop_list(sentence_break_file, unicode_data.sentence_break_props); + TRY(parse_special_casing(*special_casing_file, unicode_data)); + TRY(parse_prop_list(*derived_general_category_file, unicode_data.general_categories)); + TRY(parse_prop_list(*prop_list_file, unicode_data.prop_list)); + TRY(parse_prop_list(*derived_core_prop_file, unicode_data.prop_list)); + TRY(parse_prop_list(*derived_binary_prop_file, unicode_data.prop_list)); + TRY(parse_prop_list(*emoji_data_file, unicode_data.prop_list)); + TRY(parse_normalization_props(*normalization_file, unicode_data)); + TRY(parse_alias_list(*prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases)); + TRY(parse_prop_list(*scripts_file, unicode_data.script_list)); + TRY(parse_prop_list(*script_extensions_file, unicode_data.script_extensions, true)); + TRY(parse_name_aliases(*name_alias_file, unicode_data)); + TRY(parse_prop_list(*grapheme_break_file, unicode_data.grapheme_break_props)); + TRY(parse_prop_list(*word_break_file, unicode_data.word_break_props)); + TRY(parse_prop_list(*sentence_break_file, unicode_data.sentence_break_props)); populate_general_category_unions(unicode_data.general_categories); - parse_unicode_data(unicode_data_file, unicode_data); - parse_value_alias_list(prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases); - parse_value_alias_list(prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false); + TRY(parse_unicode_data(*unicode_data_file, unicode_data)); + TRY(parse_value_alias_list(*prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases)); + TRY(parse_value_alias_list(*prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false)); normalize_script_extensions(unicode_data.script_extensions, unicode_data.script_list, unicode_data.script_aliases); - generate_unicode_data_header(generated_header_file, unicode_data); - generate_unicode_data_implementation(generated_implementation_file, unicode_data); + TRY(generate_unicode_data_header(*generated_header_file, unicode_data)); + TRY(generate_unicode_data_implementation(*generated_implementation_file, unicode_data)); return 0; }
8532ca1b57fce7be393548fc29d615bf47a58f09
2022-11-26 03:14:47
Julian Offenhäuser
libpdf: Convert dash pattern array elements to integers if necessary
false
Convert dash pattern array elements to integers if necessary
libpdf
diff --git a/Userland/Libraries/LibPDF/Renderer.cpp b/Userland/Libraries/LibPDF/Renderer.cpp index 48d7d1023944..b692be016e41 100644 --- a/Userland/Libraries/LibPDF/Renderer.cpp +++ b/Userland/Libraries/LibPDF/Renderer.cpp @@ -162,7 +162,7 @@ RENDERER_HANDLER(set_dash_pattern) auto dash_array = MUST(m_document->resolve_to<ArrayObject>(args[0])); Vector<int> pattern; for (auto& element : *dash_array) - pattern.append(element.get<int>()); + pattern.append(element.to_int()); state().line_dash_pattern = LineDashPattern { pattern, args[1].get<int>() }; return {}; }
35efdb17f9c3856d1c241d9f63619a4d1174a509
2022-11-27 01:11:47
Liav A
userland: Add the BuggieBox program
false
Add the BuggieBox program
userland
diff --git a/Userland/BuggieBox/CMakeLists.txt b/Userland/BuggieBox/CMakeLists.txt new file mode 100644 index 000000000000..200daa51429e --- /dev/null +++ b/Userland/BuggieBox/CMakeLists.txt @@ -0,0 +1,51 @@ +serenity_component( + BuggieBox + REQUIRED + TARGETS BuggieBox +) + +function (buggiebox_utility src) + get_filename_component(utility ${src} NAME_WE) + target_sources(BuggieBox PRIVATE ${src}) + set_source_files_properties(${src} PROPERTIES COMPILE_DEFINITIONS "serenity_main=${utility}_main") +endfunction() + +set(utility_srcs + ../Utilities/cat.cpp + ../Utilities/checksum.cpp + ../Utilities/chmod.cpp + ../Utilities/chown.cpp + ../Utilities/cp.cpp + ../Utilities/df.cpp + ../Utilities/env.cpp + ../Utilities/file.cpp + ../Utilities/find.cpp + ../Utilities/id.cpp + ../Utilities/less.cpp + ../Utilities/ln.cpp + ../Utilities/ls.cpp + ../Utilities/lsblk.cpp + ../Utilities/mkdir.cpp + ../Utilities/mknod.cpp + ../Utilities/mount.cpp + ../Utilities/mv.cpp + ../Utilities/ps.cpp + ../Utilities/rm.cpp + ../Utilities/rmdir.cpp + ../Utilities/tail.cpp + ../Utilities/tree.cpp + ../Utilities/umount.cpp + ../Utilities/uname.cpp + ../Utilities/uniq.cpp +) + +serenity_bin(BuggieBox) +target_sources(BuggieBox PRIVATE main.cpp) +target_link_libraries(BuggieBox PRIVATE LibMain LibShell LibCompress LibCore LibCrypto LibGfx LibLine LibRegex) + +foreach(file IN LISTS utility_srcs) + buggiebox_utility(${file}) +endforeach() + +target_sources(BuggieBox PRIVATE ../Shell/main.cpp) +set_source_files_properties( ../Shell/main.cpp PROPERTIES COMPILE_DEFINITIONS "serenity_main=sh_main") diff --git a/Userland/BuggieBox/main.cpp b/Userland/BuggieBox/main.cpp new file mode 100644 index 000000000000..d951d7ea3bc8 --- /dev/null +++ b/Userland/BuggieBox/main.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022, Liav A. <[email protected]> + * Copyright (c) 2022, Tim Schumacher <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <AK/LexicalPath.h> +#include <LibMain/Main.h> +#include <Userland/Shell/Shell.h> + +#define ENUMERATE_UTILITIES(E) \ + E(cat) \ + E(checksum) \ + E(chmod) \ + E(chown) \ + E(cp) \ + E(df) \ + E(env) \ + E(file) \ + E(find) \ + E(id) \ + E(less) \ + E(ln) \ + E(ls) \ + E(lsblk) \ + E(mkdir) \ + E(mknod) \ + E(mount) \ + E(mv) \ + E(ps) \ + E(rm) \ + E(sh) \ + E(rmdir) \ + E(tail) \ + E(tree) \ + E(umount) \ + E(uname) \ + E(uniq) + +// Declare the entrypoints of all the tools that we delegate to. +// Relying on `decltype(serenity_main)` ensures that we always stay consistent with the `serenity_main` signature. +#define DECLARE_ENTRYPOINT(name) decltype(serenity_main) name##_main; +ENUMERATE_UTILITIES(DECLARE_ENTRYPOINT) +#undef DECLARE_ENTRYPOINT + +static void fail() +{ + out(stderr, "Direct running of BuggieBox was detected without finding a proper requested utility.\n"); + out(stderr, "The following programs are supported: uname, env, lsblk, file, df, mount, umount, mkdir, "); + out(stderr, "rmdir, rm, chown, chmod, cp, ln, ls, mv, cat, md5sum, sha1sum, sha256sum, sha512sum, sh, uniq, id, tail, "); + out(stderr, "find, less, mknod, ps\n"); + out(stderr, "To use one of these included utilities, create a symbolic link with the target being this binary, and ensure the basename"); + out(stderr, "is included within.\n"); +} + +struct Runner { + StringView name; + ErrorOr<int> (*func)(Main::Arguments arguments) = nullptr; +}; + +static constexpr Runner s_runners[] = { +#define RUNNER_ENTRY(name) { #name##sv, name##_main }, + ENUMERATE_UTILITIES(RUNNER_ENTRY) +#undef RUNNER_ENTRY + + // Some tools have additional aliases. + { "md5sum"sv, checksum_main }, + { "sha1sum"sv, checksum_main }, + { "sha256sum"sv, checksum_main }, + { "sha512sum"sv, checksum_main }, + { "Shell"sv, sh_main }, +}; + +static ErrorOr<int> run_program(Main::Arguments arguments, LexicalPath const& runbase, bool& found_runner) +{ + for (auto& runner : s_runners) { + if (runbase.basename() == runner.name) { + found_runner = true; + return runner.func(arguments); + } + } + return 0; +} + +static ErrorOr<int> buggiebox_main(Main::Arguments arguments) +{ + if (arguments.argc == 0) { + fail(); + return 1; + } + bool found_runner = false; + LexicalPath runbase { arguments.strings[0] }; + auto result = TRY(run_program(arguments, runbase, found_runner)); + if (!found_runner) + fail(); + return result; +} + +ErrorOr<int> serenity_main(Main::Arguments arguments) +{ + LexicalPath runbase { arguments.strings[0] }; + if (runbase.basename() == "BuggieBox"sv) { + Main::Arguments utility_arguments = arguments; + utility_arguments.argc--; + utility_arguments.argv++; + utility_arguments.strings = arguments.strings.slice(1); + return buggiebox_main(utility_arguments); + } + return buggiebox_main(arguments); +} diff --git a/Userland/CMakeLists.txt b/Userland/CMakeLists.txt index c3d2b295b048..6539a889985a 100644 --- a/Userland/CMakeLists.txt +++ b/Userland/CMakeLists.txt @@ -22,6 +22,7 @@ add_subdirectory(DevTools) add_subdirectory(DynamicLoader) add_subdirectory(Games) add_subdirectory(Libraries) +add_subdirectory(BuggieBox) add_subdirectory(Applets) add_subdirectory(Services) add_subdirectory(Shell)
b0e7d59b8b0bcfbd03c14a4143d0838882ea791e
2022-12-02 06:34:13
Linus Groh
libjs: Throw on conversion from TimeZone to Calendar and vice versa
false
Throw on conversion from TimeZone to Calendar and vice versa
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/ErrorTypes.h b/Userland/Libraries/LibJS/Runtime/ErrorTypes.h index b832c09bfa79..4d57ab2c8400 100644 --- a/Userland/Libraries/LibJS/Runtime/ErrorTypes.h +++ b/Userland/Libraries/LibJS/Runtime/ErrorTypes.h @@ -282,6 +282,8 @@ M(TemporalPropertyMustBeFinite, "Property must not be Infinity") \ M(TemporalPropertyMustBePositiveInteger, "Property must be a positive integer") \ M(TemporalTimeZoneOffsetStringMismatch, "Time zone offset string mismatch: '{}' is not equal to '{}'") \ + M(TemporalUnexpectedCalendarObject, "Got unexpected Calendar object in conversion to TimeZone") \ + M(TemporalUnexpectedTimeZoneObject, "Got unexpected TimeZone object in conversion to Calendar") \ M(TemporalUnknownCriticalAnnotation, "Unknown annotation key in critical annotation: '{}'") \ M(TemporalZonedDateTimeRoundZeroOrNegativeLengthDay, "Cannot round a ZonedDateTime in a calendar or time zone that has zero or " \ "negative length days") \ diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp index 249229993067..a15716f68224 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp @@ -20,6 +20,7 @@ #include <LibJS/Runtime/Temporal/PlainMonthDay.h> #include <LibJS/Runtime/Temporal/PlainTime.h> #include <LibJS/Runtime/Temporal/PlainYearMonth.h> +#include <LibJS/Runtime/Temporal/TimeZone.h> #include <LibJS/Runtime/Temporal/ZonedDateTime.h> #include <LibJS/Runtime/Value.h> @@ -446,16 +447,27 @@ ThrowCompletionOr<Object*> to_temporal_calendar(VM& vm, Value temporal_calendar_ if (is<ZonedDateTime>(temporal_calendar_like_object)) return &static_cast<ZonedDateTime&>(temporal_calendar_like_object).calendar(); - // c. If ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike. + // c. If temporalCalendarLike has an [[InitializedTemporalTimeZone]] internal slot, throw a RangeError exception. + if (is<TimeZone>(temporal_calendar_like_object)) + return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedTimeZoneObject); + + // d. If ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike. if (!TRY(temporal_calendar_like_object.has_property(vm.names.calendar))) return &temporal_calendar_like_object; - // d. Set temporalCalendarLike to ? Get(temporalCalendarLike, "calendar"). + // e. Set temporalCalendarLike to ? Get(temporalCalendarLike, "calendar"). temporal_calendar_like = TRY(temporal_calendar_like_object.get(vm.names.calendar)); - // e. If Type(temporalCalendarLike) is Object and ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike. - if (temporal_calendar_like.is_object() && !TRY(temporal_calendar_like.as_object().has_property(vm.names.calendar))) - return &temporal_calendar_like.as_object(); + // f. If Type(temporalCalendarLike) is Object, then + if (temporal_calendar_like.is_object()) { + // i. If temporalCalendarLike has an [[InitializedTemporalTimeZone]] internal slot, throw a RangeError exception. + if (is<TimeZone>(temporal_calendar_like.as_object())) + return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedTimeZoneObject); + + // ii. If ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike. + if (!TRY(temporal_calendar_like.as_object().has_property(vm.names.calendar))) + return &temporal_calendar_like.as_object(); + } } // 2. Let identifier be ? ToString(temporalCalendarLike). diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp index b3344e247c3c..9e419fae42b2 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp @@ -13,6 +13,7 @@ #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/IteratorOperations.h> #include <LibJS/Runtime/Temporal/AbstractOperations.h> +#include <LibJS/Runtime/Temporal/Calendar.h> #include <LibJS/Runtime/Temporal/Instant.h> #include <LibJS/Runtime/Temporal/PlainDateTime.h> #include <LibJS/Runtime/Temporal/TimeZone.h> @@ -307,16 +308,27 @@ ThrowCompletionOr<Object*> to_temporal_time_zone(VM& vm, Value temporal_time_zon return &zoned_date_time.time_zone(); } - // c. If ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike. + // c. If temporalTimeZoneLike has an [[InitializedTemporalCalendar]] internal slot, throw a RangeError exception. + if (is<Calendar>(temporal_time_zone_like.as_object())) + return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedCalendarObject); + + // d. If ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike. if (!TRY(temporal_time_zone_like.as_object().has_property(vm.names.timeZone))) return &temporal_time_zone_like.as_object(); - // d. Set temporalTimeZoneLike to ? Get(temporalTimeZoneLike, "timeZone"). + // e. Set temporalTimeZoneLike to ? Get(temporalTimeZoneLike, "timeZone"). temporal_time_zone_like = TRY(temporal_time_zone_like.as_object().get(vm.names.timeZone)); - // e. If Type(temporalTimeZoneLike) is Object and ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike. - if (temporal_time_zone_like.is_object() && !TRY(temporal_time_zone_like.as_object().has_property(vm.names.timeZone))) - return &temporal_time_zone_like.as_object(); + // f. If Type(temporalTimeZoneLike) is Object, then + if (temporal_time_zone_like.is_object()) { + // i. If temporalTimeZoneLike has an [[InitializedTemporalCalendar]] internal slot, throw a RangeError exception. + if (is<Calendar>(temporal_time_zone_like.as_object())) + return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedCalendarObject); + + // ii. If ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike. + if (!TRY(temporal_time_zone_like.as_object().has_property(vm.names.timeZone))) + return &temporal_time_zone_like.as_object(); + } } // 2. Let identifier be ? ToString(temporalTimeZoneLike). diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/Calendar/Calendar.from.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Calendar/Calendar.from.js index af01f7e13dac..5934b2cad828 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/Temporal/Calendar/Calendar.from.js +++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Calendar/Calendar.from.js @@ -43,3 +43,15 @@ describe("normal behavior", () => { expect(madeObservableHasPropertyLookup).toBeFalse(); }); }); + +describe("errors", () => { + test("Calendar from TimeZone", () => { + const timeZone = new Temporal.TimeZone("UTC"); + expect(() => { + Temporal.Calendar.from(timeZone); + }).toThrowWithMessage( + RangeError, + "Got unexpected TimeZone object in conversion to Calendar" + ); + }); +}); diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/TimeZone/TimeZone.from.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/TimeZone/TimeZone.from.js index 5e77c01cd782..f3e8cbb0165d 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/Temporal/TimeZone/TimeZone.from.js +++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/TimeZone/TimeZone.from.js @@ -64,3 +64,15 @@ describe("normal behavior", () => { expect(madeObservableHasPropertyLookup).toBeFalse(); }); }); + +describe("errors", () => { + test("TimeZone from Calendar", () => { + const calendar = new Temporal.Calendar("iso8601"); + expect(() => { + Temporal.TimeZone.from(calendar); + }).toThrowWithMessage( + RangeError, + "Got unexpected Calendar object in conversion to TimeZone" + ); + }); +});
1472f6d9865eec67230405522bc0b44a681440dc
2021-08-08 14:25:36
Daniel Bertalan
ak: Add formatting for infinity and NaN
false
Add formatting for infinity and NaN
ak
diff --git a/AK/Format.cpp b/AK/Format.cpp index 08653293c8d8..a7dc73f4ff28 100644 --- a/AK/Format.cpp +++ b/AK/Format.cpp @@ -19,6 +19,7 @@ # include <Kernel/Process.h> # include <Kernel/Thread.h> #else +# include <math.h> # include <stdio.h> # include <string.h> #endif @@ -344,6 +345,22 @@ void FormatBuilder::put_f64( StringBuilder string_builder; FormatBuilder format_builder { string_builder }; + if (isnan(value) || isinf(value)) [[unlikely]] { + if (value < 0.0) + string_builder.append('-'); + else if (sign_mode == SignMode::Always) + string_builder.append('+'); + else + string_builder.append(' '); + + if (isnan(value)) + string_builder.append(upper_case ? "NAN"sv : "nan"sv); + else + string_builder.append(upper_case ? "INF"sv : "inf"sv); + format_builder.put_string(string_builder.string_view(), align, min_width, NumericLimits<size_t>::max(), fill); + return; + } + bool is_negative = value < 0.0; if (is_negative) value = -value; @@ -394,6 +411,22 @@ void FormatBuilder::put_f80( StringBuilder string_builder; FormatBuilder format_builder { string_builder }; + if (isnan(value) || isinf(value)) [[unlikely]] { + if (value < 0.0l) + string_builder.append('-'); + else if (sign_mode == SignMode::Always) + string_builder.append('+'); + else + string_builder.append(' '); + + if (isnan(value)) + string_builder.append(upper_case ? "NAN"sv : "nan"sv); + else + string_builder.append(upper_case ? "INF"sv : "inf"sv); + format_builder.put_string(string_builder.string_view(), align, min_width, NumericLimits<size_t>::max(), fill); + return; + } + bool is_negative = value < 0.0l; if (is_negative) value = -value;
a3590ca6022fd49e6775e08d64007cfc661cb64d
2019-12-24 04:51:09
Andreas Kling
libgui: Paint GResizeCorner with SystemColor::Window background
false
Paint GResizeCorner with SystemColor::Window background
libgui
diff --git a/Libraries/LibGUI/GResizeCorner.cpp b/Libraries/LibGUI/GResizeCorner.cpp index da401976a75c..7b01de78de4c 100644 --- a/Libraries/LibGUI/GResizeCorner.cpp +++ b/Libraries/LibGUI/GResizeCorner.cpp @@ -20,7 +20,7 @@ void GResizeCorner::paint_event(GPaintEvent& event) { GPainter painter(*this); painter.add_clip_rect(event.rect()); - painter.fill_rect(rect(), background_color()); + painter.fill_rect(rect(), SystemColor::Window); painter.blit({ 0, 0 }, *m_bitmap, m_bitmap->rect()); GWidget::paint_event(event); }
102b8d717feb67b21ae958762d40f9712be46ddf
2023-06-08 13:35:56
Andreas Kling
libweb: Set `flex-basis` to `0%` when omitted from `flex` shorthand
false
Set `flex-basis` to `0%` when omitted from `flex` shorthand
libweb
diff --git a/Tests/LibWeb/Layout/expected/flex/flex-shorthand-flex-basis-zero-percent.txt b/Tests/LibWeb/Layout/expected/flex/flex-shorthand-flex-basis-zero-percent.txt new file mode 100644 index 000000000000..a225a4bfde72 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/flex/flex-shorthand-flex-basis-zero-percent.txt @@ -0,0 +1,29 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (1,1) content-size 798x126 [BFC] children: not-inline + BlockContainer <body> at (10,10) content-size 780x108 children: not-inline + Box <div.flex> at (11,11) content-size 500x52 flex-container(row) [FFC] children: not-inline + BlockContainer <(anonymous)> at (11,11) content-size 36.84375x52 flex-item [BFC] children: inline + line 0 width: 36.84375, height: 17.46875, bottom: 17.46875, baseline: 13.53125 + frag 0 from TextNode start: 0, length: 5, rect: [11,11 36.84375x17.46875] + "hello" + TextNode <#text> + Box <div.item.one> at (48.84375,12) content-size 461.15625x50 flex-container(row) flex-item [FFC] children: not-inline + BlockContainer <(anonymous)> at (48.84375,12) content-size 55.359375x50 flex-item [BFC] children: inline + line 0 width: 55.359375, height: 17.46875, bottom: 17.46875, baseline: 13.53125 + frag 0 from TextNode start: 0, length: 7, rect: [48.84375,12 55.359375x17.46875] + "friends" + TextNode <#text> + BlockContainer <(anonymous)> at (10,64) content-size 780x0 children: inline + TextNode <#text> + Box <div.flex> at (11,65) content-size 500x52 flex-container(row) [FFC] children: not-inline + BlockContainer <(anonymous)> at (11,65) content-size 36.84375x52 flex-item [BFC] children: inline + line 0 width: 36.84375, height: 17.46875, bottom: 17.46875, baseline: 13.53125 + frag 0 from TextNode start: 0, length: 5, rect: [11,65 36.84375x17.46875] + "hello" + TextNode <#text> + Box <div.item.two> at (48.84375,66) content-size 461.15625x50 flex-container(row) flex-item [FFC] children: not-inline + BlockContainer <(anonymous)> at (48.84375,66) content-size 55.359375x50 flex-item [BFC] children: inline + line 0 width: 55.359375, height: 17.46875, bottom: 17.46875, baseline: 13.53125 + frag 0 from TextNode start: 0, length: 7, rect: [48.84375,66 55.359375x17.46875] + "friends" + TextNode <#text> diff --git a/Tests/LibWeb/Layout/input/flex/flex-shorthand-flex-basis-zero-percent.html b/Tests/LibWeb/Layout/input/flex/flex-shorthand-flex-basis-zero-percent.html new file mode 100644 index 000000000000..c2743c97ffe6 --- /dev/null +++ b/Tests/LibWeb/Layout/input/flex/flex-shorthand-flex-basis-zero-percent.html @@ -0,0 +1,24 @@ +<!doctype html><style> + * { border: 1px solid black; } + html { background: white; } + .flex { + display: flex; + flex-wrap: wrap; + background: pink; + width: 500px; + } + .item { + display: flex; + background: orange; + width: 100%; + height: 50px; + } + .one { + flex: 1; + } + .two { + flex: 1 1; + } +</style> +<div class="flex">hello<div class="item one">friends</div></div> +<div class="flex">hello<div class="item two">friends</div></div> \ No newline at end of file diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index ee59ee62b81f..6f9fc622d426 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -5669,8 +5669,7 @@ ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_value(Vector<ComponentValue> cons case PropertyID::FlexGrow: { // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%. // https://github.com/w3c/csswg-drafts/issues/5742 - // (flex-basis takes `<length>`, not `<number>`, so the 0 is a Length.) - auto flex_basis = TRY(LengthStyleValue::create(Length::make_px(0))); + auto flex_basis = TRY(PercentageStyleValue::create(Percentage(0))); auto one = TRY(NumberStyleValue::create(1)); return FlexStyleValue::create(*value, one, flex_basis); } @@ -5732,8 +5731,11 @@ ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_value(Vector<ComponentValue> cons flex_grow = TRY(property_initial_value(m_context.realm(), PropertyID::FlexGrow)); if (!flex_shrink) flex_shrink = TRY(property_initial_value(m_context.realm(), PropertyID::FlexShrink)); - if (!flex_basis) - flex_basis = TRY(property_initial_value(m_context.realm(), PropertyID::FlexBasis)); + if (!flex_basis) { + // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%. + // https://github.com/w3c/csswg-drafts/issues/5742 + flex_basis = TRY(PercentageStyleValue::create(Percentage(0))); + } return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull()); }
2c78fa066f9b914d4be494db142675a88007a1fe
2021-07-10 00:44:08
Linus Groh
ports: Remove Python setlocale patch that's no longer needed
false
Remove Python setlocale patch that's no longer needed
ports
diff --git a/Ports/python3/patches/ReadMe.md b/Ports/python3/patches/ReadMe.md index c5ab7d039c44..9bef035ff3e6 100644 --- a/Ports/python3/patches/ReadMe.md +++ b/Ports/python3/patches/ReadMe.md @@ -12,10 +12,6 @@ Enforce UTF-8 as encoding by defining `_Py_FORCE_UTF8_LOCALE`. As usual, make the `configure` script recognize Serenity. Also set `MACHDEP` (which is used for `sys.platform`) to a version-less `serenityos`, even when not cross-compiling. -## `remove-setlocale-from-preconfig.patch` - -Our stub implementation of `setlocale()` always returns `nullptr`, which the interpreter considers critical enough to exit right away. - ## `webbrowser.patch` Register the SerenityOS Browser in the [`webbrowser`](https://docs.python.org/3/library/webbrowser.html) module. diff --git a/Ports/python3/patches/remove-setlocale-from-preconfig.patch b/Ports/python3/patches/remove-setlocale-from-preconfig.patch deleted file mode 100644 index 5ae40aa83684..000000000000 --- a/Ports/python3/patches/remove-setlocale-from-preconfig.patch +++ /dev/null @@ -1,30 +0,0 @@ ---- Python-3.9.6/Python/preconfig.c 2021-02-21 20:22:44.076023521 +0100 -+++ Python-3.9.6/Python/preconfig.c 2021-02-21 20:36:10.936698893 +0100 -@@ -790,16 +790,6 @@ - - preconfig_get_global_vars(config); - -- /* Copy LC_CTYPE locale, since it's modified later */ -- const char *loc = setlocale(LC_CTYPE, NULL); -- if (loc == NULL) { -- return _PyStatus_ERR("failed to LC_CTYPE locale"); -- } -- char *init_ctype_locale = _PyMem_RawStrdup(loc); -- if (init_ctype_locale == NULL) { -- return _PyStatus_NO_MEMORY(); -- } -- - /* Save the config to be able to restore it if encodings change */ - PyPreConfig save_config; - -@@ -899,10 +889,6 @@ - status = _PyStatus_OK(); - - done: -- if (init_ctype_locale != NULL) { -- setlocale(LC_CTYPE, init_ctype_locale); -- PyMem_RawFree(init_ctype_locale); -- } - Py_UTF8Mode = init_utf8_mode ; - #ifdef MS_WINDOWS - Py_LegacyWindowsFSEncodingFlag = init_legacy_encoding;
a9fba2fb9106f095f26f29509b025dc1fa25a8ac
2020-05-24 03:42:00
Andreas Kling
libweb: Add "name" to DocumentType nodes
false
Add "name" to DocumentType nodes
libweb
diff --git a/Libraries/LibWeb/DOM/DocumentType.h b/Libraries/LibWeb/DOM/DocumentType.h index 0df0f634d4e1..7a04df4d866b 100644 --- a/Libraries/LibWeb/DOM/DocumentType.h +++ b/Libraries/LibWeb/DOM/DocumentType.h @@ -37,6 +37,12 @@ class DocumentType final : public Node { virtual ~DocumentType() override; virtual FlyString tag_name() const override { return "#doctype"; } + + const String& name() const { return m_name; } + void set_name(const String& name) { m_name = name; } + +private: + String m_name; }; template<>
4e851145baca6cabb02c13c36e19c8dd3ef61003
2022-01-05 03:07:21
Michel Hermier
libcrypto: Make `MultiHashDigestVariant` getters `const` and `nodiscard`
false
Make `MultiHashDigestVariant` getters `const` and `nodiscard`
libcrypto
diff --git a/Userland/Libraries/LibCrypto/Hash/HashManager.h b/Userland/Libraries/LibCrypto/Hash/HashManager.h index 522565a8b15a..b161ae87d6ac 100644 --- a/Userland/Libraries/LibCrypto/Hash/HashManager.h +++ b/Userland/Libraries/LibCrypto/Hash/HashManager.h @@ -59,14 +59,14 @@ struct MultiHashDigestVariant { { } - const u8* immutable_data() const + [[nodiscard]] const u8* immutable_data() const { return m_digest.visit( [&](const Empty&) -> const u8* { VERIFY_NOT_REACHED(); }, [&](const auto& value) { return value.immutable_data(); }); } - size_t data_length() + [[nodiscard]] size_t data_length() const { return m_digest.visit( [&](const Empty&) -> size_t { VERIFY_NOT_REACHED(); },
708543c3d64c28d3c8d02d9b74d0921bf5f6c588
2019-10-23 01:48:46
Andreas Kling
hackstudio: Add a simple "Run" action
false
Add a simple "Run" action
hackstudio
diff --git a/Base/home/anon/little/Makefile b/Base/home/anon/little/Makefile index a41e4d0b96ba..137ef0065e66 100644 --- a/Base/home/anon/little/Makefile +++ b/Base/home/anon/little/Makefile @@ -11,3 +11,6 @@ $(PROGRAM): $(OBJS) clean: rm $(OBJS) $(PROGRAM) + +run: + ./$(PROGRAM) diff --git a/DevTools/HackStudio/main.cpp b/DevTools/HackStudio/main.cpp index 7548c2b09059..d70a2e8ab5ef 100644 --- a/DevTools/HackStudio/main.cpp +++ b/DevTools/HackStudio/main.cpp @@ -22,6 +22,7 @@ String g_currently_open_file; static void build(TerminalWrapper&); +static void run(TerminalWrapper&); int main(int argc, char** argv) { @@ -103,6 +104,9 @@ int main(int argc, char** argv) build_menu->add_action(GAction::create("Build", { Mod_Ctrl, Key_B }, [&](auto&) { build(terminal_wrapper); })); + build_menu->add_action(GAction::create("Run", { Mod_Ctrl, Key_R }, [&](auto&) { + run(terminal_wrapper); + })); menubar->add_menu(move(build_menu)); auto small_icon = GraphicsBitmap::load_from_file("/res/icons/16x16/app-hack-studio.png"); @@ -125,3 +129,8 @@ void build(TerminalWrapper& wrapper) { wrapper.run_command("make"); } + +void run(TerminalWrapper& wrapper) +{ + wrapper.run_command("make run"); +}
0e61d039c9cdb36faa3d4117f1a9863c1b615f69
2024-01-28 06:30:33
Ali Mohammad Pur
ak: Use IsSame<FlatPtr, T> instead of __LP64__ to guess FlatPtr's type
false
Use IsSame<FlatPtr, T> instead of __LP64__ to guess FlatPtr's type
ak
diff --git a/AK/JsonValue.h b/AK/JsonValue.h index ae05aceba8f2..b8e7419fe951 100644 --- a/AK/JsonValue.h +++ b/AK/JsonValue.h @@ -104,11 +104,17 @@ class JsonValue { Optional<FlatPtr> get_addr() const { -#ifdef __LP64__ - return get_u64(); -#else - return get_u32(); -#endif + // Note: This makes the lambda dependent on the template parameter, which is necessary + // for the `if constexpr` to not evaluate both branches. + auto fn = [&]<typename T>() -> Optional<T> { + if constexpr (IsSame<T, u64>) { + return get_u64(); + } else { + return get_u32(); + } + }; + + return fn.operator()<FlatPtr>(); } Optional<bool> get_bool() const
b0f546cd60671d2e42c9836824aba3ae1b33b0f2
2022-06-18 22:58:43
kleines Filmröllchen
meta: Run PNG size checks on CI
false
Run PNG size checks on CI
meta
diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 6673f7ea7c29..59eecdd60c50 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -46,7 +46,7 @@ jobs: wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - sudo add-apt-repository 'deb http://apt.llvm.org/jammy/ llvm-toolchain-jammy-14 main' sudo apt-get update - sudo apt-get install -y clang-format-14 ccache e2fsprogs gcc-11 g++-11 libstdc++-11-dev libmpfr-dev libmpc-dev ninja-build qemu-utils qemu-system-i386 unzip + sudo apt-get install -y clang-format-14 ccache e2fsprogs gcc-11 g++-11 libstdc++-11-dev libmpfr-dev libmpc-dev ninja-build optipng qemu-utils qemu-system-i386 unzip - name: Install JS dependencies run: sudo npm install -g [email protected] - name: Install Python dependencies
8cfd445c23dce63d0a2510bd75bdd9ee8a76197e
2023-01-25 01:43:30
Karol Kosek
kernel: Allow to remove files from sticky directory if user owns it
false
Allow to remove files from sticky directory if user owns it
kernel
diff --git a/Kernel/FileSystem/VirtualFileSystem.cpp b/Kernel/FileSystem/VirtualFileSystem.cpp index 6409c43896ee..47edde7dbf56 100644 --- a/Kernel/FileSystem/VirtualFileSystem.cpp +++ b/Kernel/FileSystem/VirtualFileSystem.cpp @@ -645,7 +645,7 @@ ErrorOr<void> VirtualFileSystem::rename(Credentials const& credentials, Custody& return EACCES; if (old_parent_inode.metadata().is_sticky()) { - if (!credentials.is_superuser() && old_inode.metadata().uid != credentials.euid()) + if (!credentials.is_superuser() && old_parent_inode.metadata().uid != credentials.euid() && old_inode.metadata().uid != credentials.euid()) return EACCES; } @@ -807,7 +807,7 @@ ErrorOr<void> VirtualFileSystem::unlink(Credentials const& credentials, StringVi return EACCES; if (parent_inode.metadata().is_sticky()) { - if (!credentials.is_superuser() && inode.metadata().uid != credentials.euid()) + if (!credentials.is_superuser() && parent_inode.metadata().uid != credentials.euid() && inode.metadata().uid != credentials.euid()) return EACCES; }
066133d97b30b41408c85a4be20123b76fd033b3
2023-04-13 16:34:44
Linus Groh
libjs: Add spec comments to StringConstructor
false
Add spec comments to StringConstructor
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/StringConstructor.cpp b/Userland/Libraries/LibJS/Runtime/StringConstructor.cpp index 0b0bc2591c58..5b97fe46c521 100644 --- a/Userland/Libraries/LibJS/Runtime/StringConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringConstructor.cpp @@ -44,11 +44,20 @@ ThrowCompletionOr<void> StringConstructor::initialize(Realm& realm) ThrowCompletionOr<Value> StringConstructor::call() { auto& vm = this->vm(); + auto value = vm.argument(0); + + // 1. If value is not present, let s be the empty String. if (!vm.argument_count()) return PrimitiveString::create(vm, String {}); - if (vm.argument(0).is_symbol()) - return PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, vm.argument(0).as_symbol().descriptive_string())); - return TRY(vm.argument(0).to_primitive_string(vm)); + + // 2. Else, + // a. If NewTarget is undefined and value is a Symbol, return SymbolDescriptiveString(value). + if (value.is_symbol()) + return PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, value.as_symbol().descriptive_string())); + + // b. Let s be ? ToString(value). + // 3. If NewTarget is undefined, return s. + return TRY(value.to_primitive_string(vm)); } // 22.1.1.1 String ( value ), https://tc39.es/ecma262/#sec-string-constructor-string-value @@ -56,79 +65,137 @@ ThrowCompletionOr<NonnullGCPtr<Object>> StringConstructor::construct(FunctionObj { auto& vm = this->vm(); auto& realm = *vm.current_realm(); + auto value = vm.argument(0); PrimitiveString* primitive_string; - if (!vm.argument_count()) + + // 1. If value is not present, let s be the empty String. + if (!vm.argument_count()) { primitive_string = PrimitiveString::create(vm, String {}); - else - primitive_string = TRY(vm.argument(0).to_primitive_string(vm)); + } + // 2. Else, + else { + // b. Let s be ? ToString(value). + primitive_string = TRY(value.to_primitive_string(vm)); + } + + // 4. Return StringCreate(s, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%")). auto* prototype = TRY(get_prototype_from_constructor(vm, new_target, &Intrinsics::string_prototype)); return MUST_OR_THROW_OOM(StringObject::create(realm, *primitive_string, *prototype)); } -// 22.1.2.4 String.raw ( template, ...substitutions ), https://tc39.es/ecma262/#sec-string.raw -JS_DEFINE_NATIVE_FUNCTION(StringConstructor::raw) -{ - auto* cooked = TRY(vm.argument(0).to_object(vm)); - auto raw_value = TRY(cooked->get(vm.names.raw)); - auto* raw = TRY(raw_value.to_object(vm)); - auto literal_segments = TRY(length_of_array_like(vm, *raw)); - - if (literal_segments == 0) - return PrimitiveString::create(vm, String {}); - - auto const number_of_substituions = vm.argument_count() - 1; - - StringBuilder builder; - for (size_t i = 0; i < literal_segments; ++i) { - auto next_key = DeprecatedString::number(i); - auto next_segment_value = TRY(raw->get(next_key)); - auto next_segment = TRY(next_segment_value.to_deprecated_string(vm)); - - builder.append(next_segment); - - if (i + 1 == literal_segments) - break; - - if (i < number_of_substituions) { - auto next = vm.argument(i + 1); - auto next_sub = TRY(next.to_deprecated_string(vm)); - builder.append(next_sub); - } - } - return PrimitiveString::create(vm, builder.to_deprecated_string()); -} - // 22.1.2.1 String.fromCharCode ( ...codeUnits ), https://tc39.es/ecma262/#sec-string.fromcharcode JS_DEFINE_NATIVE_FUNCTION(StringConstructor::from_char_code) { + // 1. Let result be the empty String. Utf16Data string; string.ensure_capacity(vm.argument_count()); - for (size_t i = 0; i < vm.argument_count(); ++i) - string.append(TRY(vm.argument(i).to_u16(vm))); + // 2. For each element next of codeUnits, do + for (size_t i = 0; i < vm.argument_count(); ++i) { + // a. Let nextCU be the code unit whose numeric value is ℝ(? ToUint16(next)). + auto next_code_unit = TRY(vm.argument(i).to_u16(vm)); + // b. Set result to the string-concatenation of result and nextCU. + string.append(next_code_unit); + } + + // 3. Return result. return PrimitiveString::create(vm, TRY(Utf16String::create(vm, move(string)))); } // 22.1.2.2 String.fromCodePoint ( ...codePoints ), https://tc39.es/ecma262/#sec-string.fromcodepoint JS_DEFINE_NATIVE_FUNCTION(StringConstructor::from_code_point) { + // 1. Let result be the empty String. Utf16Data string; - string.ensure_capacity(vm.argument_count()); // This will be an under-estimate if any code point is > 0xffff. + // This will be an under-estimate if any code point is > 0xffff. + string.ensure_capacity(vm.argument_count()); + // 2. For each element next of codePoints, do for (size_t i = 0; i < vm.argument_count(); ++i) { + // a. Let nextCP be ? ToNumber(next). auto next_code_point = TRY(vm.argument(i).to_number(vm)); + + // b. If IsIntegralNumber(nextCP) is false, throw a RangeError exception. if (!next_code_point.is_integral_number()) return vm.throw_completion<RangeError>(ErrorType::InvalidCodePoint, TRY_OR_THROW_OOM(vm, next_code_point.to_string_without_side_effects())); - auto code_point = TRY(next_code_point.to_i32(vm)); + + auto code_point = MUST(next_code_point.to_i32(vm)); + + // c. If ℝ(nextCP) < 0 or ℝ(nextCP) > 0x10FFFF, throw a RangeError exception. if (code_point < 0 || code_point > 0x10FFFF) return vm.throw_completion<RangeError>(ErrorType::InvalidCodePoint, TRY_OR_THROW_OOM(vm, next_code_point.to_string_without_side_effects())); + // d. Set result to the string-concatenation of result and UTF16EncodeCodePoint(ℝ(nextCP)). TRY_OR_THROW_OOM(vm, code_point_to_utf16(string, static_cast<u32>(code_point))); } + // 3. Assert: If codePoints is empty, then result is the empty String. + if (!vm.argument_count()) + VERIFY(string.is_empty()); + + // 4. Return result. return PrimitiveString::create(vm, TRY(Utf16String::create(vm, move(string)))); } +// 22.1.2.4 String.raw ( template, ...substitutions ), https://tc39.es/ecma262/#sec-string.raw +JS_DEFINE_NATIVE_FUNCTION(StringConstructor::raw) +{ + auto template_ = vm.argument(0); + + // 1. Let substitutionCount be the number of elements in substitutions. + auto substitution_count = vm.argument_count() > 0 ? vm.argument_count() - 1 : 0; + + // 2. Let cooked be ? ToObject(template). + auto* cooked = TRY(template_.to_object(vm)); + + // 3. Let literals be ? ToObject(? Get(cooked, "raw")). + auto* literals = TRY(TRY(cooked->get(vm.names.raw)).to_object(vm)); + + // 4. Let literalCount be ? LengthOfArrayLike(literals). + auto literal_count = TRY(length_of_array_like(vm, *literals)); + + // 5. If literalCount ≤ 0, return the empty String. + if (literal_count == 0) + return PrimitiveString::create(vm, String {}); + + // 6. Let R be the empty String. + StringBuilder builder; + + // 7. Let nextIndex be 0. + // 8. Repeat, + for (size_t i = 0; i < literal_count; ++i) { + auto next_key = DeprecatedString::number(i); + + // a. Let nextLiteralVal be ? Get(literals, ! ToString(𝔽(nextIndex))). + auto next_literal_value = TRY(literals->get(next_key)); + + // b. Let nextLiteral be ? ToString(nextLiteralVal). + auto next_literal = TRY(next_literal_value.to_deprecated_string(vm)); + + // c. Set R to the string-concatenation of R and nextLiteral. + builder.append(next_literal); + + // d. If nextIndex + 1 = literalCount, return R. + if (i + 1 == literal_count) + break; + + // e. If nextIndex < substitutionCount, then + if (i < substitution_count) { + // i. Let nextSubVal be substitutions[nextIndex]. + auto next_substitution_value = vm.argument(i + 1); + + // ii. Let nextSub be ? ToString(nextSubVal). + auto next_substitution = TRY(next_substitution_value.to_deprecated_string(vm)); + + // iii. Set R to the string-concatenation of R and nextSub. + builder.append(next_substitution); + } + + // f. Set nextIndex to nextIndex + 1. + } + return PrimitiveString::create(vm, builder.to_deprecated_string()); +} + }
21c59efbb9531fcc8f1fb352a74e1daf96060687
2021-07-31 03:48:11
Sam Atkins
libweb: Treat CSS calc() values as "builtin_or_dynamic"
false
Treat CSS calc() values as "builtin_or_dynamic"
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index 5972f4335fc0..c1acefa74656 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -1386,7 +1386,7 @@ Optional<float> Parser::try_parse_float(StringView string) return is_negative ? -value : value; } -RefPtr<StyleValue> Parser::parse_keyword_or_custom_value(ParsingContext const&, StyleComponentValueRule const& component_value) +RefPtr<StyleValue> Parser::parse_builtin_or_dynamic_value(ParsingContext const& context, StyleComponentValueRule const& component_value) { if (component_value.is(Token::Type::Ident)) { auto ident = component_value.token().ident(); @@ -1804,8 +1804,8 @@ RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, Proper } } - if (auto keyword_or_custom = parse_keyword_or_custom_value(context, component_value)) - return keyword_or_custom; + if (auto builtin_or_dynamic = parse_builtin_or_dynamic_value(context, component_value)) + return builtin_or_dynamic; if (auto length = parse_length_value(context, component_value)) return length; diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h index fa7d47f6b2d2..183ed8d37afd 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.h +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.h @@ -169,7 +169,7 @@ class Parser { static Optional<Length> parse_length(ParsingContext const&, StyleComponentValueRule const&); static Optional<URL> parse_url_function(ParsingContext const&, StyleComponentValueRule const&); - static RefPtr<StyleValue> parse_keyword_or_custom_value(ParsingContext const&, StyleComponentValueRule const&); + static RefPtr<StyleValue> parse_builtin_or_dynamic_value(ParsingContext const&, StyleComponentValueRule const&); static RefPtr<StyleValue> parse_length_value(ParsingContext const&, StyleComponentValueRule const&); static RefPtr<StyleValue> parse_numeric_value(ParsingContext const&, StyleComponentValueRule const&); static RefPtr<StyleValue> parse_identifier_value(ParsingContext const&, StyleComponentValueRule const&); diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h index 5501772d5949..52fe6fa632c7 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleValue.h +++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h @@ -241,20 +241,13 @@ class StyleValue : public RefCounted<StyleValue> { bool is_length() const { return type() == Type::Length; } bool is_custom_property() const { return type() == Type::CustomProperty; } bool is_numeric() const { return type() == Type::Numeric; } - bool is_value_list() const - { - return type() == Type::ValueList; - } - - bool is_builtin_or_dynamic() const - { - return is_inherit() || is_initial() || is_custom_property(); - } + bool is_value_list() const { return type() == Type::ValueList; } bool is_box_shadow() const { return type() == Type::BoxShadow; } + bool is_calculated() const { return type() == Type::Calculated; } - bool is_calculated() const + bool is_builtin_or_dynamic() const { - return type() == Type::Calculated; + return is_inherit() || is_initial() || is_custom_property() || is_calculated(); } virtual String to_string() const = 0;
767b23c4aa599ebefe0e344608e0c255cc32e45a
2022-09-29 18:32:17
implicitfield
libc: Allow detection of supported locales through setlocale
false
Allow detection of supported locales through setlocale
libc
diff --git a/Userland/Libraries/LibC/locale.cpp b/Userland/Libraries/LibC/locale.cpp index 06cbcdb6ce73..36ff8010d422 100644 --- a/Userland/Libraries/LibC/locale.cpp +++ b/Userland/Libraries/LibC/locale.cpp @@ -45,11 +45,19 @@ static struct lconv default_locale = { default_empty_value }; -char* setlocale(int, char const*) +char* setlocale(int, char const* locale) { - static char locale[2]; - memcpy(locale, "C", 2); - return locale; + static char c_locale_string[2]; + memcpy(c_locale_string, "C", 2); + + // If we get a null pointer, return the current locale as per POSIX spec. + if (locale == nullptr) + return c_locale_string; + + if (strcmp(locale, "POSIX") == 0 || strcmp(locale, "C") == 0 || strcmp(locale, "") == 0) + return c_locale_string; + + return nullptr; } struct lconv* localeconv()
aae296ef08a8c03f82ec5a9baaa89633525221b6
2020-08-13 00:11:13
Andreas Kling
filemanager: Use FileIconProvider in the properties dialog
false
Use FileIconProvider in the properties dialog
filemanager
diff --git a/Applications/FileManager/PropertiesDialog.cpp b/Applications/FileManager/PropertiesDialog.cpp index f4aa7f9f047e..c972316e513c 100644 --- a/Applications/FileManager/PropertiesDialog.cpp +++ b/Applications/FileManager/PropertiesDialog.cpp @@ -29,6 +29,7 @@ #include <AK/StringBuilder.h> #include <LibGUI/BoxLayout.h> #include <LibGUI/CheckBox.h> +#include <LibGUI/FileIconProvider.h> #include <LibGUI/FilePicker.h> #include <LibGUI/MessageBox.h> #include <LibGUI/TabWidget.h> @@ -39,9 +40,8 @@ #include <string.h> #include <unistd.h> -PropertiesDialog::PropertiesDialog(GUI::FileSystemModel& model, String path, bool disable_rename, Window* parent_window) +PropertiesDialog::PropertiesDialog(const String& path, bool disable_rename, Window* parent_window) : Dialog(parent_window) - , m_model(model) { auto lexical_path = LexicalPath(path); ASSERT(lexical_path.is_valid()); @@ -170,7 +170,7 @@ PropertiesDialog::~PropertiesDialog() { } void PropertiesDialog::update() { - auto bitmap = m_model.icon_for_file(m_mode, m_name).bitmap_for_size(32); + auto bitmap = GUI::FileIconProvider::icon_for_path(m_name, m_mode).bitmap_for_size(32); m_icon->set_bitmap(bitmap); set_title(String::format("%s - Properties", m_name.characters())); } @@ -187,7 +187,7 @@ void PropertiesDialog::permission_changed(mode_t mask, bool set) m_apply_button->set_enabled(m_name_dirty || m_permissions_dirty); } -String PropertiesDialog::make_full_path(String name) +String PropertiesDialog::make_full_path(const String& name) { return String::format("%s/%s", m_parent_path.characters(), name.characters()); } diff --git a/Applications/FileManager/PropertiesDialog.h b/Applications/FileManager/PropertiesDialog.h index 424dba58a894..0aefc1447f1a 100644 --- a/Applications/FileManager/PropertiesDialog.h +++ b/Applications/FileManager/PropertiesDialog.h @@ -40,7 +40,7 @@ class PropertiesDialog final : public GUI::Dialog { virtual ~PropertiesDialog() override; private: - PropertiesDialog(GUI::FileSystemModel&, String, bool disable_rename, Window* parent = nullptr); + PropertiesDialog(const String& path, bool disable_rename, Window* parent = nullptr); struct PropertyValuePair { String property; @@ -82,17 +82,16 @@ class PropertiesDialog final : public GUI::Dialog { void permission_changed(mode_t mask, bool set); bool apply_changes(); void update(); - String make_full_path(String name); + String make_full_path(const String& name); - GUI::FileSystemModel& m_model; RefPtr<GUI::Button> m_apply_button; RefPtr<GUI::TextBox> m_name_box; RefPtr<GUI::ImageWidget> m_icon; String m_name; String m_parent_path; String m_path; - mode_t m_mode; - mode_t m_old_mode; + mode_t m_mode { 0 }; + mode_t m_old_mode { 0 }; bool m_permissions_dirty { false }; bool m_name_dirty { false }; }; diff --git a/Applications/FileManager/main.cpp b/Applications/FileManager/main.cpp index 6920647040e4..0138c6be9a74 100644 --- a/Applications/FileManager/main.cpp +++ b/Applications/FileManager/main.cpp @@ -480,7 +480,6 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio auto properties_action = GUI::Action::create( "Properties...", { Mod_Alt, Key_Return }, Gfx::Bitmap::load_from_file("/res/icons/16x16/properties.png"), [&](const GUI::Action& action) { - auto& model = directory_view.model(); String container_dir_path; String path; Vector<String> selected; @@ -496,9 +495,9 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio RefPtr<PropertiesDialog> properties; if (selected.is_empty()) { - properties = window->add<PropertiesDialog>(model, path, true); + properties = window->add<PropertiesDialog>(path, true); } else { - properties = window->add<PropertiesDialog>(model, selected.first(), access(container_dir_path.characters(), W_OK) != 0); + properties = window->add<PropertiesDialog>(selected.first(), access(container_dir_path.characters(), W_OK) != 0); } properties->exec();
fb443b3fb45d26d5275600a3eda7f4ea4abb82da
2021-10-04 00:44:03
Linus Groh
libjs: Convert create_data_property() to ThrowCompletionOr
false
Convert create_data_property() to ThrowCompletionOr
libjs
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp index 22bfe2e36e9a..c6aa0d6a6c26 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/WrapperGenerator.cpp @@ -2880,7 +2880,7 @@ void @prototype_class@::initialize(JS::GlobalObject& global_object) if (attribute.extended_attributes.contains("Unscopable")) { attribute_generator.append(R"~~~( - unscopable_object->create_data_property("@attribute.name@", JS::Value(true)); + MUST(unscopable_object->create_data_property("@attribute.name@", JS::Value(true))); )~~~"); } @@ -2911,7 +2911,7 @@ void @prototype_class@::initialize(JS::GlobalObject& global_object) if (function.extended_attributes.contains("Unscopable")) { function_generator.append(R"~~~( - unscopable_object->create_data_property("@function.name@", JS::Value(true)); + MUST(unscopable_object->create_data_property("@function.name@", JS::Value(true))); )~~~"); } diff --git a/Userland/Libraries/LibJS/Runtime/JSONObject.cpp b/Userland/Libraries/LibJS/Runtime/JSONObject.cpp index 41e26403b682..7473125bdcad 100644 --- a/Userland/Libraries/LibJS/Runtime/JSONObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/JSONObject.cpp @@ -468,13 +468,10 @@ Value JSONObject::internalize_json_property(GlobalObject& global_object, Object* auto element = internalize_json_property(global_object, &value_object, key, reviver); if (auto* exception = vm.exception()) return throw_completion(exception->value()); - if (element.is_undefined()) { + if (element.is_undefined()) TRY(value_object.internal_delete(key)); - } else { - value_object.create_data_property(key, element); - if (auto* exception = vm.exception()) - return throw_completion(exception->value()); - } + else + TRY(value_object.create_data_property(key, element)); return {}; }; diff --git a/Userland/Libraries/LibJS/Runtime/Object.cpp b/Userland/Libraries/LibJS/Runtime/Object.cpp index f269026aec0f..3b95ee41044e 100644 --- a/Userland/Libraries/LibJS/Runtime/Object.cpp +++ b/Userland/Libraries/LibJS/Runtime/Object.cpp @@ -117,7 +117,7 @@ ThrowCompletionOr<bool> Object::set(PropertyName const& property_name, Value val } // 7.3.5 CreateDataProperty ( O, P, V ), https://tc39.es/ecma262/#sec-createdataproperty -bool Object::create_data_property(PropertyName const& property_name, Value value) +ThrowCompletionOr<bool> Object::create_data_property(PropertyName const& property_name, Value value) { // 1. Assert: Type(O) is Object. @@ -133,7 +133,7 @@ bool Object::create_data_property(PropertyName const& property_name, Value value }; // 4. Return ? O.[[DefineOwnProperty]](P, newDesc). - return TRY_OR_DISCARD(internal_define_own_property(property_name, new_descriptor)); + return internal_define_own_property(property_name, new_descriptor); } // 7.3.6 CreateMethodProperty ( O, P, V ), https://tc39.es/ecma262/#sec-createmethodproperty @@ -170,9 +170,7 @@ bool Object::create_data_property_or_throw(PropertyName const& property_name, Va VERIFY(property_name.is_valid()); // 3. Let success be ? CreateDataProperty(O, P, V). - auto success = create_data_property(property_name, value); - if (vm.exception()) - return {}; + auto success = TRY_OR_DISCARD(create_data_property(property_name, value)); // 4. If success is false, throw a TypeError exception. if (!success) { @@ -779,7 +777,7 @@ bool Object::ordinary_set_with_own_descriptor(PropertyName const& property_name, VERIFY(!receiver.as_object().storage_has(property_name)); // ii. Return ? CreateDataProperty(Receiver, P, V). - return receiver.as_object().create_data_property(property_name, value); + return TRY_OR_DISCARD(receiver.as_object().create_data_property(property_name, value)); } } diff --git a/Userland/Libraries/LibJS/Runtime/Object.h b/Userland/Libraries/LibJS/Runtime/Object.h index 345eafefc48c..68a4df79a57d 100644 --- a/Userland/Libraries/LibJS/Runtime/Object.h +++ b/Userland/Libraries/LibJS/Runtime/Object.h @@ -77,7 +77,7 @@ class Object : public Cell { ThrowCompletionOr<Value> get(PropertyName const&) const; ThrowCompletionOr<bool> set(PropertyName const&, Value, ShouldThrowExceptions); - bool create_data_property(PropertyName const&, Value); + ThrowCompletionOr<bool> create_data_property(PropertyName const&, Value); bool create_method_property(PropertyName const&, Value); bool create_data_property_or_throw(PropertyName const&, Value); bool create_non_enumerable_data_property_or_throw(PropertyName const&, Value); diff --git a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp index fe4aaae8db49..9e774befc30b 100644 --- a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp @@ -144,22 +144,16 @@ static Value make_indices_array(GlobalObject& global_object, Utf16View const& st if (match_indices.has_value()) match_indices_array = get_match_indices_array(global_object, string, *match_indices); - array->create_data_property(i, match_indices_array); - if (vm.exception()) - return {}; + TRY_OR_DISCARD(array->create_data_property(i, match_indices_array)); } for (auto const& entry : group_names) { auto match_indices_array = get_match_indices_array(global_object, string, entry.value); - groups.as_object().create_data_property(entry.key, match_indices_array); - if (vm.exception()) - return {}; + TRY_OR_DISCARD(groups.as_object().create_data_property(entry.key, match_indices_array)); } - array->create_data_property(vm.names.groups, groups); - if (vm.exception()) - return {}; + TRY_OR_DISCARD(array->create_data_property(vm.names.groups, groups)); return array; } @@ -257,9 +251,7 @@ static Value regexp_builtin_exec(GlobalObject& global_object, RegExpObject& rege if (has_indices) { auto indices_array = make_indices_array(global_object, string_view, indices, group_names, has_groups); - array->create_data_property(vm.names.indices, indices_array); - if (vm.exception()) - return {}; + TRY_OR_DISCARD(array->create_data_property(vm.names.indices, indices_array)); } array->create_data_property_or_throw(vm.names.index, Value(match_index));
00d00b84d366a982ce2dc6085135eb26953ca258
2025-03-18 21:17:23
Timothy Flynn
libjs: Ensure relevant extension keys are included in ICU locale data
false
Ensure relevant extension keys are included in ICU locale data
libjs
diff --git a/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp b/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp index 166f7a84c94b..486209ee3f20 100644 --- a/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp +++ b/Libraries/LibJS/Runtime/Intl/AbstractOperations.cpp @@ -500,6 +500,8 @@ ResolvedLocale resolve_locale(ReadonlySpan<String> requested_locales, LocaleOpti // 12. Let supportedKeywords be a new empty List. Vector<Unicode::Keyword> supported_keywords; + Vector<Unicode::Keyword> icu_keywords; + // 13. For each element key of relevantExtensionKeys, do for (auto const& key : relevant_extension_keys) { // a. Let keyLocaleData be foundLocaleData.[[<key>]]. @@ -574,10 +576,23 @@ ResolvedLocale resolve_locale(ReadonlySpan<String> requested_locales, LocaleOpti if (supported_keyword.has_value()) supported_keywords.append(supported_keyword.release_value()); + if (auto* value_string = value.get_pointer<String>()) + icu_keywords.empend(MUST(String::from_utf8(key)), *value_string); + // m. Set result.[[<key>]] to value. find_key_in_value(result, key) = move(value); } + // AD-HOC: For ICU, we need to form a locale with all relevant extension keys present. + if (icu_keywords.is_empty()) { + result.icu_locale = found_locale; + } else { + auto locale_id = Unicode::parse_unicode_locale_id(found_locale); + VERIFY(locale_id.has_value()); + + result.icu_locale = insert_unicode_extension_and_canonicalize(locale_id.release_value(), {}, move(icu_keywords)); + } + // 14. If supportedKeywords is not empty, then if (!supported_keywords.is_empty()) { auto locale_id = Unicode::parse_unicode_locale_id(found_locale); diff --git a/Libraries/LibJS/Runtime/Intl/AbstractOperations.h b/Libraries/LibJS/Runtime/Intl/AbstractOperations.h index 14adeabceb7d..1d0d3f9f6444 100644 --- a/Libraries/LibJS/Runtime/Intl/AbstractOperations.h +++ b/Libraries/LibJS/Runtime/Intl/AbstractOperations.h @@ -38,6 +38,7 @@ struct MatchedLocale { struct ResolvedLocale { String locale; + String icu_locale; LocaleKey ca; // [[Calendar]] LocaleKey co; // [[Collation]] LocaleKey hc; // [[HourCycle]] diff --git a/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp b/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp index 36e49b699067..2b0306b7036d 100644 --- a/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp +++ b/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp @@ -47,32 +47,32 @@ static Optional<Unicode::DateTimeFormat const&> get_or_create_formatter(StringVi Optional<Unicode::DateTimeFormat const&> DateTimeFormat::temporal_plain_date_formatter() { - return get_or_create_formatter(m_locale, m_temporal_time_zone, m_temporal_plain_date_formatter, m_temporal_plain_date_format); + return get_or_create_formatter(m_icu_locale, m_temporal_time_zone, m_temporal_plain_date_formatter, m_temporal_plain_date_format); } Optional<Unicode::DateTimeFormat const&> DateTimeFormat::temporal_plain_year_month_formatter() { - return get_or_create_formatter(m_locale, m_temporal_time_zone, m_temporal_plain_year_month_formatter, m_temporal_plain_year_month_format); + return get_or_create_formatter(m_icu_locale, m_temporal_time_zone, m_temporal_plain_year_month_formatter, m_temporal_plain_year_month_format); } Optional<Unicode::DateTimeFormat const&> DateTimeFormat::temporal_plain_month_day_formatter() { - return get_or_create_formatter(m_locale, m_temporal_time_zone, m_temporal_plain_month_day_formatter, m_temporal_plain_month_day_format); + return get_or_create_formatter(m_icu_locale, m_temporal_time_zone, m_temporal_plain_month_day_formatter, m_temporal_plain_month_day_format); } Optional<Unicode::DateTimeFormat const&> DateTimeFormat::temporal_plain_time_formatter() { - return get_or_create_formatter(m_locale, m_temporal_time_zone, m_temporal_plain_time_formatter, m_temporal_plain_time_format); + return get_or_create_formatter(m_icu_locale, m_temporal_time_zone, m_temporal_plain_time_formatter, m_temporal_plain_time_format); } Optional<Unicode::DateTimeFormat const&> DateTimeFormat::temporal_plain_date_time_formatter() { - return get_or_create_formatter(m_locale, m_temporal_time_zone, m_temporal_plain_date_time_formatter, m_temporal_plain_date_time_format); + return get_or_create_formatter(m_icu_locale, m_temporal_time_zone, m_temporal_plain_date_time_formatter, m_temporal_plain_date_time_format); } Optional<Unicode::DateTimeFormat const&> DateTimeFormat::temporal_instant_formatter() { - return get_or_create_formatter(m_locale, m_temporal_time_zone, m_temporal_instant_formatter, m_temporal_instant_format); + return get_or_create_formatter(m_icu_locale, m_temporal_time_zone, m_temporal_instant_formatter, m_temporal_instant_format); } // 11.5.5 FormatDateTimePattern ( dateTimeFormat, patternParts, x, rangeFormatOptions ), https://tc39.es/ecma402/#sec-formatdatetimepattern diff --git a/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h b/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h index b758bdd09d60..2179f004cb17 100644 --- a/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h +++ b/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h @@ -38,6 +38,9 @@ class DateTimeFormat final : public Object { String const& locale() const { return m_locale; } void set_locale(String locale) { m_locale = move(locale); } + String const& icu_locale() const { return m_icu_locale; } + void set_icu_locale(String icu_locale) { m_icu_locale = move(icu_locale); } + String const& calendar() const { return m_calendar; } void set_calendar(String calendar) { m_calendar = move(calendar); } @@ -107,6 +110,7 @@ class DateTimeFormat final : public Object { GC::Ptr<NativeFunction> m_bound_format; // [[BoundFormat]] // Non-standard. Stores the ICU date-time formatters for the Intl object's formatting options. + String m_icu_locale; OwnPtr<Unicode::DateTimeFormat> m_formatter; OwnPtr<Unicode::DateTimeFormat> m_temporal_plain_date_formatter; OwnPtr<Unicode::DateTimeFormat> m_temporal_plain_year_month_formatter; diff --git a/Libraries/LibJS/Runtime/Intl/DateTimeFormatConstructor.cpp b/Libraries/LibJS/Runtime/Intl/DateTimeFormatConstructor.cpp index c8a33df77977..c68d1cdc8877 100644 --- a/Libraries/LibJS/Runtime/Intl/DateTimeFormatConstructor.cpp +++ b/Libraries/LibJS/Runtime/Intl/DateTimeFormatConstructor.cpp @@ -149,6 +149,7 @@ ThrowCompletionOr<GC::Ref<DateTimeFormat>> create_date_time_format(VM& vm, Funct // 18. Set dateTimeFormat.[[Locale]] to r.[[Locale]]. date_time_format->set_locale(move(result.locale)); + date_time_format->set_icu_locale(move(result.icu_locale)); // 19. Let resolvedCalendar be r.[[ca]]. // 20. Set dateTimeFormat.[[Calendar]] to resolvedCalendar. @@ -355,7 +356,7 @@ ThrowCompletionOr<GC::Ref<DateTimeFormat>> create_date_time_format(VM& vm, Funct // d. Let styles be resolvedLocaleData.[[styles]].[[<resolvedCalendar>]]. // e. Let bestFormat be DateTimeStyleFormat(dateStyle, timeStyle, styles). formatter = Unicode::DateTimeFormat::create_for_date_and_time_style( - date_time_format->locale(), + date_time_format->icu_locale(), time_zone, format_options.hour_cycle, format_options.hour12, @@ -443,7 +444,7 @@ ThrowCompletionOr<GC::Ref<DateTimeFormat>> create_date_time_format(VM& vm, Funct } formatter = Unicode::DateTimeFormat::create_for_pattern_options( - date_time_format->locale(), + date_time_format->icu_locale(), time_zone, best_format); } diff --git a/Libraries/LibJS/Runtime/Intl/DurationFormatConstructor.cpp b/Libraries/LibJS/Runtime/Intl/DurationFormatConstructor.cpp index 7fd57e818238..d5513cb0b453 100644 --- a/Libraries/LibJS/Runtime/Intl/DurationFormatConstructor.cpp +++ b/Libraries/LibJS/Runtime/Intl/DurationFormatConstructor.cpp @@ -89,7 +89,7 @@ ThrowCompletionOr<GC::Ref<Object>> DurationFormatConstructor::construct(Function // 11. Let resolvedLocaleData be r.[[LocaleData]]. // 12. Let digitalFormat be resolvedLocaleData.[[DigitalFormat]]. - auto digital_format = Unicode::digital_format(duration_format->locale()); + auto digital_format = Unicode::digital_format(result.icu_locale); // 13. Set durationFormat.[[HourMinuteSeparator]] to digitalFormat.[[HourMinuteSeparator]]. duration_format->set_hour_minute_separator(move(digital_format.hours_minutes_separator)); diff --git a/Libraries/LibJS/Runtime/Intl/NumberFormatConstructor.cpp b/Libraries/LibJS/Runtime/Intl/NumberFormatConstructor.cpp index 041a2c1d0d26..15967bb8e6a2 100644 --- a/Libraries/LibJS/Runtime/Intl/NumberFormatConstructor.cpp +++ b/Libraries/LibJS/Runtime/Intl/NumberFormatConstructor.cpp @@ -184,8 +184,7 @@ ThrowCompletionOr<GC::Ref<Object>> NumberFormatConstructor::construct(FunctionOb // Non-standard, create an ICU number formatter for this Intl object. auto formatter = Unicode::NumberFormat::create( - number_format->locale(), - number_format->numbering_system(), + result.icu_locale, number_format->display_options(), number_format->rounding_options()); number_format->set_formatter(move(formatter)); diff --git a/Libraries/LibJS/Runtime/Intl/PluralRulesConstructor.cpp b/Libraries/LibJS/Runtime/Intl/PluralRulesConstructor.cpp index df0a4aaf63a8..f2ca85d3f2ac 100644 --- a/Libraries/LibJS/Runtime/Intl/PluralRulesConstructor.cpp +++ b/Libraries/LibJS/Runtime/Intl/PluralRulesConstructor.cpp @@ -87,8 +87,7 @@ ThrowCompletionOr<GC::Ref<Object>> PluralRulesConstructor::construct(FunctionObj // Non-standard, create an ICU number formatter for this Intl object. auto formatter = Unicode::NumberFormat::create( - plural_rules->locale(), - {}, + result.icu_locale, {}, plural_rules->rounding_options()); diff --git a/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp b/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp index 58c09924577b..75da8e74b98c 100644 --- a/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp +++ b/Libraries/LibJS/Runtime/Intl/RelativeTimeFormatConstructor.cpp @@ -112,7 +112,7 @@ ThrowCompletionOr<GC::Ref<Object>> RelativeTimeFormatConstructor::construct(Func // 20. Let relativeTimeFormat.[[NumberFormat]] be ! Construct(%Intl.NumberFormat%, « locale »). // 21. Let relativeTimeFormat.[[PluralRules]] be ! Construct(%Intl.PluralRules%, « locale »). auto formatter = Unicode::RelativeTimeFormat::create( - relative_time_format->locale(), + result.icu_locale, relative_time_format->style()); relative_time_format->set_formatter(move(formatter)); diff --git a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.format.js b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.format.js index 0300fb3090ac..f34f8616f908 100644 --- a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.format.js +++ b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.format.js @@ -652,17 +652,17 @@ describe("Temporal objects", () => { test("Temporal.PlainDate", () => { const plainDate = new Temporal.PlainDate(1989, 1, 23); - expect(formatter.format(plainDate)).toBe("1/23/1989"); + expect(formatter.format(plainDate)).toBe("1989-01-23"); }); test("Temporal.PlainYearMonth", () => { const plainYearMonth = new Temporal.PlainYearMonth(1989, 1); - expect(formatter.format(plainYearMonth)).toBe("1/1989"); + expect(formatter.format(plainYearMonth)).toBe("1989-01"); }); test("Temporal.PlainMonthDay", () => { const plainMonthDay = new Temporal.PlainMonthDay(1, 23); - expect(formatter.format(plainMonthDay)).toBe("1/23"); + expect(formatter.format(plainMonthDay)).toBe("01-23"); }); test("Temporal.PlainTime", () => { @@ -672,6 +672,6 @@ describe("Temporal objects", () => { test("Temporal.Instant", () => { const instant = new Temporal.Instant(1732740069000000000n); - expect(formatter.format(instant)).toBe("11/27/2024, 8:41:09 PM"); + expect(formatter.format(instant)).toBe("2024-11-27, 8:41:09 PM"); }); }); diff --git a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRange.js b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRange.js index 1ea6bf59476b..3b7fe4dddf13 100644 --- a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRange.js +++ b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRange.js @@ -322,19 +322,19 @@ describe("Temporal objects", () => { test("Temporal.PlainDate", () => { const plainDate1 = new Temporal.PlainDate(1989, 1, 23); const plainDate2 = new Temporal.PlainDate(2024, 11, 27); - expect(formatter.formatRange(plainDate1, plainDate2)).toBe("1/23/1989 – 11/27/2024"); + expect(formatter.formatRange(plainDate1, plainDate2)).toBe("1989-01-23 – 2024-11-27"); }); test("Temporal.PlainYearMonth", () => { const plainYearMonth1 = new Temporal.PlainYearMonth(1989, 1); const plainYearMonth2 = new Temporal.PlainYearMonth(2024, 11); - expect(formatter.formatRange(plainYearMonth1, plainYearMonth2)).toBe("1/1989 – 11/2024"); + expect(formatter.formatRange(plainYearMonth1, plainYearMonth2)).toBe("1989-01 – 2024-11"); }); test("Temporal.PlainMonthDay", () => { const plainMonthDay1 = new Temporal.PlainMonthDay(1, 23); const plainMonthDay2 = new Temporal.PlainMonthDay(11, 27); - expect(formatter.formatRange(plainMonthDay1, plainMonthDay2)).toBe("1/23 – 11/27"); + expect(formatter.formatRange(plainMonthDay1, plainMonthDay2)).toBe("01-23 – 11-27"); }); test("Temporal.PlainTime", () => { @@ -347,7 +347,7 @@ describe("Temporal objects", () => { const instant1 = new Temporal.Instant(601546251000000000n); const instant2 = new Temporal.Instant(1732740069000000000n); expect(formatter.formatRange(instant1, instant2)).toBe( - "1/23/1989, 8:10:51 AM – 11/27/2024, 8:41:09 PM" + "1989-01-23, 8:10:51 AM – 2024-11-27, 8:41:09 PM" ); }); }); diff --git a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRangeToParts.js b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRangeToParts.js index 57548cda756c..d66faef2c29e 100644 --- a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRangeToParts.js +++ b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatRangeToParts.js @@ -736,17 +736,17 @@ describe("Temporal objects", () => { const plainDate1 = new Temporal.PlainDate(1989, 1, 23); const plainDate2 = new Temporal.PlainDate(2024, 11, 27); expect(formatter.formatRangeToParts(plainDate1, plainDate2)).toEqual([ - { type: "month", value: "1", source: "startRange" }, - { type: "literal", value: "/", source: "startRange" }, - { type: "day", value: "23", source: "startRange" }, - { type: "literal", value: "/", source: "startRange" }, { type: "year", value: "1989", source: "startRange" }, + { type: "literal", value: "-", source: "startRange" }, + { type: "month", value: "01", source: "startRange" }, + { type: "literal", value: "-", source: "startRange" }, + { type: "day", value: "23", source: "startRange" }, { type: "literal", value: " – ", source: "shared" }, + { type: "year", value: "2024", source: "endRange" }, + { type: "literal", value: "-", source: "endRange" }, { type: "month", value: "11", source: "endRange" }, - { type: "literal", value: "/", source: "endRange" }, + { type: "literal", value: "-", source: "endRange" }, { type: "day", value: "27", source: "endRange" }, - { type: "literal", value: "/", source: "endRange" }, - { type: "year", value: "2024", source: "endRange" }, ]); }); @@ -754,13 +754,13 @@ describe("Temporal objects", () => { const plainYearMonth1 = new Temporal.PlainYearMonth(1989, 1); const plainYearMonth2 = new Temporal.PlainYearMonth(2024, 11); expect(formatter.formatRangeToParts(plainYearMonth1, plainYearMonth2)).toEqual([ - { type: "month", value: "1", source: "startRange" }, - { type: "literal", value: "/", source: "startRange" }, { type: "year", value: "1989", source: "startRange" }, + { type: "literal", value: "-", source: "startRange" }, + { type: "month", value: "01", source: "startRange" }, { type: "literal", value: " – ", source: "shared" }, - { type: "month", value: "11", source: "endRange" }, - { type: "literal", value: "/", source: "endRange" }, { type: "year", value: "2024", source: "endRange" }, + { type: "literal", value: "-", source: "endRange" }, + { type: "month", value: "11", source: "endRange" }, ]); }); @@ -768,12 +768,12 @@ describe("Temporal objects", () => { const plainMonthDay1 = new Temporal.PlainMonthDay(1, 23); const plainMonthDay2 = new Temporal.PlainMonthDay(11, 27); expect(formatter.formatRangeToParts(plainMonthDay1, plainMonthDay2)).toEqual([ - { type: "month", value: "1", source: "startRange" }, - { type: "literal", value: "/", source: "startRange" }, + { type: "month", value: "01", source: "startRange" }, + { type: "literal", value: "-", source: "startRange" }, { type: "day", value: "23", source: "startRange" }, { type: "literal", value: " – ", source: "shared" }, { type: "month", value: "11", source: "endRange" }, - { type: "literal", value: "/", source: "endRange" }, + { type: "literal", value: "-", source: "endRange" }, { type: "day", value: "27", source: "endRange" }, ]); }); @@ -804,11 +804,11 @@ describe("Temporal objects", () => { const instant1 = new Temporal.Instant(601546251000000000n); const instant2 = new Temporal.Instant(1732740069000000000n); expect(formatter.formatRangeToParts(instant1, instant2)).toEqual([ - { type: "month", value: "1", source: "startRange" }, - { type: "literal", value: "/", source: "startRange" }, - { type: "day", value: "23", source: "startRange" }, - { type: "literal", value: "/", source: "startRange" }, { type: "year", value: "1989", source: "startRange" }, + { type: "literal", value: "-", source: "startRange" }, + { type: "month", value: "01", source: "startRange" }, + { type: "literal", value: "-", source: "startRange" }, + { type: "day", value: "23", source: "startRange" }, { type: "literal", value: ", ", source: "startRange" }, { type: "hour", value: "8", source: "startRange" }, { type: "literal", value: ":", source: "startRange" }, @@ -818,11 +818,11 @@ describe("Temporal objects", () => { { type: "literal", value: " ", source: "startRange" }, { type: "dayPeriod", value: "AM", source: "startRange" }, { type: "literal", value: " – ", source: "shared" }, + { type: "year", value: "2024", source: "endRange" }, + { type: "literal", value: "-", source: "endRange" }, { type: "month", value: "11", source: "endRange" }, - { type: "literal", value: "/", source: "endRange" }, + { type: "literal", value: "-", source: "endRange" }, { type: "day", value: "27", source: "endRange" }, - { type: "literal", value: "/", source: "endRange" }, - { type: "year", value: "2024", source: "endRange" }, { type: "literal", value: ", ", source: "endRange" }, { type: "hour", value: "8", source: "endRange" }, { type: "literal", value: ":", source: "endRange" }, diff --git a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatToParts.js b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatToParts.js index 9ca0b871c911..ed7137af9706 100644 --- a/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatToParts.js +++ b/Libraries/LibJS/Tests/builtins/Intl/DateTimeFormat/DateTimeFormat.prototype.formatToParts.js @@ -350,28 +350,28 @@ describe("Temporal objects", () => { test("Temporal.PlainDate", () => { const plainDate = new Temporal.PlainDate(1989, 1, 23); expect(formatter.formatToParts(plainDate)).toEqual([ - { type: "month", value: "1" }, - { type: "literal", value: "/" }, - { type: "day", value: "23" }, - { type: "literal", value: "/" }, { type: "year", value: "1989" }, + { type: "literal", value: "-" }, + { type: "month", value: "01" }, + { type: "literal", value: "-" }, + { type: "day", value: "23" }, ]); }); test("Temporal.PlainYearMonth", () => { const plainYearMonth = new Temporal.PlainYearMonth(1989, 1); expect(formatter.formatToParts(plainYearMonth)).toEqual([ - { type: "month", value: "1" }, - { type: "literal", value: "/" }, { type: "year", value: "1989" }, + { type: "literal", value: "-" }, + { type: "month", value: "01" }, ]); }); test("Temporal.PlainMonthDay", () => { const plainMonthDay = new Temporal.PlainMonthDay(1, 23); expect(formatter.formatToParts(plainMonthDay)).toEqual([ - { type: "month", value: "1" }, - { type: "literal", value: "/" }, + { type: "month", value: "01" }, + { type: "literal", value: "-" }, { type: "day", value: "23" }, ]); }); @@ -392,11 +392,11 @@ describe("Temporal objects", () => { test("Temporal.Instant", () => { const instant = new Temporal.Instant(1732740069000000000n); expect(formatter.formatToParts(instant)).toEqual([ + { type: "year", value: "2024" }, + { type: "literal", value: "-" }, { type: "month", value: "11" }, - { type: "literal", value: "/" }, + { type: "literal", value: "-" }, { type: "day", value: "27" }, - { type: "literal", value: "/" }, - { type: "year", value: "2024" }, { type: "literal", value: ", " }, { type: "hour", value: "8" }, { type: "literal", value: ":" }, diff --git a/Libraries/LibJS/Tests/builtins/Intl/RelativeTimeFormat/RelativeTimeFormat.prototype.format.js b/Libraries/LibJS/Tests/builtins/Intl/RelativeTimeFormat/RelativeTimeFormat.prototype.format.js index def30e3c5b2c..95b5fa1568a5 100644 --- a/Libraries/LibJS/Tests/builtins/Intl/RelativeTimeFormat/RelativeTimeFormat.prototype.format.js +++ b/Libraries/LibJS/Tests/builtins/Intl/RelativeTimeFormat/RelativeTimeFormat.prototype.format.js @@ -129,6 +129,11 @@ describe("second", () => { runTest("second", "narrow", "auto", en, ar, pl); }); + + test("numberingSystem set via locale options", () => { + const formatter = new Intl.RelativeTimeFormat("en", { numberingSystem: "arab" }); + expect(formatter.format(1, "second")).toBe("in ١ second"); + }); }); describe("minute", () => { diff --git a/Libraries/LibUnicode/DurationFormat.cpp b/Libraries/LibUnicode/DurationFormat.cpp index cadca63d3073..7c637ab4eda2 100644 --- a/Libraries/LibUnicode/DurationFormat.cpp +++ b/Libraries/LibUnicode/DurationFormat.cpp @@ -38,7 +38,7 @@ DigitalFormat digital_format(StringView locale) rounding_options.min_significant_digits = 1; rounding_options.max_significant_digits = 2; - auto number_formatter = NumberFormat::create(locale, "latn"sv, {}, rounding_options); + auto number_formatter = NumberFormat::create(locale, {}, rounding_options); auto icu_locale = adopt_own(*locale_data->locale().clone()); icu_locale->setUnicodeKeywordValue("nu", "latn", status); diff --git a/Libraries/LibUnicode/NumberFormat.cpp b/Libraries/LibUnicode/NumberFormat.cpp index a44d6aba57db..6e713bd029b3 100644 --- a/Libraries/LibUnicode/NumberFormat.cpp +++ b/Libraries/LibUnicode/NumberFormat.cpp @@ -866,12 +866,9 @@ class NumberFormatImpl : public NumberFormat { NonnullOwnPtr<NumberFormat> NumberFormat::create( StringView locale, - StringView numbering_system, DisplayOptions const& display_options, RoundingOptions const& rounding_options) { - UErrorCode status = U_ZERO_ERROR; - auto locale_data = LocaleData::for_locale(locale); VERIFY(locale_data.has_value()); @@ -879,11 +876,6 @@ NonnullOwnPtr<NumberFormat> NumberFormat::create( apply_display_options(formatter, display_options); apply_rounding_options(formatter, rounding_options); - if (!numbering_system.is_empty()) { - if (auto* symbols = icu::NumberingSystem::createInstanceByName(ByteString(numbering_system).characters(), status); symbols && icu_success(status)) - formatter = formatter.adoptSymbols(symbols); - } - bool is_unit = display_options.style == NumberFormatStyle::Unit; return adopt_own(*new NumberFormatImpl(locale_data->locale(), move(formatter), is_unit)); } diff --git a/Libraries/LibUnicode/NumberFormat.h b/Libraries/LibUnicode/NumberFormat.h index e9bc46126376..929160f45176 100644 --- a/Libraries/LibUnicode/NumberFormat.h +++ b/Libraries/LibUnicode/NumberFormat.h @@ -142,7 +142,6 @@ class NumberFormat { public: static NonnullOwnPtr<NumberFormat> create( StringView locale, - StringView numbering_system, DisplayOptions const&, RoundingOptions const&);
5947c37637f8ea3d4c323a04e5e5dfe9fad5a4d7
2024-12-15 01:38:50
Timothy Flynn
libjs: Return the allocated dst register from deleting super properties
false
Return the allocated dst register from deleting super properties
libjs
diff --git a/Libraries/LibJS/Bytecode/Generator.cpp b/Libraries/LibJS/Bytecode/Generator.cpp index f4c99673a1c4..dcd7b04efa43 100644 --- a/Libraries/LibJS/Bytecode/Generator.cpp +++ b/Libraries/LibJS/Bytecode/Generator.cpp @@ -812,7 +812,7 @@ CodeGenerationErrorOr<Optional<ScopedOperand>> Generator::emit_delete_reference( emit<Bytecode::Op::DeleteByIdWithThis>(dst, *super_reference.base, *super_reference.this_value, identifier_table_ref); } - return Optional<ScopedOperand> {}; + return dst; } auto object = TRY(expression.object().generate_bytecode(*this)).value(); diff --git a/Libraries/LibJS/Tests/operators/delete-basic.js b/Libraries/LibJS/Tests/operators/delete-basic.js index f41269c5fc9e..fc6d58b057a2 100644 --- a/Libraries/LibJS/Tests/operators/delete-basic.js +++ b/Libraries/LibJS/Tests/operators/delete-basic.js @@ -93,6 +93,13 @@ test("deleting super property", () => { } } + class D { + static foo() { + const deleter = () => delete super.foo; + deleter(); + } + } + const obj = new B(); expect(() => { obj.bar(); @@ -106,6 +113,10 @@ test("deleting super property", () => { expect(() => { C.foo(); }).toThrowWithMessage(ReferenceError, "Can't delete a property on 'super'"); + + expect(() => { + D.foo(); + }).toThrowWithMessage(ReferenceError, "Can't delete a property on 'super'"); }); test("deleting an object computed property coerces the object to a property key", () => {
f7ac3545ccfae9e84b2ffb2b1b6f5cfd886a307e
2021-09-27 22:15:45
Luke Wilde
libweb: Add initial support for CustomEvent
false
Add initial support for CustomEvent
libweb
diff --git a/Userland/Libraries/LibWeb/Bindings/EventWrapperFactory.cpp b/Userland/Libraries/LibWeb/Bindings/EventWrapperFactory.cpp index 71176cf4f605..ccdb1204f3b1 100644 --- a/Userland/Libraries/LibWeb/Bindings/EventWrapperFactory.cpp +++ b/Userland/Libraries/LibWeb/Bindings/EventWrapperFactory.cpp @@ -1,10 +1,12 @@ /* * Copyright (c) 2020, Andreas Kling <[email protected]> + * Copyright (c) 2021, Luke Wilde <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibWeb/Bindings/CloseEventWrapper.h> +#include <LibWeb/Bindings/CustomEventWrapper.h> #include <LibWeb/Bindings/EventWrapper.h> #include <LibWeb/Bindings/EventWrapperFactory.h> #include <LibWeb/Bindings/MessageEventWrapper.h> @@ -17,6 +19,8 @@ namespace Web::Bindings { EventWrapper* wrap(JS::GlobalObject& global_object, DOM::Event& event) { + if (is<DOM::CustomEvent>(event)) + return static_cast<CustomEventWrapper*>(wrap_impl(global_object, static_cast<DOM::CustomEvent&>(event))); if (is<HTML::CloseEvent>(event)) return static_cast<CloseEventWrapper*>(wrap_impl(global_object, static_cast<HTML::CloseEvent&>(event))); if (is<HTML::MessageEvent>(event)) diff --git a/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h b/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h index 303ebb0f92a8..fd79b55a683e 100644 --- a/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h +++ b/Userland/Libraries/LibWeb/Bindings/WindowObjectHelper.h @@ -22,6 +22,8 @@ #include <LibWeb/Bindings/CloseEventPrototype.h> #include <LibWeb/Bindings/CommentConstructor.h> #include <LibWeb/Bindings/CommentPrototype.h> +#include <LibWeb/Bindings/CustomEventConstructor.h> +#include <LibWeb/Bindings/CustomEventPrototype.h> #include <LibWeb/Bindings/DOMExceptionConstructor.h> #include <LibWeb/Bindings/DOMExceptionPrototype.h> #include <LibWeb/Bindings/DOMImplementationConstructor.h> @@ -265,6 +267,7 @@ ADD_WINDOW_OBJECT_INTERFACE(CharacterData) \ ADD_WINDOW_OBJECT_INTERFACE(CloseEvent) \ ADD_WINDOW_OBJECT_INTERFACE(Comment) \ + ADD_WINDOW_OBJECT_INTERFACE(CustomEvent) \ ADD_WINDOW_OBJECT_INTERFACE(CSSStyleSheet) \ ADD_WINDOW_OBJECT_INTERFACE(DocumentFragment) \ ADD_WINDOW_OBJECT_INTERFACE(Document) \ diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 7df24978b995..e7c89a9f2e95 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -45,6 +45,7 @@ set(SOURCES DOM/CharacterData.cpp DOM/CharacterData.idl DOM/Comment.cpp + DOM/CustomEvent.cpp DOM/DOMImplementation.cpp DOM/Document.cpp DOM/DocumentFragment.cpp @@ -328,6 +329,7 @@ libweb_js_wrapper(DOM/AbortController) libweb_js_wrapper(DOM/AbortSignal) 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) diff --git a/Userland/Libraries/LibWeb/DOM/CustomEvent.cpp b/Userland/Libraries/LibWeb/DOM/CustomEvent.cpp new file mode 100644 index 000000000000..17c414f910bf --- /dev/null +++ b/Userland/Libraries/LibWeb/DOM/CustomEvent.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021, Luke Wilde <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/DOM/CustomEvent.h> + +namespace Web::DOM { + +CustomEvent::CustomEvent(FlyString const& event_name) + : Event(event_name) +{ +} + +CustomEvent::~CustomEvent() +{ +} + +void CustomEvent::visit_edges(JS::Cell::Visitor& visitor) +{ + visitor.visit(m_detail); +} + +// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent +void CustomEvent::init_custom_event(String const& type, bool bubbles, bool cancelable, JS::Value detail) +{ + // 1. If this’s dispatch flag is set, then return. + if (dispatched()) + return; + + // 2. Initialize this with type, bubbles, and cancelable. + initialize(type, bubbles, cancelable); + + // 3. Set this’s detail attribute to detail. + m_detail = detail; +} + +} diff --git a/Userland/Libraries/LibWeb/DOM/CustomEvent.h b/Userland/Libraries/LibWeb/DOM/CustomEvent.h new file mode 100644 index 000000000000..ad4efe04993d --- /dev/null +++ b/Userland/Libraries/LibWeb/DOM/CustomEvent.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021, Luke Wilde <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <LibWeb/DOM/Event.h> + +namespace Web::DOM { + +// https://dom.spec.whatwg.org/#customevent +class CustomEvent : public Event { +public: + using WrapperType = Bindings::CustomEventWrapper; + + static NonnullRefPtr<CustomEvent> create(FlyString const& event_name) + { + return adopt_ref(*new CustomEvent(event_name)); + } + + virtual ~CustomEvent() override; + + // https://dom.spec.whatwg.org/#dom-customevent-detail + JS::Value detail() const { return m_detail; } + + void visit_edges(JS::Cell::Visitor&); + + void init_custom_event(String const& type, bool bubbles, bool cancelable, JS::Value detail); + +private: + CustomEvent(FlyString const&); + + // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent-type-bubbles-cancelable-detail-detail + JS::Value m_detail { JS::js_null() }; +}; + +} diff --git a/Userland/Libraries/LibWeb/DOM/CustomEvent.idl b/Userland/Libraries/LibWeb/DOM/CustomEvent.idl new file mode 100644 index 000000000000..53abba31ac18 --- /dev/null +++ b/Userland/Libraries/LibWeb/DOM/CustomEvent.idl @@ -0,0 +1,8 @@ +[Exposed=(Window,Worker), CustomVisit] +interface CustomEvent : Event { + // FIXME: constructor(DOMString type, optional CustomEventInit eventInitDict = {}); + + readonly attribute any detail; + + undefined initCustomEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any detail = null); +}; diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp index 875a36e0a4be..f16a5bd203f0 100644 --- a/Userland/Libraries/LibWeb/DOM/Document.cpp +++ b/Userland/Libraries/LibWeb/DOM/Document.cpp @@ -18,6 +18,7 @@ #include <LibWeb/CSS/StyleComputer.h> #include <LibWeb/Cookie/ParsedCookie.h> #include <LibWeb/DOM/Comment.h> +#include <LibWeb/DOM/CustomEvent.h> #include <LibWeb/DOM/DOMException.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/DocumentFragment.h> @@ -739,7 +740,7 @@ NonnullRefPtr<Event> Document::create_event(const String& interface) } else if (interface_lowercase == "compositionevent") { event = Event::create(""); // FIXME: Create CompositionEvent } else if (interface_lowercase == "customevent") { - event = Event::create(""); // FIXME: Create CustomEvent + event = CustomEvent::create(""); } else if (interface_lowercase == "devicemotionevent") { event = Event::create(""); // FIXME: Create DeviceMotionEvent } else if (interface_lowercase == "deviceorientationevent") { diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index 241a09e83dc6..70d9eb29fcc5 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -62,6 +62,7 @@ class AbortController; class AbortSignal; class CharacterData; class Comment; +class CustomEvent; class Document; class DocumentFragment; class DocumentLoadEventDelayer; @@ -261,6 +262,7 @@ class CanvasRenderingContext2DWrapper; class CharacterDataWrapper; class CloseEventWrapper; class CommentWrapper; +class CustomEventWrapper; class DocumentFragmentWrapper; class DocumentTypeWrapper; class DocumentWrapper;
e5cf395a54b44ad5f1a8b4af09d860a832fda90c
2021-12-16 13:04:11
Hendiadyoin1
kernel: Collapse blocking logic for exclusive Mutex' restore_lock()
false
Collapse blocking logic for exclusive Mutex' restore_lock()
kernel
diff --git a/Kernel/Locking/Mutex.cpp b/Kernel/Locking/Mutex.cpp index 663fc8175944..7592e71ea050 100644 --- a/Kernel/Locking/Mutex.cpp +++ b/Kernel/Locking/Mutex.cpp @@ -329,12 +329,8 @@ void Mutex::restore_lock(Mode mode, u32 lock_count, [[maybe_unused]] LockLocatio switch (mode) { case Mode::Exclusive: { auto previous_mode = m_mode; - bool need_to_block = false; - if (m_mode == Mode::Exclusive && m_holder != current_thread) - need_to_block = true; - else if (m_mode == Mode::Shared && (m_shared_holders.size() != 1 || !m_shared_holders.contains(current_thread))) - need_to_block = true; - if (need_to_block) { + if ((m_mode == Mode::Exclusive && m_holder != current_thread) + || (m_mode == Mode::Shared && (m_shared_holders.size() != 1 || !m_shared_holders.contains(current_thread)))) { block(*current_thread, Mode::Exclusive, lock, lock_count); did_block = true; // If we blocked then m_mode should have been updated to what we requested
5e6101dd3ef17e07a9bceb13f355e1e496f62d4f
2022-11-08 15:24:48
Liav A
kernel: Split the TmpFS core files into smaller components
false
Split the TmpFS core files into smaller components
kernel
diff --git a/Kernel/CMakeLists.txt b/Kernel/CMakeLists.txt index cf54143dc17f..c44af9b2bbf7 100644 --- a/Kernel/CMakeLists.txt +++ b/Kernel/CMakeLists.txt @@ -183,7 +183,8 @@ set(KERNEL_SOURCES FileSystem/SysFS/Subsystems/Kernel/Variables/Directory.cpp FileSystem/SysFS/Subsystems/Kernel/Variables/DumpKmallocStack.cpp FileSystem/SysFS/Subsystems/Kernel/Variables/UBSANDeadly.cpp - FileSystem/TmpFS.cpp + FileSystem/TmpFS/FileSystem.cpp + FileSystem/TmpFS/Inode.cpp FileSystem/VirtualFileSystem.cpp Firmware/BIOS.cpp Firmware/ACPI/Initialize.cpp diff --git a/Kernel/FileSystem/TmpFS/FileSystem.cpp b/Kernel/FileSystem/TmpFS/FileSystem.cpp new file mode 100644 index 000000000000..26926ef0c319 --- /dev/null +++ b/Kernel/FileSystem/TmpFS/FileSystem.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2019-2020, Sergey Bugaev <[email protected]> + * Copyright (c) 2022, Liav A. <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <Kernel/FileSystem/TmpFS/FileSystem.h> +#include <Kernel/FileSystem/TmpFS/Inode.h> + +namespace Kernel { + +ErrorOr<NonnullLockRefPtr<FileSystem>> TmpFS::try_create() +{ + return TRY(adopt_nonnull_lock_ref_or_enomem(new (nothrow) TmpFS)); +} + +TmpFS::TmpFS() = default; +TmpFS::~TmpFS() = default; + +ErrorOr<void> TmpFS::initialize() +{ + m_root_inode = TRY(TmpFSInode::try_create_root(*this)); + return {}; +} + +Inode& TmpFS::root_inode() +{ + VERIFY(!m_root_inode.is_null()); + return *m_root_inode; +} + +unsigned TmpFS::next_inode_index() +{ + MutexLocker locker(m_lock); + + return m_next_inode_index++; +} + +} diff --git a/Kernel/FileSystem/TmpFS/FileSystem.h b/Kernel/FileSystem/TmpFS/FileSystem.h new file mode 100644 index 000000000000..13c0fbbb7599 --- /dev/null +++ b/Kernel/FileSystem/TmpFS/FileSystem.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2019-2020, Sergey Bugaev <[email protected]> + * Copyright (c) 2022, Liav A. <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <Kernel/FileSystem/FileSystem.h> +#include <Kernel/FileSystem/Inode.h> +#include <Kernel/Forward.h> + +namespace Kernel { + +class TmpFS final : public FileSystem { + friend class TmpFSInode; + +public: + virtual ~TmpFS() override; + static ErrorOr<NonnullLockRefPtr<FileSystem>> try_create(); + virtual ErrorOr<void> initialize() override; + + virtual StringView class_name() const override { return "TmpFS"sv; } + + virtual bool supports_watchers() const override { return true; } + + virtual Inode& root_inode() override; + +private: + TmpFS(); + + LockRefPtr<TmpFSInode> m_root_inode; + + unsigned m_next_inode_index { 1 }; + unsigned next_inode_index(); +}; + +} diff --git a/Kernel/FileSystem/TmpFS.cpp b/Kernel/FileSystem/TmpFS/Inode.cpp similarity index 95% rename from Kernel/FileSystem/TmpFS.cpp rename to Kernel/FileSystem/TmpFS/Inode.cpp index 7f66a9b4d447..166df6de038a 100644 --- a/Kernel/FileSystem/TmpFS.cpp +++ b/Kernel/FileSystem/TmpFS/Inode.cpp @@ -5,39 +5,11 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include <Kernel/FileSystem/TmpFS.h> +#include <Kernel/FileSystem/TmpFS/Inode.h> #include <Kernel/Process.h> -#include <LibC/limits.h> namespace Kernel { -ErrorOr<NonnullLockRefPtr<FileSystem>> TmpFS::try_create() -{ - return TRY(adopt_nonnull_lock_ref_or_enomem(new (nothrow) TmpFS)); -} - -TmpFS::TmpFS() = default; -TmpFS::~TmpFS() = default; - -ErrorOr<void> TmpFS::initialize() -{ - m_root_inode = TRY(TmpFSInode::try_create_root(*this)); - return {}; -} - -Inode& TmpFS::root_inode() -{ - VERIFY(!m_root_inode.is_null()); - return *m_root_inode; -} - -unsigned TmpFS::next_inode_index() -{ - MutexLocker locker(m_lock); - - return m_next_inode_index++; -} - TmpFSInode::TmpFSInode(TmpFS& fs, InodeMetadata const& metadata, LockWeakPtr<TmpFSInode> parent) : Inode(fs, fs.next_inode_index()) , m_metadata(metadata) diff --git a/Kernel/FileSystem/TmpFS.h b/Kernel/FileSystem/TmpFS/Inode.h similarity index 83% rename from Kernel/FileSystem/TmpFS.h rename to Kernel/FileSystem/TmpFS/Inode.h index 3a98c89de27d..667f0a9aad2b 100644 --- a/Kernel/FileSystem/TmpFS.h +++ b/Kernel/FileSystem/TmpFS/Inode.h @@ -7,39 +7,12 @@ #pragma once -#include <Kernel/FileSystem/FileSystem.h> #include <Kernel/FileSystem/Inode.h> -#include <Kernel/KBuffer.h> -#include <Kernel/Locking/MutexProtected.h> +#include <Kernel/FileSystem/TmpFS/FileSystem.h> #include <Kernel/Memory/AnonymousVMObject.h> namespace Kernel { -class TmpFSInode; - -class TmpFS final : public FileSystem { - friend class TmpFSInode; - -public: - virtual ~TmpFS() override; - static ErrorOr<NonnullLockRefPtr<FileSystem>> try_create(); - virtual ErrorOr<void> initialize() override; - - virtual StringView class_name() const override { return "TmpFS"sv; } - - virtual bool supports_watchers() const override { return true; } - - virtual Inode& root_inode() override; - -private: - TmpFS(); - - LockRefPtr<TmpFSInode> m_root_inode; - - unsigned m_next_inode_index { 1 }; - unsigned next_inode_index(); -}; - class TmpFSInode final : public Inode { friend class TmpFS; diff --git a/Kernel/Forward.h b/Kernel/Forward.h index ba2c62bb6846..e83f87cb8cd8 100644 --- a/Kernel/Forward.h +++ b/Kernel/Forward.h @@ -61,6 +61,7 @@ class TCPSocket; class TTY; class Thread; class ThreadTracer; +class TmpFSInode; class UDPSocket; class UserOrKernelBuffer; class VirtualFileSystem; diff --git a/Kernel/Syscalls/mount.cpp b/Kernel/Syscalls/mount.cpp index 792169c81edc..51699117807e 100644 --- a/Kernel/Syscalls/mount.cpp +++ b/Kernel/Syscalls/mount.cpp @@ -12,7 +12,7 @@ #include <Kernel/FileSystem/Plan9FileSystem.h> #include <Kernel/FileSystem/ProcFS.h> #include <Kernel/FileSystem/SysFS/FileSystem.h> -#include <Kernel/FileSystem/TmpFS.h> +#include <Kernel/FileSystem/TmpFS/FileSystem.h> #include <Kernel/FileSystem/VirtualFileSystem.h> #include <Kernel/Process.h>
756829555ab55ea9bb01712b80bcd68b6f4a9613
2020-05-30 22:10:23
Andreas Kling
libweb: Parse "textarea" tags during the "in body" insertion mode
false
Parse "textarea" tags during the "in body" insertion mode
libweb
diff --git a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp index 24b7fdc2802e..cb320cfb5060 100644 --- a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp +++ b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp @@ -1154,7 +1154,24 @@ void HTMLDocumentParser::handle_in_body(HTMLToken& token) } if (token.is_start_tag() && token.tag_name() == "textarea") { - TODO(); + insert_html_element(token); + + // If the next token is a U+000A LINE FEED (LF) character token, + // then ignore that token and move on to the next one. + // (Newlines at the start of pre blocks are ignored as an authoring convenience.) + auto next_token = m_tokenizer.next_token(); + + m_tokenizer.switch_to({}, HTMLTokenizer::State::RCDATA); + m_original_insertion_mode = m_insertion_mode; + m_frameset_ok = false; + m_insertion_mode = InsertionMode::Text; + + if (next_token.has_value() && next_token.value().is_character() && next_token.value().codepoint() == '\n') { + // Ignore it. + } else { + process_using_the_rules_for(m_insertion_mode, next_token.value()); + } + return; } if (token.is_start_tag() && token.tag_name() == "xmp") { diff --git a/Libraries/LibWeb/Parser/HTMLTokenizer.cpp b/Libraries/LibWeb/Parser/HTMLTokenizer.cpp index 82555d04bd3a..7c20d5d535f1 100644 --- a/Libraries/LibWeb/Parser/HTMLTokenizer.cpp +++ b/Libraries/LibWeb/Parser/HTMLTokenizer.cpp @@ -1029,11 +1029,13 @@ Optional<HTMLToken> HTMLTokenizer::next_token() } ON_EOF { - TODO(); + PARSE_ERROR(); + EMIT_EOF; } ANYTHING_ELSE { - TODO(); + PARSE_ERROR(); + RECONSUME_IN(BeforeAttributeName); } } END_STATE @@ -1521,7 +1523,9 @@ Optional<HTMLToken> HTMLTokenizer::next_token() ANYTHING_ELSE { // FIXME: Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the RCDATA state. - TODO(); + m_queued_tokens.enqueue(HTMLToken::make_character('<')); + m_queued_tokens.enqueue(HTMLToken::make_character('/')); + RECONSUME_IN(RCDATA); } } END_STATE @@ -1531,24 +1535,33 @@ Optional<HTMLToken> HTMLTokenizer::next_token() ON_WHITESPACE { if (!current_end_tag_token_is_appropriate()) { - // FIXME: Otherwise, treat it as per the "anything else" entry below. - TODO(); + m_queued_tokens.enqueue(HTMLToken::make_character('<')); + m_queued_tokens.enqueue(HTMLToken::make_character('/')); + for (auto codepoint : m_temporary_buffer) + m_queued_tokens.enqueue(HTMLToken::make_character(codepoint)); + RECONSUME_IN(RCDATA); } SWITCH_TO(BeforeAttributeName); } ON('/') { if (!current_end_tag_token_is_appropriate()) { - // FIXME: Otherwise, treat it as per the "anything else" entry below. - TODO(); + m_queued_tokens.enqueue(HTMLToken::make_character('<')); + m_queued_tokens.enqueue(HTMLToken::make_character('/')); + for (auto codepoint : m_temporary_buffer) + m_queued_tokens.enqueue(HTMLToken::make_character(codepoint)); + RECONSUME_IN(RCDATA); } SWITCH_TO(SelfClosingStartTag); } ON('>') { if (!current_end_tag_token_is_appropriate()) { - // FIXME: Otherwise, treat it as per the "anything else" entry below. - TODO(); + m_queued_tokens.enqueue(HTMLToken::make_character('<')); + m_queued_tokens.enqueue(HTMLToken::make_character('/')); + for (auto codepoint : m_temporary_buffer) + m_queued_tokens.enqueue(HTMLToken::make_character(codepoint)); + RECONSUME_IN(RCDATA); } SWITCH_TO_AND_EMIT_CURRENT_TOKEN(Data); } @@ -1566,7 +1579,11 @@ Optional<HTMLToken> HTMLTokenizer::next_token() } ANYTHING_ELSE { - TODO(); + m_queued_tokens.enqueue(HTMLToken::make_character('<')); + m_queued_tokens.enqueue(HTMLToken::make_character('/')); + for (auto codepoint : m_temporary_buffer) + m_queued_tokens.enqueue(HTMLToken::make_character(codepoint)); + RECONSUME_IN(RCDATA); } } END_STATE
d36e3af7bebbf4601aceab365a81ca931e58d27e
2021-09-27 19:43:29
Sam Atkins
libweb: Don't try to ad-block data: urls
false
Don't try to ad-block data: urls
libweb
diff --git a/Userland/Libraries/LibWeb/Loader/ContentFilter.cpp b/Userland/Libraries/LibWeb/Loader/ContentFilter.cpp index 5a33e09e245a..5d1e1777fe66 100644 --- a/Userland/Libraries/LibWeb/Loader/ContentFilter.cpp +++ b/Userland/Libraries/LibWeb/Loader/ContentFilter.cpp @@ -25,6 +25,9 @@ ContentFilter::~ContentFilter() bool ContentFilter::is_filtered(const AK::URL& url) const { + if (url.protocol() == "data") + return false; + auto url_string = url.to_string(); for (auto& pattern : m_patterns) {
bed5961fc21ea499ede556d6269df29b8a7a9e15
2022-12-22 20:18:53
Sam Atkins
ak: Rename Bitmap::try_create() to ::create()
false
Rename Bitmap::try_create() to ::create()
ak
diff --git a/AK/Bitmap.h b/AK/Bitmap.h index d39fd0184231..ff5ac5ef6967 100644 --- a/AK/Bitmap.h +++ b/AK/Bitmap.h @@ -22,7 +22,7 @@ class Bitmap : public BitmapView { AK_MAKE_NONCOPYABLE(Bitmap); public: - static ErrorOr<Bitmap> try_create(size_t size, bool default_value) + static ErrorOr<Bitmap> create(size_t size, bool default_value) { VERIFY(size != 0); @@ -37,7 +37,7 @@ class Bitmap : public BitmapView { static Bitmap must_create(size_t size, bool default_value) { - return MUST(try_create(size, default_value)); + return MUST(create(size, default_value)); } Bitmap() = default; diff --git a/Kernel/Bus/PCI/Controller/HostController.cpp b/Kernel/Bus/PCI/Controller/HostController.cpp index 81754c2cc5d0..22cd93de5cf0 100644 --- a/Kernel/Bus/PCI/Controller/HostController.cpp +++ b/Kernel/Bus/PCI/Controller/HostController.cpp @@ -14,7 +14,7 @@ namespace Kernel::PCI { HostController::HostController(PCI::Domain const& domain) : m_domain(domain) - , m_enumerated_buses(Bitmap::try_create(256, false).release_value_but_fixme_should_propagate_errors()) + , m_enumerated_buses(Bitmap::create(256, false).release_value_but_fixme_should_propagate_errors()) { } diff --git a/Kernel/Memory/AnonymousVMObject.cpp b/Kernel/Memory/AnonymousVMObject.cpp index 291951324d5a..3dc4f90ccd3a 100644 --- a/Kernel/Memory/AnonymousVMObject.cpp +++ b/Kernel/Memory/AnonymousVMObject.cpp @@ -279,7 +279,7 @@ NonnullRefPtr<PhysicalPage> AnonymousVMObject::allocate_committed_page(Badge<Reg ErrorOr<void> AnonymousVMObject::ensure_cow_map() { if (m_cow_map.is_null()) - m_cow_map = TRY(Bitmap::try_create(page_count(), true)); + m_cow_map = TRY(Bitmap::create(page_count(), true)); return {}; } diff --git a/Kernel/Memory/PrivateInodeVMObject.cpp b/Kernel/Memory/PrivateInodeVMObject.cpp index 6f769c6df5ab..8463656e06d9 100644 --- a/Kernel/Memory/PrivateInodeVMObject.cpp +++ b/Kernel/Memory/PrivateInodeVMObject.cpp @@ -23,14 +23,14 @@ ErrorOr<NonnullLockRefPtr<PrivateInodeVMObject>> PrivateInodeVMObject::try_creat auto size = max(inode.size(), (offset + range_size)); VERIFY(size > 0); auto new_physical_pages = TRY(VMObject::try_create_physical_pages(size)); - auto dirty_pages = TRY(Bitmap::try_create(new_physical_pages.size(), false)); + auto dirty_pages = TRY(Bitmap::create(new_physical_pages.size(), false)); return adopt_nonnull_lock_ref_or_enomem(new (nothrow) PrivateInodeVMObject(inode, move(new_physical_pages), move(dirty_pages))); } ErrorOr<NonnullLockRefPtr<VMObject>> PrivateInodeVMObject::try_clone() { auto new_physical_pages = TRY(this->try_clone_physical_pages()); - auto dirty_pages = TRY(Bitmap::try_create(new_physical_pages.size(), false)); + auto dirty_pages = TRY(Bitmap::create(new_physical_pages.size(), false)); return adopt_nonnull_lock_ref_or_enomem<VMObject>(new (nothrow) PrivateInodeVMObject(*this, move(new_physical_pages), move(dirty_pages))); } diff --git a/Kernel/Memory/SharedInodeVMObject.cpp b/Kernel/Memory/SharedInodeVMObject.cpp index 29b2095d13c7..233af5979f41 100644 --- a/Kernel/Memory/SharedInodeVMObject.cpp +++ b/Kernel/Memory/SharedInodeVMObject.cpp @@ -26,7 +26,7 @@ ErrorOr<NonnullLockRefPtr<SharedInodeVMObject>> SharedInodeVMObject::try_create_ if (auto shared_vmobject = inode.shared_vmobject()) return shared_vmobject.release_nonnull(); auto new_physical_pages = TRY(VMObject::try_create_physical_pages(size)); - auto dirty_pages = TRY(Bitmap::try_create(new_physical_pages.size(), false)); + auto dirty_pages = TRY(Bitmap::create(new_physical_pages.size(), false)); auto vmobject = TRY(adopt_nonnull_lock_ref_or_enomem(new (nothrow) SharedInodeVMObject(inode, move(new_physical_pages), move(dirty_pages)))); TRY(vmobject->inode().set_shared_vmobject(*vmobject)); return vmobject; @@ -35,7 +35,7 @@ ErrorOr<NonnullLockRefPtr<SharedInodeVMObject>> SharedInodeVMObject::try_create_ ErrorOr<NonnullLockRefPtr<VMObject>> SharedInodeVMObject::try_clone() { auto new_physical_pages = TRY(this->try_clone_physical_pages()); - auto dirty_pages = TRY(Bitmap::try_create(new_physical_pages.size(), false)); + auto dirty_pages = TRY(Bitmap::create(new_physical_pages.size(), false)); return adopt_nonnull_lock_ref_or_enomem<VMObject>(new (nothrow) SharedInodeVMObject(*this, move(new_physical_pages), move(dirty_pages))); }
b7dae4f90eca46220217b8a858afe5915f761a1b
2021-08-11 01:21:05
Andreas Kling
kernel: Add CLOCK_MONOTONIC_COARSE to the kernel time page
false
Add CLOCK_MONOTONIC_COARSE to the kernel time page
kernel
diff --git a/Kernel/API/TimePage.h b/Kernel/API/TimePage.h index e1492cd21fab..76e6b44f8f42 100644 --- a/Kernel/API/TimePage.h +++ b/Kernel/API/TimePage.h @@ -18,7 +18,7 @@ namespace Kernel { inline bool time_page_supports(clockid_t clock_id) { - return clock_id == CLOCK_REALTIME_COARSE; + return clock_id == CLOCK_REALTIME_COARSE || clock_id == CLOCK_MONOTONIC_COARSE; } struct TimePage { diff --git a/Kernel/Time/TimeManagement.cpp b/Kernel/Time/TimeManagement.cpp index 9c4360496573..6d9f6c6bf106 100644 --- a/Kernel/Time/TimeManagement.cpp +++ b/Kernel/Time/TimeManagement.cpp @@ -363,9 +363,9 @@ void TimeManagement::increment_time_since_boot_hpet() // TODO: Apply m_remaining_epoch_time_adjustment timespec_add(m_epoch_time, { (time_t)(delta_ns / 1000000000), (long)(delta_ns % 1000000000) }, m_epoch_time); - update_time_page(); - m_update1.store(update_iteration + 1, AK::MemoryOrder::memory_order_release); + + update_time_page(); } void TimeManagement::increment_time_since_boot() @@ -396,8 +396,9 @@ void TimeManagement::increment_time_since_boot() m_ticks_this_second = 0; } - update_time_page(); m_update1.store(update_iteration + 1, AK::MemoryOrder::memory_order_release); + + update_time_page(); } void TimeManagement::system_timer_tick(const RegisterState& regs) @@ -432,6 +433,7 @@ void TimeManagement::update_time_page() auto* page = time_page(); u32 update_iteration = AK::atomic_fetch_add(&page->update2, 1u, AK::MemoryOrder::memory_order_acquire); page->clocks[CLOCK_REALTIME_COARSE] = m_epoch_time; + page->clocks[CLOCK_MONOTONIC_COARSE] = monotonic_time(TimePrecision::Coarse).to_timespec(); AK::atomic_store(&page->update1, update_iteration + 1u, AK::MemoryOrder::memory_order_release); }
9ea5a00e24076431fe197ec76f88009ef28d9bbb
2021-11-18 17:55:21
Lady Gegga
base: Add Shavian characters to font Katica Regular 10
false
Add Shavian characters to font Katica Regular 10
base
diff --git a/Base/res/fonts/KaticaRegular10.font b/Base/res/fonts/KaticaRegular10.font index 88f2244ec4fc..803b74458f05 100644 Binary files a/Base/res/fonts/KaticaRegular10.font and b/Base/res/fonts/KaticaRegular10.font differ
82768e7ac5a50618d3334118160a63bb61d4db83
2019-02-17 06:13:01
Andreas Kling
windowserver: Move video mode setup to WSScreen.
false
Move video mode setup to WSScreen.
windowserver
diff --git a/WindowServer/WSMessageLoop.cpp b/WindowServer/WSMessageLoop.cpp index b49dde17b58d..df0ed7bf3fe7 100644 --- a/WindowServer/WSMessageLoop.cpp +++ b/WindowServer/WSMessageLoop.cpp @@ -1,18 +1,18 @@ -#include "WSMessageLoop.h" -#include "WSMessage.h" -#include "WSMessageReceiver.h" -#include "WSWindowManager.h" -#include "WSScreen.h" +#include <WindowServer/WSMessageLoop.h> +#include <WindowServer/WSMessage.h> +#include <WindowServer/WSMessageReceiver.h> +#include <WindowServer/WSWindowManager.h> +#include <WindowServer/WSScreen.h> #include <WindowServer/WSClientConnection.h> -#include <Kernel/KeyCode.h> #include <WindowServer/WSAPITypes.h> -#include <unistd.h> -#include <time.h> -#include <sys/socket.h> -#include <sys/select.h> -#include <fcntl.h> -#include <stdio.h> -#include <errno.h> +#include <Kernel/KeyCode.h> +#include <LibC/sys/socket.h> +#include <LibC/sys/select.h> +#include <LibC/unistd.h> +#include <LibC/time.h> +#include <LibC/fcntl.h> +#include <LibC/stdio.h> +#include <LibC/errno.h> //#define WSEVENTLOOP_DEBUG diff --git a/WindowServer/WSScreen.cpp b/WindowServer/WSScreen.cpp index e2e2ce76104f..dbeeeca6b311 100644 --- a/WindowServer/WSScreen.cpp +++ b/WindowServer/WSScreen.cpp @@ -2,6 +2,10 @@ #include "WSMessageLoop.h" #include "WSMessage.h" #include "WSWindowManager.h" +#include <unistd.h> +#include <fcntl.h> +#include <sys/ioctl.h> +#include <sys/mman.h> static WSScreen* s_the; @@ -11,15 +15,29 @@ WSScreen& WSScreen::the() return *s_the; } -WSScreen::WSScreen(RGBA32* framebuffer, unsigned width, unsigned height) - : m_framebuffer(framebuffer) - , m_width(width) +WSScreen::WSScreen(unsigned width, unsigned height) + : m_width(width) , m_height(height) { ASSERT(!s_the); s_the = this; m_cursor_location = rect().center(); + + m_framebuffer_fd = open("/dev/bxvga", O_RDWR); + ASSERT(m_framebuffer_fd >= 0); + + struct BXVGAResolution { + int width; + int height; + }; + BXVGAResolution resolution { (int)width, (int)height}; + int rc = ioctl(m_framebuffer_fd, 1985, (int)&resolution); + ASSERT(rc == 0); + + size_t framebuffer_size_in_bytes = resolution.width * resolution.height * sizeof(RGBA32) * 2; + m_framebuffer = (RGBA32*)mmap(nullptr, framebuffer_size_in_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, m_framebuffer_fd, 0); + ASSERT(m_framebuffer && m_framebuffer != (void*)-1); } WSScreen::~WSScreen() @@ -68,3 +86,9 @@ void WSScreen::on_receive_keyboard_data(KeyEvent kernel_event) message->m_alt = kernel_event.alt(); WSMessageLoop::the().post_message(&WSWindowManager::the(), move(message)); } + +void WSScreen::set_y_offset(int offset) +{ + int rc = ioctl(m_framebuffer_fd, 1982, offset); + ASSERT(rc == 0); +} diff --git a/WindowServer/WSScreen.h b/WindowServer/WSScreen.h index e9c41373e10f..851a12fd9544 100644 --- a/WindowServer/WSScreen.h +++ b/WindowServer/WSScreen.h @@ -7,7 +7,7 @@ class WSScreen { public: - WSScreen(RGBA32*, unsigned width, unsigned height); + WSScreen(unsigned width, unsigned height); ~WSScreen(); void set_resolution(int width, int height); @@ -21,6 +21,8 @@ class WSScreen { Size size() const { return { width(), height() }; } Rect rect() const { return { 0, 0, width(), height() }; } + void set_y_offset(int); + Point cursor_location() const { return m_cursor_location; } bool left_mouse_button_pressed() const { return m_left_mouse_button_pressed; } bool right_mouse_button_pressed() const { return m_right_mouse_button_pressed; } @@ -28,14 +30,12 @@ class WSScreen { void on_receive_mouse_data(int dx, int dy, bool left_button, bool right_button); void on_receive_keyboard_data(KeyEvent); -protected: - WSScreen(unsigned width, unsigned height); - private: RGBA32* m_framebuffer { nullptr }; int m_width { 0 }; int m_height { 0 }; + int m_framebuffer_fd { -1 }; Point m_cursor_location; bool m_left_mouse_button_pressed { false }; diff --git a/WindowServer/WSWindowManager.cpp b/WindowServer/WSWindowManager.cpp index 665f747c97dc..811033437afd 100644 --- a/WindowServer/WSWindowManager.cpp +++ b/WindowServer/WSWindowManager.cpp @@ -11,7 +11,6 @@ #include "WSMenuBar.h" #include "WSMenuItem.h" #include <WindowServer/WSClientConnection.h> -#include <sys/ioctl.h> #include <unistd.h> #include <stdio.h> #include <time.h> @@ -128,11 +127,8 @@ void WSWindowManager::flip_buffers() { swap(m_front_bitmap, m_back_bitmap); swap(m_front_painter, m_back_painter); - if (m_framebuffer_fd != -1) { - int new_y_offset = m_buffers_are_flipped ? 0 : m_screen_rect.height(); - int rc = ioctl(m_framebuffer_fd, 1982, new_y_offset); - ASSERT(rc == 0); - } + int new_y_offset = m_buffers_are_flipped ? 0 : m_screen_rect.height(); + WSScreen::the().set_y_offset(new_y_offset); m_buffers_are_flipped = !m_buffers_are_flipped; } diff --git a/WindowServer/WSWindowManager.h b/WindowServer/WSWindowManager.h index 08631f3b92a5..0ef8ec07eb89 100644 --- a/WindowServer/WSWindowManager.h +++ b/WindowServer/WSWindowManager.h @@ -66,9 +66,6 @@ class WSWindowManager : public WSMessageReceiver { Color menu_selection_color() const { return m_menu_selection_color; } int menubar_menu_margin() const; - int framebuffer_fd() const { return m_framebuffer_fd; } - void set_framebuffer_fd(int fd) { m_framebuffer_fd = fd; } - private: void process_mouse_event(WSMouseEvent&); void handle_menu_mouse_event(WSMenu&, WSMouseEvent&); @@ -149,6 +146,4 @@ class WSWindowManager : public WSMessageReceiver { Color m_menu_selection_color; WeakPtr<WSMenuBar> m_current_menubar; WeakPtr<WSMenu> m_current_menu; - - int m_framebuffer_fd { -1 }; }; diff --git a/WindowServer/main.cpp b/WindowServer/main.cpp index f74ad07f7664..2ffa3957f869 100644 --- a/WindowServer/main.cpp +++ b/WindowServer/main.cpp @@ -1,40 +1,14 @@ -#include <SharedGraphics/Font.h> #include <WindowServer/WSScreen.h> #include <WindowServer/WSWindowManager.h> #include <WindowServer/WSMessageLoop.h> -#include <WindowServer/WSWindow.h> -#include <unistd.h> -#include <fcntl.h> -#include <sys/ioctl.h> -#include <sys/mman.h> int main(int, char**) { - dbgprintf("WindowServer starting...\n"); WSMessageLoop loop; - - int bxvga_fd = open("/dev/bxvga", O_RDWR); - ASSERT(bxvga_fd >= 0); - - struct BXVGAResolution { - int width; - int height; - }; - BXVGAResolution resolution { 1024, 768 }; - int rc = ioctl(bxvga_fd, 1985, (int)&resolution); - ASSERT(rc == 0); - - size_t framebuffer_size_in_bytes = resolution.width * resolution.height * sizeof(RGBA32) * 2; - void* framebuffer = mmap(nullptr, framebuffer_size_in_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, bxvga_fd, 0); - ASSERT(framebuffer && framebuffer != (void*)-1); - - WSScreen screen((dword*)framebuffer, resolution.width, resolution.height); - + WSScreen screen(1024, 768); WSWindowManager window_manager; - window_manager.set_framebuffer_fd(bxvga_fd); dbgprintf("Entering WindowServer main loop.\n"); WSMessageLoop::the().exec(); - ASSERT_NOT_REACHED(); }
bd272e638cc33e3282ffde1052eafd15cd00eac5
2022-12-08 18:16:03
Sam Atkins
libweb: Introduce CSSPixels and DevicePixels classes
false
Introduce CSSPixels and DevicePixels classes
libweb
diff --git a/Userland/Libraries/LibWeb/PixelUnits.h b/Userland/Libraries/LibWeb/PixelUnits.h new file mode 100644 index 000000000000..702107e81b12 --- /dev/null +++ b/Userland/Libraries/LibWeb/PixelUnits.h @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2022, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Concepts.h> +#include <AK/DistinctNumeric.h> +#include <AK/Traits.h> +#include <LibGfx/Forward.h> +#include <math.h> + +namespace Web { + +/// DevicePixels: A position or length on the physical display. +AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(int, DevicePixels, Arithmetic, CastToUnderlying, Comparison, Increment); + +template<Arithmetic T> +constexpr bool operator==(DevicePixels left, T right) { return left.value() == right; } + +template<Arithmetic T> +constexpr bool operator!=(DevicePixels left, T right) { return left.value() != right; } + +template<Arithmetic T> +constexpr bool operator>(DevicePixels left, T right) { return left.value() > right; } + +template<Arithmetic T> +constexpr bool operator<(DevicePixels left, T right) { return left.value() < right; } + +template<Arithmetic T> +constexpr bool operator>=(DevicePixels left, T right) { return left.value() >= right; } + +template<Arithmetic T> +constexpr bool operator<=(DevicePixels left, T right) { return left.value() <= right; } + +template<Arithmetic T> +constexpr DevicePixels operator*(DevicePixels left, T right) { return left.value() * right; } +template<Arithmetic T> +constexpr DevicePixels operator*(T left, DevicePixels right) { return right * left; } + +template<Arithmetic T> +constexpr DevicePixels operator/(DevicePixels left, T right) { return left.value() / right; } + +template<Arithmetic T> +constexpr DevicePixels operator%(DevicePixels left, T right) { return left.value() % right; } + +/// CSSPixels: A position or length in CSS "reference pixels", independent of zoom or screen DPI. +/// See https://www.w3.org/TR/css-values-3/#reference-pixel +AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(float, CSSPixels, Arithmetic, CastToUnderlying, Comparison, Increment); + +template<Arithmetic T> +constexpr bool operator==(CSSPixels left, T right) { return left.value() == right; } + +template<Arithmetic T> +constexpr bool operator!=(CSSPixels left, T right) { return left.value() != right; } + +template<Arithmetic T> +constexpr bool operator>(CSSPixels left, T right) { return left.value() > right; } + +template<Arithmetic T> +constexpr bool operator<(CSSPixels left, T right) { return left.value() < right; } + +template<Arithmetic T> +constexpr bool operator>=(CSSPixels left, T right) { return left.value() >= right; } + +template<Arithmetic T> +constexpr bool operator<=(CSSPixels left, T right) { return left.value() <= right; } + +template<Arithmetic T> +constexpr CSSPixels operator*(CSSPixels left, T right) { return left.value() * right; } +template<Arithmetic T> +constexpr CSSPixels operator*(T left, CSSPixels right) { return right * left; } + +template<Arithmetic T> +constexpr CSSPixels operator/(CSSPixels left, T right) { return left.value() / right; } + +template<Arithmetic T> +constexpr CSSPixels operator%(CSSPixels left, T right) { return left.value() % right; } + +using CSSPixelLine = Gfx::Line<CSSPixels>; +using CSSPixelPoint = Gfx::Point<CSSPixels>; +using CSSPixelRect = Gfx::Rect<CSSPixels>; +using CSSPixelSize = Gfx::Size<CSSPixels>; + +using DevicePixelLine = Gfx::Line<DevicePixels>; +using DevicePixelPoint = Gfx::Point<DevicePixels>; +using DevicePixelRect = Gfx::Rect<DevicePixels>; +using DevicePixelSize = Gfx::Size<DevicePixels>; + +} + +constexpr Web::CSSPixels floor(Web::CSSPixels const& value) +{ + return ::floorf(value.value()); +} + +constexpr Web::CSSPixels ceil(Web::CSSPixels const& value) +{ + return ::ceilf(value.value()); +} + +constexpr Web::CSSPixels round(Web::CSSPixels const& value) +{ + return ::roundf(value.value()); +} + +constexpr Web::CSSPixels fmod(Web::CSSPixels const& x, Web::CSSPixels const& y) +{ + return ::fmodf(x.value(), y.value()); +} + +constexpr Web::CSSPixels abs(Web::CSSPixels const& value) +{ + return AK::abs(value.value()); +} + +constexpr Web::DevicePixels abs(Web::DevicePixels const& value) +{ + return AK::abs(value.value()); +} + +namespace AK { + +template<> +struct Traits<Web::CSSPixels> : public GenericTraits<Web::CSSPixels> { + static unsigned hash(Web::CSSPixels const& key) + { + return double_hash(key.value()); + } + + static bool equals(Web::CSSPixels const& a, Web::CSSPixels const& b) + { + return a == b; + } +}; + +template<> +struct Traits<Web::DevicePixels> : public GenericTraits<Web::DevicePixels> { + static unsigned hash(Web::DevicePixels const& key) + { + return double_hash(key.value()); + } + + static bool equals(Web::DevicePixels const& a, Web::DevicePixels const& b) + { + return a == b; + } +}; + +template<> +struct Formatter<Web::CSSPixels> : Formatter<float> { + ErrorOr<void> format(FormatBuilder& builder, Web::CSSPixels const& value) + { + return Formatter<float>::format(builder, value.value()); + } +}; + +template<> +struct Formatter<Web::DevicePixels> : Formatter<float> { + ErrorOr<void> format(FormatBuilder& builder, Web::DevicePixels const& value) + { + return Formatter<float>::format(builder, value.value()); + } +}; + +}
3d0786f96b9157b959409f43a8eb5312ec847e04
2021-05-22 14:21:00
Ali Mohammad Pur
meta: Add GDB pretty printer for AK::Variant
false
Add GDB pretty printer for AK::Variant
meta
diff --git a/Meta/serenity_gdb.py b/Meta/serenity_gdb.py index 7e3f7d1d7fea..5cd6aef5db98 100644 --- a/Meta/serenity_gdb.py +++ b/Meta/serenity_gdb.py @@ -40,6 +40,8 @@ def handler_class_for_type(type, re=re.compile('^([^<]+)(<.*>)?$')): return AKStringView elif klass == 'AK::StringImpl': return AKStringImpl + elif klass == 'AK::Variant': + return AKVariant elif klass == 'AK::Vector': return AKVector elif klass == 'VirtualAddress': @@ -186,6 +188,40 @@ def prettyprint_type(cls, type): return f'AK::RefPtr<{handler_class_for_type(contained_type).prettyprint_type(contained_type)}>' +class AKVariant: + def __init__(self, val): + self.val = val + self.index = int(self.val["m_index"]) + self.contained_types = self.resolve_types(self.val.type) + + def to_string(self): + return AKVariant.prettyprint_type(self.val.type) + + def children(self): + data = self.val["m_data"] + ty = self.contained_types[self.index] + return [(ty.name, data.cast(ty.pointer()).referenced_value())] + + @classmethod + def resolve_types(cls, ty): + contained_types = [] + type_resolved = ty.strip_typedefs() + index = 0 + while True: + try: + arg = type_resolved.template_argument(index) + index += 1 + contained_types.append(arg) + except RuntimeError: + break + return contained_types + + @classmethod + def prettyprint_type(cls, ty): + names = ", ".join(handler_class_for_type(t).prettyprint_type(t) for t in AKVariant.resolve_types(ty)) + return f'AK::Variant<{names}>' + + class AKVector: def __init__(self, val): self.val = val
3023a89e9b9c9fcd9f1eea87e707054013d70625
2020-07-31 03:59:26
Andreas Kling
kernel: Remove SmapDisabler in sys$setsockopt()
false
Remove SmapDisabler in sys$setsockopt()
kernel
diff --git a/Kernel/Net/IPv4Socket.cpp b/Kernel/Net/IPv4Socket.cpp index f38d3371f6b9..80c4d44c03a0 100644 --- a/Kernel/Net/IPv4Socket.cpp +++ b/Kernel/Net/IPv4Socket.cpp @@ -428,19 +428,23 @@ String IPv4Socket::absolute_path(const FileDescription&) const return builder.to_string(); } -KResult IPv4Socket::setsockopt(int level, int option, const void* value, socklen_t value_size) +KResult IPv4Socket::setsockopt(int level, int option, const void* user_value, socklen_t user_value_size) { if (level != IPPROTO_IP) - return Socket::setsockopt(level, option, value, value_size); + return Socket::setsockopt(level, option, user_value, user_value_size); switch (option) { - case IP_TTL: - if (value_size < sizeof(int)) + case IP_TTL: { + if (user_value_size < sizeof(int)) return KResult(-EINVAL); - if (*(const int*)value < 0 || *(const int*)value > 255) + int value; + if (!Process::current()->validate_read_and_copy_typed(&value, (const int*)user_value)) + return KResult(-EFAULT); + if (value < 0 || value > 255) return KResult(-EINVAL); - m_ttl = (u8) * (const int*)value; + m_ttl = value; return KSuccess; + } default: return KResult(-ENOPROTOOPT); } diff --git a/Kernel/Net/Socket.cpp b/Kernel/Net/Socket.cpp index 99c17d066ade..22c2022fb96c 100644 --- a/Kernel/Net/Socket.cpp +++ b/Kernel/Net/Socket.cpp @@ -101,24 +101,26 @@ KResult Socket::queue_connection_from(NonnullRefPtr<Socket> peer) return KSuccess; } -KResult Socket::setsockopt(int level, int option, const void* value, socklen_t value_size) +KResult Socket::setsockopt(int level, int option, const void* user_value, socklen_t user_value_size) { ASSERT(level == SOL_SOCKET); switch (option) { case SO_SNDTIMEO: - if (value_size != sizeof(timeval)) + if (user_value_size != sizeof(timeval)) return KResult(-EINVAL); - m_send_timeout = *(const timeval*)value; + copy_from_user(&m_send_timeout, (const timeval*)user_value); return KSuccess; case SO_RCVTIMEO: - if (value_size != sizeof(timeval)) + if (user_value_size != sizeof(timeval)) return KResult(-EINVAL); - m_receive_timeout = *(const timeval*)value; + copy_from_user(&m_receive_timeout, (const timeval*)user_value); return KSuccess; case SO_BINDTODEVICE: { - if (value_size != IFNAMSIZ) + if (user_value_size != IFNAMSIZ) return KResult(-EINVAL); - StringView ifname { (const char*)value }; + auto ifname = Process::current()->validate_and_copy_string_from_user((const char*)user_value, user_value_size); + if (ifname.is_null()) + return KResult(-EFAULT); auto device = NetworkAdapter::lookup_by_name(ifname); if (!device) return KResult(-ENODEV); diff --git a/Kernel/Syscalls/socket.cpp b/Kernel/Syscalls/socket.cpp index 9204abcfc967..c8eb20ff850b 100644 --- a/Kernel/Syscalls/socket.cpp +++ b/Kernel/Syscalls/socket.cpp @@ -317,29 +317,21 @@ int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params) return socket.getsockopt(*description, level, option, value, value_size); } -int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params) +int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* user_params) { - if (!validate_read_typed(params)) + Syscall::SC_setsockopt_params params; + if (!validate_read_and_copy_typed(&params, user_params)) return -EFAULT; - - SmapDisabler disabler; - - int sockfd = params->sockfd; - int level = params->level; - int option = params->option; - const void* value = params->value; - socklen_t value_size = params->value_size; - - if (!validate_read(value, value_size)) + if (!validate_read(params.value, params.value_size)) return -EFAULT; - auto description = file_description(sockfd); + auto description = file_description(params.sockfd); if (!description) return -EBADF; if (!description->is_socket()) return -ENOTSOCK; auto& socket = *description->socket(); REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain()); - return socket.setsockopt(level, option, value, value_size); + return socket.setsockopt(params.level, params.option, params.value, params.value_size); } }
30685a7714e1b18f7da48753769ac7ae0bc442c7
2020-12-16 00:10:06
Andreas Kling
libweb: Add equals() for LengthStyleValue and ColorStyleValue
false
Add equals() for LengthStyleValue and ColorStyleValue
libweb
diff --git a/Libraries/LibWeb/CSS/Length.h b/Libraries/LibWeb/CSS/Length.h index ec781aee6d29..ff1d2897b0ce 100644 --- a/Libraries/LibWeb/CSS/Length.h +++ b/Libraries/LibWeb/CSS/Length.h @@ -154,6 +154,16 @@ class Length { return String::format("[%g %s]", m_value, unit_name()); } + bool operator==(const Length& other) const + { + return m_type == other.m_type && m_value == other.m_value; + } + + bool operator!=(const Length& other) const + { + return !(*this == other); + } + private: float relative_length_to_px(const Layout::Node&) const; diff --git a/Libraries/LibWeb/CSS/StyleValue.h b/Libraries/LibWeb/CSS/StyleValue.h index 52b724c57c24..2fba93a98877 100644 --- a/Libraries/LibWeb/CSS/StyleValue.h +++ b/Libraries/LibWeb/CSS/StyleValue.h @@ -338,6 +338,13 @@ class LengthStyleValue : public StyleValue { virtual bool is_auto() const override { return m_length.is_auto(); } + virtual bool equals(const StyleValue& other) const override + { + if (type() != other.type()) + return false; + return m_length == static_cast<const LengthStyleValue&>(other).m_length; + } + private: explicit LengthStyleValue(const Length& length) : StyleValue(Type::Length) @@ -388,6 +395,13 @@ class ColorStyleValue : public StyleValue { String to_string() const override { return m_color.to_string(); } Color to_color(const DOM::Document&) const override { return m_color; } + virtual bool equals(const StyleValue& other) const override + { + if (type() != other.type()) + return false; + return m_color == static_cast<const ColorStyleValue&>(other).m_color; + } + private: explicit ColorStyleValue(Color color) : StyleValue(Type::Color)
19d4f4c7b54c0de0e6d13122b05f29f4810782ac
2019-12-29 04:28:52
Andreas Kling
libhtml: Add missing flock to Makefile (thanks jcs)
false
Add missing flock to Makefile (thanks jcs)
libhtml
diff --git a/Libraries/LibHTML/Makefile b/Libraries/LibHTML/Makefile index 6d21f5b68584..64f0d47324c8 100644 --- a/Libraries/LibHTML/Makefile +++ b/Libraries/LibHTML/Makefile @@ -90,7 +90,7 @@ CSS/PropertyID.cpp: CSS/Properties.json $(GENERATE_CSS_PROPERTYID_CPP) ResourceLoader.cpp: ../../Servers/ProtocolServer/ProtocolClientEndpoint.h ../../Servers/ProtocolServer/ProtocolClientEndpoint.h: - @$(MAKE) -C $(dir $(@)) + @flock ../../Servers/ProtocolServer $(MAKE) -C $(dir $(@)) EXTRA_CLEAN = CSS/DefaultStyleSheetSource.cpp CSS/PropertyID.h CSS/PropertyID.cpp
bfe081caadceaabf9104fbc464d15d705752a78f
2023-02-21 05:24:04
Andreas Kling
libgfx: Fix const-correctness issues
false
Fix const-correctness issues
libgfx
diff --git a/Userland/Libraries/LibGfx/BMPWriter.cpp b/Userland/Libraries/LibGfx/BMPWriter.cpp index 9b4a9c08ecbb..5bdbd1a2838b 100644 --- a/Userland/Libraries/LibGfx/BMPWriter.cpp +++ b/Userland/Libraries/LibGfx/BMPWriter.cpp @@ -42,7 +42,7 @@ class OutputStreamer { u8* m_data; }; -static ByteBuffer write_pixel_data(RefPtr<Bitmap> const bitmap, int pixel_row_data_size, int bytes_per_pixel, bool include_alpha_channel) +static ByteBuffer write_pixel_data(RefPtr<Bitmap const> bitmap, int pixel_row_data_size, int bytes_per_pixel, bool include_alpha_channel) { int image_size = pixel_row_data_size * bitmap->height(); auto buffer_result = ByteBuffer::create_uninitialized(image_size); @@ -78,7 +78,7 @@ static ByteBuffer compress_pixel_data(ByteBuffer const& pixel_data, BMPWriter::C VERIFY_NOT_REACHED(); } -ByteBuffer BMPWriter::dump(RefPtr<Bitmap> const bitmap, DibHeader dib_header) +ByteBuffer BMPWriter::dump(RefPtr<Bitmap const> bitmap, DibHeader dib_header) { switch (dib_header) { diff --git a/Userland/Libraries/LibGfx/BMPWriter.h b/Userland/Libraries/LibGfx/BMPWriter.h index 0dc3c2c0ba80..c9f9c0b8b334 100644 --- a/Userland/Libraries/LibGfx/BMPWriter.h +++ b/Userland/Libraries/LibGfx/BMPWriter.h @@ -27,7 +27,7 @@ class BMPWriter { V4 = 108, }; - ByteBuffer dump(RefPtr<Bitmap> const, DibHeader dib_header = DibHeader::V4); + ByteBuffer dump(RefPtr<Bitmap const>, DibHeader dib_header = DibHeader::V4); inline void set_compression(Compression compression) { m_compression = compression; } diff --git a/Userland/Libraries/LibGfx/Bitmap.cpp b/Userland/Libraries/LibGfx/Bitmap.cpp index 6e22d052d5a3..d1422db02d53 100644 --- a/Userland/Libraries/LibGfx/Bitmap.cpp +++ b/Userland/Libraries/LibGfx/Bitmap.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2021, Andreas Kling <[email protected]> + * Copyright (c) 2018-2023, Andreas Kling <[email protected]> * Copyright (c) 2022, Timothy Slater <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibGfx/Bitmap.h b/Userland/Libraries/LibGfx/Bitmap.h index 35627183f1e0..7d718395545e 100644 --- a/Userland/Libraries/LibGfx/Bitmap.h +++ b/Userland/Libraries/LibGfx/Bitmap.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2021, Andreas Kling <[email protected]> + * Copyright (c) 2018-2023, Andreas Kling <[email protected]> * Copyright (c) 2022, Timothy Slater <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause diff --git a/Userland/Libraries/LibGfx/Font/Font.h b/Userland/Libraries/LibGfx/Font/Font.h index 5e18cfd53b52..40ca2ac92a0c 100644 --- a/Userland/Libraries/LibGfx/Font/Font.h +++ b/Userland/Libraries/LibGfx/Font/Font.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, Stephan Unverwerth <[email protected]> + * Copyright (c) 2023, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -202,7 +203,7 @@ class Font : public RefCounted<Font> { Font const& bold_variant() const; private: - mutable RefPtr<Gfx::Font> m_bold_variant; + mutable RefPtr<Gfx::Font const> m_bold_variant; }; } diff --git a/Userland/Libraries/LibGfx/Font/ScaledFont.h b/Userland/Libraries/LibGfx/Font/ScaledFont.h index b87a5095b402..b0f4f9f17b99 100644 --- a/Userland/Libraries/LibGfx/Font/ScaledFont.h +++ b/Userland/Libraries/LibGfx/Font/ScaledFont.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2022, the SerenityOS developers. + * Copyright (c) 2023, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -33,7 +34,7 @@ class ScaledFont final : public Gfx::Font { // ^Gfx::Font virtual NonnullRefPtr<Font> clone() const override { return MUST(try_clone()); } // FIXME: clone() should not need to be implemented - virtual ErrorOr<NonnullRefPtr<Font>> try_clone() const override { return *this; } + virtual ErrorOr<NonnullRefPtr<Font>> try_clone() const override { return const_cast<ScaledFont&>(*this); } virtual u8 presentation_size() const override { return m_point_height; } virtual float pixel_size() const override { return m_point_height * 1.33333333f; } virtual Gfx::FontPixelMetrics pixel_metrics() const override; diff --git a/Userland/Libraries/LibGfx/Font/WOFF/Font.h b/Userland/Libraries/LibGfx/Font/WOFF/Font.h index 9bb8e55fd87c..dfd29cd80915 100644 --- a/Userland/Libraries/LibGfx/Font/WOFF/Font.h +++ b/Userland/Libraries/LibGfx/Font/WOFF/Font.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2022, the SerenityOS developers. + * Copyright (c) 2023, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -38,14 +39,14 @@ class Font : public Gfx::VectorFont { virtual bool is_fixed_width() const override { return m_input_font->is_fixed_width(); } private: - Font(NonnullRefPtr<Gfx::VectorFont> input_font, ByteBuffer input_font_buffer) + Font(NonnullRefPtr<Gfx::VectorFont const> input_font, ByteBuffer input_font_buffer) : m_input_font_buffer(move(input_font_buffer)) , m_input_font(move(input_font)) { } ByteBuffer m_input_font_buffer; - NonnullRefPtr<Gfx::VectorFont> m_input_font; + NonnullRefPtr<Gfx::VectorFont const> m_input_font; }; } diff --git a/Userland/Libraries/LibGfx/Palette.cpp b/Userland/Libraries/LibGfx/Palette.cpp index 5a3046e516d1..6426382bedf2 100644 --- a/Userland/Libraries/LibGfx/Palette.cpp +++ b/Userland/Libraries/LibGfx/Palette.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2018-2023, Andreas Kling <[email protected]> * Copyright (c) 2021, Sam Atkins <[email protected]> * Copyright (c) 2022, Filiph Sandström <[email protected]> * @@ -22,7 +22,7 @@ PaletteImpl::PaletteImpl(Core::AnonymousBuffer buffer) { } -Palette::Palette(PaletteImpl const& impl) +Palette::Palette(PaletteImpl& impl) : m_impl(impl) { } diff --git a/Userland/Libraries/LibGfx/Palette.h b/Userland/Libraries/LibGfx/Palette.h index 1b99332e6b43..b2e20efbfd4c 100644 --- a/Userland/Libraries/LibGfx/Palette.h +++ b/Userland/Libraries/LibGfx/Palette.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2020, Andreas Kling <[email protected]> + * Copyright (c) 2018-2023, Andreas Kling <[email protected]> * Copyright (c) 2021, Sam Atkins <[email protected]> * Copyright (c) 2022, Filiph Sandström <[email protected]> * @@ -59,7 +59,7 @@ class PaletteImpl : public RefCounted<PaletteImpl> { class Palette { public: - explicit Palette(PaletteImpl const&); + explicit Palette(PaletteImpl&); ~Palette() = default; Color accent() const { return color(ColorRole::Accent); }
dbc2f7ed48f00234f5f94a30b06b83842d9cf4dd
2024-07-17 14:50:11
Braydn
libjs: Implement CreatePerIterationEnvironment for 'for' statements
false
Implement CreatePerIterationEnvironment for 'for' statements
libjs
diff --git a/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp b/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp index 5be01c2fc193..887b24d33dd2 100644 --- a/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp +++ b/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp @@ -981,6 +981,7 @@ Bytecode::CodeGenerationErrorOr<Optional<ScopedOperand>> ForStatement::generate_ Bytecode::BasicBlock* update_block_ptr { nullptr }; bool has_lexical_environment = false; + Vector<IdentifierTableIndex> per_iteration_bindings; if (m_init) { if (m_init->is_variable_declaration()) { @@ -994,8 +995,7 @@ Bytecode::CodeGenerationErrorOr<Optional<ScopedOperand>> ForStatement::generate_ if (variable_declaration.is_lexical_declaration() && has_non_local_variables) { has_lexical_environment = true; - - // FIXME: Is Block correct? + // Setup variable scope for bound identifiers generator.begin_variable_scope(); bool is_const = variable_declaration.is_constant_declaration(); @@ -1005,6 +1005,9 @@ Bytecode::CodeGenerationErrorOr<Optional<ScopedOperand>> ForStatement::generate_ return; auto index = generator.intern_identifier(identifier.string()); generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_const); + if (!is_const) { + per_iteration_bindings.append(index); + } })); } } @@ -1012,6 +1015,36 @@ Bytecode::CodeGenerationErrorOr<Optional<ScopedOperand>> ForStatement::generate_ (void)TRY(m_init->generate_bytecode(generator)); } + // CreatePerIterationEnvironment (https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-createperiterationenvironment) + auto generate_per_iteration_bindings = [&per_iteration_bindings = static_cast<Vector<IdentifierTableIndex> const&>(per_iteration_bindings), + &generator]() { + if (per_iteration_bindings.is_empty()) { + return; + } + + // Copy all the last values into registers for use in step 1.e.iii + // Register copies of bindings are required since the changing of the + // running execution context in the final step requires leaving the + // current variable scope before creating "thisIterationEnv" + Vector<ScopedOperand> registers; + for (auto const& binding : per_iteration_bindings) { + auto reg = generator.allocate_register(); + generator.emit<Bytecode::Op::GetBinding>(reg, binding); + registers.append(reg); + } + + generator.end_variable_scope(); + generator.begin_variable_scope(); + + for (size_t i = 0; i < per_iteration_bindings.size(); ++i) { + generator.emit<Bytecode::Op::CreateVariable>(per_iteration_bindings[i], Bytecode::Op::EnvironmentMode::Lexical, false); + generator.emit<Bytecode::Op::InitializeLexicalBinding>(per_iteration_bindings[i], registers[i]); + } + }; + + // CreatePerIterationEnvironment where lastIterationEnv is the variable + // scope created above for bound identifiers + generate_per_iteration_bindings(); body_block_ptr = &generator.make_block(); if (m_update) @@ -1049,6 +1082,9 @@ Bytecode::CodeGenerationErrorOr<Optional<ScopedOperand>> ForStatement::generate_ generator.end_breakable_scope(); generator.end_continuable_scope(); + // CreatePerIterationEnvironment where lastIterationEnv is the environment + // created by the previous CreatePerIterationEnvironment setup + generate_per_iteration_bindings(); if (!generator.is_current_block_terminated()) { if (m_update) { generator.emit<Bytecode::Op::Jump>(Bytecode::Label { *update_block_ptr }); @@ -1059,6 +1095,9 @@ Bytecode::CodeGenerationErrorOr<Optional<ScopedOperand>> ForStatement::generate_ generator.switch_to_basic_block(end_block); + // Leave the environment setup by CreatePerIterationEnvironment or if there + // are no perIterationBindings the variable scope created for bound + // identifiers if (has_lexical_environment) generator.end_variable_scope(); diff --git a/Userland/Libraries/LibJS/Tests/loops/for-scopes.js b/Userland/Libraries/LibJS/Tests/loops/for-scopes.js index 2f89bd122970..d3a7e645c84a 100644 --- a/Userland/Libraries/LibJS/Tests/loops/for-scopes.js +++ b/Userland/Libraries/LibJS/Tests/loops/for-scopes.js @@ -16,3 +16,19 @@ test("const in for head", () => { c; }).toThrowWithMessage(ReferenceError, "'c' is not defined"); }); + +test("let variables captured by value", () => { + let result = ""; + let functionList = []; + for (let i = 0; i < 9; i++) { + result += i; + functionList.push(function () { + return i; + }); + } + for (let i = 0; i < functionList.length; i++) { + result += functionList[i](); + } + + expect(result).toEqual("012345678012345678"); +});
41f3817b36f4dd08f3d3ce612adfd6bad2a59950
2020-03-19 00:35:52
Andreas Kling
libweb: Use a JS::Handle to keep the EventListener function alive
false
Use a JS::Handle to keep the EventListener function alive
libweb
diff --git a/Libraries/LibWeb/Bindings/EventListenerWrapper.cpp b/Libraries/LibWeb/Bindings/EventListenerWrapper.cpp index d01d5fa15b95..0948d29d45a3 100644 --- a/Libraries/LibWeb/Bindings/EventListenerWrapper.cpp +++ b/Libraries/LibWeb/Bindings/EventListenerWrapper.cpp @@ -14,11 +14,5 @@ EventListenerWrapper::~EventListenerWrapper() { } -void EventListenerWrapper::visit_children(JS::Cell::Visitor& visitor) -{ - Wrapper::visit_children(visitor); - visitor.visit(impl().function()); -} - } } diff --git a/Libraries/LibWeb/Bindings/EventListenerWrapper.h b/Libraries/LibWeb/Bindings/EventListenerWrapper.h index c3a3bcc86d87..c04927581618 100644 --- a/Libraries/LibWeb/Bindings/EventListenerWrapper.h +++ b/Libraries/LibWeb/Bindings/EventListenerWrapper.h @@ -41,7 +41,6 @@ class EventListenerWrapper final : public Wrapper { private: virtual const char* class_name() const override { return "EventListenerWrapper"; } - virtual void visit_children(JS::Cell::Visitor&) override; NonnullRefPtr<EventListener> m_impl; }; diff --git a/Libraries/LibWeb/Bindings/EventTargetWrapper.cpp b/Libraries/LibWeb/Bindings/EventTargetWrapper.cpp index 0d92f395e4c5..0d30ec086f1f 100644 --- a/Libraries/LibWeb/Bindings/EventTargetWrapper.cpp +++ b/Libraries/LibWeb/Bindings/EventTargetWrapper.cpp @@ -18,8 +18,8 @@ EventTargetWrapper::EventTargetWrapper(EventTarget& impl) auto event_name = arguments[0].to_string(); ASSERT(arguments[1].is_object()); ASSERT(arguments[1].as_object()->is_function()); - auto listener = adopt(*new EventListener(static_cast<JS::Function*>(const_cast<Object*>(arguments[1].as_object())))); - wrap(this_object->heap(), *listener); + auto* function = static_cast<JS::Function*>(const_cast<Object*>(arguments[1].as_object())); + auto listener = adopt(*new EventListener(JS::make_handle(function))); static_cast<EventTargetWrapper*>(this_object)->impl().add_event_listener(event_name, move(listener)); return JS::js_undefined(); }); diff --git a/Libraries/LibWeb/DOM/EventListener.cpp b/Libraries/LibWeb/DOM/EventListener.cpp index e69de29bb2d1..4cad68964ab4 100644 --- a/Libraries/LibWeb/DOM/EventListener.cpp +++ b/Libraries/LibWeb/DOM/EventListener.cpp @@ -0,0 +1,11 @@ +#include <LibJS/Runtime/Function.h> +#include <LibWeb/DOM/EventListener.h> + +namespace Web { + +JS::Function* EventListener::function() +{ + return m_function.cell(); +} + +} diff --git a/Libraries/LibWeb/DOM/EventListener.h b/Libraries/LibWeb/DOM/EventListener.h index e6e3a8ede9d9..1c32d919b715 100644 --- a/Libraries/LibWeb/DOM/EventListener.h +++ b/Libraries/LibWeb/DOM/EventListener.h @@ -1,7 +1,7 @@ #pragma once #include <AK/RefCounted.h> -#include <LibJS/Forward.h> +#include <LibJS/Heap/Handle.h> #include <LibWeb/Bindings/Wrappable.h> namespace Web { @@ -12,15 +12,15 @@ class EventListener public: using WrapperType = Bindings::EventListenerWrapper; - explicit EventListener(JS::Function* function) - : m_function(function) + explicit EventListener(JS::Handle<JS::Function> function) + : m_function(move(function)) { } - JS::Function* function() { return m_function; } + JS::Function* function(); private: - JS::Function* m_function { nullptr }; + JS::Handle<JS::Function> m_function; }; }
2de843692cfd844609cef5a65dd36627a42f85f6
2020-04-18 23:14:57
Andreas Kling
base: Tweak Redmond 2000 menu selection color
false
Tweak Redmond 2000 menu selection color
base
diff --git a/Base/res/themes/Redmond 2000.ini b/Base/res/themes/Redmond 2000.ini index fbd0774ef624..939ee2d1d066 100644 --- a/Base/res/themes/Redmond 2000.ini +++ b/Base/res/themes/Redmond 2000.ini @@ -15,7 +15,7 @@ HighlightWindowTitle=white MenuBase=white MenuBaseText=black MenuStripe=#bbb7b0 -MenuSelection=#ad714f +MenuSelection=#4f71ad MenuSelectionText=white Window=#d4d0c8 WindowText=black
dd582e4ae3994f98754e255ad8890d0128cf737d
2023-01-15 23:41:25
Tim Ledbetter
pixelpaint: Hold shift to increase move tool speed with the arrow keys
false
Hold shift to increase move tool speed with the arrow keys
pixelpaint
diff --git a/Userland/Applications/PixelPaint/Tools/MoveTool.cpp b/Userland/Applications/PixelPaint/Tools/MoveTool.cpp index bbe9900a6d2f..1559b93f9637 100644 --- a/Userland/Applications/PixelPaint/Tools/MoveTool.cpp +++ b/Userland/Applications/PixelPaint/Tools/MoveTool.cpp @@ -141,7 +141,7 @@ bool MoveTool::on_keydown(GUI::KeyEvent& event) if (m_scaling) return true; - if (event.modifiers() != 0) + if (!(event.modifiers() == Mod_None || event.modifiers() == Mod_Shift)) return false; auto* layer = m_editor->active_layer(); @@ -149,19 +149,19 @@ bool MoveTool::on_keydown(GUI::KeyEvent& event) return false; auto new_location = layer->location(); - + auto speed = event.shift() ? 10 : 1; switch (event.key()) { case Key_Up: - new_location.translate_by(0, -1); + new_location.translate_by(0, -speed); break; case Key_Down: - new_location.translate_by(0, 1); + new_location.translate_by(0, speed); break; case Key_Left: - new_location.translate_by(-1, 0); + new_location.translate_by(-speed, 0); break; case Key_Right: - new_location.translate_by(1, 0); + new_location.translate_by(speed, 0); break; default: return false;
ea67f373482c8f63a3af835d276ca73dc3ae8faf
2025-01-17 13:38:15
Tim Ledbetter
meta: Support importing WPT crash tests
false
Support importing WPT crash tests
meta
diff --git a/Meta/import-wpt-test.py b/Meta/import-wpt-test.py index c2d77aac567a..6e0c53f8c907 100755 --- a/Meta/import-wpt-test.py +++ b/Meta/import-wpt-test.py @@ -5,7 +5,7 @@ from enum import Enum from html.parser import HTMLParser from pathlib import Path -from urllib.parse import urljoin +from urllib.parse import urljoin, urlparse from urllib.request import urlopen import re import os @@ -17,6 +17,7 @@ class TestType(Enum): TEXT = 1, 'Tests/LibWeb/Text/input/wpt-import', 'Tests/LibWeb/Text/expected/wpt-import' REF = 2, 'Tests/LibWeb/Ref/input/wpt-import', 'Tests/LibWeb/Ref/expected/wpt-import' + CRASH = 3, 'Tests/LibWeb/Crash/wpt-import', '' def __new__(cls, *args, **kwds): obj = object.__new__(cls) @@ -130,6 +131,21 @@ def map_to_path(sources: list[ResourceAndType], is_resource=True, resource_path= return filepaths +def is_crash_test(url_string): + # https://web-platform-tests.org/writing-tests/crashtest.html + # A test file is treated as a crash test if they have -crash in their name before the file extension, or they are + # located in a folder named crashtests + parsed_url = urlparse(url_string) + path_segments = parsed_url.path.strip('/').split('/') + if len(path_segments) > 1 and "crashtests" in path_segments[::-1]: + return True + file_name = path_segments[-1] + file_name_parts = file_name.split('.') + if len(file_name_parts) > 1 and any([part.endswith('-crash') for part in file_name_parts[:-1]]): + return True + return False + + def modify_sources(files, resources: list[ResourceAndType]) -> None: for file in files: # Get the distance to the wpt-imports folder @@ -191,7 +207,7 @@ def download_files(filepaths): def create_expectation_files(files): # Ref tests don't have an expectation text file - if test_type == TestType.REF: + if test_type in [TestType.REF, TestType.CRASH]: return for file in files: @@ -219,10 +235,14 @@ def main(): page = response.read().decode("utf-8") global test_type, reference_path, raw_reference_path - identifier = TestTypeIdentifier(url_to_import) - identifier.feed(page) - test_type = identifier.test_type - raw_reference_path = identifier.reference_path + if is_crash_test(url_to_import): + test_type = TestType.CRASH + else: + identifier = TestTypeIdentifier(url_to_import) + identifier.feed(page) + test_type = identifier.test_type + raw_reference_path = identifier.reference_path + print(f"Identified {url_to_import} as type {test_type}, ref {raw_reference_path}") main_file = [ResourceAndType(resource_path, ResourceType.INPUT)]
821e875bc0f18d16fc3401e361c9368ccb19416f
2020-11-03 21:17:56
AnotherTest
spreadsheet: Serialise Positions to URLs and add Sheet::from_uri()
false
Serialise Positions to URLs and add Sheet::from_uri()
spreadsheet
diff --git a/Applications/Spreadsheet/Position.h b/Applications/Spreadsheet/Position.h index 358ab9c1f614..af7d7f70a941 100644 --- a/Applications/Spreadsheet/Position.h +++ b/Applications/Spreadsheet/Position.h @@ -28,6 +28,7 @@ #include <AK/String.h> #include <AK/Types.h> +#include <AK/URL.h> namespace Spreadsheet { @@ -44,6 +45,16 @@ struct Position { { return !(other == *this); } + + URL to_url() const + { + URL url; + url.set_protocol("spreadsheet"); + url.set_host("cell"); + url.set_path(String::formatted("/{}", getpid())); + url.set_fragment(String::formatted("{}{}", column, row)); + return url; + } }; } diff --git a/Applications/Spreadsheet/Spreadsheet.cpp b/Applications/Spreadsheet/Spreadsheet.cpp index e306a0fbc6b1..309b9c10c848 100644 --- a/Applications/Spreadsheet/Spreadsheet.cpp +++ b/Applications/Spreadsheet/Spreadsheet.cpp @@ -32,6 +32,7 @@ #include <AK/JsonObject.h> #include <AK/JsonParser.h> #include <AK/TemporaryChange.h> +#include <AK/URL.h> #include <LibCore/File.h> #include <LibJS/Parser.h> #include <LibJS/Runtime/Function.h> @@ -202,6 +203,24 @@ Optional<Position> Sheet::parse_cell_name(const StringView& name) return Position { col, row.to_uint().value() }; } +Cell* Sheet::from_url(const URL& url) +{ + if (!url.is_valid()) { + dbgln("Invalid url: {}", url.to_string()); + return nullptr; + } + + if (url.protocol() != "spreadsheet" || url.host() != "cell") { + dbgln("Bad url: {}", url.to_string()); + return nullptr; + } + + // FIXME: Figure out a way to do this cross-process. + ASSERT(url.path() == String::formatted("/{}", getpid())); + + return at(url.fragment()); +} + RefPtr<Sheet> Sheet::from_json(const JsonObject& object, Workbook& workbook) { auto sheet = adopt(*new Sheet(workbook)); diff --git a/Applications/Spreadsheet/Spreadsheet.h b/Applications/Spreadsheet/Spreadsheet.h index c210f40bc3f5..4f1c3f2110b2 100644 --- a/Applications/Spreadsheet/Spreadsheet.h +++ b/Applications/Spreadsheet/Spreadsheet.h @@ -49,6 +49,9 @@ class Sheet : public Core::Object { static Optional<Position> parse_cell_name(const StringView&); + Cell* from_url(const URL&); + const Cell* from_url(const URL& url) const { return const_cast<Sheet*>(this)->from_url(url); } + JsonObject to_json() const; static RefPtr<Sheet> from_json(const JsonObject&, Workbook&);
a95f761cb445f08812d594dc8c970fba4a550d3e
2024-11-20 03:02:11
Andrew Kaster
ak: Include missing StdLibExtras from NeverDestroyed
false
Include missing StdLibExtras from NeverDestroyed
ak
diff --git a/AK/NeverDestroyed.h b/AK/NeverDestroyed.h index 48dfde179873..7c4d57ea9e8d 100644 --- a/AK/NeverDestroyed.h +++ b/AK/NeverDestroyed.h @@ -7,6 +7,7 @@ #pragma once #include <AK/Noncopyable.h> +#include <AK/StdLibExtras.h> #include <AK/Types.h> namespace AK {
6772d442e5c5c68785f03e82a5f5762b3c83ce58
2024-07-18 14:13:38
Andrew Kaster
libaudio: Prefix AK::Duration with AK Namespace
false
Prefix AK::Duration with AK Namespace
libaudio
diff --git a/Userland/Libraries/LibAudio/PlaybackStream.h b/Userland/Libraries/LibAudio/PlaybackStream.h index 0162711d9b2f..847859ee03c9 100644 --- a/Userland/Libraries/LibAudio/PlaybackStream.h +++ b/Userland/Libraries/LibAudio/PlaybackStream.h @@ -52,7 +52,7 @@ class PlaybackStream : public AtomicRefCounted<PlaybackStream> { // // The value provided to the promise resolution will match the `total_time_played()` at the exact moment that // the stream was resumed. - virtual NonnullRefPtr<Core::ThreadedPromise<Duration>> resume() = 0; + virtual NonnullRefPtr<Core::ThreadedPromise<AK::Duration>> resume() = 0; // Completes playback of any buffered audio data and then suspends playback and buffering. virtual NonnullRefPtr<Core::ThreadedPromise<void>> drain_buffer_and_suspend() = 0; // Drops any buffered audio data and then suspends playback and buffering. This can used be to stop playback @@ -64,7 +64,7 @@ class PlaybackStream : public AtomicRefCounted<PlaybackStream> { // whenever possible. // // This function should be able to run from any thread safely. - virtual ErrorOr<Duration> total_time_played() = 0; + virtual ErrorOr<AK::Duration> total_time_played() = 0; virtual NonnullRefPtr<Core::ThreadedPromise<void>> set_volume(double volume) = 0; }; diff --git a/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.cpp b/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.cpp index 88a3d16bee9e..56b2d3997b5b 100644 --- a/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.cpp +++ b/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.cpp @@ -42,14 +42,14 @@ struct AudioTask { Volume, }; - void resolve(Duration time) + void resolve(AK::Duration time) { promise.visit( [](Empty) { VERIFY_NOT_REACHED(); }, [&](NonnullRefPtr<Core::ThreadedPromise<void>>& promise) { promise->resolve(); }, - [&](NonnullRefPtr<Core::ThreadedPromise<Duration>>& promise) { + [&](NonnullRefPtr<Core::ThreadedPromise<AK::Duration>>& promise) { promise->resolve(move(time)); }); } @@ -66,7 +66,7 @@ struct AudioTask { } Type type; - Variant<Empty, NonnullRefPtr<Core::ThreadedPromise<void>>, NonnullRefPtr<Core::ThreadedPromise<Duration>>> promise; + Variant<Empty, NonnullRefPtr<Core::ThreadedPromise<void>>, NonnullRefPtr<Core::ThreadedPromise<AK::Duration>>> promise; Optional<double> data {}; }; @@ -128,9 +128,9 @@ class AudioState : public RefCounted<AudioState> { }); } - Duration last_sample_time() const + AK::Duration last_sample_time() const { - return Duration::from_milliseconds(m_last_sample_time.load()); + return AK::Duration::from_milliseconds(m_last_sample_time.load()); } private: @@ -182,7 +182,7 @@ class AudioState : public RefCounted<AudioState> { } if (error == noErr) - task.resolve(Duration::from_milliseconds(last_sample_time)); + task.resolve(AK::Duration::from_milliseconds(last_sample_time)); else task.reject(error); } @@ -248,9 +248,9 @@ void PlaybackStreamAudioUnit::set_underrun_callback(Function<void()>) // FIXME: Implement this. } -NonnullRefPtr<Core::ThreadedPromise<Duration>> PlaybackStreamAudioUnit::resume() +NonnullRefPtr<Core::ThreadedPromise<AK::Duration>> PlaybackStreamAudioUnit::resume() { - auto promise = Core::ThreadedPromise<Duration>::create(); + auto promise = Core::ThreadedPromise<AK::Duration>::create(); AudioTask task { AudioTask::Type::Play, promise }; if (auto result = m_state->queue_task(move(task)); result.is_error()) @@ -281,7 +281,7 @@ NonnullRefPtr<Core::ThreadedPromise<void>> PlaybackStreamAudioUnit::discard_buff return promise; } -ErrorOr<Duration> PlaybackStreamAudioUnit::total_time_played() +ErrorOr<AK::Duration> PlaybackStreamAudioUnit::total_time_played() { return m_state->last_sample_time(); } diff --git a/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.h b/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.h index 3bb11eb1fa2c..c4650147ba82 100644 --- a/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.h +++ b/Userland/Libraries/LibAudio/PlaybackStreamAudioUnit.h @@ -21,11 +21,11 @@ class PlaybackStreamAudioUnit final : public PlaybackStream { virtual void set_underrun_callback(Function<void()>) override; - virtual NonnullRefPtr<Core::ThreadedPromise<Duration>> resume() override; + virtual NonnullRefPtr<Core::ThreadedPromise<AK::Duration>> resume() override; virtual NonnullRefPtr<Core::ThreadedPromise<void>> drain_buffer_and_suspend() override; virtual NonnullRefPtr<Core::ThreadedPromise<void>> discard_buffer_and_suspend() override; - virtual ErrorOr<Duration> total_time_played() override; + virtual ErrorOr<AK::Duration> total_time_played() override; virtual NonnullRefPtr<Core::ThreadedPromise<void>> set_volume(double) override; diff --git a/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.cpp b/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.cpp index 89ae851338dc..4cb440751d3c 100644 --- a/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.cpp +++ b/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.cpp @@ -77,9 +77,9 @@ void PlaybackStreamPulseAudio::set_underrun_callback(Function<void()> callback) }); } -NonnullRefPtr<Core::ThreadedPromise<Duration>> PlaybackStreamPulseAudio::resume() +NonnullRefPtr<Core::ThreadedPromise<AK::Duration>> PlaybackStreamPulseAudio::resume() { - auto promise = Core::ThreadedPromise<Duration>::create(); + auto promise = Core::ThreadedPromise<AK::Duration>::create(); TRY_OR_REJECT(m_state->check_is_running(), promise); m_state->enqueue([this, promise]() { TRY_OR_REJECT(m_state->stream()->resume()); @@ -110,11 +110,11 @@ NonnullRefPtr<Core::ThreadedPromise<void>> PlaybackStreamPulseAudio::discard_buf return promise; } -ErrorOr<Duration> PlaybackStreamPulseAudio::total_time_played() +ErrorOr<AK::Duration> PlaybackStreamPulseAudio::total_time_played() { if (m_state->stream() != nullptr) return m_state->stream()->total_time_played(); - return Duration::zero(); + return AK::Duration::zero(); } NonnullRefPtr<Core::ThreadedPromise<void>> PlaybackStreamPulseAudio::set_volume(double volume) diff --git a/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.h b/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.h index d1671944557d..7b6dcc20a823 100644 --- a/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.h +++ b/Userland/Libraries/LibAudio/PlaybackStreamPulseAudio.h @@ -18,11 +18,11 @@ class PlaybackStreamPulseAudio final virtual void set_underrun_callback(Function<void()>) override; - virtual NonnullRefPtr<Core::ThreadedPromise<Duration>> resume() override; + virtual NonnullRefPtr<Core::ThreadedPromise<AK::Duration>> resume() override; virtual NonnullRefPtr<Core::ThreadedPromise<void>> drain_buffer_and_suspend() override; virtual NonnullRefPtr<Core::ThreadedPromise<void>> discard_buffer_and_suspend() override; - virtual ErrorOr<Duration> total_time_played() override; + virtual ErrorOr<AK::Duration> total_time_played() override; virtual NonnullRefPtr<Core::ThreadedPromise<void>> set_volume(double) override; diff --git a/Userland/Libraries/LibAudio/PulseAudioWrappers.cpp b/Userland/Libraries/LibAudio/PulseAudioWrappers.cpp index 1c51475716c7..48d762850c8d 100644 --- a/Userland/Libraries/LibAudio/PulseAudioWrappers.cpp +++ b/Userland/Libraries/LibAudio/PulseAudioWrappers.cpp @@ -452,7 +452,7 @@ ErrorOr<void> PulseAudioStream::resume() return {}; } -ErrorOr<Duration> PulseAudioStream::total_time_played() +ErrorOr<AK::Duration> PulseAudioStream::total_time_played() { auto locker = m_context->main_loop_locker(); @@ -465,19 +465,19 @@ ErrorOr<Duration> PulseAudioStream::total_time_played() // last-returned time. If we never call pa_stream_get_time() until after giving // the stream its first samples, the issue never occurs. if (!m_started_playback) - return Duration::zero(); + return AK::Duration::zero(); pa_usec_t time = 0; auto error = pa_stream_get_time(m_stream, &time); if (error == -PA_ERR_NODATA) - return Duration::zero(); + return AK::Duration::zero(); if (error != 0) return Error::from_string_literal("Failed to get time from PulseAudio stream"); if (time > NumericLimits<i64>::max()) { warnln("WARNING: Audio time is too large!"); time -= NumericLimits<i64>::max(); } - return Duration::from_microseconds(static_cast<i64>(time)); + return AK::Duration::from_microseconds(static_cast<i64>(time)); } ErrorOr<void> PulseAudioStream::set_volume(double volume) diff --git a/Userland/Libraries/LibAudio/PulseAudioWrappers.h b/Userland/Libraries/LibAudio/PulseAudioWrappers.h index 64e04f1eab9e..ed445c89df6a 100644 --- a/Userland/Libraries/LibAudio/PulseAudioWrappers.h +++ b/Userland/Libraries/LibAudio/PulseAudioWrappers.h @@ -118,7 +118,7 @@ class PulseAudioStream : public AtomicRefCounted<PulseAudioStream> { // Uncorks the stream and forces data to be written to the buffers to force playback to // resume as soon as possible. ErrorOr<void> resume(); - ErrorOr<Duration> total_time_played(); + ErrorOr<AK::Duration> total_time_played(); ErrorOr<void> set_volume(double volume);
1af9e441309efd31a524fab0d7b0378338743148
2024-06-08 11:28:11
Andrew Kaster
cmake: Use CMAKE_LINKER_TYPE on CMake >= 3.29
false
Use CMAKE_LINKER_TYPE on CMake >= 3.29
cmake
diff --git a/Meta/CMake/use_linker.cmake b/Meta/CMake/use_linker.cmake index 9a722b99ca42..e7186f83b561 100644 --- a/Meta/CMake/use_linker.cmake +++ b/Meta/CMake/use_linker.cmake @@ -19,8 +19,14 @@ if (NOT APPLE AND NOT LAGOM_USE_LINKER) endif() if (LAGOM_USE_LINKER) - set(LINKER_FLAG "-fuse-ld=${LAGOM_USE_LINKER}") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${LINKER_FLAG}") - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LINKER_FLAG}") - set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LINKER_FLAG}") + # FIXME: Move to only setting CMAKE_LINKER_TYPE once we drop support for CMake < 3.29 + if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.29) + string(TOUPPER ${LAGOM_USE_LINKER} linker_type) + set(CMAKE_LINKER_TYPE ${linker_type}) + else() + set(LINKER_FLAG "-fuse-ld=${LAGOM_USE_LINKER}") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${LINKER_FLAG}") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LINKER_FLAG}") + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LINKER_FLAG}") + endif() endif()
4e7d307166c1589737cff2d5df48dcec676afc66
2022-01-12 19:39:09
Idan Horowitz
kernel: Convert Mount::absolute_path to ErrorOr<NonnullOwnPtr<KString>>
false
Convert Mount::absolute_path to ErrorOr<NonnullOwnPtr<KString>>
kernel
diff --git a/Kernel/FileSystem/Mount.cpp b/Kernel/FileSystem/Mount.cpp index 1f05f36c8167..e934d2eb711b 100644 --- a/Kernel/FileSystem/Mount.cpp +++ b/Kernel/FileSystem/Mount.cpp @@ -27,11 +27,11 @@ Mount::Mount(Inode& source, Custody& host_custody, int flags) { } -String Mount::absolute_path() const +ErrorOr<NonnullOwnPtr<KString>> Mount::absolute_path() const { if (!m_host_custody) - return "/"; - return m_host_custody->absolute_path(); + return KString::try_create("/"sv); + return m_host_custody->try_serialize_absolute_path(); } Inode* Mount::host() diff --git a/Kernel/FileSystem/Mount.h b/Kernel/FileSystem/Mount.h index 065f2766fee6..7fdf67f0c976 100644 --- a/Kernel/FileSystem/Mount.h +++ b/Kernel/FileSystem/Mount.h @@ -26,7 +26,7 @@ class Mount { FileSystem const& guest_fs() const { return *m_guest_fs; } FileSystem& guest_fs() { return *m_guest_fs; } - String absolute_path() const; + ErrorOr<NonnullOwnPtr<KString>> absolute_path() const; int flags() const { return m_flags; } void set_flags(int flags) { m_flags = flags; } diff --git a/Kernel/GlobalProcessExposed.cpp b/Kernel/GlobalProcessExposed.cpp index 94009c676229..378e73e1e1ac 100644 --- a/Kernel/GlobalProcessExposed.cpp +++ b/Kernel/GlobalProcessExposed.cpp @@ -358,7 +358,12 @@ class ProcFSDiskUsage final : public ProcFSGlobalInformation { fs_object.add("free_block_count", fs.free_block_count()); fs_object.add("total_inode_count", fs.total_inode_count()); fs_object.add("free_inode_count", fs.free_inode_count()); - fs_object.add("mount_point", mount.absolute_path()); + auto mount_point_or_error = mount.absolute_path(); + if (mount_point_or_error.is_error()) { + result = mount_point_or_error.release_error(); + return IterationDecision::Break; + } + fs_object.add("mount_point", mount_point_or_error.value()->view()); fs_object.add("block_size", static_cast<u64>(fs.block_size())); fs_object.add("readonly", fs.is_readonly()); fs_object.add("mount_flags", mount.flags());
5744dd43c5291c88b3366b00c73c15f919389b2b
2020-06-24 14:38:46
Andreas Kling
libweb: Remove default Length constructor and add make_auto()/make_px()
false
Remove default Length constructor and add make_auto()/make_px()
libweb
diff --git a/Libraries/LibWeb/CSS/Length.h b/Libraries/LibWeb/CSS/Length.h index d290b714d785..f531ace3a07f 100644 --- a/Libraries/LibWeb/CSS/Length.h +++ b/Libraries/LibWeb/CSS/Length.h @@ -40,7 +40,6 @@ class Length { Rem, }; - Length() { } Length(int value, Type type) : m_type(type) , m_value(value) @@ -52,6 +51,9 @@ class Length { { } + static Length make_auto() { return Length(0, Type::Auto); } + static Length make_px(float value) { return Length(value, Type::Px); } + bool is_auto() const { return m_type == Type::Auto; } bool is_absolute() const { return m_type == Type::Px; } bool is_relative() const { return m_type == Type::Em || m_type == Type::Rem; } diff --git a/Libraries/LibWeb/CSS/LengthBox.h b/Libraries/LibWeb/CSS/LengthBox.h index 230babd4834f..7c983d9ed7d0 100644 --- a/Libraries/LibWeb/CSS/LengthBox.h +++ b/Libraries/LibWeb/CSS/LengthBox.h @@ -31,10 +31,10 @@ namespace Web { struct LengthBox { - Length top; - Length right; - Length bottom; - Length left; + Length top { Length::make_auto() }; + Length right { Length::make_auto() }; + Length bottom { Length::make_auto() }; + Length left { Length::make_auto() }; }; } diff --git a/Libraries/LibWeb/CSS/StyleProperties.cpp b/Libraries/LibWeb/CSS/StyleProperties.cpp index b0e184171b81..6683ecb12be1 100644 --- a/Libraries/LibWeb/CSS/StyleProperties.cpp +++ b/Libraries/LibWeb/CSS/StyleProperties.cpp @@ -179,7 +179,7 @@ void StyleProperties::load_font() const float StyleProperties::line_height(const LayoutNode& layout_node) const { - auto line_height_length = length_or_fallback(CSS::PropertyID::LineHeight, {}); + auto line_height_length = length_or_fallback(CSS::PropertyID::LineHeight, Length::make_auto()); if (line_height_length.is_absolute()) return (float)line_height_length.to_px(layout_node); return (float)font().glyph_height() * 1.4f; diff --git a/Libraries/LibWeb/CSS/StyleValue.h b/Libraries/LibWeb/CSS/StyleValue.h index d68d1680d556..4bcf689e4b91 100644 --- a/Libraries/LibWeb/CSS/StyleValue.h +++ b/Libraries/LibWeb/CSS/StyleValue.h @@ -155,7 +155,7 @@ class StyleValue : public RefCounted<StyleValue> { bool is_position() const { return type() == Type::Position; } virtual String to_string() const = 0; - virtual Length to_length() const { return {}; } + virtual Length to_length() const { return Length::make_auto(); } virtual Color to_color(const Document&) const { return {}; } virtual bool is_auto() const { return false; } @@ -225,7 +225,7 @@ class PercentageStyleValue : public StyleValue { Length to_length(float reference) const { return Length((m_percentage / 100.0f) * reference, Length::Type::Px); } private: - virtual Length to_length() const override { return {}; } + virtual Length to_length() const override { return Length::make_auto(); } virtual bool is_auto() const override { return false; } explicit PercentageStyleValue(float percentage) diff --git a/Libraries/LibWeb/Layout/LayoutBlock.cpp b/Libraries/LibWeb/Layout/LayoutBlock.cpp index 6fef0b9bb349..bd543badd8f7 100644 --- a/Libraries/LibWeb/Layout/LayoutBlock.cpp +++ b/Libraries/LibWeb/Layout/LayoutBlock.cpp @@ -70,19 +70,19 @@ void LayoutBlock::layout_absolutely_positioned_descendant(LayoutBox& box) box.layout(LayoutMode::Default); auto& box_model = box.box_model(); auto& style = box.style(); - auto zero_value = Length(0, Length::Type::Px); + auto zero_value = Length::make_px(0); - auto specified_width = style.length_or_fallback(CSS::PropertyID::Width, Length(), width()); + auto specified_width = style.length_or_fallback(CSS::PropertyID::Width, Length::make_auto(), width()); - box_model.margin().top = style.length_or_fallback(CSS::PropertyID::MarginTop, {}, height()); - box_model.margin().right = style.length_or_fallback(CSS::PropertyID::MarginRight, {}, width()); - box_model.margin().bottom = style.length_or_fallback(CSS::PropertyID::MarginBottom, {}, height()); - box_model.margin().left = style.length_or_fallback(CSS::PropertyID::MarginLeft, {}, width()); + box_model.margin().top = style.length_or_fallback(CSS::PropertyID::MarginTop, Length::make_auto(), height()); + box_model.margin().right = style.length_or_fallback(CSS::PropertyID::MarginRight, Length::make_auto(), width()); + box_model.margin().bottom = style.length_or_fallback(CSS::PropertyID::MarginBottom, Length::make_auto(), height()); + box_model.margin().left = style.length_or_fallback(CSS::PropertyID::MarginLeft, Length::make_auto(), width()); - box_model.offset().top = style.length_or_fallback(CSS::PropertyID::Top, {}, height()); - box_model.offset().right = style.length_or_fallback(CSS::PropertyID::Right, {}, width()); - box_model.offset().bottom = style.length_or_fallback(CSS::PropertyID::Bottom, {}, height()); - box_model.offset().left = style.length_or_fallback(CSS::PropertyID::Left, {}, width()); + box_model.offset().top = style.length_or_fallback(CSS::PropertyID::Top, Length::make_auto(), height()); + box_model.offset().right = style.length_or_fallback(CSS::PropertyID::Right, Length::make_auto(), width()); + box_model.offset().bottom = style.length_or_fallback(CSS::PropertyID::Bottom, Length::make_auto(), height()); + box_model.offset().left = style.length_or_fallback(CSS::PropertyID::Left, Length::make_auto(), width()); if (box_model.offset().left.is_auto() && specified_width.is_auto() && box_model.offset().right.is_auto()) { if (box_model.margin().left.is_auto()) @@ -164,7 +164,7 @@ void LayoutBlock::layout_contained_boxes(LayoutMode layout_mode) }); if (layout_mode != LayoutMode::Default) { - auto specified_width = style().length_or_fallback(CSS::PropertyID::Width, Length(), containing_block()->width()); + auto specified_width = style().length_or_fallback(CSS::PropertyID::Width, Length::make_auto(), containing_block()->width()); if (specified_width.is_auto()) set_width(content_width); } @@ -279,14 +279,14 @@ void LayoutBlock::compute_width_for_absolutely_positioned_block() { auto& style = this->style(); auto& containing_block = *this->containing_block(); - auto zero_value = Length(0, Length::Type::Px); + auto zero_value = Length::make_px(0); - Length margin_left; - Length margin_right; - Length border_left; - Length border_right; - Length padding_left; - Length padding_right; + Length margin_left = Length::make_auto(); + Length margin_right = Length::make_auto(); + Length border_left = Length::make_auto(); + Length border_right = Length::make_auto(); + Length padding_left = Length::make_auto(); + Length padding_right = Length::make_auto(); auto try_compute_width = [&](const auto& a_width) { margin_left = style.length_or_fallback(CSS::PropertyID::MarginLeft, zero_value, containing_block.width()); @@ -296,8 +296,8 @@ void LayoutBlock::compute_width_for_absolutely_positioned_block() padding_left = style.length_or_fallback(CSS::PropertyID::PaddingLeft, zero_value, containing_block.width()); padding_right = style.length_or_fallback(CSS::PropertyID::PaddingRight, zero_value, containing_block.width()); - auto left = style.length_or_fallback(CSS::PropertyID::Left, {}, containing_block.width()); - auto right = style.length_or_fallback(CSS::PropertyID::Right, {}, containing_block.width()); + auto left = style.length_or_fallback(CSS::PropertyID::Left, Length::make_auto(), containing_block.width()); + auto right = style.length_or_fallback(CSS::PropertyID::Right, Length::make_auto(), containing_block.width()); auto width = a_width; auto solve_for_left = [&] { @@ -316,14 +316,14 @@ void LayoutBlock::compute_width_for_absolutely_positioned_block() if (left.is_auto() && width.is_auto() && right.is_auto()) { // First set any 'auto' values for 'margin-left' and 'margin-right' to 0. if (margin_left.is_auto()) - margin_left = Length(0, Length::Type::Px); + margin_left = Length::make_px(0); if (margin_right.is_auto()) - margin_right = Length(0, Length::Type::Px); + margin_right = Length::make_px(0); // Then, if the 'direction' property of the element establishing the static-position containing block // is 'ltr' set 'left' to the static position and apply rule number three below; // otherwise, set 'right' to the static position and apply rule number one below. // FIXME: This is very hackish. - left = Length(0, Length::Type::Px); + left = Length::make_px(0); goto Rule3; } @@ -333,9 +333,9 @@ void LayoutBlock::compute_width_for_absolutely_positioned_block() } if (margin_left.is_auto()) - margin_left = Length(0, Length::Type::Px); + margin_left = Length::make_px(0); if (margin_right.is_auto()) - margin_right = Length(0, Length::Type::Px); + margin_right = Length::make_px(0); // 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', // then the width is shrink-to-fit. Then solve for 'left' @@ -386,14 +386,14 @@ void LayoutBlock::compute_width_for_absolutely_positioned_block() return width; }; - auto specified_width = style.length_or_fallback(CSS::PropertyID::Width, {}, containing_block.width()); + auto specified_width = style.length_or_fallback(CSS::PropertyID::Width, Length::make_auto(), containing_block.width()); // 1. The tentative used width is calculated (without 'min-width' and 'max-width') auto used_width = try_compute_width(specified_width); // 2. The tentative used width is greater than 'max-width', the rules above are applied again, // but this time using the computed value of 'max-width' as the computed value for 'width'. - auto specified_max_width = style.length_or_fallback(CSS::PropertyID::MaxWidth, {}, containing_block.width()); + auto specified_max_width = style.length_or_fallback(CSS::PropertyID::MaxWidth, Length::make_auto(), containing_block.width()); if (!specified_max_width.is_auto()) { if (used_width.to_px(*this) > specified_max_width.to_px(*this)) { used_width = try_compute_width(specified_max_width); @@ -402,7 +402,7 @@ void LayoutBlock::compute_width_for_absolutely_positioned_block() // 3. If the resulting width is smaller than 'min-width', the rules above are applied again, // but this time using the value of 'min-width' as the computed value for 'width'. - auto specified_min_width = style.length_or_fallback(CSS::PropertyID::MinWidth, {}, containing_block.width()); + auto specified_min_width = style.length_or_fallback(CSS::PropertyID::MinWidth, Length::make_auto(), containing_block.width()); if (!specified_min_width.is_auto()) { if (used_width.to_px(*this) < specified_min_width.to_px(*this)) { used_width = try_compute_width(specified_min_width); @@ -425,15 +425,15 @@ void LayoutBlock::compute_width() return compute_width_for_absolutely_positioned_block(); auto& style = this->style(); - auto auto_value = Length(); - auto zero_value = Length(0, Length::Type::Px); + auto auto_value = Length::make_auto(); + auto zero_value = Length::make_px(0); - Length margin_left; - Length margin_right; - Length border_left; - Length border_right; - Length padding_left; - Length padding_right; + Length margin_left = Length::make_auto(); + Length margin_right = Length::make_auto(); + Length border_left = Length::make_auto(); + Length border_right = Length::make_auto(); + Length padding_left = Length::make_auto(); + Length padding_right = Length::make_auto(); auto& containing_block = *this->containing_block(); @@ -562,7 +562,7 @@ void LayoutBlock::place_block_level_replaced_element_in_normal_flow(LayoutReplac { ASSERT(!is_absolutely_positioned()); auto& style = box.style(); - auto zero_value = Length(0, Length::Type::Px); + auto zero_value = Length::make_px(0); auto& containing_block = *this; auto& replaced_element_box_model = box.box_model(); @@ -617,7 +617,7 @@ LayoutBlock::ShrinkToFitResult LayoutBlock::calculate_shrink_to_fit_width() void LayoutBlock::place_block_level_non_replaced_element_in_normal_flow(LayoutBlock& block) { auto& style = block.style(); - auto zero_value = Length(0, Length::Type::Px); + auto zero_value = Length::make_px(0); auto& containing_block = *this; auto& box = block.box_model(); @@ -674,17 +674,17 @@ void LayoutBlock::compute_height() { auto& style = this->style(); - auto specified_height = style.length_or_fallback(CSS::PropertyID::Height, Length(), containing_block()->height()); - auto specified_max_height = style.length_or_fallback(CSS::PropertyID::MaxHeight, Length(), containing_block()->height()); + auto specified_height = style.length_or_fallback(CSS::PropertyID::Height, Length::make_auto(), containing_block()->height()); + auto specified_max_height = style.length_or_fallback(CSS::PropertyID::MaxHeight, Length::make_auto(), containing_block()->height()); auto& containing_block = *this->containing_block(); - box_model().margin().top = style.length_or_fallback(CSS::PropertyID::MarginTop, Length(0, Length::Type::Px), containing_block.width()); - box_model().margin().bottom = style.length_or_fallback(CSS::PropertyID::MarginBottom, Length(0, Length::Type::Px), containing_block.width()); - box_model().border().top = style.length_or_fallback(CSS::PropertyID::BorderTopWidth, Length(0, Length::Type::Px)); - box_model().border().bottom = style.length_or_fallback(CSS::PropertyID::BorderBottomWidth, Length(0, Length::Type::Px)); - box_model().padding().top = style.length_or_fallback(CSS::PropertyID::PaddingTop, Length(0, Length::Type::Px), containing_block.width()); - box_model().padding().bottom = style.length_or_fallback(CSS::PropertyID::PaddingBottom, Length(0, Length::Type::Px), containing_block.width()); + box_model().margin().top = style.length_or_fallback(CSS::PropertyID::MarginTop, Length::make_px(0), containing_block.width()); + box_model().margin().bottom = style.length_or_fallback(CSS::PropertyID::MarginBottom, Length::make_px(0), containing_block.width()); + box_model().border().top = style.length_or_fallback(CSS::PropertyID::BorderTopWidth, Length::make_px(0)); + box_model().border().bottom = style.length_or_fallback(CSS::PropertyID::BorderBottomWidth, Length::make_px(0)); + box_model().padding().top = style.length_or_fallback(CSS::PropertyID::PaddingTop, Length::make_px(0), containing_block.width()); + box_model().padding().bottom = style.length_or_fallback(CSS::PropertyID::PaddingBottom, Length::make_px(0), containing_block.width()); if (!specified_height.is_auto()) { float used_height = specified_height.to_px(*this); diff --git a/Libraries/LibWeb/Layout/LayoutReplaced.cpp b/Libraries/LibWeb/Layout/LayoutReplaced.cpp index 202e39ca7c46..d0dce29b2f1c 100644 --- a/Libraries/LibWeb/Layout/LayoutReplaced.cpp +++ b/Libraries/LibWeb/Layout/LayoutReplaced.cpp @@ -46,8 +46,8 @@ float LayoutReplaced::calculate_width() const // 10.3.2 [Inline,] replaced elements auto& style = this->style(); - auto auto_value = Length(); - auto zero_value = Length(0, Length::Type::Px); + auto auto_value = Length::make_auto(); + auto zero_value = Length::make_px(0); auto& containing_block = *this->containing_block(); auto margin_left = style.length_or_fallback(CSS::PropertyID::MarginLeft, zero_value, containing_block.width()); @@ -99,7 +99,7 @@ float LayoutReplaced::calculate_height() const // 10.6.2 Inline replaced elements, block-level replaced elements in normal flow, // 'inline-block' replaced elements in normal flow and floating replaced elements auto& style = this->style(); - auto auto_value = Length(); + auto auto_value = Length::make_auto(); auto& containing_block = *this->containing_block(); auto specified_width = style.length_or_fallback(CSS::PropertyID::Width, auto_value, containing_block.width()); diff --git a/Libraries/LibWeb/Parser/CSSParser.cpp b/Libraries/LibWeb/Parser/CSSParser.cpp index d7b1ef3e3e6a..f037c7e07d71 100644 --- a/Libraries/LibWeb/Parser/CSSParser.cpp +++ b/Libraries/LibWeb/Parser/CSSParser.cpp @@ -279,7 +279,7 @@ NonnullRefPtr<StyleValue> parse_css_value(const StringView& string) if (string.equals_ignoring_case("initial")) return InitialStyleValue::create(); if (string.equals_ignoring_case("auto")) - return LengthStyleValue::create(Length()); + return LengthStyleValue::create(Length::make_auto()); auto color = parse_css_color(string); if (color.has_value())
3cabd17f9b6164d39ad95865b2920eaea8e0b2f9
2023-01-13 00:25:10
Andreas Kling
libweb: Add convenient Selection::range() accessor
false
Add convenient Selection::range() accessor
libweb
diff --git a/Userland/Libraries/LibWeb/Selection/Selection.cpp b/Userland/Libraries/LibWeb/Selection/Selection.cpp index f3ba361965b8..6305d5fec2d3 100644 --- a/Userland/Libraries/LibWeb/Selection/Selection.cpp +++ b/Userland/Libraries/LibWeb/Selection/Selection.cpp @@ -429,4 +429,9 @@ DeprecatedString Selection::to_deprecated_string() const return m_range->to_deprecated_string(); } +JS::GCPtr<DOM::Range> Selection::range() const +{ + return m_range; +} + } diff --git a/Userland/Libraries/LibWeb/Selection/Selection.h b/Userland/Libraries/LibWeb/Selection/Selection.h index 81fb7dd16f6f..a96a6e4fc18f 100644 --- a/Userland/Libraries/LibWeb/Selection/Selection.h +++ b/Userland/Libraries/LibWeb/Selection/Selection.h @@ -50,6 +50,9 @@ class Selection final : public Bindings::PlatformObject { DeprecatedString to_deprecated_string() const; + // Non-standard convenience accessor for the selection's range. + JS::GCPtr<DOM::Range> range() const; + private: Selection(JS::NonnullGCPtr<JS::Realm>, JS::NonnullGCPtr<DOM::Document>);
2c6bd3a61b3e9a030a85bac8ba46b6bbca3fe7e8
2021-07-26 20:45:31
Idan Horowitz
libjs: Use narrower types in Temporal PlainDate/PlainDateTime/Calendar
false
Use narrower types in Temporal PlainDate/PlainDateTime/Calendar
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp index d8786c26d1d5..1e7a3d6a3b8e 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp @@ -577,9 +577,9 @@ Optional<TemporalTimeZone> parse_temporal_time_zone_string(GlobalObject& global_ VERIFY(sign_part.has_value()); // b. Set hours to ! ToIntegerOrInfinity(hours). - i32 hours = Value(js_string(vm, *hours_part)).to_integer_or_infinity(global_object); + u8 hours = Value(js_string(vm, *hours_part)).to_integer_or_infinity(global_object); - i32 sign; + u8 sign; // c. If sign is the code unit 0x002D (HYPHEN-MINUS) or the code unit 0x2212 (MINUS SIGN), then if (sign_part->is_one_of("-", "\u2212")) { // i. Set sign to −1. @@ -592,10 +592,10 @@ Optional<TemporalTimeZone> parse_temporal_time_zone_string(GlobalObject& global_ } // e. Set minutes to ! ToIntegerOrInfinity(minutes). - i32 minutes = Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object); + u8 minutes = Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object); // f. Set seconds to ! ToIntegerOrInfinity(seconds). - i32 seconds = Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object); + u8 seconds = Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object); i32 nanoseconds; // g. If fraction is not undefined, then diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h index e4069ca38d13..ecff7da44802 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h @@ -33,25 +33,23 @@ struct ISODateTime { Optional<String> calendar = {}; }; -// FIXME: Use more narrow types for most of these (u8/u16) struct TemporalInstant { i32 year; - i32 month; - i32 day; - i32 hour; - i32 minute; - i32 second; - i32 millisecond; - i32 microsecond; - i32 nanosecond; + u8 month; + u8 day; + u8 hour; + u8 minute; + u8 second; + u16 millisecond; + u16 microsecond; + u16 nanosecond; Optional<String> time_zone_offset; }; -// FIXME: Use more narrow type for month/day (u8) struct TemporalDate { i32 year; - i32 month; - i32 day; + u8 month; + u8 day; Optional<String> calendar; }; diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp index 7b5ae40ab30c..f844821261a5 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp @@ -460,7 +460,7 @@ u16 iso_days_in_year(i32 year) } // 12.1.32 ISODaysInMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isodaysinmonth -i32 iso_days_in_month(i32 year, i32 month) +u8 iso_days_in_month(i32 year, u8 month) { // 1. Assert: year is an integer. @@ -547,7 +547,7 @@ u8 to_iso_week_of_year(i32 year, u8 month, u8 day) } // 12.1.36 BuildISOMonthCode ( month ), https://tc39.es/proposal-temporal/#sec-buildisomonthcode -String build_iso_month_code(i32 month) +String build_iso_month_code(u8 month) { return String::formatted("M{:02}", month); } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.h b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.h index 4009bb0e4e7c..9700f23cbafb 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.h @@ -53,11 +53,11 @@ PlainDate* date_from_fields(GlobalObject&, Object& calendar, Object& fields, Obj bool calendar_equals(GlobalObject&, Object& one, Object& two); bool is_iso_leap_year(i32 year); u16 iso_days_in_year(i32 year); -i32 iso_days_in_month(i32 year, i32 month); +u8 iso_days_in_month(i32 year, u8 month); u8 to_iso_day_of_week(i32 year, u8 month, u8 day); u16 to_iso_day_of_year(i32 year, u8 month, u8 day); u8 to_iso_week_of_year(i32 year, u8 month, u8 day); -String build_iso_month_code(i32 month); +String build_iso_month_code(u8 month); double resolve_iso_month(GlobalObject&, Object& fields); Optional<TemporalDate> iso_date_from_fields(GlobalObject&, Object& fields, Object& options); i32 iso_year(Object& temporal_object); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp index 9f148af0abb3..35dad3677cbd 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp @@ -14,7 +14,7 @@ namespace JS::Temporal { // 3 Temporal.PlainDate Objects, https://tc39.es/proposal-temporal/#sec-temporal-plaindate-objects -PlainDate::PlainDate(i32 year, i32 month, i32 day, Object& calendar, Object& prototype) +PlainDate::PlainDate(i32 year, u8 month, u8 day, Object& calendar, Object& prototype) : Object(prototype) , m_iso_year(year) , m_iso_month(month) @@ -29,7 +29,7 @@ void PlainDate::visit_edges(Visitor& visitor) } // 3.5.1 CreateTemporalDate ( isoYear, isoMonth, isoDay, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaldate -PlainDate* create_temporal_date(GlobalObject& global_object, i32 iso_year, i32 iso_month, i32 iso_day, Object& calendar, FunctionObject* new_target) +PlainDate* create_temporal_date(GlobalObject& global_object, i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, FunctionObject* new_target) { auto& vm = global_object.vm(); @@ -159,13 +159,13 @@ Optional<TemporalDate> regulate_iso_date(GlobalObject& global_object, double yea // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards. // This does not change the exposed behaviour as the call to IsValidISODate will immediately check that these values are valid ISO // values (for years: -273975 - 273975, for months: 1 - 12, for days: 1 - 31) all of which are subsets of this check. - if (!AK::is_within_range<i32>(year) || !AK::is_within_range<i32>(month) || !AK::is_within_range<i32>(day)) { + if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month) || !AK::is_within_range<u8>(day)) { vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate); return {}; } auto y = static_cast<i32>(year); - auto m = static_cast<i32>(month); - auto d = static_cast<i32>(day); + auto m = static_cast<u8>(month); + auto d = static_cast<u8>(day); // a. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception. if (is_valid_iso_date(y, m, d)) { vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate); @@ -191,13 +191,13 @@ Optional<TemporalDate> regulate_iso_date(GlobalObject& global_object, double yea day = constrain_to_range(day, 1, iso_days_in_month(y, month)); // c. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }. - return TemporalDate { .year = y, .month = static_cast<i32>(month), .day = static_cast<i32>(day), .calendar = {} }; + return TemporalDate { .year = y, .month = static_cast<u8>(month), .day = static_cast<u8>(day), .calendar = {} }; } VERIFY_NOT_REACHED(); } // 3.5.5 IsValidISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisodate -bool is_valid_iso_date(i32 year, i32 month, i32 day) +bool is_valid_iso_date(i32 year, u8 month, u8 day) { // 1. Assert: year, month, and day are integers. diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h index 3265f7f59d90..abc49edfcaf8 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h @@ -15,12 +15,12 @@ class PlainDate final : public Object { JS_OBJECT(PlainDate, Object); public: - PlainDate(i32 iso_year, i32 iso_month, i32 iso_day, Object& calendar, Object& prototype); + PlainDate(i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, Object& prototype); virtual ~PlainDate() override = default; [[nodiscard]] i32 iso_year() const { return m_iso_year; } - [[nodiscard]] i32 iso_month() const { return m_iso_month; } - [[nodiscard]] i32 iso_day() const { return m_iso_day; } + [[nodiscard]] u8 iso_month() const { return m_iso_month; } + [[nodiscard]] u8 iso_day() const { return m_iso_day; } [[nodiscard]] Object const& calendar() const { return m_calendar; } [[nodiscard]] Object& calendar() { return m_calendar; } @@ -28,15 +28,15 @@ class PlainDate final : public Object { virtual void visit_edges(Visitor&) override; // 3.4 Properties of Temporal.PlainDate Instances, https://tc39.es/proposal-temporal/#sec-properties-of-temporal-plaindate-instances - i32 m_iso_year { 0 }; // [[ISOYear]] - i32 m_iso_month { 1 }; // [[ISOMonth]] - i32 m_iso_day { 1 }; // [[ISODay]] - Object& m_calendar; // [[Calendar]] + i32 m_iso_year { 0 }; // [[ISOYear]] + u8 m_iso_month { 1 }; // [[ISOMonth]] + u8 m_iso_day { 1 }; // [[ISODay]] + Object& m_calendar; // [[Calendar]] }; -PlainDate* create_temporal_date(GlobalObject&, i32 iso_year, i32 iso_month, i32 iso_day, Object& calendar, FunctionObject* new_target = nullptr); +PlainDate* create_temporal_date(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, FunctionObject* new_target = nullptr); PlainDate* to_temporal_date(GlobalObject&, Value item, Object* options = nullptr); Optional<TemporalDate> regulate_iso_date(GlobalObject&, double year, double month, double day, String const& overflow); -bool is_valid_iso_date(i32 year, i32 month, i32 day); +bool is_valid_iso_date(i32 year, u8 month, u8 day); } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp index aa9f550ad472..1e5e056daef6 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp @@ -84,7 +84,7 @@ Value PlainDateConstructor::construct(FunctionObject& new_target) // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards. // This does not change the exposed behaviour as the call to CreateTemporalDate will immediately check that these values are valid // ISO values (for years: -273975 - 273975, for months: 1 - 12, for days: 1 - 31) all of which are subsets of this check. - if (!AK::is_within_range<i32>(y) || !AK::is_within_range<i32>(m) || !AK::is_within_range<i32>(d)) { + if (!AK::is_within_range<i32>(y) || !AK::is_within_range<u8>(m) || !AK::is_within_range<u8>(d)) { vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate); return {}; } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp index 646151a8ea45..785edb4939a1 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp @@ -36,7 +36,7 @@ void PlainDateTime::visit_edges(Visitor& visitor) } // 5.5.1 GetEpochFromISOParts ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-getepochfromisoparts -BigInt* get_epoch_from_iso_parts(GlobalObject& global_object, i32 year, i32 month, i32 day, i32 hour, i32 minute, i32 second, i32 millisecond, i32 microsecond, i32 nanosecond) +BigInt* get_epoch_from_iso_parts(GlobalObject& global_object, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond) { auto& vm = global_object.vm(); @@ -70,7 +70,7 @@ const auto DATETIME_NANOSECONDS_MIN = "-8640086400000000000000"_sbigint; const auto DATETIME_NANOSECONDS_MAX = "8640086400000000000000"_sbigint; // 5.5.2 ISODateTimeWithinLimits ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-isodatetimewithinlimits -bool iso_date_time_within_limits(GlobalObject& global_object, i32 year, i32 month, i32 day, i32 hour, i32 minute, i32 second, i32 millisecond, i32 microsecond, i32 nanosecond) +bool iso_date_time_within_limits(GlobalObject& global_object, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond) { // 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers. diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h index 4764723339d0..89ec45a53e3e 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h @@ -46,8 +46,8 @@ class PlainDateTime final : public Object { Object& m_calendar; // [[Calendar]] }; -BigInt* get_epoch_from_iso_parts(GlobalObject&, i32 year, i32 month, i32 day, i32 hour, i32 minute, i32 second, i32 millisecond, i32 microsecond, i32 nanosecond); -bool iso_date_time_within_limits(GlobalObject&, i32 year, i32 month, i32 day, i32 hour, i32 minute, i32 second, i32 millisecond, i32 microsecond, i32 nanosecond); +BigInt* get_epoch_from_iso_parts(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond); +bool iso_date_time_within_limits(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond); PlainDateTime* create_temporal_date_time(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, FunctionObject* new_target = nullptr); } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp index 993cd462b162..da1487cc6523 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp @@ -10,42 +10,42 @@ namespace JS::Temporal { // 4.5.5 IsValidTime ( hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidtime -bool is_valid_time(i32 hour, i32 minute, i32 second, i32 millisecond, i32 microsecond, i32 nanosecond) +bool is_valid_time(u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond) { // 1. Assert: hour, minute, second, millisecond, microsecond, and nanosecond are integers. // 2. If hour < 0 or hour > 23, then - if (hour < 0 || hour > 23) { + if (hour > 23) { // a. Return false. return false; } // 3. If minute < 0 or minute > 59, then - if (minute < 0 || minute > 59) { + if (minute > 59) { // a. Return false. return false; } // 4. If second < 0 or second > 59, then - if (second < 0 || second > 59) { + if (second > 59) { // a. Return false. return false; } // 5. If millisecond < 0 or millisecond > 999, then - if (millisecond < 0 || millisecond > 999) { + if (millisecond > 999) { // a. Return false. return false; } // 6. If microsecond < 0 or microsecond > 999, then - if (microsecond < 0 || microsecond > 999) { + if (microsecond > 999) { // a. Return false. return false; } // 7. If nanosecond < 0 or nanosecond > 999, then - if (nanosecond < 0 || nanosecond > 999) { + if (nanosecond > 999) { // a. Return false. return false; } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h index cbc842d38354..748298071e71 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainTime.h @@ -10,6 +10,6 @@ namespace JS::Temporal { -bool is_valid_time(i32 hour, i32 minute, i32 second, i32 millisecond, i32 microsecond, i32 nanosecond); +bool is_valid_time(u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond); }
bce7fdba8117a82b832063645210df3fbb8614ea
2021-06-25 20:28:36
Andreas Kling
libjs: Bring Reference records a bit closer to the ECMAScript spec
false
Bring Reference records a bit closer to the ECMAScript spec
libjs
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp index 6f6a0a74bed9..edf1480f9191 100644 --- a/Userland/Libraries/LibJS/AST.cpp +++ b/Userland/Libraries/LibJS/AST.cpp @@ -130,7 +130,7 @@ CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interprete if (is<MemberExpression>(*m_callee)) { auto& member_expression = static_cast<MemberExpression const&>(*m_callee); Value callee; - Object* this_value = nullptr; + Value this_value; if (is<SuperExpression>(member_expression.object())) { auto super_base = interpreter.current_function_environment_record()->get_super_base(); @@ -141,7 +141,7 @@ CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interprete auto property_name = member_expression.computed_property_name(interpreter, global_object); if (!property_name.is_valid()) return {}; - auto reference = Reference(super_base, property_name); + auto reference = Reference { super_base, property_name, super_base }; callee = reference.get(global_object); if (vm.exception()) return {}; @@ -153,9 +153,7 @@ CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interprete callee = reference.get(global_object); if (vm.exception()) return {}; - this_value = reference.base().to_object(global_object); - if (vm.exception()) - return {}; + this_value = reference.get_this_value(); } return { this_value, callee }; @@ -667,9 +665,9 @@ Reference Expression::to_reference(Interpreter&, GlobalObject&) const return {}; } -Reference Identifier::to_reference(Interpreter& interpreter, GlobalObject&) const +Reference Identifier::to_reference(Interpreter& interpreter, GlobalObject& global_object) const { - return interpreter.vm().resolve_binding(string()); + return interpreter.vm().resolve_binding(global_object, string()); } Reference MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& global_object) const @@ -677,10 +675,16 @@ Reference MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& auto object_value = m_object->execute(interpreter, global_object); if (interpreter.exception()) return {}; + + object_value = require_object_coercible(global_object, object_value); + if (interpreter.exception()) + return {}; + auto property_name = computed_property_name(interpreter, global_object); if (!property_name.is_valid()) - return {}; - return { object_value, property_name }; + return Reference {}; + + return Reference { object_value, property_name, object_value }; } Value UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const @@ -701,12 +705,10 @@ Value UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_ob if (interpreter.exception()) { return {}; } - // FIXME: standard recommends checking with is_unresolvable but it ALWAYS return false here - if (reference.is_local_variable() || reference.is_global_variable()) { - const auto& name = reference.name(); - lhs_result = interpreter.vm().get_variable(name.to_string(), global_object).value_or(js_undefined()); - if (interpreter.exception()) - return {}; + if (reference.is_unresolvable()) { + lhs_result = js_undefined(); + } else { + lhs_result = reference.get(global_object, false); } } else { lhs_result = m_lhs->execute(interpreter, global_object); @@ -1477,6 +1479,7 @@ Value UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_o InterpreterNodeScope node_scope { interpreter, *this }; auto reference = m_argument->to_reference(interpreter, global_object); + if (interpreter.exception()) return {}; auto old_value = reference.get(global_object); diff --git a/Userland/Libraries/LibJS/Runtime/Reference.cpp b/Userland/Libraries/LibJS/Runtime/Reference.cpp index 2bc6b466f8c8..99204c60fca4 100644 --- a/Userland/Libraries/LibJS/Runtime/Reference.cpp +++ b/Userland/Libraries/LibJS/Runtime/Reference.cpp @@ -1,9 +1,10 @@ /* - * Copyright (c) 2020, Andreas Kling <[email protected]> + * Copyright (c) 2020-2021, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ +#include <LibJS/AST.h> #include <LibJS/Runtime/Error.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/Reference.h> @@ -15,39 +16,50 @@ void Reference::put(GlobalObject& global_object, Value value) auto& vm = global_object.vm(); if (is_unresolvable()) { - throw_reference_error(global_object); + if (m_strict) { + throw_reference_error(global_object); + return; + } + global_object.put(m_name, value); return; } - if (is_local_variable() || is_global_variable()) { - if (is_local_variable()) - vm.set_variable(m_name.to_string(), value, global_object); - else - global_object.put(m_name, value); - return; - } + if (is_property_reference()) { + // FIXME: This is an ad-hoc hack until we support proper variable bindings. + if (!m_base_value.is_object() && vm.in_strict_mode()) { + if (m_base_value.is_nullish()) + vm.throw_exception<TypeError>(global_object, ErrorType::ReferenceNullishSetProperty, m_name.to_value(vm).to_string_without_side_effects(), m_base_value.to_string_without_side_effects()); + else + vm.throw_exception<TypeError>(global_object, ErrorType::ReferencePrimitiveSetProperty, m_name.to_value(vm).to_string_without_side_effects(), m_base_value.typeof(), m_base_value.to_string_without_side_effects()); + return; + } - auto base = this->base(); + auto* base_obj = m_base_value.to_object(global_object); + if (!base_obj) + return; - if (!base.is_object() && vm.in_strict_mode()) { - if (base.is_nullish()) - vm.throw_exception<TypeError>(global_object, ErrorType::ReferenceNullishSetProperty, m_name.to_value(vm).to_string_without_side_effects(), base.to_string_without_side_effects()); - else - vm.throw_exception<TypeError>(global_object, ErrorType::ReferencePrimitiveSetProperty, m_name.to_value(vm).to_string_without_side_effects(), base.typeof(), base.to_string_without_side_effects()); + bool succeeded = base_obj->put(m_name, value); + if (!succeeded && m_strict) { + vm.throw_exception<TypeError>(global_object, ErrorType::ReferenceNullishSetProperty, m_name.to_value(vm).to_string_without_side_effects(), m_base_value.to_string_without_side_effects()); + return; + } return; } - if (base.is_nullish()) { - // This will always fail the to_object() call below, let's throw the TypeError ourselves with a nice message instead. - vm.throw_exception<TypeError>(global_object, ErrorType::ReferenceNullishSetProperty, m_name.to_value(vm).to_string_without_side_effects(), base.to_string_without_side_effects()); - return; - } + VERIFY(m_base_type == BaseType::EnvironmentRecord); + auto existing_variable = m_base_environment_record->get_from_environment_record(m_name.as_string()); + Variable variable { + .value = value, + .declaration_kind = existing_variable.has_value() ? existing_variable->declaration_kind : DeclarationKind::Var + }; - auto* object = base.to_object(global_object); - if (!object) + // FIXME: This is a hack until we support proper variable bindings. + if (variable.declaration_kind == DeclarationKind::Const) { + vm.throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst); return; + } - object->put(m_name, value); + m_base_environment_record->put_into_environment_record(m_name.as_string(), variable); } void Reference::throw_reference_error(GlobalObject& global_object) @@ -59,71 +71,92 @@ void Reference::throw_reference_error(GlobalObject& global_object) vm.throw_exception<ReferenceError>(global_object, ErrorType::UnknownIdentifier, m_name.to_string_or_symbol().to_display_string()); } -Value Reference::get(GlobalObject& global_object) +Value Reference::get(GlobalObject& global_object, bool throw_if_undefined) { - auto& vm = global_object.vm(); - if (is_unresolvable()) { throw_reference_error(global_object); return {}; } - if (is_local_variable() || is_global_variable()) { - Value value; - if (is_local_variable()) - value = vm.get_variable(m_name.to_string(), global_object); - else - value = global_object.get(m_name); - if (vm.exception()) - return {}; - if (value.is_empty()) { - throw_reference_error(global_object); + if (is_property_reference()) { + auto* base_obj = m_base_value.to_object(global_object); + if (!base_obj) return {}; - } - return value; + return base_obj->get(m_name).value_or(js_undefined()); } - auto base = this->base(); - - if (base.is_nullish()) { - // This will always fail the to_object() call below, let's throw the TypeError ourselves with a nice message instead. - vm.throw_exception<TypeError>(global_object, ErrorType::ReferenceNullishGetProperty, m_name.to_value(vm).to_string_without_side_effects(), base.to_string_without_side_effects()); + VERIFY(m_base_type == BaseType::EnvironmentRecord); + auto value = m_base_environment_record->get_from_environment_record(m_name.as_string()); + if (!value.has_value()) { + if (!throw_if_undefined) { + // FIXME: This is an ad-hoc hack for the `typeof` operator until we support proper variable bindings. + return js_undefined(); + } + throw_reference_error(global_object); return {}; } - - auto* object = base.to_object(global_object); - if (!object) - return {}; - - return object->get(m_name).value_or(js_undefined()); + return value->value; } bool Reference::delete_(GlobalObject& global_object) { - if (is_unresolvable()) + if (is_unresolvable()) { + VERIFY(!m_strict); return true; + } auto& vm = global_object.vm(); - if (is_local_variable() || is_global_variable()) { - if (is_local_variable()) - return vm.delete_variable(m_name.to_string()); - else - return global_object.delete_property(m_name); + if (is_property_reference()) { + auto* base_obj = m_base_value.to_object(global_object); + if (!base_obj) + return false; + bool succeeded = base_obj->delete_property(m_name); + if (!succeeded && m_strict) { + vm.throw_exception<TypeError>(global_object, ErrorType::ReferenceNullishDeleteProperty, m_name.to_value(vm).to_string_without_side_effects(), m_base_value.to_string_without_side_effects()); + return false; + } + return succeeded; } - auto base = this->base(); + VERIFY(m_base_type == BaseType::EnvironmentRecord); + return m_base_environment_record->delete_from_environment_record(m_name.as_string()); +} - if (base.is_nullish()) { - // This will always fail the to_object() call below, let's throw the TypeError ourselves with a nice message instead. - vm.throw_exception<TypeError>(global_object, ErrorType::ReferenceNullishDeleteProperty, m_name.to_value(vm).to_string_without_side_effects(), base.to_string_without_side_effects()); - return false; +String Reference::to_string() const +{ + StringBuilder builder; + builder.append("Reference { Base="); + switch (m_base_type) { + case BaseType::Unresolvable: + builder.append("Unresolvable"); + break; + case BaseType::EnvironmentRecord: + builder.appendff("{}", base_environment().class_name()); + break; + case BaseType::Value: + if (m_base_value.is_empty()) + builder.append("<empty>"); + else + builder.appendff("{}", m_base_value.to_string_without_side_effects()); + break; } + builder.append(", ReferencedName="); + if (!m_name.is_valid()) + builder.append("<invalid>"); + else if (m_name.is_symbol()) + builder.appendff("{}", m_name.as_symbol()->to_string()); + else + builder.appendff("{}", m_name.to_string()); + builder.appendff(", Strict={}", m_strict); + builder.appendff(", ThisValue="); + if (m_this_value.is_empty()) + builder.append("<empty>"); + else + builder.appendff("{}", m_this_value.to_string_without_side_effects()); - auto* object = base.to_object(global_object); - VERIFY(object); - - return object->delete_property(m_name); + builder.append(" }"); + return builder.to_string(); } } diff --git a/Userland/Libraries/LibJS/Runtime/Reference.h b/Userland/Libraries/LibJS/Runtime/Reference.h index 864d7855c4e7..32503cb26868 100644 --- a/Userland/Libraries/LibJS/Runtime/Reference.h +++ b/Userland/Libraries/LibJS/Runtime/Reference.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Andreas Kling <[email protected]> + * Copyright (c) 2020-2021, Andreas Kling <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -7,6 +7,7 @@ #pragma once #include <AK/String.h> +#include <LibJS/Runtime/EnvironmentRecord.h> #include <LibJS/Runtime/PropertyName.h> #include <LibJS/Runtime/Value.h> @@ -14,69 +15,105 @@ namespace JS { class Reference { public: + enum class BaseType : u8 { + Unresolvable, + Value, + EnvironmentRecord, + }; + Reference() { } - Reference(Value base, const PropertyName& name, bool strict = false) - : m_base(base) + Reference(BaseType type, PropertyName const& name, bool strict) + : m_base_type(type) , m_name(name) , m_strict(strict) { } - enum LocalVariableTag { LocalVariable }; - Reference(LocalVariableTag, const FlyString& name, bool strict = false) - : m_base(js_null()) + Reference(Value base, PropertyName const& name, Value this_value, bool strict = false) + : m_base_type(BaseType::Value) + , m_base_value(base) , m_name(name) + , m_this_value(this_value) , m_strict(strict) - , m_local_variable(true) { + if (base.is_nullish()) { + m_base_type = BaseType::Unresolvable; + m_base_value = {}; + m_this_value = {}; + m_name = {}; + } } - enum GlobalVariableTag { GlobalVariable }; - Reference(GlobalVariableTag, const FlyString& name, bool strict = false) - : m_base(js_null()) - , m_name(name) + Reference(EnvironmentRecord& base, FlyString const& referenced_name, bool strict = false) + : m_base_type(BaseType::EnvironmentRecord) + , m_base_environment_record(&base) + , m_name(referenced_name) , m_strict(strict) - , m_global_variable(true) { } - Value base() const { return m_base; } - const PropertyName& name() const { return m_name; } - bool is_strict() const { return m_strict; } + Value base() const + { + VERIFY(m_base_type == BaseType::Value); + return m_base_value; + } - bool is_unresolvable() const { return m_base.is_empty(); } - bool is_property() const + EnvironmentRecord& base_environment() const { - return m_base.is_object() || has_primitive_base(); + VERIFY(m_base_type == BaseType::EnvironmentRecord); + return *m_base_environment_record; } - bool has_primitive_base() const + PropertyName const& name() const { return m_name; } + bool is_strict() const { return m_strict; } + + // 6.2.4.2 IsUnresolvableReference ( V ), https://tc39.es/ecma262/#sec-isunresolvablereference + bool is_unresolvable() const { return m_base_type == BaseType::Unresolvable; } + + // 6.2.4.1 IsPropertyReference ( V ), https://tc39.es/ecma262/#sec-ispropertyreference + bool is_property_reference() const { - return m_base.is_boolean() || m_base.is_string() || m_base.is_number(); + if (is_unresolvable()) + return false; + if (m_base_type == BaseType::EnvironmentRecord) + return false; + if (m_base_value.is_boolean() || m_base_value.is_string() || m_base_value.is_symbol() || m_base_value.is_bigint() || m_base_value.is_number() || m_base_value.is_object()) + return true; + return false; } - bool is_local_variable() const + // 6.2.4.7 GetThisValue ( V ), https://tc39.es/ecma262/#sec-getthisvalue + Value get_this_value() const { - return m_local_variable; + VERIFY(is_property_reference()); + if (is_super_reference()) + return m_this_value; + return m_base_value; } - bool is_global_variable() const + // 6.2.4.3 IsSuperReference ( V ), https://tc39.es/ecma262/#sec-issuperreference + bool is_super_reference() const { - return m_global_variable; + return !m_this_value.is_empty(); } void put(GlobalObject&, Value); - Value get(GlobalObject&); + Value get(GlobalObject&, bool throw_if_undefined = true); bool delete_(GlobalObject&); + String to_string() const; + private: void throw_reference_error(GlobalObject&); - Value m_base; + BaseType m_base_type { BaseType::Unresolvable }; + union { + Value m_base_value; + EnvironmentRecord* m_base_environment_record; + }; PropertyName m_name; + Value m_this_value; bool m_strict { false }; - bool m_local_variable { false }; - bool m_global_variable { false }; }; } diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp index 1740481d651a..8da5e08d0da7 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.cpp +++ b/Userland/Libraries/LibJS/Runtime/VM.cpp @@ -393,16 +393,16 @@ Value VM::get_variable(const FlyString& name, GlobalObject& global_object) } // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding -Reference VM::resolve_binding(FlyString const& name) +Reference VM::resolve_binding(GlobalObject& global_object, FlyString const& name, EnvironmentRecord*) { // FIXME: This implementation of ResolveBinding is non-conforming. for (auto* environment_record = lexical_environment(); environment_record && environment_record->outer_environment(); environment_record = environment_record->outer_environment()) { auto possible_match = environment_record->get_from_environment_record(name); if (possible_match.has_value()) - return { Reference::LocalVariable, name }; + return Reference { *environment_record, name }; } - return { Reference::GlobalVariable, name }; + return Reference { global_object.environment_record(), name }; } Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments) diff --git a/Userland/Libraries/LibJS/Runtime/VM.h b/Userland/Libraries/LibJS/Runtime/VM.h index 3a6173ba9d50..6e0677111806 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.h +++ b/Userland/Libraries/LibJS/Runtime/VM.h @@ -204,7 +204,7 @@ class VM : public RefCounted<VM> { void assign(const FlyString& target, Value, GlobalObject&, bool first_assignment = false, EnvironmentRecord* specific_scope = nullptr); void assign(const NonnullRefPtr<BindingPattern>& target, Value, GlobalObject&, bool first_assignment = false, EnvironmentRecord* specific_scope = nullptr); - Reference resolve_binding(FlyString const&); + Reference resolve_binding(GlobalObject&, FlyString const&, EnvironmentRecord* = nullptr); template<typename T, typename... Args> void throw_exception(GlobalObject& global_object, Args&&... args) diff --git a/Userland/Libraries/LibJS/Tests/strict-mode-errors.js b/Userland/Libraries/LibJS/Tests/strict-mode-errors.js index 8c8d756c4f64..acbe586500d9 100644 --- a/Userland/Libraries/LibJS/Tests/strict-mode-errors.js +++ b/Userland/Libraries/LibJS/Tests/strict-mode-errors.js @@ -18,12 +18,9 @@ test("basic functionality", () => { [null, undefined].forEach(primitive => { expect(() => { primitive.foo = "bar"; - }).toThrowWithMessage(TypeError, `Cannot set property 'foo' of ${primitive}`); + }).toThrowWithMessage(TypeError, `${primitive} cannot be converted to an object`); expect(() => { primitive[Symbol.hasInstance] = 123; - }).toThrowWithMessage( - TypeError, - `Cannot set property 'Symbol(Symbol.hasInstance)' of ${primitive}` - ); + }).toThrowWithMessage(TypeError, `${primitive} cannot be converted to an object`); }); });
7adcdecc7bfbaf416f709645a01ebe45e0884705
2022-01-09 18:21:13
Stephan Unverwerth
ak: Add SIMDExtras.h with SIMD related functions
false
Add SIMDExtras.h with SIMD related functions
ak
diff --git a/AK/SIMDExtras.h b/AK/SIMDExtras.h new file mode 100644 index 000000000000..4b4a40611660 --- /dev/null +++ b/AK/SIMDExtras.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2021, Stephan Unverwerth <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/SIMD.h> + +// Returning a vector on i686 target generates warning "psabi". +// This prevents the CI, treating this as an error, from running to completion. +#pragma GCC diagnostic push +#pragma GCC diagnostic warning "-Wpsabi" + +namespace AK::SIMD { + +// SIMD Vector Expansion + +ALWAYS_INLINE static constexpr f32x4 expand4(float f) +{ + return f32x4 { f, f, f, f }; +} + +ALWAYS_INLINE static constexpr i32x4 expand4(i32 i) +{ + return i32x4 { i, i, i, i }; +} + +ALWAYS_INLINE static constexpr u32x4 expand4(u32 u) +{ + return u32x4 { u, u, u, u }; +} + +// Casting + +template<typename TSrc> +ALWAYS_INLINE static u32x4 to_u32x4(TSrc v) +{ + return __builtin_convertvector(v, u32x4); +} + +template<typename TSrc> +ALWAYS_INLINE static i32x4 to_i32x4(TSrc v) +{ + return __builtin_convertvector(v, i32x4); +} + +template<typename TSrc> +ALWAYS_INLINE static f32x4 to_f32x4(TSrc v) +{ + return __builtin_convertvector(v, f32x4); +} + +// Masking + +ALWAYS_INLINE static i32 maskbits(i32x4 mask) +{ +#if defined(__SSE__) + return __builtin_ia32_movmskps((f32x4)mask); +#else + return ((mask[0] & 0x80000000) >> 31) | ((mask[1] & 0x80000000) >> 30) | ((mask[2] & 0x80000000) >> 29) | ((mask[3] & 0x80000000) >> 28); +#endif +} + +ALWAYS_INLINE static bool all(i32x4 mask) +{ + return maskbits(mask) == 15; +} + +ALWAYS_INLINE static bool any(i32x4 mask) +{ + return maskbits(mask) != 0; +} + +ALWAYS_INLINE static bool none(i32x4 mask) +{ + return maskbits(mask) == 0; +} + +ALWAYS_INLINE static int maskcount(i32x4 mask) +{ + constexpr static int count_lut[16] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; + return count_lut[maskbits(mask)]; +} + +// Load / Store + +ALWAYS_INLINE static f32x4 load4(float const* a, float const* b, float const* c, float const* d) +{ + return f32x4 { *a, *b, *c, *d }; +} + +ALWAYS_INLINE static u32x4 load4(u32 const* a, u32 const* b, u32 const* c, u32 const* d) +{ + return u32x4 { *a, *b, *c, *d }; +} + +ALWAYS_INLINE static f32x4 load4_masked(float const* a, float const* b, float const* c, float const* d, i32x4 mask) +{ + int bits = maskbits(mask); + return f32x4 { + bits & 1 ? *a : 0.f, + bits & 2 ? *b : 0.f, + bits & 4 ? *c : 0.f, + bits & 8 ? *d : 0.f, + }; +} + +ALWAYS_INLINE static u32x4 load4_masked(u32 const* a, u32 const* b, u32 const* c, u32 const* d, i32x4 mask) +{ + int bits = maskbits(mask); + return u32x4 { + bits & 1 ? *a : 0u, + bits & 2 ? *b : 0u, + bits & 4 ? *c : 0u, + bits & 8 ? *d : 0u, + }; +} + +template<typename VectorType, typename UnderlyingType = decltype(declval<VectorType>()[0])> +ALWAYS_INLINE static void store4(VectorType v, UnderlyingType* a, UnderlyingType* b, UnderlyingType* c, UnderlyingType* d) +{ + *a = v[0]; + *b = v[1]; + *c = v[2]; + *d = v[3]; +} + +template<typename VectorType, typename UnderlyingType = decltype(declval<VectorType>()[0])> +ALWAYS_INLINE static void store4_masked(VectorType v, UnderlyingType* a, UnderlyingType* b, UnderlyingType* c, UnderlyingType* d, i32x4 mask) +{ + int bits = maskbits(mask); + if (bits & 1) + *a = v[0]; + if (bits & 2) + *b = v[1]; + if (bits & 4) + *c = v[2]; + if (bits & 8) + *d = v[3]; +} + +#pragma GCC diagnostic pop + +}
62d86afee9f9df97559c82d1a68e9eb302ecef1f
2021-12-02 00:52:04
James Mintram
kernel: Add an x86 include check+error in x86/DescriptorTable.h
false
Add an x86 include check+error in x86/DescriptorTable.h
kernel
diff --git a/Kernel/Arch/x86/DescriptorTable.h b/Kernel/Arch/x86/DescriptorTable.h index bffa5f826eb3..bf6f5096723e 100644 --- a/Kernel/Arch/x86/DescriptorTable.h +++ b/Kernel/Arch/x86/DescriptorTable.h @@ -11,6 +11,9 @@ #include <AK/Types.h> #include <Kernel/VirtualAddress.h> +#include <AK/Platform.h> +VALIDATE_IS_X86() + #if ARCH(I386) # define GDT_SELECTOR_CODE0 0x08 # define GDT_SELECTOR_DATA0 0x10
97234a5b9daaa62e2b6cb792b8bd60c554072203
2021-01-27 01:32:46
Nico Weber
libgui: Switch cancel/confirm button order on file picker dialog
false
Switch cancel/confirm button order on file picker dialog
libgui
diff --git a/Userland/Libraries/LibGUI/FilePicker.cpp b/Userland/Libraries/LibGUI/FilePicker.cpp index 8471fa4a072c..cf3b75989c13 100644 --- a/Userland/Libraries/LibGUI/FilePicker.cpp +++ b/Userland/Libraries/LibGUI/FilePicker.cpp @@ -210,13 +210,6 @@ FilePicker::FilePicker(Window* parent_window, Mode mode, Options options, const button_container.layout()->set_spacing(4); button_container.layout()->add_spacer(); - auto& cancel_button = button_container.add<Button>(); - cancel_button.set_fixed_width(80); - cancel_button.set_text("Cancel"); - cancel_button.on_click = [this](auto) { - done(ExecCancel); - }; - auto& ok_button = button_container.add<Button>(); ok_button.set_fixed_width(80); ok_button.set_text(ok_button_name(m_mode)); @@ -224,6 +217,13 @@ FilePicker::FilePicker(Window* parent_window, Mode mode, Options options, const on_file_return(); }; + auto& cancel_button = button_container.add<Button>(); + cancel_button.set_fixed_width(80); + cancel_button.set_text("Cancel"); + cancel_button.on_click = [this](auto) { + done(ExecCancel); + }; + m_view->on_activation = [this](auto& index) { auto& filter_model = (SortingProxyModel&)*m_view->model(); auto local_index = filter_model.map_to_source(index);
57a25139a553d94d89f899eb93ca054301131be1
2021-10-09 02:32:57
Sam Atkins
libweb: Implement `@supports` rule :^)
false
Implement `@supports` rule :^)
libweb
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 9a6f035b4a3a..7916a57a122b 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -25,6 +25,7 @@ set(SOURCES CSS/CSSStyleDeclaration.cpp CSS/CSSStyleRule.cpp CSS/CSSStyleSheet.cpp + CSS/CSSSupportsRule.cpp CSS/ResolvedCSSStyleDeclaration.cpp CSS/DefaultStyleSheetSource.cpp CSS/Length.cpp diff --git a/Userland/Libraries/LibWeb/CSS/CSSRule.h b/Userland/Libraries/LibWeb/CSS/CSSRule.h index fa818bf80638..6d04af17bbb4 100644 --- a/Userland/Libraries/LibWeb/CSS/CSSRule.h +++ b/Userland/Libraries/LibWeb/CSS/CSSRule.h @@ -26,6 +26,7 @@ class CSSRule Style, Import, Media, + Supports, __Count, }; diff --git a/Userland/Libraries/LibWeb/CSS/CSSRuleList.cpp b/Userland/Libraries/LibWeb/CSS/CSSRuleList.cpp index 92f02249d5c5..acca567e8ad9 100644 --- a/Userland/Libraries/LibWeb/CSS/CSSRuleList.cpp +++ b/Userland/Libraries/LibWeb/CSS/CSSRuleList.cpp @@ -8,6 +8,7 @@ #include <LibWeb/CSS/CSSImportRule.h> #include <LibWeb/CSS/CSSMediaRule.h> #include <LibWeb/CSS/CSSRuleList.h> +#include <LibWeb/CSS/CSSSupportsRule.h> #include <LibWeb/DOM/ExceptionOr.h> namespace Web::CSS { @@ -93,6 +94,9 @@ void CSSRuleList::for_each_effective_style_rule(Function<void(CSSStyleRule const case CSSRule::Type::Media: verify_cast<CSSMediaRule>(rule).for_each_effective_style_rule(callback); break; + case CSSRule::Type::Supports: + verify_cast<CSSSupportsRule>(rule).for_each_effective_style_rule(callback); + break; case CSSRule::Type::__Count: VERIFY_NOT_REACHED(); } @@ -114,6 +118,8 @@ bool CSSRuleList::for_first_not_loaded_import_rule(Function<void(CSSImportRule&) } } else if (rule.type() == CSSRule::Type::Media) { return verify_cast<CSSMediaRule>(rule).for_first_not_loaded_import_rule(callback); + } else if (rule.type() == CSSRule::Type::Supports) { + return verify_cast<CSSSupportsRule>(rule).for_first_not_loaded_import_rule(callback); } } diff --git a/Userland/Libraries/LibWeb/CSS/CSSSupportsRule.cpp b/Userland/Libraries/LibWeb/CSS/CSSSupportsRule.cpp new file mode 100644 index 000000000000..b949d41697f3 --- /dev/null +++ b/Userland/Libraries/LibWeb/CSS/CSSSupportsRule.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/CSS/CSSSupportsRule.h> +#include <LibWeb/CSS/Parser/Parser.h> + +namespace Web::CSS { + +CSSSupportsRule::CSSSupportsRule(NonnullRefPtr<Supports>&& supports, NonnullRefPtrVector<CSSRule>&& rules) + : CSSConditionRule(move(rules)) + , m_supports(move(supports)) +{ +} + +CSSSupportsRule::~CSSSupportsRule() +{ +} + +String CSSSupportsRule::condition_text() const +{ + // FIXME: Serializing supports rules! + return "<supports-condition>"; +} + +void CSSSupportsRule::set_condition_text(String text) +{ + if (auto new_supports = parse_css_supports({}, text)) + m_supports = new_supports.release_nonnull(); +} + +} diff --git a/Userland/Libraries/LibWeb/CSS/CSSSupportsRule.h b/Userland/Libraries/LibWeb/CSS/CSSSupportsRule.h new file mode 100644 index 000000000000..890fb563cf28 --- /dev/null +++ b/Userland/Libraries/LibWeb/CSS/CSSSupportsRule.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/NonnullRefPtr.h> +#include <AK/NonnullRefPtrVector.h> +#include <LibWeb/CSS/CSSConditionRule.h> +#include <LibWeb/CSS/CSSRule.h> +#include <LibWeb/CSS/Supports.h> +#include <LibWeb/Forward.h> + +namespace Web::CSS { + +// https://www.w3.org/TR/css-conditional-3/#the-csssupportsrule-interface +class CSSSupportsRule final : public CSSConditionRule { + AK_MAKE_NONCOPYABLE(CSSSupportsRule); + AK_MAKE_NONMOVABLE(CSSSupportsRule); + +public: + static NonnullRefPtr<CSSSupportsRule> create(NonnullRefPtr<Supports>&& supports, NonnullRefPtrVector<CSSRule>&& rules) + { + return adopt_ref(*new CSSSupportsRule(move(supports), move(rules))); + } + + ~CSSSupportsRule(); + + virtual StringView class_name() const override { return "CSSSupportsRule"; }; + virtual Type type() const override { return Type::Supports; }; + + String condition_text() const override; + void set_condition_text(String) override; + virtual bool condition_matches() const override { return m_supports->matches(); } + +private: + explicit CSSSupportsRule(NonnullRefPtr<Supports>&&, NonnullRefPtrVector<CSSRule>&&); + + NonnullRefPtr<Supports> m_supports; +}; + +template<> +inline bool CSSRule::fast_is<CSSSupportsRule>() const { return type() == CSSRule::Type::Supports; } + +} diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index 3e07c61ded34..3c5f8f5b3a6d 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -16,6 +16,7 @@ #include <LibWeb/CSS/CSSStyleDeclaration.h> #include <LibWeb/CSS/CSSStyleRule.h> #include <LibWeb/CSS/CSSStyleSheet.h> +#include <LibWeb/CSS/CSSSupportsRule.h> #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h> #include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/CSS/Parser/StyleBlockRule.h> @@ -1735,6 +1736,29 @@ RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule) return CSSImportRule::create(url.value()); else dbgln("Unable to parse url from @import rule"); + + } else if (rule->m_name.equals_ignoring_case("supports"sv)) { + + auto supports_tokens = TokenStream { rule->prelude() }; + auto supports = parse_a_supports(supports_tokens); + if (!supports) { + if constexpr (CSS_PARSER_DEBUG) { + dbgln("CSSParser: @supports rule invalid; discarding."); + supports_tokens.dump_all_tokens(); + } + return {}; + } + + auto child_tokens = TokenStream { rule->block().values() }; + auto parser_rules = consume_a_list_of_rules(child_tokens, false); + NonnullRefPtrVector<CSSRule> child_rules; + for (auto& raw_rule : parser_rules) { + if (auto child_rule = convert_to_rule(raw_rule)) + child_rules.append(*child_rule); + } + + return CSSSupportsRule::create(supports.release_nonnull(), move(child_rules)); + } else { dbgln("Unrecognized CSS at-rule: @{}", rule->m_name); } diff --git a/Userland/Libraries/LibWeb/Dump.cpp b/Userland/Libraries/LibWeb/Dump.cpp index ecad72e0be20..bd805aa60f39 100644 --- a/Userland/Libraries/LibWeb/Dump.cpp +++ b/Userland/Libraries/LibWeb/Dump.cpp @@ -13,6 +13,7 @@ #include <LibWeb/CSS/CSSRule.h> #include <LibWeb/CSS/CSSStyleRule.h> #include <LibWeb/CSS/CSSStyleSheet.h> +#include <LibWeb/CSS/CSSSupportsRule.h> #include <LibWeb/CSS/PropertyID.h> #include <LibWeb/DOM/Comment.h> #include <LibWeb/DOM/Document.h> @@ -500,6 +501,9 @@ void dump_rule(StringBuilder& builder, CSS::CSSRule const& rule, int indent_leve case CSS::CSSRule::Type::Media: dump_media_rule(builder, verify_cast<CSS::CSSMediaRule const>(rule), indent_levels); break; + case CSS::CSSRule::Type::Supports: + dump_supports_rule(builder, verify_cast<CSS::CSSSupportsRule const>(rule), indent_levels); + break; case CSS::CSSRule::Type::__Count: VERIFY_NOT_REACHED(); } @@ -521,6 +525,16 @@ void dump_media_rule(StringBuilder& builder, CSS::CSSMediaRule const& media, int } } +void dump_supports_rule(StringBuilder& builder, CSS::CSSSupportsRule const& supports, int indent_levels) +{ + indent(builder, indent_levels); + builder.appendff(" Supports: {}\n Rules ({}):\n", supports.condition_text(), supports.css_rules().length()); + + for (auto& rule : supports.css_rules()) { + dump_rule(builder, rule, indent_levels + 1); + } +} + void dump_style_rule(StringBuilder& builder, CSS::CSSStyleRule const& rule, int indent_levels) { for (auto& selector : rule.selectors()) { diff --git a/Userland/Libraries/LibWeb/Dump.h b/Userland/Libraries/LibWeb/Dump.h index 885e46ef08ca..81a7d4040a51 100644 --- a/Userland/Libraries/LibWeb/Dump.h +++ b/Userland/Libraries/LibWeb/Dump.h @@ -23,6 +23,7 @@ void dump_rule(CSS::CSSRule const&); void dump_style_rule(StringBuilder&, CSS::CSSStyleRule const&, int indent_levels = 0); void dump_import_rule(StringBuilder&, CSS::CSSImportRule const&, int indent_levels = 0); void dump_media_rule(StringBuilder&, CSS::CSSMediaRule const&, int indent_levels = 0); +void dump_supports_rule(StringBuilder&, CSS::CSSSupportsRule const&, int indent_levels = 0); void dump_selector(StringBuilder&, CSS::Selector const&); void dump_selector(CSS::Selector const&); diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index cdc6d6a33bd4..4d01a66e97b2 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -26,6 +26,7 @@ class CSSRuleList; class CSSStyleDeclaration; class CSSStyleRule; class CSSStyleSheet; +class CSSSupportsRule; class Display; class ElementInlineCSSStyleDeclaration; class Length;
46f42d9755650b4187b67fbdd70f0dac167eb4af
2023-08-20 23:34:10
MacDue
libweb: Add support for the SVG gradient spreadMethod attribute
false
Add support for the SVG gradient spreadMethod attribute
libweb
diff --git a/Userland/Libraries/LibWeb/SVG/AttributeParser.cpp b/Userland/Libraries/LibWeb/SVG/AttributeParser.cpp index d219c97571de..f4149eb2a57c 100644 --- a/Userland/Libraries/LibWeb/SVG/AttributeParser.cpp +++ b/Userland/Libraries/LibWeb/SVG/AttributeParser.cpp @@ -509,6 +509,21 @@ Optional<GradientUnits> AttributeParser::parse_gradient_units(StringView input) return {}; } +// https://svgwg.org/svg2-draft/pservers.html#RadialGradientElementSpreadMethodAttribute +Optional<SpreadMethod> AttributeParser::parse_spread_method(StringView input) +{ + GenericLexer lexer { input }; + lexer.ignore_while(whitespace); + auto spread_method_string = lexer.consume_until(whitespace); + if (spread_method_string == "pad"sv) + return SpreadMethod::Pad; + if (spread_method_string == "repeat"sv) + return SpreadMethod::Repeat; + if (spread_method_string == "reflect"sv) + return SpreadMethod::Reflect; + return {}; +} + // https://drafts.csswg.org/css-transforms/#svg-syntax Optional<Vector<Transform>> AttributeParser::parse_transform() { diff --git a/Userland/Libraries/LibWeb/SVG/AttributeParser.h b/Userland/Libraries/LibWeb/SVG/AttributeParser.h index de1c72d22fdb..773e88697081 100644 --- a/Userland/Libraries/LibWeb/SVG/AttributeParser.h +++ b/Userland/Libraries/LibWeb/SVG/AttributeParser.h @@ -93,6 +93,12 @@ enum class GradientUnits { UserSpaceOnUse }; +enum class SpreadMethod { + Pad, + Repeat, + Reflect +}; + class NumberPercentage { public: NumberPercentage(float value, bool is_percentage) @@ -144,6 +150,7 @@ class AttributeParser final { static Optional<Vector<Transform>> parse_transform(StringView input); static Optional<PreserveAspectRatio> parse_preserve_aspect_ratio(StringView input); static Optional<GradientUnits> parse_gradient_units(StringView input); + static Optional<SpreadMethod> parse_spread_method(StringView input); private: AttributeParser(StringView source); diff --git a/Userland/Libraries/LibWeb/SVG/SVGGradientElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGGradientElement.cpp index 6e403c406985..972986bcca6f 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGGradientElement.cpp +++ b/Userland/Libraries/LibWeb/SVG/SVGGradientElement.cpp @@ -22,6 +22,8 @@ void SVGGradientElement::attribute_changed(DeprecatedFlyString const& name, Depr SVGElement::attribute_changed(name, value); if (name == AttributeNames::gradientUnits) { m_gradient_units = AttributeParser::parse_gradient_units(value); + } else if (name == AttributeNames::spreadMethod) { + m_spread_method = AttributeParser::parse_spread_method(value); } else if (name == AttributeNames::gradientTransform) { if (auto transform_list = AttributeParser::parse_transform(value); transform_list.has_value()) { m_gradient_transform = transform_from_transform_list(*transform_list); @@ -40,6 +42,15 @@ GradientUnits SVGGradientElement::gradient_units() const return GradientUnits::ObjectBoundingBox; } +SpreadMethod SVGGradientElement::spread_method() const +{ + if (m_spread_method.has_value()) + return *m_spread_method; + if (auto gradient = linked_gradient()) + return gradient->spread_method(); + return SpreadMethod::Pad; +} + Optional<Gfx::AffineTransform> SVGGradientElement::gradient_transform() const { if (m_gradient_transform.has_value()) diff --git a/Userland/Libraries/LibWeb/SVG/SVGGradientElement.h b/Userland/Libraries/LibWeb/SVG/SVGGradientElement.h index 536d49038dc2..b4feb74b8bce 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGGradientElement.h +++ b/Userland/Libraries/LibWeb/SVG/SVGGradientElement.h @@ -20,6 +20,20 @@ struct SVGPaintContext { Gfx::AffineTransform transform; }; +inline Gfx::SVGGradientPaintStyle::SpreadMethod to_gfx_spread_method(SpreadMethod spread_method) +{ + switch (spread_method) { + case SpreadMethod::Pad: + return Gfx::SVGGradientPaintStyle::SpreadMethod::Pad; + case SpreadMethod::Reflect: + return Gfx::SVGGradientPaintStyle::SpreadMethod::Reflect; + case SpreadMethod::Repeat: + return Gfx::SVGGradientPaintStyle::SpreadMethod::Repeat; + default: + VERIFY_NOT_REACHED(); + } +} + class SVGGradientElement : public SVGElement { WEB_PLATFORM_OBJECT(SVGGradientElement, SVGElement); @@ -32,6 +46,8 @@ class SVGGradientElement : public SVGElement { GradientUnits gradient_units() const; + SpreadMethod spread_method() const; + Optional<Gfx::AffineTransform> gradient_transform() const; protected: @@ -61,6 +77,7 @@ class SVGGradientElement : public SVGElement { private: Optional<GradientUnits> m_gradient_units = {}; + Optional<SpreadMethod> m_spread_method = {}; Optional<Gfx::AffineTransform> m_gradient_transform = {}; }; diff --git a/Userland/Libraries/LibWeb/SVG/SVGLinearGradientElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGLinearGradientElement.cpp index 9a2363f04adf..de2bee93ca9f 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGLinearGradientElement.cpp +++ b/Userland/Libraries/LibWeb/SVG/SVGLinearGradientElement.cpp @@ -131,6 +131,7 @@ Optional<Gfx::PaintStyle const&> SVGLinearGradientElement::to_gfx_paint_style(SV } m_paint_style->set_gradient_transform(gradient_paint_transform(paint_context)); + m_paint_style->set_spread_method(to_gfx_spread_method(spread_method())); return *m_paint_style; } diff --git a/Userland/Libraries/LibWeb/SVG/SVGRadialGradientElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGRadialGradientElement.cpp index 935442662a86..9a7fa7181cdd 100644 --- a/Userland/Libraries/LibWeb/SVG/SVGRadialGradientElement.cpp +++ b/Userland/Libraries/LibWeb/SVG/SVGRadialGradientElement.cpp @@ -172,6 +172,7 @@ Optional<Gfx::PaintStyle const&> SVGRadialGradientElement::to_gfx_paint_style(SV m_paint_style->set_end_radius(end_radius); } m_paint_style->set_gradient_transform(gradient_paint_transform(paint_context)); + m_paint_style->set_spread_method(to_gfx_spread_method(spread_method())); return *m_paint_style; }
8540c4e574e269de667ed061908276895d8ebd8f
2022-11-26 03:19:59
Andreas Kling
libweb: Implement [SameObject] for HTMLTableElement.{rows,tBodies}
false
Implement [SameObject] for HTMLTableElement.{rows,tBodies}
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp index d779dabce881..5bf12f966522 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp @@ -25,6 +25,13 @@ HTMLTableElement::HTMLTableElement(DOM::Document& document, DOM::QualifiedName q HTMLTableElement::~HTMLTableElement() = default; +void HTMLTableElement::visit_edges(Cell::Visitor& visitor) +{ + Base::visit_edges(visitor); + visitor.visit(m_rows); + visitor.visit(m_t_bodies); +} + void HTMLTableElement::apply_presentational_hints(CSS::StyleProperties& style) const { for_each_attribute([&](auto& name, auto& value) { @@ -221,11 +228,17 @@ void HTMLTableElement::delete_t_foot() } } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-tbodies JS::NonnullGCPtr<DOM::HTMLCollection> HTMLTableElement::t_bodies() { - return DOM::HTMLCollection::create(*this, [](DOM::Element const& element) { - return element.local_name() == TagNames::tbody; - }); + // The tBodies attribute must return an HTMLCollection rooted at the table node, + // whose filter matches only tbody elements that are children of the table element. + if (!m_t_bodies) { + m_t_bodies = DOM::HTMLCollection::create(*this, [](DOM::Element const& element) { + return element.local_name() == TagNames::tbody; + }); + } + return *m_t_bodies; } JS::NonnullGCPtr<HTMLTableSectionElement> HTMLTableElement::create_t_body() @@ -252,6 +265,7 @@ JS::NonnullGCPtr<HTMLTableSectionElement> HTMLTableElement::create_t_body() return static_cast<HTMLTableSectionElement&>(*tbody); } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-rows JS::NonnullGCPtr<DOM::HTMLCollection> HTMLTableElement::rows() { HTMLTableElement* table_node = this; @@ -261,23 +275,26 @@ JS::NonnullGCPtr<DOM::HTMLCollection> HTMLTableElement::rows() // still in tree order. // How do you sort HTMLCollection? - return DOM::HTMLCollection::create(*this, [table_node](DOM::Element const& element) { - // Only match TR elements which are: - // * children of the table element - // * children of the thead, tbody, or tfoot elements that are themselves children of the table element - if (!is<HTMLTableRowElement>(element)) { - return false; - } - if (element.parent_element() == table_node) - return true; + if (!m_rows) { + m_rows = DOM::HTMLCollection::create(*this, [table_node](DOM::Element const& element) { + // Only match TR elements which are: + // * children of the table element + // * children of the thead, tbody, or tfoot elements that are themselves children of the table element + if (!is<HTMLTableRowElement>(element)) { + return false; + } + if (element.parent_element() == table_node) + return true; - if (element.parent_element() && (element.parent_element()->local_name() == TagNames::thead || element.parent_element()->local_name() == TagNames::tbody || element.parent_element()->local_name() == TagNames::tfoot) - && element.parent()->parent() == table_node) { - return true; - } + if (element.parent_element() && (element.parent_element()->local_name() == TagNames::thead || element.parent_element()->local_name() == TagNames::tbody || element.parent_element()->local_name() == TagNames::tfoot) + && element.parent()->parent() == table_node) { + return true; + } - return false; - }); + return false; + }); + } + return *m_rows; } WebIDL::ExceptionOr<JS::NonnullGCPtr<HTMLTableRowElement>> HTMLTableElement::insert_row(long index) diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.h b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.h index e18dd4058b95..d9fa4e9e9f18 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.h +++ b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.h @@ -45,7 +45,12 @@ class HTMLTableElement final : public HTMLElement { private: HTMLTableElement(DOM::Document&, DOM::QualifiedName); + virtual void visit_edges(Cell::Visitor&) override; + virtual void apply_presentational_hints(CSS::StyleProperties&) const override; + + JS::GCPtr<DOM::HTMLCollection> mutable m_rows; + JS::GCPtr<DOM::HTMLCollection> mutable m_t_bodies; }; }
6d150df58a0b64c4cb583fc374fd05e60d387dc6
2019-10-13 02:05:23
Calvin Buckley
libc: Add readdir_r for re-entrant directory reading (#648)
false
Add readdir_r for re-entrant directory reading (#648)
libc
diff --git a/Libraries/LibC/dirent.cpp b/Libraries/LibC/dirent.cpp index 1d6f82b7336f..6ab0fa4de8c0 100644 --- a/Libraries/LibC/dirent.cpp +++ b/Libraries/LibC/dirent.cpp @@ -50,6 +50,47 @@ struct [[gnu::packed]] sys_dirent } }; +static void create_struct_dirent(sys_dirent* sys_ent, struct dirent* str_ent) +{ + str_ent->d_ino = sys_ent->ino; + str_ent->d_type = sys_ent->file_type; + str_ent->d_off = 0; + str_ent->d_reclen = sys_ent->total_size(); + for (size_t i = 0; i < sys_ent->namelen; ++i) + str_ent->d_name[i] = sys_ent->name[i]; + // FIXME: I think this null termination behavior is not supposed to be here. + str_ent->d_name[sys_ent->namelen] = '\0'; +} + +static int allocate_dirp_buffer(DIR* dirp) +{ + if (dirp->buffer) { + return 0; + } + + struct stat st; + // preserve errno since this could be a reentrant call + int old_errno = errno; + int rc = fstat(dirp->fd, &st); + if (rc < 0) { + int new_errno = errno; + errno = old_errno; + return new_errno; + } + size_t size_to_allocate = max(st.st_size, 4096); + dirp->buffer = (char*)malloc(size_to_allocate); + ssize_t nread = syscall(SC_get_dir_entries, dirp->fd, dirp->buffer, size_to_allocate); + if (nread < 0) { + // uh-oh, the syscall returned an error + free(dirp->buffer); + dirp->buffer = nullptr; + return -nread; + } + dirp->buffer_size = nread; + dirp->nextptr = dirp->buffer; + return 0; +} + dirent* readdir(DIR* dirp) { if (!dirp) @@ -57,35 +98,75 @@ dirent* readdir(DIR* dirp) if (dirp->fd == -1) return nullptr; - if (!dirp->buffer) { - struct stat st; - int rc = fstat(dirp->fd, &st); - if (rc < 0) - return nullptr; - size_t size_to_allocate = max(st.st_size, 4096); - dirp->buffer = (char*)malloc(size_to_allocate); - ssize_t nread = syscall(SC_get_dir_entries, dirp->fd, dirp->buffer, size_to_allocate); - dirp->buffer_size = nread; - dirp->nextptr = dirp->buffer; + if (int new_errno = allocate_dirp_buffer(dirp)) { + // readdir is allowed to mutate errno + errno = new_errno; + return nullptr; } if (dirp->nextptr >= (dirp->buffer + dirp->buffer_size)) return nullptr; auto* sys_ent = (sys_dirent*)dirp->nextptr; - dirp->cur_ent.d_ino = sys_ent->ino; - dirp->cur_ent.d_type = sys_ent->file_type; - dirp->cur_ent.d_off = 0; - dirp->cur_ent.d_reclen = sys_ent->total_size(); - for (size_t i = 0; i < sys_ent->namelen; ++i) - dirp->cur_ent.d_name[i] = sys_ent->name[i]; - // FIXME: I think this null termination behavior is not supposed to be here. - dirp->cur_ent.d_name[sys_ent->namelen] = '\0'; + create_struct_dirent(sys_ent, &dirp->cur_ent); dirp->nextptr += sys_ent->total_size(); return &dirp->cur_ent; } +static bool compare_sys_struct_dirent(sys_dirent* sys_ent, struct dirent* str_ent) +{ + size_t namelen = min((size_t)256, sys_ent->namelen); + // These fields are guaranteed by create_struct_dirent to be the same + return sys_ent->ino == str_ent->d_ino + && sys_ent->file_type == str_ent->d_type + && sys_ent->total_size() == str_ent->d_reclen + && strncmp(sys_ent->name, str_ent->d_name, namelen) == 0; +} + +int readdir_r(DIR* dirp, struct dirent* entry, struct dirent** result) +{ + if (!dirp || dirp->fd == -1) { + *result = nullptr; + return EBADF; + } + + if (int new_errno = allocate_dirp_buffer(dirp)) { + *result = nullptr; + return new_errno; + } + + // This doesn't care about dirp state; seek until we find the entry. + // Unfortunately, we can't just compare struct dirent to sys_dirent, so + // manually compare the fields. This seems a bit risky, but could work. + auto* buffer = dirp->buffer; + auto* sys_ent = (sys_dirent*)buffer; + bool found = false; + while (!(found || buffer >= dirp->buffer + dirp->buffer_size)) { + found = compare_sys_struct_dirent(sys_ent, entry); + + // Make sure if we found one, it's the one after (end of buffer or not) + buffer += sys_ent->total_size(); + sys_ent = (sys_dirent*)buffer; + } + + // If we found one, but hit end of buffer, then EOD + if (found && buffer >= dirp->buffer + dirp->buffer_size) { + *result = nullptr; + return 0; + } + // If we never found a match for entry in buffer, start from the beginning + else if (!found) { + buffer = dirp->buffer; + sys_ent = (sys_dirent*)buffer; + } + + *result = entry; + create_struct_dirent(sys_ent, entry); + + return 0; +} + int dirfd(DIR* dirp) { ASSERT(dirp); diff --git a/Libraries/LibC/dirent.h b/Libraries/LibC/dirent.h index b127489a9200..4b05813c8496 100644 --- a/Libraries/LibC/dirent.h +++ b/Libraries/LibC/dirent.h @@ -25,6 +25,7 @@ typedef struct __DIR DIR; DIR* opendir(const char* name); int closedir(DIR*); struct dirent* readdir(DIR*); +int readdir_r(DIR*, struct dirent*, struct dirent**); int dirfd(DIR*); __END_DECLS
460c2caaf73b5384f0eebb2b18e174dbc25246a5
2022-02-06 21:19:54
Timothy Flynn
libjs: Implement BigInt.asIntN
false
Implement BigInt.asIntN
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp b/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp index 9ae52c2abd3d..fd64dbb14195 100644 --- a/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/BigIntConstructor.cpp @@ -5,6 +5,7 @@ */ #include <AK/String.h> +#include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/BigInt.h> #include <LibJS/Runtime/BigIntConstructor.h> #include <LibJS/Runtime/BigIntObject.h> @@ -14,6 +15,8 @@ namespace JS { +static const Crypto::SignedBigInteger BIGINT_ONE { 1 }; + BigIntConstructor::BigIntConstructor(GlobalObject& global_object) : NativeFunction(vm().names.BigInt.as_string(), *global_object.function_prototype()) { @@ -27,9 +30,8 @@ void BigIntConstructor::initialize(GlobalObject& global_object) // 21.2.2.3 BigInt.prototype, https://tc39.es/ecma262/#sec-bigint.prototype define_direct_property(vm.names.prototype, global_object.bigint_prototype(), 0); - // TODO: Implement these functions below and uncomment this. - // u8 attr = Attribute::Writable | Attribute::Configurable; - // define_native_function(vm.names.asIntN, as_int_n, 2, attr); + u8 attr = Attribute::Writable | Attribute::Configurable; + define_native_function(vm.names.asIntN, as_int_n, 2, attr); // define_native_function(vm.names.asUintN, as_uint_n, 2, attr); define_direct_property(vm.names.length, Value(1), Attribute::Configurable); @@ -67,7 +69,27 @@ ThrowCompletionOr<Object*> BigIntConstructor::construct(FunctionObject&) // 21.2.2.1 BigInt.asIntN ( bits, bigint ), https://tc39.es/ecma262/#sec-bigint.asintn JS_DEFINE_NATIVE_FUNCTION(BigIntConstructor::as_int_n) { - TODO(); + // 1. Set bits to ? ToIndex(bits). + auto bits = TRY(vm.argument(0).to_index(global_object)); + + // 2. Set bigint to ? ToBigInt(bigint). + auto* bigint = TRY(vm.argument(1).to_bigint(global_object)); + + // 3. Let mod be ℝ(bigint) modulo 2^bits. + // FIXME: For large values of `bits`, this can likely be improved with a SignedBigInteger API to + // drop the most significant bits. + auto bits_shift_left = BIGINT_ONE.shift_left(bits); + auto mod = modulo(bigint->big_integer(), bits_shift_left); + + // 4. If mod ≥ 2^(bits-1), return ℤ(mod - 2^bits); otherwise, return ℤ(mod). + // NOTE: Some of the below conditionals are non-standard, but are to protect SignedBigInteger from + // allocating an absurd amount of memory if `bits - 1` overflows to NumericLimits<size_t>::max. + if ((bits == 0) && (mod >= BIGINT_ONE)) + return js_bigint(vm, mod.minus(bits_shift_left)); + if ((bits > 0) && (mod >= BIGINT_ONE.shift_left(bits - 1))) + return js_bigint(vm, mod.minus(bits_shift_left)); + + return js_bigint(vm, mod); } // 21.2.2.2 BigInt.asUintN ( bits, bigint ), https://tc39.es/ecma262/#sec-bigint.asuintn diff --git a/Userland/Libraries/LibJS/Tests/builtins/BigInt/BigInt.asIntN.js b/Userland/Libraries/LibJS/Tests/builtins/BigInt/BigInt.asIntN.js new file mode 100644 index 000000000000..e448a7c72a8e --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/BigInt/BigInt.asIntN.js @@ -0,0 +1,79 @@ +describe("errors", () => { + test("invalid index", () => { + expect(() => { + BigInt.asIntN(-1, 0n); + }).toThrowWithMessage(RangeError, "Index must be a positive integer"); + + expect(() => { + BigInt.asIntN(Symbol(), 0n); + }).toThrowWithMessage(TypeError, "Cannot convert symbol to number"); + }); + + test("invalid BigInt", () => { + expect(() => { + BigInt.asIntN(1, 1); + }).toThrowWithMessage(TypeError, "Cannot convert number to BigInt"); + + expect(() => { + BigInt.asIntN(1, Symbol()); + }).toThrowWithMessage(TypeError, "Cannot convert symbol to BigInt"); + + expect(() => { + BigInt.asIntN(1, "foo"); + }).toThrowWithMessage(SyntaxError, "Invalid value for BigInt: foo"); + }); +}); + +describe("correct behavior", () => { + test("length is 2", () => { + expect(BigInt.asIntN).toHaveLength(2); + }); + + test("basic functionality", () => { + expect(BigInt.asIntN(0, -2n)).toBe(0n); + expect(BigInt.asIntN(0, -1n)).toBe(0n); + expect(BigInt.asIntN(0, 0n)).toBe(0n); + expect(BigInt.asIntN(0, 1n)).toBe(0n); + expect(BigInt.asIntN(0, 2n)).toBe(0n); + + expect(BigInt.asIntN(1, -3n)).toBe(-1n); + expect(BigInt.asIntN(1, -2n)).toBe(0n); + expect(BigInt.asIntN(1, -1n)).toBe(-1n); + expect(BigInt.asIntN(1, 0n)).toBe(0n); + expect(BigInt.asIntN(1, 1n)).toBe(-1n); + expect(BigInt.asIntN(1, 2n)).toBe(0n); + expect(BigInt.asIntN(1, 3n)).toBe(-1n); + + expect(BigInt.asIntN(2, -3n)).toBe(1n); + expect(BigInt.asIntN(2, -2n)).toBe(-2n); + expect(BigInt.asIntN(2, -1n)).toBe(-1n); + expect(BigInt.asIntN(2, 0n)).toBe(0n); + expect(BigInt.asIntN(2, 1n)).toBe(1n); + expect(BigInt.asIntN(2, 2n)).toBe(-2n); + expect(BigInt.asIntN(2, 3n)).toBe(-1n); + + expect(BigInt.asIntN(4, -3n)).toBe(-3n); + expect(BigInt.asIntN(4, -2n)).toBe(-2n); + expect(BigInt.asIntN(4, -1n)).toBe(-1n); + expect(BigInt.asIntN(4, 0n)).toBe(0n); + expect(BigInt.asIntN(4, 1n)).toBe(1n); + expect(BigInt.asIntN(4, 2n)).toBe(2n); + expect(BigInt.asIntN(4, 3n)).toBe(3n); + + const extremelyBigInt = 123456789123456789123456789123456789123456789123456789n; + + expect(BigInt.asIntN(0, extremelyBigInt)).toBe(0n); + expect(BigInt.asIntN(1, extremelyBigInt)).toBe(-1n); + expect(BigInt.asIntN(2, extremelyBigInt)).toBe(1n); + expect(BigInt.asIntN(4, extremelyBigInt)).toBe(5n); + expect(BigInt.asIntN(128, extremelyBigInt)).toBe(-99061374399389259395070030194384019691n); + expect(BigInt.asIntN(256, extremelyBigInt)).toBe(extremelyBigInt); + + expect(BigInt.asIntN(0, -extremelyBigInt)).toBe(0n); + expect(BigInt.asIntN(1, -extremelyBigInt)).toBe(-1n); + expect(BigInt.asIntN(2, -extremelyBigInt)).toBe(-1n); + expect(BigInt.asIntN(4, -extremelyBigInt)).toBe(-5n); + expect(BigInt.asIntN(128, -extremelyBigInt)).toBe(99061374399389259395070030194384019691n); + expect(BigInt.asIntN(256, -extremelyBigInt)).toBe(-extremelyBigInt); + }); +});
858f6dc1d1b7026a857567f59bf4a7d315b31cbf
2020-07-12 02:46:16
Linus Groh
systemmonitor: Parse /proc/cpuinfo as JSON
false
Parse /proc/cpuinfo as JSON
systemmonitor
diff --git a/Applications/SystemMonitor/ProcessModel.cpp b/Applications/SystemMonitor/ProcessModel.cpp index 47a04182166a..5fe335378147 100644 --- a/Applications/SystemMonitor/ProcessModel.cpp +++ b/Applications/SystemMonitor/ProcessModel.cpp @@ -54,38 +54,13 @@ ProcessModel::ProcessModel() auto file = Core::File::construct("/proc/cpuinfo"); if (file->open(Core::IODevice::ReadOnly)) { - OwnPtr<CpuInfo> cpu; - u32 cpu_id = 0; - while (file->can_read_line()) { - auto line = file->read_line(1024); - if (line.is_null()) - continue; - - auto str = String::copy(line, Chomp); - if (str.is_empty() && cpu) - m_cpus.append(cpu.release_nonnull()); - - size_t i; - bool have_val = false; - for (i = 0; i < str.length(); i++) { - if (str[i] == ':') { - have_val = true; - break; - } - } - if (!have_val) - continue; - auto key = str.substring(0, i); - auto val = str.substring(i + 1, str.length() - i - 1).trim_whitespace(); - - if (!cpu) - cpu = make<CpuInfo>(cpu_id++); - - cpu->values.set(key, val); - } - - if (cpu) - m_cpus.append(cpu.release_nonnull()); + auto json = JsonValue::from_string({ file->read_all() }); + auto cpuinfo_array = json.value().as_array(); + cpuinfo_array.for_each([&](auto& value) { + auto& cpu_object = value.as_object(); + auto cpu_id = cpu_object.get("processor").as_u32(); + m_cpus.append(make<CpuInfo>(cpu_id)); + }); } if (m_cpus.is_empty()) diff --git a/Applications/SystemMonitor/ProcessModel.h b/Applications/SystemMonitor/ProcessModel.h index a30ab4ff29e6..e6f254d9a4cf 100644 --- a/Applications/SystemMonitor/ProcessModel.h +++ b/Applications/SystemMonitor/ProcessModel.h @@ -89,14 +89,12 @@ class ProcessModel final : public GUI::Model { virtual GUI::Variant data(const GUI::ModelIndex&, Role = Role::Display) const override; virtual void update() override; - struct CpuInfo - { + struct CpuInfo { u32 id; - float total_cpu_percent{0.0}; - HashMap<String, String> values; - - CpuInfo(u32 id): - id(id) + float total_cpu_percent { 0.0 }; + + CpuInfo(u32 id) + : id(id) { } };
e339c2bce803288287f601b3a0f8404ed031796e
2019-12-09 04:11:02
Andreas Kling
windowserver: Disambiguate "dragging" a bit, use "moving" more instead
false
Disambiguate "dragging" a bit, use "moving" more instead
windowserver
diff --git a/Base/home/anon/WindowManager.ini b/Base/home/anon/WindowManager.ini index 320767ba04e5..4ad27fcfe928 100644 --- a/Base/home/anon/WindowManager.ini +++ b/Base/home/anon/WindowManager.ini @@ -24,9 +24,9 @@ InactiveWindowBorder=128,128,128 InactiveWindowBorder2=192,192,192 InactiveWindowTitle=213,208,199 -DraggingWindowBorder=161,50,13 -DraggingWindowBorder2=250,220,187 -DraggingWindowTitle=255,255,255 +MovingWindowBorder=161,50,13 +MovingWindowBorder2=250,220,187 +MovingWindowTitle=255,255,255 HighlightWindowBorder=161,13,13 HighlightWindowBorder2=250,187,187 diff --git a/Servers/WindowServer/WSCompositor.cpp b/Servers/WindowServer/WSCompositor.cpp index 51d1e55e9764..459cc301ed8d 100644 --- a/Servers/WindowServer/WSCompositor.cpp +++ b/Servers/WindowServer/WSCompositor.cpp @@ -397,7 +397,7 @@ void WSCompositor::invalidate_cursor() void WSCompositor::draw_geometry_label() { auto& wm = WSWindowManager::the(); - auto* window_being_moved_or_resized = wm.m_drag_window ? wm.m_drag_window.ptr() : (wm.m_resize_window ? wm.m_resize_window.ptr() : nullptr); + auto* window_being_moved_or_resized = wm.m_move_window ? wm.m_move_window.ptr() : (wm.m_resize_window ? wm.m_resize_window.ptr() : nullptr); if (!window_being_moved_or_resized) { m_last_geometry_label_rect = {}; return; diff --git a/Servers/WindowServer/WSWindowFrame.cpp b/Servers/WindowServer/WSWindowFrame.cpp index 01fbd0cfecae..3b4801a26cf8 100644 --- a/Servers/WindowServer/WSWindowFrame.cpp +++ b/Servers/WindowServer/WSWindowFrame.cpp @@ -173,10 +173,10 @@ void WSWindowFrame::paint(Painter& painter) border_color = wm.m_highlight_window_border_color; border_color2 = wm.m_highlight_window_border_color2; title_color = wm.m_highlight_window_title_color; - } else if (&window == wm.m_drag_window) { - border_color = wm.m_dragging_window_border_color; - border_color2 = wm.m_dragging_window_border_color2; - title_color = wm.m_dragging_window_title_color; + } else if (&window == wm.m_move_window) { + border_color = wm.m_moving_window_border_color; + border_color2 = wm.m_moving_window_border_color2; + title_color = wm.m_moving_window_title_color; } else if (&window == wm.m_active_window) { border_color = wm.m_active_window_border_color; border_color2 = wm.m_active_window_border_color2; @@ -301,7 +301,7 @@ void WSWindowFrame::on_mouse_event(const WSMouseEvent& event) return button.on_mouse_event(event.translated(-button.relative_rect().location())); } if (event.type() == WSEvent::MouseDown && event.button() == MouseButton::Left) - wm.start_window_drag(m_window, event.translated(rect().location())); + wm.start_window_move(m_window, event.translated(rect().location())); return; } diff --git a/Servers/WindowServer/WSWindowManager.cpp b/Servers/WindowServer/WSWindowManager.cpp index 825b89f247e9..622d34ba516e 100644 --- a/Servers/WindowServer/WSWindowManager.cpp +++ b/Servers/WindowServer/WSWindowManager.cpp @@ -29,7 +29,7 @@ //#define DEBUG_COUNTERS //#define DEBUG_MENUS //#define RESIZE_DEBUG -//#define DRAG_DEBUG +//#define MOVE_DEBUG //#define DOUBLECLICK_DEBUG static WSWindowManager* s_the; @@ -197,9 +197,9 @@ void WSWindowManager::reload_config(bool set_screen) m_inactive_window_border_color2 = m_wm_config->read_color_entry("Colors", "InactiveWindowBorder2", Color::Red); m_inactive_window_title_color = m_wm_config->read_color_entry("Colors", "InactiveWindowTitle", Color::Red); - m_dragging_window_border_color = m_wm_config->read_color_entry("Colors", "DraggingWindowBorder", Color::Red); - m_dragging_window_border_color2 = m_wm_config->read_color_entry("Colors", "DraggingWindowBorder2", Color::Red); - m_dragging_window_title_color = m_wm_config->read_color_entry("Colors", "DraggingWindowTitle", Color::Red); + m_moving_window_border_color = m_wm_config->read_color_entry("Colors", "MovingWindowBorder", Color::Red); + m_moving_window_border_color2 = m_wm_config->read_color_entry("Colors", "MovingWindowBorder2", Color::Red); + m_moving_window_title_color = m_wm_config->read_color_entry("Colors", "MovingWindowTitle", Color::Red); m_highlight_window_border_color = m_wm_config->read_color_entry("Colors", "HighlightWindowBorder", Color::Red); m_highlight_window_border_color2 = m_wm_config->read_color_entry("Colors", "HighlightWindowBorder2", Color::Red); @@ -410,15 +410,15 @@ void WSWindowManager::pick_new_active_window() }); } -void WSWindowManager::start_window_drag(WSWindow& window, const WSMouseEvent& event) +void WSWindowManager::start_window_move(WSWindow& window, const WSMouseEvent& event) { -#ifdef DRAG_DEBUG - dbg() << "[WM] Begin dragging WSWindow{" << &window << "}"; +#ifdef MOVE_DEBUG + dbg() << "[WM] Begin moving WSWindow{" << &window << "}"; #endif move_to_front_and_make_active(window); - m_drag_window = window.make_weak_ptr(); - m_drag_origin = event.position(); - m_drag_window_origin = window.position(); + m_move_window = window.make_weak_ptr(); + m_move_origin = event.position(); + m_move_window_origin = window.position(); invalidate(window); } @@ -459,53 +459,53 @@ void WSWindowManager::start_window_resize(WSWindow& window, const WSMouseEvent& start_window_resize(window, event.position(), event.button()); } -bool WSWindowManager::process_ongoing_window_drag(WSMouseEvent& event, WSWindow*& hovered_window) +bool WSWindowManager::process_ongoing_window_move(WSMouseEvent& event, WSWindow*& hovered_window) { - if (!m_drag_window) + if (!m_move_window) return false; if (event.type() == WSEvent::MouseUp && event.button() == MouseButton::Left) { -#ifdef DRAG_DEBUG - dbg() << "[WM] Finish dragging WSWindow{" << m_drag_window << "}"; +#ifdef MOVE_DEBUG + dbg() << "[WM] Finish moving WSWindow{" << m_move_window << "}"; #endif - invalidate(*m_drag_window); - if (m_drag_window->rect().contains(event.position())) - hovered_window = m_drag_window; - if (m_drag_window->is_resizable()) { - process_event_for_doubleclick(*m_drag_window, event); + invalidate(*m_move_window); + if (m_move_window->rect().contains(event.position())) + hovered_window = m_move_window; + if (m_move_window->is_resizable()) { + process_event_for_doubleclick(*m_move_window, event); if (event.type() == WSEvent::MouseDoubleClick) { #if defined(DOUBLECLICK_DEBUG) dbg() << "[WM] Click up became doubleclick!"; #endif - m_drag_window->set_maximized(!m_drag_window->is_maximized()); + m_move_window->set_maximized(!m_move_window->is_maximized()); } } - m_drag_window = nullptr; + m_move_window = nullptr; return true; } if (event.type() == WSEvent::MouseMove) { -#ifdef DRAG_DEBUG - dbg() << "[WM] Dragging, origin: " << m_drag_origin << ", now: " << event.position(); - if (m_drag_window->is_maximized()) { - dbg() << " [!] The window is still maximized. Not dragging yet."; +#ifdef MOVE_DEBUG + dbg() << "[WM] Moving, origin: " << m_move_origin << ", now: " << event.position(); + if (m_move_window->is_maximized()) { + dbg() << " [!] The window is still maximized. Not moving yet."; } #endif - if (m_drag_window->is_maximized()) { - auto pixels_moved_from_start = event.position().pixels_moved(m_drag_origin); - // dbg() << "[WM] " << pixels_moved_from_start << " moved since start of drag"; + if (m_move_window->is_maximized()) { + auto pixels_moved_from_start = event.position().pixels_moved(m_move_origin); + // dbg() << "[WM] " << pixels_moved_from_start << " moved since start of window move"; if (pixels_moved_from_start > 5) { // dbg() << "[WM] de-maximizing window"; - m_drag_origin = event.position(); - auto width_before_resize = m_drag_window->width(); - m_drag_window->set_maximized(false); - m_drag_window->move_to(m_drag_origin.x() - (m_drag_window->width() * ((float)m_drag_origin.x() / width_before_resize)), m_drag_origin.y()); - m_drag_window_origin = m_drag_window->position(); + m_move_origin = event.position(); + auto width_before_resize = m_move_window->width(); + m_move_window->set_maximized(false); + m_move_window->move_to(m_move_origin.x() - (m_move_window->width() * ((float)m_move_origin.x() / width_before_resize)), m_move_origin.y()); + m_move_window_origin = m_move_window->position(); } } else { - Point pos = m_drag_window_origin.translated(event.position() - m_drag_origin); - m_drag_window->set_position_without_repaint(pos); - if (m_drag_window->rect().contains(event.position())) - hovered_window = m_drag_window; + Point pos = m_move_window_origin.translated(event.position() - m_move_origin); + m_move_window->set_position_without_repaint(pos); + if (m_move_window->rect().contains(event.position())) + hovered_window = m_move_window; return true; } } @@ -743,7 +743,7 @@ void WSWindowManager::process_mouse_event(WSMouseEvent& event, WSWindow*& hovere if (process_ongoing_drag(event, hovered_window)) return; - if (process_ongoing_window_drag(event, hovered_window)) + if (process_ongoing_window_move(event, hovered_window)) return; if (process_ongoing_window_resize(event, hovered_window)) @@ -812,8 +812,8 @@ void WSWindowManager::process_mouse_event(WSMouseEvent& event, WSWindow*& hovere // client application. We must keep delivering to that client // application until the input sequence is done. // - // This prevents e.g. dragging on one window out of the bounds starting - // a drag in that other unrelated window, and other silly shennanigans. + // This prevents e.g. moving on one window out of the bounds starting + // a move in that other unrelated window, and other silly shenanigans. if (!windows_who_received_mouse_event_due_to_cursor_tracking.contains(m_active_input_window)) { auto translated_event = event.translated(-m_active_input_window->position()); deliver_mouse_event(*m_active_input_window, translated_event); @@ -839,12 +839,12 @@ void WSWindowManager::process_mouse_event(WSMouseEvent& event, WSWindow*& hovere if (&window != m_resize_candidate.ptr()) clear_resize_candidate(); - // First check if we should initiate a drag or resize (Logo+LMB or Logo+RMB). + // First check if we should initiate a move or resize (Logo+LMB or Logo+RMB). // In those cases, the event is swallowed by the window manager. if (window.is_movable()) { if (!window.is_fullscreen() && m_keyboard_modifiers == Mod_Logo && event.type() == WSEvent::MouseDown && event.button() == MouseButton::Left) { hovered_window = &window; - start_window_drag(window, event); + start_window_move(window, event); return IterationDecision::Break; } if (window.is_resizable() && m_keyboard_modifiers == Mod_Logo && event.type() == WSEvent::MouseDown && event.button() == MouseButton::Right && !window.is_blocked_by_modal_window()) { @@ -1107,7 +1107,7 @@ const WSCursor& WSWindowManager::active_cursor() const if (m_dnd_client) return *m_drag_cursor; - if (m_drag_window) + if (m_move_window) return *m_move_cursor; if (m_resize_window || m_resize_candidate) { diff --git a/Servers/WindowServer/WSWindowManager.h b/Servers/WindowServer/WSWindowManager.h index 61e55b09f441..88e8bc7d874e 100644 --- a/Servers/WindowServer/WSWindowManager.h +++ b/Servers/WindowServer/WSWindowManager.h @@ -164,9 +164,9 @@ class WSWindowManager : public CObject { void process_event_for_doubleclick(WSWindow& window, WSMouseEvent& event); void deliver_mouse_event(WSWindow& window, WSMouseEvent& event); bool process_ongoing_window_resize(const WSMouseEvent&, WSWindow*& hovered_window); - bool process_ongoing_window_drag(WSMouseEvent&, WSWindow*& hovered_window); + bool process_ongoing_window_move(WSMouseEvent&, WSWindow*& hovered_window); bool process_ongoing_drag(WSMouseEvent&, WSWindow*& hovered_window); - void start_window_drag(WSWindow&, const WSMouseEvent&); + void start_window_move(WSWindow&, const WSMouseEvent&); void set_hovered_window(WSWindow*); template<typename Callback> IterationDecision for_each_visible_window_of_type_from_back_to_front(WSWindowType, Callback, bool ignore_highlight = false); @@ -206,9 +206,9 @@ class WSWindowManager : public CObject { Color m_inactive_window_border_color; Color m_inactive_window_border_color2; Color m_inactive_window_title_color; - Color m_dragging_window_border_color; - Color m_dragging_window_border_color2; - Color m_dragging_window_title_color; + Color m_moving_window_border_color; + Color m_moving_window_border_color2; + Color m_moving_window_title_color; Color m_highlight_window_border_color; Color m_highlight_window_border_color2; Color m_highlight_window_title_color; @@ -246,9 +246,9 @@ class WSWindowManager : public CObject { WeakPtr<WSWindow> m_highlight_window; WeakPtr<WSWindow> m_active_input_window; - WeakPtr<WSWindow> m_drag_window; - Point m_drag_origin; - Point m_drag_window_origin; + WeakPtr<WSWindow> m_move_window; + Point m_move_origin; + Point m_move_window_origin; WeakPtr<WSWindow> m_resize_window; WeakPtr<WSWindow> m_resize_candidate;
4dc4de052a36e817606ab6268f74e4665f2dab93
2023-10-18 20:20:32
Nico Weber
libpdf: Implement opcode 28 for CFF font programs
false
Implement opcode 28 for CFF font programs
libpdf
diff --git a/Userland/Libraries/LibPDF/Fonts/Type1FontProgram.cpp b/Userland/Libraries/LibPDF/Fonts/Type1FontProgram.cpp index 3bf879e552b2..571a33a87426 100644 --- a/Userland/Libraries/LibPDF/Fonts/Type1FontProgram.cpp +++ b/Userland/Libraries/LibPDF/Fonts/Type1FontProgram.cpp @@ -274,6 +274,17 @@ PDFErrorOr<Type1FontProgram::Glyph> Type1FontProgram::parse_glyph(ReadonlyBytes TRY(push(((v - 247) * 256) + w + 108)); } else if (v >= 32) { TRY(push(v - 139)); + } else if (v == 28) { + if (is_type2) { + // Type 2 spec: "In addition to the 32 to 255 range of values, a ShortInt value is specified by using the operator (28) + // followed by two bytes which represent numbers between –32768 and +32767. The most significant byte follows the (28)." + TRY(require(2)); + i16 a = static_cast<i16>((data[i + 1] << 8) | data[i + 2]); + i += 2; + TRY(push(a)); + } else { + return error(DeprecatedString::formatted("CFF Subr command 28 only valid in type2 data")); + } } else { // Not a parameter but a command byte. switch (v) {
504d62286452b5537b723ee3baf3f85867fcd690
2021-04-27 22:41:59
Andreas Kling
libweb: Remove unnecessary temporary Vector in text layout
false
Remove unnecessary temporary Vector in text layout
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/TextNode.cpp b/Userland/Libraries/LibWeb/Layout/TextNode.cpp index c3b388a420f3..adab30210aa4 100644 --- a/Userland/Libraries/LibWeb/Layout/TextNode.cpp +++ b/Userland/Libraries/LibWeb/Layout/TextNode.cpp @@ -140,18 +140,13 @@ void TextNode::split_into_lines_by_rules(InlineFormattingContext& context, Layou m_text_for_rendering = dom_node().data(); } - Vector<Chunk, 128> chunks; ChunkIterator iterator(m_text_for_rendering, layout_mode, do_wrap_lines, do_wrap_breaks); for (;;) { - auto chunk = iterator.next(); - if (!chunk.has_value()) + auto chunk_opt = iterator.next(); + if (!chunk_opt.has_value()) break; - chunks.append(chunk.release_value()); - } - - for (size_t i = 0; i < chunks.size(); ++i) { - auto& chunk = chunks[i]; + auto& chunk = chunk_opt.value(); // Collapse entire fragment into non-existence if previous fragment on line ended in whitespace. if (do_collapse && line_boxes.last().is_empty_or_ends_in_whitespace() && chunk.is_all_whitespace)
adfb371e4fab823d7926c621b606cbb5f0142700
2025-02-06 06:05:10
Andrew Kaster
libweb: Reference multipage spec for form element constraints
false
Reference multipage spec for form element constraints
libweb
diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.h b/Libraries/LibWeb/HTML/FormAssociatedElement.h index 5b17111a06fd..3d101bb15be6 100644 --- a/Libraries/LibWeb/HTML/FormAssociatedElement.h +++ b/Libraries/LibWeb/HTML/FormAssociatedElement.h @@ -91,13 +91,13 @@ class FormAssociatedElement { // https://html.spec.whatwg.org/multipage/forms.html#concept-submit-button virtual bool is_submit_button() const { return false; } - // https://html.spec.whatwg.org/#candidate-for-constraint-validation + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#candidate-for-constraint-validation bool is_candidate_for_constraint_validation() const; - // https://html.spec.whatwg.org/#concept-fv-valid + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fv-valid bool satisfies_its_constraints() const; - // https://html.spec.whatwg.org/#definitions + // https://html.spec.whatwg.org/multipage/form-control-infrastructure/#definitions virtual bool suffering_from_being_missing() const { return false; } virtual bool suffering_from_a_type_mismatch() const { return false; } virtual bool suffering_from_a_pattern_mismatch() const { return false; }
ecccd511fac7662f9ab9bf499cbe0c2be49b2440
2021-12-12 00:43:36
Andreas Kling
meta: Run QEMU with QMP socket
false
Run QEMU with QMP socket
meta
diff --git a/Meta/run.sh b/Meta/run.sh index e5bf93565d1e..444a7b4b0367 100755 --- a/Meta/run.sh +++ b/Meta/run.sh @@ -213,6 +213,7 @@ if [ -z "$SERENITY_MACHINE" ]; then -device i82801b11-bridge,id=bridge3 -device sdhci-pci,bus=bridge3 -device ich9-ahci,bus=bridge3 -chardev stdio,id=stdout,mux=on + -qmp unix:qmp-sock,server,nowait " fi fi
24651f854c5e0bcc2ce13ed5b61f7c6e795f2160
2021-10-23 21:23:11
Andreas Kling
libgui: Add Widget::repaint() to force an immediate repaint
false
Add Widget::repaint() to force an immediate repaint
libgui
diff --git a/Userland/Libraries/LibGUI/Widget.cpp b/Userland/Libraries/LibGUI/Widget.cpp index 3496d3b0a4d1..a0cb514a30c5 100644 --- a/Userland/Libraries/LibGUI/Widget.cpp +++ b/Userland/Libraries/LibGUI/Widget.cpp @@ -616,6 +616,22 @@ void Widget::update(const Gfx::IntRect& rect) window->update(bound_by_widget.translated(window_relative_rect().location())); } +void Widget::repaint() +{ + if (rect().is_empty()) + return; + repaint(rect()); +} + +void Widget::repaint(Gfx::IntRect const& rect) +{ + auto* window = this->window(); + if (!window) + return; + update(rect); + window->flush_pending_paints_immediately(); +} + Gfx::IntRect Widget::window_relative_rect() const { auto rect = relative_rect(); diff --git a/Userland/Libraries/LibGUI/Widget.h b/Userland/Libraries/LibGUI/Widget.h index d8de4d6ff517..29ae0f007980 100644 --- a/Userland/Libraries/LibGUI/Widget.h +++ b/Userland/Libraries/LibGUI/Widget.h @@ -136,9 +136,14 @@ class Widget : public Core::Object { Gfx::IntRect rect() const { return { 0, 0, width(), height() }; } Gfx::IntSize size() const { return m_relative_rect.size(); } + // Invalidate the widget (or an area thereof), causing a repaint to happen soon. void update(); void update(const Gfx::IntRect&); + // Repaint the widget (or an area thereof) immediately. + void repaint(); + void repaint(Gfx::IntRect const&); + bool is_focused() const; void set_focus(bool, FocusSource = FocusSource::Programmatic); diff --git a/Userland/Libraries/LibGUI/Window.cpp b/Userland/Libraries/LibGUI/Window.cpp index 5dd3eb1ea99a..5dbd41b5ea5a 100644 --- a/Userland/Libraries/LibGUI/Window.cpp +++ b/Userland/Libraries/LibGUI/Window.cpp @@ -1204,4 +1204,14 @@ void Window::set_modified(bool modified) WindowServerConnection::the().async_set_window_modified(m_window_id, modified); } +void Window::flush_pending_paints_immediately() +{ + if (!m_window_id) + return; + if (m_pending_paint_event_rects.is_empty()) + return; + MultiPaintEvent paint_event(move(m_pending_paint_event_rects), size()); + handle_multi_paint_event(paint_event); +} + } diff --git a/Userland/Libraries/LibGUI/Window.h b/Userland/Libraries/LibGUI/Window.h index e472873215e1..119a5529b7fc 100644 --- a/Userland/Libraries/LibGUI/Window.h +++ b/Userland/Libraries/LibGUI/Window.h @@ -202,6 +202,8 @@ class Window : public Core::Object { Menu& add_menu(String name); + void flush_pending_paints_immediately(); + protected: Window(Core::Object* parent = nullptr); virtual void wm_event(WMEvent&);
7e79563bb9db3ba864e689fd6eb0c243adbc5a84
2020-12-29 01:58:40
Andreas Kling
libgui: Show tooltip after a small delay
false
Show tooltip after a small delay
libgui
diff --git a/Libraries/LibGUI/Application.cpp b/Libraries/LibGUI/Application.cpp index 18837aeb0773..a70e7d5b3939 100644 --- a/Libraries/LibGUI/Application.cpp +++ b/Libraries/LibGUI/Application.cpp @@ -40,6 +40,34 @@ namespace GUI { +class Application::TooltipWindow final : public Window { + C_OBJECT(TooltipWindow); + +public: + void set_tooltip(String tooltip) + { + // FIXME: Add some kind of GUI::Label auto-sizing feature. + int text_width = m_label->font().width(tooltip); + set_rect(rect().x(), rect().y(), text_width + 10, m_label->font().glyph_height() + 8); + m_label->set_text(move(tooltip)); + } + +private: + TooltipWindow() + { + set_window_type(WindowType::Tooltip); + m_label = set_main_widget<Label>(); + m_label->set_background_role(Gfx::ColorRole::Tooltip); + m_label->set_foreground_role(Gfx::ColorRole::TooltipText); + m_label->set_fill_with_background_color(true); + m_label->set_frame_thickness(1); + m_label->set_frame_shape(Gfx::FrameShape::Container); + m_label->set_frame_shadow(Gfx::FrameShadow::Plain); + } + + RefPtr<Label> m_label; +}; + static NeverDestroyed<WeakPtr<Application>> s_the; Application* Application::the() @@ -64,6 +92,14 @@ Application::Application(int argc, char** argv) String arg(argv[i]); m_args.append(move(arg)); } + + m_tooltip_show_timer = Core::Timer::create_single_shot(700, [this] { + tooltip_show_timer_did_fire(); + }); + + m_tooltip_hide_timer = Core::Timer::create_single_shot(50, [this] { + tooltip_hide_timer_did_fire(); + }); } Application::~Application() @@ -108,65 +144,29 @@ Action* Application::action_for_key_event(const KeyEvent& event) return (*it).value; } -class Application::TooltipWindow final : public Window { - C_OBJECT(TooltipWindow); - -public: - void set_tooltip(const StringView& tooltip) - { - // FIXME: Add some kind of GUI::Label auto-sizing feature. - int text_width = m_label->font().width(tooltip); - set_rect(rect().x(), rect().y(), text_width + 10, m_label->font().glyph_height() + 8); - m_label->set_text(tooltip); - } - -private: - TooltipWindow() - { - set_window_type(WindowType::Tooltip); - m_label = set_main_widget<Label>(); - m_label->set_background_role(Gfx::ColorRole::Tooltip); - m_label->set_foreground_role(Gfx::ColorRole::TooltipText); - m_label->set_fill_with_background_color(true); - m_label->set_frame_thickness(1); - m_label->set_frame_shape(Gfx::FrameShape::Container); - m_label->set_frame_shadow(Gfx::FrameShadow::Plain); - } - - RefPtr<Label> m_label; -}; - -void Application::show_tooltip(const StringView& tooltip, const Gfx::IntPoint& screen_location, const Widget* tooltip_source_widget) +void Application::show_tooltip(String tooltip, const Widget* tooltip_source_widget) { m_tooltip_source_widget = tooltip_source_widget; if (!m_tooltip_window) { m_tooltip_window = TooltipWindow::construct(); m_tooltip_window->set_double_buffering_enabled(false); } - m_tooltip_window->set_tooltip(tooltip); - - Gfx::IntRect desktop_rect = Desktop::the().rect(); - - const int margin = 30; - Gfx::IntPoint adjusted_pos = screen_location; - if (adjusted_pos.x() + m_tooltip_window->width() >= desktop_rect.width() - margin) { - adjusted_pos = adjusted_pos.translated(-m_tooltip_window->width(), 0); - } - if (adjusted_pos.y() + m_tooltip_window->height() >= desktop_rect.height() - margin) { - adjusted_pos = adjusted_pos.translated(0, -(m_tooltip_window->height() * 2)); + m_tooltip_window->set_tooltip(move(tooltip)); + + if (m_tooltip_window->is_visible()) { + tooltip_show_timer_did_fire(); + m_tooltip_show_timer->stop(); + m_tooltip_hide_timer->stop(); + } else { + m_tooltip_show_timer->restart(); + m_tooltip_hide_timer->stop(); } - - m_tooltip_window->move_to(adjusted_pos); - m_tooltip_window->show(); } void Application::hide_tooltip() { - m_tooltip_source_widget = nullptr; - if (m_tooltip_window) { - m_tooltip_window->hide(); - m_tooltip_window = nullptr; - } + m_tooltip_show_timer->stop(); + m_tooltip_hide_timer->start(); } void Application::did_create_window(Badge<Window>) @@ -202,4 +202,32 @@ Gfx::Palette Application::palette() const return Palette(*m_palette); } +void Application::tooltip_show_timer_did_fire() +{ + ASSERT(m_tooltip_window); + Gfx::IntRect desktop_rect = Desktop::the().rect(); + + const int margin = 30; + Gfx::IntPoint adjusted_pos = WindowServerConnection::the().send_sync<Messages::WindowServer::GetGlobalCursorPosition>()->position(); + + adjusted_pos.move_by(0, 18); + + if (adjusted_pos.x() + m_tooltip_window->width() >= desktop_rect.width() - margin) { + adjusted_pos = adjusted_pos.translated(-m_tooltip_window->width(), 0); + } + if (adjusted_pos.y() + m_tooltip_window->height() >= desktop_rect.height() - margin) { + adjusted_pos = adjusted_pos.translated(0, -(m_tooltip_window->height() * 2)); + } + + m_tooltip_window->move_to(adjusted_pos); + m_tooltip_window->show(); +} + +void Application::tooltip_hide_timer_did_fire() +{ + m_tooltip_source_widget = nullptr; + if (m_tooltip_window) + m_tooltip_window->hide(); +} + } diff --git a/Libraries/LibGUI/Application.h b/Libraries/LibGUI/Application.h index d28b9da7ce27..834120bf16b9 100644 --- a/Libraries/LibGUI/Application.h +++ b/Libraries/LibGUI/Application.h @@ -54,7 +54,7 @@ class Application : public Core::Object { void register_global_shortcut_action(Badge<Action>, Action&); void unregister_global_shortcut_action(Badge<Action>, Action&); - void show_tooltip(const StringView&, const Gfx::IntPoint& screen_location, const Widget* tooltip_source_widget); + void show_tooltip(String, const Widget* tooltip_source_widget); void hide_tooltip(); Widget* tooltip_source_widget() { return m_tooltip_source_widget; }; @@ -79,12 +79,17 @@ class Application : public Core::Object { private: Application(int argc, char** argv); + void tooltip_show_timer_did_fire(); + void tooltip_hide_timer_did_fire(); + OwnPtr<Core::EventLoop> m_event_loop; RefPtr<MenuBar> m_menubar; RefPtr<Gfx::PaletteImpl> m_palette; RefPtr<Gfx::PaletteImpl> m_system_palette; HashMap<Shortcut, Action*> m_global_shortcut_actions; class TooltipWindow; + RefPtr<Core::Timer> m_tooltip_show_timer; + RefPtr<Core::Timer> m_tooltip_hide_timer; RefPtr<TooltipWindow> m_tooltip_window; RefPtr<Widget> m_tooltip_source_widget; bool m_quit_when_last_window_deleted { true }; diff --git a/Libraries/LibGUI/Widget.cpp b/Libraries/LibGUI/Widget.cpp index 47aaf29646a5..3f68cc22c25f 100644 --- a/Libraries/LibGUI/Widget.cpp +++ b/Libraries/LibGUI/Widget.cpp @@ -919,7 +919,7 @@ void Widget::set_tooltip(const StringView& tooltip) void Widget::show_tooltip() { if (has_tooltip()) - Application::the()->show_tooltip(m_tooltip, screen_relative_rect().center().translated(0, height() / 2), this); + Application::the()->show_tooltip(m_tooltip, this); } Gfx::IntRect Widget::children_clip_rect() const diff --git a/Libraries/LibWeb/InProcessWebView.cpp b/Libraries/LibWeb/InProcessWebView.cpp index 87015831452c..1fa94ec3deac 100644 --- a/Libraries/LibWeb/InProcessWebView.cpp +++ b/Libraries/LibWeb/InProcessWebView.cpp @@ -201,9 +201,9 @@ void InProcessWebView::page_did_middle_click_link(const URL& url, const String& on_link_middle_click(url, target, modifiers); } -void InProcessWebView::page_did_enter_tooltip_area(const Gfx::IntPoint& content_position, const String& title) +void InProcessWebView::page_did_enter_tooltip_area([[maybe_unused]] const Gfx::IntPoint& content_position, const String& title) { - GUI::Application::the()->show_tooltip(title, screen_relative_rect().location().translated(to_widget_position(content_position)), nullptr); + GUI::Application::the()->show_tooltip(title, nullptr); } void InProcessWebView::page_did_leave_tooltip_area()
d58cf1a05d4056af381edac71b168ba3b82ffa0e
2020-03-11 14:46:55
Oriko
libgui: Syntax highlight string escape sequences
false
Syntax highlight string escape sequences
libgui
diff --git a/Libraries/LibGUI/CppLexer.cpp b/Libraries/LibGUI/CppLexer.cpp index bbd76a45de72..78a7558779ca 100644 --- a/Libraries/LibGUI/CppLexer.cpp +++ b/Libraries/LibGUI/CppLexer.cpp @@ -243,6 +243,61 @@ Vector<CppToken> CppLexer::lex() tokens.append(token); }; + auto match_escape_sequence = [&]() -> size_t { + switch (peek(1)) { + case '\'': + case '"': + case '?': + case '\\': + case 'a': + case 'b': + case 'f': + case 'n': + case 'r': + case 't': + case 'v': + return 2; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': { + size_t octal_digits = 1; + for (size_t i = 0; i < 2; ++i) { + char next = peek(2 + i); + if (next < '0' || next > '7') + break; + ++octal_digits; + } + return 1 + octal_digits; + } + case 'x': { + size_t hex_digits = 0; + for (size_t i = 0; i < 2; ++i) { + if (!isxdigit(peek(2 + i))) + break; + ++hex_digits; + } + return 2 + hex_digits; + } + case 'u': { + bool is_unicode = true; + for (size_t i = 0; i < 4; ++i) { + if (!isxdigit(peek(2 + i))) { + is_unicode = false; + break; + } + } + return is_unicode ? 6 : 0; + } + default: + return 0; + } + }; + while (m_index < m_input.length()) { auto ch = peek(); if (isspace(ch)) { @@ -328,6 +383,19 @@ Vector<CppToken> CppLexer::lex() begin_token(); consume(); while (peek()) { + if (peek() == '\\') { + size_t escape = match_escape_sequence(); + if (escape > 0) { + commit_token(CppToken::Type::DoubleQuotedString); + begin_token(); + for (size_t i = 0; i < escape; ++i) + consume(); + commit_token(CppToken::Type::EscapeSequence); + begin_token(); + continue; + } + } + if (consume() == '"') break; } @@ -338,6 +406,19 @@ Vector<CppToken> CppLexer::lex() begin_token(); consume(); while (peek()) { + if (peek() == '\\') { + size_t escape = match_escape_sequence(); + if (escape > 0) { + commit_token(CppToken::Type::SingleQuotedString); + begin_token(); + for (size_t i = 0; i < escape; ++i) + consume(); + commit_token(CppToken::Type::EscapeSequence); + begin_token(); + continue; + } + } + if (consume() == '\'') break; } diff --git a/Libraries/LibGUI/CppLexer.h b/Libraries/LibGUI/CppLexer.h index 09e8ed80872e..63583cd4a1d6 100644 --- a/Libraries/LibGUI/CppLexer.h +++ b/Libraries/LibGUI/CppLexer.h @@ -46,6 +46,7 @@ namespace GUI { __TOKEN(Semicolon) \ __TOKEN(DoubleQuotedString) \ __TOKEN(SingleQuotedString) \ + __TOKEN(EscapeSequence) \ __TOKEN(Comment) \ __TOKEN(Number) \ __TOKEN(Keyword) \ diff --git a/Libraries/LibGUI/CppSyntaxHighlighter.cpp b/Libraries/LibGUI/CppSyntaxHighlighter.cpp index 3f1d5c434042..abb11248a424 100644 --- a/Libraries/LibGUI/CppSyntaxHighlighter.cpp +++ b/Libraries/LibGUI/CppSyntaxHighlighter.cpp @@ -23,6 +23,8 @@ static TextStyle style_for_token_type(CppToken::Type type) case CppToken::Type::SingleQuotedString: case CppToken::Type::Number: return { Color::from_rgb(0x800000) }; + case CppToken::Type::EscapeSequence: + return { Color::from_rgb(0x800080), &Gfx::Font::default_bold_fixed_width_font() }; case CppToken::Type::PreprocessorStatement: return { Color::from_rgb(0x008080) }; case CppToken::Type::Comment:
bfe5509a28033c844e942ebc79337c9d876b4746
2021-08-14 22:12:14
Daniel Bertalan
userspaceemulator: Prefix MmapRegions' name with '(UE)'
false
Prefix MmapRegions' name with '(UE)'
userspaceemulator
diff --git a/Userland/DevTools/UserspaceEmulator/MmapRegion.cpp b/Userland/DevTools/UserspaceEmulator/MmapRegion.cpp index eff2431999bd..f5b145c8cfa5 100644 --- a/Userland/DevTools/UserspaceEmulator/MmapRegion.cpp +++ b/Userland/DevTools/UserspaceEmulator/MmapRegion.cpp @@ -27,7 +27,7 @@ static void free_pages(void* ptr, size_t bytes) NonnullOwnPtr<MmapRegion> MmapRegion::create_anonymous(u32 base, u32 size, u32 prot, String name) { - auto data = (u8*)mmap_initialized(size, 0, nullptr); + auto data = (u8*)mmap_initialized(size, 0, String::formatted("(UE) {}", name).characters()); auto shadow_data = (u8*)mmap_initialized(size, 1, "MmapRegion ShadowData"); auto region = adopt_own(*new MmapRegion(base, size, prot, data, shadow_data)); region->m_name = move(name); @@ -38,7 +38,7 @@ NonnullOwnPtr<MmapRegion> MmapRegion::create_file_backed(u32 base, u32 size, u32 { // Since we put the memory to an arbitrary location, do not pass MAP_FIXED to the Kernel. auto real_flags = flags & ~MAP_FIXED; - auto data = (u8*)mmap_with_name(nullptr, size, prot, real_flags, fd, offset, name.is_empty() ? nullptr : name.characters()); + auto data = (u8*)mmap_with_name(nullptr, size, prot, real_flags, fd, offset, name.is_empty() ? nullptr : String::formatted("(UE) {}", name).characters()); VERIFY(data != MAP_FAILED); auto shadow_data = (u8*)mmap_initialized(size, 1, "MmapRegion ShadowData"); auto region = adopt_own(*new MmapRegion(base, size, prot, data, shadow_data)); @@ -317,4 +317,10 @@ void MmapRegion::set_prot(int prot) } } +void MmapRegion::set_name(String name) +{ + m_name = move(name); + set_mmap_name(range().base().as_ptr(), range().size(), String::formatted("(UE) {}", m_name).characters()); +} + } diff --git a/Userland/DevTools/UserspaceEmulator/MmapRegion.h b/Userland/DevTools/UserspaceEmulator/MmapRegion.h index b39eaeee1bbc..82ee22a6aa3a 100644 --- a/Userland/DevTools/UserspaceEmulator/MmapRegion.h +++ b/Userland/DevTools/UserspaceEmulator/MmapRegion.h @@ -61,7 +61,7 @@ class MmapRegion final : public Region { return {}; return m_name.substring(0, *maybe_separator); } - void set_name(String name) { m_name = move(name); } + void set_name(String name); private: MmapRegion(u32 base, u32 size, int prot, u8* data, u8* shadow_data);
69f11fc1c657603b189015fd620f96e32adfb9fd
2024-10-08 22:32:27
Jelle Raaijmakers
libweb: Implement navigator.deviceMemory
false
Implement navigator.deviceMemory
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Navigator.h b/Userland/Libraries/LibWeb/HTML/Navigator.h index e48061e096f9..a9b1e116d734 100644 --- a/Userland/Libraries/LibWeb/HTML/Navigator.h +++ b/Userland/Libraries/LibWeb/HTML/Navigator.h @@ -10,6 +10,7 @@ #include <LibWeb/HTML/MimeTypeArray.h> #include <LibWeb/HTML/NavigatorBeacon.h> #include <LibWeb/HTML/NavigatorConcurrentHardware.h> +#include <LibWeb/HTML/NavigatorDeviceMemory.h> #include <LibWeb/HTML/NavigatorID.h> #include <LibWeb/HTML/NavigatorLanguage.h> #include <LibWeb/HTML/NavigatorOnLine.h> @@ -23,6 +24,7 @@ namespace Web::HTML { class Navigator : public Bindings::PlatformObject , public NavigatorBeaconMixin , public NavigatorConcurrentHardwareMixin + , public NavigatorDeviceMemoryMixin , public NavigatorIDMixin , public NavigatorLanguageMixin , public NavigatorOnLineMixin diff --git a/Userland/Libraries/LibWeb/HTML/Navigator.idl b/Userland/Libraries/LibWeb/HTML/Navigator.idl index 94f31502a872..e93f60d8cdd9 100644 --- a/Userland/Libraries/LibWeb/HTML/Navigator.idl +++ b/Userland/Libraries/LibWeb/HTML/Navigator.idl @@ -1,10 +1,11 @@ #import <Clipboard/Clipboard.idl> #import <HTML/MimeTypeArray.idl> #import <HTML/NavigatorBeacon.idl> +#import <HTML/NavigatorConcurrentHardware.idl> +#import <HTML/NavigatorDeviceMemory.idl> #import <HTML/NavigatorID.idl> #import <HTML/NavigatorLanguage.idl> #import <HTML/NavigatorOnLine.idl> -#import <HTML/NavigatorConcurrentHardware.idl> #import <HTML/PluginArray.idl> #import <HTML/ServiceWorkerContainer.idl> #import <HTML/UserActivation.idl> @@ -72,3 +73,4 @@ Navigator includes NavigatorPlugins; Navigator includes NavigatorConcurrentHardware; Navigator includes NavigatorAutomationInformation; Navigator includes NavigatorStorage; +Navigator includes NavigatorDeviceMemory; diff --git a/Userland/Libraries/LibWeb/HTML/NavigatorDeviceMemory.h b/Userland/Libraries/LibWeb/HTML/NavigatorDeviceMemory.h new file mode 100644 index 000000000000..4a2615e7b93b --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/NavigatorDeviceMemory.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024, Jelle Raaijmakers <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/BuiltinWrappers.h> +#include <LibCore/System.h> +#include <LibWeb/WebIDL/Types.h> + +namespace Web::HTML { + +class NavigatorDeviceMemoryMixin { +public: + // https://www.w3.org/TR/device-memory/#computing-device-memory-value + WebIDL::Double device_memory() const + { + // The value is calculated by using the actual device memory in MiB then rounding it to the + // nearest number where only the most signicant bit can be set and the rest are zeros + // (nearest power of two). + auto memory_in_bytes = Core::System::physical_memory_bytes(); + auto memory_in_mib = memory_in_bytes / MiB; + auto required_bits = AK::count_required_bits(memory_in_mib); + auto lower_memory_in_mib = static_cast<u64>(1) << (required_bits - 1); + auto upper_memory_in_mib = static_cast<u64>(1) << required_bits; + auto rounded_memory_in_mib = upper_memory_in_mib - memory_in_mib <= memory_in_mib - lower_memory_in_mib + ? upper_memory_in_mib + : lower_memory_in_mib; + + // Then dividing that number by 1024.0 to get the value in GiB. + auto memory_in_gib = static_cast<WebIDL::Double>(rounded_memory_in_mib) / 1024.0; + + // An upper bound and a lower bound should be set on the list of values. + return AK::clamp(memory_in_gib, 1.0, 4.0); + } +}; + +} diff --git a/Userland/Libraries/LibWeb/HTML/NavigatorDeviceMemory.idl b/Userland/Libraries/LibWeb/HTML/NavigatorDeviceMemory.idl new file mode 100644 index 000000000000..4402200fffca --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/NavigatorDeviceMemory.idl @@ -0,0 +1,5 @@ +// https://www.w3.org/TR/device-memory/#sec-device-memory-js-api +[SecureContext, Exposed=(Window,Worker)] +interface mixin NavigatorDeviceMemory { + readonly attribute double deviceMemory; +}; diff --git a/Userland/Libraries/LibWeb/HTML/WorkerNavigator.h b/Userland/Libraries/LibWeb/HTML/WorkerNavigator.h index 51d7dc5f9d89..7848e1d62e99 100644 --- a/Userland/Libraries/LibWeb/HTML/WorkerNavigator.h +++ b/Userland/Libraries/LibWeb/HTML/WorkerNavigator.h @@ -9,6 +9,7 @@ #include <LibWeb/Bindings/PlatformObject.h> #include <LibWeb/HTML/NavigatorConcurrentHardware.h> +#include <LibWeb/HTML/NavigatorDeviceMemory.h> #include <LibWeb/HTML/NavigatorID.h> #include <LibWeb/HTML/NavigatorLanguage.h> #include <LibWeb/HTML/NavigatorOnLine.h> @@ -20,6 +21,7 @@ namespace Web::HTML { class WorkerNavigator : public Bindings::PlatformObject , public NavigatorConcurrentHardwareMixin + , public NavigatorDeviceMemoryMixin , public NavigatorIDMixin , public NavigatorLanguageMixin , public NavigatorOnLineMixin diff --git a/Userland/Libraries/LibWeb/HTML/WorkerNavigator.idl b/Userland/Libraries/LibWeb/HTML/WorkerNavigator.idl index 86bccd7652de..bba17e0e9aa8 100644 --- a/Userland/Libraries/LibWeb/HTML/WorkerNavigator.idl +++ b/Userland/Libraries/LibWeb/HTML/WorkerNavigator.idl @@ -1,7 +1,8 @@ +#import <HTML/NavigatorConcurrentHardware.idl> +#import <HTML/NavigatorDeviceMemory.idl> #import <HTML/NavigatorID.idl> #import <HTML/NavigatorLanguage.idl> #import <HTML/NavigatorOnLine.idl> -#import <HTML/NavigatorConcurrentHardware.idl> #import <MediaCapabilitiesAPI/MediaCapabilities.idl> #import <StorageAPI/NavigatorStorage.idl> @@ -20,3 +21,4 @@ WorkerNavigator includes NavigatorLanguage; WorkerNavigator includes NavigatorOnLine; WorkerNavigator includes NavigatorConcurrentHardware; WorkerNavigator includes NavigatorStorage; +WorkerNavigator includes NavigatorDeviceMemory;
916cb256de5896343e3d5f7eea8949bd6e494d6d
2023-12-28 00:00:39
Timothy Flynn
libjs: Ensure enlarged ArrayBuffers are filled with zeros
false
Ensure enlarged ArrayBuffers are filled with zeros
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp index 1970aeeef55d..26751a4fa5b3 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.cpp +++ b/Userland/Libraries/LibJS/Runtime/VM.cpp @@ -149,7 +149,7 @@ VM::VM(OwnPtr<CustomData> custom_data, ErrorMessages error_messages) // The default implementation of HostResizeArrayBuffer is to return NormalCompletion(unhandled). - if (auto result = buffer.buffer().try_resize(new_byte_length); result.is_error()) + if (auto result = buffer.buffer().try_resize(new_byte_length, ByteBuffer::ZeroFillNewElements::Yes); result.is_error()) return throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, new_byte_length); return HandledByHost::Handled; diff --git a/Userland/Libraries/LibJS/Tests/builtins/ArrayBuffer/ArrayBuffer.prototype.resize.js b/Userland/Libraries/LibJS/Tests/builtins/ArrayBuffer/ArrayBuffer.prototype.resize.js index 0c62e80e0b79..1b0a68274024 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/ArrayBuffer/ArrayBuffer.prototype.resize.js +++ b/Userland/Libraries/LibJS/Tests/builtins/ArrayBuffer/ArrayBuffer.prototype.resize.js @@ -54,4 +54,38 @@ describe("normal behavior", () => { expect(buffer.byteLength).toBe(i); } }); + + test("enlarged buffers filled with zeros", () => { + let buffer = new ArrayBuffer(5, { maxByteLength: 10 }); + + const readBuffer = () => { + let array = new Uint8Array(buffer, 0, buffer.byteLength / Uint8Array.BYTES_PER_ELEMENT); + let values = []; + + for (let value of array) { + values.push(Number(value)); + } + + return values; + }; + + const writeBuffer = values => { + let array = new Uint8Array(buffer, 0, buffer.byteLength / Uint8Array.BYTES_PER_ELEMENT); + array.set(values); + }; + + expect(readBuffer()).toEqual([0, 0, 0, 0, 0]); + + writeBuffer([1, 2, 3, 4, 5]); + expect(readBuffer()).toEqual([1, 2, 3, 4, 5]); + + buffer.resize(8); + expect(readBuffer()).toEqual([1, 2, 3, 4, 5, 0, 0, 0]); + + writeBuffer([1, 2, 3, 4, 5, 6, 7, 8]); + expect(readBuffer()).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + + buffer.resize(10); + expect(readBuffer()).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 0, 0]); + }); });
7aa3cfda09117a4bf34c645b20d786f65693e746
2021-10-07 03:34:05
sin-ack
systemmonitor: Use size_t for graph values
false
Use size_t for graph values
systemmonitor
diff --git a/Userland/Applications/SystemMonitor/GraphWidget.cpp b/Userland/Applications/SystemMonitor/GraphWidget.cpp index 3d0336e03f35..4f7d9575bc95 100644 --- a/Userland/Applications/SystemMonitor/GraphWidget.cpp +++ b/Userland/Applications/SystemMonitor/GraphWidget.cpp @@ -20,7 +20,7 @@ GraphWidget::~GraphWidget() { } -void GraphWidget::add_value(Vector<int, 1>&& value) +void GraphWidget::add_value(Vector<size_t, 1>&& value) { m_values.enqueue(move(value)); update(); diff --git a/Userland/Applications/SystemMonitor/GraphWidget.h b/Userland/Applications/SystemMonitor/GraphWidget.h index 84498fde53b4..ba5679fa3c0c 100644 --- a/Userland/Applications/SystemMonitor/GraphWidget.h +++ b/Userland/Applications/SystemMonitor/GraphWidget.h @@ -15,15 +15,15 @@ class GraphWidget final : public GUI::Frame { public: virtual ~GraphWidget() override; - void set_max(int max) { m_max = max; } - int max() const { return m_max; } + void set_max(size_t max) { m_max = max; } + size_t max() const { return m_max; } - void add_value(Vector<int, 1>&&); + void add_value(Vector<size_t, 1>&&); struct ValueFormat { Gfx::ColorRole graph_color_role { Gfx::ColorRole::Base }; Color text_shadow_color { Color::Transparent }; - Function<String(int)> text_formatter; + Function<String(size_t)> text_formatter; }; void set_value_format(size_t index, ValueFormat&& format) { @@ -38,9 +38,9 @@ class GraphWidget final : public GUI::Frame { virtual void paint_event(GUI::PaintEvent&) override; - int m_max { 100 }; + size_t m_max { 100 }; Vector<ValueFormat, 1> m_value_format; - CircularQueue<Vector<int, 1>, 4000> m_values; + CircularQueue<Vector<size_t, 1>, 4000> m_values; bool m_stack_values { false }; Vector<Gfx::IntPoint, 1> m_calculated_points; diff --git a/Userland/Applications/SystemMonitor/MemoryStatsWidget.cpp b/Userland/Applications/SystemMonitor/MemoryStatsWidget.cpp index 1c0a23705fba..97e5ea4eefef 100644 --- a/Userland/Applications/SystemMonitor/MemoryStatsWidget.cpp +++ b/Userland/Applications/SystemMonitor/MemoryStatsWidget.cpp @@ -117,5 +117,5 @@ void MemoryStatsWidget::refresh() m_kmalloc_difference_label->set_text(String::formatted("{:+}", kmalloc_call_count - kfree_call_count)); m_graph.set_max(page_count_to_bytes(total_userphysical_and_swappable_pages) + kmalloc_bytes_total); - m_graph.add_value({ (int)page_count_to_bytes(user_physical_committed), (int)page_count_to_bytes(user_physical_allocated), (int)kmalloc_bytes_total }); + m_graph.add_value({ page_count_to_bytes(user_physical_committed), page_count_to_bytes(user_physical_allocated), kmalloc_bytes_total }); } diff --git a/Userland/Applications/SystemMonitor/main.cpp b/Userland/Applications/SystemMonitor/main.cpp index a6bfd016ad95..739268a44a44 100644 --- a/Userland/Applications/SystemMonitor/main.cpp +++ b/Userland/Applications/SystemMonitor/main.cpp @@ -700,7 +700,7 @@ NonnullRefPtr<GUI::Widget> build_performance_tab() ProcessModel::the().on_cpu_info_change = [cpu_graphs](const NonnullOwnPtrVector<ProcessModel::CpuInfo>& cpus) { float sum_cpu = 0; for (size_t i = 0; i < cpus.size(); ++i) { - cpu_graphs[i].add_value({ (int)cpus[i].total_cpu_percent, (int)cpus[i].total_cpu_percent_kernel }); + cpu_graphs[i].add_value({ static_cast<size_t>(cpus[i].total_cpu_percent), static_cast<size_t>(cpus[i].total_cpu_percent_kernel) }); sum_cpu += cpus[i].total_cpu_percent; } float cpu_usage = sum_cpu / (float)cpus.size();
0c799b23cbf444f46e794d10745a14d79eff5ef1
2024-05-12 19:54:18
Shannon Booth
libweb: Use WebIDL::UnsignedLong for deltaMode in WheelEvent
false
Use WebIDL::UnsignedLong for deltaMode in WheelEvent
libweb
diff --git a/Userland/Libraries/LibWeb/UIEvents/WheelEvent.h b/Userland/Libraries/LibWeb/UIEvents/WheelEvent.h index dff0d57c26e1..ec8e37f282ae 100644 --- a/Userland/Libraries/LibWeb/UIEvents/WheelEvent.h +++ b/Userland/Libraries/LibWeb/UIEvents/WheelEvent.h @@ -12,7 +12,7 @@ namespace Web::UIEvents { -enum class WheelDeltaMode : WebIDL::UnsignedLong { +enum WheelDeltaMode : WebIDL::UnsignedLong { DOM_DELTA_PIXEL = 0, DOM_DELTA_LINE = 1, DOM_DELTA_PAGE = 2, @@ -23,7 +23,7 @@ struct WheelEventInit : public MouseEventInit { double delta_y = 0; double delta_z = 0; - WheelDeltaMode delta_mode = WheelDeltaMode::DOM_DELTA_PIXEL; + WebIDL::UnsignedLong delta_mode = WheelDeltaMode::DOM_DELTA_PIXEL; }; class WheelEvent final : public MouseEvent { @@ -39,7 +39,7 @@ class WheelEvent final : public MouseEvent { double delta_x() const { return m_delta_x; } double delta_y() const { return m_delta_y; } double delta_z() const { return m_delta_z; } - WebIDL::UnsignedLong delta_mode() const { return to_underlying(m_delta_mode); } + WebIDL::UnsignedLong delta_mode() const { return m_delta_mode; } private: WheelEvent(JS::Realm&, FlyString const& event_name, WheelEventInit const& event_init, double page_x, double page_y, double offset_x, double offset_y); @@ -51,7 +51,7 @@ class WheelEvent final : public MouseEvent { double m_delta_x { 0 }; double m_delta_y { 0 }; double m_delta_z { 0 }; - WheelDeltaMode m_delta_mode { WheelDeltaMode::DOM_DELTA_PIXEL }; + WebIDL::UnsignedLong m_delta_mode { WheelDeltaMode::DOM_DELTA_PIXEL }; }; }