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
ac2d9d9273b0bd79b9345d43ba7e644b59341477
2023-08-05 16:52:59
Aliaksandr Kalenik
ladybird: Do not try to use pixelDelta() to calculate wheel offset
false
Do not try to use pixelDelta() to calculate wheel offset
ladybird
diff --git a/Ladybird/WebContentView.cpp b/Ladybird/WebContentView.cpp index 20854d7543ce..cd1c2a9189e9 100644 --- a/Ladybird/WebContentView.cpp +++ b/Ladybird/WebContentView.cpp @@ -282,13 +282,8 @@ void WebContentView::wheelEvent(QWheelEvent* event) auto button = get_button_from_qt_event(*event); auto buttons = get_buttons_from_qt_event(*event); auto modifiers = get_modifiers_from_qt_mouse_event(*event); - auto num_pixels = -event->pixelDelta() / m_inverse_pixel_scaling_ratio; auto num_degrees = -event->angleDelta() / 8; - if (!num_pixels.isNull()) { - client().async_mouse_wheel(to_content_position(position), button, buttons, modifiers, num_pixels.x(), num_pixels.y()); - } else if (!num_degrees.isNull()) { - client().async_mouse_wheel(to_content_position(position), button, buttons, modifiers, num_degrees.x(), num_degrees.y()); - } + client().async_mouse_wheel(to_content_position(position), button, buttons, modifiers, num_degrees.x(), num_degrees.y()); event->accept(); return;
fd32f00839f064d2aad2ba53dd66ea4e3d6a2eff
2020-09-19 00:19:35
Linus Groh
libjs: Mark more ASTNode classes as `final`
false
Mark more ASTNode classes as `final`
libjs
diff --git a/Libraries/LibJS/AST.h b/Libraries/LibJS/AST.h index 2e1cdbebd5ef..057162b43fa3 100644 --- a/Libraries/LibJS/AST.h +++ b/Libraries/LibJS/AST.h @@ -143,7 +143,7 @@ class ScopeNode : public Statement { bool m_strict_mode { false }; }; -class Program : public ScopeNode { +class Program final : public ScopeNode { public: Program() { } @@ -152,7 +152,7 @@ class Program : public ScopeNode { virtual const char* class_name() const override { return "Program"; } }; -class BlockStatement : public ScopeNode { +class BlockStatement final : public ScopeNode { public: BlockStatement() { } @@ -248,7 +248,7 @@ class ErrorExpression final : public Expression { const char* class_name() const override { return "ErrorExpression"; } }; -class ReturnStatement : public Statement { +class ReturnStatement final : public Statement { public: explicit ReturnStatement(RefPtr<Expression> argument) : m_argument(move(argument)) @@ -266,7 +266,7 @@ class ReturnStatement : public Statement { RefPtr<Expression> m_argument; }; -class IfStatement : public Statement { +class IfStatement final : public Statement { public: IfStatement(NonnullRefPtr<Expression> predicate, NonnullRefPtr<Statement> consequent, RefPtr<Statement> alternate) : m_predicate(move(predicate)) @@ -290,7 +290,7 @@ class IfStatement : public Statement { RefPtr<Statement> m_alternate; }; -class WhileStatement : public Statement { +class WhileStatement final : public Statement { public: WhileStatement(NonnullRefPtr<Expression> test, NonnullRefPtr<Statement> body) : m_test(move(test)) @@ -311,7 +311,7 @@ class WhileStatement : public Statement { NonnullRefPtr<Statement> m_body; }; -class DoWhileStatement : public Statement { +class DoWhileStatement final : public Statement { public: DoWhileStatement(NonnullRefPtr<Expression> test, NonnullRefPtr<Statement> body) : m_test(move(test)) @@ -332,7 +332,7 @@ class DoWhileStatement : public Statement { NonnullRefPtr<Statement> m_body; }; -class ForStatement : public Statement { +class ForStatement final : public Statement { public: ForStatement(RefPtr<ASTNode> init, RefPtr<Expression> test, RefPtr<Expression> update, NonnullRefPtr<Statement> body) : m_init(move(init)) @@ -359,7 +359,7 @@ class ForStatement : public Statement { NonnullRefPtr<Statement> m_body; }; -class ForInStatement : public Statement { +class ForInStatement final : public Statement { public: ForInStatement(NonnullRefPtr<ASTNode> lhs, NonnullRefPtr<Expression> rhs, NonnullRefPtr<Statement> body) : m_lhs(move(lhs)) @@ -383,7 +383,7 @@ class ForInStatement : public Statement { NonnullRefPtr<Statement> m_body; }; -class ForOfStatement : public Statement { +class ForOfStatement final : public Statement { public: ForOfStatement(NonnullRefPtr<ASTNode> lhs, NonnullRefPtr<Expression> rhs, NonnullRefPtr<Statement> body) : m_lhs(move(lhs)) @@ -432,7 +432,7 @@ enum class BinaryOp { InstanceOf, }; -class BinaryExpression : public Expression { +class BinaryExpression final : public Expression { public: BinaryExpression(BinaryOp op, NonnullRefPtr<Expression> lhs, NonnullRefPtr<Expression> rhs) : m_op(op) @@ -458,7 +458,7 @@ enum class LogicalOp { NullishCoalescing, }; -class LogicalExpression : public Expression { +class LogicalExpression final : public Expression { public: LogicalExpression(LogicalOp op, NonnullRefPtr<Expression> lhs, NonnullRefPtr<Expression> rhs) : m_op(op) @@ -488,7 +488,7 @@ enum class UnaryOp { Delete, }; -class UnaryExpression : public Expression { +class UnaryExpression final : public Expression { public: UnaryExpression(UnaryOp op, NonnullRefPtr<Expression> lhs) : m_op(op) @@ -811,7 +811,7 @@ enum class AssignmentOp { UnsignedRightShiftAssignment, }; -class AssignmentExpression : public Expression { +class AssignmentExpression final : public Expression { public: AssignmentExpression(AssignmentOp op, NonnullRefPtr<Expression> lhs, NonnullRefPtr<Expression> rhs) : m_op(op) @@ -836,7 +836,7 @@ enum class UpdateOp { Decrement, }; -class UpdateExpression : public Expression { +class UpdateExpression final : public Expression { public: UpdateExpression(UpdateOp op, NonnullRefPtr<Expression> argument, bool prefixed = false) : m_op(op) @@ -888,7 +888,7 @@ class VariableDeclarator final : public ASTNode { RefPtr<Expression> m_init; }; -class VariableDeclaration : public Declaration { +class VariableDeclaration final : public Declaration { public: VariableDeclaration(DeclarationKind declaration_kind, NonnullRefPtrVector<VariableDeclarator> declarations) : m_declaration_kind(declaration_kind) @@ -950,7 +950,7 @@ class ObjectProperty final : public ASTNode { bool m_is_method { false }; }; -class ObjectExpression : public Expression { +class ObjectExpression final : public Expression { public: ObjectExpression(NonnullRefPtrVector<ObjectProperty> properties = {}) : m_properties(move(properties)) @@ -966,7 +966,7 @@ class ObjectExpression : public Expression { NonnullRefPtrVector<ObjectProperty> m_properties; }; -class ArrayExpression : public Expression { +class ArrayExpression final : public Expression { public: ArrayExpression(Vector<RefPtr<Expression>> elements) : m_elements(move(elements))
906e310411a50273b9c4aa9f1d2ed2fb62b56ec9
2021-01-03 15:19:20
Andreas Kling
libgui: Improve up/down arrow behavior in TextEditor with wrapping
false
Improve up/down arrow behavior in TextEditor with wrapping
libgui
diff --git a/Libraries/LibGUI/TextEditor.cpp b/Libraries/LibGUI/TextEditor.cpp index c85bfbd1622a..7ad7a88af15b 100644 --- a/Libraries/LibGUI/TextEditor.cpp +++ b/Libraries/LibGUI/TextEditor.cpp @@ -148,13 +148,9 @@ void TextEditor::update_content_size() set_size_occupied_by_fixed_elements({ ruler_width(), 0 }); } -TextPosition TextEditor::text_position_at(const Gfx::IntPoint& a_position) const +TextPosition TextEditor::text_position_at_content_position(const Gfx::IntPoint& content_position) const { - auto position = a_position; - position.move_by(horizontal_scrollbar().value(), vertical_scrollbar().value()); - position.move_by(-(m_horizontal_content_padding + ruler_width()), 0); - position.move_by(-frame_thickness(), -frame_thickness()); - + auto position = content_position; if (is_single_line() && icon()) position.move_by(-(icon_size() + icon_padding()), 0); @@ -212,6 +208,15 @@ TextPosition TextEditor::text_position_at(const Gfx::IntPoint& a_position) const return { line_index, column_index }; } +TextPosition TextEditor::text_position_at(const Gfx::IntPoint& widget_position) const +{ + auto content_position = widget_position; + content_position.move_by(horizontal_scrollbar().value(), vertical_scrollbar().value()); + content_position.move_by(-(m_horizontal_content_padding + ruler_width()), 0); + content_position.move_by(-frame_thickness(), -frame_thickness()); + return text_position_at_content_position(content_position); +} + void TextEditor::doubleclick_event(MouseEvent& event) { if (event.button() != MouseButton::Left) @@ -760,15 +765,22 @@ void TextEditor::keydown_event(KeyEvent& event) return; } if (is_multi_line() && event.key() == KeyCode::Key_Up) { - if (m_cursor.line() > 0) { + if (m_cursor.line() > 0 || m_line_wrapping_enabled) { if (event.ctrl() && event.shift()) { move_selected_lines_up(); return; } - size_t new_line = m_cursor.line() - 1; - size_t new_column = min(m_cursor.column(), line(new_line).length()); + TextPosition new_cursor; + if (m_line_wrapping_enabled) { + auto position_above = cursor_content_rect().location().translated(0, -line_height()); + new_cursor = text_position_at_content_position(position_above); + } else { + size_t new_line = m_cursor.line() - 1; + size_t new_column = min(m_cursor.column(), line(new_line).length()); + new_cursor = { new_line, new_column }; + } toggle_selection_if_needed_for_event(event); - set_cursor(new_line, new_column); + set_cursor(new_cursor); if (event.shift() && m_selection.start().is_valid()) { m_selection.set_end(m_cursor); did_update_selection(); @@ -781,15 +793,23 @@ void TextEditor::keydown_event(KeyEvent& event) return; } if (is_multi_line() && event.key() == KeyCode::Key_Down) { - if (m_cursor.line() < (line_count() - 1)) { + if (m_cursor.line() < (line_count() - 1) || m_line_wrapping_enabled) { if (event.ctrl() && event.shift()) { move_selected_lines_down(); return; } - size_t new_line = m_cursor.line() + 1; - size_t new_column = min(m_cursor.column(), line(new_line).length()); + TextPosition new_cursor; + if (m_line_wrapping_enabled) { + new_cursor = text_position_at_content_position(cursor_content_rect().location().translated(0, line_height())); + auto position_below = cursor_content_rect().location().translated(0, line_height()); + new_cursor = text_position_at_content_position(position_below); + } else { + size_t new_line = m_cursor.line() + 1; + size_t new_column = min(m_cursor.column(), line(new_line).length()); + new_cursor = { new_line, new_column }; + } toggle_selection_if_needed_for_event(event); - set_cursor(new_line, new_column); + set_cursor(new_cursor); if (event.shift() && m_selection.start().is_valid()) { m_selection.set_end(m_cursor); did_update_selection(); diff --git a/Libraries/LibGUI/TextEditor.h b/Libraries/LibGUI/TextEditor.h index 7a0dcb045652..bfc146fac8b2 100644 --- a/Libraries/LibGUI/TextEditor.h +++ b/Libraries/LibGUI/TextEditor.h @@ -191,6 +191,7 @@ class TextEditor Gfx::IntRect ruler_content_rect(size_t line) const; TextPosition text_position_at(const Gfx::IntPoint&) const; + TextPosition text_position_at_content_position(const Gfx::IntPoint&) const; bool ruler_visible() const { return m_ruler_visible; } Gfx::IntRect content_rect_for_position(const TextPosition&) const; int ruler_width() const;
39c178338729e925b81286ffdac6cca58dfb9133
2020-12-21 04:49:21
Liav A
kernel: Allow to install a real IRQ handler on a spurious one
false
Allow to install a real IRQ handler on a spurious one
kernel
diff --git a/Kernel/Arch/i386/CPU.cpp b/Kernel/Arch/i386/CPU.cpp index b863ab25974d..4325495aa472 100644 --- a/Kernel/Arch/i386/CPU.cpp +++ b/Kernel/Arch/i386/CPU.cpp @@ -583,6 +583,10 @@ void register_generic_interrupt_handler(u8 interrupt_number, GenericInterruptHan return; } if (!s_interrupt_handler[interrupt_number]->is_shared_handler()) { + if (s_interrupt_handler[interrupt_number]->type() == HandlerType::SpuriousInterruptHandler) { + static_cast<SpuriousInterruptHandler*>(s_interrupt_handler[interrupt_number])->register_handler(handler); + return; + } ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::IRQHandler); auto& previous_handler = *s_interrupt_handler[interrupt_number]; s_interrupt_handler[interrupt_number] = nullptr; diff --git a/Kernel/Interrupts/SpuriousInterruptHandler.cpp b/Kernel/Interrupts/SpuriousInterruptHandler.cpp index 4a886a588f2d..3b831d9b58a7 100644 --- a/Kernel/Interrupts/SpuriousInterruptHandler.cpp +++ b/Kernel/Interrupts/SpuriousInterruptHandler.cpp @@ -34,17 +34,25 @@ void SpuriousInterruptHandler::initialize(u8 interrupt_number) new SpuriousInterruptHandler(interrupt_number); } -void SpuriousInterruptHandler::register_handler(GenericInterruptHandler&) +void SpuriousInterruptHandler::register_handler(GenericInterruptHandler& handler) { + ASSERT(!m_real_handler); + m_real_handler = &handler; } void SpuriousInterruptHandler::unregister_handler(GenericInterruptHandler&) { + TODO(); } bool SpuriousInterruptHandler::eoi() { - // FIXME: Actually check if IRQ7 or IRQ15 are spurious, and if not, call EOI with the correct interrupt number. - m_responsible_irq_controller->eoi(*this); + // Actually check if IRQ7 or IRQ15 are spurious, and if not, call EOI with the correct interrupt number. + if (m_real_irq) { + m_responsible_irq_controller->eoi(*this); + m_real_irq = false; // return to default state! + return true; + } + m_responsible_irq_controller->spurious_eoi(*this); return false; } @@ -58,9 +66,15 @@ SpuriousInterruptHandler::~SpuriousInterruptHandler() { } -void SpuriousInterruptHandler::handle_interrupt(const RegisterState&) +void SpuriousInterruptHandler::handle_interrupt(const RegisterState& state) { - // FIXME: Actually check if IRQ7 or IRQ15 are spurious, and if not, call the real handler to handle the IRQ. + // Actually check if IRQ7 or IRQ15 are spurious, and if not, call the real handler to handle the IRQ. + if (m_responsible_irq_controller->get_isr() & (1 << 15)) { + m_real_irq = true; // remember that we had a real IRQ, when EOI later! + m_real_handler->increment_invoking_counter(); + m_real_handler->handle_interrupt(state); + return; + } klog() << "Spurious Interrupt, vector " << interrupt_number(); } @@ -74,6 +88,7 @@ void SpuriousInterruptHandler::enable_interrupt_vector() void SpuriousInterruptHandler::disable_interrupt_vector() { + ASSERT(!m_real_irq); // this flag should not be set when we call this method if (!m_enabled) return; m_enabled = false; diff --git a/Kernel/Interrupts/SpuriousInterruptHandler.h b/Kernel/Interrupts/SpuriousInterruptHandler.h index 82e4a624b90d..7c6f4f04ad68 100644 --- a/Kernel/Interrupts/SpuriousInterruptHandler.h +++ b/Kernel/Interrupts/SpuriousInterruptHandler.h @@ -58,6 +58,7 @@ class SpuriousInterruptHandler final : public GenericInterruptHandler { void disable_interrupt_vector(); explicit SpuriousInterruptHandler(u8 interrupt_number); bool m_enabled; + bool m_real_irq { false }; RefPtr<IRQController> m_responsible_irq_controller; OwnPtr<GenericInterruptHandler> m_real_handler; };
74840de7fc19173627fc6b137f3cd67ec54c77a8
2024-06-03 14:23:32
Matthew Olsson
libweb: Generate a method to get camel-cased CSS property names
false
Generate a method to get camel-cased CSS property names
libweb
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp index 8df9c8059906..93e869ad2613 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/GenerateCSSPropertyID.cpp @@ -174,6 +174,7 @@ bool is_animatable_property(PropertyID); Optional<PropertyID> property_id_from_camel_case_string(StringView); Optional<PropertyID> property_id_from_string(StringView); [[nodiscard]] FlyString const& string_from_property_id(PropertyID); +[[nodiscard]] FlyString const& camel_case_string_from_property_id(PropertyID); bool is_inherited_property(PropertyID); NonnullRefPtr<StyleValue> property_initial_value(JS::Realm&, PropertyID); @@ -428,6 +429,33 @@ FlyString const& string_from_property_id(PropertyID property_id) { } } +FlyString const& camel_case_string_from_property_id(PropertyID property_id) { + switch (property_id) { +)~~~"); + + properties.for_each_member([&](auto& name, auto& value) { + VERIFY(value.is_object()); + + auto member_generator = generator.fork(); + member_generator.set("name", name); + member_generator.set("name:titlecase", title_casify(name)); + member_generator.set("name:camelcase", camel_casify(name)); + member_generator.append(R"~~~( + case PropertyID::@name:titlecase@: { + static FlyString name = "@name:camelcase@"_fly_string; + return name; + } +)~~~"); + }); + + generator.append(R"~~~( + default: { + static FlyString invalid_property_id_string = "(invalid CSS::PropertyID)"_fly_string; + return invalid_property_id_string; + } + } +} + AnimationType animation_type_from_longhand_property(PropertyID property_id) { switch (property_id) {
3499ac4b54b56a3da0fee0a45f2fb28a74b6a075
2020-12-27 20:03:47
Andreas Kling
base: Flip shortcut emblem icons horizontally
false
Flip shortcut emblem icons horizontally
base
diff --git a/Base/res/icons/symlink-emblem-small.png b/Base/res/icons/symlink-emblem-small.png index fc3babc19569..e35cda893280 100644 Binary files a/Base/res/icons/symlink-emblem-small.png and b/Base/res/icons/symlink-emblem-small.png differ diff --git a/Base/res/icons/symlink-emblem.png b/Base/res/icons/symlink-emblem.png index 2b1d35627c8e..956de4e76988 100644 Binary files a/Base/res/icons/symlink-emblem.png and b/Base/res/icons/symlink-emblem.png differ
2801323236066a823cd698513c02f079a021f472
2021-11-11 13:50:04
Ali Mohammad Pur
libweb: Implement WebAssembly::validate()
false
Implement WebAssembly::validate()
libweb
diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp index 18502d1f331a..76d6b3cf7bfd 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp @@ -18,6 +18,7 @@ #include <LibJS/Runtime/DataView.h> #include <LibJS/Runtime/TypedArray.h> #include <LibWasm/AbstractMachine/Interpreter.h> +#include <LibWasm/AbstractMachine/Validator.h> #include <LibWeb/Bindings/WindowObject.h> #include <LibWeb/WebAssembly/WebAssemblyInstanceConstructor.h> #include <LibWeb/WebAssembly/WebAssemblyObject.h> @@ -89,9 +90,30 @@ void WebAssemblyObject::visit_edges(Visitor& visitor) JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::validate) { - // FIXME: Implement this once module validation is implemented in LibWasm. - dbgln("Hit WebAssemblyObject::validate() stub!"); - return JS::Value { true }; + // 1. Let stableBytes be a copy of the bytes held by the buffer bytes. + // Note: There's no need to copy the bytes here as the buffer data cannot change while we're compiling the module. + auto buffer = TRY(vm.argument(0).to_object(global_object)); + + // 2. Compile stableBytes as a WebAssembly module and store the results as module. + auto maybe_module = parse_module(global_object, buffer); + + // 3. If module is error, return false. + if (maybe_module.is_error()) + return JS::Value(false); + + // Drop the module from the cache, we're never going to refer to it. + ScopeGuard drop_from_cache { + [&] { + s_compiled_modules.take_last(); + } + }; + + // 3 continued - our "compile" step is lazy with validation, explicitly do the validation. + if (s_abstract_machine.validate(s_compiled_modules[maybe_module.value()].module).is_error()) + return JS::Value(false); + + // 4. Return true. + return JS::Value(true); } JS::ThrowCompletionOr<size_t> parse_module(JS::GlobalObject& global_object, JS::Object* buffer_object) @@ -123,6 +145,11 @@ JS::ThrowCompletionOr<size_t> parse_module(JS::GlobalObject& global_object, JS:: return vm.throw_completion<JS::TypeError>(global_object, Wasm::parse_error_to_string(module_result.error())); } + if (auto validation_result = WebAssemblyObject::s_abstract_machine.validate(module_result.value()); validation_result.is_error()) { + // FIXME: Throw CompileError instead. + return vm.throw_completion<JS::TypeError>(global_object, validation_result.error().error_string); + } + WebAssemblyObject::s_compiled_modules.append(make<WebAssemblyObject::CompiledWebAssemblyModule>(module_result.release_value())); return WebAssemblyObject::s_compiled_modules.size() - 1; }
e557602d34eb453e3dce15c46b1956388f5cf53c
2023-03-07 17:21:12
Luke Wilde
libweb: Fully read body if there is one in fetch response handover
false
Fully read body if there is one in fetch response handover
libweb
diff --git a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp index 9d1d32222ea5..d95438b5abf3 100644 --- a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp @@ -648,11 +648,10 @@ WebIDL::ExceptionOr<void> fetch_response_handover(JS::Realm& realm, Infrastructu process_body({}); }); } - // FIXME: 4. Otherwise, fully read response’s body given processBody, processBodyError, and fetchParams’s task - // destination. + // 4. Otherwise, fully read response’s body given processBody, processBodyError, and fetchParams’s task + // destination. else { - // NOTE: This branch is not taken for JS fetch(), which supplies no 'process response consume body' function. - (void)process_body_error; + TRY(response.body()->fully_read(realm, move(process_body), move(process_body_error), fetch_params.task_destination())); } }
ff0b4bf360dc6d8c32c7efe3284f789677562450
2022-07-11 21:41:11
Karol Kosek
hexeditor: Gray-out null bytes
false
Gray-out null bytes
hexeditor
diff --git a/Userland/Applications/HexEditor/HexEditor.cpp b/Userland/Applications/HexEditor/HexEditor.cpp index 2aebcd1f5a02..c76504e3f4e3 100644 --- a/Userland/Applications/HexEditor/HexEditor.cpp +++ b/Userland/Applications/HexEditor/HexEditor.cpp @@ -604,8 +604,17 @@ void HexEditor::paint_event(GUI::PaintEvent& event) line_height() - m_line_spacing }; + const u8 cell_value = m_document->get(byte_position).value; + auto line = String::formatted("{:02X}", cell_value); + Gfx::Color background_color = palette().color(background_role()); - Gfx::Color text_color = edited_flag ? Color::Red : palette().color(foreground_role()); + Gfx::Color text_color = [&]() -> Gfx::Color { + if (edited_flag) + return Color::Red; + if (cell_value == 0x00) + return palette().color(ColorRole::PlaceholderText); + return palette().color(foreground_role()); + }(); if (highlight_flag) { background_color = edited_flag ? palette().selection().inverted() : palette().selection(); @@ -616,8 +625,6 @@ void HexEditor::paint_event(GUI::PaintEvent& event) } painter.fill_rect(hex_display_rect, background_color); - const u8 cell_value = m_document->get(byte_position).value; - auto line = String::formatted("{:02X}", cell_value); painter.draw_text(hex_display_rect, line, Gfx::TextAlignment::TopLeft, text_color); if (m_edit_mode == EditMode::Hex) { @@ -640,7 +647,13 @@ void HexEditor::paint_event(GUI::PaintEvent& event) }; background_color = palette().color(background_role()); - text_color = edited_flag ? Color::Red : palette().color(foreground_role()); + text_color = [&]() -> Gfx::Color { + if (edited_flag) + return Color::Red; + if (cell_value == 0x00) + return palette().color(ColorRole::PlaceholderText); + return palette().color(foreground_role()); + }(); if (highlight_flag) { background_color = edited_flag ? palette().selection().inverted() : palette().selection();
db68a52e23c2571fd0701a4bce70fffe95b5ce81
2021-10-25 02:34:47
Idan Horowitz
profiler: Use profile length in ms as histogram column count directly
false
Use profile length in ms as histogram column count directly
profiler
diff --git a/Userland/DevTools/Profiler/TimelineTrack.cpp b/Userland/DevTools/Profiler/TimelineTrack.cpp index def00478c9ac..5e04016a0a86 100644 --- a/Userland/DevTools/Profiler/TimelineTrack.cpp +++ b/Userland/DevTools/Profiler/TimelineTrack.cpp @@ -62,11 +62,9 @@ void TimelineTrack::paint_event(GUI::PaintEvent& event) return min(end_of_trace, max(timestamp, start_of_trace)); }; - float column_width = this->column_width(); - size_t columns = frame_inner_rect().width() / column_width; - - recompute_histograms_if_needed({ start_of_trace, end_of_trace, columns }); + recompute_histograms_if_needed({ start_of_trace, end_of_trace, (size_t)m_profile.length_in_ms() }); + float column_width = this->column_width(); float frame_height = (float)frame_inner_rect().height() / (float)m_max_value; for (size_t bucket = 0; bucket < m_kernel_histogram->size(); bucket++) {
ce1775d81d85ef2c318e5e86001369215435bc55
2021-02-24 19:12:38
Andreas Kling
kernel: Oops, fix broken sys$uname() function definition
false
Oops, fix broken sys$uname() function definition
kernel
diff --git a/Kernel/Syscalls/uname.cpp b/Kernel/Syscalls/uname.cpp index 3b2279653c4b..863d962e8beb 100644 --- a/Kernel/Syscalls/uname.cpp +++ b/Kernel/Syscalls/uname.cpp @@ -28,7 +28,7 @@ namespace Kernel { -int Process::sys$uname(Userspace<utsname*> buf) +int Process::sys$uname(Userspace<utsname*> user_buf) { extern String* g_hostname; extern Lock* g_hostname_lock;
de4061ff945ab660be1799386a9c707e05b3cfdc
2020-11-16 17:51:18
AnotherTest
libtls: Count the mac size towards the packet length in CBC mode
false
Count the mac size towards the packet length in CBC mode
libtls
diff --git a/Libraries/LibTLS/Record.cpp b/Libraries/LibTLS/Record.cpp index 338528c13048..521bee2705e0 100644 --- a/Libraries/LibTLS/Record.cpp +++ b/Libraries/LibTLS/Record.cpp @@ -77,10 +77,10 @@ void TLSv12::update_packet(ByteBuffer& packet) // If the length is already a multiple a block_size, // an entire block of padding is added. // In short, we _never_ have no padding. - padding = block_size - length % block_size; - length += padding; mac_size = mac_length(); length += mac_size; + padding = block_size - length % block_size; + length += padding; } else { block_size = m_aes_local.gcm->cipher().block_size(); padding = 0;
47a4a5ac1d3631a3df0a2b9f8c242b2decec826a
2021-01-21 16:05:32
Andreas Kling
base: Add root to the /etc/shadow file
false
Add root to the /etc/shadow file
base
diff --git a/Base/etc/shadow b/Base/etc/shadow index 947ab79d3b03..2a96727ce7a6 100644 --- a/Base/etc/shadow +++ b/Base/etc/shadow @@ -1 +1,2 @@ +root: anon:$5$zFiQBeTD88m/mhbU$ecHDSdRd5yNV45BzIRXwtRpxJtMpVI5twjRRXO8X03Q=
83edbd05cf2813736f7a4b98f21d529a42f23107
2020-06-18 19:58:20
LepkoQQ
base: Add slovenian characters to Katica and Csilla fonts
false
Add slovenian characters to Katica and Csilla fonts
base
diff --git a/Base/res/fonts/CsillaBold7x10.font b/Base/res/fonts/CsillaBold7x10.font index 3fb1693e5e77..cdefabe6ed1c 100644 Binary files a/Base/res/fonts/CsillaBold7x10.font and b/Base/res/fonts/CsillaBold7x10.font differ diff --git a/Base/res/fonts/CsillaThin7x10.font b/Base/res/fonts/CsillaThin7x10.font index 47c29de35258..d6ef98d6a708 100644 Binary files a/Base/res/fonts/CsillaThin7x10.font and b/Base/res/fonts/CsillaThin7x10.font differ diff --git a/Base/res/fonts/Katica10.font b/Base/res/fonts/Katica10.font index 2f6d17e11cc5..9f5ecc91cf55 100644 Binary files a/Base/res/fonts/Katica10.font and b/Base/res/fonts/Katica10.font differ diff --git a/Base/res/fonts/KaticaBold10.font b/Base/res/fonts/KaticaBold10.font index a635d512eed3..b5a9fe0e0176 100644 Binary files a/Base/res/fonts/KaticaBold10.font and b/Base/res/fonts/KaticaBold10.font differ
049c1a536c295cc85c0e3e42721cd3e4c382fe00
2022-09-03 21:27:37
kleines Filmröllchen
libgfx: Add saturation modification functions to Color
false
Add saturation modification functions to Color
libgfx
diff --git a/Userland/Libraries/LibGfx/Color.h b/Userland/Libraries/LibGfx/Color.h index 4277089712b2..941bc2dd7ce3 100644 --- a/Userland/Libraries/LibGfx/Color.h +++ b/Userland/Libraries/LibGfx/Color.h @@ -313,6 +313,15 @@ class Color { Vector<Color> shades(u32 steps, float max = 1.f) const; Vector<Color> tints(u32 steps, float max = 1.f) const; + constexpr Color saturated_to(float saturation) const + { + auto hsv = to_hsv(); + auto alpha = this->alpha(); + auto color = Color::from_hsv(hsv.hue, static_cast<double>(saturation), hsv.value); + color.set_alpha(alpha); + return color; + } + constexpr Color inverted() const { return Color(~red(), ~green(), ~blue(), alpha());
fa34832297f006ba09af7bf376528e7f4d3a4a37
2023-02-26 20:24:22
Nico Weber
libgfx: Implement WebPImageDecoderPlugin::loop_count()
false
Implement WebPImageDecoderPlugin::loop_count()
libgfx
diff --git a/Tests/LibGfx/TestImageDecoder.cpp b/Tests/LibGfx/TestImageDecoder.cpp index 97ff6a4aacfa..ced7b2a351a6 100644 --- a/Tests/LibGfx/TestImageDecoder.cpp +++ b/Tests/LibGfx/TestImageDecoder.cpp @@ -286,9 +286,7 @@ TEST_CASE(test_webp_extended_lossless_animated) EXPECT_EQ(plugin_decoder->frame_count(), 8u); EXPECT(plugin_decoder->is_animated()); - - // FIXME: This is wrong. - EXPECT(!plugin_decoder->loop_count()); + EXPECT_EQ(plugin_decoder->loop_count(), 42u); EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(990, 1050)); } diff --git a/Tests/LibGfx/test-inputs/extended-lossless-animated.webp b/Tests/LibGfx/test-inputs/extended-lossless-animated.webp index 5b44046e2c8c..f3d087d1cd29 100644 Binary files a/Tests/LibGfx/test-inputs/extended-lossless-animated.webp and b/Tests/LibGfx/test-inputs/extended-lossless-animated.webp differ diff --git a/Userland/Libraries/LibGfx/WebPLoader.cpp b/Userland/Libraries/LibGfx/WebPLoader.cpp index 93a40361aefd..a37066869c65 100644 --- a/Userland/Libraries/LibGfx/WebPLoader.cpp +++ b/Userland/Libraries/LibGfx/WebPLoader.cpp @@ -79,6 +79,11 @@ struct VP8XHeader { u32 height; }; +struct ANIMChunk { + u32 background_color; + u16 loop_count; +}; + } struct WebPLoadingContext { @@ -333,6 +338,20 @@ static ErrorOr<VP8XHeader> decode_webp_chunk_VP8X(WebPLoadingContext& context, C return VP8XHeader { has_icc, has_alpha, has_exif, has_xmp, has_animation, width, height }; } +// https://developers.google.com/speed/webp/docs/riff_container#animation +static ErrorOr<ANIMChunk> decode_webp_chunk_ANIM(WebPLoadingContext& context, Chunk const& anim_chunk) +{ + VERIFY(anim_chunk.type == FourCC("ANIM")); + if (anim_chunk.data.size() < 6) + return context.error("WebPImageDecoderPlugin: ANIM chunk too small"); + + u8 const* data = anim_chunk.data.data(); + u32 background_color = (u32)data[0] | ((u32)data[1] << 8) | ((u32)data[2] << 16) | ((u32)data[3] << 24); + u16 loop_count = data[4] | (data[5] << 8); + + return ANIMChunk { background_color, loop_count }; +} + // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format static ErrorOr<void> decode_webp_extended(WebPLoadingContext& context, ReadonlyBytes chunks) { @@ -532,8 +551,19 @@ bool WebPImageDecoderPlugin::is_animated() size_t WebPImageDecoderPlugin::loop_count() { - // FIXME - return 0; + if (!is_animated()) + return 0; + + if (m_context->state < WebPLoadingContext::State::ChunksDecoded) { + if (decode_webp_chunks(*m_context).is_error()) + return 0; + } + + auto anim_or_error = decode_webp_chunk_ANIM(*m_context, m_context->animation_header_chunk.value()); + if (decode_webp_chunks(*m_context).is_error()) + return 0; + + return anim_or_error.value().loop_count; } size_t WebPImageDecoderPlugin::frame_count()
8c3484296220f9445655ea3ef755207f865800da
2024-04-06 18:47:51
Shannon Booth
ak: Simplify and optimize ASCIICaseInsensitiveFlyStringTraits::equals
false
Simplify and optimize ASCIICaseInsensitiveFlyStringTraits::equals
ak
diff --git a/AK/FlyString.h b/AK/FlyString.h index df2ce8fdd3ef..90ca5d16694b 100644 --- a/AK/FlyString.h +++ b/AK/FlyString.h @@ -97,7 +97,7 @@ struct Formatter<FlyString> : Formatter<StringView> { struct ASCIICaseInsensitiveFlyStringTraits : public Traits<String> { static unsigned hash(FlyString const& s) { return s.ascii_case_insensitive_hash(); } - static bool equals(FlyString const& a, FlyString const& b) { return a.bytes().data() == b.bytes().data() || a.bytes_as_string_view().equals_ignoring_ascii_case(b.bytes_as_string_view()); } + static bool equals(FlyString const& a, FlyString const& b) { return a.equals_ignoring_ascii_case(b); } }; }
9f3f0d9983590864f5b64147329223b46c55e854
2020-03-12 17:57:28
howar6hill
libjs: Add test for function with arguments
false
Add test for function with arguments
libjs
diff --git a/Base/home/anon/js/function-with-arguments.js b/Base/home/anon/js/function-with-arguments.js new file mode 100644 index 000000000000..f87b61162c82 --- /dev/null +++ b/Base/home/anon/js/function-with-arguments.js @@ -0,0 +1,4 @@ +function foo(a, b) { + return a + b; +} +foo(1, 2 + 3);
0248e6ae2796648f8446d1d35ce680d9c5c685bc
2021-08-26 04:24:23
Jean-Baptiste Boric
libc: Check for expected size of struct __jmp_buf
false
Check for expected size of struct __jmp_buf
libc
diff --git a/Userland/Libraries/LibC/setjmp.h b/Userland/Libraries/LibC/setjmp.h index bb087830888c..25e47d870375 100644 --- a/Userland/Libraries/LibC/setjmp.h +++ b/Userland/Libraries/LibC/setjmp.h @@ -45,6 +45,14 @@ struct __jmp_buf { typedef struct __jmp_buf jmp_buf[1]; typedef struct __jmp_buf sigjmp_buf[1]; +#ifdef __i386__ +static_assert(sizeof(struct __jmp_buf) == 32, "struct __jmp_buf unsynchronized with i386/setjmp.S"); +#elif __x86_64__ +static_assert(sizeof(struct __jmp_buf) == 72, "struct __jmp_buf unsynchronized with x86_64/setjmp.S"); +#else +# error +#endif + /** * Calling conventions mandates that sigsetjmp() cannot call setjmp(), * otherwise the restored calling environment will not be the original caller's
b15316eba89228637dc91fd21aae526fed578fc0
2024-03-16 18:57:59
Andreas Kling
libweb: Avoid FlyString->String->FlyString roundtrips in CSS variables
false
Avoid FlyString->String->FlyString roundtrips in CSS variables
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index 6fa8e7a79ed1..0b06e86952fc 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -6943,7 +6943,7 @@ NonnullRefPtr<StyleValue> Parser::resolve_unresolved_style_value(Badge<StyleComp class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> { public: - static NonnullRefPtr<PropertyDependencyNode> create(String name) + static NonnullRefPtr<PropertyDependencyNode> create(FlyString name) { return adopt_ref(*new PropertyDependencyNode(move(name))); } @@ -6974,12 +6974,12 @@ class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> { } private: - explicit PropertyDependencyNode(String name) + explicit PropertyDependencyNode(FlyString name) : m_name(move(name)) { } - String m_name; + FlyString m_name; Vector<NonnullRefPtr<PropertyDependencyNode>> m_children; bool m_marked { false }; }; @@ -7008,12 +7008,12 @@ NonnullRefPtr<StyleValue> Parser::resolve_unresolved_style_value(DOM::Element& e static RefPtr<StyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, FlyString const& custom_property_name) { if (pseudo_element.has_value()) { - if (auto it = element.custom_properties(pseudo_element).find(custom_property_name.to_string()); it != element.custom_properties(pseudo_element).end()) + if (auto it = element.custom_properties(pseudo_element).find(custom_property_name); it != element.custom_properties(pseudo_element).end()) return it->value.value; } for (auto const* current_element = &element; current_element; current_element = current_element->parent_element()) { - if (auto it = current_element->custom_properties({}).find(custom_property_name.to_string()); it != current_element->custom_properties({}).end()) + if (auto it = current_element->custom_properties({}).find(custom_property_name); it != current_element->custom_properties({}).end()) return it->value.value; } return nullptr; @@ -7029,10 +7029,10 @@ bool Parser::expand_variables(DOM::Element& element, Optional<Selector::PseudoEl return false; } - auto get_dependency_node = [&](FlyString name) -> NonnullRefPtr<PropertyDependencyNode> { + auto get_dependency_node = [&](FlyString const& name) -> NonnullRefPtr<PropertyDependencyNode> { if (auto existing = dependencies.get(name); existing.has_value()) return *existing.value(); - auto new_node = PropertyDependencyNode::create(name.to_string()); + auto new_node = PropertyDependencyNode::create(name); dependencies.set(name, new_node); return new_node; };
06593b1894b22ed244ae7e996cfd340bf7b9bac9
2024-11-23 19:16:00
Timothy Flynn
libjs: Implement most of GetTemporalRelativeToOption
false
Implement most of GetTemporalRelativeToOption
libjs
diff --git a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp index 6fc6a482d2ad..8f01fabd29d8 100644 --- a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp +++ b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp @@ -409,7 +409,128 @@ ThrowCompletionOr<RelativeTo> get_temporal_relative_to_option(VM& vm, Object con if (value.is_undefined()) return RelativeTo { .plain_relative_to = {}, .zoned_relative_to = {} }; - // FIXME: Implement the remaining steps of this AO when we have implemented PlainRelativeTo and ZonedRelativeTo. + // FIXME: 3. Let offsetBehaviour be OPTION. + // FIXME: 4. Let matchBehaviour be MATCH-EXACTLY. + + String calendar; + Optional<String> time_zone; + Optional<String> offset_string; + ISODate iso_date; + Variant<ParsedISODateTime::StartOfDay, Time> time { Time {} }; + + // 5. If value is an Object, then + if (value.is_object()) { + auto& object = value.as_object(); + + // FIXME: a. If value has an [[InitializedTemporalZonedDateTime]] internal slot, then + // FIXME: i. Return the Record { [[PlainRelativeTo]]: undefined, [[ZonedRelativeTo]]: value }. + + // b. If value has an [[InitializedTemporalDate]] internal slot, then + if (is<PlainDate>(object)) { + // i. Return the Record { [[PlainRelativeTo]]: value, [[ZonedRelativeTo]]: undefined }. + return RelativeTo { .plain_relative_to = static_cast<PlainDate&>(object), .zoned_relative_to = {} }; + } + + // FIXME: c. If value has an [[InitializedTemporalDateTime]] internal slot, then + // FIXME: i. Let plainDate be ! CreateTemporalDate(value.[[ISODateTime]].[[ISODate]], value.[[Calendar]]). + // FIXME: ii. Return the Record { [[PlainRelativeTo]]: plainDate, [[ZonedRelativeTo]]: undefined }. + + // FIXME: d. Let calendar be ? GetTemporalCalendarIdentifierWithISODefault(value). + calendar = TRY(get_temporal_calendar_identifier_with_iso_default(vm, object)); + + // e. Let fields be ? PrepareCalendarFields(calendar, value, « YEAR, MONTH, MONTH-CODE, DAY », « HOUR, MINUTE, SECOND, MILLISECOND, MICROSECOND, NANOSECOND, OFFSET, TIME-ZONE », «»). + static constexpr auto calendar_field_names = to_array({ CalendarField::Year, CalendarField::Month, CalendarField::MonthCode, CalendarField::Day }); + static constexpr auto non_calendar_field_names = to_array({ CalendarField::Hour, CalendarField::Minute, CalendarField::Second, CalendarField::Millisecond, CalendarField::Microsecond, CalendarField::Nanosecond, CalendarField::Offset, CalendarField::TimeZone }); + auto fields = TRY(prepare_calendar_fields(vm, calendar, object, calendar_field_names, non_calendar_field_names, CalendarFieldList {})); + + // f. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, CONSTRAIN). + auto result = TRY(interpret_temporal_date_time_fields(vm, calendar, fields, Overflow::Constrain)); + + // g. Let timeZone be fields.[[TimeZone]]. + time_zone = move(fields.time_zone); + + // h. Let offsetString be fields.[[Offset]]. + offset_string = move(fields.offset); + + // i. If offsetString is UNSET, then + if (!offset_string.has_value()) { + // FIXME: i. Set offsetBehaviour to WALL. + } + + // j. Let isoDate be result.[[ISODate]]. + iso_date = result.iso_date; + + // k. Let time be result.[[Time]]. + time = result.time; + } + // 6. Else, + else { + // a. If value is not a String, throw a TypeError exception. + if (!value.is_string()) + return vm.throw_completion<TypeError>(ErrorType::NotAString, vm.names.relativeTo); + + // b. Let result be ? ParseISODateTime(value, « TemporalDateTimeString[+Zoned], TemporalDateTimeString[~Zoned] »). + auto result = TRY(parse_iso_date_time(vm, value.as_string().utf8_string_view(), { { Production::TemporalZonedDateTimeString, Production::TemporalDateTimeString } })); + + // c. Let offsetString be result.[[TimeZone]].[[OffsetString]]. + offset_string = move(result.time_zone.offset_string); + + // d. Let annotation be result.[[TimeZone]].[[TimeZoneAnnotation]]. + auto annotation = move(result.time_zone.time_zone_annotation); + + // e. If annotation is EMPTY, then + if (!annotation.has_value()) { + // i. Let timeZone be UNSET. + time_zone = {}; + } + // f. Else, + else { + // i. Let timeZone be ? ToTemporalTimeZoneIdentifier(annotation). + time_zone = TRY(to_temporal_time_zone_identifier(vm, *annotation)); + + // ii. If result.[[TimeZone]].[[Z]] is true, then + if (result.time_zone.z_designator) { + // FIXME: 1. Set offsetBehaviour to EXACT. + } + // iii. Else if offsetString is EMPTY, then + else if (!offset_string.has_value()) { + // FIXME: 1. Set offsetBehaviour to WALL. + } + + // FIXME: iv. Set matchBehaviour to MATCH-MINUTES. + } + + // g. Let calendar be result.[[Calendar]]. + // h. If calendar is EMPTY, set calendar to "iso8601". + calendar = result.calendar.value_or("iso8601"_string); + + // i. Set calendar to ? CanonicalizeCalendar(calendar). + calendar = TRY(canonicalize_calendar(vm, calendar)); + + // j. Let isoDate be CreateISODateRecord(result.[[Year]], result.[[Month]], result.[[Day]]). + iso_date = create_iso_date_record(*result.year, result.month, result.day); + + // k. Let time be result.[[Time]]. + time = result.time; + } + + // 7. If timeZone is UNSET, then + if (!time_zone.has_value()) { + // a. Let plainDate be ? CreateTemporalDate(isoDate, calendar). + auto plain_date = TRY(create_temporal_date(vm, iso_date, move(calendar))); + + // b. Return the Record { [[PlainRelativeTo]]: plainDate, [[ZonedRelativeTo]]: undefined }. + return RelativeTo { .plain_relative_to = plain_date, .zoned_relative_to = {} }; + } + + // FIXME: 8. If offsetBehaviour is OPTION, then + // FIXME: a. Let offsetNs be ! ParseDateTimeUTCOffset(offsetString). + // FIXME: 9. Else, + // FIXME: a. Let offsetNs be 0. + // FIXME: 10. Let epochNanoseconds be ? InterpretISODateTimeOffset(isoDate, time, offsetBehaviour, offsetNs, timeZone, compatible, reject, matchBehaviour). + // FIXME: 11. Let zonedRelativeTo be ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar). + // FIXME: 12. Return the Record { [[PlainRelativeTo]]: undefined, [[ZonedRelativeTo]]: zonedRelativeTo }. + return RelativeTo { .plain_relative_to = {}, .zoned_relative_to = {} }; } diff --git a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h index 316751566bdf..7f3e2b21c9bd 100644 --- a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h +++ b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h @@ -129,9 +129,8 @@ struct SecondsStringPrecision { }; struct RelativeTo { - // FIXME: Make these objects represent their actual types when we re-implement them. - GC::Ptr<JS::Object> plain_relative_to; // [[PlainRelativeTo]] - GC::Ptr<JS::Object> zoned_relative_to; // [[ZonedRelativeTo]] + GC::Ptr<PlainDate> plain_relative_to; // [[PlainRelativeTo]] + GC::Ptr<Object> zoned_relative_to; // FIXME: [[ZonedRelativeTo]] }; struct DifferenceSettings { diff --git a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp index 6e2467fa83f9..a06336892f6f 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp +++ b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp @@ -7,6 +7,7 @@ */ #include <LibJS/Runtime/Temporal/AbstractOperations.h> +#include <LibJS/Runtime/Temporal/Calendar.h> #include <LibJS/Runtime/Temporal/Instant.h> #include <LibJS/Runtime/Temporal/PlainDate.h> #include <LibJS/Runtime/Temporal/PlainDateTime.h> @@ -54,6 +55,19 @@ bool iso_date_time_within_limits(ISODateTime iso_date_time) return true; } +// 5.5.5 InterpretTemporalDateTimeFields ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-interprettemporaldatetimefields +ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(VM& vm, StringView calendar, CalendarFields& fields, Overflow overflow) +{ + // 1. Let isoDate be ? CalendarDateFromFields(calendar, fields, overflow). + auto iso_date = TRY(calendar_date_from_fields(vm, calendar, fields, overflow)); + + // 2. Let time be ? RegulateTime(fields.[[Hour]], fields.[[Minute]], fields.[[Second]], fields.[[Millisecond]], fields.[[Microsecond]], fields.[[Nanosecond]], overflow). + auto time = TRY(regulate_time(vm, *fields.hour, *fields.minute, *fields.second, *fields.millisecond, *fields.microsecond, *fields.nanosecond, overflow)); + + // 3. Return CombineISODateAndTimeRecord(isoDate, time). + return combine_iso_date_and_time_record(iso_date, time); +} + // 5.5.7 BalanceISODateTime ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodatetime ISODateTime balance_iso_date_time(double year, double month, double day, double hour, double minute, double second, double millisecond, double microsecond, double nanosecond) { diff --git a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h index 134f7fe6c61a..5001fcdc1318 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h +++ b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h @@ -14,6 +14,7 @@ namespace JS::Temporal { ISODateTime combine_iso_date_and_time_record(ISODate, Time); bool iso_date_time_within_limits(ISODateTime); +ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(VM&, StringView calendar, CalendarFields&, Overflow); ISODateTime balance_iso_date_time(double year, double month, double day, double hour, double minute, double second, double millisecond, double microsecond, double nanosecond); } diff --git a/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp b/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp index 6cc5fcff5c9b..0f145bd0db54 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp +++ b/Libraries/LibJS/Runtime/Temporal/PlainTime.cpp @@ -46,6 +46,46 @@ Time noon_time_record() return { .days = 0, .hour = 12, .minute = 0, .second = 0, .millisecond = 0, .microsecond = 0, .nanosecond = 0 }; } +// 4.5.8 RegulateTime ( hour, minute, second, millisecond, microsecond, nanosecond, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulatetime +ThrowCompletionOr<Time> regulate_time(VM& vm, double hour, double minute, double second, double millisecond, double microsecond, double nanosecond, Overflow overflow) +{ + switch (overflow) { + // 1. If overflow is CONSTRAIN, then + case Overflow::Constrain: + // a. Set hour to the result of clamping hour between 0 and 23. + hour = clamp(hour, 0, 23); + + // b. Set minute to the result of clamping minute between 0 and 59. + minute = clamp(minute, 0, 59); + + // c. Set second to the result of clamping second between 0 and 59. + second = clamp(second, 0, 59); + + // d. Set millisecond to the result of clamping millisecond between 0 and 999. + millisecond = clamp(millisecond, 0, 999); + + // e. Set microsecond to the result of clamping microsecond between 0 and 999. + microsecond = clamp(microsecond, 0, 999); + + // f. Set nanosecond to the result of clamping nanosecond between 0 and 999. + nanosecond = clamp(nanosecond, 0, 999); + + break; + + // 2. Else, + case Overflow::Reject: + // a. Assert: overflow is REJECT. + // b. If IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception. + if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond)) + return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainTime); + + break; + } + + // 3. Return CreateTimeRecord(hour, minute, second, millisecond, microsecond,nanosecond). + return create_time_record(hour, minute, second, millisecond, microsecond, nanosecond); +} + // 4.5.9 IsValidTime ( hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidtime bool is_valid_time(double hour, double minute, double second, double millisecond, double microsecond, double nanosecond) { diff --git a/Libraries/LibJS/Runtime/Temporal/PlainTime.h b/Libraries/LibJS/Runtime/Temporal/PlainTime.h index 3b1a22f0ea31..761f19f8c0a7 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainTime.h +++ b/Libraries/LibJS/Runtime/Temporal/PlainTime.h @@ -8,6 +8,7 @@ #pragma once +#include <LibJS/Runtime/Temporal/AbstractOperations.h> #include <LibJS/Runtime/Temporal/ISORecords.h> namespace JS::Temporal { @@ -15,6 +16,7 @@ namespace JS::Temporal { Time create_time_record(double hour, double minute, double second, double millisecond, double microsecond, double nanosecond, double delta_days = 0); Time midnight_time_record(); Time noon_time_record(); +ThrowCompletionOr<Time> regulate_time(VM&, double hour, double minute, double second, double millisecond, double microsecond, double nanosecond, Overflow); bool is_valid_time(double hour, double minute, double second, double millisecond, double microsecond, double nanosecond); Time balance_time(double hour, double minute, double second, double millisecond, double microsecond, double nanosecond); diff --git a/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp b/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp index d511218dd35c..606b2db52352 100644 --- a/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp +++ b/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp @@ -53,8 +53,14 @@ ThrowCompletionOr<String> to_temporal_time_zone_identifier(VM& vm, Value tempora if (!temporal_time_zone_like.is_string()) return vm.throw_completion<TypeError>(ErrorType::TemporalInvalidTimeZoneName, temporal_time_zone_like); + return to_temporal_time_zone_identifier(vm, temporal_time_zone_like.as_string().utf8_string_view()); +} + +// 11.1.8 ToTemporalTimeZoneIdentifier ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezoneidentifier +ThrowCompletionOr<String> to_temporal_time_zone_identifier(VM& vm, StringView temporal_time_zone_like) +{ // 3. Let parseResult be ? ParseTemporalTimeZoneString(temporalTimeZoneLike). - auto parse_result = TRY(parse_temporal_time_zone_string(vm, temporal_time_zone_like.as_string().utf8_string_view())); + auto parse_result = TRY(parse_temporal_time_zone_string(vm, temporal_time_zone_like)); // 4. Let offsetMinutes be parseResult.[[OffsetMinutes]]. // 5. If offsetMinutes is not empty, return FormatOffsetTimeZoneIdentifier(offsetMinutes). diff --git a/Libraries/LibJS/Runtime/Temporal/TimeZone.h b/Libraries/LibJS/Runtime/Temporal/TimeZone.h index 711cf1e7758f..197368948819 100644 --- a/Libraries/LibJS/Runtime/Temporal/TimeZone.h +++ b/Libraries/LibJS/Runtime/Temporal/TimeZone.h @@ -30,6 +30,7 @@ enum class Disambiguation { String format_offset_time_zone_identifier(i64 offset_minutes, Optional<TimeStyle> = {}); ThrowCompletionOr<String> to_temporal_time_zone_identifier(VM&, Value temporal_time_zone_like); +ThrowCompletionOr<String> to_temporal_time_zone_identifier(VM&, StringView temporal_time_zone_like); ThrowCompletionOr<Crypto::SignedBigInteger> get_epoch_nanoseconds_for(VM&, StringView time_zone, ISODateTime const&, Disambiguation); ThrowCompletionOr<Crypto::SignedBigInteger> disambiguate_possible_epoch_nanoseconds(VM&, Vector<Crypto::SignedBigInteger> possible_epoch_ns, StringView time_zone, ISODateTime const&, Disambiguation); ThrowCompletionOr<Vector<Crypto::SignedBigInteger>> get_possible_epoch_nanoseconds(VM&, StringView time_zone, ISODateTime const&);
34776752f802061de683a17f32474e09dbc80be3
2022-06-01 15:32:34
Tim Schumacher
ports: Remove the `nice` stub from `oksh`
false
Remove the `nice` stub from `oksh`
ports
diff --git a/Ports/oksh/patches/0001-Add-some-compat-macros-for-serenity.patch b/Ports/oksh/patches/0001-Add-some-compat-macros-for-serenity.patch index fa93c69ef7ba..bdcc56b7002c 100644 --- a/Ports/oksh/patches/0001-Add-some-compat-macros-for-serenity.patch +++ b/Ports/oksh/patches/0001-Add-some-compat-macros-for-serenity.patch @@ -20,7 +20,7 @@ index 5c86edd..6ccf7f6 100644 #define _PW_NAME_LEN 8 #else #define _PW_NAME_LEN MAXLOGNAME - 1 -@@ -116,6 +116,15 @@ +@@ -116,6 +116,14 @@ #define nice(x) (int)0 #endif /* __HAIKU__ */ @@ -30,7 +30,6 @@ index 5c86edd..6ccf7f6 100644 +#define _CS_PATH 1 +#define WCOREFLAG 0200 +#define WCOREDUMP(x) ((x) & WCOREFLAG) -+#define nice(x) (int)0 +#endif /* __serenity__ */ + #ifndef HAVE_SETRESGID
1b043d259a6de8f849c839fae6b367346566ae7c
2024-05-08 04:57:37
Jamie Mansfield
libweb: Implement ShadowRoot.onslotchange
false
Implement ShadowRoot.onslotchange
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/ShadowRoot.cpp b/Userland/Libraries/LibWeb/DOM/ShadowRoot.cpp index e4a869ecda2f..f9846aaf5102 100644 --- a/Userland/Libraries/LibWeb/DOM/ShadowRoot.cpp +++ b/Userland/Libraries/LibWeb/DOM/ShadowRoot.cpp @@ -36,6 +36,18 @@ void ShadowRoot::initialize(JS::Realm& realm) WEB_SET_PROTOTYPE_FOR_INTERFACE(ShadowRoot); } +// https://dom.spec.whatwg.org/#dom-shadowroot-onslotchange +void ShadowRoot::set_onslotchange(WebIDL::CallbackType* event_handler) +{ + set_event_handler_attribute(HTML::EventNames::slotchange, event_handler); +} + +// https://dom.spec.whatwg.org/#dom-shadowroot-onslotchange +WebIDL::CallbackType* ShadowRoot::onslotchange() +{ + return event_handler_attribute(HTML::EventNames::slotchange); +} + // https://dom.spec.whatwg.org/#ref-for-get-the-parent%E2%91%A6 EventTarget* ShadowRoot::get_parent(Event const& event) { diff --git a/Userland/Libraries/LibWeb/DOM/ShadowRoot.h b/Userland/Libraries/LibWeb/DOM/ShadowRoot.h index e2902960b451..62e70254a5c4 100644 --- a/Userland/Libraries/LibWeb/DOM/ShadowRoot.h +++ b/Userland/Libraries/LibWeb/DOM/ShadowRoot.h @@ -25,6 +25,9 @@ class ShadowRoot final : public DocumentFragment { bool delegates_focus() const { return m_delegates_focus; } void set_delegates_focus(bool delegates_focus) { m_delegates_focus = delegates_focus; } + void set_onslotchange(WebIDL::CallbackType*); + WebIDL::CallbackType* onslotchange(); + bool available_to_element_internals() const { return m_available_to_element_internals; } void set_available_to_element_internals(bool available_to_element_internals) { m_available_to_element_internals = available_to_element_internals; } diff --git a/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl b/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl index fe8711a62f3a..942f5a5f80b3 100644 --- a/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl +++ b/Userland/Libraries/LibWeb/DOM/ShadowRoot.idl @@ -9,7 +9,7 @@ interface ShadowRoot : DocumentFragment { readonly attribute boolean delegatesFocus; readonly attribute SlotAssignmentMode slotAssignment; readonly attribute Element host; - // FIXME: attribute EventHandler onslotchange; + attribute EventHandler onslotchange; }; ShadowRoot includes InnerHTML;
b67d0a363239c3ecf72f7514da74f0536595430b
2019-03-04 16:04:25
Andreas Kling
windowserver: Determine resizing "hot corner" based on window's outer rect.
false
Determine resizing "hot corner" based on window's outer rect.
windowserver
diff --git a/WindowServer/WSWindowManager.cpp b/WindowServer/WSWindowManager.cpp index 585ef2002b57..4fdfac62b7a5 100644 --- a/WindowServer/WSWindowManager.cpp +++ b/WindowServer/WSWindowManager.cpp @@ -578,11 +578,12 @@ void WSWindowManager::start_window_resize(WSWindow& window, WSMouseEvent& event) { ResizeDirection::Left, ResizeDirection::None, ResizeDirection::Right }, { ResizeDirection::DownLeft, ResizeDirection::Down, ResizeDirection::DownRight }, }; - Rect window_rect = window.rect(); - int window_relative_x = event.x() - window_rect.x(); - int window_relative_y = event.y() - window_rect.y(); - int hot_area_row = window_relative_y / (window_rect.height() / 3); - int hot_area_column = window_relative_x / (window_rect.width() / 3); + Rect outer_rect = outer_window_rect(window.rect()); + ASSERT(outer_rect.contains(event.position())); + int window_relative_x = event.x() - outer_rect.x(); + int window_relative_y = event.y() - outer_rect.y(); + int hot_area_row = window_relative_y / (outer_rect.height() / 3); + int hot_area_column = window_relative_x / (outer_rect.width() / 3); ASSERT(hot_area_row >= 0 && hot_area_row <= 2); ASSERT(hot_area_column >= 0 && hot_area_column <= 2); m_resize_direction = direction_for_hot_area[hot_area_row][hot_area_column];
c00076de829bfb55a64816f53257ad0e641ccd05
2020-05-21 17:45:49
Sergey Bugaev
libweb: Update the CSS prefix to -libweb
false
Update the CSS prefix to -libweb
libweb
diff --git a/Libraries/LibWeb/CSS/Default.css b/Libraries/LibWeb/CSS/Default.css index 01630a83cf4b..5d83d30e62ff 100644 --- a/Libraries/LibWeb/CSS/Default.css +++ b/Libraries/LibWeb/CSS/Default.css @@ -94,7 +94,7 @@ li { } a:link { - color: -libhtml-link; + color: -libweb-link; text-decoration: underline; } diff --git a/Libraries/LibWeb/CSS/StyleValue.cpp b/Libraries/LibWeb/CSS/StyleValue.cpp index be960319af1a..e507fc052957 100644 --- a/Libraries/LibWeb/CSS/StyleValue.cpp +++ b/Libraries/LibWeb/CSS/StyleValue.cpp @@ -49,7 +49,7 @@ String IdentifierStyleValue::to_string() const case CSS::ValueID::Invalid: return "(invalid)"; case CSS::ValueID::VendorSpecificLink: - return "-libhtml-link"; + return "-libweb-link"; default: ASSERT_NOT_REACHED(); } diff --git a/Libraries/LibWeb/Parser/CSSParser.cpp b/Libraries/LibWeb/Parser/CSSParser.cpp index 84d716052008..b432ead398b7 100644 --- a/Libraries/LibWeb/Parser/CSSParser.cpp +++ b/Libraries/LibWeb/Parser/CSSParser.cpp @@ -158,7 +158,7 @@ NonnullRefPtr<StyleValue> parse_css_value(const StringView& string) if (color.has_value()) return ColorStyleValue::create(color.value()); - if (string == "-libhtml-link") + if (string == "-libweb-link") return IdentifierStyleValue::create(CSS::ValueID::VendorSpecificLink); return StringStyleValue::create(string);
5da94b30eb4e44faea83ee7633fb731e6612e9fe
2021-06-10 03:58:34
Luke
libjs: Add logical assignment bytecode generation
false
Add logical assignment bytecode generation
libjs
diff --git a/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp b/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp index 8daa80b2c1a2..2b8a566ab0ac 100644 --- a/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp +++ b/Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp @@ -232,6 +232,39 @@ void AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) con } m_lhs->generate_bytecode(generator); + + Bytecode::BasicBlock* rhs_block_ptr { nullptr }; + Bytecode::BasicBlock* end_block_ptr { nullptr }; + + // Logical assignments short circuit. + if (m_op == AssignmentOp::AndAssignment) { // &&= + rhs_block_ptr = &generator.make_block(); + end_block_ptr = &generator.make_block(); + + generator.emit<Bytecode::Op::JumpConditional>().set_targets( + Bytecode::Label { *rhs_block_ptr }, + Bytecode::Label { *end_block_ptr }); + } else if (m_op == AssignmentOp::OrAssignment) { // ||= + rhs_block_ptr = &generator.make_block(); + end_block_ptr = &generator.make_block(); + + generator.emit<Bytecode::Op::JumpConditional>().set_targets( + Bytecode::Label { *end_block_ptr }, + Bytecode::Label { *rhs_block_ptr }); + } else if (m_op == AssignmentOp::NullishAssignment) { // ??= + rhs_block_ptr = &generator.make_block(); + end_block_ptr = &generator.make_block(); + + generator.emit<Bytecode::Op::JumpNullish>().set_targets( + Bytecode::Label { *rhs_block_ptr }, + Bytecode::Label { *end_block_ptr }); + } + + if (rhs_block_ptr) + generator.switch_to_basic_block(*rhs_block_ptr); + + // lhs_reg is a part of the rhs_block because the store isn't necessary + // if the logical assignment condition fails. auto lhs_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(lhs_reg); m_rhs->generate_bytecode(generator); @@ -273,12 +306,24 @@ void AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) con case AssignmentOp::UnsignedRightShiftAssignment: generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg); break; + case AssignmentOp::AndAssignment: + case AssignmentOp::OrAssignment: + case AssignmentOp::NullishAssignment: + break; // These are handled above. default: TODO(); } generator.emit<Bytecode::Op::SetVariable>(generator.intern_string(identifier.string())); + if (end_block_ptr) { + generator.emit<Bytecode::Op::Jump>().set_targets( + Bytecode::Label { *end_block_ptr }, + {}); + + generator.switch_to_basic_block(*end_block_ptr); + } + return; }
f409f68a9aaa51f0e1b6a157e73c6edb16e3de24
2023-04-02 03:09:47
MacDue
libweb: Use scaled font when painting list item markers
false
Use scaled font when painting list item markers
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp b/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp index 4fe591a181fb..5e347f3454da 100644 --- a/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp +++ b/Userland/Libraries/LibWeb/Painting/MarkerPaintable.cpp @@ -79,7 +79,9 @@ void MarkerPaintable::paint(PaintContext& context, PaintPhase phase) const case CSS::ListStyleType::UpperRoman: if (layout_box().text().is_null()) break; - context.painter().draw_text(device_enclosing.to_type<int>(), layout_box().text(), Gfx::TextAlignment::Center); + // FIXME: This should use proper text layout logic! + // This does not line up with the text in the <li> element which looks very sad :( + context.painter().draw_text(device_enclosing.to_type<int>(), layout_box().text(), layout_box().scaled_font(context), Gfx::TextAlignment::Center); break; case CSS::ListStyleType::None: return;
d60f6176444f0e29681bf55c64e83b8353fd5437
2021-07-15 05:17:51
Kenneth Myhra
ports: Add Launcher for Epsilon
false
Add Launcher for Epsilon
ports
diff --git a/Ports/epsilon/package.sh b/Ports/epsilon/package.sh index 8d78f9c5e090..827d7dadec38 100755 --- a/Ports/epsilon/package.sh +++ b/Ports/epsilon/package.sh @@ -5,6 +5,9 @@ files="https://github.com/numworks/epsilon/archive/refs/tags/${version}.tar.gz $ auth_type=sha256 makeopts="PLATFORM=simulator TARGET=serenity SERENITY_INSTALL_ROOT=${SERENITY_INSTALL_ROOT}" depends="SDL2 libpng libjpeg freetype" +launcher_name=Epsilon +launcher_category=Utilities +launcher_command=/usr/local/bin/epsilon.elf install() { run cp output/release/simulator/serenity/epsilon.elf ${SERENITY_INSTALL_ROOT}/usr/local/bin/
74a080fb68df849e9f6230e9508cf9ec6dcb8a18
2022-10-18 16:51:38
Liav A
libc: Use proper casting in fgetc and fgetc_unlocked functions
false
Use proper casting in fgetc and fgetc_unlocked functions
libc
diff --git a/Userland/Libraries/LibC/stdio.cpp b/Userland/Libraries/LibC/stdio.cpp index a4d372e6d036..5c6247bc085f 100644 --- a/Userland/Libraries/LibC/stdio.cpp +++ b/Userland/Libraries/LibC/stdio.cpp @@ -631,12 +631,10 @@ char* fgets(char* buffer, int size, FILE* stream) int fgetc(FILE* stream) { VERIFY(stream); - char ch; - size_t nread = fread(&ch, sizeof(char), 1, stream); + unsigned char ch; + size_t nread = fread(&ch, sizeof(unsigned char), 1, stream); if (nread == 1) { - // Note: We do this static_cast because otherwise when casting a char that contains - // 0xFF results in an int containing -1, so an explicit cast is required here. - return static_cast<int>(ch & 0xff); + return ch; } return EOF; } @@ -644,8 +642,8 @@ int fgetc(FILE* stream) int fgetc_unlocked(FILE* stream) { VERIFY(stream); - char ch; - size_t nread = fread_unlocked(&ch, sizeof(char), 1, stream); + unsigned char ch; + size_t nread = fread_unlocked(&ch, sizeof(unsigned char), 1, stream); if (nread == 1) return ch; return EOF;
3af793abfd0d16174ec867e2fd474ef03ddd1a38
2024-04-20 04:16:47
Sönke Holz
libelf: Correct the comment at the top of AArch64's tls.S
false
Correct the comment at the top of AArch64's tls.S
libelf
diff --git a/Userland/Libraries/LibELF/Arch/aarch64/tls.S b/Userland/Libraries/LibELF/Arch/aarch64/tls.S index f33e23add4de..a24ba3392eb9 100644 --- a/Userland/Libraries/LibELF/Arch/aarch64/tls.S +++ b/Userland/Libraries/LibELF/Arch/aarch64/tls.S @@ -24,7 +24,7 @@ // }; // // The resolver takes a pointer to the descriptor as an argument and returns -// the symbol's offset to the thread pointer (tpidr_el1). The second field of +// the symbol's offset to the thread pointer (tpidr_el0). The second field of // the descriptor is an implementation-defined value which the resolver uses to // identify the symbol. //
1bbd889f67c6a5bd30eb8d169275087fde032d73
2023-02-01 22:58:02
Timothy Flynn
meta: Set the Lagom test working directory for run-lagom-target
false
Set the Lagom test working directory for run-lagom-target
meta
diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt index 1291bf0d5165..99ffc6db448c 100644 --- a/Meta/Lagom/CMakeLists.txt +++ b/Meta/Lagom/CMakeLists.txt @@ -253,10 +253,11 @@ function(lagom_test source) add_executable(${name} ${source}) target_link_libraries(${name} PRIVATE LibCore LibTest LibTestMain ${LAGOM_TEST_LIBS}) add_test( - NAME ${name} - COMMAND ${name} - WORKING_DIRECTORY ${LAGOM_TEST_WORKING_DIRECTORY} + NAME ${name} + COMMAND ${name} + WORKING_DIRECTORY ${LAGOM_TEST_WORKING_DIRECTORY} ) + set_target_properties(${name} PROPERTIES LAGOM_WORKING_DIRECTORY "${LAGOM_TEST_WORKING_DIRECTORY}") endfunction() function(serenity_test test_src sub_dir) @@ -693,6 +694,7 @@ endif() if (NOT "$ENV{LAGOM_TARGET}" STREQUAL "") add_custom_target(run-lagom-target COMMAND "${CMAKE_COMMAND}" -E env "SERENITY_SOURCE_DIR=${SERENITY_PROJECT_ROOT}" "$<TARGET_FILE:$ENV{LAGOM_TARGET}>" $ENV{LAGOM_ARGS} + WORKING_DIRECTORY "$<TARGET_PROPERTY:$ENV{LAGOM_TARGET},LAGOM_WORKING_DIRECTORY>" DEPENDS "$<TARGET_FILE:$ENV{LAGOM_TARGET}>" USES_TERMINAL VERBATIM
cf429a788c5c1c8487aad471213650235a396bbc
2020-09-11 17:56:37
Andreas Kling
libgui: Add Widget override cursor concept
false
Add Widget override cursor concept
libgui
diff --git a/Libraries/LibGUI/Widget.cpp b/Libraries/LibGUI/Widget.cpp index 52ae9e82e59e..c79990c9caa1 100644 --- a/Libraries/LibGUI/Widget.cpp +++ b/Libraries/LibGUI/Widget.cpp @@ -318,12 +318,14 @@ void Widget::handle_mousedoubleclick_event(MouseEvent& event) void Widget::handle_enter_event(Core::Event& event) { + window()->update_cursor({}); show_tooltip(); enter_event(event); } void Widget::handle_leave_event(Core::Event& event) { + window()->update_cursor({}); Application::the()->hide_tooltip(); leave_event(event); } @@ -878,4 +880,14 @@ Gfx::IntRect Widget::children_clip_rect() const return rect(); } +void Widget::set_override_cursor(Gfx::StandardCursor cursor) +{ + if (m_override_cursor == cursor) + return; + + m_override_cursor = cursor; + if (auto* window = this->window()) + window->update_cursor({}); +} + } diff --git a/Libraries/LibGUI/Widget.h b/Libraries/LibGUI/Widget.h index 67ab5965b1ff..72c9d8373197 100644 --- a/Libraries/LibGUI/Widget.h +++ b/Libraries/LibGUI/Widget.h @@ -36,6 +36,7 @@ #include <LibGfx/Forward.h> #include <LibGfx/Orientation.h> #include <LibGfx/Rect.h> +#include <LibGfx/StandardCursor.h> #define REGISTER_WIDGET(class_name) \ extern WidgetClassRegistration registration_##class_name; \ @@ -277,6 +278,9 @@ class Widget : public Core::Object { virtual Gfx::IntRect children_clip_rect() const; + Gfx::StandardCursor override_cursor() const { return m_override_cursor; } + void set_override_cursor(Gfx::StandardCursor); + protected: Widget(); @@ -349,6 +353,8 @@ class Widget : public Core::Object { NonnullRefPtr<Gfx::PaletteImpl> m_palette; WeakPtr<Widget> m_focus_proxy; + + Gfx::StandardCursor m_override_cursor { Gfx::StandardCursor::None }; }; inline Widget* Widget::parent_widget() diff --git a/Libraries/LibGUI/Window.cpp b/Libraries/LibGUI/Window.cpp index 6c4c0b226bdd..aba48f26f672 100644 --- a/Libraries/LibGUI/Window.cpp +++ b/Libraries/LibGUI/Window.cpp @@ -228,23 +228,20 @@ void Window::set_window_type(WindowType window_type) void Window::set_cursor(Gfx::StandardCursor cursor) { - if (!is_visible()) - return; - if (!m_custom_cursor && m_cursor == cursor) + if (m_cursor == cursor) return; - WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCursor>(m_window_id, (u32)cursor); m_cursor = cursor; m_custom_cursor = nullptr; + update_cursor(); } void Window::set_cursor(const Gfx::Bitmap& cursor) { - if (!is_visible()) - return; - if (&cursor == m_custom_cursor.ptr()) + if (m_custom_cursor == &cursor) return; + m_cursor = Gfx::StandardCursor::None; m_custom_cursor = &cursor; - WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCustomCursor>(m_window_id, m_custom_cursor->to_shareable_bitmap(WindowServerConnection::the().server_pid())); + update_cursor(); } void Window::handle_drop_event(DropEvent& event) @@ -871,4 +868,24 @@ void Window::set_progress(int progress) ASSERT(m_window_id); WindowServerConnection::the().post_message(Messages::WindowServer::SetWindowProgress(m_window_id, progress)); } + +void Window::update_cursor() +{ + Gfx::StandardCursor new_cursor; + + if (m_hovered_widget && m_hovered_widget->override_cursor() != Gfx::StandardCursor::None) + new_cursor = m_hovered_widget->override_cursor(); + else + new_cursor = m_cursor; + + if (m_effective_cursor == new_cursor) + return; + m_effective_cursor = new_cursor; + + if (m_custom_cursor) + WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCustomCursor>(m_window_id, m_custom_cursor->to_shareable_bitmap(WindowServerConnection::the().server_pid())); + else + WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCursor>(m_window_id, (u32)m_effective_cursor); +} + } diff --git a/Libraries/LibGUI/Window.h b/Libraries/LibGUI/Window.h index 7e10bd6fcf83..621693f57f2c 100644 --- a/Libraries/LibGUI/Window.h +++ b/Libraries/LibGUI/Window.h @@ -196,6 +196,8 @@ class Window : public Core::Object { void set_progress(int); + void update_cursor(Badge<Widget>) { update_cursor(); } + protected: Window(Core::Object* parent = nullptr); virtual void wm_event(WMEvent&); @@ -203,6 +205,8 @@ class Window : public Core::Object { private: virtual bool is_window() const override final { return true; } + void update_cursor(); + void handle_drop_event(DropEvent&); void handle_mouse_event(MouseEvent&); void handle_multi_paint_event(MultiPaintEvent&); @@ -242,6 +246,7 @@ class Window : public Core::Object { Color m_background_color { Color::WarmGray }; WindowType m_window_type { WindowType::Normal }; Gfx::StandardCursor m_cursor { Gfx::StandardCursor::None }; + Gfx::StandardCursor m_effective_cursor { Gfx::StandardCursor::None }; bool m_is_active { false }; bool m_is_active_input { false }; bool m_has_alpha_channel { false };
ff16da98b05a297cd2b317654e3087a99ae44217
2022-03-13 07:08:45
Brian Gianforcaro
ports: Update less to version 590
false
Update less to version 590
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index cb1d84ca000b..67e7bb0e2d93 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -79,7 +79,7 @@ Please make sure to keep this list up to date when adding and updating ports. :^ | [`jot`](jot/) | jot (OpenBSD) | 6.6 | https://github.com/ibara/libpuffy | | [`jq`](jq/) | jq | 1.6 | https://stedolan.github.io/jq/ | | [`klong`](klong/) | Klong | 20190926 | https://t3x.org/klong/ | -| [`less`](less/) | less | 530 | https://www.greenwoodsoftware.com/less/ | +| [`less`](less/) | less | 590 | https://www.greenwoodsoftware.com/less/ | | [`libarchive`](libarchive/) | libarchive | 3.5.2 | https://libarchive.org/ | | [`libassuan`](libassuan/) | libassuan | 2.5.5 | https://gnupg.org/software/libassuan/index.html | | [`libatomic_ops`](libatomic_ops/) | libatomic\_ops | 7.6.10 | https://www.hboehm.info/gc/ | diff --git a/Ports/less/package.sh b/Ports/less/package.sh index 93c4a5f081b9..afb904920094 100755 --- a/Ports/less/package.sh +++ b/Ports/less/package.sh @@ -1,6 +1,6 @@ #!/usr/bin/env -S bash ../.port_include.sh port=less -version=530 +version=590 useconfigure="true" files="https://ftpmirror.gnu.org/gnu/less/less-${version}.tar.gz less-${version}.tar.gz https://ftpmirror.gnu.org/gnu/less/less-${version}.tar.gz.sig less-${version}.tar.gz.sig
7026174458ab15e2ac2d1c01c1cd24ed0e05b5d2
2023-05-24 22:57:59
Josh Spicer
meta: Prebuild repo dev container
false
Prebuild repo dev container
meta
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index aa74ed32726b..0594109ed081 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,12 +1,12 @@ { - "name": "Ubuntu", + "name": "SerenityOS", "image": "mcr.microsoft.com/devcontainers/base:jammy", // Features to add to the dev container. More info: https://containers.dev/implementors/features. "features": { "ghcr.io/devcontainers/features/github-cli:1": {}, "ghcr.io/devcontainers-contrib/features/pre-commit:1": {}, - "./serenity": { + "./features/serenity": { "llvm_version": 15, "enable_ladybird": true, "enable_serenity": true diff --git a/.devcontainer/serenity/devcontainer-feature.json b/.devcontainer/features/serenity/devcontainer-feature.json similarity index 100% rename from .devcontainer/serenity/devcontainer-feature.json rename to .devcontainer/features/serenity/devcontainer-feature.json diff --git a/.devcontainer/serenity/install.sh b/.devcontainer/features/serenity/install.sh similarity index 100% rename from .devcontainer/serenity/install.sh rename to .devcontainer/features/serenity/install.sh diff --git a/.devcontainer/optimized/.devcontainer.json b/.devcontainer/optimized/.devcontainer.json new file mode 100644 index 000000000000..c7c9c44a191a --- /dev/null +++ b/.devcontainer/optimized/.devcontainer.json @@ -0,0 +1,11 @@ +// The docker image used below was generated from '.devcontainer/devcontainer.json' +// by the '.github/workflows/dev-container.yml' workflow. +// +// By building this dev container image in advance, tools +// like GitHub Codespaces (https://containers.dev/supporting) +// do not need to install all the prerequsite dependencies from scratch, +// getting you into your development environment faster! +{ + "name": "SerenityOS (Pre-Built Image)", + "image": "ghcr.io/SerenityOS/serenity-devcontainer:base" +} diff --git a/.github/workflows/dev-container.yml b/.github/workflows/dev-container.yml new file mode 100644 index 000000000000..be3947750bcf --- /dev/null +++ b/.github/workflows/dev-container.yml @@ -0,0 +1,39 @@ +# This workflow builds a docker image with the Dev Container CLI (https://github.com/devcontainers/cli) +# +name: 'Build Dev Container Image' +on: + workflow_dispatch: + push: + paths: + - '.devcontainer/**' + schedule: + # https://crontab.guru/#0_0_*_*_1 + - cron: '0 0 * * 1' + + +permissions: + contents: read + # Push images to GHCR. + packages: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + + - name: Checkout + uses: actions/checkout@v3 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build Base Dev Container Image + uses: devcontainers/[email protected] + with: + imageName: ghcr.io/${{ github.repository_owner }}/serenity-devcontainer + imageTag: base,latest + push: always
3ddefb9f5f7250f9937c61a570bf67bd8124abb2
2022-11-03 16:59:45
Filiph Sandström
ci: Upgrade `actions/checkout` to v3
false
Upgrade `actions/checkout` to v3
ci
diff --git a/.github/workflows/libjs-test262.yml b/.github/workflows/libjs-test262.yml index 9ce65983d53b..97f8f8ff3bac 100644 --- a/.github/workflows/libjs-test262.yml +++ b/.github/workflows/libjs-test262.yml @@ -19,28 +19,28 @@ jobs: rm -rf "${{ github.workspace }}/*" - name: Checkout SerenityOS/serenity - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Checkout linusg/libjs-test262 - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: repository: linusg/libjs-test262 path: libjs-test262 - name: Checkout linusg/libjs-website - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: repository: linusg/libjs-website path: libjs-website - name: Checkout tc39/test262 - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: repository: tc39/test262 path: test262 - name: Checkout tc39/test262-parser-tests - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: repository: tc39/test262-parser-tests path: test262-parser-tests diff --git a/.github/workflows/manpages.yml b/.github/workflows/manpages.yml index adc8dd8c3c7c..bcf05662252a 100644 --- a/.github/workflows/manpages.yml +++ b/.github/workflows/manpages.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-22.04 if: always() && github.repository == 'SerenityOS/serenity' && github.ref == 'refs/heads/master' steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: r-lib/actions/setup-pandoc@v1 with: pandoc-version: '2.13' diff --git a/.github/workflows/pvs-studio-static-analysis.yml b/.github/workflows/pvs-studio-static-analysis.yml index 59793b0b6a71..fc08333cb88c 100644 --- a/.github/workflows/pvs-studio-static-analysis.yml +++ b/.github/workflows/pvs-studio-static-analysis.yml @@ -12,7 +12,7 @@ jobs: PVS_STUDIO_ANALYSIS_ARCH: i686 if: always() && github.repository == 'SerenityOS/serenity' && github.ref == 'refs/heads/master' steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: "Configure PVS-Studio Repository" run: | diff --git a/.github/workflows/sonar-cloud-static-analysis.yml b/.github/workflows/sonar-cloud-static-analysis.yml index 61c033e0ff89..ecaed3111be4 100644 --- a/.github/workflows/sonar-cloud-static-analysis.yml +++ b/.github/workflows/sonar-cloud-static-analysis.yml @@ -15,7 +15,7 @@ jobs: SONAR_SERVER_URL: "https://sonarcloud.io" SONAR_ANALYSIS_ARCH: i686 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis diff --git a/.github/workflows/twitter.yml b/.github/workflows/twitter.yml index 3c4fb788ebcf..64b1f2821db8 100644 --- a/.github/workflows/twitter.yml +++ b/.github/workflows/twitter.yml @@ -8,7 +8,7 @@ jobs: if: always() && github.repository == 'SerenityOS/serenity' && github.ref == 'refs/heads/master' steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: actions/setup-node@v2 with: node-version: '14'
139c575cc92d05b1621860791522d8a724586291
2023-09-15 22:00:26
Timothy Flynn
libunicode: Update to Unicode version 15.1.0
false
Update to Unicode version 15.1.0
libunicode
diff --git a/Meta/CMake/unicode_data.cmake b/Meta/CMake/unicode_data.cmake index ba43f3dc1856..dca7f69fe410 100644 --- a/Meta/CMake/unicode_data.cmake +++ b/Meta/CMake/unicode_data.cmake @@ -1,6 +1,6 @@ include(${CMAKE_CURRENT_LIST_DIR}/utils.cmake) -set(UCD_VERSION 15.0.0) +set(UCD_VERSION 15.1.0) set(UCD_PATH "${SERENITY_CACHE_DIR}/UCD" CACHE PATH "Download location for UCD files") set(UCD_VERSION_FILE "${UCD_PATH}/version.txt") diff --git a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp index 196410a50b57..36afc1fda1d2 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeData.cpp @@ -375,7 +375,21 @@ static ErrorOr<void> parse_prop_list(Core::InputBufferedFile& file, PropList& pr line = line.substring_view(0, *index); auto segments = line.split_view(';', SplitBehavior::KeepEmpty); - VERIFY(segments.size() == 2); + VERIFY(segments.size() == 2 || segments.size() == 3); + + String combined_segment_buffer; + + if (segments.size() == 3) { + // For example, in DerivedCoreProperties.txt, there are lines such as: + // + // 094D ; InCB; Linker # Mn DEVANAGARI SIGN VIRAMA + // + // These are used in text segmentation to prevent breaking within some extended grapheme clusters. + // So here, we combine the segments into a single property, which allows us to simply do code point + // property lookups at runtime for specific Indic Conjunct Break sequences. + combined_segment_buffer = MUST(String::join('_', Array { segments[1].trim_whitespace(), segments[2].trim_whitespace() })); + segments[1] = combined_segment_buffer; + } auto code_point_range = parse_code_point_range(segments[0].trim_whitespace()); Vector<StringView> properties; diff --git a/Tests/LibUnicode/TestSegmentation.cpp b/Tests/LibUnicode/TestSegmentation.cpp index 1159ae875b4b..675ce060fe76 100644 --- a/Tests/LibUnicode/TestSegmentation.cpp +++ b/Tests/LibUnicode/TestSegmentation.cpp @@ -51,6 +51,27 @@ TEST_CASE(grapheme_segmentation) test_grapheme_segmentation("a👩🏼‍❤️‍👨🏻b"sv, { 0u, 1u, 29u, 30u }); } +TEST_CASE(grapheme_segmentation_indic_conjunct_break) +{ + test_grapheme_segmentation("\u0915"sv, { 0u, 3u }); + test_grapheme_segmentation("\u0915a"sv, { 0u, 3u, 4u }); + test_grapheme_segmentation("\u0915\u0916"sv, { 0u, 3u, 6u }); + + test_grapheme_segmentation("\u0915\u094D\u0916"sv, { 0u, 9u }); + + test_grapheme_segmentation("\u0915\u09BC\u09CD\u094D\u0916"sv, { 0u, 15u }); + test_grapheme_segmentation("\u0915\u094D\u09BC\u09CD\u0916"sv, { 0u, 15u }); + + test_grapheme_segmentation("\u0915\u09BC\u09CD\u094D\u09BC\u09CD\u0916"sv, { 0u, 21u }); + test_grapheme_segmentation("\u0915\u09BC\u09CD\u09BC\u09CD\u094D\u0916"sv, { 0u, 21u }); + test_grapheme_segmentation("\u0915\u094D\u09BC\u09CD\u09BC\u09CD\u0916"sv, { 0u, 21u }); + + test_grapheme_segmentation("\u0915\u09BC\u09CD\u09BC\u09CD\u094D\u09BC\u09CD\u0916"sv, { 0u, 27u }); + test_grapheme_segmentation("\u0915\u09BC\u09CD\u094D\u09BC\u09CD\u09BC\u09CD\u0916"sv, { 0u, 27u }); + + test_grapheme_segmentation("\u0915\u09BC\u09CD\u09BC\u09CD\u094D\u09BC\u09CD\u09BC\u09CD\u0916"sv, { 0u, 33u }); +} + template<size_t N> static void test_word_segmentation(StringView string, size_t const (&expected_boundaries)[N]) { diff --git a/Userland/Libraries/LibUnicode/Segmentation.cpp b/Userland/Libraries/LibUnicode/Segmentation.cpp index 750f52907acb..74a8dedfb40e 100644 --- a/Userland/Libraries/LibUnicode/Segmentation.cpp +++ b/Userland/Libraries/LibUnicode/Segmentation.cpp @@ -57,6 +57,22 @@ static void for_each_grapheme_segmentation_boundary_impl([[maybe_unused]] ViewTy return (code_point_has_grapheme_break_property(code_point, properties) || ...); }; + auto skip_incb_extend_linker_sequence = [&](auto& it) { + while (true) { + if (it == view.end() || !code_point_has_property(*it, Property::InCB_Extend)) + return; + + auto next_it = it; + ++next_it; + + if (next_it == view.end() || !code_point_has_property(*next_it, Property::InCB_Linker)) + return; + + it = next_it; + ++it; + } + }; + // GB1 if (callback(0) == IterationDecision::Break) return; @@ -70,6 +86,23 @@ static void for_each_grapheme_segmentation_boundary_impl([[maybe_unused]] ViewTy for (++it; it != view.end(); ++it, code_point = next_code_point) { next_code_point = *it; + // GB9c + if (code_point_has_property(code_point, Property::InCB_Consonant)) { + auto it_copy = it; + skip_incb_extend_linker_sequence(it_copy); + + if (it_copy != view.end() && code_point_has_property(*it_copy, Property::InCB_Linker)) { + ++it_copy; + skip_incb_extend_linker_sequence(it_copy); + + if (it_copy != view.end() && code_point_has_property(*it_copy, Property::InCB_Consonant)) { + next_code_point = *it_copy; + it = it_copy; + continue; + } + } + } + // GB11 if (code_point_has_property(code_point, Property::Extended_Pictographic) && has_any_gbp(next_code_point, GBP::Extend, GBP::ZWJ)) { auto it_copy = it;
7301db4f9aac78063736597cd0d316bcdd1a6488
2019-12-18 01:45:10
Andreas Kling
gtexteditor: Fix broken rendering of selection on wrapped lines
false
Fix broken rendering of selection on wrapped lines
gtexteditor
diff --git a/Libraries/LibGUI/GTextEditor.cpp b/Libraries/LibGUI/GTextEditor.cpp index f9dad605028b..c95ef3bd9fdf 100644 --- a/Libraries/LibGUI/GTextEditor.cpp +++ b/Libraries/LibGUI/GTextEditor.cpp @@ -410,11 +410,11 @@ void GTextEditor::paint_event(GPaintEvent& event) bool selection_ends_on_current_visual_line = visual_line_index == last_visual_line_with_selection; int selection_left = selection_begins_on_current_visual_line - ? content_x_for_position({ line_index, selection_start_column_within_line }) + ? content_x_for_position({ line_index, (size_t)selection_start_column_within_line }) : m_horizontal_content_padding; int selection_right = selection_ends_on_current_visual_line - ? content_x_for_position({ line_index, selection_end_column_within_line }) + ? content_x_for_position({ line_index, (size_t)selection_end_column_within_line }) : visual_line_rect.right() + 1; Rect selection_rect { @@ -426,7 +426,7 @@ void GTextEditor::paint_event(GPaintEvent& event) painter.fill_rect(selection_rect, Color::from_rgb(0x955233)); - size_t start_of_selection_within_visual_line = max((size_t)0, selection_start_column_within_line - start_of_visual_line); + size_t start_of_selection_within_visual_line = (size_t)max(0, (int)selection_start_column_within_line - (int)start_of_visual_line); size_t end_of_selection_within_visual_line = selection_end_column_within_line - start_of_visual_line; StringView visual_selected_text {
fb9ee26c43df14f582db2a39aee87ca161ed0884
2022-03-23 20:27:05
Andreas Kling
libweb: Resolve numeric line-heights against element's own font size
false
Resolve numeric line-heights against element's own font size
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/Node.cpp b/Userland/Libraries/LibWeb/Layout/Node.cpp index 2dcb2db966cf..9870ec289d06 100644 --- a/Userland/Libraries/LibWeb/Layout/Node.cpp +++ b/Userland/Libraries/LibWeb/Layout/Node.cpp @@ -231,7 +231,12 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& specified_style) { auto& computed_values = static_cast<CSS::MutableComputedValues&>(m_computed_values); + // NOTE: We have to be careful that font-related properties get set in the right order. + // m_font is used by Length::to_px() when resolving sizes against this layout node. + // That's why it has to be set before everything else. m_font = specified_style.computed_font(); + computed_values.set_font_size(specified_style.property(CSS::PropertyID::FontSize).value()->to_length().to_px(*this)); + computed_values.set_font_weight(specified_style.property(CSS::PropertyID::FontWeight).value()->to_integer()); m_line_height = specified_style.line_height(*this); computed_values.set_vertical_align(specified_style.vertical_align()); @@ -360,9 +365,6 @@ void NodeWithStyle::apply_style(const CSS::StyleProperties& specified_style) computed_values.set_box_sizing(specified_style.box_sizing()); - computed_values.set_font_size(specified_style.property(CSS::PropertyID::FontSize).value()->to_length().to_px(*this)); - computed_values.set_font_weight(specified_style.property(CSS::PropertyID::FontWeight).value()->to_integer()); - if (auto maybe_font_variant = specified_style.font_variant(); maybe_font_variant.has_value()) computed_values.set_font_variant(maybe_font_variant.release_value());
6688ce41b21f54d71138a16a949907775397d315
2020-07-12 03:27:14
Andreas Kling
userspaceemulator: Implement some of the IMUL instruction family
false
Implement some of the IMUL instruction family
userspaceemulator
diff --git a/DevTools/UserspaceEmulator/SoftCPU.cpp b/DevTools/UserspaceEmulator/SoftCPU.cpp index e52c711b9e3b..72fd0edff790 100644 --- a/DevTools/UserspaceEmulator/SoftCPU.cpp +++ b/DevTools/UserspaceEmulator/SoftCPU.cpp @@ -281,6 +281,33 @@ static Destination op_and(SoftCPU& cpu, Destination& dest, const Source& src) return result; } +template<typename Destination, typename Source> +static typename TypeDoubler<Destination>::type op_imul(SoftCPU& cpu, const Destination& dest, const Source& src) +{ + Destination result = 0; + u32 new_flags = 0; + + if constexpr (sizeof(Destination) == 4) { + asm volatile("imull %%ecx, %%eax\n" + : "=a"(result) + : "a"(dest), "c"((i32)src)); + } else if constexpr (sizeof(Destination) == 2) { + asm volatile("imulw %%cx, %%ax\n" + : "=a"(result) + : "a"(dest), "c"((i16)src)); + } else { + ASSERT_NOT_REACHED(); + } + + asm volatile( + "pushf\n" + "pop %%ebx" + : "=b"(new_flags)); + + cpu.set_flags_oszapc(new_flags); + return result; +} + template<bool update_dest, typename Op> void SoftCPU::generic_AL_imm8(Op op, const X86::Instruction& insn) { @@ -514,12 +541,36 @@ void SoftCPU::IDIV_RM8(const X86::Instruction&) { TODO(); } void SoftCPU::IMUL_RM16(const X86::Instruction&) { TODO(); } void SoftCPU::IMUL_RM32(const X86::Instruction&) { TODO(); } void SoftCPU::IMUL_RM8(const X86::Instruction&) { TODO(); } -void SoftCPU::IMUL_reg16_RM16(const X86::Instruction&) { TODO(); } -void SoftCPU::IMUL_reg16_RM16_imm16(const X86::Instruction&) { TODO(); } -void SoftCPU::IMUL_reg16_RM16_imm8(const X86::Instruction&) { TODO(); } -void SoftCPU::IMUL_reg32_RM32(const X86::Instruction&) { TODO(); } -void SoftCPU::IMUL_reg32_RM32_imm32(const X86::Instruction&) { TODO(); } -void SoftCPU::IMUL_reg32_RM32_imm8(const X86::Instruction&) { TODO(); } + +void SoftCPU::IMUL_reg16_RM16(const X86::Instruction& insn) +{ + gpr16(insn.reg16()) = op_imul<i16, i16>(*this, gpr16(insn.reg16()), insn.modrm().read16(*this, insn)); +} + +void SoftCPU::IMUL_reg16_RM16_imm16(const X86::Instruction& insn) +{ + gpr16(insn.reg16()) = op_imul<i16, i16>(*this, insn.modrm().read16(*this, insn), insn.imm16()); +} + +void SoftCPU::IMUL_reg16_RM16_imm8(const X86::Instruction& insn) +{ + gpr16(insn.reg16()) = op_imul<i16, i8>(*this, insn.modrm().read16(*this, insn), insn.imm8()); +} + +void SoftCPU::IMUL_reg32_RM32(const X86::Instruction& insn) +{ + gpr32(insn.reg32()) = op_imul<i32, i32>(*this, gpr32(insn.reg32()), insn.modrm().read32(*this, insn)); +} + +void SoftCPU::IMUL_reg32_RM32_imm32(const X86::Instruction& insn) +{ + gpr32(insn.reg32()) = op_imul<i32, i32>(*this, insn.modrm().read32(*this, insn), insn.imm32()); +} + +void SoftCPU::IMUL_reg32_RM32_imm8(const X86::Instruction& insn) +{ + gpr32(insn.reg32()) = op_imul<i32, i8>(*this, insn.modrm().read32(*this, insn), insn.imm8()); +} template<typename T> static T op_inc(SoftCPU& cpu, T data)
4e56e9fa2af3649e36d2cfcd2fd9a6523223dda0
2021-04-10 18:28:48
Andreas Kling
pixelpaint: Alt shortcuts and book title capitalization in menus
false
Alt shortcuts and book title capitalization in menus
pixelpaint
diff --git a/Userland/Applications/PixelPaint/MoveTool.cpp b/Userland/Applications/PixelPaint/MoveTool.cpp index ebeba5ba89fd..1b04878bcea9 100644 --- a/Userland/Applications/PixelPaint/MoveTool.cpp +++ b/Userland/Applications/PixelPaint/MoveTool.cpp @@ -123,7 +123,7 @@ void MoveTool::on_context_menu(Layer& layer, GUI::ContextMenuEvent& event) m_editor)); m_context_menu->add_separator(); m_context_menu->add_action(GUI::Action::create( - "Delete layer", Gfx::Bitmap::load_from_file("/res/icons/16x16/delete.png"), [this](auto&) { + "&Delete Layer", Gfx::Bitmap::load_from_file("/res/icons/16x16/delete.png"), [this](auto&) { m_editor->image()->remove_layer(*m_context_menu_layer); // FIXME: This should not be done imperatively here. Perhaps a Image::Client interface that ImageEditor can implement? if (m_editor->active_layer() == m_context_menu_layer) diff --git a/Userland/Applications/PixelPaint/main.cpp b/Userland/Applications/PixelPaint/main.cpp index bbaab8942a59..b39631bcaeaa 100644 --- a/Userland/Applications/PixelPaint/main.cpp +++ b/Userland/Applications/PixelPaint/main.cpp @@ -115,7 +115,7 @@ int main(int argc, char** argv) window->show(); auto menubar = GUI::MenuBar::construct(); - auto& app_menu = menubar->add_menu("File"); + auto& file_menu = menubar->add_menu("&File"); auto open_image_file = [&](auto& path) { auto image = PixelPaint::Image::create_from_file(path); @@ -127,9 +127,9 @@ int main(int argc, char** argv) layer_list_widget.set_image(image); }; - app_menu.add_action( + file_menu.add_action( GUI::Action::create( - "New", [&](auto&) { + "&New Image...", [&](auto&) { auto dialog = PixelPaint::CreateNewImageDialog::construct(window); if (dialog->exec() == GUI::Dialog::ExecOK) { auto image = PixelPaint::Image::create_with_size(dialog->image_size()); @@ -143,43 +143,35 @@ int main(int argc, char** argv) } }, window)); - app_menu.add_action(GUI::CommonActions::make_open_action([&](auto&) { + file_menu.add_action(GUI::CommonActions::make_open_action([&](auto&) { Optional<String> open_path = GUI::FilePicker::get_open_filepath(window); - if (!open_path.has_value()) return; - open_image_file(open_path.value()); })); - app_menu.add_action(GUI::CommonActions::make_save_as_action([&](auto&) { + file_menu.add_action(GUI::CommonActions::make_save_as_action([&](auto&) { if (!image_editor.image()) return; - Optional<String> save_path = GUI::FilePicker::get_save_filepath(window, "untitled", "pp"); - if (!save_path.has_value()) return; - image_editor.image()->save(save_path.value()); })); - auto& export_submenu = app_menu.add_submenu("Export"); + auto& export_submenu = file_menu.add_submenu("&Export"); export_submenu.add_action( GUI::Action::create( - "As BMP", [&](auto&) { + "As &BMP", [&](auto&) { if (!image_editor.image()) return; - Optional<String> save_path = GUI::FilePicker::get_save_filepath(window, "untitled", "bmp"); - if (!save_path.has_value()) return; - image_editor.image()->export_bmp(save_path.value()); }, window)); export_submenu.add_action( GUI::Action::create( - "As PNG", [&](auto&) { + "As &PNG", [&](auto&) { if (!image_editor.image()) return; @@ -192,13 +184,12 @@ int main(int argc, char** argv) }, window)); - app_menu.add_separator(); - app_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) { + file_menu.add_separator(); + file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) { GUI::Application::the()->quit(); - return; })); - auto& edit_menu = menubar->add_menu("Edit"); + auto& edit_menu = menubar->add_menu("&Edit"); auto paste_action = GUI::CommonActions::make_paste_action([&](auto&) { VERIFY(image_editor.image()); auto bitmap = GUI::Clipboard::the().bitmap(); @@ -227,16 +218,16 @@ int main(int argc, char** argv) }); edit_menu.add_action(redo_action); - auto& tool_menu = menubar->add_menu("Tool"); + auto& tool_menu = menubar->add_menu("&Tool"); toolbox.for_each_tool([&](auto& tool) { if (tool.action()) tool_menu.add_action(*tool.action()); return IterationDecision::Continue; }); - auto& layer_menu = menubar->add_menu("Layer"); + auto& layer_menu = menubar->add_menu("&Layer"); layer_menu.add_action(GUI::Action::create( - "Create new layer...", { Mod_Ctrl | Mod_Shift, Key_N }, [&](auto&) { + "&New Layer...", { Mod_Ctrl | Mod_Shift, Key_N }, [&](auto&) { auto dialog = PixelPaint::CreateNewLayerDialog::construct(image_editor.image()->size(), window); if (dialog->exec() == GUI::Dialog::ExecOK) { auto layer = PixelPaint::Layer::create_with_size(*image_editor.image(), dialog->layer_size(), dialog->layer_name()); @@ -252,28 +243,28 @@ int main(int argc, char** argv) layer_menu.add_separator(); layer_menu.add_action(GUI::Action::create( - "Select previous layer", { 0, Key_PageUp }, [&](auto&) { + "Select &Previous Layer", { 0, Key_PageUp }, [&](auto&) { layer_list_widget.move_selection(1); }, window)); layer_menu.add_action(GUI::Action::create( - "Select next layer", { 0, Key_PageDown }, [&](auto&) { + "Select &Next Layer", { 0, Key_PageDown }, [&](auto&) { layer_list_widget.move_selection(-1); }, window)); layer_menu.add_action(GUI::Action::create( - "Select top layer", { 0, Key_Home }, [&](auto&) { + "Select &Top Layer", { 0, Key_Home }, [&](auto&) { layer_list_widget.select_top_layer(); }, window)); layer_menu.add_action(GUI::Action::create( - "Select bottom layer", { 0, Key_End }, [&](auto&) { + "Select &Bottom Layer", { 0, Key_End }, [&](auto&) { layer_list_widget.select_bottom_layer(); }, window)); layer_menu.add_separator(); layer_menu.add_action(GUI::Action::create( - "Move active layer up", { Mod_Ctrl, Key_PageUp }, [&](auto&) { + "Move Active Layer &Up", { Mod_Ctrl, Key_PageUp }, [&](auto&) { auto active_layer = image_editor.active_layer(); if (!active_layer) return; @@ -281,7 +272,7 @@ int main(int argc, char** argv) }, window)); layer_menu.add_action(GUI::Action::create( - "Move active layer down", { Mod_Ctrl, Key_PageDown }, [&](auto&) { + "Move Active Layer &Down", { Mod_Ctrl, Key_PageDown }, [&](auto&) { auto active_layer = image_editor.active_layer(); if (!active_layer) return; @@ -290,7 +281,7 @@ int main(int argc, char** argv) window)); layer_menu.add_separator(); layer_menu.add_action(GUI::Action::create( - "Remove active layer", { Mod_Ctrl, Key_D }, [&](auto&) { + "&Remove Active Layer", { Mod_Ctrl, Key_D }, [&](auto&) { auto active_layer = image_editor.active_layer(); if (!active_layer) return; @@ -299,11 +290,11 @@ int main(int argc, char** argv) }, window)); - auto& filter_menu = menubar->add_menu("Filter"); - auto& spatial_filters_menu = filter_menu.add_submenu("Spatial"); + auto& filter_menu = menubar->add_menu("&Filter"); + auto& spatial_filters_menu = filter_menu.add_submenu("&Spatial"); - auto& edge_detect_submenu = spatial_filters_menu.add_submenu("Edge Detect"); - edge_detect_submenu.add_action(GUI::Action::create("Laplacian (cardinal)", [&](auto&) { + auto& edge_detect_submenu = spatial_filters_menu.add_submenu("&Edge Detect"); + edge_detect_submenu.add_action(GUI::Action::create("Laplacian (&Cardinal)", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::LaplacianFilter filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::LaplacianFilter>::get(false)) { @@ -312,7 +303,7 @@ int main(int argc, char** argv) } } })); - edge_detect_submenu.add_action(GUI::Action::create("Laplacian (diagonal)", [&](auto&) { + edge_detect_submenu.add_action(GUI::Action::create("Laplacian (&Diagonal)", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::LaplacianFilter filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::LaplacianFilter>::get(true)) { @@ -321,8 +312,8 @@ int main(int argc, char** argv) } } })); - auto& blur_submenu = spatial_filters_menu.add_submenu("Blur and Sharpen"); - blur_submenu.add_action(GUI::Action::create("Gaussian Blur (3x3)", [&](auto&) { + auto& blur_submenu = spatial_filters_menu.add_submenu("&Blur and Sharpen"); + blur_submenu.add_action(GUI::Action::create("&Gaussian Blur (3x3)", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::SpatialGaussianBlurFilter<3> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::SpatialGaussianBlurFilter<3>>::get()) { @@ -331,7 +322,7 @@ int main(int argc, char** argv) } } })); - blur_submenu.add_action(GUI::Action::create("Gaussian Blur (5x5)", [&](auto&) { + blur_submenu.add_action(GUI::Action::create("&Gaussian Blur (5x5)", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::SpatialGaussianBlurFilter<5> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::SpatialGaussianBlurFilter<5>>::get()) { @@ -340,7 +331,7 @@ int main(int argc, char** argv) } } })); - blur_submenu.add_action(GUI::Action::create("Box Blur (3x3)", [&](auto&) { + blur_submenu.add_action(GUI::Action::create("&Box Blur (3x3)", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::BoxBlurFilter<3> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::BoxBlurFilter<3>>::get()) { @@ -349,7 +340,7 @@ int main(int argc, char** argv) } } })); - blur_submenu.add_action(GUI::Action::create("Box Blur (5x5)", [&](auto&) { + blur_submenu.add_action(GUI::Action::create("&Box Blur (5x5)", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::BoxBlurFilter<5> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::BoxBlurFilter<5>>::get()) { @@ -358,7 +349,7 @@ int main(int argc, char** argv) } } })); - blur_submenu.add_action(GUI::Action::create("Sharpen", [&](auto&) { + blur_submenu.add_action(GUI::Action::create("&Sharpen", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::SharpenFilter filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::SharpenFilter>::get()) { @@ -369,7 +360,7 @@ int main(int argc, char** argv) })); spatial_filters_menu.add_separator(); - spatial_filters_menu.add_action(GUI::Action::create("Generic 5x5 Convolution", [&](auto&) { + spatial_filters_menu.add_action(GUI::Action::create("Generic 5x5 &Convolution", [&](auto&) { if (auto* layer = image_editor.active_layer()) { Gfx::GenericConvolutionFilter<5> filter; if (auto parameters = PixelPaint::FilterParameters<Gfx::GenericConvolutionFilter<5>>::get(window)) { @@ -379,7 +370,7 @@ int main(int argc, char** argv) } })); - auto& help_menu = menubar->add_menu("Help"); + auto& help_menu = menubar->add_menu("&Help"); help_menu.add_action(GUI::CommonActions::make_about_action("PixelPaint", app_icon, window)); window->set_menubar(move(menubar));
a221596614cde869d0b0ef1036c2a9e9ba48f0c5
2022-01-08 23:52:00
Daniel Bertalan
libc: Fix typo: fgetround => fegetround
false
Fix typo: fgetround => fegetround
libc
diff --git a/Userland/Libraries/LibC/float.h b/Userland/Libraries/LibC/float.h index 086f38a4056b..e3843499c3ba 100644 --- a/Userland/Libraries/LibC/float.h +++ b/Userland/Libraries/LibC/float.h @@ -8,7 +8,7 @@ #pragma once // Defined in fenv.cpp, but we must not include fenv.h, so here's its prototype. -int fgetround(); +int fegetround(); #define FLT_RADIX 2 #define DECIMAL_DIG 21
5e3972a9463c31214cecc5e30e4624ea51c276f1
2020-06-04 12:39:33
Kyle McLean
libweb: Parse "body" end tags during "in body"
false
Parse "body" end tags during "in body"
libweb
diff --git a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp index bfb39f9d5663..8d8732e96bdb 100644 --- a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp +++ b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp @@ -889,15 +889,16 @@ void HTMLDocumentParser::handle_in_body(HTMLToken& token) if (token.is_end_tag() && token.tag_name() == "body") { if (!m_stack_of_open_elements.has_in_scope("body")) { - TODO(); + PARSE_ERROR(); + return; } - // FIXME: Otherwise, if there is a node in the stack of open elements that is - // not either a dd element, a dt element, an li element, an optgroup element, - // an option element, a p element, an rb element, an rp element, an rt element, - // an rtc element, a tbody element, a td element, a tfoot element, a th element, - // a thead element, a tr element, the body element, or the html element, - // then this is a parse error. + for (auto& node : m_stack_of_open_elements.elements()) { + if (!node.tag_name().is_one_of("dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc", "tbody", "td", "tfoot", "th", "thead", "tr", "body", "html")) { + PARSE_ERROR(); + break; + } + } m_insertion_mode = InsertionMode::AfterBody; return;
3596522d23636c8de6fdf5c9286d61cbdb24db4d
2019-09-16 23:16:34
Andreas Kling
shell: Add a "time" builtin to show how long a command took to run
false
Add a "time" builtin to show how long a command took to run
shell
diff --git a/Shell/main.cpp b/Shell/main.cpp index 4abdc7316571..8c236416f6e4 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -25,6 +25,8 @@ GlobalState g; static LineEditor editor; +static int run_command(const String&); + static String prompt() { if (g.uid == 0) @@ -133,6 +135,25 @@ static int sh_history(int, char**) return 0; } +static int sh_time(int argc, char** argv) +{ + if (argc == 1) { + printf("usage: time <command>\n"); + return 0; + } + StringBuilder builder; + for (int i = 1; i < argc; ++i) { + builder.append(argv[i]); + if (i != argc - 1) + builder.append(' '); + } + CElapsedTimer timer; + timer.start(); + int exit_code = run_command(builder.to_string()); + printf("Time: %d ms\n", timer.elapsed()); + return exit_code; +} + static int sh_umask(int argc, char** argv) { if (argc == 1) { @@ -392,6 +413,10 @@ static bool handle_builtin(int argc, char** argv, int& retval) retval = sh_popd(argc, argv); return true; } + if (!strcmp(argv[0], "time")) { + retval = sh_time(argc, argv); + return true; + } return false; }
1ea236e4540ce7797ed5a1514c0bc9c77d82946e
2024-11-15 23:21:45
Andrew Kaster
ak: Skip test for StringView's CxxSequence conformance for now
false
Skip test for StringView's CxxSequence conformance for now
ak
diff --git a/Tests/AK/TestAKBindings.swift b/Tests/AK/TestAKBindings.swift index 37211c021d47..7a9b02d6bc32 100644 --- a/Tests/AK/TestAKBindings.swift +++ b/Tests/AK/TestAKBindings.swift @@ -26,7 +26,7 @@ struct TestAKBindings { var standardError = StandardError() print("Testing CxxSequence types...", to: &standardError) - precondition(isCxxSequenceType(AK.StringView.self)) + //precondition(isCxxSequenceType(AK.StringView.self)) precondition(isCxxSequenceType(AK.Bytes.self)) precondition(isCxxSequenceType(AK.ReadonlyBytes.self)) precondition(isCxxSequenceType(AK.Utf16Data.self))
57d8b0ec734ce9297a7f51b6f817ce51a8a9fff7
2023-09-06 06:06:09
Shannon Booth
libweb: Port HTMLButtonElement interface from DeprecatedString to String
false
Port HTMLButtonElement interface from DeprecatedString to String
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.cpp index c05dc80030a3..d60904637c23 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.cpp @@ -57,18 +57,18 @@ void HTMLButtonElement::initialize(JS::Realm& realm) set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLButtonElementPrototype>(realm, "HTMLButtonElement")); } -DeprecatedString HTMLButtonElement::type() const +StringView HTMLButtonElement::type() const { auto value = deprecated_attribute(HTML::AttributeNames::type); #define __ENUMERATE_HTML_BUTTON_TYPE_ATTRIBUTE(keyword, _) \ if (value.equals_ignoring_ascii_case(#keyword##sv)) \ - return #keyword; + return #keyword##sv; ENUMERATE_HTML_BUTTON_TYPE_ATTRIBUTES #undef __ENUMERATE_HTML_BUTTON_TYPE_ATTRIBUTE // The missing value default and invalid value default are the Submit Button state. - return "submit"; + return "submit"sv; } HTMLButtonElement::TypeAttributeState HTMLButtonElement::type_state() const @@ -85,7 +85,7 @@ HTMLButtonElement::TypeAttributeState HTMLButtonElement::type_state() const return HTMLButtonElement::TypeAttributeState::Submit; } -WebIDL::ExceptionOr<void> HTMLButtonElement::set_type(DeprecatedString const& type) +WebIDL::ExceptionOr<void> HTMLButtonElement::set_type(String const& type) { return set_attribute(HTML::AttributeNames::type, type); } diff --git a/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.h b/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.h index dc1182b05de0..028a94d72372 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.h +++ b/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.h @@ -34,9 +34,9 @@ class HTMLButtonElement final #undef __ENUMERATE_HTML_BUTTON_TYPE_ATTRIBUTE }; - DeprecatedString type() const; + StringView type() const; TypeAttributeState type_state() const; - WebIDL::ExceptionOr<void> set_type(DeprecatedString const&); + WebIDL::ExceptionOr<void> set_type(String const&); // ^EventTarget // https://html.spec.whatwg.org/multipage/interaction.html#the-tabindex-attribute:the-button-element diff --git a/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.idl b/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.idl index 952deaa44257..6e58725ed65a 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.idl +++ b/Userland/Libraries/LibWeb/HTML/HTMLButtonElement.idl @@ -1,7 +1,7 @@ #import <HTML/HTMLElement.idl> // https://html.spec.whatwg.org/multipage/semantics.html#htmlbuttonelement -[Exposed=Window, UseDeprecatedAKString] +[Exposed=Window] interface HTMLButtonElement : HTMLElement { [HTMLConstructor] constructor();
cf5ce8277f22b083089288bdc7179d8130b6674a
2025-01-27 16:54:48
devgianlu
libcrypto: Use OpenSSL for SECPxxxr1 sign/verify operations
false
Use OpenSSL for SECPxxxr1 sign/verify operations
libcrypto
diff --git a/Libraries/LibCrypto/Curves/SECPxxxr1.h b/Libraries/LibCrypto/Curves/SECPxxxr1.h index 8e3b85c44fb9..27b073e33e08 100644 --- a/Libraries/LibCrypto/Curves/SECPxxxr1.h +++ b/Libraries/LibCrypto/Curves/SECPxxxr1.h @@ -21,8 +21,9 @@ #include <LibCrypto/OpenSSL.h> #include <openssl/core_names.h> -#include <openssl/evp.h> #include <openssl/ec.h> +#include <openssl/evp.h> +#include <openssl/param_build.h> namespace { // Used by ASN1 macros @@ -365,72 +366,57 @@ class SECPxxxr1 : public EllipticCurve { ErrorOr<bool> verify_point(ReadonlyBytes hash, SECPxxxr1Point pubkey, SECPxxxr1Signature signature) { - static constexpr size_t expected_word_count = KEY_BIT_SIZE / 32; - if (signature.r.length() < expected_word_count || signature.s.length() < expected_word_count) { - return false; - } + auto ctx_import = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr))); - auto r = unsigned_big_integer_to_storage_type(signature.r); - auto s = unsigned_big_integer_to_storage_type(signature.s); - if (r.is_zero_constant_time() || s.is_zero_constant_time()) - return false; + OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx_import.ptr())); - // z is the hash - StorageType z = 0u; - for (size_t i = 0; i < KEY_BYTE_SIZE && i < hash.size(); i++) { - z <<= 8; - z |= hash[i]; - } + auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new()); + ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); }; - StorageType r_mo = to_montgomery_order(r); - StorageType s_mo = to_montgomery_order(s); - StorageType z_mo = to_montgomery_order(z); + OPENSSL_TRY(OSSL_PARAM_BLD_push_utf8_string(params_bld, OSSL_PKEY_PARAM_GROUP_NAME, CURVE_PARAMETERS.name, strlen(CURVE_PARAMETERS.name))); - StorageType s_inv = modular_inverse_order(s_mo); + auto pubkey_bytes = TRY(pubkey.to_uncompressed()); + OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_PUB_KEY, pubkey_bytes.data(), pubkey_bytes.size())); - StorageType u1 = modular_multiply_order(z_mo, s_inv); - StorageType u2 = modular_multiply_order(r_mo, s_inv); + auto* params = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_to_param(params_bld)); + ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); }; - u1 = from_montgomery_order(u1); - u2 = from_montgomery_order(u2); + auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new())); + auto* key_ptr = key.ptr(); + OPENSSL_TRY(EVP_PKEY_fromdata(ctx_import.ptr(), &key_ptr, EVP_PKEY_PUBLIC_KEY, params)); - JacobianPoint point1 = TRY(generate_public_key_internal(u1)); - JacobianPoint point2 = TRY(compute_coordinate_internal(u2, JacobianPoint { - unsigned_big_integer_to_storage_type(pubkey.x), - unsigned_big_integer_to_storage_type(pubkey.y), - 1u, - })); + auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.ptr(), nullptr))); - // Convert the input point into Montgomery form - point1.x = to_montgomery(point1.x); - point1.y = to_montgomery(point1.y); - point1.z = to_montgomery(point1.z); + OPENSSL_TRY(EVP_PKEY_verify_init(ctx.ptr())); - VERIFY(is_point_on_curve(point1)); + auto* sig_obj = OPENSSL_TRY_PTR(ECDSA_SIG_new()); + ScopeGuard const free_sig_obj = [&] { ECDSA_SIG_free(sig_obj); }; - // Convert the input point into Montgomery form - point2.x = to_montgomery(point2.x); - point2.y = to_montgomery(point2.y); - point2.z = to_montgomery(point2.z); + auto r = TRY(unsigned_big_integer_to_openssl_bignum(signature.r)); + auto s = TRY(unsigned_big_integer_to_openssl_bignum(signature.s)); - VERIFY(is_point_on_curve(point2)); + // Let sig_obj own a copy of r and s + OPENSSL_TRY(ECDSA_SIG_set0(sig_obj, BN_dup(r.ptr()), BN_dup(s.ptr()))); - JacobianPoint result = point_add(point1, point2); + u8* sig = nullptr; + ScopeGuard const free_sig = [&] { OPENSSL_free(sig); }; - // Convert from Jacobian coordinates back to Affine coordinates - convert_jacobian_to_affine(result); - - // Make sure the resulting point is on the curve - VERIFY(is_point_on_curve(result)); - - // Convert the result back from Montgomery form - result.x = from_montgomery(result.x); - result.y = from_montgomery(result.y); - // Final modular reduction on the coordinates - result.x = modular_reduce(result.x); - result.y = modular_reduce(result.y); + auto sig_len = TRY([&] -> ErrorOr<int> { + auto ret = i2d_ECDSA_SIG(sig_obj, &sig); + if (ret <= 0) { + OPENSSL_TRY(ret); + VERIFY_NOT_REACHED(); + } + return ret; + }()); - return r.is_equal_to_constant_time(result.x); + auto ret = EVP_PKEY_verify(ctx.ptr(), sig, sig_len, hash.data(), hash.size()); + if (ret == 1) + return true; + if (ret == 0) + return false; + OPENSSL_TRY(ret); + VERIFY_NOT_REACHED(); } ErrorOr<bool> verify(ReadonlyBytes hash, ReadonlyBytes pubkey, SECPxxxr1Signature signature) @@ -441,51 +427,48 @@ class SECPxxxr1 : public EllipticCurve { ErrorOr<SECPxxxr1Signature> sign_scalar(ReadonlyBytes hash, UnsignedBigInteger private_key) { - auto d = unsigned_big_integer_to_storage_type(private_key); + auto ctx_import = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr))); - auto k_int = TRY(generate_private_key_scalar()); - auto k = unsigned_big_integer_to_storage_type(k_int); - auto k_mo = to_montgomery_order(k); + OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx_import.ptr())); - auto kG = TRY(generate_public_key_internal(k)); - auto r = kG.x; + auto d = TRY(unsigned_big_integer_to_openssl_bignum(private_key)); - if (r.is_zero_constant_time()) { - // Retry with a new k - return sign_scalar(hash, private_key); - } + auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new()); + ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); }; - // Compute z from the hash - StorageType z = 0u; - for (size_t i = 0; i < KEY_BYTE_SIZE && i < hash.size(); i++) { - z <<= 8; - z |= hash[i]; - } + OPENSSL_TRY(OSSL_PARAM_BLD_push_utf8_string(params_bld, OSSL_PKEY_PARAM_GROUP_NAME, CURVE_PARAMETERS.name, strlen(CURVE_PARAMETERS.name))); + OPENSSL_TRY(OSSL_PARAM_BLD_push_BN(params_bld, OSSL_PKEY_PARAM_PRIV_KEY, d.ptr())); - // s = k^-1 * (z + r * d) mod n - auto r_mo = to_montgomery_order(r); - auto z_mo = to_montgomery_order(z); - auto d_mo = to_montgomery_order(d); + auto* params = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_to_param(params_bld)); + ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); }; - // r * d mod n - auto rd_mo = modular_multiply_order(r_mo, d_mo); + auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new())); + auto* key_ptr = key.ptr(); + OPENSSL_TRY(EVP_PKEY_fromdata(ctx_import.ptr(), &key_ptr, EVP_PKEY_KEYPAIR, params)); - // z + (r * d) mod n - auto z_plus_rd_mo = modular_add_order(z_mo, rd_mo); + auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.ptr(), nullptr))); - // k^-1 mod n - auto k_inv_mo = modular_inverse_order(k_mo); + OPENSSL_TRY(EVP_PKEY_sign_init(ctx.ptr())); - // s = k^-1 * (z + r * d) mod n - auto s_mo = modular_multiply_order(z_plus_rd_mo, k_inv_mo); - auto s = from_montgomery_order(s_mo); + size_t sig_len = 0; + OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), nullptr, &sig_len, hash.data(), hash.size())); - if (s.is_zero_constant_time()) { - // Retry with a new k - return sign_scalar(hash, private_key); - } + auto sig = TRY(ByteBuffer::create_uninitialized(sig_len)); + OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), sig.data(), &sig_len, hash.data(), hash.size())); + + auto const* sig_data = sig.data(); + auto* sig_obj = OPENSSL_TRY_PTR(d2i_ECDSA_SIG(nullptr, &sig_data, sig.size())); + ScopeGuard const free_sig_obj = [&] { ECDSA_SIG_free(sig_obj); }; - return SECPxxxr1Signature { storage_type_to_unsigned_big_integer(r), storage_type_to_unsigned_big_integer(s), KEY_BYTE_SIZE }; + // Duplicate r and s so that sig_obj can own them + auto r = TRY(OpenSSL_BN::wrap(BN_dup(OPENSSL_TRY_PTR(ECDSA_SIG_get0_r(sig_obj))))); + auto s = TRY(OpenSSL_BN::wrap(BN_dup(OPENSSL_TRY_PTR(ECDSA_SIG_get0_s(sig_obj))))); + + return SECPxxxr1Signature { + TRY(openssl_bignum_to_unsigned_big_integer(r)), + TRY(openssl_bignum_to_unsigned_big_integer(s)), + KEY_BYTE_SIZE, + }; } ErrorOr<SECPxxxr1Signature> sign(ReadonlyBytes hash, ReadonlyBytes private_key_bytes) diff --git a/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt index 9461ed38b459..830cd022e438 100644 --- a/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt +++ b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/sign_verify/ecdsa.https.any.txt @@ -2,8 +2,7 @@ Harness status: OK Found 253 tests -205 Pass -48 Fail +253 Pass Pass setup Pass ECDSA P-256 with SHA-1 verification Pass ECDSA P-256 with SHA-256 verification @@ -13,10 +12,10 @@ Pass ECDSA P-384 with SHA-1 verification Pass ECDSA P-384 with SHA-256 verification Pass ECDSA P-384 with SHA-384 verification Pass ECDSA P-384 with SHA-512 verification -Fail ECDSA P-521 with SHA-1 verification -Fail ECDSA P-521 with SHA-256 verification -Fail ECDSA P-521 with SHA-384 verification -Fail ECDSA P-521 with SHA-512 verification +Pass ECDSA P-521 with SHA-1 verification +Pass ECDSA P-521 with SHA-256 verification +Pass ECDSA P-521 with SHA-384 verification +Pass ECDSA P-521 with SHA-512 verification Pass ECDSA P-256 with SHA-1 verification with altered signature after call Pass ECDSA P-256 with SHA-256 verification with altered signature after call Pass ECDSA P-256 with SHA-384 verification with altered signature after call @@ -25,10 +24,10 @@ Pass ECDSA P-384 with SHA-1 verification with altered signature after call Pass ECDSA P-384 with SHA-256 verification with altered signature after call Pass ECDSA P-384 with SHA-384 verification with altered signature after call Pass ECDSA P-384 with SHA-512 verification with altered signature after call -Fail ECDSA P-521 with SHA-1 verification with altered signature after call -Fail ECDSA P-521 with SHA-256 verification with altered signature after call -Fail ECDSA P-521 with SHA-384 verification with altered signature after call -Fail ECDSA P-521 with SHA-512 verification with altered signature after call +Pass ECDSA P-521 with SHA-1 verification with altered signature after call +Pass ECDSA P-521 with SHA-256 verification with altered signature after call +Pass ECDSA P-521 with SHA-384 verification with altered signature after call +Pass ECDSA P-521 with SHA-512 verification with altered signature after call Pass ECDSA P-256 with SHA-1 with altered plaintext after call Pass ECDSA P-256 with SHA-256 with altered plaintext after call Pass ECDSA P-256 with SHA-384 with altered plaintext after call @@ -37,10 +36,10 @@ Pass ECDSA P-384 with SHA-1 with altered plaintext after call Pass ECDSA P-384 with SHA-256 with altered plaintext after call Pass ECDSA P-384 with SHA-384 with altered plaintext after call Pass ECDSA P-384 with SHA-512 with altered plaintext after call -Fail ECDSA P-521 with SHA-1 with altered plaintext after call -Fail ECDSA P-521 with SHA-256 with altered plaintext after call -Fail ECDSA P-521 with SHA-384 with altered plaintext after call -Fail ECDSA P-521 with SHA-512 with altered plaintext after call +Pass ECDSA P-521 with SHA-1 with altered plaintext after call +Pass ECDSA P-521 with SHA-256 with altered plaintext after call +Pass ECDSA P-521 with SHA-384 with altered plaintext after call +Pass ECDSA P-521 with SHA-512 with altered plaintext after call Pass ECDSA P-256 with SHA-1 using privateKey to verify Pass ECDSA P-256 with SHA-256 using privateKey to verify Pass ECDSA P-256 with SHA-384 using privateKey to verify @@ -85,10 +84,10 @@ Pass ECDSA P-384 with SHA-1 round trip Pass ECDSA P-384 with SHA-256 round trip Pass ECDSA P-384 with SHA-384 round trip Pass ECDSA P-384 with SHA-512 round trip -Fail ECDSA P-521 with SHA-1 round trip -Fail ECDSA P-521 with SHA-256 round trip -Fail ECDSA P-521 with SHA-384 round trip -Fail ECDSA P-521 with SHA-512 round trip +Pass ECDSA P-521 with SHA-1 round trip +Pass ECDSA P-521 with SHA-256 round trip +Pass ECDSA P-521 with SHA-384 round trip +Pass ECDSA P-521 with SHA-512 round trip Pass ECDSA P-256 with SHA-1 signing with wrong algorithm name Pass ECDSA P-256 with SHA-256 signing with wrong algorithm name Pass ECDSA P-256 with SHA-384 signing with wrong algorithm name @@ -121,10 +120,10 @@ Pass ECDSA P-384 with SHA-1 verification failure due to altered signature Pass ECDSA P-384 with SHA-256 verification failure due to altered signature Pass ECDSA P-384 with SHA-384 verification failure due to altered signature Pass ECDSA P-384 with SHA-512 verification failure due to altered signature -Fail ECDSA P-521 with SHA-1 verification failure due to altered signature -Fail ECDSA P-521 with SHA-256 verification failure due to altered signature -Fail ECDSA P-521 with SHA-384 verification failure due to altered signature -Fail ECDSA P-521 with SHA-512 verification failure due to altered signature +Pass ECDSA P-521 with SHA-1 verification failure due to altered signature +Pass ECDSA P-521 with SHA-256 verification failure due to altered signature +Pass ECDSA P-521 with SHA-384 verification failure due to altered signature +Pass ECDSA P-521 with SHA-512 verification failure due to altered signature Pass ECDSA P-256 with SHA-1 verification failure due to wrong hash Pass ECDSA P-256 with SHA-256 verification failure due to wrong hash Pass ECDSA P-256 with SHA-384 verification failure due to wrong hash @@ -133,10 +132,10 @@ Pass ECDSA P-384 with SHA-1 verification failure due to wrong hash Pass ECDSA P-384 with SHA-256 verification failure due to wrong hash Pass ECDSA P-384 with SHA-384 verification failure due to wrong hash Pass ECDSA P-384 with SHA-512 verification failure due to wrong hash -Fail ECDSA P-521 with SHA-1 verification failure due to wrong hash -Fail ECDSA P-521 with SHA-256 verification failure due to wrong hash -Fail ECDSA P-521 with SHA-384 verification failure due to wrong hash -Fail ECDSA P-521 with SHA-512 verification failure due to wrong hash +Pass ECDSA P-521 with SHA-1 verification failure due to wrong hash +Pass ECDSA P-521 with SHA-256 verification failure due to wrong hash +Pass ECDSA P-521 with SHA-384 verification failure due to wrong hash +Pass ECDSA P-521 with SHA-512 verification failure due to wrong hash Pass ECDSA P-256 with SHA-1 verification failure due to bad hash name Pass ECDSA P-256 with SHA-256 verification failure due to bad hash name Pass ECDSA P-256 with SHA-384 verification failure due to bad hash name @@ -157,10 +156,10 @@ Pass ECDSA P-384 with SHA-1 verification failure due to shortened signature Pass ECDSA P-384 with SHA-256 verification failure due to shortened signature Pass ECDSA P-384 with SHA-384 verification failure due to shortened signature Pass ECDSA P-384 with SHA-512 verification failure due to shortened signature -Fail ECDSA P-521 with SHA-1 verification failure due to shortened signature -Fail ECDSA P-521 with SHA-256 verification failure due to shortened signature -Fail ECDSA P-521 with SHA-384 verification failure due to shortened signature -Fail ECDSA P-521 with SHA-512 verification failure due to shortened signature +Pass ECDSA P-521 with SHA-1 verification failure due to shortened signature +Pass ECDSA P-521 with SHA-256 verification failure due to shortened signature +Pass ECDSA P-521 with SHA-384 verification failure due to shortened signature +Pass ECDSA P-521 with SHA-512 verification failure due to shortened signature Pass ECDSA P-256 with SHA-1 verification failure due to altered plaintext Pass ECDSA P-256 with SHA-256 verification failure due to altered plaintext Pass ECDSA P-256 with SHA-384 verification failure due to altered plaintext @@ -169,10 +168,10 @@ Pass ECDSA P-384 with SHA-1 verification failure due to altered plaintext Pass ECDSA P-384 with SHA-256 verification failure due to altered plaintext Pass ECDSA P-384 with SHA-384 verification failure due to altered plaintext Pass ECDSA P-384 with SHA-512 verification failure due to altered plaintext -Fail ECDSA P-521 with SHA-1 verification failure due to altered plaintext -Fail ECDSA P-521 with SHA-256 verification failure due to altered plaintext -Fail ECDSA P-521 with SHA-384 verification failure due to altered plaintext -Fail ECDSA P-521 with SHA-512 verification failure due to altered plaintext +Pass ECDSA P-521 with SHA-1 verification failure due to altered plaintext +Pass ECDSA P-521 with SHA-256 verification failure due to altered plaintext +Pass ECDSA P-521 with SHA-384 verification failure due to altered plaintext +Pass ECDSA P-521 with SHA-512 verification failure due to altered plaintext Pass ECDSA P-256 with SHA-1 - The signature was truncated by 1 byte verification Pass ECDSA P-256 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-256 verification Pass ECDSA P-256 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-384 verification @@ -229,31 +228,31 @@ Pass ECDSA P-384 with SHA-512 - The signature was made using SHA-512, however ve Pass ECDSA P-384 with SHA-512 - Signature has excess padding verification Pass ECDSA P-384 with SHA-512 - The signature is empty verification Pass ECDSA P-384 with SHA-512 - The signature is all zeroes verification -Fail ECDSA P-521 with SHA-1 - The signature was truncated by 1 byte verification -Fail ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-256 verification -Fail ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-384 verification -Fail ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-512 verification +Pass ECDSA P-521 with SHA-1 - The signature was truncated by 1 byte verification +Pass ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-256 verification +Pass ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-384 verification +Pass ECDSA P-521 with SHA-1 - The signature was made using SHA-1, however verification is being done using SHA-512 verification Pass ECDSA P-521 with SHA-1 - Signature has excess padding verification Pass ECDSA P-521 with SHA-1 - The signature is empty verification Pass ECDSA P-521 with SHA-1 - The signature is all zeroes verification -Fail ECDSA P-521 with SHA-256 - The signature was truncated by 1 byte verification -Fail ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-1 verification -Fail ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-384 verification -Fail ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-512 verification +Pass ECDSA P-521 with SHA-256 - The signature was truncated by 1 byte verification +Pass ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-1 verification +Pass ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-384 verification +Pass ECDSA P-521 with SHA-256 - The signature was made using SHA-256, however verification is being done using SHA-512 verification Pass ECDSA P-521 with SHA-256 - Signature has excess padding verification Pass ECDSA P-521 with SHA-256 - The signature is empty verification Pass ECDSA P-521 with SHA-256 - The signature is all zeroes verification -Fail ECDSA P-521 with SHA-384 - The signature was truncated by 1 byte verification -Fail ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-1 verification -Fail ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-256 verification -Fail ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-512 verification +Pass ECDSA P-521 with SHA-384 - The signature was truncated by 1 byte verification +Pass ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-1 verification +Pass ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-256 verification +Pass ECDSA P-521 with SHA-384 - The signature was made using SHA-384, however verification is being done using SHA-512 verification Pass ECDSA P-521 with SHA-384 - Signature has excess padding verification Pass ECDSA P-521 with SHA-384 - The signature is empty verification Pass ECDSA P-521 with SHA-384 - The signature is all zeroes verification -Fail ECDSA P-521 with SHA-512 - The signature was truncated by 1 byte verification -Fail ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-1 verification -Fail ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-256 verification -Fail ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-384 verification +Pass ECDSA P-521 with SHA-512 - The signature was truncated by 1 byte verification +Pass ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-1 verification +Pass ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-256 verification +Pass ECDSA P-521 with SHA-512 - The signature was made using SHA-512, however verification is being done using SHA-384 verification Pass ECDSA P-521 with SHA-512 - Signature has excess padding verification Pass ECDSA P-521 with SHA-512 - The signature is empty verification Pass ECDSA P-521 with SHA-512 - The signature is all zeroes verification \ No newline at end of file
8a6f7b787e6ee0202624475c671ece85c8435709
2025-02-25 04:39:20
mikiubo
libregex: Use depth-first search in regex optimizer
false
Use depth-first search in regex optimizer
libregex
diff --git a/Libraries/LibRegex/RegexOptimizer.cpp b/Libraries/LibRegex/RegexOptimizer.cpp index 2294ed335686..28d7cf438571 100644 --- a/Libraries/LibRegex/RegexOptimizer.cpp +++ b/Libraries/LibRegex/RegexOptimizer.cpp @@ -6,11 +6,11 @@ #include <AK/Debug.h> #include <AK/Function.h> -#include <AK/Queue.h> #include <AK/QuickSort.h> #include <AK/RedBlackTree.h> #include <AK/Stack.h> #include <AK/Trie.h> +#include <AK/Vector.h> #include <LibRegex/Regex.h> #include <LibRegex/RegexBytecodeStreamOptimizer.h> #include <LibUnicode/CharacterTypes.h> @@ -1176,8 +1176,8 @@ void Optimizer::append_alternation(ByteCode& target, Span<ByteCode> alternatives patch_locations.append({ node_ip, target_ip }); }; - Queue<Tree*> nodes_to_visit; - nodes_to_visit.enqueue(&trie); + Vector<Tree*> nodes_to_visit; + nodes_to_visit.append(&trie); HashMap<size_t, NonnullOwnPtr<RedBlackTree<u64, u64>>> instruction_positions; if (has_any_backwards_jump) @@ -1195,7 +1195,7 @@ void Optimizer::append_alternation(ByteCode& target, Span<ByteCode> alternatives // forkjump child2 // ... while (!nodes_to_visit.is_empty()) { - auto const* node = nodes_to_visit.dequeue(); + auto const* node = nodes_to_visit.take_last(); for (auto& patch : patch_locations) { if (!patch.done && node_is(node, patch.source_ip)) { auto value = static_cast<ByteCodeValueType>(target.size() - patch.target_ip - 1); @@ -1291,7 +1291,7 @@ void Optimizer::append_alternation(ByteCode& target, Span<ByteCode> alternatives target.append(static_cast<ByteCodeValueType>(OpCodeId::ForkJump)); add_patch_point(child_node, target.size()); target.append(static_cast<ByteCodeValueType>(0)); - nodes_to_visit.enqueue(child_node); + nodes_to_visit.append(child_node); } } diff --git a/Tests/LibRegex/Regex.cpp b/Tests/LibRegex/Regex.cpp index 148656b9a989..a5faf6b2dcb9 100644 --- a/Tests/LibRegex/Regex.cpp +++ b/Tests/LibRegex/Regex.cpp @@ -716,6 +716,7 @@ TEST_CASE(ECMA262_match) ""sv, false, }, // See above, also ladybird#2931. { "[^]*[^]"sv, "i"sv, true }, // Optimizer bug, ignoring an enabled trailing 'invert' when comparing blocks, ladybird#3421. + { "xx|...|...."sv, "cd"sv, false }, }; // clang-format on
75260bff92fa75033c92cf09d0ab6cf55b515c85
2021-08-07 15:18:00
Jean-Baptiste Boric
kernel: Introduce ProtectedValue
false
Introduce ProtectedValue
kernel
diff --git a/Kernel/Locking/ProtectedValue.h b/Kernel/Locking/ProtectedValue.h new file mode 100644 index 000000000000..676f932473fb --- /dev/null +++ b/Kernel/Locking/ProtectedValue.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021, the SerenityOS developers. + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <Kernel/Locking/ContendedResource.h> + +namespace Kernel { + +template<typename T> +class ProtectedValue : private T + , public ContendedResource { + AK_MAKE_NONCOPYABLE(ProtectedValue); + AK_MAKE_NONMOVABLE(ProtectedValue); + +protected: + using LockedShared = LockedResource<T const, LockMode::Shared>; + using LockedExclusive = LockedResource<T, LockMode::Exclusive>; + + LockedShared lock_shared() const { return LockedShared(this, this->ContendedResource::m_mutex); } + LockedExclusive lock_exclusive() { return LockedExclusive(this, this->ContendedResource::m_mutex); } + +public: + using T::T; + + ProtectedValue() = default; + + template<typename Callback> + decltype(auto) with_shared(Callback callback) const + { + auto lock = lock_shared(); + return callback(*lock); + } + + template<typename Callback> + decltype(auto) with_exclusive(Callback callback) + { + auto lock = lock_exclusive(); + return callback(*lock); + } + + template<typename Callback> + void for_each_shared(Callback callback) const + { + with_shared([&](const auto& value) { + for (auto& item : value) + callback(item); + }); + } + + template<typename Callback> + void for_each_exclusive(Callback callback) + { + with_exclusive([&](auto& value) { + for (auto& item : value) + callback(item); + }); + } +}; + +}
7bc7e2a48fbee7d4decda5567dd949feb376207c
2024-01-24 02:37:06
Andrew Kaster
libweb: Convert SubtleCrypto::digest to use WebIDL Promises
false
Convert SubtleCrypto::digest to use WebIDL Promises
libweb
diff --git a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp index ff04be187134..193a390a5a5c 100644 --- a/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp +++ b/Userland/Libraries/LibWeb/Crypto/SubtleCrypto.cpp @@ -8,11 +8,15 @@ #include <LibCrypto/Hash/HashManager.h> #include <LibJS/Runtime/ArrayBuffer.h> #include <LibJS/Runtime/Promise.h> +#include <LibWeb/Bindings/ExceptionOrUtils.h> #include <LibWeb/Bindings/Intrinsics.h> #include <LibWeb/Crypto/SubtleCrypto.h> +#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h> +#include <LibWeb/Platform/EventLoopPlugin.h> #include <LibWeb/WebIDL/AbstractOperations.h> #include <LibWeb/WebIDL/Buffers.h> #include <LibWeb/WebIDL/ExceptionOr.h> +#include <LibWeb/WebIDL/Promise.h> namespace Web::Crypto { @@ -119,69 +123,65 @@ JS::NonnullGCPtr<JS::Promise> SubtleCrypto::digest(AlgorithmIdentifier const& al // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the digest() method. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*data->raw_object()); if (data_buffer_or_error.is_error()) { - auto error = WebIDL::OperationError::create(realm, "Failed to copy bytes from ArrayBuffer"_fly_string); - auto promise = JS::Promise::create(realm); - promise->reject(error.ptr()); - return promise; + auto promise = WebIDL::create_rejected_promise(realm, WebIDL::OperationError::create(realm, "Failed to copy bytes from ArrayBuffer"_fly_string)); + return verify_cast<JS::Promise>(*promise->promise()); } - auto& data_buffer = data_buffer_or_error.value(); + auto data_buffer = data_buffer_or_error.release_value(); // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "digest". auto normalized_algorithm = normalize_an_algorithm(algorithm, "digest"_string); // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm. + // FIXME: Spec bug: link to https://webidl.spec.whatwg.org/#a-promise-rejected-with if (normalized_algorithm.is_error()) { - auto promise = JS::Promise::create(realm); - auto error = normalized_algorithm.release_error(); - auto error_value = error.value().value(); - promise->reject(error_value); - return promise; + auto promise = WebIDL::create_rejected_promise(realm, normalized_algorithm.release_error().release_value().value()); + return verify_cast<JS::Promise>(*promise->promise()); } // 5. Let promise be a new Promise. - auto promise = JS::Promise::create(realm); + auto promise = WebIDL::create_promise(realm); // 6. Return promise and perform the remaining steps in parallel. - // FIXME: We don't have a good abstraction for this yet, so we do it in sync. - - // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm. - - // 8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message. - auto algorithm_object = normalized_algorithm.release_value(); - auto algorithm_name = algorithm_object.name; - - ::Crypto::Hash::HashKind hash_kind; - if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) { - hash_kind = ::Crypto::Hash::HashKind::SHA1; - } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) { - hash_kind = ::Crypto::Hash::HashKind::SHA256; - } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) { - hash_kind = ::Crypto::Hash::HashKind::SHA384; - } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) { - hash_kind = ::Crypto::Hash::HashKind::SHA512; - } else { - auto error = WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name))); - promise->reject(error.ptr()); - return promise; - } - - ::Crypto::Hash::Manager hash { hash_kind }; - hash.update(data_buffer); - - auto digest = hash.digest(); - auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size()); - if (result_buffer.is_error()) { - auto error = WebIDL::OperationError::create(realm, "Failed to create result buffer"_fly_string); - promise->reject(error.ptr()); - return promise; - } - - auto result = JS::ArrayBuffer::create(realm, result_buffer.release_value()); - - // 9. Resolve promise with result. - promise->fulfill(result); - - return promise; + Platform::EventLoopPlugin::the().deferred_invoke([&realm, algorithm_object = normalized_algorithm.release_value(), promise, data_buffer = move(data_buffer)]() -> void { + HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes); + + // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm. + // FIXME: Need spec reference to https://webidl.spec.whatwg.org/#reject + + // 8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message. + auto algorithm_name = algorithm_object.name; + + ::Crypto::Hash::HashKind hash_kind; + if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) { + hash_kind = ::Crypto::Hash::HashKind::SHA1; + } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) { + hash_kind = ::Crypto::Hash::HashKind::SHA256; + } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) { + hash_kind = ::Crypto::Hash::HashKind::SHA384; + } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) { + hash_kind = ::Crypto::Hash::HashKind::SHA512; + } else { + WebIDL::reject_promise(realm, promise, WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)))); + return; + } + + ::Crypto::Hash::Manager hash { hash_kind }; + hash.update(data_buffer); + + auto digest = hash.digest(); + auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size()); + if (result_buffer.is_error()) { + WebIDL::reject_promise(realm, promise, WebIDL::OperationError::create(realm, "Failed to create result buffer"_fly_string)); + return; + } + + auto result = JS::ArrayBuffer::create(realm, result_buffer.release_value()); + + // 9. Resolve promise with result. + WebIDL::resolve_promise(realm, promise, result); + }); + + return verify_cast<JS::Promise>(*promise->promise()); } SubtleCrypto::SupportedAlgorithmsMap& SubtleCrypto::supported_algorithms_internal()
5aa803f7f2d938bdabdceb387e49a37510a2ca3b
2022-02-07 19:09:29
electrikmilk
base: Use GML file type icon
false
Use GML file type icon
base
diff --git a/Base/etc/FileIconProvider.ini b/Base/etc/FileIconProvider.ini index f7c91fe53a7d..21eb6df866db 100644 --- a/Base/etc/FileIconProvider.ini +++ b/Base/etc/FileIconProvider.ini @@ -12,6 +12,7 @@ library=*.so,*.so.*,*.a markdown=*.md music=*.midi object=*.o,*.obj +gml=*.gml palette=*.palette pdf=*.pdf python=*.py
c884aa3f25e6492b8931e2eb5d45b25a55b49e12
2022-11-26 03:19:59
Andreas Kling
base: Add a test for [SameObject] behavior in LibWeb
false
Add a test for [SameObject] behavior in LibWeb
base
diff --git a/Base/res/html/tests/sameobject-behavior-for-htmlcollection-properties.html b/Base/res/html/tests/sameobject-behavior-for-htmlcollection-properties.html new file mode 100644 index 000000000000..aa3b923ef677 --- /dev/null +++ b/Base/res/html/tests/sameobject-behavior-for-htmlcollection-properties.html @@ -0,0 +1,52 @@ +<html> +<style> +.ball { + border-radius: 9999px; + width: 40px; + height: 40px; + display: inline-block; +} +.pass { + background: green; +} +.fail { + background: red; +} +</style> +<p>This test verifies that various HTMLCollection properties have <b>[SameObject]</b> behavior.</p> +<p>You should see a bunch of green balls below this line.</p> + <div id="out"></div> + <form><table><thead><tr><td></td></tr></thead></table></form> + +<script> + let out = document.querySelector("#out") + + function test(expr) { + let a = eval(expr) + let b = eval(expr) + let e = document.createElement("div") + e.className = "ball " + ((a === b) ? "pass" : "fail") + out.appendChild(e) + } + + let table = document.querySelector("table") + let tr = document.querySelector("tr") + let form = document.querySelector("form") + let thead = document.querySelector("thead") + + test("table.tBodies") + test("table.rows") + test("thead.rows") + test("tr.cells") + test("form.elements") + + test("document.applets") + test("document.anchors") + test("document.images") + test("document.embeds") + test("document.plugins") + test("document.links") + test("document.forms") + test("document.scripts") +</script> +</html>
86a4d0694f86b81f0e71b44747f6b282809195fa
2021-07-08 17:15:55
pancake
filemanager: Add Open in Terminal on folder context menu
false
Add Open in Terminal on folder context menu
filemanager
diff --git a/Userland/Applications/FileManager/DirectoryView.cpp b/Userland/Applications/FileManager/DirectoryView.cpp index 763dbdb56f41..361bc99a611e 100644 --- a/Userland/Applications/FileManager/DirectoryView.cpp +++ b/Userland/Applications/FileManager/DirectoryView.cpp @@ -26,6 +26,23 @@ namespace FileManager { +void spawn_terminal(String const& directory) +{ + posix_spawn_file_actions_t spawn_actions; + posix_spawn_file_actions_init(&spawn_actions); + posix_spawn_file_actions_addchdir(&spawn_actions, directory.characters()); + + pid_t pid; + const char* argv[] = { "Terminal", nullptr }; + if ((errno = posix_spawn(&pid, "/bin/Terminal", &spawn_actions, nullptr, const_cast<char**>(argv), environ))) { + perror("posix_spawn"); + } else { + if (disown(pid) < 0) + perror("disown"); + } + posix_spawn_file_actions_destroy(&spawn_actions); +} + enum class FileOperation { Copy, }; @@ -570,18 +587,7 @@ void DirectoryView::setup_actions() }); m_open_terminal_action = GUI::Action::create("Open &Terminal Here", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"), [&](auto&) { - posix_spawn_file_actions_t spawn_actions; - posix_spawn_file_actions_init(&spawn_actions); - posix_spawn_file_actions_addchdir(&spawn_actions, path().characters()); - pid_t pid; - const char* argv[] = { "Terminal", nullptr }; - if ((errno = posix_spawn(&pid, "/bin/Terminal", &spawn_actions, nullptr, const_cast<char**>(argv), environ))) { - perror("posix_spawn"); - } else { - if (disown(pid) < 0) - perror("disown"); - } - posix_spawn_file_actions_destroy(&spawn_actions); + spawn_terminal(path()); }); m_delete_action = GUI::CommonActions::make_delete_action([this](auto&) { do_delete(true); }, window()); diff --git a/Userland/Applications/FileManager/DirectoryView.h b/Userland/Applications/FileManager/DirectoryView.h index c93b870ddf16..3dec5bdabcb6 100644 --- a/Userland/Applications/FileManager/DirectoryView.h +++ b/Userland/Applications/FileManager/DirectoryView.h @@ -20,6 +20,8 @@ namespace FileManager { +void spawn_terminal(String const& directory); + class LauncherHandler : public RefCounted<LauncherHandler> { public: LauncherHandler(const NonnullRefPtr<Desktop::Launcher::Details>& details) diff --git a/Userland/Applications/FileManager/main.cpp b/Userland/Applications/FileManager/main.cpp index c9a671bb71df..ed1ee2ab8a6d 100644 --- a/Userland/Applications/FileManager/main.cpp +++ b/Userland/Applications/FileManager/main.cpp @@ -699,6 +699,26 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio }, window); + auto open_in_new_terminal_action + = GUI::Action::create( + "Open in &Terminal", + {}, + Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"), + [&](GUI::Action const& action) { + Vector<String> paths; + if (action.activator() == tree_view_directory_context_menu) + paths = tree_view_selected_file_paths(); + else + paths = directory_view.selected_file_paths(); + + for (auto& path : paths) { + if (Core::File::is_directory(path)) { + spawn_terminal(path); + } + } + }, + window); + auto shortcut_action = GUI::Action::create( "Create Desktop &Shortcut", @@ -1015,6 +1035,7 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio }; directory_context_menu->add_action(open_in_new_window_action); + directory_context_menu->add_action(open_in_new_terminal_action); directory_context_menu->add_action(copy_action); directory_context_menu->add_action(cut_action); directory_context_menu->add_action(folder_specific_paste_action); @@ -1033,6 +1054,7 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio directory_view_context_menu->add_action(properties_action); tree_view_directory_context_menu->add_action(open_in_new_window_action); + tree_view_directory_context_menu->add_action(open_in_new_terminal_action); tree_view_directory_context_menu->add_action(copy_action); tree_view_directory_context_menu->add_action(cut_action); tree_view_directory_context_menu->add_action(paste_action);
e8eadd19a5ef589d7d8eb73aa89915bc9643b40c
2019-08-12 23:07:28
Andreas Kling
kernel: Show region access bits (R/W/X) in crash dump region lists
false
Show region access bits (R/W/X) in crash dump region lists
kernel
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 82bb9bfe5b33..3b5cfb58362c 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -669,12 +669,15 @@ Process::~Process() void Process::dump_regions() { kprintf("Process %s(%u) regions:\n", name().characters(), pid()); - kprintf("BEGIN END SIZE NAME\n"); + kprintf("BEGIN END SIZE ACCESS NAME\n"); for (auto& region : m_regions) { - kprintf("%x -- %x %x %s\n", + kprintf("%x -- %x %x %c%c%c %s\n", region.vaddr().get(), region.vaddr().offset(region.size() - 1).get(), region.size(), + region.is_readable() ? 'R' : ' ', + region.is_writable() ? 'W' : ' ', + region.is_executable() ? 'X' : ' ', region.name().characters()); } }
f5d779f47e5d1859571ec0778d78454a610602f9
2019-08-26 16:50:01
Andreas Kling
kernel: Never forcibly page in entire executables
false
Never forcibly page in entire executables
kernel
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index e324aa836f16..9a519ed4c45c 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -359,12 +359,6 @@ int Process::do_exec(String path, Vector<String> arguments, Vector<String> envir RefPtr<Region> region = allocate_region_with_vmo(VirtualAddress(), metadata.size, vmo, 0, description->absolute_path(), PROT_READ); ASSERT(region); - if (this != &current->process()) { - // FIXME: Don't force-load the entire executable at once, let the on-demand pager take care of it. - bool success = region->page_in(); - ASSERT(success); - } - OwnPtr<ELFLoader> loader; { // Okay, here comes the sleight of hand, pay close attention.. diff --git a/Kernel/VM/Region.cpp b/Kernel/VM/Region.cpp index 537101cf8a10..ebe9a576fb68 100644 --- a/Kernel/VM/Region.cpp +++ b/Kernel/VM/Region.cpp @@ -46,26 +46,6 @@ Region::~Region() MM.unregister_region(*this); } -bool Region::page_in() -{ - ASSERT(m_page_directory); - ASSERT(vmo().is_inode()); -#ifdef MM_DEBUG - dbgprintf("MM: page_in %u pages\n", page_count()); -#endif - for (size_t i = 0; i < page_count(); ++i) { - auto& vmo_page = vmo().physical_pages()[first_page_index() + i]; - if (vmo_page.is_null()) { - bool success = MM.page_in_from_inode(*this, i); - if (!success) - return false; - continue; - } - MM.remap_region_page(*this, i); - } - return true; -} - NonnullRefPtr<Region> Region::clone() { ASSERT(current); diff --git a/Kernel/VM/Region.h b/Kernel/VM/Region.h index 32e02193fe0d..5d4a12cf89d6 100644 --- a/Kernel/VM/Region.h +++ b/Kernel/VM/Region.h @@ -71,7 +71,6 @@ class Region : public RefCounted<Region> return size() / PAGE_SIZE; } - bool page_in(); int commit(); size_t amount_resident() const;
02b9461714feb327e7cafa90374bc2c6367cd74c
2022-10-06 16:47:38
FrHun
libgui: Consider spacing for Toolbar overflow calculation
false
Consider spacing for Toolbar overflow calculation
libgui
diff --git a/Userland/Libraries/LibGUI/Toolbar.cpp b/Userland/Libraries/LibGUI/Toolbar.cpp index 3e0801d9c014..62b16ee58171 100644 --- a/Userland/Libraries/LibGUI/Toolbar.cpp +++ b/Userland/Libraries/LibGUI/Toolbar.cpp @@ -182,6 +182,7 @@ ErrorOr<void> Toolbar::update_overflow_menu() auto position { 0 }; auto is_horizontal { m_orientation == Gfx::Orientation::Horizontal }; auto margin { is_horizontal ? layout()->margins().horizontal_total() : layout()->margins().vertical_total() }; + auto spacing { layout()->spacing() }; auto toolbar_size { is_horizontal ? width() : height() }; for (size_t i = 0; i < m_items.size() - 1; ++i) { @@ -192,7 +193,7 @@ ErrorOr<void> Toolbar::update_overflow_menu() break; } item.widget->set_visible(true); - position += item_size; + position += item_size + spacing; } if (!marginal_index.has_value()) { @@ -207,10 +208,10 @@ ErrorOr<void> Toolbar::update_overflow_menu() for (size_t i = marginal_index.value() - 1; i > 0; --i) { auto& item = m_items.at(i); auto item_size = is_horizontal ? item.widget->width() : item.widget->height(); - if (position + m_button_size + margin <= toolbar_size) + if (position + m_button_size + spacing + margin <= toolbar_size) break; item.widget->set_visible(false); - position -= item_size; + position -= item_size + spacing; marginal_index = i; } }
6af2418de71ad71b16eca1aea7b1528ab8cfa44d
2020-05-29 11:23:30
Sergey Bugaev
kernel: Pass a Custody instead of Inode to VFS methods
false
Pass a Custody instead of Inode to VFS methods
kernel
diff --git a/Kernel/FileSystem/InodeFile.cpp b/Kernel/FileSystem/InodeFile.cpp index 3e2443450607..4e286cc3da28 100644 --- a/Kernel/FileSystem/InodeFile.cpp +++ b/Kernel/FileSystem/InodeFile.cpp @@ -100,13 +100,15 @@ KResult InodeFile::truncate(u64 size) KResult InodeFile::chown(FileDescription& description, uid_t uid, gid_t gid) { ASSERT(description.inode() == m_inode); - return VFS::the().chown(*m_inode, uid, gid); + ASSERT(description.custody()); + return VFS::the().chown(*description.custody(), uid, gid); } KResult InodeFile::chmod(FileDescription& description, mode_t mode) { ASSERT(description.inode() == m_inode); - return VFS::the().chmod(*m_inode, mode); + ASSERT(description.custody()); + return VFS::the().chmod(*description.custody(), mode); } } diff --git a/Kernel/FileSystem/VirtualFileSystem.cpp b/Kernel/FileSystem/VirtualFileSystem.cpp index e4d97772fc9a..112dece57e80 100644 --- a/Kernel/FileSystem/VirtualFileSystem.cpp +++ b/Kernel/FileSystem/VirtualFileSystem.cpp @@ -393,8 +393,9 @@ KResultOr<NonnullRefPtr<Custody>> VFS::open_directory(StringView path, Custody& return custody; } -KResult VFS::chmod(Inode& inode, mode_t mode) +KResult VFS::chmod(Custody& custody, mode_t mode) { + auto& inode = custody.inode(); if (inode.fs().is_readonly()) return KResult(-EROFS); @@ -412,8 +413,7 @@ KResult VFS::chmod(StringView path, mode_t mode, Custody& base) if (custody_or_error.is_error()) return custody_or_error.error(); auto& custody = *custody_or_error.value(); - auto& inode = custody.inode(); - return chmod(inode, mode); + return chmod(custody, mode); } KResult VFS::rename(StringView old_path, StringView new_path, Custody& base) @@ -479,8 +479,9 @@ KResult VFS::rename(StringView old_path, StringView new_path, Custody& base) return KSuccess; } -KResult VFS::chown(Inode& inode, uid_t a_uid, gid_t a_gid) +KResult VFS::chown(Custody& custody, uid_t a_uid, gid_t a_gid) { + auto& inode = custody.inode(); if (inode.fs().is_readonly()) return KResult(-EROFS); @@ -521,8 +522,7 @@ KResult VFS::chown(StringView path, uid_t a_uid, gid_t a_gid, Custody& base) if (custody_or_error.is_error()) return custody_or_error.error(); auto& custody = *custody_or_error.value(); - auto& inode = custody.inode(); - return chown(inode, a_uid, a_gid); + return chown(custody, a_uid, a_gid); } KResult VFS::link(StringView old_path, StringView new_path, Custody& base) diff --git a/Kernel/FileSystem/VirtualFileSystem.h b/Kernel/FileSystem/VirtualFileSystem.h index ff390a2df0bf..d4c70c3e3830 100644 --- a/Kernel/FileSystem/VirtualFileSystem.h +++ b/Kernel/FileSystem/VirtualFileSystem.h @@ -118,9 +118,9 @@ class VFS { KResult symlink(StringView target, StringView linkpath, Custody& base); KResult rmdir(StringView path, Custody& base); KResult chmod(StringView path, mode_t, Custody& base); - KResult chmod(Inode&, mode_t); + KResult chmod(Custody&, mode_t); KResult chown(StringView path, uid_t, gid_t, Custody& base); - KResult chown(Inode&, uid_t, gid_t); + KResult chown(Custody&, uid_t, gid_t); KResult access(StringView path, int mode, Custody& base); KResultOr<InodeMetadata> lookup_metadata(StringView path, Custody& base, int options = 0); KResult utime(StringView path, Custody& base, time_t atime, time_t mtime);
39a6d29b398b6102d5d33719a4fcb713234b1453
2019-12-16 00:30:19
Andreas Kling
systemmonitor: Make the memory map the "default view"
false
Make the memory map the "default view"
systemmonitor
diff --git a/Applications/SystemMonitor/main.cpp b/Applications/SystemMonitor/main.cpp index c6c997b893ba..edc690251c4e 100644 --- a/Applications/SystemMonitor/main.cpp +++ b/Applications/SystemMonitor/main.cpp @@ -166,12 +166,12 @@ int main(int argc, char** argv) auto process_tab_widget = GTabWidget::construct(process_container_splitter); - auto open_files_widget = ProcessFileDescriptorMapWidget::construct(nullptr); - process_tab_widget->add_widget("Open files", open_files_widget); - auto memory_map_widget = ProcessMemoryMapWidget::construct(nullptr); process_tab_widget->add_widget("Memory map", memory_map_widget); + auto open_files_widget = ProcessFileDescriptorMapWidget::construct(nullptr); + process_tab_widget->add_widget("Open files", open_files_widget); + auto stacks_widget = ProcessStacksWidget::construct(nullptr); process_tab_widget->add_widget("Stacks", stacks_widget);
d2b887a793397a7a22c7ba50e7f6cb704f809446
2022-07-13 04:56:29
Andreas Kling
libweb: Only create one wrapper for inline content inside flex container
false
Only create one wrapper for inline content inside flex container
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp index c50b7ae97172..46aab132fefe 100644 --- a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp +++ b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp @@ -60,6 +60,7 @@ static Layout::Node& insertion_parent_for_inline_node(Layout::NodeWithStyle& lay if (layout_parent.computed_values().display().is_flex_inside()) { layout_parent.append_child(layout_parent.create_anonymous_wrapper()); + return *layout_parent.last_child(); } if (!has_in_flow_block_children(layout_parent) || layout_parent.children_are_inline())
1f8a7db6dbb940787fc0aa4bda422fb98357ec2f
2024-02-27 01:46:27
Andrew Kaster
meta: Port recent changes to the gn build
false
Port recent changes to the gn build
meta
diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/Animations/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/Animations/BUILD.gn index 484355e94d2a..20162478017a 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/Animations/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/Animations/BUILD.gn @@ -2,6 +2,8 @@ source_set("Animations") { configs += [ "//Userland/Libraries/LibWeb:configs" ] deps = [ "//Userland/Libraries/LibWeb:all_generated" ] sources = [ + "Animatable.cpp", + "Animatable.h", "Animation.cpp", "Animation.h", "AnimationEffect.cpp", @@ -12,6 +14,8 @@ source_set("Animations") { "AnimationTimeline.h", "DocumentTimeline.cpp", "DocumentTimeline.h", + "KeyframeEffect.cpp", + "KeyframeEffect.h", "TimingFunction.cpp", "TimingFunction.h", ] diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/CSS/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/CSS/BUILD.gn index 076a33f87ffd..82386ea14c8b 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/CSS/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/CSS/BUILD.gn @@ -8,7 +8,9 @@ source_set("CSS") { ] sources = [ "Angle.cpp", + "AnimationEvent.cpp", "CSS.cpp", + "CSSAnimation.cpp", "CSSConditionRule.cpp", "CSSFontFaceRule.cpp", "CSSGroupingRule.cpp", diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn index d0028cd43dac..42aa97d50bac 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/Layout/BUILD.gn @@ -20,6 +20,7 @@ source_set("Layout") { "FrameBox.cpp", "GridFormattingContext.cpp", "ImageBox.cpp", + "ImageProvider.cpp", "InlineFormattingContext.cpp", "InlineLevelIterator.cpp", "InlineNode.cpp", diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn index 966093079f47..9b5d4f6f8fcf 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/Painting/BUILD.gn @@ -14,6 +14,9 @@ source_set("Painting") { "ButtonPaintable.cpp", "CanvasPaintable.cpp", "CheckBoxPaintable.cpp", + "Command.cpp", + "CommandExecutorCPU.cpp", + "CommandList.cpp", "FilterPainting.cpp", "GradientPainting.cpp", "ImagePaintable.cpp", @@ -26,7 +29,6 @@ source_set("Painting") { "Paintable.cpp", "PaintableBox.cpp", "PaintableFragment.cpp", - "PaintingCommandExecutorCPU.cpp", "RadioButtonPaintable.cpp", "RecordingPainter.cpp", "SVGGraphicsPaintable.cpp", @@ -42,7 +44,7 @@ source_set("Painting") { ] if (current_os == "linux" || current_os == "mac") { - sources += [ "PaintingCommandExecutorGPU.cpp" ] + sources += [ "CommandExecutorGPU.cpp" ] public_deps = [ "//Userland/Libraries/LibAccelGfx" ] } } diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/ResizeObserver/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibWeb/ResizeObserver/BUILD.gn index 375e13b5d04d..5c2fa16239f5 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/ResizeObserver/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/ResizeObserver/BUILD.gn @@ -1,5 +1,14 @@ source_set("ResizeObserver") { configs += [ "//Userland/Libraries/LibWeb:configs" ] deps = [ "//Userland/Libraries/LibWeb:all_generated" ] - sources = [ "ResizeObserver.cpp" ] + sources = [ + "ResizeObservation.cpp", + "ResizeObservation.h", + "ResizeObserver.cpp", + "ResizeObserver.h", + "ResizeObserverEntry.cpp", + "ResizeObserverEntry.h", + "ResizeObserverSize.cpp", + "ResizeObserverSize.h", + ] } diff --git a/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni b/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni index 2fccc907577d..8db796eff351 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni +++ b/Meta/gn/secondary/Userland/Libraries/LibWeb/idl_files.gni @@ -23,11 +23,14 @@ standard_idl_files = [ "//Userland/Libraries/LibWeb/Animations/AnimationEffect.idl", "//Userland/Libraries/LibWeb/Animations/AnimationPlaybackEvent.idl", "//Userland/Libraries/LibWeb/Animations/AnimationTimeline.idl", + "//Userland/Libraries/LibWeb/Animations/KeyframeEffect.idl", "//Userland/Libraries/LibWeb/Animations/DocumentTimeline.idl", "//Userland/Libraries/LibWeb/Clipboard/Clipboard.idl", "//Userland/Libraries/LibWeb/Crypto/Crypto.idl", "//Userland/Libraries/LibWeb/Crypto/CryptoKey.idl", "//Userland/Libraries/LibWeb/Crypto/SubtleCrypto.idl", + "//Userland/Libraries/LibWeb/CSS/AnimationEvent.idl", + "//Userland/Libraries/LibWeb/CSS/CSSAnimation.idl", "//Userland/Libraries/LibWeb/CSS/CSSConditionRule.idl", "//Userland/Libraries/LibWeb/CSS/CSSFontFaceRule.idl", "//Userland/Libraries/LibWeb/CSS/CSSGroupingRule.idl", @@ -228,6 +231,8 @@ standard_idl_files = [ "//Userland/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.idl", "//Userland/Libraries/LibWeb/RequestIdleCallback/IdleDeadline.idl", "//Userland/Libraries/LibWeb/ResizeObserver/ResizeObserver.idl", + "//Userland/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.idl", + "//Userland/Libraries/LibWeb/ResizeObserver/ResizeObserverSize.idl", "//Userland/Libraries/LibWeb/Selection/Selection.idl", "//Userland/Libraries/LibWeb/Streams/ByteLengthQueuingStrategy.idl", "//Userland/Libraries/LibWeb/Streams/CountQueuingStrategy.idl",
70d0004605f52f5ffb3cdcc3ef9046134eb76db9
2021-07-31 14:52:53
Andreas Kling
meta: Add Jelle Raaijmakers to the contributors list :^)
false
Add Jelle Raaijmakers to the contributors list :^)
meta
diff --git a/README.md b/README.md index eb50877ecffd..28e3100d3409 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ Join our Discord server: [SerenityOS Discord](https://discord.gg/serenityos) * **Stephan Unverwerth** - [sunverwerth](https://github.com/sunverwerth) * **Max Wipfli** - [MaxWipfli](https://github.com/MaxWipfli) * **Daniel Bertalan** - [BertalanD](https://github.com/BertalanD) +* **Jelle Raaijmakers** - [GMTA](https://github.com/GMTA) (And many more!) The people listed above have landed more than 100 commits in the project. :^)
d0072aef8b17650f8c6ec3bdb96e94fdb6dfcbca
2021-03-28 14:54:22
Andreas Kling
libcore: Make Core::Object::event() protected
false
Make Core::Object::event() protected
libcore
diff --git a/Userland/Libraries/LibCore/Object.h b/Userland/Libraries/LibCore/Object.h index 05a33d3f6d8b..c3b105aa5482 100644 --- a/Userland/Libraries/LibCore/Object.h +++ b/Userland/Libraries/LibCore/Object.h @@ -73,7 +73,6 @@ class Object virtual ~Object(); virtual const char* class_name() const = 0; - virtual void event(Core::Event&); const String& name() const { return m_name; } void set_name(const StringView& name) { m_name = name; } @@ -155,6 +154,8 @@ class Object void register_property(const String& name, Function<JsonValue()> getter, Function<bool(const JsonValue&)> setter = nullptr); + virtual void event(Core::Event&); + virtual void timer_event(TimerEvent&); virtual void custom_event(CustomEvent&);
21f500937baeff39704ae2d824255fb2377e1357
2022-11-26 07:11:21
Andrew Kaster
meta: Add devcontainer configuration for use with Github Codespaces
false
Add devcontainer configuration for use with Github Codespaces
meta
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 000000000000..aa74ed32726b --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,40 @@ +{ + "name": "Ubuntu", + "image": "mcr.microsoft.com/devcontainers/base:jammy", + + // Features to add to the dev container. More info: https://containers.dev/implementors/features. + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/devcontainers-contrib/features/pre-commit:1": {}, + "./serenity": { + "llvm_version": 15, + "enable_ladybird": true, + "enable_serenity": true + }, + "ghcr.io/devcontainers/features/desktop-lite": { + "password": "vscode", + "webPort": "6080", + "vncPort": "5901" + } + }, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + "forwardPorts": [6080, 5901], + "portsAttributes": { + "5901": { + "label": "VNC" + }, + "6080": { + "label": "Web VNC" + } + }, + + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": "pre-commit install; pre-commit install --hook-type commit-msg" + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root", +} diff --git a/.devcontainer/serenity/devcontainer-feature.json b/.devcontainer/serenity/devcontainer-feature.json new file mode 100644 index 000000000000..b338474813ec --- /dev/null +++ b/.devcontainer/serenity/devcontainer-feature.json @@ -0,0 +1,28 @@ +{ + "name": "Serenity Development", + "id": "serenity", + "version": "1.0.0", + "description": "Enable development of Serenity and Lagom libraries and applications", + "options": { + "llvm_version": { + "type": "string", + "proposals": [ + 14, + 15, + "trunk" + ], + "default": 15, + "description": "Select LLVM compiler version to use" + }, + "enable_ladybird": { + "type": "boolean", + "default": true, + "description": "Install Qt6 packages for Ladybird development" + }, + "enable_serenity": { + "type": "boolean", + "default": true, + "description": "Install packages for SerenityOS development" + } + } +} diff --git a/.devcontainer/serenity/install.sh b/.devcontainer/serenity/install.sh new file mode 100755 index 000000000000..bf98846b7288 --- /dev/null +++ b/.devcontainer/serenity/install.sh @@ -0,0 +1,62 @@ +#!/bin/sh +set -e + +# Feature options + +LLVM_VERSION=${LLVM_VERSION:-15} +ENABLE_LADYBIRD=${ENABLE_LADYBIRD:-true} +ENABLE_SERENITY=${ENABLE_SERENITY:-true} + +### Check distro + +if [ ! -f /etc/lsb-release ]; then + echo "Not an Ubuntu container, add logic for your distro to the serenity feature or use Ubuntu" + exit 1 +fi + +# shellcheck source=/dev/null +. /etc/lsb-release + +### Declare helper functions + +install_llvm_key() { + wget -O /usr/share/keyrings/llvm-snapshot.gpg.key https://apt.llvm.org/llvm-snapshot.gpg.key + echo "deb [signed-by=/usr/share/keyrings/llvm-snapshot.gpg.key] http://apt.llvm.org/${DISTRIB_CODENAME}/ llvm-toolchain-${DISTRIB_CODENAME} main" | tee -a /etc/apt/sources.list.d/llvm.list + if [ ! "${LLVM_VERSION}" = "trunk" ]; then + echo "deb [signed-by=/usr/share/keyrings/llvm-snapshot.gpg.key] http://apt.llvm.org/${DISTRIB_CODENAME}/ llvm-toolchain-${DISTRIB_CODENAME}-${LLVM_VERSION} main" | tee -a /etc/apt/sources.list.d/llvm.list + fi + apt update -y +} + +### Install packages + +apt update -y +apt install -y build-essential cmake ninja-build ccache shellcheck +if [ "${ENABLE_LADYBIRD}" = "true" ]; then + apt install -y libgl1-mesa-dev qt6-base-dev qt6-tools-dev-tools qt6-wayland +fi +if [ "${ENABLE_SERENITY}" = "true" ]; then + apt install -y curl libmpfr-dev libmpc-dev libgmp-dev e2fsprogs genext2fs qemu-system-gui qemu-system-x86 qemu-utils rsync unzip texinfo +fi + +### Ensure new enough host compiler is available + +VERSION="0.0.0" +if command -v clang >/dev/null 2>&1; then + VERSION="$(clang -dumpversion)" +fi +MAJOR_VERSION="${VERSION%%.*}" + +if [ "${LLVM_VERSION}" = "trunk" ]; then + install_llvm_key + + apt install -y llvm clang clangd clang-tools lld lldb clang-tidy clang-format +elif [ "${MAJOR_VERSION}" -lt "${LLVM_VERSION}" ]; then + FAILED_INSTALL=0 + apt install -y "llvm-${LLVM_VERSION}" "clang-${LLVM_VERSION}" "clangd-${LLVM_VERSION}" "clang-tools-${LLVM_VERSION}" "lld-${LLVM_VERSION}" "lldb-${LLVM_VERSION}" "clang-tidy-${LLVM_VERSION}" "clang-format-${LLVM_VERSION}" || FAILED_INSTALL=1 + + if [ "${FAILED_INSTALL}" -ne 0 ]; then + install_llvm_key + apt install -y "llvm-${LLVM_VERSION}" "clang-${LLVM_VERSION}" "clangd-${LLVM_VERSION}" "clang-tools-${LLVM_VERSION}" "lld-${LLVM_VERSION}" "lldb-${LLVM_VERSION}" "clang-tidy-${LLVM_VERSION}" "clang-format-${LLVM_VERSION}" + fi +fi
09547f4084b5674a291856faf002967ef8aac521
2021-12-14 10:58:56
Timothy Flynn
libunicode: Generate unique lists of calendar symbols structures
false
Generate unique lists of calendar symbols structures
libunicode
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp index 9ae77a6576d2..700333e1a1c5 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp @@ -43,6 +43,9 @@ constexpr auto s_symbol_list_index_type = "u16"sv; using CalendarSymbolsIndexType = u16; constexpr auto s_calendar_symbols_index_type = "u16"sv; +using CalendarSymbolsListIndexType = u8; +constexpr auto s_calendar_symbols_list_index_type = "u8"sv; + struct CalendarPattern : public Unicode::CalendarPattern { bool contains_only_date_fields() const { @@ -285,6 +288,8 @@ struct AK::Traits<CalendarSymbols> : public GenericTraits<CalendarSymbols> { static unsigned hash(CalendarSymbols const& c) { return c.hash(); } }; +using CalendarSymbolsList = Vector<CalendarSymbolsIndexType>; + struct Calendar { StringIndexType calendar { 0 }; @@ -297,7 +302,7 @@ struct Calendar { Vector<CalendarRangePatternIndexType> range_formats {}; Vector<CalendarRangePatternIndexType> range12_formats {}; - Vector<CalendarSymbolsIndexType> symbols {}; + CalendarSymbolsListIndexType symbols { 0 }; }; struct TimeZone { @@ -325,6 +330,7 @@ struct UnicodeLocaleData { UniqueStorage<CalendarFormat, CalendarFormatIndexType> unique_formats; UniqueStorage<SymbolList, SymbolListIndexType> unique_symbol_lists; UniqueStorage<CalendarSymbols, CalendarSymbolsIndexType> unique_calendar_symbols; + UniqueStorage<CalendarSymbolsList, CalendarSymbolsListIndexType> unique_calendar_symbols_lists; HashMap<String, Locale> locales; @@ -931,10 +937,12 @@ static void parse_calendar_symbols(Calendar& calendar, JsonObject const& calenda } }; }; + CalendarSymbolsList symbols_list {}; + auto store_symbol_lists = [&](auto symbol, auto symbol_lists) { auto symbol_index = to_underlying(symbol); - if (symbol_index >= calendar.symbols.size()) - calendar.symbols.resize(symbol_index + 1); + if (symbol_index >= symbols_list.size()) + symbols_list.resize(symbol_index + 1); CalendarSymbols symbols {}; symbols.narrow_symbols = locale_data.unique_symbol_lists.ensure(move(symbol_lists[0])); @@ -942,7 +950,7 @@ static void parse_calendar_symbols(Calendar& calendar, JsonObject const& calenda symbols.long_symbols = locale_data.unique_symbol_lists.ensure(move(symbol_lists[2])); auto calendar_symbols_index = locale_data.unique_calendar_symbols.ensure(move(symbols)); - calendar.symbols[symbol_index] = calendar_symbols_index; + symbols_list[symbol_index] = calendar_symbols_index; }; auto parse_era_symbols = [&](auto const& symbols_object) { @@ -1057,6 +1065,8 @@ static void parse_calendar_symbols(Calendar& calendar, JsonObject const& calenda parse_month_symbols(calendar_object.get("months"sv).as_object().get("format"sv).as_object()); parse_weekday_symbols(calendar_object.get("days"sv).as_object().get("format"sv).as_object()); parse_day_period_symbols(calendar_object.get("dayPeriods"sv).as_object().get("format"sv).as_object()); + + calendar.symbols = locale_data.unique_calendar_symbols_lists.ensure(move(symbols_list)); } static ErrorOr<void> parse_calendars(String locale_calendars_path, UnicodeLocaleData& locale_data, Locale& locale) @@ -1379,6 +1389,7 @@ static void generate_unicode_locale_implementation(Core::File& file, UnicodeLoca generator.set("calendar_format_index_type"sv, s_calendar_format_index_type); generator.set("symbol_list_index_type"sv, s_symbol_list_index_type); generator.set("calendar_symbols_index_type"sv, s_calendar_symbols_index_type); + generator.set("calendar_symbols_list_index_type"sv, s_calendar_symbols_list_index_type); generator.append(R"~~~( #include <AK/Array.h> @@ -1524,7 +1535,7 @@ struct CalendarData { Span<@calendar_range_pattern_index_type@ const> range_formats {}; Span<@calendar_range_pattern_index_type@ const> range12_formats {}; - Array<@calendar_symbols_index_type@, 4> symbols {}; + @calendar_symbols_list_index_type@ symbols { 0 }; }; struct TimeZoneData { @@ -1543,6 +1554,7 @@ struct DayPeriodData { locale_data.unique_formats.generate(generator, "CalendarFormat"sv, "s_calendar_formats"sv, 10); locale_data.unique_symbol_lists.generate(generator, s_string_index_type, "s_symbol_lists"sv); locale_data.unique_calendar_symbols.generate(generator, "CalendarSymbols"sv, "s_calendar_symbols"sv, 10); + locale_data.unique_calendar_symbols_lists.generate(generator, s_calendar_symbols_index_type, "s_calendar_symbol_lists"sv); auto append_pattern_list = [&](auto name, auto type, auto const& formats) { generator.set("name", move(name)); @@ -1593,21 +1605,14 @@ static constexpr Array<CalendarData, @size@> @name@ { {)~~~"); generator.set("default_range_format", String::number(calendar.default_range_format)); generator.set("range_formats", format_name(calendar_key, "range_formats"sv)); generator.set("range12_formats", format_name(calendar_key, "range12_formats"sv)); + generator.set("symbols"sv, String::number(calendar.symbols)); generator.append(R"~~~( { @calendar@, )~~~"); generator.append("@date_formats@, @time_formats@, @date_time_formats@, @[email protected](), "); - generator.append("@default_range_format@, @[email protected](), @[email protected](), {"); - - bool first = true; - for (auto symbols : calendar.symbols) { - generator.append(first ? " " : ", "); - generator.append(String::number(symbols)); - first = false; - } - - generator.append(" } },"); + generator.append("@default_range_format@, @[email protected](), @[email protected](), "); + generator.append("@symbols@ }, "); } generator.append(R"~~~( @@ -1826,9 +1831,10 @@ Vector<Unicode::CalendarRangePattern> get_calendar_range12_formats(StringView lo static Span<@string_index_type@ const> find_calendar_symbols(StringView locale, StringView calendar, CalendarSymbol symbol, CalendarPatternStyle style) { if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) { + auto const& symbols_list = s_calendar_symbol_lists[data->symbols]; auto symbol_index = to_underlying(symbol); - auto calendar_symbols_index = data->symbols.at(symbol_index); + auto calendar_symbols_index = symbols_list.at(symbol_index); auto const& symbols = s_calendar_symbols.at(calendar_symbols_index); @symbol_list_index_type@ symbol_list_index = 0;
fdb647c097d0ca36dfdd73bb4646132b5b82c43b
2022-03-16 00:18:19
Andreas Kling
libweb: Use a WeakPtr for DocumentFragment's "host" field
false
Use a WeakPtr for DocumentFragment's "host" field
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/DocumentFragment.h b/Userland/Libraries/LibWeb/DOM/DocumentFragment.h index 7a0ef4fa7193..5b208500ab73 100644 --- a/Userland/Libraries/LibWeb/DOM/DocumentFragment.h +++ b/Userland/Libraries/LibWeb/DOM/DocumentFragment.h @@ -26,13 +26,14 @@ class DocumentFragment virtual FlyString node_name() const override { return "#document-fragment"; } - RefPtr<Element> host() { return m_host; } - const RefPtr<Element> host() const { return m_host; } + Element* host() { return m_host; } + Element const* host() const { return m_host; } void set_host(Element& host) { m_host = host; } private: - RefPtr<Element> m_host; + // https://dom.spec.whatwg.org/#concept-documentfragment-host + WeakPtr<Element> m_host; }; } diff --git a/Userland/Libraries/LibWeb/DOM/Node.cpp b/Userland/Libraries/LibWeb/DOM/Node.cpp index b1eb86a63d17..5f65d4a29ac2 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.cpp +++ b/Userland/Libraries/LibWeb/DOM/Node.cpp @@ -701,7 +701,14 @@ u16 Node::compare_document_position(RefPtr<Node> other) // https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor bool Node::is_host_including_inclusive_ancestor_of(const Node& other) const { - return is_inclusive_ancestor_of(other) || (is<DocumentFragment>(other.root()) && verify_cast<DocumentFragment>(other.root()).host() && is_inclusive_ancestor_of(*verify_cast<DocumentFragment>(other.root()).host().ptr())); + if (is_inclusive_ancestor_of(other)) + return true; + if (is<DocumentFragment>(other.root()) + && static_cast<DocumentFragment const&>(other.root()).host() + && is_inclusive_ancestor_of(*static_cast<DocumentFragment const&>(other.root()).host())) { + return true; + } + return false; } // https://dom.spec.whatwg.org/#dom-node-ownerdocument
c853bc2ba681432d550ca8622a8158306e877fd5
2021-08-31 20:15:57
Mustafa Quraish
pixelpaint: Rename `Mode` to `FillMode` for Ellipse/Rectangle
false
Rename `Mode` to `FillMode` for Ellipse/Rectangle
pixelpaint
diff --git a/Userland/Applications/PixelPaint/EllipseTool.cpp b/Userland/Applications/PixelPaint/EllipseTool.cpp index 5c5e4666c5ce..d60ad0baee22 100644 --- a/Userland/Applications/PixelPaint/EllipseTool.cpp +++ b/Userland/Applications/PixelPaint/EllipseTool.cpp @@ -37,11 +37,11 @@ void EllipseTool::draw_using(GUI::Painter& painter, Gfx::IntPoint const& start_p ellipse_intersecting_rect = Gfx::IntRect::from_two_points(start_position, end_position); } - switch (m_mode) { - case Mode::Outline: + switch (m_fill_mode) { + case FillMode::Outline: painter.draw_ellipse_intersecting(ellipse_intersecting_rect, m_editor->color_for(m_drawing_button), m_thickness); break; - case Mode::Fill: + case FillMode::Fill: painter.fill_ellipse(ellipse_intersecting_rect, m_editor->color_for(m_drawing_button)); break; default: @@ -148,10 +148,10 @@ GUI::Widget* EllipseTool::get_properties_widget() auto& fill_mode_radio = mode_radio_container.add<GUI::RadioButton>("Fill"); outline_mode_radio.on_checked = [&](bool) { - m_mode = Mode::Outline; + m_fill_mode = FillMode::Outline; }; fill_mode_radio.on_checked = [&](bool) { - m_mode = Mode::Fill; + m_fill_mode = FillMode::Fill; }; outline_mode_radio.set_checked(true); diff --git a/Userland/Applications/PixelPaint/EllipseTool.h b/Userland/Applications/PixelPaint/EllipseTool.h index 9f85b95e7380..059c4f055fe3 100644 --- a/Userland/Applications/PixelPaint/EllipseTool.h +++ b/Userland/Applications/PixelPaint/EllipseTool.h @@ -27,7 +27,7 @@ class EllipseTool final : public Tool { virtual Gfx::StandardCursor cursor() override { return Gfx::StandardCursor::Crosshair; } private: - enum class Mode { + enum class FillMode { Outline, Fill, }; @@ -44,7 +44,7 @@ class EllipseTool final : public Tool { Gfx::IntPoint m_ellipse_start_position; Gfx::IntPoint m_ellipse_end_position; int m_thickness { 1 }; - Mode m_mode { Mode::Outline }; + FillMode m_fill_mode { FillMode::Outline }; DrawMode m_draw_mode { DrawMode::FromCorner }; }; diff --git a/Userland/Applications/PixelPaint/RectangleTool.cpp b/Userland/Applications/PixelPaint/RectangleTool.cpp index 066b50775249..34b9395c330c 100644 --- a/Userland/Applications/PixelPaint/RectangleTool.cpp +++ b/Userland/Applications/PixelPaint/RectangleTool.cpp @@ -36,14 +36,14 @@ void RectangleTool::draw_using(GUI::Painter& painter, Gfx::IntPoint const& start rect = Gfx::IntRect::from_two_points(start_position, end_position); } - switch (m_mode) { - case Mode::Fill: + switch (m_fill_mode) { + case FillMode::Fill: painter.fill_rect(rect, m_editor->color_for(m_drawing_button)); break; - case Mode::Outline: + case FillMode::Outline: painter.draw_rect(rect, m_editor->color_for(m_drawing_button)); break; - case Mode::Gradient: + case FillMode::Gradient: painter.fill_rect_with_gradient(rect, m_editor->primary_color(), m_editor->secondary_color()); break; default: @@ -138,13 +138,13 @@ GUI::Widget* RectangleTool::get_properties_widget() auto& gradient_mode_radio = mode_radio_container.add<GUI::RadioButton>("Gradient"); outline_mode_radio.on_checked = [&](bool) { - m_mode = Mode::Outline; + m_fill_mode = FillMode::Outline; }; fill_mode_radio.on_checked = [&](bool) { - m_mode = Mode::Fill; + m_fill_mode = FillMode::Fill; }; gradient_mode_radio.on_checked = [&](bool) { - m_mode = Mode::Gradient; + m_fill_mode = FillMode::Gradient; }; outline_mode_radio.set_checked(true); diff --git a/Userland/Applications/PixelPaint/RectangleTool.h b/Userland/Applications/PixelPaint/RectangleTool.h index fd437b65945c..f84e4031cbb6 100644 --- a/Userland/Applications/PixelPaint/RectangleTool.h +++ b/Userland/Applications/PixelPaint/RectangleTool.h @@ -27,7 +27,7 @@ class RectangleTool final : public Tool { virtual Gfx::StandardCursor cursor() override { return Gfx::StandardCursor::Crosshair; } private: - enum class Mode { + enum class FillMode { Outline, Fill, Gradient, @@ -44,7 +44,7 @@ class RectangleTool final : public Tool { GUI::MouseButton m_drawing_button { GUI::MouseButton::None }; Gfx::IntPoint m_rectangle_start_position; Gfx::IntPoint m_rectangle_end_position; - Mode m_mode { Mode::Outline }; + FillMode m_fill_mode { FillMode::Outline }; DrawMode m_draw_mode { DrawMode::FromCorner }; };
199f0e45cb94371f983741755ca42babc909a884
2024-09-25 21:49:51
Saleem Abdulrasool
meta: Make `download_file` work on Windows
false
Make `download_file` work on Windows
meta
diff --git a/Meta/gn/build/download_file.py b/Meta/gn/build/download_file.py index bf3eda82b952..29f1e804eb48 100644 --- a/Meta/gn/build/download_file.py +++ b/Meta/gn/build/download_file.py @@ -70,7 +70,7 @@ def main(): try: with tempfile.NamedTemporaryFile(delete=False, dir=output_file.parent) as out: out.write(f.read()) - os.rename(out.name, output_file) + os.rename(out.name, output_file) except IOError: os.unlink(out.name)
62596f3e434f8a407c9b861d33a504ae90a6edcd
2024-03-02 13:41:03
Timothy Flynn
ci: Reduce the ccache size for CI
false
Reduce the ccache size for CI
ci
diff --git a/Meta/Azure/Caches.yml b/Meta/Azure/Caches.yml index bc8f76e2547b..ec77e7d43dbd 100644 --- a/Meta/Azure/Caches.yml +++ b/Meta/Azure/Caches.yml @@ -55,6 +55,7 @@ steps: - script: | CCACHE_DIR=${{ parameters.serenity_ccache_path }} ccache -M ${{ parameters.serenity_ccache_size }} + CCACHE_DIR=${{ parameters.serenity_ccache_path }} ccache -c CCACHE_DIR=${{ parameters.serenity_ccache_path }} ccache -s displayName: 'Configure Serenity ccache' diff --git a/Meta/Azure/Lagom.yml b/Meta/Azure/Lagom.yml index 8bcd73086149..514f2f2824e0 100644 --- a/Meta/Azure/Lagom.yml +++ b/Meta/Azure/Lagom.yml @@ -56,7 +56,7 @@ jobs: with_remote_data_caches: true ${{ if eq(parameters.os, 'macOS') }}: ccache_version: 2 - serenity_ccache_size: '2G' + serenity_ccache_size: '2G' - ${{ if eq(parameters.os, 'Android') }}: - script: |
80e756daefb3b2fe0df3f9182f3c674924bd53c9
2023-10-10 18:06:25
Sam Atkins
libgfx: Load BitmapFont data more safely
false
Load BitmapFont data more safely
libgfx
diff --git a/Userland/Libraries/LibGfx/Font/BitmapFont.cpp b/Userland/Libraries/LibGfx/Font/BitmapFont.cpp index 745762368c95..ebaa4f26ad5b 100644 --- a/Userland/Libraries/LibGfx/Font/BitmapFont.cpp +++ b/Userland/Libraries/LibGfx/Font/BitmapFont.cpp @@ -40,6 +40,18 @@ static_assert(AssertSize<FontFileHeader, 80>()); static constexpr size_t s_max_glyph_count = 0x110000; static constexpr size_t s_max_range_mask_size = s_max_glyph_count / (256 * 8); +} + +// FIXME: We define the traits for the const FontFileHeader, because that's the one we use, and defining +// Traits<T> doesn't apply to Traits<T const>. Once that's fixed, remove the const here. +template<> +class AK::Traits<Gfx::FontFileHeader const> : public GenericTraits<Gfx::FontFileHeader const> { +public: + static constexpr bool is_trivially_serializable() { return true; } +}; + +namespace Gfx { + NonnullRefPtr<Font> BitmapFont::clone() const { return MUST(try_clone()); @@ -176,9 +188,9 @@ BitmapFont::~BitmapFont() } } -ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::load_from_memory(u8 const* data) +ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_mapped_file(NonnullOwnPtr<Core::MappedFile> mapped_file) { - auto const& header = *reinterpret_cast<FontFileHeader const*>(data); + auto& header = *TRY(mapped_file->read_in_place<FontFileHeader const>()); if (memcmp(header.magic, "!Fnt", 4)) return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Incompatible header"); if (header.name[sizeof(header.name) - 1] != '\0') @@ -188,16 +200,29 @@ ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::load_from_memory(u8 const* data) size_t bytes_per_glyph = sizeof(u32) * header.glyph_height; size_t glyph_count { 0 }; - u8* range_mask_start = const_cast<u8*>(data + sizeof(FontFileHeader)); - Bytes range_mask { range_mask_start, header.range_mask_size }; + + // FIXME: These ReadonlyFoo -> Foo casts are awkward, and only needed because BitmapFont is + // sometimes editable and sometimes not. Splitting it into editable/non-editable classes + // would make this a lot cleaner. + ReadonlyBytes readonly_range_mask = TRY(mapped_file->read_in_place<u8 const>(header.range_mask_size)); + Bytes range_mask { const_cast<u8*>(readonly_range_mask.data()), readonly_range_mask.size() }; for (size_t i = 0; i < header.range_mask_size; ++i) glyph_count += 256 * popcount(range_mask[i]); - u8* rows_start = range_mask_start + header.range_mask_size; - Bytes rows { rows_start, glyph_count * bytes_per_glyph }; - Span<u8> widths { rows_start + glyph_count * bytes_per_glyph, glyph_count }; + + ReadonlyBytes readonly_rows = TRY(mapped_file->read_in_place<u8 const>(glyph_count * bytes_per_glyph)); + Bytes rows { const_cast<u8*>(readonly_rows.data()), readonly_rows.size() }; + + ReadonlySpan<u8> readonly_widths = TRY(mapped_file->read_in_place<u8 const>(glyph_count)); + Span<u8> widths { const_cast<u8*>(readonly_widths.data()), readonly_widths.size() }; + + if (!mapped_file->is_eof()) + return Error::from_string_literal("Gfx::BitmapFont::load_from_memory: Trailing data in file"); + auto name = TRY(String::from_utf8(ReadonlyBytes { header.name, strlen(header.name) })); auto family = TRY(String::from_utf8(ReadonlyBytes { header.family, strlen(header.family) })); - return adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(move(name), move(family), rows, widths, !header.is_variable_width, header.glyph_width, header.glyph_height, header.glyph_spacing, range_mask, header.baseline, header.mean_line, header.presentation_size, header.weight, header.slope)); + auto font = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) BitmapFont(move(name), move(family), rows, widths, !header.is_variable_width, header.glyph_width, header.glyph_height, header.glyph_spacing, range_mask, header.baseline, header.mean_line, header.presentation_size, header.weight, header.slope))); + font->m_mapped_file = move(mapped_file); + return font; } RefPtr<BitmapFont> BitmapFont::load_from_file(DeprecatedString const& path) @@ -211,13 +236,6 @@ ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_file(DeprecatedStri return try_load_from_mapped_file(move(mapped_file)); } -ErrorOr<NonnullRefPtr<BitmapFont>> BitmapFont::try_load_from_mapped_file(OwnPtr<Core::MappedFile> mapped_file) -{ - auto font = TRY(load_from_memory((u8 const*)mapped_file->data())); - font->m_mapped_file = move(mapped_file); - return font; -} - ErrorOr<void> BitmapFont::write_to_file(DeprecatedString const& path) { auto stream = TRY(Core::File::open(path, Core::File::OpenMode::Write)); diff --git a/Userland/Libraries/LibGfx/Font/BitmapFont.h b/Userland/Libraries/LibGfx/Font/BitmapFont.h index dc937166e4fb..d7893cb157ce 100644 --- a/Userland/Libraries/LibGfx/Font/BitmapFont.h +++ b/Userland/Libraries/LibGfx/Font/BitmapFont.h @@ -31,7 +31,7 @@ class BitmapFont final : public Font { static RefPtr<BitmapFont> load_from_file(DeprecatedString const& path); static ErrorOr<NonnullRefPtr<BitmapFont>> try_load_from_file(DeprecatedString const& path); - static ErrorOr<NonnullRefPtr<BitmapFont>> try_load_from_mapped_file(OwnPtr<Core::MappedFile>); + static ErrorOr<NonnullRefPtr<BitmapFont>> try_load_from_mapped_file(NonnullOwnPtr<Core::MappedFile>); ErrorOr<void> write_to_file(DeprecatedString const& path); ErrorOr<void> write_to_file(NonnullOwnPtr<Core::File> file); @@ -134,8 +134,6 @@ class BitmapFont final : public Font { u8 glyph_width, u8 glyph_height, u8 glyph_spacing, Bytes range_mask, u8 baseline, u8 mean_line, u8 presentation_size, u16 weight, u8 slope, bool owns_arrays = false); - static ErrorOr<NonnullRefPtr<BitmapFont>> load_from_memory(u8 const*); - template<typename T> int unicode_view_width(T const& view) const;
fb4a20ade59d954b2708cf756dd92363053220d0
2023-08-23 18:56:03
Aman Singh
kernel: Fix condition for write to succeed on pseudoterminal
false
Fix condition for write to succeed on pseudoterminal
kernel
diff --git a/Kernel/TTY/MasterPTY.cpp b/Kernel/TTY/MasterPTY.cpp index f4c8652a8b7d..6385f0f40a8f 100644 --- a/Kernel/TTY/MasterPTY.cpp +++ b/Kernel/TTY/MasterPTY.cpp @@ -96,7 +96,7 @@ bool MasterPTY::can_write_from_slave() const { if (m_closed) return true; - return m_buffer->space_for_writing(); + return m_buffer->space_for_writing() >= 2; } ErrorOr<void> MasterPTY::close()
7ae7170d6140f7cad730f05f84b53437058b82f4
2021-04-30 01:46:18
Andreas Kling
everywhere: "file name" => "filename"
false
"file name" => "filename"
everywhere
diff --git a/AK/SourceLocation.h b/AK/SourceLocation.h index 54bd62fdcf05..8e1a2a5dcb22 100644 --- a/AK/SourceLocation.h +++ b/AK/SourceLocation.h @@ -16,7 +16,7 @@ namespace AK { class SourceLocation { public: [[nodiscard]] constexpr StringView function_name() const { return StringView(m_function); } - [[nodiscard]] constexpr StringView file_name() const { return StringView(m_file); } + [[nodiscard]] constexpr StringView filename() const { return StringView(m_file); } [[nodiscard]] constexpr u32 line_number() const { return m_line; } [[nodiscard]] static constexpr SourceLocation current(const char* const file = __builtin_FILE(), u32 line = __builtin_LINE(), const char* const function = __builtin_FUNCTION()) @@ -45,7 +45,7 @@ template<> struct AK::Formatter<AK::SourceLocation> : AK::Formatter<FormatString> { void format(FormatBuilder& builder, AK::SourceLocation location) { - return AK::Formatter<FormatString>::format(builder, "[{} @ {}:{}]", location.function_name(), location.file_name(), location.line_number()); + return AK::Formatter<FormatString>::format(builder, "[{} @ {}:{}]", location.function_name(), location.filename(), location.line_number()); } }; diff --git a/AK/Tests/TestSourceLocation.cpp b/AK/Tests/TestSourceLocation.cpp index 15910062f339..d770751d1d1d 100644 --- a/AK/Tests/TestSourceLocation.cpp +++ b/AK/Tests/TestSourceLocation.cpp @@ -13,7 +13,7 @@ TEST_CASE(basic_scenario) { auto location = SourceLocation::current(); - EXPECT_EQ(StringView(__FILE__), location.file_name()); + EXPECT_EQ(StringView(__FILE__), location.filename()); EXPECT_EQ(StringView(__FUNCTION__), location.function_name()); EXPECT_EQ(__LINE__ - 3u, location.line_number()); } diff --git a/Kernel/FileSystem/ext2_fs.h b/Kernel/FileSystem/ext2_fs.h index 6211a485459f..2782845cee67 100644 --- a/Kernel/FileSystem/ext2_fs.h +++ b/Kernel/FileSystem/ext2_fs.h @@ -664,7 +664,7 @@ struct ext2_dir_entry { __u32 inode; /* Inode number */ __u16 rec_len; /* Directory entry length */ __u16 name_len; /* Name length */ - char name[EXT2_NAME_LEN]; /* File name */ + char name[EXT2_NAME_LEN]; /* Filename */ }; /* @@ -678,7 +678,7 @@ struct ext2_dir_entry_2 { __u16 rec_len; /* Directory entry length */ __u8 name_len; /* Name length */ __u8 file_type; - char name[EXT2_NAME_LEN]; /* File name */ + char name[EXT2_NAME_LEN]; /* Filename */ }; /* diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index 9a80a6167ba9..c1cc4711abff 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -362,7 +362,7 @@ void Thread::finalize() ScopedSpinLock list_lock(m_holding_locks_lock); for (auto& info : m_holding_locks_list) { const auto& location = info.source_location; - dbgln(" - Lock: \"{}\" @ {} locked in function \"{}\" at \"{}:{}\" with a count of: {}", info.lock->name(), info.lock, location.function_name(), location.file_name(), location.line_number(), info.count); + dbgln(" - Lock: \"{}\" @ {} locked in function \"{}\" at \"{}:{}\" with a count of: {}", info.lock->name(), info.lock, location.function_name(), location.filename(), location.line_number(), info.count); } VERIFY_NOT_REACHED(); } diff --git a/Meta/lint-keymaps.py b/Meta/lint-keymaps.py index a22258c0ce7c..162db7827673 100755 --- a/Meta/lint-keymaps.py +++ b/Meta/lint-keymaps.py @@ -15,7 +15,7 @@ def report(filename, problem): """Print a lint problem to stdout. Args: - filename (str): keymap file name + filename (str): keymap filename problem (str): problem message """ print('{}: {}'.format(filename, problem)) @@ -25,7 +25,7 @@ def validate_single_map(filename, mapname, values): """Validate a key map. Args: - filename (str): keymap file name + filename (str): keymap filename mapname (str): map name (altgr_map, alt_map, shift_altgr_map) values (list): key values @@ -63,7 +63,7 @@ def validate_fullmap(filename, fullmap): """Validate a full key map for all map names (including maps for key modifiers). Args: - filename (str): keymap file name + filename (str): keymap filename fullmap (dict): key mappings Returns: @@ -126,7 +126,7 @@ def list_files_here(): """Retrieve a list of all '.json' files in the working directory. Returns: - list: JSON file names + list: JSON filenames """ filelist = [] diff --git a/Meta/lint-ports.py b/Meta/lint-ports.py index 32f4382cd003..be2aa83544a5 100755 --- a/Meta/lint-ports.py +++ b/Meta/lint-ports.py @@ -31,7 +31,7 @@ def read_port_table(filename): """Open a file and find all PORT_TABLE_REGEX matches. Args: - filename (str): file name + filename (str): filename Returns: set: all PORT_TABLE_REGEX matches diff --git a/Userland/Applications/Debugger/main.cpp b/Userland/Applications/Debugger/main.cpp index 1d4e3469eb09..0f4976d0f94b 100644 --- a/Userland/Applications/Debugger/main.cpp +++ b/Userland/Applications/Debugger/main.cpp @@ -90,7 +90,7 @@ static bool insert_breakpoint_at_source_position(const String& file, size_t line warnln("Could not insert breakpoint at {}:{}", file, line); return false; } - outln("Breakpoint inserted [{}:{} ({}:{:p})]", result.value().file_name, result.value().line_number, result.value().library_name, result.value().address); + outln("Breakpoint inserted [{}:{} ({}:{:p})]", result.value().filename, result.value().line_number, result.value().library_name, result.value().address); return true; } diff --git a/Userland/Applications/FileManager/FileOperationProgressWidget.cpp b/Userland/Applications/FileManager/FileOperationProgressWidget.cpp index 0f6b84a8aac6..8098c98f52c9 100644 --- a/Userland/Applications/FileManager/FileOperationProgressWidget.cpp +++ b/Userland/Applications/FileManager/FileOperationProgressWidget.cpp @@ -134,14 +134,14 @@ String FileOperationProgressWidget::estimate_time(off_t bytes_done, off_t total_ return String::formatted("{} hours and {} minutes", hours_remaining, minutes_remaining); } -void FileOperationProgressWidget::did_progress(off_t bytes_done, off_t total_byte_count, size_t files_done, size_t total_file_count, [[maybe_unused]] off_t current_file_done, [[maybe_unused]] off_t current_file_size, const StringView& current_file_name) +void FileOperationProgressWidget::did_progress(off_t bytes_done, off_t total_byte_count, size_t files_done, size_t total_file_count, [[maybe_unused]] off_t current_file_done, [[maybe_unused]] off_t current_file_size, const StringView& current_filename) { auto& files_copied_label = *find_descendant_of_type_named<GUI::Label>("files_copied_label"); auto& current_file_label = *find_descendant_of_type_named<GUI::Label>("current_file_label"); auto& overall_progressbar = *find_descendant_of_type_named<GUI::Progressbar>("overall_progressbar"); auto& estimated_time_label = *find_descendant_of_type_named<GUI::Label>("estimated_time_label"); - current_file_label.set_text(current_file_name); + current_file_label.set_text(current_filename); files_copied_label.set_text(String::formatted("Copying file {} of {}", files_done, total_file_count)); estimated_time_label.set_text(estimate_time(bytes_done, total_byte_count)); diff --git a/Userland/Applications/FileManager/FileOperationProgressWidget.h b/Userland/Applications/FileManager/FileOperationProgressWidget.h index 7a55f5833b97..6f9b69233481 100644 --- a/Userland/Applications/FileManager/FileOperationProgressWidget.h +++ b/Userland/Applications/FileManager/FileOperationProgressWidget.h @@ -22,7 +22,7 @@ class FileOperationProgressWidget : public GUI::Widget { void did_finish(); void did_error(String message); - void did_progress(off_t bytes_done, off_t total_byte_count, size_t files_done, size_t total_file_count, off_t current_file_done, off_t current_file_size, const StringView& current_file_name); + void did_progress(off_t bytes_done, off_t total_byte_count, size_t files_done, size_t total_file_count, off_t current_file_done, off_t current_file_size, const StringView& current_filename); void close_pipe(); diff --git a/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.cpp b/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.cpp index d85e5c596301..6f72a18e4371 100644 --- a/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.cpp +++ b/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.cpp @@ -123,12 +123,12 @@ void KeyboardMapperWidget::create_frame() bottom_widget.layout()->add_spacer(); } -void KeyboardMapperWidget::load_from_file(String file_name) +void KeyboardMapperWidget::load_from_file(String filename) { - auto result = Keyboard::CharacterMapFile::load_from_file(file_name); + auto result = Keyboard::CharacterMapFile::load_from_file(filename); VERIFY(result.has_value()); - m_file_name = file_name; + m_filename = filename; m_character_map = result.value(); set_current_map("map"); @@ -145,7 +145,7 @@ void KeyboardMapperWidget::load_from_system() auto result = Keyboard::CharacterMap::fetch_system_map(); VERIFY(!result.is_error()); - m_file_name = String::formatted("/res/keymaps/{}.json", result.value().character_map_name()); + m_filename = String::formatted("/res/keymaps/{}.json", result.value().character_map_name()); m_character_map = result.value().character_map_data(); set_current_map("map"); @@ -159,10 +159,10 @@ void KeyboardMapperWidget::load_from_system() void KeyboardMapperWidget::save() { - save_to_file(m_file_name); + save_to_file(m_filename); } -void KeyboardMapperWidget::save_to_file(const StringView& file_name) +void KeyboardMapperWidget::save_to_file(const StringView& filename) { JsonObject map_json; @@ -188,12 +188,12 @@ void KeyboardMapperWidget::save_to_file(const StringView& file_name) // Write to file. String file_content = map_json.to_string(); - auto file = Core::File::construct(file_name); + auto file = Core::File::construct(filename); file->open(Core::IODevice::WriteOnly); if (!file->is_open()) { StringBuilder sb; sb.append("Failed to open "); - sb.append(file_name); + sb.append(filename); sb.append(" for write. Error: "); sb.append(file->error_string()); @@ -213,7 +213,7 @@ void KeyboardMapperWidget::save_to_file(const StringView& file_name) } m_modified = false; - m_file_name = file_name; + m_filename = filename; update_window_title(); } @@ -274,7 +274,7 @@ void KeyboardMapperWidget::set_current_map(const String current_map) void KeyboardMapperWidget::update_window_title() { StringBuilder sb; - sb.append(m_file_name); + sb.append(m_filename); if (m_modified) sb.append(" (*)"); sb.append(" - KeyboardMapper"); diff --git a/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.h b/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.h index cdff3cc0744e..1c11dc17ca5e 100644 --- a/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.h +++ b/Userland/Applications/KeyboardMapper/KeyboardMapperWidget.h @@ -34,7 +34,7 @@ class KeyboardMapperWidget : public GUI::Widget { Vector<KeyButton*> m_keys; RefPtr<GUI::Widget> m_map_group; - String m_file_name; + String m_filename; Keyboard::CharacterMapData m_character_map; String m_current_map_name; bool m_modified { false }; diff --git a/Userland/Applications/KeyboardSettings/CharacterMapFileListModel.h b/Userland/Applications/KeyboardSettings/CharacterMapFileListModel.h index d0585e1c46db..2dc6f3df04a4 100644 --- a/Userland/Applications/KeyboardSettings/CharacterMapFileListModel.h +++ b/Userland/Applications/KeyboardSettings/CharacterMapFileListModel.h @@ -11,16 +11,16 @@ class CharacterMapFileListModel final : public GUI::Model { public: - static NonnullRefPtr<CharacterMapFileListModel> create(Vector<String>& file_names) + static NonnullRefPtr<CharacterMapFileListModel> create(Vector<String>& filenames) { - return adopt_ref(*new CharacterMapFileListModel(file_names)); + return adopt_ref(*new CharacterMapFileListModel(filenames)); } virtual ~CharacterMapFileListModel() override { } virtual int row_count(const GUI::ModelIndex&) const override { - return m_file_names.size(); + return m_filenames.size(); } virtual int column_count(const GUI::ModelIndex&) const override @@ -34,7 +34,7 @@ class CharacterMapFileListModel final : public GUI::Model { VERIFY(index.column() == 0); if (role == GUI::ModelRole::Display) - return m_file_names.at(index.row()); + return m_filenames.at(index.row()); return {}; } @@ -45,10 +45,10 @@ class CharacterMapFileListModel final : public GUI::Model { } private: - explicit CharacterMapFileListModel(Vector<String>& file_names) - : m_file_names(file_names) + explicit CharacterMapFileListModel(Vector<String>& filenames) + : m_filenames(filenames) { } - Vector<String>& m_file_names; + Vector<String>& m_filenames; }; diff --git a/Userland/Applications/Terminal/main.cpp b/Userland/Applications/Terminal/main.cpp index 8f733ecdcf4b..71b0cc81da3b 100644 --- a/Userland/Applications/Terminal/main.cpp +++ b/Userland/Applications/Terminal/main.cpp @@ -329,7 +329,7 @@ int main(int argc, char** argv) } RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("Terminal"); - Core::File::ensure_parent_directories(config->file_name()); + Core::File::ensure_parent_directories(config->filename()); pid_t shell_pid = 0; @@ -485,7 +485,7 @@ int main(int argc, char** argv) return 1; } - if (unveil(config->file_name().characters(), "rwc") < 0) { + if (unveil(config->filename().characters(), "rwc") < 0) { perror("unveil"); return 1; } diff --git a/Userland/DevTools/HackStudio/HackStudioWidget.cpp b/Userland/DevTools/HackStudio/HackStudioWidget.cpp index eacb469d6337..0fafe27a9838 100644 --- a/Userland/DevTools/HackStudio/HackStudioWidget.cpp +++ b/Userland/DevTools/HackStudio/HackStudioWidget.cpp @@ -675,14 +675,14 @@ String HackStudioWidget::get_full_path_of_serenity_source(const String& file) return String::formatted("{}/{}", serenity_sources_base, relative_path_builder.to_string()); } -RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(const String& file_name) +RefPtr<EditorWrapper> HackStudioWidget::get_editor_of_file(const String& filename) { - String file_path = file_name; + String file_path = filename; // TODO: We can probably do a more specific condition here, something like // "if (file.starts_with("../Libraries/") || file.starts_with("../AK/"))" - if (file_name.starts_with("../")) { - file_path = get_full_path_of_serenity_source(file_name); + if (filename.starts_with("../")) { + file_path = get_full_path_of_serenity_source(filename); } if (!open_file(file_path)) diff --git a/Userland/DevTools/HackStudio/HackStudioWidget.h b/Userland/DevTools/HackStudio/HackStudioWidget.h index c3104a66e80b..9cf5e8b6d62c 100644 --- a/Userland/DevTools/HackStudio/HackStudioWidget.h +++ b/Userland/DevTools/HackStudio/HackStudioWidget.h @@ -86,7 +86,7 @@ class HackStudioWidget : public GUI::Widget { NonnullRefPtr<GUI::Action> create_set_autocomplete_mode_action(); void add_new_editor(GUI::Widget& parent); - RefPtr<EditorWrapper> get_editor_of_file(const String& file_name); + RefPtr<EditorWrapper> get_editor_of_file(const String& filename); String get_project_executable_path() const; void on_action_tab_change(); diff --git a/Userland/DevTools/HackStudio/LanguageServers/ClientConnection.cpp b/Userland/DevTools/HackStudio/LanguageServers/ClientConnection.cpp index 601ecf307a3f..6346f865e36d 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/ClientConnection.cpp +++ b/Userland/DevTools/HackStudio/LanguageServers/ClientConnection.cpp @@ -46,28 +46,28 @@ OwnPtr<Messages::LanguageServer::GreetResponse> ClientConnection::handle(const M void ClientConnection::handle(const Messages::LanguageServer::FileOpened& message) { - if (m_filedb.is_open(message.file_name())) { + if (m_filedb.is_open(message.filename())) { return; } - m_filedb.add(message.file_name(), message.file().take_fd()); - m_autocomplete_engine->file_opened(message.file_name()); + m_filedb.add(message.filename(), message.file().take_fd()); + m_autocomplete_engine->file_opened(message.filename()); } void ClientConnection::handle(const Messages::LanguageServer::FileEditInsertText& message) { - dbgln_if(LANGUAGE_SERVER_DEBUG, "InsertText for file: {}", message.file_name()); + dbgln_if(LANGUAGE_SERVER_DEBUG, "InsertText for file: {}", message.filename()); dbgln_if(LANGUAGE_SERVER_DEBUG, "Text: {}", message.text()); dbgln_if(LANGUAGE_SERVER_DEBUG, "[{}:{}]", message.start_line(), message.start_column()); - m_filedb.on_file_edit_insert_text(message.file_name(), message.text(), message.start_line(), message.start_column()); - m_autocomplete_engine->on_edit(message.file_name()); + m_filedb.on_file_edit_insert_text(message.filename(), message.text(), message.start_line(), message.start_column()); + m_autocomplete_engine->on_edit(message.filename()); } void ClientConnection::handle(const Messages::LanguageServer::FileEditRemoveText& message) { - dbgln_if(LANGUAGE_SERVER_DEBUG, "RemoveText for file: {}", message.file_name()); + dbgln_if(LANGUAGE_SERVER_DEBUG, "RemoveText for file: {}", message.filename()); dbgln_if(LANGUAGE_SERVER_DEBUG, "[{}:{} - {}:{}]", message.start_line(), message.start_column(), message.end_line(), message.end_column()); - m_filedb.on_file_edit_remove_text(message.file_name(), message.start_line(), message.start_column(), message.end_line(), message.end_column()); - m_autocomplete_engine->on_edit(message.file_name()); + m_filedb.on_file_edit_remove_text(message.filename(), message.start_line(), message.start_column(), message.end_line(), message.end_column()); + m_autocomplete_engine->on_edit(message.filename()); } void ClientConnection::handle(const Messages::LanguageServer::AutoCompleteSuggestions& message) @@ -87,17 +87,17 @@ void ClientConnection::handle(const Messages::LanguageServer::AutoCompleteSugges void ClientConnection::handle(const Messages::LanguageServer::SetFileContent& message) { - dbgln_if(LANGUAGE_SERVER_DEBUG, "SetFileContent: {}", message.file_name()); - auto document = m_filedb.get(message.file_name()); + dbgln_if(LANGUAGE_SERVER_DEBUG, "SetFileContent: {}", message.filename()); + auto document = m_filedb.get(message.filename()); if (!document) { - m_filedb.add(message.file_name(), message.content()); - VERIFY(m_filedb.is_open(message.file_name())); + m_filedb.add(message.filename(), message.content()); + VERIFY(m_filedb.is_open(message.filename())); } else { const auto& content = message.content(); document->set_text(content.view()); } - VERIFY(m_filedb.is_open(message.file_name())); - m_autocomplete_engine->on_edit(message.file_name()); + VERIFY(m_filedb.is_open(message.filename())); + m_autocomplete_engine->on_edit(message.filename()); } void ClientConnection::handle(const Messages::LanguageServer::FindDeclaration& message) diff --git a/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.cpp b/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.cpp index 29018894ad8b..cb5957e121b1 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.cpp +++ b/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.cpp @@ -337,9 +337,9 @@ void ParserAutoComplete::file_opened([[maybe_unused]] const String& file) set_document_data(file, create_document_data_for(file)); } -Optional<GUI::AutocompleteProvider::ProjectLocation> ParserAutoComplete::find_declaration_of(const String& file_name, const GUI::TextPosition& identifier_position) +Optional<GUI::AutocompleteProvider::ProjectLocation> ParserAutoComplete::find_declaration_of(const String& filename, const GUI::TextPosition& identifier_position) { - const auto* document_ptr = get_or_create_document_data(file_name); + const auto* document_ptr = get_or_create_document_data(filename); if (!document_ptr) return {}; diff --git a/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.h b/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.h index f1e8a103f72c..5d8c4487dbe3 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.h +++ b/Userland/DevTools/HackStudio/LanguageServers/Cpp/ParserAutoComplete.h @@ -28,7 +28,7 @@ class ParserAutoComplete : public AutoCompleteEngine { virtual Vector<GUI::AutocompleteProvider::Entry> get_suggestions(const String& file, const GUI::TextPosition& autocomplete_position) override; virtual void on_edit(const String& file) override; virtual void file_opened([[maybe_unused]] const String& file) override; - virtual Optional<GUI::AutocompleteProvider::ProjectLocation> find_declaration_of(const String& file_name, const GUI::TextPosition& identifier_position) override; + virtual Optional<GUI::AutocompleteProvider::ProjectLocation> find_declaration_of(const String& filename, const GUI::TextPosition& identifier_position) override; private: struct DocumentData { diff --git a/Userland/DevTools/HackStudio/LanguageServers/FileDB.cpp b/Userland/DevTools/HackStudio/LanguageServers/FileDB.cpp index 0dc64cb6a352..13f14959fecd 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/FileDB.cpp +++ b/Userland/DevTools/HackStudio/LanguageServers/FileDB.cpp @@ -11,9 +11,9 @@ namespace LanguageServers { -RefPtr<const GUI::TextDocument> FileDB::get(const String& file_name) const +RefPtr<const GUI::TextDocument> FileDB::get(const String& filename) const { - auto absolute_path = to_absolute_path(file_name); + auto absolute_path = to_absolute_path(filename); auto document_optional = m_open_files.get(absolute_path); if (!document_optional.has_value()) return nullptr; @@ -21,60 +21,60 @@ RefPtr<const GUI::TextDocument> FileDB::get(const String& file_name) const return document_optional.value(); } -RefPtr<GUI::TextDocument> FileDB::get(const String& file_name) +RefPtr<GUI::TextDocument> FileDB::get(const String& filename) { - auto document = reinterpret_cast<const FileDB*>(this)->get(file_name); + auto document = reinterpret_cast<const FileDB*>(this)->get(filename); if (document.is_null()) return nullptr; return adopt_ref(*const_cast<GUI::TextDocument*>(document.leak_ref())); } -RefPtr<const GUI::TextDocument> FileDB::get_or_create_from_filesystem(const String& file_name) const +RefPtr<const GUI::TextDocument> FileDB::get_or_create_from_filesystem(const String& filename) const { - auto absolute_path = to_absolute_path(file_name); + auto absolute_path = to_absolute_path(filename); auto document = get(absolute_path); if (document) return document; return create_from_filesystem(absolute_path); } -RefPtr<GUI::TextDocument> FileDB::get_or_create_from_filesystem(const String& file_name) +RefPtr<GUI::TextDocument> FileDB::get_or_create_from_filesystem(const String& filename) { - auto document = reinterpret_cast<const FileDB*>(this)->get_or_create_from_filesystem(file_name); + auto document = reinterpret_cast<const FileDB*>(this)->get_or_create_from_filesystem(filename); if (document.is_null()) return nullptr; return adopt_ref(*const_cast<GUI::TextDocument*>(document.leak_ref())); } -bool FileDB::is_open(const String& file_name) const +bool FileDB::is_open(const String& filename) const { - return m_open_files.contains(to_absolute_path(file_name)); + return m_open_files.contains(to_absolute_path(filename)); } -bool FileDB::add(const String& file_name, int fd) +bool FileDB::add(const String& filename, int fd) { auto document = create_from_fd(fd); if (!document) return false; - m_open_files.set(to_absolute_path(file_name), document.release_nonnull()); + m_open_files.set(to_absolute_path(filename), document.release_nonnull()); return true; } -String FileDB::to_absolute_path(const String& file_name) const +String FileDB::to_absolute_path(const String& filename) const { - if (LexicalPath { file_name }.is_absolute()) { - return file_name; + if (LexicalPath { filename }.is_absolute()) { + return filename; } VERIFY(!m_project_root.is_null()); - return LexicalPath { String::formatted("{}/{}", m_project_root, file_name) }.string(); + return LexicalPath { String::formatted("{}/{}", m_project_root, filename) }.string(); } -RefPtr<GUI::TextDocument> FileDB::create_from_filesystem(const String& file_name) const +RefPtr<GUI::TextDocument> FileDB::create_from_filesystem(const String& filename) const { - auto file = Core::File::open(to_absolute_path(file_name), Core::IODevice::ReadOnly); + auto file = Core::File::open(to_absolute_path(filename), Core::IODevice::ReadOnly); if (file.is_error()) { - dbgln("failed to create document for {} from filesystem", file_name); + dbgln("failed to create document for {} from filesystem", filename); return nullptr; } return create_from_file(*file.value()); @@ -117,10 +117,10 @@ RefPtr<GUI::TextDocument> FileDB::create_from_file(Core::File& file) const return document; } -void FileDB::on_file_edit_insert_text(const String& file_name, const String& inserted_text, size_t start_line, size_t start_column) +void FileDB::on_file_edit_insert_text(const String& filename, const String& inserted_text, size_t start_line, size_t start_column) { - VERIFY(is_open(file_name)); - auto document = get(file_name); + VERIFY(is_open(filename)); + auto document = get(filename); VERIFY(document); GUI::TextPosition start_position { start_line, start_column }; document->insert_at(start_position, inserted_text, &s_default_document_client); @@ -128,12 +128,12 @@ void FileDB::on_file_edit_insert_text(const String& file_name, const String& ins dbgln_if(FILE_CONTENT_DEBUG, "{}", document->text()); } -void FileDB::on_file_edit_remove_text(const String& file_name, size_t start_line, size_t start_column, size_t end_line, size_t end_column) +void FileDB::on_file_edit_remove_text(const String& filename, size_t start_line, size_t start_column, size_t end_line, size_t end_column) { // TODO: If file is not open - need to get its contents // Otherwise- somehow verify that respawned language server is synced with all file contents - VERIFY(is_open(file_name)); - auto document = get(file_name); + VERIFY(is_open(filename)); + auto document = get(filename); VERIFY(document); GUI::TextPosition start_position { start_line, start_column }; GUI::TextRange range { @@ -153,7 +153,7 @@ RefPtr<GUI::TextDocument> FileDB::create_with_content(const String& content) return document; } -bool FileDB::add(const String& file_name, const String& content) +bool FileDB::add(const String& filename, const String& content) { auto document = create_with_content(content); if (!document) { @@ -161,7 +161,7 @@ bool FileDB::add(const String& file_name, const String& content) return false; } - m_open_files.set(to_absolute_path(file_name), document.release_nonnull()); + m_open_files.set(to_absolute_path(filename), document.release_nonnull()); return true; } diff --git a/Userland/DevTools/HackStudio/LanguageServers/FileDB.h b/Userland/DevTools/HackStudio/LanguageServers/FileDB.h index 8c0b6733a18c..c3eda1b46103 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/FileDB.h +++ b/Userland/DevTools/HackStudio/LanguageServers/FileDB.h @@ -15,22 +15,22 @@ namespace LanguageServers { class FileDB final { public: - RefPtr<const GUI::TextDocument> get(const String& file_name) const; - RefPtr<GUI::TextDocument> get(const String& file_name); - RefPtr<const GUI::TextDocument> get_or_create_from_filesystem(const String& file_name) const; - RefPtr<GUI::TextDocument> get_or_create_from_filesystem(const String& file_name); - bool add(const String& file_name, int fd); - bool add(const String& file_name, const String& content); + RefPtr<const GUI::TextDocument> get(const String& filename) const; + RefPtr<GUI::TextDocument> get(const String& filename); + RefPtr<const GUI::TextDocument> get_or_create_from_filesystem(const String& filename) const; + RefPtr<GUI::TextDocument> get_or_create_from_filesystem(const String& filename); + bool add(const String& filename, int fd); + bool add(const String& filename, const String& content); void set_project_root(const String& root_path) { m_project_root = root_path; } - void on_file_edit_insert_text(const String& file_name, const String& inserted_text, size_t start_line, size_t start_column); - void on_file_edit_remove_text(const String& file_name, size_t start_line, size_t start_column, size_t end_line, size_t end_column); - String to_absolute_path(const String& file_name) const; - bool is_open(const String& file_name) const; + void on_file_edit_insert_text(const String& filename, const String& inserted_text, size_t start_line, size_t start_column); + void on_file_edit_remove_text(const String& filename, size_t start_line, size_t start_column, size_t end_line, size_t end_column); + String to_absolute_path(const String& filename) const; + bool is_open(const String& filename) const; private: - RefPtr<GUI::TextDocument> create_from_filesystem(const String& file_name) const; + RefPtr<GUI::TextDocument> create_from_filesystem(const String& filename) const; RefPtr<GUI::TextDocument> create_from_fd(int fd) const; RefPtr<GUI::TextDocument> create_from_file(Core::File&) const; static RefPtr<GUI::TextDocument> create_with_content(const String&); diff --git a/Userland/DevTools/HackStudio/LanguageServers/LanguageServer.ipc b/Userland/DevTools/HackStudio/LanguageServers/LanguageServer.ipc index 938d616be2af..ea3b3b416ed0 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/LanguageServer.ipc +++ b/Userland/DevTools/HackStudio/LanguageServers/LanguageServer.ipc @@ -2,10 +2,10 @@ endpoint LanguageServer { Greet(String project_root) => () - FileOpened(String file_name, IPC::File file) =| - FileEditInsertText(String file_name, String text, i32 start_line, i32 start_column) =| - FileEditRemoveText(String file_name, i32 start_line, i32 start_column, i32 end_line, i32 end_column) =| - SetFileContent(String file_name, String content) =| + FileOpened(String filename, IPC::File file) =| + FileEditInsertText(String filename, String text, i32 start_line, i32 start_column) =| + FileEditRemoveText(String filename, i32 start_line, i32 start_column, i32 end_line, i32 end_column) =| + SetFileContent(String filename, String content) =| AutoCompleteSuggestions(GUI::AutocompleteProvider::ProjectLocation location) =| SetAutoCompleteMode(String mode) =| diff --git a/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.cpp b/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.cpp index fc00931fa8fe..81182db506e2 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.cpp +++ b/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.cpp @@ -164,10 +164,10 @@ void AutoComplete::file_opened([[maybe_unused]] const String& file) set_document_data(file, create_document_data_for(file)); } -Optional<GUI::AutocompleteProvider::ProjectLocation> AutoComplete::find_declaration_of(const String& file_name, const GUI::TextPosition& identifier_position) +Optional<GUI::AutocompleteProvider::ProjectLocation> AutoComplete::find_declaration_of(const String& filename, const GUI::TextPosition& identifier_position) { - dbgln_if(SH_LANGUAGE_SERVER_DEBUG, "find_declaration_of({}, {}:{})", file_name, identifier_position.line(), identifier_position.column()); - const auto& document = get_or_create_document_data(file_name); + dbgln_if(SH_LANGUAGE_SERVER_DEBUG, "find_declaration_of({}, {}:{})", filename, identifier_position.line(), identifier_position.column()); + const auto& document = get_or_create_document_data(filename); auto position = resolve(document, identifier_position); auto result = document.node->hit_test_position(position); if (!result.matching_node) { diff --git a/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.h b/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.h index de1d3f9d7047..2bfdf0aced22 100644 --- a/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.h +++ b/Userland/DevTools/HackStudio/LanguageServers/Shell/AutoComplete.h @@ -17,7 +17,7 @@ class AutoComplete : public AutoCompleteEngine { virtual Vector<GUI::AutocompleteProvider::Entry> get_suggestions(const String& file, const GUI::TextPosition& position) override; virtual void on_edit(const String& file) override; virtual void file_opened([[maybe_unused]] const String& file) override; - virtual Optional<GUI::AutocompleteProvider::ProjectLocation> find_declaration_of(const String& file_name, const GUI::TextPosition& identifier_position) override; + virtual Optional<GUI::AutocompleteProvider::ProjectLocation> find_declaration_of(const String& filename, const GUI::TextPosition& identifier_position) override; private: struct DocumentData { diff --git a/Userland/DevTools/HackStudio/main.cpp b/Userland/DevTools/HackStudio/main.cpp index 4b9c7013cbcc..547d69ad7a8c 100644 --- a/Userland/DevTools/HackStudio/main.cpp +++ b/Userland/DevTools/HackStudio/main.cpp @@ -132,14 +132,14 @@ GUI::TextEditor& current_editor() return s_hack_studio_widget->current_editor(); } -void open_file(const String& file_name) +void open_file(const String& filename) { - s_hack_studio_widget->open_file(file_name); + s_hack_studio_widget->open_file(filename); } -void open_file(const String& file_name, size_t line, size_t column) +void open_file(const String& filename, size_t line, size_t column) { - s_hack_studio_widget->open_file(file_name); + s_hack_studio_widget->open_file(filename); s_hack_studio_widget->current_editor_wrapper().editor().set_cursor({ line, column }); } diff --git a/Userland/Games/2048/main.cpp b/Userland/Games/2048/main.cpp index 99054b147032..4c12afe699c3 100644 --- a/Userland/Games/2048/main.cpp +++ b/Userland/Games/2048/main.cpp @@ -56,7 +56,7 @@ int main(int argc, char** argv) return 1; } - if (unveil(config->file_name().characters(), "crw") < 0) { + if (unveil(config->filename().characters(), "crw") < 0) { perror("unveil"); return 1; } diff --git a/Userland/Games/Chess/main.cpp b/Userland/Games/Chess/main.cpp index 928d7990f396..4747a14996a4 100644 --- a/Userland/Games/Chess/main.cpp +++ b/Userland/Games/Chess/main.cpp @@ -38,7 +38,7 @@ int main(int argc, char** argv) return 1; } - if (unveil(config->file_name().characters(), "crw") < 0) { + if (unveil(config->filename().characters(), "crw") < 0) { perror("unveil"); return 1; } diff --git a/Userland/Games/Minesweeper/main.cpp b/Userland/Games/Minesweeper/main.cpp index 424adf59cbd7..c6a1d1994a38 100644 --- a/Userland/Games/Minesweeper/main.cpp +++ b/Userland/Games/Minesweeper/main.cpp @@ -40,7 +40,7 @@ int main(int argc, char** argv) return 1; } - if (unveil(config->file_name().characters(), "crw") < 0) { + if (unveil(config->filename().characters(), "crw") < 0) { perror("unveil"); return 1; } diff --git a/Userland/Games/Pong/main.cpp b/Userland/Games/Pong/main.cpp index d7cce5901ee4..6451b5d3ec17 100644 --- a/Userland/Games/Pong/main.cpp +++ b/Userland/Games/Pong/main.cpp @@ -35,7 +35,7 @@ int main(int argc, char** argv) return 1; } - if (unveil(config->file_name().characters(), "rwc") < 0) { + if (unveil(config->filename().characters(), "rwc") < 0) { perror("unveil"); return 1; } diff --git a/Userland/Games/Snake/main.cpp b/Userland/Games/Snake/main.cpp index 13674ea302e2..ae10a8b7a158 100644 --- a/Userland/Games/Snake/main.cpp +++ b/Userland/Games/Snake/main.cpp @@ -38,7 +38,7 @@ int main(int argc, char** argv) return 1; } - if (unveil(config->file_name().characters(), "crw") < 0) { + if (unveil(config->filename().characters(), "crw") < 0) { perror("unveil"); return 1; } diff --git a/Userland/Libraries/LibArchive/Tar.h b/Userland/Libraries/LibArchive/Tar.h index 4d2867193b1c..de3118b983a6 100644 --- a/Userland/Libraries/LibArchive/Tar.h +++ b/Userland/Libraries/LibArchive/Tar.h @@ -38,7 +38,7 @@ constexpr const char* posix1_tar_version = ""; // POSIX.1-1988 format version class [[gnu::packed]] TarFileHeader { public: - const StringView file_name() const { return m_file_name; } + const StringView filename() const { return m_filename; } mode_t mode() const { return get_tar_field(m_mode); } uid_t uid() const { return get_tar_field(m_uid); } gid_t gid() const { return get_tar_field(m_gid); } @@ -57,7 +57,7 @@ class [[gnu::packed]] TarFileHeader { // FIXME: support ustar filename prefix const StringView prefix() const { return m_prefix; } - void set_file_name(const String& file_name) { VERIFY(file_name.copy_characters_to_buffer(m_file_name, sizeof(m_file_name))); } + void set_filename(const String& filename) { VERIFY(filename.copy_characters_to_buffer(m_filename, sizeof(m_filename))); } void set_mode(mode_t mode) { VERIFY(String::formatted("{:o}", mode).copy_characters_to_buffer(m_mode, sizeof(m_mode))); } void set_uid(uid_t uid) { VERIFY(String::formatted("{:o}", uid).copy_characters_to_buffer(m_uid, sizeof(m_uid))); } void set_gid(gid_t gid) { VERIFY(String::formatted("{:o}", gid).copy_characters_to_buffer(m_gid, sizeof(m_gid))); } @@ -77,7 +77,7 @@ class [[gnu::packed]] TarFileHeader { void calculate_checksum(); private: - char m_file_name[100]; + char m_filename[100]; char m_mode[8]; char m_uid[8]; char m_gid[8]; diff --git a/Userland/Libraries/LibArchive/TarStream.cpp b/Userland/Libraries/LibArchive/TarStream.cpp index bb892fea7e94..5db912b6b20d 100644 --- a/Userland/Libraries/LibArchive/TarStream.cpp +++ b/Userland/Libraries/LibArchive/TarStream.cpp @@ -132,7 +132,7 @@ void TarOutputStream::add_directory(const String& path, mode_t mode) TarFileHeader header; memset(&header, 0, sizeof(header)); header.set_size(0); - header.set_file_name(String::formatted("{}/", path)); // Old tar implementations assume directory names end with a / + header.set_filename(String::formatted("{}/", path)); // Old tar implementations assume directory names end with a / header.set_type_flag(TarFileType::Directory); header.set_mode(mode); header.set_magic(gnu_magic); @@ -149,7 +149,7 @@ void TarOutputStream::add_file(const String& path, mode_t mode, const ReadonlyBy TarFileHeader header; memset(&header, 0, sizeof(header)); header.set_size(bytes.size()); - header.set_file_name(path); + header.set_filename(path); header.set_type_flag(TarFileType::NormalFile); header.set_mode(mode); header.set_magic(gnu_magic); diff --git a/Userland/Libraries/LibCore/ConfigFile.cpp b/Userland/Libraries/LibCore/ConfigFile.cpp index 7bb69df9acb9..5bbf8fae2132 100644 --- a/Userland/Libraries/LibCore/ConfigFile.cpp +++ b/Userland/Libraries/LibCore/ConfigFile.cpp @@ -41,8 +41,8 @@ NonnullRefPtr<ConfigFile> ConfigFile::open(const String& path) return adopt_ref(*new ConfigFile(path)); } -ConfigFile::ConfigFile(const String& file_name) - : m_file_name(file_name) +ConfigFile::ConfigFile(const String& filename) + : m_filename(filename) { reparse(); } @@ -56,7 +56,7 @@ void ConfigFile::reparse() { m_groups.clear(); - auto file = File::construct(m_file_name); + auto file = File::construct(m_filename); if (!file->open(IODevice::OpenMode::ReadOnly)) return; @@ -151,7 +151,7 @@ bool ConfigFile::sync() if (!m_dirty) return true; - FILE* fp = fopen(m_file_name.characters(), "wb"); + FILE* fp = fopen(m_filename.characters(), "wb"); if (!fp) return false; diff --git a/Userland/Libraries/LibCore/ConfigFile.h b/Userland/Libraries/LibCore/ConfigFile.h index 862cd6255d77..0610f39e0ca2 100644 --- a/Userland/Libraries/LibCore/ConfigFile.h +++ b/Userland/Libraries/LibCore/ConfigFile.h @@ -47,14 +47,14 @@ class ConfigFile : public RefCounted<ConfigFile> { void remove_group(const String& group); void remove_entry(const String& group, const String& key); - String file_name() const { return m_file_name; } + String filename() const { return m_filename; } private: - explicit ConfigFile(const String& file_name); + explicit ConfigFile(const String& filename); void reparse(); - String m_file_name; + String m_filename; HashMap<String, HashMap<String, String>> m_groups; bool m_dirty { false }; }; diff --git a/Userland/Libraries/LibDebug/DebugSession.cpp b/Userland/Libraries/LibDebug/DebugSession.cpp index 55a2c6874ab7..b05494705a52 100644 --- a/Userland/Libraries/LibDebug/DebugSession.cpp +++ b/Userland/Libraries/LibDebug/DebugSession.cpp @@ -372,9 +372,9 @@ Optional<DebugSession::InsertBreakpointAtSymbolResult> DebugSession::insert_brea return result; } -Optional<DebugSession::InsertBreakpointAtSourcePositionResult> DebugSession::insert_breakpoint(const String& file_name, size_t line_number) +Optional<DebugSession::InsertBreakpointAtSourcePositionResult> DebugSession::insert_breakpoint(const String& filename, size_t line_number) { - auto address_and_source_position = get_address_from_source_position(file_name, line_number); + auto address_and_source_position = get_address_from_source_position(filename, line_number); if (!address_and_source_position.has_value()) return {}; diff --git a/Userland/Libraries/LibDebug/DebugSession.h b/Userland/Libraries/LibDebug/DebugSession.h index 0e9057cb3c54..dac76d5387f4 100644 --- a/Userland/Libraries/LibDebug/DebugSession.h +++ b/Userland/Libraries/LibDebug/DebugSession.h @@ -57,12 +57,12 @@ class DebugSession { struct InsertBreakpointAtSourcePositionResult { String library_name; - String file_name; + String filename; size_t line_number { 0 }; FlatPtr address { 0 }; }; - Optional<InsertBreakpointAtSourcePositionResult> insert_breakpoint(const String& file_name, size_t line_number); + Optional<InsertBreakpointAtSourcePositionResult> insert_breakpoint(const String& filename, size_t line_number); bool insert_breakpoint(void* address); bool disable_breakpoint(void* address); diff --git a/Userland/Libraries/LibDesktop/AppFile.h b/Userland/Libraries/LibDesktop/AppFile.h index 5f847ec3e61a..2172601a49e3 100644 --- a/Userland/Libraries/LibDesktop/AppFile.h +++ b/Userland/Libraries/LibDesktop/AppFile.h @@ -21,7 +21,7 @@ class AppFile : public RefCounted<AppFile> { ~AppFile(); bool is_valid() const { return m_valid; } - String file_name() const { return m_config->file_name(); } + String filename() const { return m_config->filename(); } String name() const; String executable() const; diff --git a/Userland/Libraries/LibDl/dlfcn.cpp b/Userland/Libraries/LibDl/dlfcn.cpp index cde41168d5a1..ef730e845d89 100644 --- a/Userland/Libraries/LibDl/dlfcn.cpp +++ b/Userland/Libraries/LibDl/dlfcn.cpp @@ -41,9 +41,9 @@ char* dlerror() return const_cast<char*>(s_dlerror_text); } -void* dlopen(const char* file_name, int flags) +void* dlopen(const char* filename, int flags) { - auto result = __dlopen(file_name, flags); + auto result = __dlopen(filename, flags); if (result.is_error()) { store_error(result.error().text); return nullptr; diff --git a/Userland/Libraries/LibELF/AuxiliaryVector.h b/Userland/Libraries/LibELF/AuxiliaryVector.h index bad82fadf95f..3524e9c9fbc1 100644 --- a/Userland/Libraries/LibELF/AuxiliaryVector.h +++ b/Userland/Libraries/LibELF/AuxiliaryVector.h @@ -42,7 +42,7 @@ typedef struct #define AT_BASE_PLATFORM 24 /* a_ptr points to a string identifying base platform name, which might be different from platform (e.g x86_64 when in i386 compat) */ #define AT_RANDOM 25 /* a_ptr points to 16 securely generated random bytes */ #define AT_HWCAP2 26 /* a_val holds extended hw feature mask. Currently 0 */ -#define AT_EXECFN 31 /* a_ptr points to file name of executed program */ +#define AT_EXECFN 31 /* a_ptr points to filename of executed program */ #define AT_EXE_BASE 32 /* a_ptr holds base address where main program was loaded into memory */ #define AT_EXE_SIZE 33 /* a_val holds the size of the main program in memory */ diff --git a/Userland/Libraries/LibGUI/Desktop.cpp b/Userland/Libraries/LibGUI/Desktop.cpp index 024a1d3cac51..77d40ed2b3f6 100644 --- a/Userland/Libraries/LibGUI/Desktop.cpp +++ b/Userland/Libraries/LibGUI/Desktop.cpp @@ -49,7 +49,7 @@ bool Desktop::set_wallpaper(const StringView& path, bool save_config) if (ret_val && save_config) { RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("WindowManager"); - dbgln("Saving wallpaper path '{}' to config file at {}", path, config->file_name()); + dbgln("Saving wallpaper path '{}' to config file at {}", path, config->filename()); config->write_entry("Background", "Wallpaper", path); config->sync(); } diff --git a/Userland/Libraries/LibGUI/FilePicker.cpp b/Userland/Libraries/LibGUI/FilePicker.cpp index 1685dcacea7c..0abf77d6b61b 100644 --- a/Userland/Libraries/LibGUI/FilePicker.cpp +++ b/Userland/Libraries/LibGUI/FilePicker.cpp @@ -62,7 +62,7 @@ Optional<String> FilePicker::get_save_filepath(Window* parent_window, const Stri return {}; } -FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& file_name, const StringView& path) +FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& filename, const StringView& path) : Dialog(parent_window) , m_model(FileSystemModel::create()) , m_mode(mode) @@ -148,7 +148,7 @@ FilePicker::FilePicker(Window* parent_window, Mode mode, const StringView& file_ m_filename_textbox = *widget.find_descendant_of_type_named<GUI::TextBox>("filename_textbox"); m_filename_textbox->set_focus(true); if (m_mode == Mode::Save) { - m_filename_textbox->set_text(file_name); + m_filename_textbox->set_text(filename); m_filename_textbox->select_all(); } m_filename_textbox->on_return_pressed = [&] { diff --git a/Userland/Libraries/LibGUI/FilePicker.h b/Userland/Libraries/LibGUI/FilePicker.h index 595a6465221e..93edc3413685 100644 --- a/Userland/Libraries/LibGUI/FilePicker.h +++ b/Userland/Libraries/LibGUI/FilePicker.h @@ -43,7 +43,7 @@ class FilePicker final // ^GUI::ModelClient virtual void model_did_update(unsigned) override; - FilePicker(Window* parent_window, Mode type = Mode::Open, const StringView& file_name = "Untitled", const StringView& path = Core::StandardPaths::home_directory()); + FilePicker(Window* parent_window, Mode type = Mode::Open, const StringView& filename = "Untitled", const StringView& path = Core::StandardPaths::home_directory()); static String ok_button_name(Mode mode) { diff --git a/Userland/Libraries/LibGUI/FilePickerDialog.gml b/Userland/Libraries/LibGUI/FilePickerDialog.gml index 6bac8140ccfa..cd291fac5bc4 100644 --- a/Userland/Libraries/LibGUI/FilePickerDialog.gml +++ b/Userland/Libraries/LibGUI/FilePickerDialog.gml @@ -30,7 +30,7 @@ } @GUI::Label { - text: "File name:" + text: "Filename:" text_alignment: "CenterRight" fixed_height: 24 } diff --git a/Userland/Libraries/LibKeyboard/CharacterMap.h b/Userland/Libraries/LibKeyboard/CharacterMap.h index 48407cf20e56..d12c1f4940d2 100644 --- a/Userland/Libraries/LibKeyboard/CharacterMap.h +++ b/Userland/Libraries/LibKeyboard/CharacterMap.h @@ -20,7 +20,7 @@ class CharacterMap { public: CharacterMap(const String& map_name, const CharacterMapData& map_data); - static Optional<CharacterMap> load_from_file(const String& file_name); + static Optional<CharacterMap> load_from_file(const String& filename); #ifndef KERNEL int set_system_map(); diff --git a/Userland/Libraries/LibKeyboard/CharacterMapFile.cpp b/Userland/Libraries/LibKeyboard/CharacterMapFile.cpp index cdefe2402350..05fb406383d5 100644 --- a/Userland/Libraries/LibKeyboard/CharacterMapFile.cpp +++ b/Userland/Libraries/LibKeyboard/CharacterMapFile.cpp @@ -11,13 +11,13 @@ namespace Keyboard { -Optional<CharacterMapData> CharacterMapFile::load_from_file(const String& file_name) +Optional<CharacterMapData> CharacterMapFile::load_from_file(const String& filename) { - auto path = file_name; + auto path = filename; if (!path.ends_with(".json")) { StringBuilder full_path; full_path.append("/res/keymaps/"); - full_path.append(file_name); + full_path.append(filename); full_path.append(".json"); path = full_path.to_string(); } @@ -25,7 +25,7 @@ Optional<CharacterMapData> CharacterMapFile::load_from_file(const String& file_n auto file = Core::File::construct(path); file->open(Core::IODevice::ReadOnly); if (!file->is_open()) { - dbgln("Failed to open {}: {}", file_name, file->error_string()); + dbgln("Failed to open {}: {}", filename, file->error_string()); return {}; } diff --git a/Userland/Libraries/LibKeyboard/CharacterMapFile.h b/Userland/Libraries/LibKeyboard/CharacterMapFile.h index 361901f13ceb..c11800d61298 100644 --- a/Userland/Libraries/LibKeyboard/CharacterMapFile.h +++ b/Userland/Libraries/LibKeyboard/CharacterMapFile.h @@ -14,7 +14,7 @@ namespace Keyboard { class CharacterMapFile { public: - static Optional<CharacterMapData> load_from_file(const String& file_name); + static Optional<CharacterMapData> load_from_file(const String& filename); private: static Vector<u32> read_map(const JsonObject& json, const String& name); diff --git a/Userland/Libraries/LibPCIDB/Database.cpp b/Userland/Libraries/LibPCIDB/Database.cpp index 3821049d6894..4282afd84cda 100644 --- a/Userland/Libraries/LibPCIDB/Database.cpp +++ b/Userland/Libraries/LibPCIDB/Database.cpp @@ -12,9 +12,9 @@ namespace PCIDB { -RefPtr<Database> Database::open(const String& file_name) +RefPtr<Database> Database::open(const String& filename) { - auto file_or_error = MappedFile::map(file_name); + auto file_or_error = MappedFile::map(filename); if (file_or_error.is_error()) return nullptr; auto res = adopt_ref(*new Database(file_or_error.release_value())); diff --git a/Userland/Libraries/LibPCIDB/Database.h b/Userland/Libraries/LibPCIDB/Database.h index 704d643f89b5..01a0073c8d10 100644 --- a/Userland/Libraries/LibPCIDB/Database.h +++ b/Userland/Libraries/LibPCIDB/Database.h @@ -53,7 +53,7 @@ struct Class { class Database : public RefCounted<Database> { public: - static RefPtr<Database> open(const String& file_name); + static RefPtr<Database> open(const String& filename); static RefPtr<Database> open() { return open("/res/pci.ids"); }; const StringView get_vendor(u16 vendor_id) const; diff --git a/Userland/Libraries/LibVT/TerminalWidget.cpp b/Userland/Libraries/LibVT/TerminalWidget.cpp index 328fbd602a0d..db287562eb46 100644 --- a/Userland/Libraries/LibVT/TerminalWidget.cpp +++ b/Userland/Libraries/LibVT/TerminalWidget.cpp @@ -93,7 +93,7 @@ TerminalWidget::TerminalWidget(int ptm_fd, bool automatic_size_policy, RefPtr<Co update(); }; - dbgln("Load config file from {}", m_config->file_name()); + dbgln("Load config file from {}", m_config->filename()); m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text", "CursorBlinkInterval", 500)); diff --git a/Userland/Services/LookupServer/LookupServer.cpp b/Userland/Services/LookupServer/LookupServer.cpp index 442f0090596a..cac9f0f28ec8 100644 --- a/Userland/Services/LookupServer/LookupServer.cpp +++ b/Userland/Services/LookupServer/LookupServer.cpp @@ -37,7 +37,7 @@ LookupServer::LookupServer() s_the = this; auto config = Core::ConfigFile::get_for_system("LookupServer"); - dbgln("Using network config file at {}", config->file_name()); + dbgln("Using network config file at {}", config->filename()); m_nameservers = config->read_entry("DNS", "Nameservers", "1.1.1.1,1.0.0.1").split(','); load_etc_hosts(); diff --git a/Userland/Services/WindowServer/Cursor.cpp b/Userland/Services/WindowServer/Cursor.cpp index 9722be3390a0..a62ebe3bfc8c 100644 --- a/Userland/Services/WindowServer/Cursor.cpp +++ b/Userland/Services/WindowServer/Cursor.cpp @@ -10,7 +10,7 @@ namespace WindowServer { -CursorParams CursorParams::parse_from_file_name(const StringView& cursor_path, const Gfx::IntPoint& default_hotspot) +CursorParams CursorParams::parse_from_filename(const StringView& cursor_path, const Gfx::IntPoint& default_hotspot) { LexicalPath path(cursor_path); if (!path.is_valid()) { @@ -123,7 +123,7 @@ NonnullRefPtr<Cursor> Cursor::create(NonnullRefPtr<Gfx::Bitmap>&& bitmap) NonnullRefPtr<Cursor> Cursor::create(NonnullRefPtr<Gfx::Bitmap>&& bitmap, const StringView& filename) { auto default_hotspot = bitmap->rect().center(); - return adopt_ref(*new Cursor(move(bitmap), CursorParams::parse_from_file_name(filename, default_hotspot))); + return adopt_ref(*new Cursor(move(bitmap), CursorParams::parse_from_filename(filename, default_hotspot))); } RefPtr<Cursor> Cursor::create(Gfx::StandardCursor standard_cursor) diff --git a/Userland/Services/WindowServer/Cursor.h b/Userland/Services/WindowServer/Cursor.h index c615396e253c..a6f237f18169 100644 --- a/Userland/Services/WindowServer/Cursor.h +++ b/Userland/Services/WindowServer/Cursor.h @@ -13,7 +13,7 @@ namespace WindowServer { class CursorParams { public: - static CursorParams parse_from_file_name(const StringView&, const Gfx::IntPoint&); + static CursorParams parse_from_filename(const StringView&, const Gfx::IntPoint&); CursorParams(const Gfx::IntPoint& hotspot) : m_hotspot(hotspot) { diff --git a/Userland/Services/WindowServer/WindowManager.cpp b/Userland/Services/WindowServer/WindowManager.cpp index 30daf61036f8..1986507e2bd8 100644 --- a/Userland/Services/WindowServer/WindowManager.cpp +++ b/Userland/Services/WindowServer/WindowManager.cpp @@ -116,13 +116,13 @@ bool WindowManager::set_resolution(int width, int height, int scale) } if (m_config) { if (success) { - dbgln("Saving resolution: {} @ {}x to config file at {}", Gfx::IntSize(width, height), scale, m_config->file_name()); + dbgln("Saving resolution: {} @ {}x to config file at {}", Gfx::IntSize(width, height), scale, m_config->filename()); m_config->write_num_entry("Screen", "Width", width); m_config->write_num_entry("Screen", "Height", height); m_config->write_num_entry("Screen", "ScaleFactor", scale); m_config->sync(); } else { - dbgln("Saving fallback resolution: {} @1x to config file at {}", resolution(), m_config->file_name()); + dbgln("Saving fallback resolution: {} @1x to config file at {}", resolution(), m_config->filename()); m_config->write_num_entry("Screen", "Width", resolution().width()); m_config->write_num_entry("Screen", "Height", resolution().height()); m_config->write_num_entry("Screen", "ScaleFactor", 1); @@ -140,7 +140,7 @@ Gfx::IntSize WindowManager::resolution() const void WindowManager::set_acceleration_factor(double factor) { Screen::the().set_acceleration_factor(factor); - dbgln("Saving acceleration factor {} to config file at {}", factor, m_config->file_name()); + dbgln("Saving acceleration factor {} to config file at {}", factor, m_config->filename()); m_config->write_entry("Mouse", "AccelerationFactor", String::formatted("{}", factor)); m_config->sync(); } @@ -148,7 +148,7 @@ void WindowManager::set_acceleration_factor(double factor) void WindowManager::set_scroll_step_size(unsigned step_size) { Screen::the().set_scroll_step_size(step_size); - dbgln("Saving scroll step size {} to config file at {}", step_size, m_config->file_name()); + dbgln("Saving scroll step size {} to config file at {}", step_size, m_config->filename()); m_config->write_entry("Mouse", "ScrollStepSize", String::number(step_size)); m_config->sync(); } @@ -157,7 +157,7 @@ void WindowManager::set_double_click_speed(int speed) { VERIFY(speed >= double_click_speed_min && speed <= double_click_speed_max); m_double_click_speed = speed; - dbgln("Saving double-click speed {} to config file at {}", speed, m_config->file_name()); + dbgln("Saving double-click speed {} to config file at {}", speed, m_config->filename()); m_config->write_entry("Input", "DoubleClickSpeed", String::number(speed)); m_config->sync(); } diff --git a/Userland/Utilities/head.cpp b/Userland/Utilities/head.cpp index d51b66f6a288..8455dedc23d1 100644 --- a/Userland/Utilities/head.cpp +++ b/Userland/Utilities/head.cpp @@ -30,8 +30,8 @@ int main(int argc, char** argv) args_parser.set_general_help("Print the beginning ('head') of a file."); args_parser.add_option(line_count, "Number of lines to print (default 10)", "lines", 'n', "number"); args_parser.add_option(char_count, "Number of characters to print", "characters", 'c', "number"); - args_parser.add_option(never_print_filenames, "Never print file names", "quiet", 'q'); - args_parser.add_option(always_print_filenames, "Always print file names", "verbose", 'v'); + args_parser.add_option(never_print_filenames, "Never print filenames", "quiet", 'q'); + args_parser.add_option(always_print_filenames, "Always print filenames", "verbose", 'v'); args_parser.add_positional_argument(files, "File to process", "file", Core::ArgsParser::Required::No); args_parser.parse(argc, argv); diff --git a/Userland/Utilities/js.cpp b/Userland/Utilities/js.cpp index b2f2ed09fe3b..3045f2d5d68d 100644 --- a/Userland/Utilities/js.cpp +++ b/Userland/Utilities/js.cpp @@ -574,8 +574,8 @@ JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help) outln("REPL commands:"); outln(" exit(code): exit the REPL with specified code. Defaults to 0."); outln(" help(): display this menu"); - outln(" load(files): accepts file names as params to load into running session. For example load(\"js/1.js\", \"js/2.js\", \"js/3.js\")"); - outln(" save(file): accepts a file name, writes REPL input history to a file. For example: save(\"foo.txt\")"); + outln(" load(files): accepts filenames as params to load into running session. For example load(\"js/1.js\", \"js/2.js\", \"js/3.js\")"); + outln(" save(file): accepts a filename, writes REPL input history to a file. For example: save(\"foo.txt\")"); return JS::js_undefined(); } @@ -585,10 +585,10 @@ JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file) return JS::Value(false); for (auto& file : vm.call_frame().arguments) { - String file_name = file.as_string().string(); - auto js_file = Core::File::construct(file_name); + String filename = file.as_string().string(); + auto js_file = Core::File::construct(filename); if (!js_file->open(Core::IODevice::ReadOnly)) { - warnln("Failed to open {}: {}", file_name, js_file->error_string()); + warnln("Failed to open {}: {}", filename, js_file->error_string()); continue; } auto file_contents = js_file->read_all(); diff --git a/Userland/Utilities/lsof.cpp b/Userland/Utilities/lsof.cpp index e67eeb06a120..7cb86a9625fa 100644 --- a/Userland/Utilities/lsof.cpp +++ b/Userland/Utilities/lsof.cpp @@ -124,7 +124,7 @@ int main(int argc, char* argv[]) int arg_uid_int = -1; int arg_pgid { -1 }; pid_t arg_pid { -1 }; - const char* arg_file_name { nullptr }; + const char* arg_filename { nullptr }; if (argc == 1) arg_all_processes = true; @@ -135,7 +135,7 @@ int main(int argc, char* argv[]) parser.add_option(arg_fd, "Select by file descriptor", nullptr, 'd', "fd"); parser.add_option(arg_uid, "Select by login/UID", nullptr, 'u', "login/UID"); parser.add_option(arg_pgid, "Select by process group ID", nullptr, 'g', "PGID"); - parser.add_positional_argument(arg_file_name, "File name", "file name", Core::ArgsParser::Required::No); + parser.add_positional_argument(arg_filename, "Filename", "filename", Core::ArgsParser::Required::No); parser.parse(argc, argv); } { @@ -164,7 +164,7 @@ int main(int argc, char* argv[]) || (arg_uid_int != -1 && (int)process.value.uid == arg_uid_int) || (arg_uid != nullptr && process.value.username == arg_uid) || (arg_pgid != -1 && (int)process.value.pgid == arg_pgid) - || (arg_file_name != nullptr && file.name == arg_file_name)) + || (arg_filename != nullptr && file.name == arg_filename)) display_entry(file, process.value); } } diff --git a/Userland/Utilities/md.cpp b/Userland/Utilities/md.cpp index 306830756cd8..564ae282ca0c 100644 --- a/Userland/Utilities/md.cpp +++ b/Userland/Utilities/md.cpp @@ -22,7 +22,7 @@ int main(int argc, char* argv[]) return 1; } - const char* file_name = nullptr; + const char* filename = nullptr; bool html = false; int view_width = 0; @@ -30,7 +30,7 @@ int main(int argc, char* argv[]) args_parser.set_general_help("Render Markdown to some other format."); args_parser.add_option(html, "Render to HTML rather than for the terminal", "html", 'H'); args_parser.add_option(view_width, "Viewport width for the terminal (defaults to current terminal width)", "view-width", 0, "width"); - args_parser.add_positional_argument(file_name, "Path to Markdown file", "path", Core::ArgsParser::Required::No); + args_parser.add_positional_argument(filename, "Path to Markdown file", "path", Core::ArgsParser::Required::No); args_parser.parse(argc, argv); if (!html && view_width == 0) { @@ -47,10 +47,10 @@ int main(int argc, char* argv[]) } auto file = Core::File::construct(); bool success; - if (file_name == nullptr) { + if (filename == nullptr) { success = file->open(STDIN_FILENO, Core::IODevice::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No); } else { - file->set_filename(file_name); + file->set_filename(filename); success = file->open(Core::IODevice::OpenMode::ReadOnly); } if (!success) { diff --git a/Userland/Utilities/pathchk.cpp b/Userland/Utilities/pathchk.cpp index d4ff7fc9aa39..77caa9757059 100644 --- a/Userland/Utilities/pathchk.cpp +++ b/Userland/Utilities/pathchk.cpp @@ -42,17 +42,17 @@ int main(int argc, char** argv) unsigned long name_max = flag_most_posix ? _POSIX_NAME_MAX : pathconf(str_path.characters(), _PC_NAME_MAX); if (str_path.length() > path_max) { - warnln("{}: limit {} exceeded by length {} of file name '{}'", argv[0], path_max, str_path.length(), str_path); + warnln("{}: limit {} exceeded by length {} of filename '{}'", argv[0], path_max, str_path.length(), str_path); fail = true; continue; } if (flag_most_posix) { - // POSIX portable file name character set (a-z A-Z 0-9 . _ -) + // POSIX portable filename character set (a-z A-Z 0-9 . _ -) for (long unsigned i = 0; i < str_path.length(); ++i) { auto c = path[i]; if (!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && c != '/' && c != '.' && c != '-' && c != '_') { - warnln("{}: non-portable character '{}' in file name '{}'", argv[0], path[i], str_path); + warnln("{}: non-portable character '{}' in filename '{}'", argv[0], path[i], str_path); fail = true; continue; } @@ -70,7 +70,7 @@ int main(int argc, char** argv) if (flag_empty_name_and_leading_dash) { if (str_path.is_empty()) { - warnln("{}: empty file name", argv[0]); + warnln("{}: empty filename", argv[0]); fail = true; continue; } @@ -79,13 +79,13 @@ int main(int argc, char** argv) for (auto& component : str_path.split('/')) { if (flag_empty_name_and_leading_dash) { if (component.starts_with('-')) { - warnln("{}: leading '-' in a component of file name '{}'", argv[0], str_path); + warnln("{}: leading '-' in a component of filename '{}'", argv[0], str_path); fail = true; break; } } if (component.length() > name_max) { - warnln("{}: limit {} exceeded by length {} of file name component '{}'", argv[0], name_max, component.length(), component.characters()); + warnln("{}: limit {} exceeded by length {} of filename component '{}'", argv[0], name_max, component.length(), component.characters()); fail = true; break; } diff --git a/Userland/Utilities/tar.cpp b/Userland/Utilities/tar.cpp index 7877787b3745..18ed93681cdc 100644 --- a/Userland/Utilities/tar.cpp +++ b/Userland/Utilities/tar.cpp @@ -68,7 +68,7 @@ int main(int argc, char** argv) } for (; !tar_stream.finished(); tar_stream.advance()) { if (list || verbose) - outln("{}", tar_stream.header().file_name()); + outln("{}", tar_stream.header().filename()); if (extract) { Archive::TarFileStream file_stream = tar_stream.file_contents(); @@ -77,7 +77,7 @@ int main(int argc, char** argv) switch (header.type_flag()) { case Archive::TarFileType::NormalFile: case Archive::TarFileType::AlternateNormalFile: { - int fd = open(String(header.file_name()).characters(), O_CREAT | O_WRONLY, header.mode()); + int fd = open(String(header.filename()).characters(), O_CREAT | O_WRONLY, header.mode()); if (fd < 0) { perror("open"); return 1; @@ -95,7 +95,7 @@ int main(int argc, char** argv) break; } case Archive::TarFileType::Directory: { - if (mkdir(String(header.file_name()).characters(), header.mode())) { + if (mkdir(String(header.filename()).characters(), header.mode())) { perror("mkdir"); return 1; } diff --git a/Userland/Utilities/test-crypto.cpp b/Userland/Utilities/test-crypto.cpp index bc676de168b5..191d85ddb185 100644 --- a/Userland/Utilities/test-crypto.cpp +++ b/Userland/Utilities/test-crypto.cpp @@ -128,7 +128,7 @@ static int run(Function<void(const char*, size_t)> fn) } } else { if (filename == nullptr) { - puts("must specify a file name"); + puts("must specify a filename"); return 1; } if (!Core::File::exists(filename)) {
f48651fccc56cafdcc0ab56a63fd44c2c171f976
2022-08-16 18:28:51
kleines Filmröllchen
libcore: Add MIME sniffing for MP3 and WAV
false
Add MIME sniffing for MP3 and WAV
libcore
diff --git a/Userland/Libraries/LibCore/MimeData.cpp b/Userland/Libraries/LibCore/MimeData.cpp index 5fcc8b3d7356..6d802974fbd9 100644 --- a/Userland/Libraries/LibCore/MimeData.cpp +++ b/Userland/Libraries/LibCore/MimeData.cpp @@ -128,6 +128,7 @@ String guess_mime_type_based_on_filename(StringView path) __ENUMERATE_MIME_TYPE_HEADER(lua_bytecode, "extra/lua-bytecode", 0, 4, 0x1B, 'L', 'u', 'a') \ __ENUMERATE_MIME_TYPE_HEADER(midi, "audio/midi", 0, 4, 0x4D, 0x54, 0x68, 0x64) \ __ENUMERATE_MIME_TYPE_HEADER(mkv, "extra/matroska", 0, 4, 0x1A, 0x45, 0xDF, 0xA3) \ + __ENUMERATE_MIME_TYPE_HEADER(mp3, "audio/mpeg", 0, 2, 0xFF, 0xFB) \ __ENUMERATE_MIME_TYPE_HEADER(nesrom, "extra/nes-rom", 0, 4, 'N', 'E', 'S', 0x1A) \ __ENUMERATE_MIME_TYPE_HEADER(pbm, "image/x-portable-bitmap", 0, 3, 0x50, 0x31, 0x0A) \ __ENUMERATE_MIME_TYPE_HEADER(pdf, "application/pdf", 0, 5, 0x25, 'P', 'D', 'F', 0x2D) \ @@ -145,6 +146,7 @@ String guess_mime_type_based_on_filename(StringView path) __ENUMERATE_MIME_TYPE_HEADER(tiff, "image/tiff", 0, 4, 'I', 'I', '*', 0x00) \ __ENUMERATE_MIME_TYPE_HEADER(tiff_bigendian, "image/tiff", 0, 4, 'M', 'M', 0x00, '*') \ __ENUMERATE_MIME_TYPE_HEADER(wasm, "application/wasm", 0, 4, 0x00, 'a', 's', 'm') \ + __ENUMERATE_MIME_TYPE_HEADER(wav, "audio/wave", 8, 4, 'W', 'A', 'V', 'E') \ __ENUMERATE_MIME_TYPE_HEADER(win_31x_archive, "extra/win-31x-compressed", 0, 4, 'K', 'W', 'A', 'J') \ __ENUMERATE_MIME_TYPE_HEADER(win_95_archive, "extra/win-95-compressed", 0, 4, 'S', 'Z', 'D', 'D') \ __ENUMERATE_MIME_TYPE_HEADER(zlib_0, "extra/raw-zlib", 0, 2, 0x78, 0x01) \
672c4cdbc23482f643b1321fd923e77dba53ddc7
2021-09-13 17:13:53
Mustafa Quraish
pixelpaint: Add keyboard shortcut for Invert filter
false
Add keyboard shortcut for Invert filter
pixelpaint
diff --git a/Userland/Applications/PixelPaint/MainWidget.cpp b/Userland/Applications/PixelPaint/MainWidget.cpp index 03caf3d19557..6bf69d944278 100644 --- a/Userland/Applications/PixelPaint/MainWidget.cpp +++ b/Userland/Applications/PixelPaint/MainWidget.cpp @@ -680,7 +680,7 @@ void MainWidget::initialize_menubar(GUI::Window& window) editor->did_complete_action(); } })); - color_filters_menu.add_action(GUI::Action::create("Invert", [&](auto&) { + color_filters_menu.add_action(GUI::Action::create("Invert", { Mod_Ctrl, Key_I }, [&](auto&) { auto* editor = current_image_editor(); if (!editor) return;
803ca8cc806e19c93a5eb8e18b9342fd52dc078d
2023-07-31 08:48:51
Shannon Booth
ak: Make serialize_ipv6_address take a StringBuilder
false
Make serialize_ipv6_address take a StringBuilder
ak
diff --git a/AK/URLParser.cpp b/AK/URLParser.cpp index 7570d714f0ee..8105a65a72b1 100644 --- a/AK/URLParser.cpp +++ b/AK/URLParser.cpp @@ -227,10 +227,9 @@ static ErrorOr<String> serialize_ipv4_address(URL::IPv4Address address) } // https://url.spec.whatwg.org/#concept-ipv6-serializer -static ErrorOr<String> serialize_ipv6_address(URL::IPv6Address const& address) +static void serialize_ipv6_address(URL::IPv6Address const& address, StringBuilder& output) { // 1. Let output be the empty string. - StringBuilder output; // 2. Let compress be an index to the first IPv6 piece in the first longest sequences of address’s IPv6 pieces that are 0. // 3. If there is no sequence of address’s IPv6 pieces that are 0 that is longer than 1, then set compress to null. @@ -286,7 +285,6 @@ static ErrorOr<String> serialize_ipv6_address(URL::IPv6Address const& address) } // 6. Return output. - return output.to_string(); } // https://url.spec.whatwg.org/#concept-ipv6-parser @@ -566,10 +564,9 @@ static Optional<DeprecatedString> parse_host(StringView input, bool is_not_speci if (!address.has_value()) return {}; - auto result = serialize_ipv6_address(*address); - if (result.is_error()) - return {}; - return result.release_value().to_deprecated_string(); + StringBuilder output; + serialize_ipv6_address(*address, output); + return output.to_deprecated_string(); } // 2. If isNotSpecial is true, then return the result of opaque-host parsing input.
3be9a9ac7630ffdecd8bf2bfb741e2b92550507d
2020-12-26 20:39:02
Andreas Kling
libtls: Fix TLS breakage after ByteBuffer => Span conversion
false
Fix TLS breakage after ByteBuffer => Span conversion
libtls
diff --git a/Libraries/LibTLS/Record.cpp b/Libraries/LibTLS/Record.cpp index fe306949ecae..913b7ab81cf8 100644 --- a/Libraries/LibTLS/Record.cpp +++ b/Libraries/LibTLS/Record.cpp @@ -343,7 +343,7 @@ ssize_t TLSv12::handle_message(ReadonlyBytes buffer) ASSERT(m_aes_remote.cbc); auto iv_size = iv_length(); - auto decrypted = m_aes_remote.cbc->create_aligned_buffer(length - iv_size); + decrypted = m_aes_remote.cbc->create_aligned_buffer(length - iv_size); auto iv = buffer.slice(header_size, iv_size); Bytes decrypted_span = decrypted; @@ -383,7 +383,7 @@ ssize_t TLSv12::handle_message(ReadonlyBytes buffer) return (i8)Error::IntegrityCheckFailed; } - plain = decrypted.slice(0, length); + plain = decrypted.bytes().slice(0, length); } } m_context.remote_sequence_number++;
4132f645ee7918fe82e835ee5b7f66f222ef5982
2019-04-14 08:09:56
Andreas Kling
kernel: Merge TSS.h into i386.h.
false
Merge TSS.h into i386.h.
kernel
diff --git a/Kernel/TSS.h b/Kernel/TSS.h deleted file mode 100644 index f3e370439e7d..000000000000 --- a/Kernel/TSS.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include <AK/Types.h> - -struct [[gnu::packed]] TSS32 { - word backlink, __blh; - dword esp0; - word ss0, __ss0h; - dword esp1; - word ss1, __ss1h; - dword esp2; - word ss2, __ss2h; - dword cr3, eip, eflags; - dword eax,ecx,edx,ebx,esp,ebp,esi,edi; - word es, __esh; - word cs, __csh; - word ss, __ssh; - word ds, __dsh; - word fs, __fsh; - word gs, __gsh; - word ldt, __ldth; - word trace, iomapbase; -}; diff --git a/Kernel/Thread.h b/Kernel/Thread.h index 98c3d8b4b93d..8fe9a12a7ef7 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -1,7 +1,6 @@ #pragma once #include <Kernel/i386.h> -#include <Kernel/TSS.h> #include <Kernel/KResult.h> #include <Kernel/LinearAddress.h> #include <Kernel/UnixTypes.h> diff --git a/Kernel/i386.h b/Kernel/i386.h index 379fac0d71ed..c770d4528681 100644 --- a/Kernel/i386.h +++ b/Kernel/i386.h @@ -6,6 +6,26 @@ #define PAGE_SIZE 4096 #define PAGE_MASK 0xfffff000 +struct [[gnu::packed]] TSS32 { + word backlink, __blh; + dword esp0; + word ss0, __ss0h; + dword esp1; + word ss1, __ss1h; + dword esp2; + word ss2, __ss2h; + dword cr3, eip, eflags; + dword eax,ecx,edx,ebx,esp,ebp,esi,edi; + word es, __esh; + word cs, __csh; + word ss, __ssh; + word ds, __dsh; + word fs, __fsh; + word gs, __gsh; + word ldt, __ldth; + word trace, iomapbase; +}; + union [[gnu::packed]] Descriptor { struct { word limit_lo;
5615a2691adbcee9d992135b2f7931b6daf3abdb
2024-01-17 14:12:56
Nico Weber
libpdf: Extract activate_clip() / deactivate_clip() functions
false
Extract activate_clip() / deactivate_clip() functions
libpdf
diff --git a/Userland/Libraries/LibPDF/Renderer.cpp b/Userland/Libraries/LibPDF/Renderer.cpp index 04cd6f9a70d5..59ccd4a92e6e 100644 --- a/Userland/Libraries/LibPDF/Renderer.cpp +++ b/Userland/Libraries/LibPDF/Renderer.cpp @@ -290,11 +290,7 @@ RENDERER_HANDLER(path_append_rect) return {}; } -/// -// Path painting operations -/// - -void Renderer::begin_path_paint() +void Renderer::activate_clip() { auto bounding_box = state().clipping_paths.current.bounding_box(); m_painter.clear_clip_rect(); @@ -304,13 +300,27 @@ void Renderer::begin_path_paint() m_painter.add_clip_rect(bounding_box.to_type<int>()); } -void Renderer::end_path_paint() +void Renderer::deactivate_clip() { - m_current_path.clear(); m_painter.clear_clip_rect(); state().clipping_paths.current = state().clipping_paths.next; } +/// +// Path painting operations +/// + +void Renderer::begin_path_paint() +{ + activate_clip(); +} + +void Renderer::end_path_paint() +{ + m_current_path.clear(); + deactivate_clip(); +} + RENDERER_HANDLER(path_stroke) { begin_path_paint(); diff --git a/Userland/Libraries/LibPDF/Renderer.h b/Userland/Libraries/LibPDF/Renderer.h index 177679dd4e67..32a3467d2949 100644 --- a/Userland/Libraries/LibPDF/Renderer.h +++ b/Userland/Libraries/LibPDF/Renderer.h @@ -127,6 +127,9 @@ class Renderer { PDFErrorOr<void> handle_text_next_line_show_string(ReadonlySpan<Value> args, Optional<NonnullRefPtr<DictObject>> = {}); PDFErrorOr<void> handle_text_next_line_show_string_set_spacing(ReadonlySpan<Value> args, Optional<NonnullRefPtr<DictObject>> = {}); + void activate_clip(); + void deactivate_clip(); + void begin_path_paint(); void end_path_paint(); PDFErrorOr<void> set_graphics_state_from_dict(NonnullRefPtr<DictObject>);
353e3e75dcff05f05a65cfc3c70d1cff8db5d50c
2024-08-19 12:32:21
Tim Ledbetter
libweb: Limit `HTMLProgressElement.max` to positive values
false
Limit `HTMLProgressElement.max` to positive values
libweb
diff --git a/Tests/LibWeb/Text/expected/HTML/HTMLProgressElement-set-attributes.txt b/Tests/LibWeb/Text/expected/HTML/HTMLProgressElement-set-attributes.txt index 6af4a53740eb..902e15e68c5b 100644 --- a/Tests/LibWeb/Text/expected/HTML/HTMLProgressElement-set-attributes.txt +++ b/Tests/LibWeb/Text/expected/HTML/HTMLProgressElement-set-attributes.txt @@ -2,6 +2,7 @@ value attribute initial value: 0 max attribute initial value: 1 value attribute after setting value attribute to -1: 0 max attribute after setting max attribute to -1: 1 +max attribute after setting max attribute to 0: 1 value attribute after setting value attribute to 50: 1 value attribute after setting max attribute to 100: 50 max attribute after setting max attribute to 100: 100 diff --git a/Tests/LibWeb/Text/input/HTML/HTMLProgressElement-set-attributes.html b/Tests/LibWeb/Text/input/HTML/HTMLProgressElement-set-attributes.html index 98905b0d2f0d..60da7461602c 100644 --- a/Tests/LibWeb/Text/input/HTML/HTMLProgressElement-set-attributes.html +++ b/Tests/LibWeb/Text/input/HTML/HTMLProgressElement-set-attributes.html @@ -9,6 +9,8 @@ println(`value attribute after setting value attribute to -1: ${progressElement.value}`); progressElement.max = -1; println(`max attribute after setting max attribute to -1: ${progressElement.max}`); + progressElement.max = 0; + println(`max attribute after setting max attribute to 0: ${progressElement.max}`); progressElement.value = 50; println(`value attribute after setting value attribute to 50: ${progressElement.value}`); progressElement.max = 100; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp index e4f1ce5bfa2b..8ecfac9c7fa8 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLProgressElement.cpp @@ -64,7 +64,8 @@ double HTMLProgressElement::max() const { if (auto max_string = get_attribute(HTML::AttributeNames::max); max_string.has_value()) { if (auto max = parse_floating_point_number(*max_string); max.has_value()) - return AK::max(*max, 0); + if (*max > 0) + return *max; } return 1; }
e56f8706ce40e903e1897a8175cea65ed8f4760e
2020-03-02 15:50:34
Andreas Kling
kernel: Map executables at a kernel address during ELF load
false
Map executables at a kernel address during ELF load
kernel
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 00b172a440a5..9d67b0668166 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -832,9 +832,6 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve dbg() << "Process " << pid() << " exec: PD=" << m_page_directory.ptr() << " created"; #endif - MM.enter_process_paging_scope(*this); - - Region* region { nullptr }; InodeMetadata loader_metadata; @@ -848,23 +845,22 @@ int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Ve // FIXME: We should be able to load both the PT_INTERP interpreter and the main program... once the RTLD is smart enough if (interpreter_description) { loader_metadata = interpreter_description->metadata(); - region = allocate_region_with_vmobject(VirtualAddress(), loader_metadata.size, *vmobject, 0, interpreter_description->absolute_path(), PROT_READ, false); // we don't need the interpreter file desciption after we've loaded (or not) it into memory interpreter_description = nullptr; } else { loader_metadata = main_program_description->metadata(); - region = allocate_region_with_vmobject(VirtualAddress(), loader_metadata.size, *vmobject, 0, main_program_description->absolute_path(), PROT_READ, false); } - ASSERT(region); - - region->set_shared(true); + auto region = MM.allocate_kernel_region_with_vmobject(*vmobject, PAGE_ROUND_UP(loader_metadata.size), "ELF loading", Region::Access::Read); + if (!region) + return -ENOMEM; Region* master_tls_region { nullptr }; size_t master_tls_size = 0; size_t master_tls_alignment = 0; u32 entry_eip = 0; + MM.enter_process_paging_scope(*this); OwnPtr<ELFLoader> loader; { ArmedScopeGuard rollback_regions_guard([&]() {
8c6646a034843fb6309a5806f21e71b214821266
2022-01-11 16:17:34
Lady Gegga
base: Adjust 21B9, 2190, 2192, 219D, 219C in font Katica Regular 10
false
Adjust 21B9, 2190, 2192, 219D, 219C in font Katica Regular 10
base
diff --git a/Base/res/fonts/KaticaRegular10.font b/Base/res/fonts/KaticaRegular10.font index 9c2a4c77e784..317d0200230b 100644 Binary files a/Base/res/fonts/KaticaRegular10.font and b/Base/res/fonts/KaticaRegular10.font differ
7551090056154285f0d4cf7435f48dfdd200a041
2021-02-13 05:48:03
Andreas Kling
kernel: Round up ranges to page size multiples in munmap and mprotect
false
Round up ranges to page size multiples in munmap and mprotect
kernel
diff --git a/Kernel/Syscalls/mmap.cpp b/Kernel/Syscalls/mmap.cpp index 4a6bb966623c..c81228860ec2 100644 --- a/Kernel/Syscalls/mmap.cpp +++ b/Kernel/Syscalls/mmap.cpp @@ -160,7 +160,7 @@ void* Process::sys$mmap(Userspace<const Syscall::SC_mmap_params*> user_params) if (alignment & ~PAGE_MASK) return (void*)-EINVAL; - if (!is_user_range(VirtualAddress(addr), size)) + if (!is_user_range(VirtualAddress(addr), PAGE_ROUND_UP(size))) return (void*)-EFAULT; String name; @@ -272,14 +272,14 @@ int Process::sys$mprotect(void* addr, size_t size, int prot) REQUIRE_PROMISE(prot_exec); } - if (!size) + Range range_to_mprotect = { VirtualAddress(addr), PAGE_ROUND_UP(size) }; + + if (!range_to_mprotect.size()) return -EINVAL; - if (!is_user_range(VirtualAddress(addr), size)) + if (!is_user_range(range_to_mprotect)) return -EFAULT; - Range range_to_mprotect = { VirtualAddress(addr), size }; - if (auto* whole_region = space().find_region_from_range(range_to_mprotect)) { if (!whole_region->is_mmap()) return -EPERM; @@ -343,13 +343,15 @@ int Process::sys$madvise(void* address, size_t size, int advice) { REQUIRE_PROMISE(stdio); - if (!size) + Range range_to_madvise { VirtualAddress(address), PAGE_ROUND_UP(size) }; + + if (!range_to_madvise.size()) return -EINVAL; - if (!is_user_range(VirtualAddress(address), size)) + if (!is_user_range(range_to_madvise)) return -EFAULT; - auto* region = space().find_region_from_range({ VirtualAddress(address), size }); + auto* region = space().find_region_from_range(range_to_madvise); if (!region) return -EINVAL; if (!region->is_mmap()) @@ -413,10 +415,11 @@ int Process::sys$munmap(void* addr, size_t size) if (!size) return -EINVAL; - if (!is_user_range(VirtualAddress(addr), size)) + Range range_to_unmap { VirtualAddress(addr), PAGE_ROUND_UP(size) }; + + if (!is_user_range(range_to_unmap)) return -EFAULT; - Range range_to_unmap { VirtualAddress(addr), size }; if (auto* whole_region = space().find_region_from_range(range_to_unmap)) { if (!whole_region->is_mmap()) return -EPERM; diff --git a/Kernel/VM/MemoryManager.h b/Kernel/VM/MemoryManager.h index c33cb7487ed3..7780ca0e75ab 100644 --- a/Kernel/VM/MemoryManager.h +++ b/Kernel/VM/MemoryManager.h @@ -265,6 +265,11 @@ inline bool is_user_range(VirtualAddress vaddr, size_t size) return is_user_address(vaddr) && is_user_address(vaddr.offset(size)); } +inline bool is_user_range(const Range& range) +{ + return is_user_range(range.base(), range.size()); +} + inline bool PhysicalPage::is_shared_zero_page() const { return this == &MM.shared_zero_page();
5cd01bd644ad899cd20eac94421291b69619a78e
2023-05-29 09:05:41
Ali Mohammad Pur
libweb: Allow '0' as a CSS dimension value
false
Allow '0' as a CSS dimension value
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp index e400ecdb79d5..1e697a6ddea5 100644 --- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp +++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp @@ -3683,7 +3683,7 @@ ErrorOr<RefPtr<StyleValue>> Parser::parse_dimension_value(ComponentValue const& // 2) It's a 0. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0. - if (component_value.is(Token::Type::Number) && !(m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength))) + if (component_value.is(Token::Type::Number) && component_value.token().number_value() != 0 && !(m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength))) return nullptr; auto dimension = parse_dimension(component_value);
12f5e9c5f87072fb1c54739d8a185e43356b5bd5
2025-03-04 05:21:50
Andreas Kling
libweb: Only put connected elements into document's by-name-or-id cache
false
Only put connected elements into document's by-name-or-id cache
libweb
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp index 2045afe47f37..0dd01b1f98ec 100644 --- a/Libraries/LibWeb/DOM/Element.cpp +++ b/Libraries/LibWeb/DOM/Element.cpp @@ -1129,22 +1129,24 @@ void Element::inserted() { Base::inserted(); - if (m_id.has_value()) - document().element_with_id_was_added({}, *this); - - if (m_name.has_value()) - document().element_with_name_was_added({}, *this); + if (is_connected()) { + if (m_id.has_value()) + document().element_with_id_was_added({}, *this); + if (m_name.has_value()) + document().element_with_name_was_added({}, *this); + } } void Element::removed_from(Node* old_parent, Node& old_root) { Base::removed_from(old_parent, old_root); - if (m_id.has_value()) - document().element_with_id_was_removed({}, *this); - - if (m_name.has_value()) - document().element_with_name_was_removed({}, *this); + if (old_root.is_connected()) { + if (m_id.has_value()) + document().element_with_id_was_removed({}, *this); + if (m_name.has_value()) + document().element_with_name_was_removed({}, *this); + } } void Element::children_changed(ChildrenChangedMetadata const* metadata) @@ -3530,14 +3532,16 @@ void Element::attribute_changed(FlyString const& local_name, Optional<String> co else m_id = value_or_empty; - document().element_id_changed({}, *this); + if (is_connected()) + document().element_id_changed({}, *this); } else if (local_name == HTML::AttributeNames::name) { if (value_or_empty.is_empty()) m_name = {}; else m_name = value_or_empty; - document().element_name_changed({}, *this); + if (is_connected()) + document().element_name_changed({}, *this); } else if (local_name == HTML::AttributeNames::class_) { if (value_or_empty.is_empty()) { m_classes.clear(); diff --git a/Tests/LibWeb/Text/expected/HTML/document-named-shenanigans.txt b/Tests/LibWeb/Text/expected/HTML/document-named-shenanigans.txt new file mode 100644 index 000000000000..679f70470b66 --- /dev/null +++ b/Tests/LibWeb/Text/expected/HTML/document-named-shenanigans.txt @@ -0,0 +1,15 @@ +Testing <div> element +,,,,,,,,,,,,,,, + +Testing <form> element +,,,,,,[object HTMLFormElement],,[object HTMLFormElement],,,,,,, + +Testing <img> element +,,,,,,[object HTMLImageElement],,[object HTMLImageElement],,,,,,, + +Testing <embed> element +,,,,,,[object HTMLEmbedElement],,[object HTMLEmbedElement],,,,,,, + +Testing <object> element +,,,,,,[object HTMLObjectElement],,[object HTMLObjectElement],,[object HTMLObjectElement],[object HTMLObjectElement],,[object HTMLObjectElement],, + diff --git a/Tests/LibWeb/Text/input/HTML/document-named-shenanigans.html b/Tests/LibWeb/Text/input/HTML/document-named-shenanigans.html new file mode 100644 index 000000000000..a61e6ab9953f --- /dev/null +++ b/Tests/LibWeb/Text/input/HTML/document-named-shenanigans.html @@ -0,0 +1,64 @@ +<script src="../include.js"></script> +<script> + function go(tagName) { + println("Testing <" + tagName + "> element"); + + let a = []; + + let e = document.createElement(tagName); + a.push(document.shenanigans); + + e.setAttribute("name", "shenanigans"); + a.push(document.shenanigans); + + e.setAttribute("name", "mischief"); + a.push(document.shenanigans); + a.push(document.mischief); + + e.name = "shenanigans"; + a.push(document.shenanigans); + a.push(document.mischief); + + document.body.appendChild(e); + a.push(document.shenanigans); + + e.remove(); + a.push(document.shenanigans); + + document.body.appendChild(e); + a.push(document.shenanigans); + + e.removeAttribute("name"); + a.push(document.hijinks); + + e.setAttribute("id", "hijinks"); + a.push(document.hijinks); + + document.body.appendChild(e); + a.push(document.hijinks); + + e.remove(); + a.push(document.hijinks); + + document.body.appendChild(e); + a.push(document.hijinks); + + e.removeAttribute("id"); + a.push(document.hijinks); + + e.remove(); + a.push(document.hijinks); + + println(a); + + println(""); + } + + test(() => { + go("div"); + go("form"); + go("img"); + go("embed"); + go("object"); + }); +</script>
ade510fe17da6dbb41bc5e61cfce278ff471d210
2024-11-26 22:05:15
Timothy Flynn
libjs: Pass ISO types by value vs. const-reference more correctly
false
Pass ISO types by value vs. const-reference more correctly
libjs
diff --git a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp index 23b6ff724839..0a6ffc535b87 100644 --- a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp +++ b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp @@ -75,7 +75,7 @@ double epoch_days_to_epoch_ms(double day, double time) } // 13.4 CheckISODaysRange ( isoDate ), https://tc39.es/proposal-temporal/#sec-checkisodaysrange -ThrowCompletionOr<void> check_iso_days_range(VM& vm, ISODate const& iso_date) +ThrowCompletionOr<void> check_iso_days_range(VM& vm, ISODate iso_date) { // 1. If abs(ISODateToEpochDays(isoDate.[[Year]], isoDate.[[Month]] - 1, isoDate.[[Day]])) > 10**8, then if (fabs(iso_date_to_epoch_days(iso_date.year, iso_date.month - 1, iso_date.day)) > 100'000'000) { @@ -1725,7 +1725,7 @@ ThrowCompletionOr<String> to_offset_string(VM& vm, Value argument) } // 13.42 ISODateToFields ( calendar, isoDate, type ), https://tc39.es/proposal-temporal/#sec-temporal-isodatetofields -CalendarFields iso_date_to_fields(StringView calendar, ISODate const& iso_date, DateType type) +CalendarFields iso_date_to_fields(StringView calendar, ISODate iso_date, DateType type) { // 1. Let fields be an empty Calendar Fields Record with all fields set to unset. auto fields = CalendarFields::unset(); diff --git a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h index c53d531bdcf0..bc1949b4e0fb 100644 --- a/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h +++ b/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h @@ -172,7 +172,7 @@ struct DifferenceSettings { double iso_date_to_epoch_days(double year, double month, double date); double epoch_days_to_epoch_ms(double day, double time); -ThrowCompletionOr<void> check_iso_days_range(VM&, ISODate const&); +ThrowCompletionOr<void> check_iso_days_range(VM&, ISODate); ThrowCompletionOr<Overflow> get_temporal_overflow_option(VM&, Object const& options); ThrowCompletionOr<Disambiguation> get_temporal_disambiguation_option(VM&, Object const& options); RoundingMode negate_rounding_mode(RoundingMode); @@ -206,7 +206,7 @@ ThrowCompletionOr<GC::Ref<Duration>> parse_temporal_duration_string(VM&, StringV ThrowCompletionOr<TimeZone> parse_temporal_time_zone_string(VM&, StringView time_zone_string); ThrowCompletionOr<String> to_month_code(VM&, Value argument); ThrowCompletionOr<String> to_offset_string(VM&, Value argument); -CalendarFields iso_date_to_fields(StringView calendar, ISODate const&, DateType); +CalendarFields iso_date_to_fields(StringView calendar, ISODate, DateType); ThrowCompletionOr<DifferenceSettings> get_difference_settings(VM&, DurationOperation, Object const& options, UnitGroup, ReadonlySpan<Unit> disallowed_units, Unit fallback_smallest_unit, Unit smallest_largest_default_unit); // 13.38 ToIntegerWithTruncation ( argument ), https://tc39.es/proposal-temporal/#sec-tointegerwithtruncation diff --git a/Libraries/LibJS/Runtime/Temporal/Calendar.cpp b/Libraries/LibJS/Runtime/Temporal/Calendar.cpp index b88b063bc06f..5752920a796a 100644 --- a/Libraries/LibJS/Runtime/Temporal/Calendar.cpp +++ b/Libraries/LibJS/Runtime/Temporal/Calendar.cpp @@ -316,7 +316,7 @@ CalendarFields calendar_merge_fields(StringView calendar, CalendarFields const& } // 12.2.6 CalendarDateAdd ( calendar, isoDate, duration, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendardateadd -ThrowCompletionOr<ISODate> calendar_date_add(VM& vm, StringView calendar, ISODate const& iso_date, DateDuration const& duration, Overflow overflow) +ThrowCompletionOr<ISODate> calendar_date_add(VM& vm, StringView calendar, ISODate iso_date, DateDuration const& duration, Overflow overflow) { ISODate result; @@ -349,7 +349,7 @@ ThrowCompletionOr<ISODate> calendar_date_add(VM& vm, StringView calendar, ISODat } // 12.2.7 CalendarDateUntil ( calendar, one, two, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-calendardateuntil -DateDuration calendar_date_until(VM& vm, StringView calendar, ISODate const& one, ISODate const& two, Unit largest_unit) +DateDuration calendar_date_until(VM& vm, StringView calendar, ISODate one, ISODate two, Unit largest_unit) { // 1. If calendar is "iso8601", then if (calendar == "iso8601"sv) { @@ -610,7 +610,7 @@ u8 iso_days_in_month(double year, double month) } // 12.2.16 ISOWeekOfYear ( isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-isoweekofyear -YearWeek iso_week_of_year(ISODate const& iso_date) +YearWeek iso_week_of_year(ISODate iso_date) { // 1. Let year be isoDate.[[Year]]. auto year = iso_date.year; @@ -691,7 +691,7 @@ YearWeek iso_week_of_year(ISODate const& iso_date) } // 12.2.17 ISODayOfYear ( isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-isodayofyear -u16 iso_day_of_year(ISODate const& iso_date) +u16 iso_day_of_year(ISODate iso_date) { // 1. Let epochDays be ISODateToEpochDays(isoDate.[[Year]], isoDate.[[Month]] - 1, isoDate.[[Day]]). auto epoch_days = iso_date_to_epoch_days(iso_date.year, iso_date.month - 1, iso_date.day); @@ -701,7 +701,7 @@ u16 iso_day_of_year(ISODate const& iso_date) } // 12.2.18 ISODayOfWeek ( isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-isodayofweek -u8 iso_day_of_week(ISODate const& iso_date) +u8 iso_day_of_week(ISODate iso_date) { // 1. Let epochDays be ISODateToEpochDays(isoDate.[[Year]], isoDate.[[Month]] - 1, isoDate.[[Day]]). auto epoch_days = iso_date_to_epoch_days(iso_date.year, iso_date.month - 1, iso_date.day); @@ -764,7 +764,7 @@ ThrowCompletionOr<ISODate> calendar_month_day_to_iso_reference_date(VM& vm, Stri } // 12.2.21 CalendarISOToDate ( calendar, isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-calendarisotodate -CalendarDate calendar_iso_to_date(StringView calendar, ISODate const& iso_date) +CalendarDate calendar_iso_to_date(StringView calendar, ISODate iso_date) { // 1. If calendar is "iso8601", then if (calendar == "iso8601"sv) { diff --git a/Libraries/LibJS/Runtime/Temporal/Calendar.h b/Libraries/LibJS/Runtime/Temporal/Calendar.h index 00359f58a690..89e170740379 100644 --- a/Libraries/LibJS/Runtime/Temporal/Calendar.h +++ b/Libraries/LibJS/Runtime/Temporal/Calendar.h @@ -105,18 +105,18 @@ ThrowCompletionOr<ISODate> calendar_month_day_from_fields(VM&, StringView calend String format_calendar_annotation(StringView id, ShowCalendar); bool calendar_equals(StringView one, StringView two); u8 iso_days_in_month(double year, double month); -YearWeek iso_week_of_year(ISODate const&); -u16 iso_day_of_year(ISODate const&); -u8 iso_day_of_week(ISODate const&); +YearWeek iso_week_of_year(ISODate); +u16 iso_day_of_year(ISODate); +u8 iso_day_of_week(ISODate); Vector<CalendarField> calendar_field_keys_present(CalendarFields const&); CalendarFields calendar_merge_fields(StringView calendar, CalendarFields const& fields, CalendarFields const& additional_fields); -ThrowCompletionOr<ISODate> calendar_date_add(VM&, StringView calendar, ISODate const&, DateDuration const&, Overflow); -DateDuration calendar_date_until(VM&, StringView calendar, ISODate const&, ISODate const&, Unit largest_unit); +ThrowCompletionOr<ISODate> calendar_date_add(VM&, StringView calendar, ISODate, DateDuration const&, Overflow); +DateDuration calendar_date_until(VM&, StringView calendar, ISODate, ISODate, Unit largest_unit); ThrowCompletionOr<String> to_temporal_calendar_identifier(VM&, Value temporal_calendar_like); ThrowCompletionOr<String> get_temporal_calendar_identifier_with_iso_default(VM&, Object const& item); ThrowCompletionOr<ISODate> calendar_date_to_iso(VM&, StringView calendar, CalendarFields const&, Overflow); ThrowCompletionOr<ISODate> calendar_month_day_to_iso_reference_date(VM&, StringView calendar, CalendarFields const&, Overflow); -CalendarDate calendar_iso_to_date(StringView calendar, ISODate const&); +CalendarDate calendar_iso_to_date(StringView calendar, ISODate); Vector<CalendarField> calendar_extra_fields(StringView calendar, CalendarFieldList); Vector<CalendarField> calendar_field_keys_to_ignore(StringView calendar, ReadonlySpan<CalendarField>); ThrowCompletionOr<void> calendar_resolve_fields(VM&, StringView calendar, CalendarFields&, DateType); diff --git a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp index 69b2478a76c6..5786be7343ec 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp +++ b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp @@ -29,7 +29,7 @@ PlainDateTime::PlainDateTime(ISODateTime const& iso_date_time, String calendar, } // 5.5.3 CombineISODateAndTimeRecord ( isoDate, time ), https://tc39.es/proposal-temporal/#sec-temporal-combineisodateandtimerecord -ISODateTime combine_iso_date_and_time_record(ISODate iso_date, Time time) +ISODateTime combine_iso_date_and_time_record(ISODate iso_date, Time const& time) { // 1. NOTE: time.[[Days]] is ignored. // 2. Return ISO Date-Time Record { [[ISODate]]: isoDate, [[Time]]: time }. @@ -43,7 +43,7 @@ static auto const DATETIME_NANOSECONDS_MIN = "-8640000086400000000000"_sbigint; static auto const DATETIME_NANOSECONDS_MAX = "8640000086400000000000"_sbigint; // 5.5.4 ISODateTimeWithinLimits ( isoDateTime ), https://tc39.es/proposal-temporal/#sec-temporal-isodatetimewithinlimits -bool iso_date_time_within_limits(ISODateTime iso_date_time) +bool iso_date_time_within_limits(ISODateTime const& iso_date_time) { // 1. If abs(ISODateToEpochDays(isoDateTime.[[ISODate]].[[Year]], isoDateTime.[[ISODate]].[[Month]] - 1, isoDateTime.[[ISODate]].[[Day]])) > 10**8 + 1, return false. if (fabs(iso_date_to_epoch_days(iso_date_time.iso_date.year, iso_date_time.iso_date.month - 1, iso_date_time.iso_date.day)) > 100000001) diff --git a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h index 9d38caa2002f..b7cc2e8481e6 100644 --- a/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h +++ b/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h @@ -32,8 +32,8 @@ class PlainDateTime final : public Object { String m_calendar; // [[Calendar]] }; -ISODateTime combine_iso_date_and_time_record(ISODate, Time); -bool iso_date_time_within_limits(ISODateTime); +ISODateTime combine_iso_date_and_time_record(ISODate, Time const&); +bool iso_date_time_within_limits(ISODateTime const&); ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(VM&, StringView calendar, CalendarFields&, Overflow); ThrowCompletionOr<GC::Ref<PlainDateTime>> to_temporal_date_time(VM&, Value item, Value options = js_undefined()); ISODateTime balance_iso_date_time(double year, double month, double day, double hour, double minute, double second, double millisecond, double microsecond, double nanosecond);
a5936864d963e29d27d4a5fe4f04dab456ad378c
2023-05-22 09:37:05
Luke Wilde
libweb: Stub AudioContext constructor
false
Stub AudioContext constructor
libweb
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp index 6cd384390483..0b406511b88e 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp @@ -3114,6 +3114,7 @@ using namespace Web::UIEvents; using namespace Web::URL; using namespace Web::XHR; using namespace Web::WebAssembly; +using namespace Web::WebAudio; using namespace Web::WebGL; using namespace Web::WebIDL; @@ -3330,6 +3331,7 @@ using namespace Web::UserTiming; using namespace Web::URL; using namespace Web::XHR; using namespace Web::WebAssembly; +using namespace Web::WebAudio; using namespace Web::WebGL; using namespace Web::WebIDL; @@ -3713,6 +3715,7 @@ using namespace Web::UserTiming; using namespace Web::WebSockets; using namespace Web::XHR; using namespace Web::WebAssembly; +using namespace Web::WebAudio; using namespace Web::WebGL; using namespace Web::WebIDL; @@ -3843,6 +3846,7 @@ using namespace Web::XHR; using namespace Web::UIEvents; using namespace Web::URL; using namespace Web::UserTiming; +using namespace Web::WebAudio; using namespace Web::WebGL; using namespace Web::WebIDL; @@ -3994,6 +3998,7 @@ using namespace Web::SVG; using namespace Web::UIEvents; using namespace Web::URL; using namespace Web::UserTiming; +using namespace Web::WebAudio; using namespace Web::WebSockets; using namespace Web::XHR; using namespace Web::WebGL; diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/Namespaces.h b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/Namespaces.h index 19593e63f53f..6fd5580dfd55 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/Namespaces.h +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/Namespaces.h @@ -31,6 +31,7 @@ static constexpr Array libweb_interface_namespaces = { "Selection"sv, "UIEvents"sv, "URL"sv, + "WebAudio"sv, "WebGL"sv, "WebIDL"sv, "WebSockets"sv, diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 0fefdb1a332e..6727d24d10a2 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -540,6 +540,8 @@ set(SOURCES WebAssembly/Module.cpp WebAssembly/Table.cpp WebAssembly/WebAssembly.cpp + WebAudio/AudioContext.cpp + WebAudio/BaseAudioContext.cpp WebDriver/Capabilities.cpp WebDriver/Client.cpp WebDriver/Contexts.cpp diff --git a/Userland/Libraries/LibWeb/Forward.h b/Userland/Libraries/LibWeb/Forward.h index b7941fd62aac..ae7703179131 100644 --- a/Userland/Libraries/LibWeb/Forward.h +++ b/Userland/Libraries/LibWeb/Forward.h @@ -577,6 +577,11 @@ class Module; class Table; } +namespace Web::WebAudio { +class AudioContext; +class BaseAudioContext; +} + namespace Web::WebGL { class WebGLContextEvent; class WebGLRenderingContext; diff --git a/Userland/Libraries/LibWeb/WebAudio/AudioContext.cpp b/Userland/Libraries/LibWeb/WebAudio/AudioContext.cpp new file mode 100644 index 000000000000..1be57a398328 --- /dev/null +++ b/Userland/Libraries/LibWeb/WebAudio/AudioContext.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023, Luke Wilde <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/Bindings/Intrinsics.h> +#include <LibWeb/WebAudio/AudioContext.h> + +namespace Web::WebAudio { + +// https://webaudio.github.io/web-audio-api/#dom-audiocontext-audiocontext +WebIDL::ExceptionOr<JS::NonnullGCPtr<AudioContext>> AudioContext::construct_impl(JS::Realm& realm) +{ + dbgln("(STUBBED) new AudioContext()"); + return MUST_OR_THROW_OOM(realm.heap().allocate<AudioContext>(realm, realm)); +} + +AudioContext::AudioContext(JS::Realm& realm) + : BaseAudioContext(realm) +{ +} + +AudioContext::~AudioContext() = default; + +JS::ThrowCompletionOr<void> AudioContext::initialize(JS::Realm& realm) +{ + MUST_OR_THROW_OOM(Base::initialize(realm)); + set_prototype(&Bindings::ensure_web_prototype<Bindings::AudioContextPrototype>(realm, "AudioContext")); + + return {}; +} + +} diff --git a/Userland/Libraries/LibWeb/WebAudio/AudioContext.h b/Userland/Libraries/LibWeb/WebAudio/AudioContext.h new file mode 100644 index 000000000000..a0fc18acf342 --- /dev/null +++ b/Userland/Libraries/LibWeb/WebAudio/AudioContext.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023, Luke Wilde <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <LibWeb/WebAudio/BaseAudioContext.h> + +namespace Web::WebAudio { + +// https://webaudio.github.io/web-audio-api/#AudioContext +class AudioContext final : public BaseAudioContext { + WEB_PLATFORM_OBJECT(AudioContext, BaseAudioContext); + +public: + static WebIDL::ExceptionOr<JS::NonnullGCPtr<AudioContext>> construct_impl(JS::Realm&); + + virtual ~AudioContext() override; + +private: + explicit AudioContext(JS::Realm&); + + virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override; +}; + +} diff --git a/Userland/Libraries/LibWeb/WebAudio/AudioContext.idl b/Userland/Libraries/LibWeb/WebAudio/AudioContext.idl new file mode 100644 index 000000000000..b3a41552dec4 --- /dev/null +++ b/Userland/Libraries/LibWeb/WebAudio/AudioContext.idl @@ -0,0 +1,8 @@ +#import <WebAudio/BaseAudioContext.idl> + +// https://webaudio.github.io/web-audio-api/#AudioContext +[Exposed=Window] +interface AudioContext : BaseAudioContext { + // FIXME: Should be constructor (optional AudioContextOptions contextOptions = {}); + constructor(); +}; diff --git a/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp b/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp new file mode 100644 index 000000000000..02b8a119f044 --- /dev/null +++ b/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023, Luke Wilde <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/Bindings/Intrinsics.h> +#include <LibWeb/WebAudio/BaseAudioContext.h> + +namespace Web::WebAudio { + +BaseAudioContext::BaseAudioContext(JS::Realm& realm) + : DOM::EventTarget(realm) +{ +} + +BaseAudioContext::~BaseAudioContext() = default; + +JS::ThrowCompletionOr<void> BaseAudioContext::initialize(JS::Realm& realm) +{ + MUST_OR_THROW_OOM(Base::initialize(realm)); + set_prototype(&Bindings::ensure_web_prototype<Bindings::BaseAudioContextPrototype>(realm, "BaseAudioContext")); + + return {}; +} + +} diff --git a/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.h b/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.h new file mode 100644 index 000000000000..6b6365a4a0b0 --- /dev/null +++ b/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2023, Luke Wilde <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <LibWeb/DOM/EventTarget.h> + +namespace Web::WebAudio { + +// https://webaudio.github.io/web-audio-api/#BaseAudioContext +class BaseAudioContext : public DOM::EventTarget { + WEB_PLATFORM_OBJECT(BaseAudioContext, DOM::EventTarget); + +public: + virtual ~BaseAudioContext() override; + +protected: + explicit BaseAudioContext(JS::Realm&); + + virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override; +}; + +} diff --git a/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.idl b/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.idl new file mode 100644 index 000000000000..a246460979a8 --- /dev/null +++ b/Userland/Libraries/LibWeb/WebAudio/BaseAudioContext.idl @@ -0,0 +1,6 @@ +#import <DOM/EventTarget.idl> + +// https://webaudio.github.io/web-audio-api/#BaseAudioContext +[Exposed=Window] +interface BaseAudioContext : EventTarget { +}; diff --git a/Userland/Libraries/LibWeb/idl_files.cmake b/Userland/Libraries/LibWeb/idl_files.cmake index 9d6166dbe7cb..69da34330486 100644 --- a/Userland/Libraries/LibWeb/idl_files.cmake +++ b/Userland/Libraries/LibWeb/idl_files.cmake @@ -227,6 +227,8 @@ libweb_js_bindings(WebAssembly/Memory) libweb_js_bindings(WebAssembly/Module) libweb_js_bindings(WebAssembly/Table) libweb_js_bindings(WebAssembly/WebAssembly NAMESPACE) +libweb_js_bindings(WebAudio/AudioContext) +libweb_js_bindings(WebAudio/BaseAudioContext) libweb_js_bindings(WebGL/WebGLContextEvent) libweb_js_bindings(WebGL/WebGLRenderingContext) libweb_js_bindings(WebIDL/DOMException)
d01eba6fa3e144367501c9295a03641cb81f532b
2020-07-19 15:16:37
Peter Elliott
kernel: Implement FIFOs/named pipes
false
Implement FIFOs/named pipes
kernel
diff --git a/Kernel/FileSystem/FIFO.cpp b/Kernel/FileSystem/FIFO.cpp index 610b580ada02..43a344120876 100644 --- a/Kernel/FileSystem/FIFO.cpp +++ b/Kernel/FileSystem/FIFO.cpp @@ -60,6 +60,35 @@ NonnullRefPtr<FileDescription> FIFO::open_direction(FIFO::Direction direction) return description; } +NonnullRefPtr<FileDescription> FIFO::open_direction_blocking(FIFO::Direction direction) +{ + Locker locker(m_open_lock); + + auto description = open_direction(direction); + + if (direction == Direction::Reader) { + m_read_open_queue.wake_all(); + + if (m_writers == 0) { + locker.unlock(); + Thread::current()->wait_on(m_write_open_queue, "FIFO"); + locker.lock(); + } + } + + if (direction == Direction::Writer) { + m_write_open_queue.wake_all(); + + if (m_readers == 0) { + locker.unlock(); + Thread::current()->wait_on(m_read_open_queue, "FIFO"); + locker.lock(); + } + } + + return description; +} + FIFO::FIFO(uid_t uid) : m_uid(uid) { diff --git a/Kernel/FileSystem/FIFO.h b/Kernel/FileSystem/FIFO.h index 81a65d8caef4..81a48680967e 100644 --- a/Kernel/FileSystem/FIFO.h +++ b/Kernel/FileSystem/FIFO.h @@ -28,7 +28,9 @@ #include <Kernel/DoubleBuffer.h> #include <Kernel/FileSystem/File.h> +#include <Kernel/Lock.h> #include <Kernel/UnixTypes.h> +#include <Kernel/WaitQueue.h> namespace Kernel { @@ -48,6 +50,7 @@ class FIFO final : public File { uid_t uid() const { return m_uid; } NonnullRefPtr<FileDescription> open_direction(Direction); + NonnullRefPtr<FileDescription> open_direction_blocking(Direction); void attach(Direction); void detach(Direction); @@ -71,6 +74,10 @@ class FIFO final : public File { uid_t m_uid { 0 }; int m_fifo_id { 0 }; + + WaitQueue m_read_open_queue; + WaitQueue m_write_open_queue; + Lock m_open_lock; }; } diff --git a/Kernel/FileSystem/Inode.cpp b/Kernel/FileSystem/Inode.cpp index ec410bcac34d..8d4f76a6ad93 100644 --- a/Kernel/FileSystem/Inode.cpp +++ b/Kernel/FileSystem/Inode.cpp @@ -205,6 +205,18 @@ void Inode::unregister_watcher(Badge<InodeWatcher>, InodeWatcher& watcher) m_watchers.remove(&watcher); } +FIFO& Inode::fifo() +{ + ASSERT(metadata().is_fifo()); + + // FIXME: Release m_fifo when it is closed by all readers and writers + if (!m_fifo) + m_fifo = FIFO::create(metadata().uid); + + ASSERT(m_fifo); + return *m_fifo; +} + void Inode::set_metadata_dirty(bool metadata_dirty) { if (m_metadata_dirty == metadata_dirty) diff --git a/Kernel/FileSystem/Inode.h b/Kernel/FileSystem/Inode.h index ff15682fbcc2..d6a13f01fb45 100644 --- a/Kernel/FileSystem/Inode.h +++ b/Kernel/FileSystem/Inode.h @@ -32,6 +32,7 @@ #include <AK/RefCounted.h> #include <AK/String.h> #include <AK/WeakPtr.h> +#include <Kernel/FileSystem/FIFO.h> #include <Kernel/FileSystem/FileSystem.h> #include <Kernel/FileSystem/InodeIdentifier.h> #include <Kernel/FileSystem/InodeMetadata.h> @@ -111,6 +112,8 @@ class Inode : public RefCounted<Inode> void register_watcher(Badge<InodeWatcher>, InodeWatcher&); void unregister_watcher(Badge<InodeWatcher>, InodeWatcher&); + FIFO& fifo(); + // For InlineLinkedListNode. Inode* m_next { nullptr }; Inode* m_prev { nullptr }; @@ -134,6 +137,7 @@ class Inode : public RefCounted<Inode> RefPtr<LocalSocket> m_socket; HashTable<InodeWatcher*> m_watchers; bool m_metadata_dirty { false }; + RefPtr<FIFO> m_fifo; }; } diff --git a/Kernel/FileSystem/VirtualFileSystem.cpp b/Kernel/FileSystem/VirtualFileSystem.cpp index ef8fd319004b..d6aec7a730a7 100644 --- a/Kernel/FileSystem/VirtualFileSystem.cpp +++ b/Kernel/FileSystem/VirtualFileSystem.cpp @@ -292,6 +292,23 @@ KResultOr<NonnullRefPtr<FileDescription>> VFS::open(StringView path, int options if (auto preopen_fd = inode.preopen_fd()) return *preopen_fd; + if (metadata.is_fifo()) { + if (options & O_WRONLY) { + auto description = inode.fifo().open_direction_blocking(FIFO::Direction::Writer); + description->set_rw_mode(options); + description->set_file_flags(options); + description->set_original_inode({}, inode); + return description; + } else if (options & O_RDONLY) { + auto description = inode.fifo().open_direction_blocking(FIFO::Direction::Reader); + description->set_rw_mode(options); + description->set_file_flags(options); + description->set_original_inode({}, inode); + return description; + } + return KResult(-EINVAL); + } + if (metadata.is_device()) { if (custody.mount_flags() & MS_NODEV) return KResult(-EACCES);
967654880037fae4639397326af5f99efc534cd8
2021-05-22 23:27:19
Andreas Kling
systemmonitor: Symbolicate process stacks in a background thread
false
Symbolicate process stacks in a background thread
systemmonitor
diff --git a/Userland/Applications/SystemMonitor/ThreadStackWidget.cpp b/Userland/Applications/SystemMonitor/ThreadStackWidget.cpp index eb07a28b7ff9..e3b4111b8c19 100644 --- a/Userland/Applications/SystemMonitor/ThreadStackWidget.cpp +++ b/Userland/Applications/SystemMonitor/ThreadStackWidget.cpp @@ -9,6 +9,7 @@ #include <LibCore/Timer.h> #include <LibGUI/BoxLayout.h> #include <LibSymbolication/Symbolication.h> +#include <LibThreading/BackgroundAction.h> ThreadStackWidget::ThreadStackWidget() { @@ -16,6 +17,7 @@ ThreadStackWidget::ThreadStackWidget() layout()->set_margins({ 4, 4, 4, 4 }); m_stack_editor = add<GUI::TextEditor>(); m_stack_editor->set_mode(GUI::TextEditor::ReadOnly); + m_stack_editor->set_text("Symbolicating..."); } ThreadStackWidget::~ThreadStackWidget() @@ -42,13 +44,41 @@ void ThreadStackWidget::set_ids(pid_t pid, pid_t tid) m_tid = tid; } +class CompletionEvent : public Core::CustomEvent { +public: + explicit CompletionEvent(Vector<Symbolication::Symbol> symbols) + : Core::CustomEvent(0) + , m_symbols(move(symbols)) + { + } + + Vector<Symbolication::Symbol> const& symbols() const { return m_symbols; } + +private: + Vector<Symbolication::Symbol> m_symbols; +}; + void ThreadStackWidget::refresh() { - auto symbols = Symbolication::symbolicate_thread(m_pid, m_tid); + Threading::BackgroundAction<Vector<Symbolication::Symbol>>::create( + [pid = m_pid, tid = m_tid] { + return Symbolication::symbolicate_thread(pid, tid); + }, + + [weak_this = make_weak_ptr()](auto result) { + if (!weak_this) + return; + Core::EventLoop::main().post_event(const_cast<Core::Object&>(*weak_this), make<CompletionEvent>(move(result))); + }); +} + +void ThreadStackWidget::custom_event(Core::CustomEvent& event) +{ + auto& completion_event = downcast<CompletionEvent>(event); StringBuilder builder; - for (auto& symbol : symbols) { + for (auto& symbol : completion_event.symbols()) { builder.appendff("{:p}", symbol.address); if (!symbol.name.is_empty()) builder.appendff(" {}", symbol.name); diff --git a/Userland/Applications/SystemMonitor/ThreadStackWidget.h b/Userland/Applications/SystemMonitor/ThreadStackWidget.h index b4d405af9b90..a6bb65b8105d 100644 --- a/Userland/Applications/SystemMonitor/ThreadStackWidget.h +++ b/Userland/Applications/SystemMonitor/ThreadStackWidget.h @@ -22,6 +22,7 @@ class ThreadStackWidget final : public GUI::Widget { virtual void show_event(GUI::ShowEvent&) override; virtual void hide_event(GUI::HideEvent&) override; + virtual void custom_event(Core::CustomEvent&) override; pid_t m_pid { -1 }; pid_t m_tid { -1 }; diff --git a/Userland/Applications/SystemMonitor/main.cpp b/Userland/Applications/SystemMonitor/main.cpp index 5e42f3783ed2..4e101f8f2c06 100644 --- a/Userland/Applications/SystemMonitor/main.cpp +++ b/Userland/Applications/SystemMonitor/main.cpp @@ -103,7 +103,7 @@ int main(int argc, char** argv) sched_setparam(0, &param); } - if (pledge("stdio proc recvfd sendfd rpath exec unix", nullptr) < 0) { + if (pledge("stdio thread proc recvfd sendfd rpath exec unix", nullptr) < 0) { perror("pledge"); return 1; }
cf188df86cbe08428aba24be5fac36f62d539850
2021-10-28 14:53:44
Sam Atkins
libgfx: Make style painters use east const and virtual specifiers
false
Make style painters use east const and virtual specifiers
libgfx
diff --git a/Userland/Libraries/LibGfx/ClassicStylePainter.cpp b/Userland/Libraries/LibGfx/ClassicStylePainter.cpp index c8c940662b5a..d0d953d06c46 100644 --- a/Userland/Libraries/LibGfx/ClassicStylePainter.cpp +++ b/Userland/Libraries/LibGfx/ClassicStylePainter.cpp @@ -14,7 +14,7 @@ namespace Gfx { -void ClassicStylePainter::paint_tab_button(Painter& painter, const IntRect& rect, const Palette& palette, bool active, bool hovered, bool enabled, bool top, bool in_active_window) +void ClassicStylePainter::paint_tab_button(Painter& painter, IntRect const& rect, Palette const& palette, bool active, bool hovered, bool enabled, bool top, bool in_active_window) { Color base_color = palette.button(); Color highlight_color2 = palette.threed_highlight(); @@ -164,7 +164,7 @@ static void paint_button_new(Painter& painter, IntRect const& a_rect, Palette co } } -void ClassicStylePainter::paint_button(Painter& painter, const IntRect& rect, const Palette& palette, ButtonStyle button_style, bool pressed, bool hovered, bool checked, bool enabled, bool focused) +void ClassicStylePainter::paint_button(Painter& painter, IntRect const& rect, Palette const& palette, ButtonStyle button_style, bool pressed, bool hovered, bool checked, bool enabled, bool focused) { if (button_style == ButtonStyle::Normal || button_style == ButtonStyle::ThickCap) return paint_button_new(painter, rect, palette, button_style, pressed, checked, hovered, enabled, focused); @@ -213,7 +213,7 @@ void ClassicStylePainter::paint_button(Painter& painter, const IntRect& rect, co } } -void ClassicStylePainter::paint_frame(Painter& painter, const IntRect& rect, const Palette& palette, FrameShape shape, FrameShadow shadow, int thickness, bool skip_vertical_lines) +void ClassicStylePainter::paint_frame(Painter& painter, IntRect const& rect, Palette const& palette, FrameShape shape, FrameShadow shadow, int thickness, bool skip_vertical_lines) { Color top_left_color; Color bottom_right_color; @@ -280,7 +280,7 @@ void ClassicStylePainter::paint_frame(Painter& painter, const IntRect& rect, con } } -void ClassicStylePainter::paint_window_frame(Painter& painter, const IntRect& rect, const Palette& palette) +void ClassicStylePainter::paint_window_frame(Painter& painter, IntRect const& rect, Palette const& palette) { Color base_color = palette.button(); Color dark_shade = palette.threed_shadow2(); @@ -306,7 +306,7 @@ void ClassicStylePainter::paint_window_frame(Painter& painter, const IntRect& re painter.draw_line(rect.bottom_left().translated(3, -3), rect.bottom_right().translated(-3, -3), base_color); } -void ClassicStylePainter::paint_progressbar(Painter& painter, const IntRect& rect, const Palette& palette, int min, int max, int value, const StringView& text, Orientation orientation) +void ClassicStylePainter::paint_progressbar(Painter& painter, IntRect const& rect, Palette const& palette, int min, int max, int value, StringView const& text, Orientation orientation) { // First we fill the entire widget with the gradient. This incurs a bit of // overdraw but ensures a consistent look throughout the progression. @@ -347,14 +347,14 @@ static RefPtr<Gfx::Bitmap> s_filled_circle_bitmap; static RefPtr<Gfx::Bitmap> s_changing_filled_circle_bitmap; static RefPtr<Gfx::Bitmap> s_changing_unfilled_circle_bitmap; -static const Gfx::Bitmap& circle_bitmap(bool checked, bool changing) +static Gfx::Bitmap const& circle_bitmap(bool checked, bool changing) { if (changing) return checked ? *s_changing_filled_circle_bitmap : *s_changing_unfilled_circle_bitmap; return checked ? *s_filled_circle_bitmap : *s_unfilled_circle_bitmap; } -void ClassicStylePainter::paint_radio_button(Painter& painter, const IntRect& rect, const Palette&, bool is_checked, bool is_being_pressed) +void ClassicStylePainter::paint_radio_button(Painter& painter, IntRect const& rect, Palette const&, bool is_checked, bool is_being_pressed) { if (!s_unfilled_circle_bitmap) { s_unfilled_circle_bitmap = Bitmap::try_load_from_file("/res/icons/serenity/unfilled-radio-circle.png"); @@ -367,7 +367,7 @@ void ClassicStylePainter::paint_radio_button(Painter& painter, const IntRect& re painter.blit(rect.location(), bitmap, bitmap.rect()); } -static const char* s_checked_bitmap_data = { +static char const* s_checked_bitmap_data = { " " " # " " ## " @@ -380,10 +380,10 @@ static const char* s_checked_bitmap_data = { }; static Gfx::CharacterBitmap* s_checked_bitmap; -static const int s_checked_bitmap_width = 9; -static const int s_checked_bitmap_height = 9; +static int const s_checked_bitmap_width = 9; +static int const s_checked_bitmap_height = 9; -void ClassicStylePainter::paint_check_box(Painter& painter, const IntRect& rect, const Palette& palette, bool is_enabled, bool is_checked, bool is_being_pressed) +void ClassicStylePainter::paint_check_box(Painter& painter, IntRect const& rect, Palette const& palette, bool is_enabled, bool is_checked, bool is_being_pressed) { painter.fill_rect(rect, is_enabled ? palette.base() : palette.window()); paint_frame(painter, rect, palette, Gfx::FrameShape::Container, Gfx::FrameShadow::Sunken, 2); @@ -400,7 +400,7 @@ void ClassicStylePainter::paint_check_box(Painter& painter, const IntRect& rect, } } -void ClassicStylePainter::paint_transparency_grid(Painter& painter, const IntRect& rect, const Palette& palette) +void ClassicStylePainter::paint_transparency_grid(Painter& painter, IntRect const& rect, Palette const& palette) { painter.fill_rect_with_checkerboard(rect, { 8, 8 }, palette.base().darkened(0.9), palette.base()); } diff --git a/Userland/Libraries/LibGfx/ClassicStylePainter.h b/Userland/Libraries/LibGfx/ClassicStylePainter.h index 4043c8c965ef..5f64321a9ea6 100644 --- a/Userland/Libraries/LibGfx/ClassicStylePainter.h +++ b/Userland/Libraries/LibGfx/ClassicStylePainter.h @@ -15,14 +15,14 @@ namespace Gfx { class ClassicStylePainter : public BaseStylePainter { public: - void paint_button(Painter&, const IntRect&, const Palette&, ButtonStyle, bool pressed, bool hovered = false, bool checked = false, bool enabled = true, bool focused = false) override; - void paint_tab_button(Painter&, const IntRect&, const Palette&, bool active, bool hovered, bool enabled, bool top, bool in_active_window) override; - void paint_frame(Painter&, const IntRect&, const Palette&, FrameShape, FrameShadow, int thickness, bool skip_vertical_lines = false) override; - void paint_window_frame(Painter&, const IntRect&, const Palette&) override; - void paint_progressbar(Painter&, const IntRect&, const Palette&, int min, int max, int value, const StringView& text, Orientation = Orientation::Horizontal) override; - void paint_radio_button(Painter&, const IntRect&, const Palette&, bool is_checked, bool is_being_pressed) override; - void paint_check_box(Painter&, const IntRect&, const Palette&, bool is_enabled, bool is_checked, bool is_being_pressed) override; - void paint_transparency_grid(Painter&, const IntRect&, const Palette&) override; + virtual void paint_button(Painter&, IntRect const&, Palette const&, ButtonStyle, bool pressed, bool hovered = false, bool checked = false, bool enabled = true, bool focused = false) override; + virtual void paint_tab_button(Painter&, IntRect const&, Palette const&, bool active, bool hovered, bool enabled, bool top, bool in_active_window) override; + virtual void paint_frame(Painter&, IntRect const&, Palette const&, FrameShape, FrameShadow, int thickness, bool skip_vertical_lines = false) override; + virtual void paint_window_frame(Painter&, IntRect const&, Palette const&) override; + virtual void paint_progressbar(Painter&, IntRect const&, Palette const&, int min, int max, int value, StringView const& text, Orientation = Orientation::Horizontal) override; + virtual void paint_radio_button(Painter&, IntRect const&, Palette const&, bool is_checked, bool is_being_pressed) override; + virtual void paint_check_box(Painter&, IntRect const&, Palette const&, bool is_enabled, bool is_checked, bool is_being_pressed) override; + virtual void paint_transparency_grid(Painter&, IntRect const&, Palette const&) override; }; } diff --git a/Userland/Libraries/LibGfx/StylePainter.h b/Userland/Libraries/LibGfx/StylePainter.h index 67381790316f..fa2d34cb8a10 100644 --- a/Userland/Libraries/LibGfx/StylePainter.h +++ b/Userland/Libraries/LibGfx/StylePainter.h @@ -37,14 +37,14 @@ class BaseStylePainter { public: virtual ~BaseStylePainter() { } - virtual void paint_button(Painter&, const IntRect&, const Palette&, ButtonStyle, bool pressed, bool hovered = false, bool checked = false, bool enabled = true, bool focused = false) = 0; - virtual void paint_tab_button(Painter&, const IntRect&, const Palette&, bool active, bool hovered, bool enabled, bool top, bool in_active_window) = 0; - virtual void paint_frame(Painter&, const IntRect&, const Palette&, FrameShape, FrameShadow, int thickness, bool skip_vertical_lines = false) = 0; - virtual void paint_window_frame(Painter&, const IntRect&, const Palette&) = 0; - virtual void paint_progressbar(Painter&, const IntRect&, const Palette&, int min, int max, int value, const StringView& text, Orientation = Orientation::Horizontal) = 0; - virtual void paint_radio_button(Painter&, const IntRect&, const Palette&, bool is_checked, bool is_being_pressed) = 0; - virtual void paint_check_box(Painter&, const IntRect&, const Palette&, bool is_enabled, bool is_checked, bool is_being_pressed) = 0; - virtual void paint_transparency_grid(Painter&, const IntRect&, const Palette&) = 0; + virtual void paint_button(Painter&, IntRect const&, Palette const&, ButtonStyle, bool pressed, bool hovered = false, bool checked = false, bool enabled = true, bool focused = false) = 0; + virtual void paint_tab_button(Painter&, IntRect const&, Palette const&, bool active, bool hovered, bool enabled, bool top, bool in_active_window) = 0; + virtual void paint_frame(Painter&, IntRect const&, Palette const&, FrameShape, FrameShadow, int thickness, bool skip_vertical_lines = false) = 0; + virtual void paint_window_frame(Painter&, IntRect const&, Palette const&) = 0; + virtual void paint_progressbar(Painter&, IntRect const&, Palette const&, int min, int max, int value, StringView const& text, Orientation = Orientation::Horizontal) = 0; + virtual void paint_radio_button(Painter&, IntRect const&, Palette const&, bool is_checked, bool is_being_pressed) = 0; + virtual void paint_check_box(Painter&, IntRect const&, Palette const&, bool is_enabled, bool is_checked, bool is_being_pressed) = 0; + virtual void paint_transparency_grid(Painter&, IntRect const&, Palette const&) = 0; protected: BaseStylePainter() { } @@ -55,14 +55,14 @@ class StylePainter { static BaseStylePainter& current(); // FIXME: These are here for API compatibility, we should probably remove them and move BaseStylePainter into here - static void paint_button(Painter&, const IntRect&, const Palette&, ButtonStyle, bool pressed, bool hovered = false, bool checked = false, bool enabled = true, bool focused = false); - static void paint_tab_button(Painter&, const IntRect&, const Palette&, bool active, bool hovered, bool enabled, bool top, bool in_active_window); - static void paint_frame(Painter&, const IntRect&, const Palette&, FrameShape, FrameShadow, int thickness, bool skip_vertical_lines = false); - static void paint_window_frame(Painter&, const IntRect&, const Palette&); - static void paint_progressbar(Painter&, const IntRect&, const Palette&, int min, int max, int value, const StringView& text, Orientation = Orientation::Horizontal); - static void paint_radio_button(Painter&, const IntRect&, const Palette&, bool is_checked, bool is_being_pressed); - static void paint_check_box(Painter&, const IntRect&, const Palette&, bool is_enabled, bool is_checked, bool is_being_pressed); - static void paint_transparency_grid(Painter&, const IntRect&, const Palette&); + static void paint_button(Painter&, IntRect const&, Palette const&, ButtonStyle, bool pressed, bool hovered = false, bool checked = false, bool enabled = true, bool focused = false); + static void paint_tab_button(Painter&, IntRect const&, Palette const&, bool active, bool hovered, bool enabled, bool top, bool in_active_window); + static void paint_frame(Painter&, IntRect const&, Palette const&, FrameShape, FrameShadow, int thickness, bool skip_vertical_lines = false); + static void paint_window_frame(Painter&, IntRect const&, Palette const&); + static void paint_progressbar(Painter&, IntRect const&, Palette const&, int min, int max, int value, StringView const& text, Orientation = Orientation::Horizontal); + static void paint_radio_button(Painter&, IntRect const&, Palette const&, bool is_checked, bool is_being_pressed); + static void paint_check_box(Painter&, IntRect const&, Palette const&, bool is_enabled, bool is_checked, bool is_being_pressed); + static void paint_transparency_grid(Painter&, IntRect const&, Palette const&); }; }
431776ebb7b3ef95f8b86614966eb0c54113e6d8
2022-04-05 15:16:48
Ali Mohammad Pur
js: Print the accumulator instead of the returned value in BC mode
false
Print the accumulator instead of the returned value in BC mode
js
diff --git a/Userland/Utilities/js.cpp b/Userland/Utilities/js.cpp index 56f0a306aa55..bb15a8969185 100644 --- a/Userland/Utilities/js.cpp +++ b/Userland/Utilities/js.cpp @@ -1051,7 +1051,11 @@ static bool parse_and_run(JS::Interpreter& interpreter, StringView source, Strin if (s_run_bytecode) { JS::Bytecode::Interpreter bytecode_interpreter(interpreter.global_object(), interpreter.realm()); - result = bytecode_interpreter.run(*executable); + auto result_or_error = bytecode_interpreter.run_and_return_frame(*executable, nullptr); + if (result_or_error.value.is_error()) + result = result_or_error.value.release_error(); + else + result = result_or_error.frame->registers[0]; } else { return ReturnEarly::Yes; }
5db8940c9e6f505208e7cec0543f772ae56979c9
2020-03-20 19:11:23
Andreas Kling
libjs: Use StringBuilder::join()
false
Use StringBuilder::join()
libjs
diff --git a/Libraries/LibJS/AST.cpp b/Libraries/LibJS/AST.cpp index b9ee359d4a88..7edbc26e44d3 100644 --- a/Libraries/LibJS/AST.cpp +++ b/Libraries/LibJS/AST.cpp @@ -393,16 +393,8 @@ void NullLiteral::dump(int indent) const void FunctionNode::dump(int indent, const char* class_name) const { - bool first_time = true; StringBuilder parameters_builder; - for (const auto& parameter : parameters()) { - if (first_time) - first_time = false; - else - parameters_builder.append(','); - - parameters_builder.append(parameter); - } + parameters_builder.join(',', parameters()); print_indent(indent); printf("%s '%s(%s)'\n", class_name, name().characters(), parameters_builder.build().characters());
352c1fec2d5c60cb6fb97f193aebaf5bb29ad611
2022-12-27 19:58:16
thankyouverycool
taskbar: Propagate more errors on widget population
false
Propagate more errors on widget population
taskbar
diff --git a/Userland/Services/Taskbar/TaskbarWindow.cpp b/Userland/Services/Taskbar/TaskbarWindow.cpp index 2c6e3e9c34e7..d52a52b0fd2a 100644 --- a/Userland/Services/Taskbar/TaskbarWindow.cpp +++ b/Userland/Services/Taskbar/TaskbarWindow.cpp @@ -68,40 +68,36 @@ TaskbarWindow::TaskbarWindow() set_title("Taskbar"); on_screen_rects_change(GUI::Desktop::the().rects(), GUI::Desktop::the().main_screen_index()); - - auto& main_widget = set_main_widget<TaskbarWidget>(); - main_widget.set_layout<GUI::HorizontalBoxLayout>(); - main_widget.layout()->set_margins({ 2, 3, 0, 3 }); } ErrorOr<void> TaskbarWindow::populate_taskbar() { - if (!main_widget()) - return Error::from_string_literal("TaskbarWindow::populate_taskbar: main_widget is not set"); + auto main_widget = TRY(try_set_main_widget<TaskbarWidget>()); + (void)TRY(main_widget->try_set_layout<GUI::HorizontalBoxLayout>()); + main_widget->layout()->set_margins({ 2, 3, 0, 3 }); m_quick_launch = TRY(Taskbar::QuickLaunchWidget::create()); - main_widget()->add_child(*m_quick_launch); + TRY(main_widget->try_add_child(*m_quick_launch)); - m_task_button_container = main_widget()->add<GUI::Widget>(); - m_task_button_container->set_layout<GUI::HorizontalBoxLayout>(); + m_task_button_container = TRY(main_widget->try_add<GUI::Widget>()); + (void)TRY(m_task_button_container->try_set_layout<GUI::HorizontalBoxLayout>()); m_task_button_container->layout()->set_spacing(3); m_default_icon = TRY(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/window.png"sv)); - m_applet_area_container = main_widget()->add<GUI::Frame>(); + m_applet_area_container = TRY(main_widget->try_add<GUI::Frame>()); m_applet_area_container->set_frame_thickness(1); m_applet_area_container->set_frame_shape(Gfx::FrameShape::Box); m_applet_area_container->set_frame_shadow(Gfx::FrameShadow::Sunken); - m_clock_widget = main_widget()->add<Taskbar::ClockWidget>(); + m_clock_widget = TRY(main_widget->try_add<Taskbar::ClockWidget>()); - m_show_desktop_button = GUI::Button::construct(); + m_show_desktop_button = TRY(main_widget->try_add<GUI::Button>()); m_show_desktop_button->set_tooltip("Show Desktop"); - m_show_desktop_button->set_icon(GUI::Icon::default_icon("desktop"sv).bitmap_for_size(16)); + m_show_desktop_button->set_icon(TRY(GUI::Icon::try_create_default_icon("desktop"sv)).bitmap_for_size(16)); m_show_desktop_button->set_button_style(Gfx::ButtonStyle::Coolbar); m_show_desktop_button->set_fixed_size(24, 24); m_show_desktop_button->on_click = TaskbarWindow::show_desktop_button_clicked; - main_widget()->add_child(*m_show_desktop_button); return {}; }
e0a68d4b6e9ecd8343bcb486c4ec7054b8e920c6
2021-05-15 17:30:23
Ömer Kurttekin
hackstudio: Pledge "fattr"
false
Pledge "fattr"
hackstudio
diff --git a/Userland/DevTools/HackStudio/main.cpp b/Userland/DevTools/HackStudio/main.cpp index 8efdd5f0be6d..b54d82e2070c 100644 --- a/Userland/DevTools/HackStudio/main.cpp +++ b/Userland/DevTools/HackStudio/main.cpp @@ -40,7 +40,7 @@ static void update_path_environment_variable(); int main(int argc, char** argv) { - if (pledge("stdio recvfd sendfd tty rpath cpath wpath proc exec unix thread ptrace", nullptr) < 0) { + if (pledge("stdio recvfd sendfd tty rpath cpath wpath proc exec unix fattr thread ptrace", nullptr) < 0) { perror("pledge"); return 1; }
bceee87f6131f37464aac9c0f46ce348410ae997
2020-12-28 03:57:07
Brendan Coles
libelf: Reject ELF with program header p_filesz larger than p_memsz
false
Reject ELF with program header p_filesz larger than p_memsz
libelf
diff --git a/Libraries/LibELF/Validation.cpp b/Libraries/LibELF/Validation.cpp index 12d7b29d0a1d..b7e1584cd347 100644 --- a/Libraries/LibELF/Validation.cpp +++ b/Libraries/LibELF/Validation.cpp @@ -193,6 +193,13 @@ bool validate_program_headers(const Elf32_Ehdr& elf_header, size_t file_size, co for (size_t header_index = 0; header_index < num_program_headers; ++header_index) { auto& program_header = program_header_begin[header_index]; + + if (program_header.p_filesz > program_header.p_memsz) { + if (verbose) + dbgln("Program header ({}) has p_filesz ({}) larger than p_memsz ({})", header_index, program_header.p_filesz, program_header.p_memsz); + return false; + } + switch (program_header.p_type) { case PT_INTERP: // We checked above that file_size was >= buffer size. We only care about buffer size anyway, we're trying to read this!
3e3f760808e614ca70d97294013cb58f2a0deaf5
2021-08-23 03:32:09
Andreas Kling
kernel: Fix some trivial clang-tidy warnings in Thread.{cpp,h}
false
Fix some trivial clang-tidy warnings in Thread.{cpp,h}
kernel
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp index 08bdd31f04d0..3c5d4ec18abf 100644 --- a/Kernel/Thread.cpp +++ b/Kernel/Thread.cpp @@ -61,7 +61,7 @@ Thread::Thread(NonnullRefPtr<Process> process, NonnullOwnPtr<Memory::Region> ker : m_process(move(process)) , m_kernel_stack_region(move(kernel_stack_region)) , m_name(move(name)) - , m_block_timer(block_timer) + , m_block_timer(move(block_timer)) { bool is_first_thread = m_process->add_thread(*this); if (is_first_thread) { @@ -142,7 +142,7 @@ Thread::~Thread() { { // We need to explicitly remove ourselves from the thread list - // here. We may get pre-empted in the middle of destructing this + // here. We may get preempted in the middle of destructing this // thread, which causes problems if the thread list is iterated. // Specifically, if this is the last thread of a process, checking // block conditions would access m_process, which would be in @@ -252,7 +252,7 @@ u32 Thread::unblock_from_lock(Kernel::Mutex& lock) set_state(Thread::Runnable); }; if (Processor::current().in_irq()) { - Processor::current().deferred_call_queue([do_unblock = move(do_unblock), self = make_weak_ptr()]() { + Processor::deferred_call_queue([do_unblock = move(do_unblock), self = make_weak_ptr()]() { if (auto this_thread = self.strong_ref()) do_unblock(); }); @@ -273,7 +273,7 @@ void Thread::unblock_from_blocker(Blocker& blocker) unblock(); }; if (Processor::current().in_irq()) { - Processor::current().deferred_call_queue([do_unblock = move(do_unblock), self = make_weak_ptr()]() { + Processor::deferred_call_queue([do_unblock = move(do_unblock), self = make_weak_ptr()]() { if (auto this_thread = self.strong_ref()) do_unblock(); }); @@ -599,12 +599,8 @@ void Thread::check_dispatch_pending_signal() } } - switch (result) { - case DispatchSignalResult::Yield: + if (result == DispatchSignalResult::Yield) { yield_without_releasing_big_lock(); - break; - default: - break; } } @@ -787,8 +783,9 @@ static DefaultSignalAction default_signal_action(u8 signal) case SIGTTIN: case SIGTTOU: return DefaultSignalAction::Stop; + default: + VERIFY_NOT_REACHED(); } - VERIFY_NOT_REACHED(); } bool Thread::should_ignore_signal(u8 signal) const @@ -1021,7 +1018,7 @@ RegisterState& Thread::get_register_dump_from_stack() auto* trap = current_trap(); // We should *always* have a trap. If we don't we're probably a kernel - // thread that hasn't been pre-empted. If we want to support this, we + // thread that hasn't been preempted. If we want to support this, we // need to capture the registers probably into m_regs and return it VERIFY(trap); diff --git a/Kernel/Thread.h b/Kernel/Thread.h index 314318668097..c4ee8a04ed28 100644 --- a/Kernel/Thread.h +++ b/Kernel/Thread.h @@ -151,7 +151,6 @@ class Thread friend class Mutex; friend class Process; - friend class ProtectedProcessBase; friend class Scheduler; friend struct ThreadReadyQueue; @@ -161,8 +160,6 @@ class Thread return Processor::current_thread(); } - static void initialize(); - static KResultOr<NonnullRefPtr<Thread>> try_create(NonnullRefPtr<Process>); ~Thread(); @@ -253,11 +250,6 @@ class Thread } } - [[nodiscard]] bool timed_out() const - { - return m_type == InterruptedByTimeout; - } - private: Type m_type; }; @@ -696,7 +688,7 @@ class Thread }; typedef Vector<FDInfo, FD_SETSIZE> FDVector; - SelectBlocker(FDVector& fds); + explicit SelectBlocker(FDVector& fds); virtual ~SelectBlocker(); virtual bool unblock(bool, void*) override; @@ -750,7 +742,7 @@ class Thread friend class WaitBlocker; public: - WaitBlockCondition(Process& process) + explicit WaitBlockCondition(Process& process) : m_process(process) { } @@ -1296,7 +1288,7 @@ class Thread mutable RecursiveSpinlock m_block_lock; NonnullRefPtr<Process> m_process; ThreadID m_tid { -1 }; - ThreadRegisters m_regs; + ThreadRegisters m_regs {}; DebugRegisterState m_debug_register_state {}; TrapFrame* m_current_trap { nullptr }; u32 m_saved_critical { 1 };
49e7ffc06a51632fc6210660d7765f2dfbe408d7
2019-04-20 18:10:59
Andreas Kling
windowserver: Introduce a WM event mask so Taskbar can ignore window rects.
false
Introduce a WM event mask so Taskbar can ignore window rects.
windowserver
diff --git a/Applications/Taskbar/TaskbarWindow.cpp b/Applications/Taskbar/TaskbarWindow.cpp index deaae2d789a6..562d6aad633c 100644 --- a/Applications/Taskbar/TaskbarWindow.cpp +++ b/Applications/Taskbar/TaskbarWindow.cpp @@ -76,6 +76,17 @@ void TaskbarWindow::wm_event(GWMEvent& event) update(); break; } + case GEvent::WM_WindowRectChanged: { +#ifdef EVENT_DEBUG + auto& changed_event = static_cast<GWMWindowRectChangedEvent&>(event); + dbgprintf("WM_WindowRectChanged: client_id=%d, window_id=%d, rect=%s\n", + changed_event.client_id(), + changed_event.window_id(), + changed_event.rect().to_string().characters() + ); +#endif + break; + } case GEvent::WM_WindowIconChanged: { auto& changed_event = static_cast<GWMWindowIconChangedEvent&>(event); #ifdef EVENT_DEBUG diff --git a/LibGUI/GEvent.h b/LibGUI/GEvent.h index ecbe51ead3ef..25636afbef68 100644 --- a/LibGUI/GEvent.h +++ b/LibGUI/GEvent.h @@ -30,9 +30,13 @@ class GEvent : public CEvent{ FocusOut, WindowCloseRequest, ContextMenu, + + __Begin_WM_Events, WM_WindowRemoved, WM_WindowStateChanged, + WM_WindowRectChanged, WM_WindowIconChanged, + __End_WM_Events, }; GEvent() { } @@ -95,6 +99,20 @@ class GWMWindowStateChangedEvent : public GWMEvent { bool m_minimized; }; +class GWMWindowRectChangedEvent : public GWMEvent { +public: + GWMWindowRectChangedEvent(int client_id, int window_id, const Rect& rect) + : GWMEvent(GEvent::Type::WM_WindowRectChanged, client_id, window_id) + , m_rect(rect) + { + } + + Rect rect() const { return m_rect; } + +private: + Rect m_rect; +}; + class GWMWindowIconChangedEvent : public GWMEvent { public: GWMWindowIconChangedEvent(int client_id, int window_id, const String& icon_path) diff --git a/LibGUI/GEventLoop.cpp b/LibGUI/GEventLoop.cpp index b14c621e913d..809943a738f3 100644 --- a/LibGUI/GEventLoop.cpp +++ b/LibGUI/GEventLoop.cpp @@ -175,6 +175,8 @@ void GEventLoop::handle_wm_event(const WSAPI_ServerMessage& event, GWindow& wind #endif if (event.type == WSAPI_ServerMessage::WM_WindowStateChanged) return post_event(window, make<GWMWindowStateChangedEvent>(event.wm.client_id, event.wm.window_id, String(event.text, event.text_length), event.wm.rect, event.wm.is_active, (GWindowType)event.wm.window_type, event.wm.is_minimized)); + if (event.type == WSAPI_ServerMessage::WM_WindowRectChanged) + return post_event(window, make<GWMWindowRectChangedEvent>(event.wm.client_id, event.wm.window_id, event.wm.rect)); if (event.type == WSAPI_ServerMessage::WM_WindowIconChanged) return post_event(window, make<GWMWindowIconChangedEvent>(event.wm.client_id, event.wm.window_id, String(event.text, event.text_length))); if (event.type == WSAPI_ServerMessage::WM_WindowRemoved) diff --git a/LibGUI/GWindow.cpp b/LibGUI/GWindow.cpp index de38f0ffcc47..505338f7d68f 100644 --- a/LibGUI/GWindow.cpp +++ b/LibGUI/GWindow.cpp @@ -277,7 +277,7 @@ void GWindow::event(CEvent& event) return; } - if (event.type() == GEvent::WM_WindowRemoved || event.type() == GEvent::WM_WindowStateChanged || event.type() == GEvent::WM_WindowIconChanged) + if (event.type() > GEvent::__Begin_WM_Events && event.type() < GEvent::__End_WM_Events) return wm_event(static_cast<GWMEvent&>(event)); CObject::event(event); diff --git a/Servers/WindowServer/WSAPITypes.h b/Servers/WindowServer/WSAPITypes.h index c7377d3e005c..99f74bbb1d2f 100644 --- a/Servers/WindowServer/WSAPITypes.h +++ b/Servers/WindowServer/WSAPITypes.h @@ -57,6 +57,13 @@ enum class WSAPI_StandardCursor : unsigned char { ResizeVertical, }; +enum WSAPI_WMEventMask : unsigned { + WindowRectChanges = 1 << 0, + WindowStateChanges = 1 << 1, + WindowIconChanges = 1 << 2, + WindowRemovals = 1 << 3, +}; + struct WSAPI_ServerMessage { enum Type : unsigned { Invalid, @@ -97,6 +104,7 @@ struct WSAPI_ServerMessage { ScreenRectChanged, WM_WindowRemoved, WM_WindowStateChanged, + WM_WindowRectChanged, WM_WindowIconChanged, }; Type type { Invalid }; diff --git a/Servers/WindowServer/WSEvent.h b/Servers/WindowServer/WSEvent.h index 4c9d85f5bff0..e667fd5053e7 100644 --- a/Servers/WindowServer/WSEvent.h +++ b/Servers/WindowServer/WSEvent.h @@ -29,6 +29,7 @@ class WSEvent : public CEvent { WM_WindowRemoved, WM_WindowStateChanged, + WM_WindowRectChanged, WM_WindowIconChanged, __Begin_API_Client_Requests, @@ -750,3 +751,17 @@ class WSWMWindowIconChangedEvent : public WSWMEvent { private: String m_icon_path; }; + +class WSWMWindowRectChangedEvent : public WSWMEvent { +public: + WSWMWindowRectChangedEvent(int client_id, int window_id, const Rect& rect) + : WSWMEvent(WSEvent::WM_WindowRectChanged, client_id, window_id) + , m_rect(rect) + { + } + + Rect rect() const { return m_rect; } + +private: + Rect m_rect; +}; diff --git a/Servers/WindowServer/WSWindow.cpp b/Servers/WindowServer/WSWindow.cpp index b8f3df4ca8ae..4bb1e16cd8ad 100644 --- a/Servers/WindowServer/WSWindow.cpp +++ b/Servers/WindowServer/WSWindow.cpp @@ -38,8 +38,10 @@ WSWindow::WSWindow(WSClientConnection& client, WSWindowType window_type, int win , m_frame(*this) { // FIXME: This should not be hard-coded here. - if (m_type == WSWindowType::Taskbar) + if (m_type == WSWindowType::Taskbar) { + m_wm_event_mask = WSAPI_WMEventMask::WindowStateChanges | WSAPI_WMEventMask::WindowRemovals | WSAPI_WMEventMask::WindowIconChanges; m_listens_to_wm_events = true; + } WSWindowManager::the().add_window(*this); } @@ -210,6 +212,15 @@ void WSWindow::event(CEvent& event) break; } + case WSEvent::WM_WindowRectChanged: { + auto& changed_event = static_cast<const WSWMWindowRectChangedEvent&>(event); + server_message.type = WSAPI_ServerMessage::Type::WM_WindowRectChanged; + server_message.wm.client_id = changed_event.client_id(); + server_message.wm.window_id = changed_event.window_id(); + server_message.wm.rect = changed_event.rect(); + break; + } + default: break; } diff --git a/Servers/WindowServer/WSWindow.h b/Servers/WindowServer/WSWindow.h index 4ac39690ed7b..b256504a04db 100644 --- a/Servers/WindowServer/WSWindow.h +++ b/Servers/WindowServer/WSWindow.h @@ -19,6 +19,9 @@ class WSWindow final : public CObject, public InlineLinkedListNode<WSWindow> { WSWindow(CObject&, WSWindowType); virtual ~WSWindow() override; + unsigned wm_event_mask() const { return m_wm_event_mask; } + void set_wm_event_mask(unsigned mask) { m_wm_event_mask = mask; } + Color background_color() const { return m_background_color; } void set_background_color(Color color) { m_background_color = color; } @@ -156,4 +159,5 @@ class WSWindow final : public CObject, public InlineLinkedListNode<WSWindow> { RetainPtr<WSCursor> m_override_cursor; WSWindowFrame m_frame; Color m_background_color { Color::LightGray }; + unsigned m_wm_event_mask { 0 }; }; diff --git a/Servers/WindowServer/WSWindowManager.cpp b/Servers/WindowServer/WSWindowManager.cpp index af0c3332278f..6bbe3d8cb267 100644 --- a/Servers/WindowServer/WSWindowManager.cpp +++ b/Servers/WindowServer/WSWindowManager.cpp @@ -19,6 +19,7 @@ #include <WindowServer/WSCursor.h> #include <WindowServer/WSButton.h> #include <LibCore/CTimer.h> +#include <WindowServer/WSAPITypes.h> //#define DEBUG_COUNTERS //#define RESIZE_DEBUG @@ -311,6 +312,8 @@ void WSWindowManager::remove_window(WSWindow& window) m_switcher.refresh(); for_each_window_listening_to_wm_events([&window] (WSWindow& listener) { + if (!(listener.wm_event_mask() & WSAPI_WMEventMask::WindowRemovals)) + return IterationDecision::Continue; if (window.client()) WSEventLoop::the().post_event(listener, make<WSWMWindowRemovedEvent>(window.client()->client_id(), window.window_id())); return IterationDecision::Continue; @@ -319,12 +322,24 @@ void WSWindowManager::remove_window(WSWindow& window) void WSWindowManager::tell_wm_listener_about_window(WSWindow& listener, WSWindow& window) { + if (!(listener.wm_event_mask() & WSAPI_WMEventMask::WindowStateChanges)) + return; if (window.client()) WSEventLoop::the().post_event(listener, make<WSWMWindowStateChangedEvent>(window.client()->client_id(), window.window_id(), window.title(), window.rect(), window.is_active(), window.type(), window.is_minimized())); } +void WSWindowManager::tell_wm_listener_about_window_rect(WSWindow& listener, WSWindow& window) +{ + if (!(listener.wm_event_mask() & WSAPI_WMEventMask::WindowRectChanges)) + return; + if (window.client()) + WSEventLoop::the().post_event(listener, make<WSWMWindowRectChangedEvent>(window.client()->client_id(), window.window_id(), window.rect())); +} + void WSWindowManager::tell_wm_listener_about_window_icon(WSWindow& listener, WSWindow& window) { + if (!(listener.wm_event_mask() & WSAPI_WMEventMask::WindowIconChanges)) + return; if (window.client()) WSEventLoop::the().post_event(listener, make<WSWMWindowIconChangedEvent>(window.client()->client_id(), window.window_id(), window.icon_path())); } @@ -345,6 +360,14 @@ void WSWindowManager::tell_wm_listeners_window_icon_changed(WSWindow& window) }); } +void WSWindowManager::tell_wm_listeners_window_rect_changed(WSWindow& window) +{ + for_each_window_listening_to_wm_events([&] (WSWindow& listener) { + tell_wm_listener_about_window_rect(listener, window); + return IterationDecision::Continue; + }); +} + void WSWindowManager::notify_title_changed(WSWindow& window) { dbgprintf("[WM] WSWindow{%p} title set to '%s'\n", &window, window.title().characters()); @@ -364,7 +387,7 @@ void WSWindowManager::notify_rect_changed(WSWindow& window, const Rect& old_rect #endif if (m_switcher.is_visible() && window.type() != WSWindowType::WindowSwitcher) m_switcher.refresh(); - tell_wm_listeners_window_state_changed(window); + tell_wm_listeners_window_rect_changed(window); } void WSWindowManager::notify_minimization_state_changed(WSWindow& window) diff --git a/Servers/WindowServer/WSWindowManager.h b/Servers/WindowServer/WSWindowManager.h index 0c1711e5c95e..a2d2bdb664b0 100644 --- a/Servers/WindowServer/WSWindowManager.h +++ b/Servers/WindowServer/WSWindowManager.h @@ -112,6 +112,7 @@ class WSWindowManager : public CObject { void tell_wm_listeners_window_state_changed(WSWindow&); void tell_wm_listeners_window_icon_changed(WSWindow&); + void tell_wm_listeners_window_rect_changed(WSWindow&); private: void process_mouse_event(const WSMouseEvent&, WSWindow*& event_window); @@ -139,6 +140,7 @@ class WSWindowManager : public CObject { void tick_clock(); void tell_wm_listener_about_window(WSWindow& listener, WSWindow&); void tell_wm_listener_about_window_icon(WSWindow& listener, WSWindow&); + void tell_wm_listener_about_window_rect(WSWindow& listener, WSWindow&); void pick_new_active_window(); WSScreen& m_screen;
89febfcd307a2a3abe2d74508857be94be849a90
2021-05-14 16:51:47
Andreas Kling
meta: Specify that we use ISO 8601 dates and the metric system
false
Specify that we use ISO 8601 dates and the metric system
meta
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 774cb7681dec..2a33de83ca65 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ In SerenityOS, we treat human language as seriously as we do programming languag The following applies to all user-facing strings, code, comments, and commit messages: -* The official project language is American English. +* The official project language is American English with ISO 8601 dates and metric units. * Use proper spelling, grammar, and punctuation. * Write in an authoritative and technical tone.
bdd3a16b16c99bd6342ad34b629b89a510942699
2023-08-19 18:42:00
Aliaksandr Kalenik
libweb: Make `Fetch::Infrastructure::Body` be GC allocated
false
Make `Fetch::Infrastructure::Body` be GC allocated
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Userland/Libraries/LibWeb/DOM/DocumentLoading.cpp index bc90501ec3ac..e54e8d226e71 100644 --- a/Userland/Libraries/LibWeb/DOM/DocumentLoading.cpp +++ b/Userland/Libraries/LibWeb/DOM/DocumentLoading.cpp @@ -233,7 +233,7 @@ JS::GCPtr<DOM::Document> load_document(Optional<HTML::NavigationParams> navigati auto& realm = document->realm(); - if (navigation_params->response->body().has_value()) { + if (navigation_params->response->body()) { auto process_body = [navigation_params, document](ByteBuffer bytes) { if (!parse_document(*document, bytes)) { // FIXME: Load html page with an error if parsing failed. diff --git a/Userland/Libraries/LibWeb/Fetch/Body.cpp b/Userland/Libraries/LibWeb/Fetch/Body.cpp index 601f32935541..5dece554d8b1 100644 --- a/Userland/Libraries/LibWeb/Fetch/Body.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Body.cpp @@ -31,7 +31,7 @@ bool BodyMixin::is_unusable() const { // An object including the Body interface mixin is said to be unusable if its body is non-null and its body’s stream is disturbed or locked. auto const& body = body_impl(); - return body.has_value() && (body->stream()->is_disturbed() || body->stream()->is_locked()); + return body && (body->stream()->is_disturbed() || body->stream()->is_locked()); } // https://fetch.spec.whatwg.org/#dom-body-body @@ -39,7 +39,7 @@ JS::GCPtr<Streams::ReadableStream> BodyMixin::body() const { // The body getter steps are to return null if this’s body is null; otherwise this’s body’s stream. auto const& body = body_impl(); - return body.has_value() ? body->stream().ptr() : nullptr; + return body ? body->stream().ptr() : nullptr; } // https://fetch.spec.whatwg.org/#dom-body-bodyused @@ -47,7 +47,7 @@ bool BodyMixin::body_used() const { // The bodyUsed getter steps are to return true if this’s body is non-null and this’s body’s stream is disturbed; otherwise false. auto const& body = body_impl(); - return body.has_value() && body->stream()->is_disturbed(); + return body && body->stream()->is_disturbed(); } // https://fetch.spec.whatwg.org/#dom-body-arraybuffer @@ -197,7 +197,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> consume_body(JS::Realm& realm // 5. If object’s body is null, then run successSteps with an empty byte sequence. auto const& body = object.body_impl(); - if (!body.has_value()) { + if (!body) { success_steps(ByteBuffer {}); } // 6. Otherwise, fully read object’s body given successSteps, errorSteps, and object’s relevant global object. diff --git a/Userland/Libraries/LibWeb/Fetch/Body.h b/Userland/Libraries/LibWeb/Fetch/Body.h index 0004fcd09d82..4ad3445cc3f0 100644 --- a/Userland/Libraries/LibWeb/Fetch/Body.h +++ b/Userland/Libraries/LibWeb/Fetch/Body.h @@ -27,8 +27,8 @@ class BodyMixin { virtual ~BodyMixin(); virtual ErrorOr<Optional<MimeSniff::MimeType>> mime_type_impl() const = 0; - virtual Optional<Infrastructure::Body&> body_impl() = 0; - virtual Optional<Infrastructure::Body const&> body_impl() const = 0; + virtual JS::GCPtr<Infrastructure::Body> body_impl() = 0; + virtual JS::GCPtr<Infrastructure::Body const> body_impl() const = 0; virtual Bindings::PlatformObject& as_platform_object() = 0; virtual Bindings::PlatformObject const& as_platform_object() const = 0; diff --git a/Userland/Libraries/LibWeb/Fetch/BodyInit.cpp b/Userland/Libraries/LibWeb/Fetch/BodyInit.cpp index d136d1a50d64..815b0bd6520e 100644 --- a/Userland/Libraries/LibWeb/Fetch/BodyInit.cpp +++ b/Userland/Libraries/LibWeb/Fetch/BodyInit.cpp @@ -136,7 +136,7 @@ WebIDL::ExceptionOr<Infrastructure::BodyWithType> extract_body(JS::Realm& realm, // FIXME: 12. If action is non-null, then run these steps in parallel: // 13. Let body be a body whose stream is stream, source is source, and length is length. - auto body = Infrastructure::Body { JS::make_handle(*stream), move(source), move(length) }; + auto body = Infrastructure::Body::create(vm, *stream, move(source), move(length)); // 14. Return (body, type). return Infrastructure::BodyWithType { .body = move(body), .type = move(type) }; diff --git a/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp b/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp index e9657cf1c0df..fdabd3149bea 100644 --- a/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp +++ b/Userland/Libraries/LibWeb/Fetch/FetchMethod.cpp @@ -165,7 +165,7 @@ void abort_fetch(JS::Realm& realm, WebIDL::Promise const& promise, JS::NonnullGC WebIDL::reject_promise(realm, promise, error); // 2. If request’s body is non-null and is readable, then cancel request’s body with error. - if (auto* body = request->body().get_pointer<Infrastructure::Body>(); body != nullptr && body->stream()->is_readable()) { + if (auto* body = request->body().get_pointer<JS::NonnullGCPtr<Infrastructure::Body>>(); body != nullptr && (*body)->stream()->is_readable()) { // TODO: Implement cancelling streams (void)error; } @@ -178,7 +178,7 @@ void abort_fetch(JS::Realm& realm, WebIDL::Promise const& promise, JS::NonnullGC auto response = response_object->response(); // 5. If response’s body is non-null and is readable, then error response’s body with error. - if (response->body().has_value()) { + if (response->body()) { auto stream = response->body()->stream(); if (stream->is_readable()) { // TODO: Implement erroring streams diff --git a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp index 33386e3ae19f..4fc352126f96 100644 --- a/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp @@ -498,7 +498,7 @@ WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> main_fetch(JS:: }; // 2. If response’s body is null, then run processBodyError and abort these steps. - if (!response->body().has_value()) { + if (!response->body()) { process_body_error({}); return; } @@ -644,7 +644,7 @@ WebIDL::ExceptionOr<void> fetch_response_handover(JS::Realm& realm, Infrastructu auto internal_response = response.is_network_error() ? JS::NonnullGCPtr { response } : response.unsafe_response(); // 6. If internalResponse’s body is null, then run processResponseEndOfBody. - if (!internal_response->body().has_value()) { + if (!internal_response->body()) { process_response_end_of_body(); } // 7. Otherwise: @@ -672,7 +672,7 @@ WebIDL::ExceptionOr<void> fetch_response_handover(JS::Realm& realm, Infrastructu // 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with // fetchParams’s task destination. - if (!internal_response->body().has_value()) { + if (!internal_response->body()) { Infrastructure::queue_fetch_task(task_destination, [process_body = move(process_body)]() { process_body({}); }); @@ -1118,7 +1118,7 @@ WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> http_redirect_f // return a network error. if (actual_response->status() != 303 && !request->body().has<Empty>() - && request->body().get<Infrastructure::Body>().source().has<Empty>()) { + && request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) { return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has body but no body source"sv)); } @@ -1160,7 +1160,7 @@ WebIDL::ExceptionOr<Optional<JS::NonnullGCPtr<PendingResponse>>> http_redirect_f // request’s body’s source. // NOTE: request’s body’s source’s nullity has already been checked. if (!request->body().has<Empty>()) { - auto const& source = request->body().get<Infrastructure::Body>().source(); + auto const& source = request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source(); // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType auto converted_source = source.has<ByteBuffer>() ? BodyInitOrReadableBytes { source.get<ByteBuffer>() } @@ -1292,8 +1292,8 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet include_credentials = IncludeCredentials::No; // 5. Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null; otherwise null. - auto content_length = http_request->body().has<Infrastructure::Body>() - ? http_request->body().get<Infrastructure::Body>().length() + auto content_length = http_request->body().has<JS::NonnullGCPtr<Infrastructure::Body>>() + ? http_request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->length() : Optional<u64> {}; // 6. Let contentLengthHeaderValue be null. @@ -1580,13 +1580,13 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet // 2. If request’s body is non-null, then: if (!request->body().has<Empty>()) { // 1. If request’s body’s source is null, then return a network error. - if (request->body().get<Infrastructure::Body>().source().has<Empty>()) { + if (request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) { returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Request has body but no body source"_string)); return; } // 2. Set request’s body to the body of the result of safely extracting request’s body’s source. - auto const& source = request->body().get<Infrastructure::Body>().source(); + auto const& source = request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source(); // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType auto converted_source = source.has<ByteBuffer>() ? BodyInitOrReadableBytes { source.get<ByteBuffer>() } @@ -1657,7 +1657,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fet // - isNewConnectionFetch is false && is_new_connection_fetch == IsNewConnectionFetch::No // - request’s body is null, or request’s body is non-null and request’s body’s source is non-null - && (request->body().has<Empty>() || !request->body().get<Infrastructure::Body>().source().has<Empty>()) + && (request->body().has<Empty>() || !request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) // then: ) { // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. @@ -1738,8 +1738,8 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> nonstandard_resource_load load_request.set_method(DeprecatedString::copy(request->method())); for (auto const& header : *request->header_list()) load_request.set_header(DeprecatedString::copy(header.name), DeprecatedString::copy(header.value)); - if (auto const* body = request->body().get_pointer<Infrastructure::Body>()) { - TRY(body->source().visit( + if (auto const* body = request->body().get_pointer<JS::NonnullGCPtr<Infrastructure::Body>>()) { + TRY((*body)->source().visit( [&](ByteBuffer const& byte_buffer) -> WebIDL::ExceptionOr<void> { load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(byte_buffer))); return {}; diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp index bb6aedee6511..ec462231aa69 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp @@ -13,20 +13,36 @@ namespace Web::Fetch::Infrastructure { -Body::Body(JS::Handle<Streams::ReadableStream> stream) +JS::NonnullGCPtr<Body> Body::create(JS::VM& vm, JS::NonnullGCPtr<Streams::ReadableStream> stream) +{ + return vm.heap().allocate_without_realm<Body>(stream); +} + +JS::NonnullGCPtr<Body> Body::create(JS::VM& vm, JS::NonnullGCPtr<Streams::ReadableStream> stream, SourceType source, Optional<u64> length) +{ + return vm.heap().allocate_without_realm<Body>(stream, source, length); +} + +Body::Body(JS::NonnullGCPtr<Streams::ReadableStream> stream) : m_stream(move(stream)) { } -Body::Body(JS::Handle<Streams::ReadableStream> stream, SourceType source, Optional<u64> length) +Body::Body(JS::NonnullGCPtr<Streams::ReadableStream> stream, SourceType source, Optional<u64> length) : m_stream(move(stream)) , m_source(move(source)) , m_length(move(length)) { } +void Body::visit_edges(Cell::Visitor& visitor) +{ + Base::visit_edges(visitor); + visitor.visit(m_stream); +} + // https://fetch.spec.whatwg.org/#concept-body-clone -Body Body::clone(JS::Realm& realm) const +JS::NonnullGCPtr<Body> Body::clone(JS::Realm& realm) const { // To clone a body body, run these steps: // FIXME: 1. Let « out1, out2 » be the result of teeing body’s stream. @@ -34,7 +50,7 @@ Body Body::clone(JS::Realm& realm) const auto out2 = realm.heap().allocate<Streams::ReadableStream>(realm, realm); // 3. Return a body whose stream is out2 and other members are copied from body. - return Body { JS::make_handle(out2), m_source, m_length }; + return Body::create(realm.vm(), out2, m_source, m_length); } // https://fetch.spec.whatwg.org/#body-fully-read @@ -80,7 +96,7 @@ WebIDL::ExceptionOr<void> Body::fully_read(JS::Realm& realm, Web::Fetch::Infrast } // https://fetch.spec.whatwg.org/#byte-sequence-as-a-body -WebIDL::ExceptionOr<Body> byte_sequence_as_body(JS::Realm& realm, ReadonlyBytes bytes) +WebIDL::ExceptionOr<JS::NonnullGCPtr<Body>> byte_sequence_as_body(JS::Realm& realm, ReadonlyBytes bytes) { // To get a byte sequence bytes as a body, return the body of the result of safely extracting bytes. auto [body, _] = TRY(safely_extract_body(realm, bytes)); diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h index ddf93a08dfd3..7923094d8532 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h @@ -21,7 +21,9 @@ namespace Web::Fetch::Infrastructure { // https://fetch.spec.whatwg.org/#concept-body -class Body final { +class Body final : public JS::Cell { + JS_CELL(Body, JS::Cell); + public: using SourceType = Variant<Empty, ByteBuffer, JS::Handle<FileAPI::Blob>>; // processBody must be an algorithm accepting a byte sequence. @@ -29,21 +31,26 @@ class Body final { // processBodyError must be an algorithm optionally accepting an exception. using ProcessBodyErrorCallback = JS::SafeFunction<void(JS::GCPtr<WebIDL::DOMException>)>; - explicit Body(JS::Handle<Streams::ReadableStream>); - Body(JS::Handle<Streams::ReadableStream>, SourceType, Optional<u64>); + [[nodiscard]] static JS::NonnullGCPtr<Body> create(JS::VM&, JS::NonnullGCPtr<Streams::ReadableStream>); + [[nodiscard]] static JS::NonnullGCPtr<Body> create(JS::VM&, JS::NonnullGCPtr<Streams::ReadableStream>, SourceType, Optional<u64>); [[nodiscard]] JS::NonnullGCPtr<Streams::ReadableStream> stream() const { return *m_stream; } [[nodiscard]] SourceType const& source() const { return m_source; } [[nodiscard]] Optional<u64> const& length() const { return m_length; } - [[nodiscard]] Body clone(JS::Realm&) const; + [[nodiscard]] JS::NonnullGCPtr<Body> clone(JS::Realm&) const; WebIDL::ExceptionOr<void> fully_read(JS::Realm&, ProcessBodyCallback process_body, ProcessBodyErrorCallback process_body_error, TaskDestination task_destination) const; + virtual void visit_edges(JS::Cell::Visitor&) override; + private: + explicit Body(JS::NonnullGCPtr<Streams::ReadableStream>); + Body(JS::NonnullGCPtr<Streams::ReadableStream>, SourceType, Optional<u64>); + // https://fetch.spec.whatwg.org/#concept-body-stream // A stream (a ReadableStream object). - JS::Handle<Streams::ReadableStream> m_stream; + JS::NonnullGCPtr<Streams::ReadableStream> m_stream; // https://fetch.spec.whatwg.org/#concept-body-source // A source (null, a byte sequence, a Blob object, or a FormData object), initially null. @@ -57,10 +64,10 @@ class Body final { // https://fetch.spec.whatwg.org/#body-with-type // A body with type is a tuple that consists of a body (a body) and a type (a header value or null). struct BodyWithType { - Body body; + JS::NonnullGCPtr<Body> body; Optional<ByteBuffer> type; }; -WebIDL::ExceptionOr<Body> byte_sequence_as_body(JS::Realm&, ReadonlyBytes); +WebIDL::ExceptionOr<JS::NonnullGCPtr<Body>> byte_sequence_as_body(JS::Realm&, ReadonlyBytes); } diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp index 3a6a3a2d660c..5c5c62076798 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp @@ -23,6 +23,9 @@ void Request::visit_edges(JS::Cell::Visitor& visitor) Base::visit_edges(visitor); visitor.visit(m_header_list); visitor.visit(m_client); + m_body.visit( + [&](JS::GCPtr<Body>& body) { visitor.visit(body); }, + [](auto&) {}); m_reserved_client.visit( [&](JS::GCPtr<HTML::EnvironmentSettingsObject> const& value) { visitor.visit(value); }, [](auto const&) {}); @@ -249,8 +252,8 @@ JS::NonnullGCPtr<Request> Request::clone(JS::Realm& realm) const new_request->set_timing_allow_failed(m_timing_allow_failed); // 2. If request’s body is non-null, set newRequest’s body to the result of cloning request’s body. - if (auto const* body = m_body.get_pointer<Body>()) - new_request->set_body(body->clone(realm)); + if (auto const* body = m_body.get_pointer<JS::NonnullGCPtr<Body>>()) + new_request->set_body((*body)->clone(realm)); // 3. Return newRequest. return new_request; diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h index 30ce01bb81e5..65f36c226593 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h @@ -153,7 +153,7 @@ class Request final : public JS::Cell { // Members are implementation-defined struct Priority { }; - using BodyType = Variant<Empty, ByteBuffer, Body>; + using BodyType = Variant<Empty, ByteBuffer, JS::NonnullGCPtr<Body>>; using OriginType = Variant<Origin, HTML::Origin>; using PolicyContainerType = Variant<PolicyContainer, HTML::PolicyContainer>; using ReferrerType = Variant<Referrer, AK::URL>; diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp index fa08e85c3fc9..92f594e083b0 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp @@ -26,6 +26,7 @@ void Response::visit_edges(JS::Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_header_list); + visitor.visit(m_body); } JS::NonnullGCPtr<Response> Response::create(JS::VM& vm) @@ -50,7 +51,7 @@ JS::NonnullGCPtr<Response> Response::network_error(JS::VM& vm, Variant<String, S auto response = Response::create(vm); response->set_status(0); response->set_type(Type::Error); - VERIFY(!response->body().has_value()); + VERIFY(!response->body()); response->m_network_error_message = move(message); return response; } @@ -163,7 +164,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::clone(JS::Realm& realm // FIXME: service worker timing info // 3. If response’s body is non-null, then set newResponse’s body to the result of cloning response’s body. - if (m_body.has_value()) + if (m_body) new_response->set_body(m_body->clone(realm)); // 4. Return newResponse. @@ -283,6 +284,7 @@ void OpaqueFilteredResponse::visit_edges(JS::Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_header_list); + visitor.visit(m_body); } JS::NonnullGCPtr<OpaqueRedirectFilteredResponse> OpaqueRedirectFilteredResponse::create(JS::VM& vm, JS::NonnullGCPtr<Response> internal_response) @@ -302,6 +304,7 @@ void OpaqueRedirectFilteredResponse::visit_edges(JS::Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_header_list); + visitor.visit(m_body); } } diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h index 58b5f0f638b6..fc7a5b2e2361 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h @@ -75,9 +75,9 @@ class Response : public JS::Cell { [[nodiscard]] virtual JS::NonnullGCPtr<HeaderList> header_list() const { return m_header_list; } void set_header_list(JS::NonnullGCPtr<HeaderList> header_list) { m_header_list = header_list; } - [[nodiscard]] virtual Optional<Body> const& body() const { return m_body; } - [[nodiscard]] virtual Optional<Body>& body() { return m_body; } - void set_body(Optional<Body> body) { m_body = move(body); } + [[nodiscard]] virtual JS::GCPtr<Body> const& body() const { return m_body; } + [[nodiscard]] virtual JS::GCPtr<Body>& body() { return m_body; } + void set_body(JS::GCPtr<Body> body) { m_body = move(body); } [[nodiscard]] virtual Optional<CacheState> const& cache_state() const { return m_cache_state; } void set_cache_state(Optional<CacheState> cache_state) { m_cache_state = move(cache_state); } @@ -147,7 +147,7 @@ class Response : public JS::Cell { // https://fetch.spec.whatwg.org/#concept-response-body // A response has an associated body (null or a body). Unless stated otherwise it is null. - Optional<Body> m_body; + JS::GCPtr<Body> m_body; // https://fetch.spec.whatwg.org/#concept-response-cache-state // A response has an associated cache state (the empty string, "local", or "validated"). Unless stated otherwise, it is the empty string. @@ -199,8 +199,8 @@ class FilteredResponse : public Response { [[nodiscard]] virtual Status status() const override { return m_internal_response->status(); } [[nodiscard]] virtual ReadonlyBytes status_message() const override { return m_internal_response->status_message(); } [[nodiscard]] virtual JS::NonnullGCPtr<HeaderList> header_list() const override { return m_internal_response->header_list(); } - [[nodiscard]] virtual Optional<Body> const& body() const override { return m_internal_response->body(); } - [[nodiscard]] virtual Optional<Body>& body() override { return m_internal_response->body(); } + [[nodiscard]] virtual JS::GCPtr<Body> const& body() const override { return m_internal_response->body(); } + [[nodiscard]] virtual JS::GCPtr<Body>& body() override { return m_internal_response->body(); } [[nodiscard]] virtual Optional<CacheState> const& cache_state() const override { return m_internal_response->cache_state(); } [[nodiscard]] virtual Vector<ByteBuffer> const& cors_exposed_header_name_list() const override { return m_internal_response->cors_exposed_header_name_list(); } [[nodiscard]] virtual bool range_requested() const override { return m_internal_response->range_requested(); } @@ -267,8 +267,8 @@ class OpaqueFilteredResponse final : public FilteredResponse { [[nodiscard]] virtual Status status() const override { return 0; } [[nodiscard]] virtual ReadonlyBytes status_message() const override { return {}; } [[nodiscard]] virtual JS::NonnullGCPtr<HeaderList> header_list() const override { return m_header_list; } - [[nodiscard]] virtual Optional<Body> const& body() const override { return m_body; } - [[nodiscard]] virtual Optional<Body>& body() override { return m_body; } + [[nodiscard]] virtual JS::GCPtr<Body> const& body() const override { return m_body; } + [[nodiscard]] virtual JS::GCPtr<Body>& body() override { return m_body; } private: OpaqueFilteredResponse(JS::NonnullGCPtr<Response>, JS::NonnullGCPtr<HeaderList>); @@ -277,7 +277,7 @@ class OpaqueFilteredResponse final : public FilteredResponse { Vector<AK::URL> m_url_list; JS::NonnullGCPtr<HeaderList> m_header_list; - Optional<Body> m_body; + JS::GCPtr<Body> m_body; }; // https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect @@ -291,8 +291,8 @@ class OpaqueRedirectFilteredResponse final : public FilteredResponse { [[nodiscard]] virtual Status status() const override { return 0; } [[nodiscard]] virtual ReadonlyBytes status_message() const override { return {}; } [[nodiscard]] virtual JS::NonnullGCPtr<HeaderList> header_list() const override { return m_header_list; } - [[nodiscard]] virtual Optional<Body> const& body() const override { return m_body; } - [[nodiscard]] virtual Optional<Body>& body() override { return m_body; } + [[nodiscard]] virtual JS::GCPtr<Body> const& body() const override { return m_body; } + [[nodiscard]] virtual JS::GCPtr<Body>& body() override { return m_body; } private: OpaqueRedirectFilteredResponse(JS::NonnullGCPtr<Response>, JS::NonnullGCPtr<HeaderList>); @@ -300,6 +300,6 @@ class OpaqueRedirectFilteredResponse final : public FilteredResponse { virtual void visit_edges(JS::Cell::Visitor&) override; JS::NonnullGCPtr<HeaderList> m_header_list; - Optional<Body> m_body; + JS::GCPtr<Body> m_body; }; } diff --git a/Userland/Libraries/LibWeb/Fetch/Request.cpp b/Userland/Libraries/LibWeb/Fetch/Request.cpp index e6fec92a4fb4..61a410f345af 100644 --- a/Userland/Libraries/LibWeb/Fetch/Request.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Request.cpp @@ -54,28 +54,28 @@ ErrorOr<Optional<MimeSniff::MimeType>> Request::mime_type_impl() const // https://fetch.spec.whatwg.org/#concept-body-body // https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A7 -Optional<Infrastructure::Body const&> Request::body_impl() const +JS::GCPtr<Infrastructure::Body const> Request::body_impl() const { // Objects including the Body interface mixin have an associated body (null or a body). // A Request object’s body is its request’s body. return m_request->body().visit( - [](Infrastructure::Body const& b) -> Optional<Infrastructure::Body const&> { return b; }, - [](Empty) -> Optional<Infrastructure::Body const&> { return {}; }, + [](JS::NonnullGCPtr<Infrastructure::Body> const& b) -> JS::GCPtr<Infrastructure::Body const> { return b; }, + [](Empty) -> JS::GCPtr<Infrastructure::Body const> { return nullptr; }, // A byte sequence will be safely extracted into a body early on in fetch. - [](ByteBuffer const&) -> Optional<Infrastructure::Body const&> { VERIFY_NOT_REACHED(); }); + [](ByteBuffer const&) -> JS::GCPtr<Infrastructure::Body const> { VERIFY_NOT_REACHED(); }); } // https://fetch.spec.whatwg.org/#concept-body-body // https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A7 -Optional<Infrastructure::Body&> Request::body_impl() +JS::GCPtr<Infrastructure::Body> Request::body_impl() { // Objects including the Body interface mixin have an associated body (null or a body). // A Request object’s body is its request’s body. return m_request->body().visit( - [](Infrastructure::Body& b) -> Optional<Infrastructure::Body&> { return b; }, - [](Empty) -> Optional<Infrastructure::Body&> { return {}; }, + [](JS::NonnullGCPtr<Infrastructure::Body>& b) -> JS::GCPtr<Infrastructure::Body> { return b; }, + [](Empty) -> JS::GCPtr<Infrastructure::Body> { return {}; }, // A byte sequence will be safely extracted into a body early on in fetch. - [](ByteBuffer&) -> Optional<Infrastructure::Body&> { VERIFY_NOT_REACHED(); }); + [](ByteBuffer&) -> JS::GCPtr<Infrastructure::Body> { VERIFY_NOT_REACHED(); }); } // https://fetch.spec.whatwg.org/#request-create @@ -440,7 +440,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Request>> Request::construct_impl(JS::Realm return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Method must not be GET or HEAD when body is provided"sv }; // 35. Let initBody be null. - Optional<Infrastructure::Body> init_body; + JS::GCPtr<Infrastructure::Body> init_body; // 36. If init["body"] exists and is non-null, then: if (init.body.has_value() && (*init.body).has_value()) { @@ -448,7 +448,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Request>> Request::construct_impl(JS::Realm auto body_with_type = TRY(extract_body(realm, (*init.body).value(), request->keepalive())); // 2. Set initBody to bodyWithType’s body. - init_body = move(body_with_type.body); + init_body = body_with_type.body; // 3. Let type be bodyWithType’s type. auto const& type = body_with_type.type; @@ -459,15 +459,15 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Request>> Request::construct_impl(JS::Realm } // 37. Let inputOrInitBody be initBody if it is non-null; otherwise inputBody. - Optional<Infrastructure::Request::BodyType> input_or_init_body = init_body.has_value() - ? Infrastructure::Request::BodyType { init_body.value() } + Optional<Infrastructure::Request::BodyType> input_or_init_body = init_body + ? Infrastructure::Request::BodyType { *init_body } : input_body; // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is null, then: // FIXME: The spec doesn't check if inputOrInitBody is a body before accessing source. - if (input_or_init_body.has_value() && input_or_init_body->has<Infrastructure::Body>() && input_or_init_body->get<Infrastructure::Body>().source().has<Empty>()) { + if (input_or_init_body.has_value() && input_or_init_body->has<JS::NonnullGCPtr<Infrastructure::Body>>() && input_or_init_body->get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) { // 1. If initBody is non-null and init["duplex"] does not exist, then throw a TypeError. - if (init_body.has_value() && !init.duplex.has_value()) + if (init_body && !init.duplex.has_value()) return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Body without source requires 'duplex' value to be set"sv }; // 2. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError. @@ -482,7 +482,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Request>> Request::construct_impl(JS::Realm auto const& final_body = input_or_init_body; // 40. If initBody is null and inputBody is non-null, then: - if (!init_body.has_value() && input_body.has_value()) { + if (!init_body && input_body.has_value()) { // 2. If input is unusable, then throw a TypeError. if (input.has<JS::Handle<Request>>() && input.get<JS::Handle<Request>>()->is_unusable()) return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Request is unusable"sv }; diff --git a/Userland/Libraries/LibWeb/Fetch/Request.h b/Userland/Libraries/LibWeb/Fetch/Request.h index 7b74776bbb3d..eccfe24e20af 100644 --- a/Userland/Libraries/LibWeb/Fetch/Request.h +++ b/Userland/Libraries/LibWeb/Fetch/Request.h @@ -73,8 +73,8 @@ class Request final // ^BodyMixin virtual ErrorOr<Optional<MimeSniff::MimeType>> mime_type_impl() const override; - virtual Optional<Infrastructure::Body&> body_impl() override; - virtual Optional<Infrastructure::Body const&> body_impl() const override; + virtual JS::GCPtr<Infrastructure::Body> body_impl() override; + virtual JS::GCPtr<Infrastructure::Body const> body_impl() const override; virtual Bindings::PlatformObject& as_platform_object() override { return *this; } virtual Bindings::PlatformObject const& as_platform_object() const override { return *this; } diff --git a/Userland/Libraries/LibWeb/Fetch/Response.cpp b/Userland/Libraries/LibWeb/Fetch/Response.cpp index e9b528cac942..db0f0a031d00 100644 --- a/Userland/Libraries/LibWeb/Fetch/Response.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Response.cpp @@ -50,24 +50,20 @@ ErrorOr<Optional<MimeSniff::MimeType>> Response::mime_type_impl() const // https://fetch.spec.whatwg.org/#concept-body-body // https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A8 -Optional<Infrastructure::Body const&> Response::body_impl() const +JS::GCPtr<Infrastructure::Body const> Response::body_impl() const { // Objects including the Body interface mixin have an associated body (null or a body). // A Response object’s body is its response’s body. - return m_response->body().has_value() - ? m_response->body().value() - : Optional<Infrastructure::Body const&> {}; + return m_response->body() ? m_response->body() : nullptr; } // https://fetch.spec.whatwg.org/#concept-body-body // https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A8 -Optional<Infrastructure::Body&> Response::body_impl() +JS::GCPtr<Infrastructure::Body> Response::body_impl() { // Objects including the Body interface mixin have an associated body (null or a body). // A Response object’s body is its response’s body. - return m_response->body().has_value() - ? m_response->body().value() - : Optional<Infrastructure::Body&> {}; + return m_response->body() ? m_response->body() : nullptr; } // https://fetch.spec.whatwg.org/#response-create diff --git a/Userland/Libraries/LibWeb/Fetch/Response.h b/Userland/Libraries/LibWeb/Fetch/Response.h index dc346630056f..d06d4fb70e4c 100644 --- a/Userland/Libraries/LibWeb/Fetch/Response.h +++ b/Userland/Libraries/LibWeb/Fetch/Response.h @@ -40,8 +40,8 @@ class Response final // ^BodyMixin virtual ErrorOr<Optional<MimeSniff::MimeType>> mime_type_impl() const override; - virtual Optional<Infrastructure::Body&> body_impl() override; - virtual Optional<Infrastructure::Body const&> body_impl() const override; + virtual JS::GCPtr<Infrastructure::Body> body_impl() override; + virtual JS::GCPtr<Infrastructure::Body const> body_impl() const override; virtual Bindings::PlatformObject& as_platform_object() override { return *this; } virtual Bindings::PlatformObject const& as_platform_object() const override { return *this; } diff --git a/Userland/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLMediaElement.cpp index 544ce46fce91..643630e08601 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLMediaElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLMediaElement.cpp @@ -1003,7 +1003,7 @@ WebIDL::ExceptionOr<void> HTMLMediaElement::fetch_resource(AK::URL const& url_re // 5. Otherwise, incrementally read response's body given updateMedia, processEndOfMedia, an empty algorithm, and global. - VERIFY(response->body().has_value()); + VERIFY(response->body()); auto empty_algorithm = [](auto) {}; // FIXME: We are "fully" reading the response here, rather than "incrementally". Memory concerns aside, this should be okay for now as we are diff --git a/Userland/Libraries/LibWeb/HTML/HTMLVideoElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLVideoElement.cpp index 5279d7b0a945..6d30e1ac2b19 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLVideoElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLVideoElement.cpp @@ -189,7 +189,7 @@ WebIDL::ExceptionOr<void> HTMLVideoElement::determine_element_poster_frame(Optio m_poster_frame = move(image.release_value().frames[0].bitmap); }; - VERIFY(response->body().has_value()); + VERIFY(response->body()); auto empty_algorithm = [](auto) {}; response->body()->fully_read(realm, move(on_image_data_read), move(empty_algorithm), JS::NonnullGCPtr { global }).release_value_but_fixme_should_propagate_errors(); diff --git a/Userland/Libraries/LibWeb/HTML/SharedImageRequest.cpp b/Userland/Libraries/LibWeb/HTML/SharedImageRequest.cpp index d24c3055153a..46b4e1d3d72d 100644 --- a/Userland/Libraries/LibWeb/HTML/SharedImageRequest.cpp +++ b/Userland/Libraries/LibWeb/HTML/SharedImageRequest.cpp @@ -82,8 +82,8 @@ void SharedImageRequest::fetch_image(JS::Realm& realm, JS::NonnullGCPtr<Fetch::I handle_failed_fetch(); }; - if (response->body().has_value()) - response->body().value().fully_read(realm, move(process_body), move(process_body_error), JS::NonnullGCPtr { realm.global_object() }).release_value_but_fixme_should_propagate_errors(); + if (response->body()) + response->body()->fully_read(realm, move(process_body), move(process_body_error), JS::NonnullGCPtr { realm.global_object() }).release_value_but_fixme_should_propagate_errors(); }; m_state = State::Fetching; diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp index 2f1635419002..bf6f3fba34ce 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.cpp @@ -82,6 +82,7 @@ void XMLHttpRequest::visit_edges(Cell::Visitor& visitor) Base::visit_edges(visitor); visitor.visit(m_upload_object); visitor.visit(m_author_request_headers); + visitor.visit(m_request_body); visitor.visit(m_response); visitor.visit(m_fetch_controller); @@ -194,7 +195,7 @@ WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response() // Note: Automatically done by the layers above us. // 2. If this’s response’s body is null, then return null. - if (!m_response->body().has_value()) + if (!m_response->body()) return JS::js_null(); // 3. Let jsonObject be the result of running parse JSON from bytes on this’s received bytes. If that threw an exception, then return null. @@ -214,7 +215,7 @@ WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response() String XMLHttpRequest::get_text_response() const { // 1. If xhr’s response’s body is null, then return the empty string. - if (!m_response->body().has_value()) + if (!m_response->body()) return String {}; // 2. Let charset be the result of get a final encoding for xhr. @@ -559,8 +560,8 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest // body // This’s request body. - if (m_request_body.has_value()) - request->set_body(m_request_body.value()); + if (m_request_body) + request->set_body(JS::NonnullGCPtr { *m_request_body }); // client // This’s relevant settings object. @@ -594,7 +595,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest // 9. If req’s body is null, then set this’s upload complete flag. // NOTE: req's body is always m_request_body here, see step 6. - if (!m_request_body.has_value()) + if (!m_request_body) m_upload_complete = true; // 10. Set this’s send() flag. @@ -615,11 +616,11 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest // NOTE: req's body is always m_request_body here, see step 6. // 4. Assert: requestBodyLength is an integer. // NOTE: This is done to provide a better assertion failure message, whereas below the message would be "m_has_value" - if (m_request_body.has_value()) + if (m_request_body) VERIFY(m_request_body->length().has_value()); // NOTE: This is const to allow the callback functions to take a copy of it and know it won't change. - auto const request_body_length = m_request_body.has_value() ? m_request_body->length().value() : 0; + auto const request_body_length = m_request_body ? m_request_body->length().value() : 0; // 5. If this’s upload complete flag is unset and this’s upload listener flag is set, then fire a progress event named loadstart at this’s upload object with requestBodyTransmitted and requestBodyLength. if (!m_upload_complete && m_upload_listener) @@ -691,7 +692,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(Optional<DocumentOrXMLHttpRequest return; // 7. If this’s response’s body is null, then run handle response end-of-body for this and return. - if (!m_response->body().has_value()) { + if (!m_response->body()) { // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context. // FIXME: However, we can receive allocation failures, but we can't propagate them anywhere currently. handle_response_end_of_body().release_value_but_fixme_should_propagate_errors(); diff --git a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h index 563bf195a204..acb1a72ff04f 100644 --- a/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h +++ b/Userland/Libraries/LibWeb/XHR/XMLHttpRequest.h @@ -136,7 +136,7 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget { // https://xhr.spec.whatwg.org/#request-body // request body // Initially null. - Optional<Fetch::Infrastructure::Body> m_request_body; + JS::GCPtr<Fetch::Infrastructure::Body> m_request_body; // https://xhr.spec.whatwg.org/#synchronous-flag // synchronous flag
8f82f6c57490a58781969a8dcf9f3f2083ba6197
2020-04-13 20:53:22
Stephan Unverwerth
libjs: Add more number test cases for #1680
false
Add more number test cases for #1680
libjs
diff --git a/Libraries/LibJS/Tests/numeric-literals-basic.js b/Libraries/LibJS/Tests/numeric-literals-basic.js index 816d309aed8b..3cf308d2cedf 100644 --- a/Libraries/LibJS/Tests/numeric-literals-basic.js +++ b/Libraries/LibJS/Tests/numeric-literals-basic.js @@ -8,12 +8,19 @@ try { assert(1e3 === 1000); assert(1e+3 === 1000); assert(1e-3 === 0.001); + assert(1. === 1); + assert(1.e1 === 10); assert(.1 === 0.1); assert(.1e1 === 1); assert(0.1e1 === 1); assert(.1e+1 === 1); assert(0.1e+1 === 1); + Number.prototype.foo = 'LOL'; + assert(1..foo === 'LOL'); + assert(1.1.foo === 'LOL'); + assert(.1.foo === 'LOL'); + console.log("PASS"); } catch (e) { console.log("FAIL: " + e);
8a0f1d87c0835bc02e38e9eb87dcaf585831887b
2021-04-07 23:06:24
Idan Horowitz
libgfx: Fix IHDR filter method field validation
false
Fix IHDR filter method field validation
libgfx
diff --git a/Userland/Libraries/LibGfx/PNGLoader.cpp b/Userland/Libraries/LibGfx/PNGLoader.cpp index 21e9ad99cf50..2260ea4d1785 100644 --- a/Userland/Libraries/LibGfx/PNGLoader.cpp +++ b/Userland/Libraries/LibGfx/PNGLoader.cpp @@ -829,7 +829,7 @@ static bool is_valid_compression_method(u8 compression_method) static bool is_valid_filter_method(u8 filter_method) { - return filter_method <= 4; + return filter_method == 0; } static bool process_IHDR(ReadonlyBytes data, PNGLoadingContext& context)
20edbb70f8e7feed1f56eca709cce0313887110c
2023-06-22 10:18:12
Aliaksandr Kalenik
libweb: Implement distributing space to tracks beyond limits in GFC
false
Implement distributing space to tracks beyond limits in GFC
libweb
diff --git a/Tests/LibWeb/Layout/expected/grid/grow-beyond-limits.txt b/Tests/LibWeb/Layout/expected/grid/grow-beyond-limits.txt new file mode 100644 index 000000000000..ae8783628940 --- /dev/null +++ b/Tests/LibWeb/Layout/expected/grid/grow-beyond-limits.txt @@ -0,0 +1,9 @@ +Viewport <#document> at (0,0) content-size 800x600 children: not-inline + BlockContainer <html> at (0,0) content-size 800x33.46875 [BFC] children: not-inline + BlockContainer <body> at (8,8) content-size 784x17.46875 children: not-inline + Box <div.container> at (8,8) content-size 784x17.46875 [GFC] children: not-inline + BlockContainer <div.item> at (8,8) content-size 28.6875x17.46875 [BFC] children: inline + line 0 width: 28.6875, height: 17.46875, bottom: 17.46875, baseline: 13.53125 + frag 0 from TextNode start: 0, length: 3, rect: [8,8 28.6875x17.46875] + "one" + TextNode <#text> diff --git a/Tests/LibWeb/Layout/input/grid/grow-beyond-limits.html b/Tests/LibWeb/Layout/input/grid/grow-beyond-limits.html new file mode 100644 index 000000000000..2ed83b38cb8a --- /dev/null +++ b/Tests/LibWeb/Layout/input/grid/grow-beyond-limits.html @@ -0,0 +1,10 @@ +<!DOCTYPE html><style> + .container { + display: grid; + grid-template-columns: minmax(min-content, 0px); + } + + .item { + background-color: aquamarine; + } +</style><div class="container"><div class="item">one</div></div> \ No newline at end of file diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp index 7caa945912ba..c8c2ba7696d0 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp @@ -783,8 +783,10 @@ void GridFormattingContext::resolve_intrinsic_track_sizes(AvailableSpace const& } template<typename Match> -void GridFormattingContext::distribute_extra_space_across_spanned_tracks_base_size(CSSPixels item_size_contribution, Vector<GridTrack&>& spanned_tracks, Match matcher) +void GridFormattingContext::distribute_extra_space_across_spanned_tracks_base_size(GridDimension dimension, CSSPixels item_size_contribution, SpaceDistributionPhase phase, Vector<GridTrack&>& spanned_tracks, Match matcher) { + auto& available_size = dimension == GridDimension::Column ? m_available_space->width : m_available_space->height; + Vector<GridTrack&> affected_tracks; for (auto& track : spanned_tracks) { if (matcher(track)) @@ -830,7 +832,31 @@ void GridFormattingContext::distribute_extra_space_across_spanned_tracks_base_si } } - // FIXME: 3. Distribute space beyond limits + // 3. Distribute space beyond limits + if (extra_space > 0) { + Vector<GridTrack&> tracks_to_grow_beyond_limits; + + // If space remains after all tracks are frozen, unfreeze and continue to + // distribute space to the item-incurred increase of... + if (phase == SpaceDistributionPhase::AccommodateMinimumContribution || phase == SpaceDistributionPhase::AccommodateMinContentContribution) { + // when accommodating minimum contributions or accommodating min-content contributions: any affected track + // that happens to also have an intrinsic max track sizing function + for (auto& track : affected_tracks) { + if (track.max_track_sizing_function.is_intrinsic(available_size)) + tracks_to_grow_beyond_limits.append(track); + } + + // if there are no such tracks, then all affected tracks. + if (tracks_to_grow_beyond_limits.size() == 0) + tracks_to_grow_beyond_limits = affected_tracks; + } + // FIXME: when accommodating max-content contributions: any affected track that happens to also have a + // max-content max track sizing function; if there are no such tracks, then all affected tracks. + + CSSPixels increase_per_track = extra_space / affected_tracks.size(); + for (auto& track : affected_tracks) + track.item_incurred_increase += increase_per_track; + } // 4. For each affected track, if the track’s item-incurred increase is larger than the track’s planned increase // set the track’s planned increase to that value. @@ -935,7 +961,7 @@ void GridFormattingContext::increase_sizes_to_accommodate_spanning_items_crossin return calculate_limited_min_content_contribution(item, dimension); return calculate_minimum_contribution(item, dimension); }(); - distribute_extra_space_across_spanned_tracks_base_size(item_size_contribution, spanned_tracks, [&](GridTrack const& track) { + distribute_extra_space_across_spanned_tracks_base_size(dimension, item_size_contribution, SpaceDistributionPhase::AccommodateMinimumContribution, spanned_tracks, [&](GridTrack const& track) { return track.min_track_sizing_function.is_intrinsic(available_size); }); for (auto& track : spanned_tracks) { @@ -947,7 +973,7 @@ void GridFormattingContext::increase_sizes_to_accommodate_spanning_items_crossin // sizing function of min-content or max-content by distributing extra space as needed to account for // these items' min-content contributions. auto item_min_content_contribution = calculate_min_content_contribution(item, dimension); - distribute_extra_space_across_spanned_tracks_base_size(item_min_content_contribution, spanned_tracks, [&](GridTrack const& track) { + distribute_extra_space_across_spanned_tracks_base_size(dimension, item_min_content_contribution, SpaceDistributionPhase::AccommodateMinContentContribution, spanned_tracks, [&](GridTrack const& track) { return track.min_track_sizing_function.is_min_content() || track.min_track_sizing_function.is_max_content(); }); for (auto& track : spanned_tracks) { @@ -960,7 +986,7 @@ void GridFormattingContext::increase_sizes_to_accommodate_spanning_items_crossin // distributing extra space as needed to account for these items' limited max-content contributions. if (available_size.is_max_content()) { auto item_limited_max_content_contribution = calculate_limited_max_content_contribution(item, dimension); - distribute_extra_space_across_spanned_tracks_base_size(item_limited_max_content_contribution, spanned_tracks, [&](GridTrack const& track) { + distribute_extra_space_across_spanned_tracks_base_size(dimension, item_limited_max_content_contribution, SpaceDistributionPhase::AccommodateMaxContentContribution, spanned_tracks, [&](GridTrack const& track) { return track.min_track_sizing_function.is_auto(available_size) || track.min_track_sizing_function.is_max_content(); }); for (auto& track : spanned_tracks) { @@ -1030,9 +1056,10 @@ void GridFormattingContext::increase_sizes_to_accommodate_spanning_items_crossin // 1. For intrinsic minimums: First increase the base size of tracks with an intrinsic min track sizing // function by distributing extra space as needed to accommodate these items’ minimum contributions. auto item_minimum_contribution = automatic_minimum_size(item, dimension); - distribute_extra_space_across_spanned_tracks_base_size(item_minimum_contribution, spanned_tracks, [&](GridTrack const& track) { - return track.min_track_sizing_function.is_flexible_length(); - }); + distribute_extra_space_across_spanned_tracks_base_size(dimension, + item_minimum_contribution, SpaceDistributionPhase::AccommodateMinimumContribution, spanned_tracks, [&](GridTrack const& track) { + return track.min_track_sizing_function.is_flexible_length(); + }); for (auto& track : spanned_tracks) { track.base_size += track.planned_increase; @@ -1074,6 +1101,8 @@ void GridFormattingContext::maximize_tracks(AvailableSpace const& available_spac while (free_space_px > 0) { auto free_space_to_distribute_per_track = free_space_px / tracks.size(); for (auto& track : tracks) { + if (track.base_size_frozen) + continue; VERIFY(isfinite(track.growth_limit.to_double())); track.base_size = min(track.growth_limit, track.base_size + free_space_to_distribute_per_track); } diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h index c767a16c40f0..cd60c5203cf1 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h @@ -242,8 +242,14 @@ class GridFormattingContext final : public FormattingContext { void collapse_auto_fit_tracks_if_needed(GridDimension const); + enum class SpaceDistributionPhase { + AccommodateMinimumContribution, + AccommodateMinContentContribution, + AccommodateMaxContentContribution + }; + template<typename Match> - void distribute_extra_space_across_spanned_tracks_base_size(CSSPixels item_size_contribution, Vector<GridTrack&>& spanned_tracks, Match matcher); + void distribute_extra_space_across_spanned_tracks_base_size(GridDimension dimension, CSSPixels item_size_contribution, SpaceDistributionPhase phase, Vector<GridTrack&>& spanned_tracks, Match matcher); template<typename Match> void distribute_extra_space_across_spanned_tracks_growth_limit(CSSPixels item_size_contribution, Vector<GridTrack&>& spanned_tracks, Match matcher);
147d30ae4f8b97543ea412885f308efc8fc5c3f3
2021-03-01 16:07:02
Idan Horowitz
spreadsheet: Implement the cut operation for cells
false
Implement the cut operation for cells
spreadsheet
diff --git a/Userland/Applications/Spreadsheet/Spreadsheet.cpp b/Userland/Applications/Spreadsheet/Spreadsheet.cpp index 9fe62404628d..48bdbc5e9777 100644 --- a/Userland/Applications/Spreadsheet/Spreadsheet.cpp +++ b/Userland/Applications/Spreadsheet/Spreadsheet.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, the SerenityOS developers. + * Copyright (c) 2020-2021, the SerenityOS developers. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -325,7 +325,7 @@ Position Sheet::offset_relative_to(const Position& base, const Position& offset, return { new_column, new_row }; } -void Sheet::copy_cells(Vector<Position> from, Vector<Position> to, Optional<Position> resolve_relative_to) +void Sheet::copy_cells(Vector<Position> from, Vector<Position> to, Optional<Position> resolve_relative_to, CopyOperation copy_operation) { auto copy_to = [&](auto& source_position, Position target_position) { auto& target_cell = ensure(target_position); @@ -337,6 +337,8 @@ void Sheet::copy_cells(Vector<Position> from, Vector<Position> to, Optional<Posi } target_cell.copy_from(*source_cell); + if (copy_operation == CopyOperation::Cut) + source_cell->set_data(""); }; if (from.size() == to.size()) { diff --git a/Userland/Applications/Spreadsheet/Spreadsheet.h b/Userland/Applications/Spreadsheet/Spreadsheet.h index 2b903dea46c7..ba0377dba118 100644 --- a/Userland/Applications/Spreadsheet/Spreadsheet.h +++ b/Userland/Applications/Spreadsheet/Spreadsheet.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, the SerenityOS developers. + * Copyright (c) 2020-2021, the SerenityOS developers. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -140,7 +140,12 @@ class Sheet : public Core::Object { const Workbook& workbook() const { return m_workbook; } - void copy_cells(Vector<Position> from, Vector<Position> to, Optional<Position> resolve_relative_to = {}); + enum class CopyOperation { + Copy, + Cut + }; + + void copy_cells(Vector<Position> from, Vector<Position> to, Optional<Position> resolve_relative_to = {}, CopyOperation copy_operation = CopyOperation::Copy); /// Gives the bottom-right corner of the smallest bounding box containing all the written data. Position written_data_bounds() const; diff --git a/Userland/Applications/Spreadsheet/main.cpp b/Userland/Applications/Spreadsheet/main.cpp index 606aca030906..f30653164553 100644 --- a/Userland/Applications/Spreadsheet/main.cpp +++ b/Userland/Applications/Spreadsheet/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, the SerenityOS developers. + * Copyright (c) 2020-2021, the SerenityOS developers. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -157,13 +157,16 @@ int main(int argc, char* argv[]) }; auto& edit_menu = menubar->add_menu("Edit"); - edit_menu.add_action(GUI::CommonActions::make_copy_action([&](auto&) { + + auto clipboard_action = [&](bool is_cut) { /// text/x-spreadsheet-data: + /// - action: copy/cut /// - currently selected cell /// - selected cell+ auto& cells = spreadsheet_widget.current_worksheet().selected_cells(); VERIFY(!cells.is_empty()); StringBuilder text_builder, url_builder; + url_builder.append(is_cut ? "cut\n" : "copy\n"); bool first = true; auto cursor = spreadsheet_widget.current_selection_cursor(); if (cursor) { @@ -190,10 +193,13 @@ int main(int argc, char* argv[]) } HashMap<String, String> metadata; metadata.set("text/x-spreadsheet-data", url_builder.to_string()); + dbgln(url_builder.to_string()); GUI::Clipboard::the().set_data(text_builder.string_view().bytes(), "text/plain", move(metadata)); - }, - window)); + }; + + edit_menu.add_action(GUI::CommonActions::make_copy_action([&] { clipboard_action(false); }, window)); + edit_menu.add_action(GUI::CommonActions::make_cut_action([&] { clipboard_action(true); }, window)); edit_menu.add_action(GUI::CommonActions::make_paste_action([&](auto&) { ScopeGuard update_after_paste { [&] { spreadsheet_widget.update(); } }; @@ -203,8 +209,10 @@ int main(int argc, char* argv[]) if (auto spreadsheet_data = data.metadata.get("text/x-spreadsheet-data"); spreadsheet_data.has_value()) { Vector<Spreadsheet::Position> source_positions, target_positions; auto& sheet = spreadsheet_widget.current_worksheet(); + auto lines = spreadsheet_data.value().split_view('\n'); + auto action = lines.take_first(); - for (auto& line : spreadsheet_data.value().split_view('\n')) { + for (auto& line : lines) { dbgln("Paste line '{}'", line); auto position = sheet.position_from_url(line); if (position.has_value()) @@ -218,7 +226,7 @@ int main(int argc, char* argv[]) return; auto first_position = source_positions.take_first(); - sheet.copy_cells(move(source_positions), move(target_positions), first_position); + sheet.copy_cells(move(source_positions), move(target_positions), first_position, action == "cut" ? Spreadsheet::Sheet::CopyOperation::Cut : Spreadsheet::Sheet::CopyOperation::Copy); } else { for (auto& cell : spreadsheet_widget.current_worksheet().selected_cells()) spreadsheet_widget.current_worksheet().ensure(cell).set_data(StringView { data.data.data(), data.data.size() });