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
99f57d0a400060168f2d8b211761b45d0dd3e1f5
2021-07-26 04:09:10
Andreas Kling
base: Add descriptions to the apps in the Settings category :^)
false
Add descriptions to the apps in the Settings category :^)
base
diff --git a/Base/res/apps/DisplaySettings.af b/Base/res/apps/DisplaySettings.af index 27572783edf9..c8f30e39d4e0 100644 --- a/Base/res/apps/DisplaySettings.af +++ b/Base/res/apps/DisplaySettings.af @@ -2,3 +2,4 @@ Name=Display Settings Executable=/bin/DisplaySettings Category=Settings +Description=Configure your display hardware, desktop wallpaper, fonts, etc. diff --git a/Base/res/apps/Keyboard.af b/Base/res/apps/Keyboard.af index 8f77b7aa5e7d..fae79b4951cb 100644 --- a/Base/res/apps/Keyboard.af +++ b/Base/res/apps/Keyboard.af @@ -2,3 +2,4 @@ Name=Keyboard Settings Executable=/bin/KeyboardSettings Category=Settings +Description=Customize your keyboard layout and other settings diff --git a/Base/res/apps/MouseSettings.af b/Base/res/apps/MouseSettings.af index 74729fa33051..d50c5e239d82 100644 --- a/Base/res/apps/MouseSettings.af +++ b/Base/res/apps/MouseSettings.af @@ -2,3 +2,4 @@ Name=Mouse Settings Executable=/bin/MouseSettings Category=Settings +Description=Customize your mouse and cursor settings
0b4f92e4529da9d6aa82de03e588f605c9bee414
2020-06-13 16:19:20
Andreas Kling
libweb: Tweak UA style to reset text-align on table elements
false
Tweak UA style to reset text-align on table elements
libweb
diff --git a/Libraries/LibWeb/CSS/Default.css b/Libraries/LibWeb/CSS/Default.css index 5e01137bbc78..ce2507731323 100644 --- a/Libraries/LibWeb/CSS/Default.css +++ b/Libraries/LibWeb/CSS/Default.css @@ -165,3 +165,8 @@ colgroup { basefont { display: block; } + +/* FIXME: I think this should only apply in quirks mode. */ +table { + text-align: left; +}
8a1e88677f86ce2e64a00c7e30c35f5f4ce8695f
2024-03-24 15:39:09
Kenneth Myhra
libweb: Add FIXME comments to ImageData.idl
false
Add FIXME comments to ImageData.idl
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/ImageData.idl b/Userland/Libraries/LibWeb/HTML/ImageData.idl index 7b1d90e636af..bf3208e9fd3e 100644 --- a/Userland/Libraries/LibWeb/HTML/ImageData.idl +++ b/Userland/Libraries/LibWeb/HTML/ImageData.idl @@ -9,8 +9,9 @@ dictionary ImageDataSettings { [Exposed=(Window,Worker), Serializable] interface ImageData { constructor(unsigned long sw, unsigned long sh, optional ImageDataSettings settings = {}); + // FIXME: constructor(Uint8ClampedArray data, unsigned long sw, optional unsigned long sh, optional ImageDataSettings settings = {}); readonly attribute unsigned long width; readonly attribute unsigned long height; readonly attribute Uint8ClampedArray data; - + // FIXME: readonly attribute PredefinedColorSpace colorSpace; };
48cc1c97d596809e175b2fca92f612254d0e977f
2022-01-05 15:51:38
Luke Wilde
libjs: Implement Array.prototype.groupBy
false
Implement Array.prototype.groupBy
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 15672a58730e..f0c953434e93 100644 --- a/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -72,6 +72,7 @@ void ArrayPrototype::initialize(GlobalObject& global_object) define_native_function(vm.names.keys, keys, 0, attr); define_native_function(vm.names.entries, entries, 0, attr); define_native_function(vm.names.copyWithin, copy_within, 2, attr); + define_native_function(vm.names.groupBy, group_by, 1, attr); // Use define_direct_property here instead of define_native_function so that // Object.is(Array.prototype[Symbol.iterator], Array.prototype.values) @@ -80,7 +81,8 @@ void ArrayPrototype::initialize(GlobalObject& global_object) define_direct_property(*vm.well_known_symbol_iterator(), get_without_side_effects(vm.names.values), attr); // 23.1.3.35 Array.prototype [ @@unscopables ], https://tc39.es/ecma262/#sec-array.prototype-@@unscopables - // With proposal, https://tc39.es/proposal-array-find-from-last/#sec-array.prototype-@@unscopables + // With find from last proposal, https://tc39.es/proposal-array-find-from-last/#sec-array.prototype-@@unscopables + // With array grouping proposal, https://tc39.es/proposal-array-grouping/#sec-array.prototype-@@unscopables auto* unscopable_list = Object::create(global_object, nullptr); MUST(unscopable_list->create_data_property_or_throw(vm.names.at, Value(true))); MUST(unscopable_list->create_data_property_or_throw(vm.names.copyWithin, Value(true))); @@ -92,6 +94,7 @@ void ArrayPrototype::initialize(GlobalObject& global_object) MUST(unscopable_list->create_data_property_or_throw(vm.names.findLastIndex, Value(true))); MUST(unscopable_list->create_data_property_or_throw(vm.names.flat, Value(true))); MUST(unscopable_list->create_data_property_or_throw(vm.names.flatMap, Value(true))); + MUST(unscopable_list->create_data_property_or_throw(vm.names.groupBy, Value(true))); MUST(unscopable_list->create_data_property_or_throw(vm.names.includes, Value(true))); MUST(unscopable_list->create_data_property_or_throw(vm.names.keys, Value(true))); MUST(unscopable_list->create_data_property_or_throw(vm.names.values, Value(true))); @@ -1665,4 +1668,86 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::at) return TRY(this_object->get(index.value())); } +// 2.3 AddValueToKeyedGroup ( groups, key, value ), https://tc39.es/proposal-array-grouping/#sec-add-value-to-keyed-group +template<typename GroupsType, typename KeyType> +static void add_value_to_keyed_group(GlobalObject& global_object, GroupsType& groups, KeyType key, Value value) +{ + // 1. For each Record { [[Key]], [[Elements]] } g of groups, do + // a. If ! SameValue(g.[[Key]], key) is true, then + // NOTE: This is performed in KeyedGroupTraits::equals for groupByToMap and Traits<JS::PropertyKey>::equals for groupBy. + auto existing_elements_iterator = groups.find(key); + if (existing_elements_iterator != groups.end()) { + // i. Assert: exactly one element of groups meets this criteria. + // NOTE: This is done on insertion into the hash map, as only `set` tells us if we overrode an entry. + + // ii. Append value as the last element of g.[[Elements]]. + existing_elements_iterator->value.append(value); + + // iii. Return. + return; + } + + // 2. Let group be the Record { [[Key]]: key, [[Elements]]: « value » }. + MarkedValueList new_elements { global_object.heap() }; + new_elements.append(value); + + // 3. Append group as the last element of groups. + auto result = groups.set(key, move(new_elements)); + VERIFY(result == AK::HashSetResult::InsertedNewEntry); +} + +// 2.1 Array.prototype.groupBy ( callbackfn [ , thisArg ] ), https://tc39.es/proposal-array-grouping/#sec-array.prototype.groupby +JS_DEFINE_NATIVE_FUNCTION(ArrayPrototype::group_by) +{ + auto callback_function = vm.argument(0); + auto this_arg = vm.argument(1); + + // 1. Let O be ? ToObject(this value). + auto* this_object = TRY(vm.this_value(global_object).to_object(global_object)); + + // 2. Let len be ? LengthOfArrayLike(O). + auto length = TRY(length_of_array_like(global_object, *this_object)); + + // 3. If IsCallable(callbackfn) is false, throw a TypeError exception. + if (!callback_function.is_function()) + return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, callback_function.to_string_without_side_effects()); + + // 5. Let groups be a new empty List. + OrderedHashMap<PropertyKey, MarkedValueList> groups; + + // 4. Let k be 0. + // 6. Repeat, while k < len + for (size_t index = 0; index < length; ++index) { + // a. Let Pk be ! ToString(𝔽(k)). + auto index_property = PropertyKey { index }; + + // b. Let kValue be ? Get(O, Pk). + auto k_value = TRY(this_object->get(index_property)); + + // c. Let propertyKey be ? ToPropertyKey(? Call(callbackfn, thisArg, « kValue, 𝔽(k), O »)). + auto property_key_value = TRY(vm.call(callback_function.as_function(), this_arg, k_value, Value(index), this_object)); + auto property_key = TRY(property_key_value.to_property_key(global_object)); + + // d. Perform ! AddValueToKeyedGroup(groups, propertyKey, kValue). + add_value_to_keyed_group(global_object, groups, property_key, k_value); + + // e. Set k to k + 1. + } + + // 7. Let obj be ! OrdinaryObjectCreate(null). + auto* object = Object::create(global_object, nullptr); + + // 8. For each Record { [[Key]], [[Elements]] } g of groups, do + for (auto& group : groups) { + // a. Let elements be ! CreateArrayFromList(g.[[Elements]]). + auto* elements = Array::create_from(global_object, group.value); + + // b. Perform ! CreateDataPropertyOrThrow(obj, g.[[Key]], elements). + MUST(object->create_data_property_or_throw(group.key, elements)); + } + + // 9. Return obj. + return object; +} + } diff --git a/Userland/Libraries/LibJS/Runtime/ArrayPrototype.h b/Userland/Libraries/LibJS/Runtime/ArrayPrototype.h index f58557cd2cdb..3dd2d07fb592 100644 --- a/Userland/Libraries/LibJS/Runtime/ArrayPrototype.h +++ b/Userland/Libraries/LibJS/Runtime/ArrayPrototype.h @@ -54,6 +54,7 @@ class ArrayPrototype final : public Array { JS_DECLARE_NATIVE_FUNCTION(keys); JS_DECLARE_NATIVE_FUNCTION(entries); JS_DECLARE_NATIVE_FUNCTION(copy_within); + JS_DECLARE_NATIVE_FUNCTION(group_by); }; } diff --git a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h index 56aca802e0ca..64d53d6c0d32 100644 --- a/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h +++ b/Userland/Libraries/LibJS/Runtime/CommonPropertyNames.h @@ -241,6 +241,7 @@ namespace JS { P(global) \ P(globalThis) \ P(group) \ + P(groupBy) \ P(groupCollapsed) \ P(groupEnd) \ P(groups) \ diff --git a/Userland/Libraries/LibJS/Tests/builtins/Array/Array.prototype-generic-functions.js b/Userland/Libraries/LibJS/Tests/builtins/Array/Array.prototype-generic-functions.js index 07b0bf610baf..587d5d841c2e 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/Array/Array.prototype-generic-functions.js +++ b/Userland/Libraries/LibJS/Tests/builtins/Array/Array.prototype-generic-functions.js @@ -304,4 +304,17 @@ describe("ability to work with generic non-array objects", () => { 2, ]); }); + + test("groupBy", () => { + const visited = []; + const o = { length: 5, 0: "foo", 1: "bar", 3: "baz" }; + const result = Array.prototype.groupBy.call(o, (value, _, object) => { + expect(object).toBe(o); + visited.push(value); + return value !== undefined ? value.startsWith("b") : false; + }); + expect(visited).toEqual(["foo", "bar", undefined, "baz", undefined]); + expect(result.false).toEqual(["foo", undefined, undefined]); + expect(result.true).toEqual(["bar", "baz"]); + }); }); diff --git a/Userland/Libraries/LibJS/Tests/builtins/Array/Array.prototype.groupBy.js b/Userland/Libraries/LibJS/Tests/builtins/Array/Array.prototype.groupBy.js new file mode 100644 index 000000000000..dd8955a2955f --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/Array/Array.prototype.groupBy.js @@ -0,0 +1,101 @@ +test("length is 1", () => { + expect(Array.prototype.groupBy).toHaveLength(1); +}); + +describe("errors", () => { + test("callback must be a function", () => { + expect(() => { + [].groupBy(undefined); + }).toThrowWithMessage(TypeError, "undefined is not a function"); + }); + + test("null or undefined this value", () => { + expect(() => { + Array.prototype.groupBy.call(); + }).toThrowWithMessage(TypeError, "ToObject on null or undefined"); + + expect(() => { + Array.prototype.groupBy.call(undefined); + }).toThrowWithMessage(TypeError, "ToObject on null or undefined"); + + expect(() => { + Array.prototype.groupBy.call(null); + }).toThrowWithMessage(TypeError, "ToObject on null or undefined"); + }); +}); + +describe("normal behavior", () => { + test("basic functionality", () => { + const array = [1, 2, 3, 4, 5, 6]; + const visited = []; + + const firstResult = array.groupBy(value => { + visited.push(value); + return value % 2 === 0; + }); + + expect(visited).toEqual([1, 2, 3, 4, 5, 6]); + expect(firstResult.true).toEqual([2, 4, 6]); + expect(firstResult.false).toEqual([1, 3, 5]); + + const firstKeys = Object.keys(firstResult); + expect(firstKeys).toHaveLength(2); + expect(firstKeys[0]).toBe("false"); + expect(firstKeys[1]).toBe("true"); + + const secondResult = array.groupBy((_, index) => { + return index < array.length / 2; + }); + + expect(secondResult.true).toEqual([1, 2, 3]); + expect(secondResult.false).toEqual([4, 5, 6]); + + const secondKeys = Object.keys(secondResult); + expect(secondKeys).toHaveLength(2); + expect(secondKeys[0]).toBe("true"); + expect(secondKeys[1]).toBe("false"); + + const thisArg = [7, 8, 9, 10, 11, 12]; + const thirdResult = array.groupBy(function (_, __, arrayVisited) { + expect(arrayVisited).toBe(array); + expect(this).toBe(thisArg); + }, thisArg); + + expect(thirdResult.undefined).not.toBe(array); + expect(thirdResult.undefined).not.toBe(thisArg); + expect(thirdResult.undefined).toEqual(array); + + const thirdKeys = Object.keys(thirdResult); + expect(thirdKeys).toHaveLength(1); + expect(thirdKeys[0]).toBe("undefined"); + }); + + test("is unscopable", () => { + expect(Array.prototype[Symbol.unscopables].groupBy).toBeTrue(); + const array = []; + with (array) { + expect(() => { + groupBy; + }).toThrowWithMessage(ReferenceError, "'groupBy' is not defined"); + } + }); + + test("never calls callback with empty array", () => { + var callbackCalled = 0; + expect( + [].groupBy(() => { + callbackCalled++; + }) + ).toEqual({}); + expect(callbackCalled).toBe(0); + }); + + test("calls callback once for every item", () => { + var callbackCalled = 0; + const result = [1, 2, 3].groupBy(() => { + callbackCalled++; + }); + expect(result.undefined).toEqual([1, 2, 3]); + expect(callbackCalled).toBe(3); + }); +});
3dc87be8917d9f4d16cc1f737b652ed2cf58c3fa
2019-11-24 16:56:21
Andreas Kling
kernel: Mark mmap()-created regions with a special bit
false
Mark mmap()-created regions with a special bit
kernel
diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 802aa6c8b4e2..79127fa0979f 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -188,6 +188,8 @@ int Process::sys$set_mmap_name(void* addr, size_t size, const char* name) auto* region = region_from_range({ VirtualAddress((u32)addr), size }); if (!region) return -EINVAL; + if (!region->is_mmap()) + return -EPERM; region->set_name(String(name)); return 0; } @@ -225,6 +227,7 @@ void* Process::sys$mmap(const Syscall::SC_mmap_params* params) region->set_shared(true); if (flags & MAP_STACK) region->set_stack(true); + region->set_mmap(true); return region->vaddr().as_ptr(); } if (offset & ~PAGE_MASK) @@ -240,6 +243,7 @@ void* Process::sys$mmap(const Syscall::SC_mmap_params* params) region->set_shared(true); if (name) region->set_name(name); + region->set_mmap(true); return region->vaddr().as_ptr(); } @@ -247,12 +251,16 @@ int Process::sys$munmap(void* addr, size_t size) { Range range_to_unmap { VirtualAddress((u32)addr), size }; if (auto* whole_region = region_from_range(range_to_unmap)) { + if (!whole_region->is_mmap()) + return -EPERM; bool success = deallocate_region(*whole_region); ASSERT(success); return 0; } if (auto* old_region = region_containing(range_to_unmap)) { + if (!old_region->is_mmap()) + return -EPERM; Range old_region_range = old_region->range(); auto remaining_ranges_after_unmap = old_region_range.carve(range_to_unmap); ASSERT(!remaining_ranges_after_unmap.is_empty()); @@ -291,6 +299,8 @@ int Process::sys$mprotect(void* addr, size_t size, int prot) auto* region = region_from_range({ VirtualAddress((u32)addr), size }); if (!region) return -EINVAL; + if (!region->is_mmap()) + return -EPERM; region->set_writable(prot & PROT_WRITE); region->remap(); return 0; diff --git a/Kernel/VM/Region.h b/Kernel/VM/Region.h index 5501e6b2e342..4ea3c2f7fc62 100644 --- a/Kernel/VM/Region.h +++ b/Kernel/VM/Region.h @@ -53,6 +53,9 @@ class Region final : public InlineLinkedListNode<Region> { bool is_stack() const { return m_stack; } void set_stack(bool stack) { m_stack = stack; } + bool is_mmap() const { return m_mmap; } + void set_mmap(bool mmap) { m_mmap = mmap; } + bool is_user_accessible() const { return m_user_accessible; } PageFaultResponse handle_fault(const PageFault&); @@ -145,5 +148,6 @@ class Region final : public InlineLinkedListNode<Region> { bool m_shared { false }; bool m_user_accessible { false }; bool m_stack { false }; + bool m_mmap { false }; mutable OwnPtr<Bitmap> m_cow_map; };
7c74d3a6576b892e4f1d9f1aa9305b01ad673cb4
2020-01-24 02:03:15
Andreas Kling
texteditor: Focus the editor after opening a new file
false
Focus the editor after opening a new file
texteditor
diff --git a/Applications/TextEditor/TextEditorWidget.cpp b/Applications/TextEditor/TextEditorWidget.cpp index 663f118189a0..fd53e7c3cc2a 100644 --- a/Applications/TextEditor/TextEditorWidget.cpp +++ b/Applications/TextEditor/TextEditorWidget.cpp @@ -442,6 +442,8 @@ void TextEditorWidget::open_sesame(const String& path) m_document_opening = true; set_path(FileSystemPath(path)); + + m_editor->set_focus(true); } bool TextEditorWidget::request_close()
b15b87486dd52dc07062bd25b82dc719ba3705b3
2022-01-13 17:15:17
David Lindbom
base: Add manual page for Chess game
false
Add manual page for Chess game
base
diff --git a/Base/usr/share/man/man6/Chess.md b/Base/usr/share/man/man6/Chess.md new file mode 100644 index 000000000000..d97a93b1cd40 --- /dev/null +++ b/Base/usr/share/man/man6/Chess.md @@ -0,0 +1,15 @@ +## Name + +Chess + +## Synopsis + +```**sh +$ Chess +``` + +## Description + +Chess is an implementation of the 15th century board game. + +The game can either be played against another human or against the ChessEngine service.
0f6654fef289421bafaacbae1aa5c04bf8292bd8
2021-07-20 12:55:42
Ali Mohammad Pur
libline: Reset the suggestion page offset when finding the max length
false
Reset the suggestion page offset when finding the max length
libline
diff --git a/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp b/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp index 882b63f9ba81..a691bba5df2d 100644 --- a/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp +++ b/Userland/Libraries/LibLine/XtermSuggestionDisplay.cpp @@ -20,6 +20,7 @@ void XtermSuggestionDisplay::display(const SuggestionManager& manager) size_t longest_suggestion_length = 0; size_t longest_suggestion_byte_length = 0; + manager.set_start_index(0); manager.for_each_suggestion([&](auto& suggestion, auto) { longest_suggestion_length = max(longest_suggestion_length, suggestion.text_view.length()); longest_suggestion_byte_length = max(longest_suggestion_byte_length, suggestion.text_string.length());
dd9a77099fa88d7db3eddb0fb73397f742cace94
2020-12-16 00:03:53
Andreas Kling
filemanager: Simplify breadcrumb bar hook callback
false
Simplify breadcrumb bar hook callback
filemanager
diff --git a/Applications/FileManager/main.cpp b/Applications/FileManager/main.cpp index 46cef00e49e5..c8291b9c31f2 100644 --- a/Applications/FileManager/main.cpp +++ b/Applications/FileManager/main.cpp @@ -655,21 +655,8 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio breadcrumb_bar.set_selected_segment(breadcrumb_bar.segment_count() - 1); - breadcrumb_bar.on_segment_click = [&directory_view, lexical_path](size_t segment_index) { - if (segment_index == 0) { - directory_view.open("/"); - return; - } - size_t part_index = segment_index - 1; - ASSERT(part_index < lexical_path.parts().size()); - - StringBuilder builder; - for (size_t i = 0; i <= part_index; ++i) { - builder.append('/'); - builder.append(lexical_path.parts()[i]); - } - - directory_view.open(builder.string_view()); + breadcrumb_bar.on_segment_click = [&](size_t segment_index) { + directory_view.open(breadcrumb_bar.segment_data(segment_index)); }; } }
091628202f17015d3cb3c1813d5deb5139410a13
2021-06-28 02:05:12
Tom
windowserver: Un-tile window if resizing warrants it
false
Un-tile window if resizing warrants it
windowserver
diff --git a/Userland/Services/WindowServer/Window.cpp b/Userland/Services/WindowServer/Window.cpp index 3253f0dba842..569a2e75a8fe 100644 --- a/Userland/Services/WindowServer/Window.cpp +++ b/Userland/Services/WindowServer/Window.cpp @@ -15,6 +15,7 @@ #include "WindowManager.h" #include <AK/Badge.h> #include <AK/CharacterTypes.h> +#include <AK/Debug.h> #include <WindowServer/WindowClientEndpoint.h> namespace WindowServer { @@ -851,53 +852,130 @@ Gfx::IntRect Window::tiled_rect(Screen* target_screen, WindowTileType tiled) con screen.width() / 2 - frame_width, max_height) .translated(screen_location); - case WindowTileType::Right: - return Gfx::IntRect(screen.width() / 2 + frame_width, - menu_height, - screen.width() / 2 - frame_width, - max_height) + case WindowTileType::Right: { + Gfx::IntPoint location { + screen.width() / 2 + frame_width, + menu_height + }; + return Gfx::IntRect( + location, + { screen.width() - location.x(), max_height }) .translated(screen_location); + } case WindowTileType::Top: return Gfx::IntRect(0, menu_height, screen.width(), (max_height - titlebar_height) / 2 - frame_width) .translated(screen_location); - case WindowTileType::Bottom: - return Gfx::IntRect(0, - menu_height + (titlebar_height + max_height) / 2 + frame_width, - screen.width(), - (max_height - titlebar_height) / 2 - frame_width) + case WindowTileType::Bottom: { + Gfx::IntPoint location { + 0, + menu_height + (titlebar_height + max_height) / 2 + frame_width + }; + return Gfx::IntRect( + location, + { screen.width(), screen.height() - location.y() }) .translated(screen_location); + } case WindowTileType::TopLeft: return Gfx::IntRect(0, menu_height, screen.width() / 2 - frame_width, (max_height - titlebar_height) / 2 - frame_width) .translated(screen_location); - case WindowTileType::TopRight: - return Gfx::IntRect(screen.width() / 2 + frame_width, - menu_height, - screen.width() / 2 - frame_width, - (max_height - titlebar_height) / 2 - frame_width) + case WindowTileType::TopRight: { + Gfx::IntPoint location { + screen.width() / 2 + frame_width, + menu_height + }; + return Gfx::IntRect( + location, + { screen.width() - location.x(), (max_height - titlebar_height) / 2 - frame_width }) .translated(screen_location); - case WindowTileType::BottomLeft: - return Gfx::IntRect(0, - menu_height + (titlebar_height + max_height) / 2 + frame_width, - screen.width() / 2 - frame_width, - (max_height - titlebar_height) / 2 - frame_width) + } + case WindowTileType::BottomLeft: { + Gfx::IntPoint location { + 0, + menu_height + (titlebar_height + max_height) / 2 + frame_width + }; + return Gfx::IntRect( + location, + { screen.width() / 2 - frame_width, screen.height() - location.y() }) .translated(screen_location); - case WindowTileType::BottomRight: - return Gfx::IntRect(screen.width() / 2 + frame_width, - menu_height + (titlebar_height + max_height) / 2 + frame_width, - screen.width() / 2 - frame_width, - (max_height - titlebar_height) / 2 - frame_width) + } + case WindowTileType::BottomRight: { + Gfx::IntPoint location { + screen.width() / 2 + frame_width, + menu_height + (titlebar_height + max_height) / 2 + frame_width + }; + return Gfx::IntRect( + location, + { screen.width() - location.x(), screen.height() - location.y() }) .translated(screen_location); + } default: VERIFY_NOT_REACHED(); } } +WindowTileType Window::tile_type_based_on_rect(Gfx::IntRect const& rect) const +{ + auto& window_screen = Screen::closest_to_rect(this->rect()); // based on currently used rect + auto tile_type = WindowTileType::None; + if (window_screen.rect().contains(rect)) { + auto current_tiled = tiled(); + bool tiling_to_top = current_tiled == WindowTileType::Top || current_tiled == WindowTileType::TopLeft || current_tiled == WindowTileType::TopRight; + bool tiling_to_bottom = current_tiled == WindowTileType::Bottom || current_tiled == WindowTileType::BottomLeft || current_tiled == WindowTileType::BottomRight; + bool tiling_to_left = current_tiled == WindowTileType::Left || current_tiled == WindowTileType::TopLeft || current_tiled == WindowTileType::BottomLeft; + bool tiling_to_right = current_tiled == WindowTileType::Right || current_tiled == WindowTileType::TopRight || current_tiled == WindowTileType::BottomRight; + + auto ideal_tiled_rect = tiled_rect(&window_screen, current_tiled); + bool same_top = ideal_tiled_rect.top() == rect.top(); + bool same_left = ideal_tiled_rect.left() == rect.left(); + bool same_right = ideal_tiled_rect.right() == rect.right(); + bool same_bottom = ideal_tiled_rect.bottom() == rect.bottom(); + + // Try to find the most suitable tile type. For example, if a window is currently tiled to the BottomRight and + // the window is resized upwards as to where it perfectly touches the screen's top border, then the more suitable + // tile type would be Right, as three sides are lined up perfectly. + if (tiling_to_top && same_top && same_left && same_right) + return WindowTileType::Top; + else if ((tiling_to_top || tiling_to_left) && same_top && same_left) + return rect.bottom() == tiled_rect(&window_screen, WindowTileType::Bottom).bottom() ? WindowTileType::Left : WindowTileType::TopLeft; + else if ((tiling_to_top || tiling_to_right) && same_top && same_right) + return rect.bottom() == tiled_rect(&window_screen, WindowTileType::Bottom).bottom() ? WindowTileType::Right : WindowTileType::TopRight; + else if (tiling_to_left && same_left && same_top && same_bottom) + return WindowTileType::Left; + else if (tiling_to_right && same_right && same_top && same_bottom) + return WindowTileType::Right; + else if (tiling_to_bottom && same_bottom && same_left && same_right) + return WindowTileType::Bottom; + else if ((tiling_to_bottom || tiling_to_left) && same_bottom && same_left) + return rect.top() == tiled_rect(&window_screen, WindowTileType::Left).top() ? WindowTileType::Left : WindowTileType::BottomLeft; + else if ((tiling_to_bottom || tiling_to_right) && same_bottom && same_right) + return rect.top() == tiled_rect(&window_screen, WindowTileType::Right).top() ? WindowTileType::Right : WindowTileType::BottomRight; + } + return tile_type; +} + +void Window::check_untile_due_to_resize(Gfx::IntRect const& new_rect) +{ + auto new_tile_type = tile_type_based_on_rect(new_rect); + if constexpr (RESIZE_DEBUG) { + if (new_tile_type == WindowTileType::None) { + auto current_rect = rect(); + auto& window_screen = Screen::closest_to_rect(current_rect); + if (!(window_screen.rect().contains(new_rect))) + dbgln("Untiling because new rect {} does not fit into screen #{} rect {}", new_rect, window_screen.index(), window_screen.rect()); + else + dbgln("Untiling because new rect {} does not touch screen #{} rect {}", new_rect, window_screen.index(), window_screen.rect()); + } else if (new_tile_type != m_tiled) + dbgln("Changing tile type from {} to {}", (int)m_tiled, (int)new_tile_type); + } + m_tiled = new_tile_type; +} + bool Window::set_untiled(Optional<Gfx::IntPoint> fixed_point) { if (m_tiled == WindowTileType::None) diff --git a/Userland/Services/WindowServer/Window.h b/Userland/Services/WindowServer/Window.h index 2b94efa820ea..09fc32431d52 100644 --- a/Userland/Services/WindowServer/Window.h +++ b/Userland/Services/WindowServer/Window.h @@ -100,6 +100,8 @@ class Window final : public Core::Object { WindowTileType tiled() const { return m_tiled; } void set_tiled(Screen*, WindowTileType); + WindowTileType tile_type_based_on_rect(Gfx::IntRect const&) const; + void check_untile_due_to_resize(Gfx::IntRect const&); bool set_untiled(Optional<Gfx::IntPoint> fixed_point = {}); bool is_occluded() const { return m_occluded; } diff --git a/Userland/Services/WindowServer/WindowManager.cpp b/Userland/Services/WindowServer/WindowManager.cpp index d8cc0a4fec1f..5be6385478da 100644 --- a/Userland/Services/WindowServer/WindowManager.cpp +++ b/Userland/Services/WindowServer/WindowManager.cpp @@ -715,6 +715,7 @@ bool WindowManager::process_ongoing_window_resize(MouseEvent const& event) // First, size the new rect. new_rect.set_width(new_rect.width() + change_w); new_rect.set_height(new_rect.height() + change_h); + m_resize_window->apply_minimum_size(new_rect); if (!m_resize_window->size_increment().is_null()) { @@ -762,6 +763,14 @@ bool WindowManager::process_ongoing_window_resize(MouseEvent const& event) if (m_resize_window->rect() == new_rect) return true; + if (m_resize_window->tiled() != WindowTileType::None) { + // Check if we should be un-tiling the window. This should happen when one side touching + // the screen border changes. We need to un-tile because while it is tiled, rendering is + // constrained to the screen where it's tiled on, and if one of these sides move we should + // no longer constrain rendering to that screen. Changing the sides not touching a screen + // border however is fine as long as the screen contains the entire window. + m_resize_window->check_untile_due_to_resize(new_rect); + } dbgln_if(RESIZE_DEBUG, "[WM] Resizing, original: {}, now: {}", m_resize_window_original_rect, new_rect); m_resize_window->set_rect(new_rect);
81d5bbcb04e9c20d052dc06b8051c828a7250c63
2022-12-14 15:29:45
Linus Groh
libjs: Convert Intl::DateTimeFormatFunction::create() to NonnullGCPtr
false
Convert Intl::DateTimeFormatFunction::create() to NonnullGCPtr
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.cpp index 9408a7904d72..3b8be4d42a70 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.cpp @@ -14,9 +14,9 @@ namespace JS::Intl { // 11.5.5 DateTime Format Functions, https://tc39.es/ecma402/#sec-datetime-format-functions -DateTimeFormatFunction* DateTimeFormatFunction::create(Realm& realm, DateTimeFormat& date_time_format) +NonnullGCPtr<DateTimeFormatFunction> DateTimeFormatFunction::create(Realm& realm, DateTimeFormat& date_time_format) { - return realm.heap().allocate<DateTimeFormatFunction>(realm, date_time_format, *realm.intrinsics().function_prototype()); + return *realm.heap().allocate<DateTimeFormatFunction>(realm, date_time_format, *realm.intrinsics().function_prototype()); } DateTimeFormatFunction::DateTimeFormatFunction(DateTimeFormat& date_time_format, Object& prototype) diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.h b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.h index d11669b8c731..8634629ba36c 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatFunction.h @@ -16,7 +16,7 @@ class DateTimeFormatFunction final : public NativeFunction { JS_OBJECT(DateTimeFormatFunction, NativeFunction); public: - static DateTimeFormatFunction* create(Realm&, DateTimeFormat&); + static NonnullGCPtr<DateTimeFormatFunction> create(Realm&, DateTimeFormat&); virtual ~DateTimeFormatFunction() override = default; virtual void initialize(Realm&) override; diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp index 2e6b99c5da4e..a18f75178274 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormatPrototype.cpp @@ -52,7 +52,7 @@ JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatPrototype::format) if (!date_time_format->bound_format()) { // a. Let F be a new built-in function object as defined in DateTime Format Functions (11.1.6). // b. Set F.[[DateTimeFormat]] to dtf. - auto* bound_format = DateTimeFormatFunction::create(realm, *date_time_format); + auto bound_format = DateTimeFormatFunction::create(realm, *date_time_format); // c. Set dtf.[[BoundFormat]] to F. date_time_format->set_bound_format(bound_format);
b58dbc29fc8b1e5711a8548f8dc2fc66c77b5213
2021-04-18 01:40:35
AnotherTest
libline: Add support for ^X^E
false
Add support for ^X^E
libline
diff --git a/Userland/Libraries/LibLine/Editor.cpp b/Userland/Libraries/LibLine/Editor.cpp index d029d837f111..e86d08bff063 100644 --- a/Userland/Libraries/LibLine/Editor.cpp +++ b/Userland/Libraries/LibLine/Editor.cpp @@ -62,6 +62,7 @@ Configuration Configuration::from_config(const StringView& libname) // Read behaviour options. auto refresh = config_file->read_entry("behaviour", "refresh", "lazy"); auto operation = config_file->read_entry("behaviour", "operation_mode"); + auto default_text_editor = config_file->read_entry("behaviour", "default_text_editor"); if (refresh.equals_ignoring_case("lazy")) configuration.set(Configuration::Lazy); @@ -77,6 +78,11 @@ Configuration Configuration::from_config(const StringView& libname) else configuration.set(Configuration::OperationMode::Unset); + if (!default_text_editor.is_empty()) + configuration.set(DefaultTextEditor { move(default_text_editor) }); + else + configuration.set(DefaultTextEditor { "/bin/TextEditor" }); + // Read keybinds. for (auto& binding_key : config_file->keys("keybinds")) { @@ -168,6 +174,9 @@ void Editor::set_default_keybinds() register_key_input_callback(ctrl('T'), EDITOR_INTERNAL_FUNCTION(transpose_characters)); register_key_input_callback('\n', EDITOR_INTERNAL_FUNCTION(finish)); + // ^X^E: Edit in external editor + register_key_input_callback(Vector<Key> { ctrl('X'), ctrl('E') }, EDITOR_INTERNAL_FUNCTION(edit_in_external_editor)); + // ^[.: alt-.: insert last arg of previous command (similar to `!$`) register_key_input_callback(Key { '.', Key::Alt }, EDITOR_INTERNAL_FUNCTION(insert_last_words)); register_key_input_callback(Key { 'b', Key::Alt }, EDITOR_INTERNAL_FUNCTION(cursor_left_word)); diff --git a/Userland/Libraries/LibLine/Editor.h b/Userland/Libraries/LibLine/Editor.h index 083d3ceb913f..23aea8d3c78b 100644 --- a/Userland/Libraries/LibLine/Editor.h +++ b/Userland/Libraries/LibLine/Editor.h @@ -81,6 +81,10 @@ struct Configuration { NoSignalHandlers, }; + struct DefaultTextEditor { + String command; + }; + Configuration() { } @@ -96,6 +100,7 @@ struct Configuration { void set(OperationMode mode) { operation_mode = mode; } void set(SignalHandler mode) { m_signal_mode = mode; } void set(const KeyBinding& binding) { keybindings.append(binding); } + void set(DefaultTextEditor editor) { m_default_text_editor = move(editor.command); } static Configuration from_config(const StringView& libname = "line"); @@ -103,6 +108,7 @@ struct Configuration { SignalHandler m_signal_mode { SignalHandler::WithSignalHandlers }; OperationMode operation_mode { OperationMode::Unset }; Vector<KeyBinding> keybindings; + String m_default_text_editor {}; }; #define ENUMERATE_EDITOR_INTERNAL_FUNCTIONS(M) \ @@ -130,7 +136,8 @@ struct Configuration { M(erase_alnum_word_forwards) \ M(capitalize_word) \ M(lowercase_word) \ - M(uppercase_word) + M(uppercase_word) \ + M(edit_in_external_editor) #define EDITOR_INTERNAL_FUNCTION(name) \ [](auto& editor) { editor.name(); return false; } diff --git a/Userland/Libraries/LibLine/InternalFunctions.cpp b/Userland/Libraries/LibLine/InternalFunctions.cpp index 015754c0b05b..73c799603da4 100644 --- a/Userland/Libraries/LibLine/InternalFunctions.cpp +++ b/Userland/Libraries/LibLine/InternalFunctions.cpp @@ -24,12 +24,16 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include <AK/ScopeGuard.h> #include <AK/ScopedValueRollback.h> #include <AK/StringBuilder.h> #include <AK/TemporaryChange.h> +#include <LibCore/File.h> #include <LibLine/Editor.h> #include <ctype.h> #include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> namespace { constexpr u32 ctrl(char c) { return c & 0x3f; } @@ -522,4 +526,91 @@ void Editor::uppercase_word() case_change_word(CaseChangeOp::Uppercase); } +void Editor::edit_in_external_editor() +{ + const auto* editor_command = getenv("EDITOR"); + if (!editor_command) + editor_command = m_configuration.m_default_text_editor.characters(); + + char file_path[] = "/tmp/line-XXXXXX"; + auto fd = mkstemp(file_path); + + if (fd < 0) { + perror("mktemp"); + return; + } + + { + auto* fp = fdopen(fd, "rw"); + if (!fp) { + perror("fdopen"); + return; + } + + StringBuilder builder; + builder.append(Utf32View { m_buffer.data(), m_buffer.size() }); + auto view = builder.string_view(); + size_t remaining_size = view.length(); + + while (remaining_size > 0) + remaining_size = fwrite(view.characters_without_null_termination() - remaining_size, sizeof(char), remaining_size, fp); + + fclose(fp); + } + + ScopeGuard remove_temp_file_guard { + [fd, file_path] { + close(fd); + unlink(file_path); + } + }; + + Vector<const char*> args { editor_command, file_path, nullptr }; + auto pid = vfork(); + + if (pid == -1) { + perror("vfork"); + return; + } + + if (pid == 0) { + execvp(editor_command, const_cast<char* const*>(args.data())); + perror("execv"); + _exit(126); + } else { + int wstatus = 0; + do { + waitpid(pid, &wstatus, 0); + } while (errno == EINTR); + + if (!(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)) + return; + } + + { + auto file_or_error = Core::File::open(file_path, Core::IODevice::OpenMode::ReadOnly); + if (file_or_error.is_error()) + return; + + auto file = file_or_error.release_value(); + auto contents = file->read_all(); + StringView data { contents }; + while (data.ends_with('\n')) + data = data.substring_view(0, data.length() - 1); + + m_cursor = 0; + m_chars_touched_in_the_middle = m_buffer.size(); + m_buffer.clear_with_capacity(); + m_refresh_needed = true; + + Utf8View view { data }; + if (view.validate()) { + for (auto cp : view) + insert(cp); + } else { + for (auto ch : data) + insert(ch); + } + } +} }
9a4b117f48afde89b7f464badc224178289d7242
2019-11-06 17:45:55
Andreas Kling
kernel: Simplify kernel entry points slightly
false
Simplify kernel entry points slightly
kernel
diff --git a/Kernel/Arch/i386/CPU.cpp b/Kernel/Arch/i386/CPU.cpp index ab98e63454ed..738dcf35b3f9 100644 --- a/Kernel/Arch/i386/CPU.cpp +++ b/Kernel/Arch/i386/CPU.cpp @@ -62,40 +62,38 @@ asm( " add $0x4, %esp\n" " iret\n"); -#define EH_ENTRY(ec) \ - extern "C" void exception_##ec##_handler(RegisterDump&); \ - extern "C" void exception_##ec##_entry(); \ - asm( \ - ".globl exception_" #ec "_entry\n" \ - "exception_" #ec "_entry: \n" \ - " pusha\n" \ - " pushw %ds\n" \ - " pushw %es\n" \ - " pushw %fs\n" \ - " pushw %gs\n" \ - " pushw %ss\n" \ - " pushw %ss\n" \ - " pushw %ss\n" \ - " pushw %ss\n" \ - " pushw %ss\n" \ - " popw %ds\n" \ - " popw %es\n" \ - " popw %fs\n" \ - " popw %gs\n" \ - " pushl %esp\n" \ - " call exception_" #ec "_handler\n" \ - " add $4, %esp\n" \ - " popw %gs\n" \ - " popw %gs\n" \ - " popw %fs\n" \ - " popw %es\n" \ - " popw %ds\n" \ - " popa\n" \ - " add $0x4, %esp\n" \ +#define EH_ENTRY(ec) \ + extern "C" void exception_##ec##_handler(RegisterDump); \ + extern "C" void exception_##ec##_entry(); \ + asm( \ + ".globl exception_" #ec "_entry\n" \ + "exception_" #ec "_entry: \n" \ + " pusha\n" \ + " pushw %ds\n" \ + " pushw %es\n" \ + " pushw %fs\n" \ + " pushw %gs\n" \ + " pushw %ss\n" \ + " pushw %ss\n" \ + " pushw %ss\n" \ + " pushw %ss\n" \ + " pushw %ss\n" \ + " popw %ds\n" \ + " popw %es\n" \ + " popw %fs\n" \ + " popw %gs\n" \ + " call exception_" #ec "_handler\n" \ + " popw %gs\n" \ + " popw %gs\n" \ + " popw %fs\n" \ + " popw %es\n" \ + " popw %ds\n" \ + " popa\n" \ + " add $0x4, %esp\n" \ " iret\n"); #define EH_ENTRY_NO_CODE(ec) \ - extern "C" void exception_##ec##_handler(RegisterDump&); \ + extern "C" void exception_##ec##_handler(RegisterDump); \ extern "C" void exception_##ec##_entry(); \ asm( \ ".globl exception_" #ec "_entry\n" \ @@ -115,9 +113,7 @@ asm( " popw %es\n" \ " popw %fs\n" \ " popw %gs\n" \ - " pushl %esp\n" \ " call exception_" #ec "_handler\n" \ - " add $4, %esp\n" \ " popw %gs\n" \ " popw %gs\n" \ " popw %fs\n" \ @@ -186,26 +182,26 @@ static void handle_crash(RegisterDump& regs, const char* description, int signal } EH_ENTRY_NO_CODE(6); -void exception_6_handler(RegisterDump& regs) +void exception_6_handler(RegisterDump regs) { handle_crash(regs, "Illegal instruction", SIGILL); } EH_ENTRY_NO_CODE(0); -void exception_0_handler(RegisterDump& regs) +void exception_0_handler(RegisterDump regs) { handle_crash(regs, "Division by zero", SIGFPE); } EH_ENTRY(13); -void exception_13_handler(RegisterDump& regs) +void exception_13_handler(RegisterDump regs) { handle_crash(regs, "General protection fault", SIGSEGV); } // 7: FPU not available exception EH_ENTRY_NO_CODE(7); -void exception_7_handler(RegisterDump& regs) +void exception_7_handler(RegisterDump regs) { (void)regs; @@ -237,7 +233,7 @@ void exception_7_handler(RegisterDump& regs) // 14: Page Fault EH_ENTRY(14); -void exception_14_handler(RegisterDump& regs) +void exception_14_handler(RegisterDump regs) { ASSERT(current); diff --git a/Kernel/Arch/i386/PIT.cpp b/Kernel/Arch/i386/PIT.cpp index 1890dac61745..b4861c30661f 100644 --- a/Kernel/Arch/i386/PIT.cpp +++ b/Kernel/Arch/i386/PIT.cpp @@ -7,7 +7,7 @@ #define IRQ_TIMER 0 extern "C" void timer_interrupt_entry(); -extern "C" void timer_interrupt_handler(RegisterDump&); +extern "C" void timer_interrupt_handler(RegisterDump); asm( ".globl timer_interrupt_entry \n" @@ -27,9 +27,7 @@ asm( " popw %es\n" " popw %fs\n" " popw %gs\n" - " pushl %esp\n" " call timer_interrupt_handler\n" - " add $4, %esp\n" " popw %gs\n" " popw %gs\n" " popw %fs\n" @@ -42,7 +40,7 @@ asm( static u32 s_ticks_this_second; static u32 s_seconds_since_boot; -void timer_interrupt_handler(RegisterDump& regs) +void timer_interrupt_handler(RegisterDump regs) { IRQHandlerScope scope(IRQ_TIMER); if (++s_ticks_this_second >= TICKS_PER_SECOND) { diff --git a/Kernel/Syscall.cpp b/Kernel/Syscall.cpp index aa581dc9fc60..a055e7951097 100644 --- a/Kernel/Syscall.cpp +++ b/Kernel/Syscall.cpp @@ -6,7 +6,7 @@ #include <Kernel/Scheduler.h> #include <Kernel/Syscall.h> -extern "C" void syscall_trap_entry(RegisterDump&); +extern "C" void syscall_trap_entry(RegisterDump); extern "C" void syscall_trap_handler(); extern volatile RegisterDump* syscallRegDump; @@ -28,9 +28,7 @@ asm( " popw %es\n" " popw %fs\n" " popw %gs\n" - " pushl %esp\n" " call syscall_trap_entry\n" - " add $4, %esp\n" " popw %gs\n" " popw %gs\n" " popw %fs\n" @@ -329,7 +327,7 @@ static u32 handle(RegisterDump& regs, u32 function, u32 arg1, u32 arg2, u32 arg3 } -void syscall_trap_entry(RegisterDump& regs) +void syscall_trap_entry(RegisterDump regs) { current->process().big_lock().lock(); u32 function = regs.eax;
e145344767f25bca786ffb298f3a2109d21b2bf6
2019-03-27 09:32:02
Andreas Kling
libc: Remove the validate_mallocation() stuff since Binutils hates it.
false
Remove the validate_mallocation() stuff since Binutils hates it.
libc
diff --git a/LibC/stdlib.cpp b/LibC/stdlib.cpp index 8bd49ed5ee52..cc152b9b12b4 100644 --- a/LibC/stdlib.cpp +++ b/LibC/stdlib.cpp @@ -24,15 +24,6 @@ struct MallocHeader { uint16_t chunk_count : 15; bool is_mmap : 1; size_t size; - - uint32_t compute_xorcheck() const - { - return 0x19820413 ^ ((first_chunk_index << 16) | chunk_count) ^ size; - } -}; - -struct MallocFooter { - uint32_t xorcheck; }; #define CHUNK_SIZE 32 @@ -51,7 +42,7 @@ void* malloc(size_t size) return nullptr; // We need space for the MallocHeader structure at the head of the block. - size_t real_size = size + sizeof(MallocHeader) + sizeof(MallocFooter); + size_t real_size = size + sizeof(MallocHeader); if (real_size >= PAGE_SIZE) { auto* memory = mmap(nullptr, real_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); @@ -111,16 +102,13 @@ void* malloc(size_t size) header->is_mmap = false; header->size = size; - auto* footer = (MallocFooter*)((byte*)header + (header->chunk_count * CHUNK_SIZE) - sizeof(MallocFooter)); - footer->xorcheck = header->compute_xorcheck(); - for (size_t k = first_chunk; k < (first_chunk + chunks_needed); ++k) s_malloc_map[k / 8] |= 1 << (k % 8); s_malloc_sum_alloc += header->chunk_count * CHUNK_SIZE; s_malloc_sum_free -= header->chunk_count * CHUNK_SIZE; - memset(ptr, MALLOC_SCRUB_BYTE, (header->chunk_count * CHUNK_SIZE) - (sizeof(MallocHeader) + sizeof(MallocFooter))); + memset(ptr, MALLOC_SCRUB_BYTE, (header->chunk_count * CHUNK_SIZE) - sizeof(MallocHeader)); return ptr; } } @@ -132,21 +120,6 @@ void* malloc(size_t size) return nullptr; } -static void validate_mallocation(void* ptr, const char* func) -{ - auto* header = (MallocHeader*)((((byte*)ptr) - sizeof(MallocHeader))); - if (header->size == 0) { - fprintf(stderr, "%s called on bad pointer %p, size=0\n", func, ptr); - assert(false); - } - auto* footer = (MallocFooter*)((byte*)header + (header->chunk_count * CHUNK_SIZE) - sizeof(MallocFooter)); - uint32_t expected_xorcheck = header->compute_xorcheck(); - if (footer->xorcheck != expected_xorcheck) { - fprintf(stderr, "%s called on bad pointer %p, xorcheck=%w (expected %w)\n", func, ptr, footer->xorcheck, expected_xorcheck); - assert(false); - } -} - void free(void* ptr) { if (!ptr) @@ -160,7 +133,6 @@ void free(void* ptr) return; } - validate_mallocation(ptr, "free()"); for (unsigned i = header->first_chunk_index; i < (header->first_chunk_index + header->chunk_count); ++i) s_malloc_map[i / 8] &= ~(1 << (i % 8)); @@ -190,7 +162,6 @@ void* realloc(void *ptr, size_t size) { if (!ptr) return malloc(size); - validate_mallocation(ptr, "realloc()"); auto* header = (MallocHeader*)((((byte*)ptr) - sizeof(MallocHeader))); size_t old_size = header->size; if (size == old_size)
228022925a169f642d48f2c0adfc78dbcaed4fd5
2023-10-03 18:51:26
kleines Filmröllchen
ports: Add qt6-qtsvg
false
Add qt6-qtsvg
ports
diff --git a/Ports/AvailablePorts.md b/Ports/AvailablePorts.md index a5732cb60800..d44bc77eabe1 100644 --- a/Ports/AvailablePorts.md +++ b/Ports/AvailablePorts.md @@ -262,6 +262,7 @@ This list is also available at [ports.serenityos.net](https://ports.serenityos.n | [`qoi`](qoi/) | Quite OK Image Format for fast, lossless image compression | edb8d7b | https://github.com/phoboslab/qoi | | [`qt6-qt5compat`](qt6-qt5compat/) | Qt6 Qt5Compat | 6.4.0 | https://doc.qt.io/qt-6/qtcore5-index.html | | [`qt6-qtbase`](qt6-qtbase/) | Qt6 QtBase | 6.4.0 | https://qt.io | +| [`qt6-qtsvg`](qt6-qtsvg/) | Qt6 QtSVG | 6.4.0 | https://qt.io | | [`qt6-serenity`](qt6-serenity/) | QSerenityPlatform | | https://github.com/SerenityPorts/QSerenityPlatform | | [`quake`](quake/) | Quake | 0.65 | https://github.com/SerenityOS/SerenityQuake | | [`quake2`](quake2/) | QuakeII | 0.1 | https://github.com/shamazmazum/quake2sdl | diff --git a/Ports/qt6-qtsvg/package.sh b/Ports/qt6-qtsvg/package.sh new file mode 100755 index 000000000000..080b179fa1d5 --- /dev/null +++ b/Ports/qt6-qtsvg/package.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env -S bash ../.port_include.sh +port='qt6-qtsvg' +version='6.4.0' +workdir="qtsvg-everywhere-src-${version}" +useconfigure='true' +files=( + "https://download.qt.io/official_releases/qt/$(cut -d. -f1,2 <<< ${version})/${version}/submodules/qtsvg-everywhere-src-${version}.tar.xz#03fdae9437d074dcfa387dc1f2c6e7e14fea0f989bf7e1aa265fd35ffc2c5b25" +) +configopts=( + '-GNinja' + "-DCMAKE_TOOLCHAIN_FILE=${SERENITY_BUILD_DIR}/CMakeToolchain.txt" + '-DCMAKE_CROSSCOMPILING=ON' + '-DQT_FORCE_BUILD_TOOLS=ON' +) +depends=( + 'qt6-qtbase' +) + +configure() { + QT_HOST_PATH="$(qmake6 -query QT_HOST_PREFIX)" + QT_HOST_CMAKE_PATH="$(qmake6 -query QT_HOST_LIBS)/cmake" + QT_HOST_TOOLS='HostInfo CoreTools GuiTools WidgetsTools' + QT_HOST_TOOLS_PATH="${QT_HOST_CMAKE_PATH}/Qt6%s/\n" + + for host_tool in ${QT_HOST_TOOLS}; do + if [[ ! -d $(printf $QT_HOST_TOOLS_PATH $host_tool) ]]; then + echo "You need to have Qt $version installed on the host (path "$(printf $QT_HOST_TOOLS_PATH $host_tool)" is missing)" + exit 1 + fi + done + + MERGED_HOST_TOOLS=$(for host_tool in ${QT_HOST_TOOLS}; do echo "-DQt6${host_tool}_DIR=${QT_HOST_CMAKE_PATH}/Qt6${host_tool}/"; done) + + run cmake ${configopts[@]} "-DQT_HOST_PATH=${QT_HOST_PATH}" ${MERGED_HOST_TOOLS} +} + +build() { + run ninja +} + +install() { + run ninja install +}
0b421a37643c11640ee01510ca49a55e60de6b2f
2023-03-10 16:37:14
kleines Filmröllchen
libaudio: Implement the Quite Okay Audio format
false
Implement the Quite Okay Audio format
libaudio
diff --git a/Userland/Libraries/LibAudio/CMakeLists.txt b/Userland/Libraries/LibAudio/CMakeLists.txt index 67777584e5b8..cd13d42af75d 100644 --- a/Userland/Libraries/LibAudio/CMakeLists.txt +++ b/Userland/Libraries/LibAudio/CMakeLists.txt @@ -5,6 +5,8 @@ set(SOURCES FlacLoader.cpp WavWriter.cpp MP3Loader.cpp + QOALoader.cpp + QOATypes.cpp UserSampleQueue.cpp ) diff --git a/Userland/Libraries/LibAudio/Loader.cpp b/Userland/Libraries/LibAudio/Loader.cpp index 12a527951939..e0d5b7e7239d 100644 --- a/Userland/Libraries/LibAudio/Loader.cpp +++ b/Userland/Libraries/LibAudio/Loader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2021, the SerenityOS developers. + * Copyright (c) 2018-2023, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ @@ -7,6 +7,7 @@ #include <LibAudio/FlacLoader.h> #include <LibAudio/Loader.h> #include <LibAudio/MP3Loader.h> +#include <LibAudio/QOALoader.h> #include <LibAudio/WavLoader.h> namespace Audio { @@ -41,6 +42,12 @@ Result<NonnullOwnPtr<LoaderPlugin>, LoaderError> Loader::create_plugin(StringVie return NonnullOwnPtr<LoaderPlugin>(plugin.release_value()); } + { + auto plugin = QOALoaderPlugin::create(path); + if (!plugin.is_error()) + return NonnullOwnPtr<LoaderPlugin>(plugin.release_value()); + } + return LoaderError { "No loader plugin available" }; } @@ -64,6 +71,12 @@ Result<NonnullOwnPtr<LoaderPlugin>, LoaderError> Loader::create_plugin(Bytes buf return NonnullOwnPtr<LoaderPlugin>(plugin.release_value()); } + { + auto plugin = QOALoaderPlugin::create(buffer); + if (!plugin.is_error()) + return NonnullOwnPtr<LoaderPlugin>(plugin.release_value()); + } + return LoaderError { "No loader plugin available" }; } diff --git a/Userland/Libraries/LibAudio/QOALoader.cpp b/Userland/Libraries/LibAudio/QOALoader.cpp new file mode 100644 index 000000000000..7d640f6d2c33 --- /dev/null +++ b/Userland/Libraries/LibAudio/QOALoader.cpp @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2023, kleines Filmröllchen <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "QOALoader.h" +#include "Loader.h" +#include "LoaderError.h" +#include "QOATypes.h" +#include <AK/Array.h> +#include <AK/Assertions.h> +#include <AK/Endian.h> +#include <AK/FixedArray.h> +#include <AK/MemoryStream.h> +#include <AK/Stream.h> +#include <AK/Types.h> +#include <LibCore/File.h> + +namespace Audio { + +QOALoaderPlugin::QOALoaderPlugin(NonnullOwnPtr<AK::SeekableStream> stream) + : LoaderPlugin(move(stream)) +{ +} + +Result<NonnullOwnPtr<QOALoaderPlugin>, LoaderError> QOALoaderPlugin::create(StringView path) +{ + auto stream = LOADER_TRY(Core::BufferedFile::create(LOADER_TRY(Core::File::open(path, Core::File::OpenMode::Read)))); + auto loader = make<QOALoaderPlugin>(move(stream)); + + LOADER_TRY(loader->initialize()); + + return loader; +} + +Result<NonnullOwnPtr<QOALoaderPlugin>, LoaderError> QOALoaderPlugin::create(Bytes buffer) +{ + auto loader = make<QOALoaderPlugin>(make<FixedMemoryStream>(buffer)); + + LOADER_TRY(loader->initialize()); + + return loader; +} + +MaybeLoaderError QOALoaderPlugin::initialize() +{ + TRY(parse_header()); + TRY(reset()); + return {}; +} + +MaybeLoaderError QOALoaderPlugin::parse_header() +{ + u32 header_magic = LOADER_TRY(m_stream->read_value<BigEndian<u32>>()); + if (header_magic != QOA::magic) + return LoaderError { LoaderError::Category::Format, 0, "QOA header: Magic number must be 'qoaf'" }; + + m_total_samples = LOADER_TRY(m_stream->read_value<BigEndian<u32>>()); + + return {}; +} + +MaybeLoaderError QOALoaderPlugin::load_one_frame(Span<Sample>& target, IsFirstFrame is_first_frame) +{ + QOA::FrameHeader header = LOADER_TRY(m_stream->read_value<QOA::FrameHeader>()); + + if (header.num_channels > 8) + dbgln("QOALoader: Warning: QOA frame at {} has more than 8 channels ({}), this is not supported by the reference implementation.", LOADER_TRY(m_stream->tell()) - sizeof(QOA::FrameHeader), header.num_channels); + if (header.num_channels == 0) + return LoaderError { LoaderError::Category::Format, LOADER_TRY(m_stream->tell()), "QOA frame: Number of channels must be greater than 0" }; + if (header.sample_count > QOA::max_frame_samples) + return LoaderError { LoaderError::Category::Format, LOADER_TRY(m_stream->tell()), "QOA frame: Too many samples in frame" }; + + // We weren't given a large enough buffer; signal that we didn't write anything and return. + if (header.sample_count > target.size()) { + target = target.trim(0); + LOADER_TRY(m_stream->seek(-sizeof(QOA::frame_header_size), AK::SeekMode::FromCurrentPosition)); + return {}; + } + + target = target.trim(header.sample_count); + + auto lms_states = LOADER_TRY(FixedArray<QOA::LMSState>::create(header.num_channels)); + for (size_t channel = 0; channel < header.num_channels; ++channel) { + auto history_packed = LOADER_TRY(m_stream->read_value<BigEndian<u64>>()); + auto weights_packed = LOADER_TRY(m_stream->read_value<BigEndian<u64>>()); + lms_states[channel] = { history_packed, weights_packed }; + } + + // We pre-allocate very large arrays here, but that's the last allocation of the QOA loader! + // Everything else is just shuffling data around. + // (We will also be using all of the arrays in every frame but the last one.) + auto channels = LOADER_TRY((FixedArray<Array<i16, QOA::max_frame_samples>>::create(header.num_channels))); + + // There's usually (and at maximum) 256 slices per channel, but less at the very end. + // If the final slice would be partial, we still need to decode it; integer division would tell us that this final slice doesn't exist. + auto const slice_count = static_cast<size_t>(ceil(static_cast<double>(header.sample_count) / static_cast<double>(QOA::slice_samples))); + VERIFY(slice_count <= QOA::max_slices_per_frame); + + // Observe the loop nesting: Slices are channel-interleaved. + for (size_t slice = 0; slice < slice_count; ++slice) { + for (size_t channel = 0; channel < header.num_channels; ++channel) { + auto slice_samples = channels[channel].span().slice(slice * QOA::slice_samples, QOA::slice_samples); + TRY(read_one_slice(lms_states[channel], slice_samples)); + } + } + + if (is_first_frame == IsFirstFrame::Yes) { + m_num_channels = header.num_channels; + m_sample_rate = header.sample_rate; + } else { + if (m_sample_rate != header.sample_rate) + return LoaderError { LoaderError::Category::Unimplemented, LOADER_TRY(m_stream->tell()), "QOA: Differing sample rate in non-initial frame" }; + if (m_num_channels != header.num_channels) + m_has_uniform_channel_count = false; + } + + switch (header.num_channels) { + case 1: + for (size_t sample = 0; sample < header.sample_count; ++sample) + target[sample] = Sample { static_cast<float>(channels[0][sample]) / static_cast<float>(NumericLimits<i16>::max()) }; + break; + // FIXME: Combine surround channels sensibly, FlacLoader has the same simplification at the moment. + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + default: + for (size_t sample = 0; sample < header.sample_count; ++sample) { + target[sample] = { + static_cast<float>(channels[0][sample]) / static_cast<float>(NumericLimits<i16>::max()), + static_cast<float>(channels[1][sample]) / static_cast<float>(NumericLimits<i16>::max()), + }; + } + break; + } + + return {}; +} + +LoaderSamples QOALoaderPlugin::get_more_samples(size_t max_samples_to_read_from_input) +{ + // Because each frame can only have so many inter-channel samples (quite a low number), + // we just load frames until the limit is reached, but at least one. + // This avoids caching samples in the QOA loader, simplifying state management. + + if (max_samples_to_read_from_input < QOA::max_frame_samples) + return LoaderError { LoaderError::Category::Internal, LOADER_TRY(m_stream->tell()), "QOA loader is not capable of reading less than one frame of samples"sv }; + + ssize_t const remaining_samples = static_cast<ssize_t>(m_total_samples - m_loaded_samples); + if (remaining_samples <= 0) + return FixedArray<Sample> {}; + size_t const samples_to_read = min(max_samples_to_read_from_input, remaining_samples); + auto is_first_frame = m_loaded_samples == 0 ? IsFirstFrame::Yes : IsFirstFrame::No; + + auto samples = LOADER_TRY(FixedArray<Sample>::create(samples_to_read)); + size_t current_loaded_samples = 0; + + while (current_loaded_samples < samples_to_read) { + auto slice_to_load_into = samples.span().slice(current_loaded_samples, min(QOA::max_frame_samples, samples.size() - current_loaded_samples)); + TRY(this->load_one_frame(slice_to_load_into, is_first_frame)); + is_first_frame = IsFirstFrame::No; + VERIFY(slice_to_load_into.size() <= QOA::max_frame_samples); + current_loaded_samples += slice_to_load_into.size(); + // The buffer wasn't large enough for the next frame. + if (slice_to_load_into.size() == 0) + break; + } + m_loaded_samples += current_loaded_samples; + auto trimmed_samples = LOADER_TRY(FixedArray<Sample>::create(samples.span().trim(current_loaded_samples))); + + return trimmed_samples; +} + +MaybeLoaderError QOALoaderPlugin::reset() +{ + LOADER_TRY(m_stream->seek(QOA::header_size, AK::SeekMode::SetPosition)); + m_loaded_samples = 0; + // Read the first frame, then seek back to the beginning. This is necessary since the first frame contains the sample rate and channel count. + auto frame_samples = LOADER_TRY(FixedArray<Sample>::create(QOA::max_frame_samples)); + auto span = frame_samples.span(); + LOADER_TRY(load_one_frame(span, IsFirstFrame::Yes)); + + LOADER_TRY(m_stream->seek(QOA::header_size, AK::SeekMode::SetPosition)); + m_loaded_samples = 0; + return {}; +} + +MaybeLoaderError QOALoaderPlugin::seek(int sample_index) +{ + if (sample_index == 0 && m_loaded_samples == 0) + return {}; + // A QOA file consists of 8 bytes header followed by a number of usually fixed-size frames. + // This fixed bitrate allows us to seek in constant time. + if (!m_has_uniform_channel_count) + return LoaderError { LoaderError::Category::Unimplemented, LOADER_TRY(m_stream->tell()), "QOA with non-uniform channel count is currently not seekable"sv }; + /// FIXME: Change the Loader API to use size_t. + VERIFY(sample_index >= 0); + // We seek to the frame "before"; i.e. the frame that contains that sample. + auto const frame_of_sample = static_cast<size_t>(AK::floor<double>(static_cast<double>(sample_index) / static_cast<double>(QOA::max_frame_samples))); + auto const frame_size = QOA::frame_header_size + m_num_channels * (QOA::lms_state_size + sizeof(QOA::PackedSlice) * QOA::max_slices_per_frame); + auto const byte_index = QOA::header_size + frame_of_sample * frame_size; + LOADER_TRY(m_stream->seek(byte_index, AK::SeekMode::SetPosition)); + m_loaded_samples = frame_of_sample * QOA::max_frame_samples; + return {}; +} + +MaybeLoaderError QOALoaderPlugin::read_one_slice(QOA::LMSState& lms_state, Span<i16>& samples) +{ + VERIFY(samples.size() == QOA::slice_samples); + + auto packed_slice = LOADER_TRY(m_stream->read_value<BigEndian<u64>>()); + auto unpacked_slice = unpack_slice(packed_slice); + + for (size_t i = 0; i < QOA::slice_samples; ++i) { + auto const residual = unpacked_slice.residuals[i]; + auto const predicted = lms_state.predict(); + auto const dequantized = QOA::dequantization_table[unpacked_slice.scale_factor_index][residual]; + auto const reconstructed = clamp(predicted + dequantized, QOA::sample_minimum, QOA::sample_maximum); + samples[i] = static_cast<i16>(reconstructed); + lms_state.update(reconstructed, dequantized); + } + + return {}; +} + +QOA::UnpackedSlice QOALoaderPlugin::unpack_slice(QOA::PackedSlice packed_slice) +{ + size_t const scale_factor_index = (packed_slice >> 60) & 0b1111; + Array<u8, 20> residuals = {}; + auto shifted_slice = packed_slice << 4; + + for (size_t i = 0; i < QOA::slice_samples; ++i) { + residuals[i] = static_cast<u8>((shifted_slice >> 61) & 0b111); + shifted_slice <<= 3; + } + + return { + .scale_factor_index = scale_factor_index, + .residuals = residuals, + }; +} + +i16 QOALoaderPlugin::qoa_divide(i16 value, i16 scale_factor) +{ + auto const reciprocal = QOA::reciprocal_table[scale_factor]; + auto const n = (value * reciprocal + (1 << 15)) >> 16; + // Rounding away from zero gives better quantization for small values. + auto const n_rounded = n + (static_cast<int>(value > 0) - static_cast<int>(value < 0)) - (static_cast<int>(n > 0) - static_cast<int>(n < 0)); + return static_cast<i16>(n_rounded); +} + +} diff --git a/Userland/Libraries/LibAudio/QOALoader.h b/Userland/Libraries/LibAudio/QOALoader.h new file mode 100644 index 000000000000..9d3cbb055ef4 --- /dev/null +++ b/Userland/Libraries/LibAudio/QOALoader.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023, kleines Filmröllchen <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Error.h> +#include <AK/Span.h> +#include <AK/Types.h> +#include <LibAudio/Loader.h> +#include <LibAudio/QOATypes.h> +#include <LibAudio/SampleFormats.h> + +namespace Audio { + +// Decoder for the Quite Okay Audio (QOA) format. +// NOTE: The QOA format is not finalized yet and this decoder might not be fully spec-compliant as of 2023-02-02. +// +// https://github.com/phoboslab/qoa/blob/master/qoa.h +class QOALoaderPlugin : public LoaderPlugin { +public: + explicit QOALoaderPlugin(NonnullOwnPtr<AK::SeekableStream> stream); + virtual ~QOALoaderPlugin() override = default; + + static Result<NonnullOwnPtr<QOALoaderPlugin>, LoaderError> create(StringView path); + static Result<NonnullOwnPtr<QOALoaderPlugin>, LoaderError> create(Bytes buffer); + + virtual LoaderSamples get_more_samples(size_t max_samples_to_read_from_input = 128 * KiB) override; + + virtual MaybeLoaderError reset() override; + virtual MaybeLoaderError seek(int sample_index) override; + + virtual int loaded_samples() override { return static_cast<int>(m_loaded_samples); } + virtual int total_samples() override { return static_cast<int>(m_total_samples); } + virtual u32 sample_rate() override { return m_sample_rate; } + virtual u16 num_channels() override { return m_num_channels; } + virtual DeprecatedString format_name() override { return "Quite Okay Audio (.qoa)"; } + virtual PcmSampleFormat pcm_format() override { return PcmSampleFormat::Int16; } + +private: + enum class IsFirstFrame : bool { + Yes = true, + No = false, + }; + + MaybeLoaderError initialize(); + MaybeLoaderError parse_header(); + + MaybeLoaderError load_one_frame(Span<Sample>& target, IsFirstFrame is_first_frame = IsFirstFrame::No); + // Updates predictor values in lms_state so the next slice can reuse the same state. + MaybeLoaderError read_one_slice(QOA::LMSState& lms_state, Span<i16>& samples); + static ALWAYS_INLINE QOA::UnpackedSlice unpack_slice(QOA::PackedSlice packed_slice); + + // QOA's division routine for scaling residuals before final quantization. + static ALWAYS_INLINE i16 qoa_divide(i16 value, i16 scale_factor); + + // Because QOA has dynamic sample rate and channel count, we only use the sample rate and channel count from the first frame. + u32 m_sample_rate { 0 }; + u8 m_num_channels { 0 }; + // If this is the case (the reference encoder even enforces it at the moment) + bool m_has_uniform_channel_count { true }; + + size_t m_loaded_samples { 0 }; + size_t m_total_samples { 0 }; +}; + +} diff --git a/Userland/Libraries/LibAudio/QOATypes.cpp b/Userland/Libraries/LibAudio/QOATypes.cpp new file mode 100644 index 000000000000..7ebdac655f38 --- /dev/null +++ b/Userland/Libraries/LibAudio/QOATypes.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2023, kleines Filmröllchen <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include "QOATypes.h" +#include <AK/Endian.h> +#include <AK/Stream.h> + +namespace Audio::QOA { + +ErrorOr<FrameHeader> FrameHeader::read_from_stream(Stream& stream) +{ + FrameHeader header; + header.num_channels = TRY(stream.read_value<u8>()); + u8 sample_rate[3]; + // Enforce the order of the reads here, since the order of expression evaluations further down is implementation-defined. + sample_rate[0] = TRY(stream.read_value<u8>()); + sample_rate[1] = TRY(stream.read_value<u8>()); + sample_rate[2] = TRY(stream.read_value<u8>()); + header.sample_rate = (sample_rate[0] << 16) | (sample_rate[1] << 8) | sample_rate[2]; + header.sample_count = TRY(stream.read_value<BigEndian<u16>>()); + header.frame_size = TRY(stream.read_value<BigEndian<u16>>()); + return header; +} + +LMSState::LMSState(u64 history_packed, u64 weights_packed) +{ + for (size_t i = 0; i < lms_history; ++i) { + // The casts ensure proper sign extension. + history[i] = static_cast<i16>(history_packed >> 48); + history_packed <<= 16; + weights[i] = static_cast<i16>(weights_packed >> 48); + weights_packed <<= 16; + } +} + +i32 LMSState::predict() const +{ + i32 prediction = 0; + for (size_t i = 0; i < lms_history; ++i) + prediction += history[i] * weights[i]; + return prediction >> 13; +} + +void LMSState::update(i32 sample, i32 residual) +{ + i32 delta = residual >> 4; + for (size_t i = 0; i < lms_history; ++i) + weights[i] += history[i] < 0 ? -delta : delta; + + for (size_t i = 0; i < lms_history - 1; ++i) + history[i] = history[i + 1]; + history[lms_history - 1] = sample; +} + +} diff --git a/Userland/Libraries/LibAudio/QOATypes.h b/Userland/Libraries/LibAudio/QOATypes.h new file mode 100644 index 000000000000..aeefb5f98be2 --- /dev/null +++ b/Userland/Libraries/LibAudio/QOATypes.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2023, kleines Filmröllchen <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Array.h> +#include <AK/Forward.h> +#include <AK/Math.h> +#include <AK/Types.h> +#include <math.h> + +namespace Audio::QOA { + +// 'qoaf' +static constexpr u32 const magic = 0x716f6166; + +static constexpr size_t const header_size = sizeof(u64); + +struct FrameHeader { + u8 num_channels; + u32 sample_rate; // 24 bits + u16 sample_count; + // TODO: might be removed and/or replaced + u16 frame_size; + + static ErrorOr<FrameHeader> read_from_stream(Stream& stream); +}; + +static constexpr size_t const frame_header_size = sizeof(u64); + +// Least mean squares (LMS) predictor FIR filter size. +static constexpr size_t const lms_history = 4; + +static constexpr size_t const lms_state_size = 2 * lms_history * sizeof(u16); + +// Only used for internal purposes; intermediate LMS states can be beyond 16 bits. +struct LMSState { + i32 history[lms_history] { 0, 0, 0, 0 }; + i32 weights[lms_history] { 0, 0, 0, 0 }; + + LMSState() = default; + LMSState(u64 history_packed, u64 weights_packed); + + i32 predict() const; + void update(i32 sample, i32 residual); +}; + +using PackedSlice = u64; + +// A QOA slice in a more directly readable format, unpacked from the stored 64-bit format. +struct UnpackedSlice { + size_t scale_factor_index; // 4 bits packed + Array<u8, 20> residuals; // 3 bits packed +}; + +// Samples within a 64-bit slice. +static constexpr size_t const slice_samples = 20; +static constexpr size_t const max_slices_per_frame = 256; +static constexpr size_t const max_frame_samples = slice_samples * max_slices_per_frame; + +// Defined as clamping limits by the spec. +static constexpr i32 const sample_minimum = -32768; +static constexpr i32 const sample_maximum = 32767; + +// Quantization and scale factor tables computed from formulas given in qoa.h + +constexpr Array<int, 17> generate_scale_factor_table() +{ + Array<int, 17> scalefactor_table; + for (size_t s = 0; s < 17; ++s) + scalefactor_table[s] = static_cast<int>(AK::round<double>(AK::pow<double>(static_cast<double>(s + 1), 2.75))); + + return scalefactor_table; +} + +// FIXME: Get rid of the literal table once Clang understands our constexpr pow() and round() implementations. +#if defined(AK_COMPILER_CLANG) +static constexpr Array<int, 17> scale_factor_table = { + 1, 7, 21, 45, 84, 138, 211, 304, 421, 562, 731, 928, 1157, 1419, 1715, 2048 +}; +#else +static constexpr Array<int, 17> scale_factor_table = generate_scale_factor_table(); +#endif + +constexpr Array<int, 17> generate_reciprocal_table() +{ + Array<int, 17> reciprocal_table; + for (size_t s = 0; s < 17; ++s) { + reciprocal_table[s] = ((1 << 16) + scale_factor_table[s] - 1) / scale_factor_table[s]; + } + return reciprocal_table; +} + +constexpr Array<Array<int, 8>, 16> generate_dequantization_table() +{ + Array<Array<int, 8>, 16> dequantization_table; + constexpr Array<double, 8> float_dequantization_table = { 0.75, -0.75, 2.5, -2.5, 4.5, -4.5, 7, -7 }; + for (size_t scale = 0; scale < 16; ++scale) { + for (size_t quantization = 0; quantization < 8; ++quantization) + dequantization_table[scale][quantization] = static_cast<int>(AK::round<double>( + static_cast<double>(scale_factor_table[scale]) * float_dequantization_table[quantization])); + } + return dequantization_table; +} + +#if defined(AK_COMPILER_CLANG) +static constexpr Array<int, 17> reciprocal_table = { + 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 +}; +static constexpr Array<Array<int, 8>, 16> dequantization_table = { + Array<int, 8> { 1, -1, 3, -3, 5, -5, 7, -7 }, + { 5, -5, 18, -18, 32, -32, 49, -49 }, + { 16, -16, 53, -53, 95, -95, 147, -147 }, + { 34, -34, 113, -113, 203, -203, 315, -315 }, + { 63, -63, 210, -210, 378, -378, 588, -588 }, + { 104, -104, 345, -345, 621, -621, 966, -966 }, + { 158, -158, 528, -528, 950, -950, 1477, -1477 }, + { 228, -228, 760, -760, 1368, -1368, 2128, -2128 }, + { 316, -316, 1053, -1053, 1895, -1895, 2947, -2947 }, + { 422, -422, 1405, -1405, 2529, -2529, 3934, -3934 }, + { 548, -548, 1828, -1828, 3290, -3290, 5117, -5117 }, + { 696, -696, 2320, -2320, 4176, -4176, 6496, -6496 }, + { 868, -868, 2893, -2893, 5207, -5207, 8099, -8099 }, + { 1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933 }, + { 1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005 }, + { 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336 }, +}; +#else +static constexpr Array<int, 17> reciprocal_table = generate_reciprocal_table(); +static constexpr Array<Array<int, 8>, 16> dequantization_table = generate_dequantization_table(); +#endif + +static constexpr Array<int, 17> quantization_table = { + 7, 7, 7, 5, 5, 3, 3, 1, // -8 ..-1 + 0, // 0 + 0, 2, 2, 4, 4, 6, 6, 6 // 1 .. 8 +}; + +}
712e348fad66e743e334e504066a92d753d7bc74
2020-10-06 23:59:26
asynts
terminal: Use new format functions.
false
Use new format functions.
terminal
diff --git a/Applications/Terminal/main.cpp b/Applications/Terminal/main.cpp index 52a1ccf461c6..1cd0494c2a90 100644 --- a/Applications/Terminal/main.cpp +++ b/Applications/Terminal/main.cpp @@ -67,9 +67,8 @@ static void utmp_update(const char* tty, pid_t pid, bool create) } if (utmpupdate_pid) return; - char shell_pid_string[64]; - snprintf(shell_pid_string, sizeof(shell_pid_string), "%d", pid); - execl("/bin/utmpupdate", "/bin/utmpupdate", "-f", "Terminal", "-p", shell_pid_string, (create ? "-c" : "-d"), tty, nullptr); + const auto shell_pid_string = String::formatted("{}", pid); + execl("/bin/utmpupdate", "/bin/utmpupdate", "-f", "Terminal", "-p", shell_pid_string.characters(), (create ? "-c" : "-d"), tty, nullptr); } static pid_t run_command(int ptm_fd, String command) @@ -77,7 +76,7 @@ static pid_t run_command(int ptm_fd, String command) pid_t pid = fork(); if (pid < 0) { perror("fork"); - dbg() << "run_command: could not fork to run '" << command << "'"; + dbgln("run_command: could not fork to run '{}'", command); return pid; } @@ -317,7 +316,7 @@ int main(int argc, char** argv) })); app_menu.add_separator(); app_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) { - dbgprintf("Terminal: Quit menu activated!\n"); + dbgln("Terminal: Quit menu activated!"); GUI::Application::the()->quit(); })); @@ -382,7 +381,7 @@ int main(int argc, char** argv) config->sync(); int result = app->exec(); - dbg() << "Exiting terminal, updating utmp"; + dbgln("Exiting terminal, updating utmp"); utmp_update(pts_name, 0, false); return result; }
e109b967a18711dbf884e6d380598225a3b5901b
2022-04-08 05:13:17
Linus Groh
libjs: Make options object const in more Temporal AOs
false
Make options object const in more Temporal AOs
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp index d015cffca82b..410bcde89b1f 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp @@ -834,7 +834,7 @@ StringView larger_of_two_temporal_units(StringView unit1, StringView unit2) } // 13.23 MergeLargestUnitOption ( options, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-mergelargestunitoption -ThrowCompletionOr<Object*> merge_largest_unit_option(GlobalObject& global_object, Object* options, String largest_unit) +ThrowCompletionOr<Object*> merge_largest_unit_option(GlobalObject& global_object, Object const* options, String largest_unit) { auto& vm = global_object.vm(); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h index c1fe33fb3505..1575909caaee 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.h @@ -119,7 +119,7 @@ ThrowCompletionOr<String> to_temporal_duration_total_unit(GlobalObject& global_o ThrowCompletionOr<Value> to_relative_temporal_object(GlobalObject&, Object const& options); ThrowCompletionOr<void> validate_temporal_unit_range(GlobalObject&, StringView largest_unit, StringView smallest_unit); StringView larger_of_two_temporal_units(StringView, StringView); -ThrowCompletionOr<Object*> merge_largest_unit_option(GlobalObject&, Object* options, String largest_unit); +ThrowCompletionOr<Object*> merge_largest_unit_option(GlobalObject&, Object const* options, String largest_unit); Optional<u16> maximum_temporal_duration_rounding_increment(StringView unit); ThrowCompletionOr<void> reject_object_with_calendar_or_time_zone(GlobalObject&, Object&); String format_seconds_string_part(u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Variant<StringView, u8> const& precision); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp index 67cad35cb481..7f7f2b0594f7 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp @@ -90,7 +90,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::date_from_fields) return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, fields.to_string_without_side_effects()); // 5. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 6. Let result be ? ISODateFromFields(fields, options). auto result = TRY(iso_date_from_fields(global_object, fields.as_object(), *options)); @@ -116,7 +116,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::year_month_from_fields) return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, fields.to_string_without_side_effects()); // 5. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 6. Let result be ? ISOYearMonthFromFields(fields, options). auto result = TRY(iso_year_month_from_fields(global_object, fields.as_object(), *options)); @@ -142,7 +142,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::month_day_from_fields) return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, fields.to_string_without_side_effects()); // 5. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 6. Let result be ? ISOMonthDayFromFields(fields, options). auto result = TRY(iso_month_day_from_fields(global_object, fields.as_object(), *options)); @@ -169,7 +169,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::date_add) auto* duration = TRY(to_temporal_duration(global_object, vm.argument(1))); // 6. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(2))); + auto const* options = TRY(get_options_object(global_object, vm.argument(2))); // 7. Let overflow be ? ToTemporalOverflow(options). auto overflow = TRY(to_temporal_overflow(global_object, options)); @@ -203,7 +203,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::date_until) auto* two = TRY(to_temporal_date(global_object, vm.argument(1))); // 6. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(2))); + auto const* options = TRY(get_options_object(global_object, vm.argument(2))); // 7. Let largestUnit be ? ToLargestTemporalUnit(options, « "hour", "minute", "second", "millisecond", "microsecond", "nanosecond" », "auto", "day"). auto largest_unit = TRY(to_largest_temporal_unit(global_object, *options, { "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv }, "auto"sv, "day"sv)); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/DurationConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/DurationConstructor.cpp index 1d8a9be0db8f..607abd6d06f1 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/DurationConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/DurationConstructor.cpp @@ -112,7 +112,7 @@ JS_DEFINE_NATIVE_FUNCTION(DurationConstructor::compare) auto* two = TRY(to_temporal_duration(global_object, vm.argument(1))); // 3. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(2))); + auto const* options = TRY(get_options_object(global_object, vm.argument(2))); // 4. Let relativeTo be ? ToRelativeTemporalObject(options). auto relative_to = TRY(to_relative_temporal_object(global_object, *options)); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp index 164a118b9f8c..57a00521aafc 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp @@ -302,7 +302,7 @@ JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::add) auto other = TRY(to_temporal_duration_record(global_object, vm.argument(0))); // 4. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 5. Let relativeTo be ? ToRelativeTemporalObject(options). auto relative_to = TRY(to_relative_temporal_object(global_object, *options)); @@ -325,7 +325,7 @@ JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::subtract) auto other = TRY(to_temporal_duration_record(global_object, vm.argument(0))); // 4. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 5. Let relativeTo be ? ToRelativeTemporalObject(options). auto relative_to = TRY(to_relative_temporal_object(global_object, *options)); @@ -583,7 +583,7 @@ JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::to_string) auto* duration = TRY(typed_this_object(global_object)); // 3. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(0))); + auto const* options = TRY(get_options_object(global_object, vm.argument(0))); // 4. Let precision be ? ToSecondsStringPrecision(options). auto precision = TRY(to_seconds_string_precision(global_object, *options)); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp index ccd6571d6862..66cd9227d72b 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp @@ -166,7 +166,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::until) auto* other = TRY(to_temporal_instant(global_object, vm.argument(0))); // 4. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 5. Let smallestUnit be ? ToSmallestTemporalUnit(options, « "year", "month", "week", "day" », "nanosecond"). auto smallest_unit = TRY(to_smallest_temporal_unit(global_object, *options, { "year"sv, "month"sv, "week"sv, "day"sv }, "nanosecond"sv)); @@ -210,7 +210,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::since) auto* other = TRY(to_temporal_instant(global_object, vm.argument(0))); // 4. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 5. Let smallestUnit be ? ToSmallestTemporalUnit(options, « "year", "month", "week", "day" », "nanosecond"). auto smallest_unit = TRY(to_smallest_temporal_unit(global_object, *options, { "year"sv, "month"sv, "week"sv, "day"sv }, "nanosecond"sv)); @@ -357,7 +357,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::to_string) auto* instant = TRY(typed_this_object(global_object)); // 3. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(0))); + auto const* options = TRY(get_options_object(global_object, vm.argument(0))); // 4. Let timeZone be ? Get(options, "timeZone"). auto time_zone = TRY(options->get(vm.names.timeZone)); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp index 0c64f7c2b769..25912f4dbf5e 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.cpp @@ -69,7 +69,7 @@ ThrowCompletionOr<PlainDate*> create_temporal_date(GlobalObject& global_object, } // 3.5.2 ToTemporalDate ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldate -ThrowCompletionOr<PlainDate*> to_temporal_date(GlobalObject& global_object, Value item, Object* options) +ThrowCompletionOr<PlainDate*> to_temporal_date(GlobalObject& global_object, Value item, Object const* options) { auto& vm = global_object.vm(); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h index 8b3095b4b6b7..383bca9a831d 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDate.h @@ -43,7 +43,7 @@ struct ISODate { }; ThrowCompletionOr<PlainDate*> create_temporal_date(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, FunctionObject const* new_target = nullptr); -ThrowCompletionOr<PlainDate*> to_temporal_date(GlobalObject&, Value item, Object* options = nullptr); +ThrowCompletionOr<PlainDate*> to_temporal_date(GlobalObject&, Value item, Object const* options = nullptr); DateDurationRecord difference_iso_date(GlobalObject&, i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2, StringView largest_unit); ThrowCompletionOr<ISODate> regulate_iso_date(GlobalObject&, double year, double month, double day, StringView overflow); bool is_valid_iso_date(i32 year, u8 month, u8 day); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp index 2c7bab921078..9439e7758ef0 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp @@ -77,7 +77,7 @@ ThrowCompletionOr<Object*> PlainDateConstructor::construct(FunctionObject& new_t JS_DEFINE_NATIVE_FUNCTION(PlainDateConstructor::from) { // 1. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); auto item = vm.argument(0); // 2. If Type(item) is Object and item has an [[InitializedTemporalDate]] internal slot, then diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp index 9286a8912307..9634e6260839 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp @@ -407,7 +407,7 @@ JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::with) auto* partial_date = TRY(prepare_partial_temporal_fields(global_object, temporal_date_like.as_object(), field_names)); // 8. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 9. Let fields be ? PrepareTemporalFields(temporalDate, fieldNames, «»). auto* fields = TRY(prepare_temporal_fields(global_object, *temporal_date, field_names, {})); @@ -453,7 +453,7 @@ JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::until) return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDifferentCalendars); // 5. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 6. Let disallowedUnits be « "hour", "minute", "second", "millisecond", "microsecond", "nanosecond" ». Vector<StringView> disallowed_units { "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv }; diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp index 5607db14ddff..9be652ee396c 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.cpp @@ -102,7 +102,7 @@ bool iso_date_time_within_limits(GlobalObject& global_object, i32 year, u8 month } // 5.5.3 InterpretTemporalDateTimeFields ( calendar, fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-interprettemporaldatetimefields -ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(GlobalObject& global_object, Object& calendar, Object& fields, Object& options) +ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(GlobalObject& global_object, Object& calendar, Object& fields, Object const& options) { // 1. Let timeResult be ? ToTemporalTimeRecord(fields). auto unregulated_time_result = TRY(to_temporal_time_record(global_object, fields)); @@ -131,7 +131,7 @@ ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(GlobalObject& } // 5.5.4 ToTemporalDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetime -ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(GlobalObject& global_object, Value item, Object* options) +ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(GlobalObject& global_object, Value item, Object const* options) { auto& vm = global_object.vm(); @@ -350,7 +350,7 @@ ISODateTime round_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, } // 5.5.11 DifferenceISODateTime ( y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1, y2, mon2, d2, h2, min2, s2, ms2, mus2, ns2, calendar, largestUnit [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-differenceisodatetime -ThrowCompletionOr<DurationRecord> difference_iso_date_time(GlobalObject& global_object, i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2, Object& calendar, StringView largest_unit, Object* options) +ThrowCompletionOr<DurationRecord> difference_iso_date_time(GlobalObject& global_object, i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2, Object& calendar, StringView largest_unit, Object const* options) { // 1. If options is not present, set options to undefined. // 2. Assert: Type(options) is Object or Undefined. diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h index 46b764ef7416..072be0710393 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTime.h @@ -65,14 +65,14 @@ struct TemporalPlainDateTime { BigInt* get_epoch_from_iso_parts(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond); bool iso_date_time_within_limits(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond); -ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(GlobalObject&, Object& calendar, Object& fields, Object& options); -ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(GlobalObject&, Value item, Object* options = nullptr); +ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(GlobalObject&, Object& calendar, Object& fields, Object const& options); +ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(GlobalObject&, Value item, Object const* options = nullptr); ISODateTime balance_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, i64 nanosecond); ThrowCompletionOr<PlainDateTime*> create_temporal_date_time(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, FunctionObject const* new_target = nullptr); ThrowCompletionOr<String> temporal_date_time_to_string(GlobalObject&, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Value calendar, Variant<StringView, u8> const& precision, StringView show_calendar); i8 compare_iso_date_time(i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2); ThrowCompletionOr<TemporalPlainDateTime> add_date_time(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Object* options); ISODateTime round_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, u64 increment, StringView unit, StringView rounding_mode, Optional<double> day_length = {}); -ThrowCompletionOr<DurationRecord> difference_iso_date_time(GlobalObject&, i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2, Object& calendar, StringView largest_unit, Object* options = nullptr); +ThrowCompletionOr<DurationRecord> difference_iso_date_time(GlobalObject&, i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2, Object& calendar, StringView largest_unit, Object const* options = nullptr); } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp index e5f6b21e4bac..8d2bef5034f9 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateTimePrototype.cpp @@ -525,7 +525,7 @@ JS_DEFINE_NATIVE_FUNCTION(PlainDateTimePrototype::until) return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDifferentCalendars); // 5. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 6. Let smallestUnit be ? ToSmallestTemporalUnit(options, « », "nanosecond"). auto smallest_unit = TRY(to_smallest_temporal_unit(global_object, *options, {}, "nanosecond"sv)); @@ -579,7 +579,7 @@ JS_DEFINE_NATIVE_FUNCTION(PlainDateTimePrototype::since) return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDifferentCalendars); // 5. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 6. Let smallestUnit be ? ToSmallestTemporalUnit(options, « », "nanosecond"). auto smallest_unit = TRY(to_smallest_temporal_unit(global_object, *options, {}, "nanosecond"sv)); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayConstructor.cpp index 91df5cfe806c..0dae13337236 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainMonthDayConstructor.cpp @@ -88,7 +88,7 @@ JS_DEFINE_NATIVE_FUNCTION(PlainMonthDayConstructor::from) auto item = vm.argument(0); // 1. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); // 2. If Type(item) is Object and item has an [[InitializedTemporalMonthDay]] internal slot, then if (item.is_object() && is<PlainMonthDay>(item.as_object())) { diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp index d84419fbcfd5..3bae3796f920 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.cpp @@ -31,7 +31,7 @@ void PlainYearMonth::visit_edges(Visitor& visitor) } // 9.5.1 ToTemporalYearMonth ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalyearmonth -ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(GlobalObject& global_object, Value item, Object* options) +ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(GlobalObject& global_object, Value item, Object const* options) { auto& vm = global_object.vm(); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h index 9835c4dc3425..77197f99bbfb 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainYearMonth.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Linus Groh <[email protected]> + * Copyright (c) 2021-2022, Linus Groh <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -39,7 +39,7 @@ struct ISOYearMonth { u8 reference_iso_day; }; -ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(GlobalObject& global_object, Value item, Object* options = nullptr); +ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(GlobalObject& global_object, Value item, Object const* options = nullptr); ThrowCompletionOr<ISOYearMonth> regulate_iso_year_month(GlobalObject&, double year, double month, StringView overflow); bool is_valid_iso_month(u8 month); bool iso_year_month_within_limits(i32 year, u8 month); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp index 80fd7391ed38..60bb3e0cd748 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp @@ -114,7 +114,7 @@ ThrowCompletionOr<BigInt const*> interpret_iso_date_time_offset(GlobalObject& gl } // 6.5.2 ToTemporalZonedDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalzoneddatetime -ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(GlobalObject& global_object, Value item, Object* options) +ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(GlobalObject& global_object, Value item, Object const* options) { auto& vm = global_object.vm(); @@ -401,7 +401,7 @@ ThrowCompletionOr<BigInt*> add_zoned_date_time(GlobalObject& global_object, BigI } // 6.5.6 DifferenceZonedDateTime ( ns1, ns2, timeZone, calendar, largestUnit [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-differencezoneddatetime -ThrowCompletionOr<DurationRecord> difference_zoned_date_time(GlobalObject& global_object, BigInt const& nanoseconds1, BigInt const& nanoseconds2, Object& time_zone, Object& calendar, StringView largest_unit, Object* options) +ThrowCompletionOr<DurationRecord> difference_zoned_date_time(GlobalObject& global_object, BigInt const& nanoseconds1, BigInt const& nanoseconds2, Object& time_zone, Object& calendar, StringView largest_unit, Object const* options) { // 1. Assert: Type(ns1) is BigInt. // 2. Assert: Type(ns2) is BigInt. diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.h b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.h index 4f8d32fd6908..e68c9f9d77c4 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.h @@ -51,11 +51,11 @@ enum class MatchBehavior { }; ThrowCompletionOr<BigInt const*> interpret_iso_date_time_offset(GlobalObject&, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, OffsetBehavior offset_behavior, double offset_nanoseconds, Value time_zone, StringView disambiguation, StringView offset_option, MatchBehavior match_behavior); -ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(GlobalObject&, Value item, Object* options = nullptr); +ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(GlobalObject&, Value item, Object const* options = nullptr); ThrowCompletionOr<ZonedDateTime*> create_temporal_zoned_date_time(GlobalObject&, BigInt const& epoch_nanoseconds, Object& time_zone, Object& calendar, FunctionObject const* new_target = nullptr); ThrowCompletionOr<String> temporal_zoned_date_time_to_string(GlobalObject&, ZonedDateTime& zoned_date_time, Variant<StringView, u8> const& precision, StringView show_calendar, StringView show_time_zone, StringView show_offset, Optional<u64> increment = {}, Optional<StringView> unit = {}, Optional<StringView> rounding_mode = {}); ThrowCompletionOr<BigInt*> add_zoned_date_time(GlobalObject&, BigInt const& epoch_nanoseconds, Value time_zone, Object& calendar, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Object* options = nullptr); -ThrowCompletionOr<DurationRecord> difference_zoned_date_time(GlobalObject&, BigInt const& nanoseconds1, BigInt const& nanoseconds2, Object& time_zone, Object& calendar, StringView largest_unit, Object* options = nullptr); +ThrowCompletionOr<DurationRecord> difference_zoned_date_time(GlobalObject&, BigInt const& nanoseconds1, BigInt const& nanoseconds2, Object& time_zone, Object& calendar, StringView largest_unit, Object const* options = nullptr); ThrowCompletionOr<NanosecondsToDaysResult> nanoseconds_to_days(GlobalObject&, Crypto::SignedBigInteger nanoseconds, Value relative_to); } diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimeConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimeConstructor.cpp index 64f16cb0d41e..1223a064b772 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimeConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimeConstructor.cpp @@ -74,7 +74,7 @@ ThrowCompletionOr<Object*> ZonedDateTimeConstructor::construct(FunctionObject& n JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimeConstructor::from) { // 1. Set options to ? GetOptionsObject(options). - auto* options = TRY(get_options_object(global_object, vm.argument(1))); + auto const* options = TRY(get_options_object(global_object, vm.argument(1))); auto item = vm.argument(0);
5c1b3ce42ef59448f641e9cc0a63e781c9f243b0
2020-04-20 20:55:50
Itamar
ak: Allow having ref counted pointers to const object
false
Allow having ref counted pointers to const object
ak
diff --git a/AK/RefCounted.h b/AK/RefCounted.h index f45320860166..12a21cc8cdd2 100644 --- a/AK/RefCounted.h +++ b/AK/RefCounted.h @@ -32,9 +32,9 @@ namespace AK { template<class T> -constexpr auto call_will_be_destroyed_if_present(T* object) -> decltype(object->will_be_destroyed(), TrueType {}) +constexpr auto call_will_be_destroyed_if_present(const T* object) -> decltype(object->will_be_destroyed(), TrueType {}) { - object->will_be_destroyed(); + const_cast<T*>(object)->will_be_destroyed(); return {}; } @@ -44,9 +44,9 @@ constexpr auto call_will_be_destroyed_if_present(...) -> FalseType } template<class T> -constexpr auto call_one_ref_left_if_present(T* object) -> decltype(object->one_ref_left(), TrueType {}) +constexpr auto call_one_ref_left_if_present(const T* object) -> decltype(object->one_ref_left(), TrueType {}) { - object->one_ref_left(); + const_cast<T*>(object)->one_ref_left(); return {}; } @@ -57,7 +57,7 @@ constexpr auto call_one_ref_left_if_present(...) -> FalseType class RefCountedBase { public: - void ref() + void ref() const { ASSERT(m_ref_count); ++m_ref_count; @@ -75,26 +75,26 @@ class RefCountedBase { ASSERT(!m_ref_count); } - void deref_base() + void deref_base() const { ASSERT(m_ref_count); --m_ref_count; } - int m_ref_count { 1 }; + mutable int m_ref_count { 1 }; }; template<typename T> class RefCounted : public RefCountedBase { public: - void unref() + void unref() const { deref_base(); if (m_ref_count == 0) { - call_will_be_destroyed_if_present(static_cast<T*>(this)); - delete static_cast<T*>(this); + call_will_be_destroyed_if_present(static_cast<const T*>(this)); + delete static_cast<const T*>(this); } else if (m_ref_count == 1) { - call_one_ref_left_if_present(static_cast<T*>(this)); + call_one_ref_left_if_present(static_cast<const T*>(this)); } } };
5331ae0e934645f09138ab4d0b9da5a93b847f3e
2021-03-27 23:53:49
Brendan Coles
base: man pages: document arguments, fix typos, use American English
false
man pages: document arguments, fix typos, use American English
base
diff --git a/Base/usr/share/man/man1/Inspector.md b/Base/usr/share/man/man1/Inspector.md index f3166147d2f5..30dd6ba86cb4 100644 --- a/Base/usr/share/man/man1/Inspector.md +++ b/Base/usr/share/man/man1/Inspector.md @@ -8,6 +8,10 @@ Inspector - Serenity process inspector $ Inspector [pid] ``` +## Arguments + +* pid: Process ID to inspect + ## Description Inspector facilitates process inspection via RPC. diff --git a/Base/usr/share/man/man1/Playground.md b/Base/usr/share/man/man1/Playground.md index fb933dfb42c2..ef633e39b57d 100644 --- a/Base/usr/share/man/man1/Playground.md +++ b/Base/usr/share/man/man1/Playground.md @@ -8,6 +8,10 @@ Playground - GUI Markup Language (GML) editor $ Playground [file] ``` +## Arguments + +* file: Path of GML file to load + ## Description Playground facilitates development of graphical user interfaces (GUI) diff --git a/Base/usr/share/man/man1/Profiler.md b/Base/usr/share/man/man1/Profiler.md index 8cdfb1e4d1e8..d6f2c6e96e75 100644 --- a/Base/usr/share/man/man1/Profiler.md +++ b/Base/usr/share/man/man1/Profiler.md @@ -5,7 +5,7 @@ Profiler - Serenity process profiler ## Synopsis ```**sh -$ Profiler [--pid PID] [perfcore file] +$ Profiler [--pid PID] [perfcore-file] ``` ## Description @@ -27,6 +27,10 @@ Profiler can also load performance information from previously created * `-p PID`, `--pid PID`: PID to profile +## Arguments + +* perfcore-file: Path of perfcore file to load + ## Examples Profile running Shell process: diff --git a/Base/usr/share/man/man1/Shell.md b/Base/usr/share/man/man1/Shell.md index de2a6720eaca..6ece59f952f4 100644 --- a/Base/usr/share/man/man1/Shell.md +++ b/Base/usr/share/man/man1/Shell.md @@ -25,7 +25,7 @@ The `Shell` utility does not promise POSIX `sh` interoperability. ## Options * `-c`, `--command-string`: Executes the given string as a command and exits -* `--skip-shellrc`: Skips running the initialisation file (at `~/.shellrc`) +* `--skip-shellrc`: Skips running the initialization file (at `~/.shellrc`) * `--format`: Format shell code from the given file and print the result to standard output * `-f`, `--live-formatting`: Enable live formatting of the line editor buffer (in REPL mode) diff --git a/Base/usr/share/man/man1/printf.md b/Base/usr/share/man/man1/printf.md index fe90d153677d..efe1f963cb71 100644 --- a/Base/usr/share/man/man1/printf.md +++ b/Base/usr/share/man/man1/printf.md @@ -15,7 +15,7 @@ $ printf <format> [arguments...] _format_ is similar to the C printf format string, with the following differences: - The format specifier `b` (`%b`) is not supported. - The format specifiers that require a writable pointer (e.g. `n`) are not supported. -- The format specifier `q` (`%q`) has a different behaviour, where it shall print a given string as a quoted string, which is safe to use in shell inputs. +- The format specifier `q` (`%q`) has a different behavior, where it shall print a given string as a quoted string, which is safe to use in shell inputs. - Common escape sequences are interpreted, namely the following: | escape | description | diff --git a/Base/usr/share/man/man1/xargs.md b/Base/usr/share/man/man1/xargs.md index 977b27fe5f43..79650b0bd68a 100644 --- a/Base/usr/share/man/man1/xargs.md +++ b/Base/usr/share/man/man1/xargs.md @@ -33,7 +33,7 @@ The standard input is left as-is if data is read from a file. * `-0`, `--null`: Split the items by zero bytes (null characters) instead of `delimiter` * `-d`, `--delimiter`: Set the `delimiter`, which is a newline (`\n`) by default * `-v`, `--verbose`: Display each expanded command on standard error before executing it -* `-a`, `--arg-file`: Read the items from the speified file, `-` refers to standard input and is the default +* `-a`, `--arg-file`: Read the items from the specified file, `-` refers to standard input and is the default * `-L`, `--line-limit`: Set `max-lines`, `0` means unlimited (which is the default) * `-s`, `--char-limit`: Set `max-chars`, which is `ARG_MAX` (the maximum command size supported by the system) by default diff --git a/Base/usr/share/man/man5/Shell.md b/Base/usr/share/man/man5/Shell.md index 896ddba8e694..b8a98bcc329e 100644 --- a/Base/usr/share/man/man5/Shell.md +++ b/Base/usr/share/man/man5/Shell.md @@ -16,7 +16,7 @@ The shell operates according to the following general steps: * Should a command be executed, the shell applies the redirections, and executes the command with the flattened argument list * Should a command need waiting, the shell shall wait for the command to finish, and continue execution -Any text below is superceded by the formal grammar defined in the _formal grammar_ section. +Any text below is superseded by the formal grammar defined in the _formal grammar_ section. ## General Token Recognition @@ -172,7 +172,7 @@ Any bareword starting with a tilde (`~`) and spanning up to the first path separ ### Evaluate Evaluate expressions take the general form of a dollar sign (`$`) followed by some _expression_, which is evaluated by the rules below. - Should the _expression_ be a string, it shall be evaluated as a dynamic variable lookup by first evaluating the string, and then looking up the given variable. -- Should the _expression_ be a list or a command, it shall be converted to a command, whose output (from the standard output) shall be captured, and split to a list with the shell local variable `IFS` (or the default splitter `\n` (newline, 0x0a)). It should be noted that the shell option `inline_exec_keep_empty_segments` will determine whether empty segments in the split list shall be preserved when this expression is evaluated, this behaviour is disabled by default. +- Should the _expression_ be a list or a command, it shall be converted to a command, whose output (from the standard output) shall be captured, and split to a list with the shell local variable `IFS` (or the default splitter `\n` (newline, 0x0a)). It should be noted that the shell option `inline_exec_keep_empty_segments` will determine whether empty segments in the split list shall be preserved when this expression is evaluated, this behavior is disabled by default. ## Commands @@ -271,7 +271,7 @@ $ for index i x in * { echo file at index $i is named $x } ##### Infinite Loops Infinite loops (as denoted by the keyword `loop`) can be used to repeat a block until the block runs `break`, or the loop terminates by external sources (interrupts, program exit, and terminating signals). -The behaviour regarding SIGINT and other signals is the same as for loops (mentioned above). +The behavior regarding SIGINT and other signals is the same as for loops (mentioned above). ###### Examples ```sh @@ -348,7 +348,7 @@ match "$(make_some_value)" { ``` ### History Event Designators -History expansion may be utilised to reuse previously typed words or commands. +History expansion may be utilized to reuse previously typed words or commands. Such expressions are of the general form `!<event_designator>(:<word_designator>)`, where `event_designator` would select an entry in the shell history, and `word_designator` would select a word (or a range of words) from that entry. | Event designator | effect | diff --git a/Base/usr/share/man/man7/Shell-vars.md b/Base/usr/share/man/man7/Shell-vars.md index 5c46d90fa59b..82e4153edf25 100644 --- a/Base/usr/share/man/man7/Shell-vars.md +++ b/Base/usr/share/man/man7/Shell-vars.md @@ -4,10 +4,10 @@ Shell Variables - Special local and environment variables used by the Shell ## Description -The Shell uses various variables to allow for customisations of certain behavioural or visual things. +The Shell uses various variables to allow for customisations of certain behavioral or visual things. Such variables can be changed or set by the user to tweak how the shell presents things. -## Behavioural +## Behavioral 1. Output interpretations @@ -23,7 +23,7 @@ The value of this variable is used to determine which entries are kept in the Sh - `ignorespace`: Entries starting with one or more space characters are ignored - `ignoredups`: Consecutive duplicate entries are ignored -- `ignoreboth`: The behaviour of `ignorespace` and `ignoredups` is combined +- `ignoreboth`: The behavior of `ignorespace` and `ignoredups` is combined - If the variable is unset (this is the default) or has any other value than the above, no entries will be excluded from history. Note: This variable is respected by every program using `Line::Editor`, e.g. [`js`(1)](../man1/js.md).
d522a6fe4c6dae3d36ca7f77c957be7073b27d9c
2019-08-26 21:40:07
Andreas Kling
windowserver: Improved look of checkable menu items
false
Improved look of checkable menu items
windowserver
diff --git a/Servers/WindowServer/WSMenu.cpp b/Servers/WindowServer/WSMenu.cpp index a4c15219f74a..cc9bb91e194f 100644 --- a/Servers/WindowServer/WSMenu.cpp +++ b/Servers/WindowServer/WSMenu.cpp @@ -124,6 +124,10 @@ void WSMenu::draw() if (!s_checked_bitmap) s_checked_bitmap = &CharacterBitmap::create_from_ascii(s_checked_bitmap_data, s_checked_bitmap_width, s_checked_bitmap_height).leak_ref(); + bool has_checkable_items = false; + for (auto& item : m_items) + has_checkable_items = has_checkable_items | item.is_checkable(); + for (auto& item : m_items) { if (item.type() == WSMenuItem::Text) { Color text_color = Color::Black; @@ -135,13 +139,17 @@ void WSMenu::draw() text_color = Color::MidGray; Rect text_rect = item.rect().translated(left_padding(), 0); if (item.is_checkable()) { + Rect checkmark_rect { text_rect.location().x(), 0, s_checked_bitmap_width, s_checked_bitmap_height }; + checkmark_rect.center_vertically_within(text_rect); + Rect checkbox_rect = checkmark_rect.inflated(4, 4); + painter.fill_rect(checkbox_rect, Color::White); + StylePainter::paint_frame(painter, checkbox_rect, FrameShape::Container, FrameShadow::Sunken, 2); if (item.is_checked()) { - Rect checkmark_rect { text_rect.location().x(), 0, s_checked_bitmap_width, s_checked_bitmap_height }; - checkmark_rect.center_vertically_within(text_rect); painter.draw_bitmap(checkmark_rect.location(), *s_checked_bitmap, Color::Black); } - text_rect.move_by(s_checked_bitmap_width + s_checked_bitmap_padding, 0); } + if (has_checkable_items) + text_rect.move_by(s_checked_bitmap_width + s_checked_bitmap_padding, 0); painter.draw_text(text_rect, item.text(), TextAlignment::CenterLeft, text_color); if (!item.shortcut_text().is_empty()) { painter.draw_text(item.rect().translated(-right_padding(), 0), item.shortcut_text(), TextAlignment::CenterRight, text_color);
97b5aa56da77fd8943651bec7e245adf3544c023
2023-02-18 05:22:47
Kenneth Myhra
libweb: Make factory method of HTML::ErrorEvent fallible
false
Make factory method of HTML::ErrorEvent fallible
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/ErrorEvent.cpp b/Userland/Libraries/LibWeb/HTML/ErrorEvent.cpp index 81b3cb061896..dd5062f22ed1 100644 --- a/Userland/Libraries/LibWeb/HTML/ErrorEvent.cpp +++ b/Userland/Libraries/LibWeb/HTML/ErrorEvent.cpp @@ -9,12 +9,12 @@ namespace Web::HTML { -ErrorEvent* ErrorEvent::create(JS::Realm& realm, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init) +WebIDL::ExceptionOr<JS::NonnullGCPtr<ErrorEvent>> ErrorEvent::create(JS::Realm& realm, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init) { - return realm.heap().allocate<ErrorEvent>(realm, realm, event_name, event_init).release_allocated_value_but_fixme_should_propagate_errors(); + return MUST_OR_THROW_OOM(realm.heap().allocate<ErrorEvent>(realm, realm, event_name, event_init)); } -ErrorEvent* ErrorEvent::construct_impl(JS::Realm& realm, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init) +WebIDL::ExceptionOr<JS::NonnullGCPtr<ErrorEvent>> ErrorEvent::construct_impl(JS::Realm& realm, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init) { return create(realm, event_name, event_init); } diff --git a/Userland/Libraries/LibWeb/HTML/ErrorEvent.h b/Userland/Libraries/LibWeb/HTML/ErrorEvent.h index ef8d2d6cdc33..7af56154f363 100644 --- a/Userland/Libraries/LibWeb/HTML/ErrorEvent.h +++ b/Userland/Libraries/LibWeb/HTML/ErrorEvent.h @@ -24,8 +24,8 @@ class ErrorEvent final : public DOM::Event { WEB_PLATFORM_OBJECT(ErrorEvent, DOM::Event); public: - static ErrorEvent* create(JS::Realm&, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init = {}); - static ErrorEvent* construct_impl(JS::Realm&, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<ErrorEvent>> create(JS::Realm&, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init = {}); + static WebIDL::ExceptionOr<JS::NonnullGCPtr<ErrorEvent>> construct_impl(JS::Realm&, DeprecatedFlyString const& event_name, ErrorEventInit const& event_init); virtual ~ErrorEvent() override;
9bf2a7c7e5db5613b494a8cd8cb47b6aa9c3e7f6
2022-11-26 07:11:21
Andrew Kaster
meta: Use proper versions in is_compiler_supported check in serenity.sh
false
Use proper versions in is_compiler_supported check in serenity.sh
meta
diff --git a/Meta/serenity.sh b/Meta/serenity.sh index 63ce4cbfcde1..2d1dce6b6a42 100755 --- a/Meta/serenity.sh +++ b/Meta/serenity.sh @@ -156,9 +156,11 @@ is_supported_compiler() { if $COMPILER --version 2>&1 | grep "Apple clang" >/dev/null; then return 1 elif $COMPILER --version 2>&1 | grep "clang" >/dev/null; then - [ "$MAJOR_VERSION" -gt 12 ] && return 0 + # Clang version check + [ "$MAJOR_VERSION" -ge 13 ] && return 0 else - [ "$MAJOR_VERSION" -gt 10 ] && return 0 + # GCC version check + [ "$MAJOR_VERSION" -ge 12 ] && return 0 fi return 1 }
0279fb4dd37759699c5dc6b570166183a77302e0
2021-09-08 21:47:07
Idan Horowitz
ak: Add key getter to IntrusiveRedBlackTreeNode
false
Add key getter to IntrusiveRedBlackTreeNode
ak
diff --git a/AK/IntrusiveRedBlackTree.h b/AK/IntrusiveRedBlackTree.h index 8d372b30e747..6190f6b27a5c 100644 --- a/AK/IntrusiveRedBlackTree.h +++ b/AK/IntrusiveRedBlackTree.h @@ -52,7 +52,7 @@ class IntrusiveRedBlackTree : public BaseRedBlackTree<K> { { auto& node = value.*member; VERIFY(!node.m_in_tree); - node.key = key; + static_cast<typename BaseTree::Node&>(node).key = key; BaseTree::insert(&node); if constexpr (!TreeNode::IsRaw) node.m_self.reference = &value; // Note: Self-reference ensures that the object will keep a ref to itself when the Container is a smart pointer. @@ -176,6 +176,11 @@ class IntrusiveRedBlackTreeNode : public BaseRedBlackTree<K>::Node { return m_in_tree; } + [[nodiscard]] K key() const + { + return BaseRedBlackTree<K>::Node::key; + } + static constexpr bool IsRaw = IsPointer<Container>; #ifndef __clang__
3fa16dfae24bfd7678fd3dcd3873a595c5014238
2019-10-22 00:03:47
Andreas Kling
hackstudio: "Go to line" was mixed up about 0/1-based line numbers
false
"Go to line" was mixed up about 0/1-based line numbers
hackstudio
diff --git a/DevTools/HackStudio/main.cpp b/DevTools/HackStudio/main.cpp index c3b2e95b556d..f77f16ba4e44 100644 --- a/DevTools/HackStudio/main.cpp +++ b/DevTools/HackStudio/main.cpp @@ -75,7 +75,7 @@ int main(int argc, char** argv) bool ok; auto line_number = input_box->text_value().to_uint(ok); if (ok) { - text_editor->set_cursor(line_number, 0); + text_editor->set_cursor(line_number - 1, 0); } } }, text_editor));
f211028252f77e5a0462617f609131a1822026f8
2022-11-06 07:17:37
Timothy Flynn
libjs: Change ToLocalTime to use epoch nanoseconds
false
Change ToLocalTime to use epoch nanoseconds
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp index 22643b6dc29e..9ead06da5bbb 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp +++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.cpp @@ -21,6 +21,8 @@ namespace JS::Intl { +static Crypto::SignedBigInteger const s_one_million_bigint { 1'000'000 }; + // 11 DateTimeFormat Objects, https://tc39.es/ecma402/#datetimeformat-objects DateTimeFormat::DateTimeFormat(Object& prototype) : Object(prototype) @@ -591,8 +593,9 @@ ThrowCompletionOr<Vector<PatternPartition>> format_date_time_pattern(VM& vm, Dat number_format3 = TRY(construct_number_format(number_format_options3)); } - // 13. Let tm be ToLocalTime(x, dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]). - auto local_time = TRY(to_local_time(vm, time, date_time_format.calendar(), date_time_format.time_zone())); + // 13. Let tm be ToLocalTime(ℤ(ℝ(x) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]). + auto time_bigint = Crypto::SignedBigInteger { time }.multiplied_by(s_one_million_bigint); + auto local_time = TRY(to_local_time(vm, time_bigint, date_time_format.calendar(), date_time_format.time_zone())); // 14. Let result be a new empty List. Vector<PatternPartition> result; @@ -932,11 +935,13 @@ ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_date_time_range_ if (isnan(end)) return vm.throw_completion<RangeError>(ErrorType::IntlInvalidTime); - // 5. Let tm1 be ToLocalTime(x, dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]). - auto start_local_time = TRY(to_local_time(vm, start, date_time_format.calendar(), date_time_format.time_zone())); + // 5. Let tm1 be ToLocalTime(ℤ(ℝ(x) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]). + auto start_bigint = Crypto::SignedBigInteger { start }.multiplied_by(s_one_million_bigint); + auto start_local_time = TRY(to_local_time(vm, start_bigint, date_time_format.calendar(), date_time_format.time_zone())); - // 6. Let tm2 be ToLocalTime(y, dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]). - auto end_local_time = TRY(to_local_time(vm, end, date_time_format.calendar(), date_time_format.time_zone())); + // 6. Let tm2 be ToLocalTime(ℤ(ℝ(y) × 10^6), dateTimeFormat.[[Calendar]], dateTimeFormat.[[TimeZone]]). + auto end_bigint = Crypto::SignedBigInteger { end }.multiplied_by(s_one_million_bigint); + auto end_local_time = TRY(to_local_time(vm, end_bigint, date_time_format.calendar(), date_time_format.time_zone())); // 7. Let rangePatterns be dateTimeFormat.[[RangePatterns]]. auto range_patterns = date_time_format.range_patterns(); @@ -1197,50 +1202,55 @@ ThrowCompletionOr<Array*> format_date_time_range_to_parts(VM& vm, DateTimeFormat return result; } -// 11.5.13 ToLocalTime ( t, calendar, timeZone ), https://tc39.es/ecma402/#sec-tolocaltime -ThrowCompletionOr<LocalTime> to_local_time(VM& vm, double time, StringView calendar, StringView time_zone) +// 11.5.13 ToLocalTime ( epochNs, calendar, timeZone ), https://tc39.es/ecma402/#sec-tolocaltime +ThrowCompletionOr<LocalTime> to_local_time(VM& vm, Crypto::SignedBigInteger const& epoch_ns, StringView calendar, StringView time_zone) { - // 1. Assert: Type(t) is Number. + // 1. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(timeZone, epochNs). + auto offset_ns = get_named_time_zone_offset_nanoseconds(time_zone, epoch_ns); - // 2. If calendar is "gregory", then - if (calendar == "gregory"sv) { - // a. Let timeZoneOffset be the value calculated according to LocalTZA(t, true) where the local time zone is replaced with timezone timeZone. - double time_zone_offset = local_tza(time, true, time_zone); + // NOTE: Unlike the spec, we still perform the below computations with BigInts until we are ready + // to divide the number by 10^6. The spec expects an MV here. If we try to use i64, we will + // overflow; if we try to use a double, we lose quite a bit of accuracy. - // b. Let tz be the time value t + timeZoneOffset. - double zoned_time = time + time_zone_offset; + // 2. Let tz be ℝ(epochNs) + offsetNs. + auto zoned_time_ns = epoch_ns.plus(Crypto::SignedBigInteger { offset_ns }); + + // 3. If calendar is "gregory", then + if (calendar == "gregory"sv) { + auto zoned_time_ms = zoned_time_ns.divided_by(s_one_million_bigint).quotient; + auto zoned_time = floor(zoned_time_ms.to_double(Crypto::UnsignedBigInteger::RoundingMode::ECMAScriptNumberValueFor)); auto year = year_from_time(zoned_time); - // c. Return a record with fields calculated from tz according to Table 7. + // a. Return a record with fields calculated from tz according to Table 8. return LocalTime { - // WeekDay(tz) specified in es2022's Week Day. + // WeekDay(𝔽(floor(tz / 10^6))) .weekday = week_day(zoned_time), - // Let year be YearFromTime(tz) specified in es2022's Year Number. If year is less than 0, return 'BC', else, return 'AD'. + // Let year be YearFromTime(𝔽(floor(tz / 10^6))). If year < -0𝔽, return "BC", else return "AD". .era = year < 0 ? ::Locale::Era::BC : ::Locale::Era::AD, - // YearFromTime(tz) specified in es2022's Year Number. + // YearFromTime(𝔽(floor(tz / 10^6))) .year = year, // undefined. .related_year = js_undefined(), // undefined. .year_name = js_undefined(), - // MonthFromTime(tz) specified in es2022's Month Number. + // MonthFromTime(𝔽(floor(tz / 10^6))) .month = month_from_time(zoned_time), - // DateFromTime(tz) specified in es2022's Date Number. + // DateFromTime(𝔽(floor(tz / 10^6))) .day = date_from_time(zoned_time), - // HourFromTime(tz) specified in es2022's Hours, Minutes, Second, and Milliseconds. + // HourFromTime(𝔽(floor(tz / 10^6))) .hour = hour_from_time(zoned_time), - // MinFromTime(tz) specified in es2022's Hours, Minutes, Second, and Milliseconds. + // MinFromTime(𝔽(floor(tz / 10^6))) .minute = min_from_time(zoned_time), - // SecFromTime(tz) specified in es2022's Hours, Minutes, Second, and Milliseconds. + // SecFromTime(𝔽(floor(tz / 10^6))) .second = sec_from_time(zoned_time), - // msFromTime(tz) specified in es2022's Hours, Minutes, Second, and Milliseconds. + // msFromTime(𝔽(floor(tz / 10^6))) .millisecond = ms_from_time(zoned_time), }; } - // 3. Else, - // a. Return a record with the fields of Column 1 of Table 7 calculated from t for the given calendar and timeZone. The calculations should use best available information about the specified calendar and timeZone, including current and historical information about time zone offsets from UTC and daylight saving time rules. + // 4. Else, + // a. Return a record with the fields of Column 1 of Table 8 calculated from tz for the given calendar. The calculations should use best available information about the specified calendar. // FIXME: Implement this when non-Gregorian calendars are supported by LibUnicode. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Non-Gregorian calendars"sv); } diff --git a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h index fffdcdfd211d..ad56e0163426 100644 --- a/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h +++ b/Userland/Libraries/LibJS/Runtime/Intl/DateTimeFormat.h @@ -159,7 +159,7 @@ enum class OptionDefaults { Time, }; -// Table 7: Record returned by ToLocalTime, https://tc39.es/ecma402/#table-datetimeformat-tolocaltime-record +// Table 8: Record returned by ToLocalTime, https://tc39.es/ecma402/#table-datetimeformat-tolocaltime-record // Note: [[InDST]] is not included here - it is handled by LibUnicode / LibTimeZone. struct LocalTime { AK::Time time_since_epoch() const @@ -191,7 +191,7 @@ ThrowCompletionOr<Array*> format_date_time_to_parts(VM&, DateTimeFormat&, double ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_date_time_range_pattern(VM&, DateTimeFormat&, double start, double end); ThrowCompletionOr<String> format_date_time_range(VM&, DateTimeFormat&, double start, double end); ThrowCompletionOr<Array*> format_date_time_range_to_parts(VM&, DateTimeFormat&, double start, double end); -ThrowCompletionOr<LocalTime> to_local_time(VM&, double time, StringView calendar, StringView time_zone); +ThrowCompletionOr<LocalTime> to_local_time(VM&, Crypto::SignedBigInteger const& epoch_ns, StringView calendar, StringView time_zone); template<typename Callback> ThrowCompletionOr<void> for_each_calendar_field(VM& vm, ::Locale::CalendarPattern& pattern, Callback&& callback)
e73b142a97db5844d24ab881a5d23acf725ca572
2021-06-15 23:06:33
Ali Mohammad Pur
libjs: Make basic block size customizable
false
Make basic block size customizable
libjs
diff --git a/Userland/Libraries/LibJS/Bytecode/BasicBlock.cpp b/Userland/Libraries/LibJS/Bytecode/BasicBlock.cpp index b4901da98fa7..0182d4412f7d 100644 --- a/Userland/Libraries/LibJS/Bytecode/BasicBlock.cpp +++ b/Userland/Libraries/LibJS/Bytecode/BasicBlock.cpp @@ -11,18 +11,18 @@ namespace JS::Bytecode { -NonnullOwnPtr<BasicBlock> BasicBlock::create(String name) +NonnullOwnPtr<BasicBlock> BasicBlock::create(String name, size_t size) { - return adopt_own(*new BasicBlock(move(name))); + return adopt_own(*new BasicBlock(move(name), max(size, static_cast<size_t>(4 * KiB)))); } -BasicBlock::BasicBlock(String name) +BasicBlock::BasicBlock(String name, size_t size) : m_name(move(name)) { // FIXME: This is not the smartest solution ever. Find something cleverer! // The main issue we're working around here is that we don't want pointers into the bytecode stream to become invalidated // during code generation due to dynamic buffer resizing. Otherwise we could just use a Vector. - m_buffer_capacity = 4 * KiB; + m_buffer_capacity = size; m_buffer = (u8*)mmap(nullptr, m_buffer_capacity, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); VERIFY(m_buffer != MAP_FAILED); } diff --git a/Userland/Libraries/LibJS/Bytecode/BasicBlock.h b/Userland/Libraries/LibJS/Bytecode/BasicBlock.h index 08912e1a6db6..b3720c2a1539 100644 --- a/Userland/Libraries/LibJS/Bytecode/BasicBlock.h +++ b/Userland/Libraries/LibJS/Bytecode/BasicBlock.h @@ -47,13 +47,14 @@ class BasicBlock { AK_MAKE_NONCOPYABLE(BasicBlock); public: - static NonnullOwnPtr<BasicBlock> create(String name); + static NonnullOwnPtr<BasicBlock> create(String name, size_t size = 4 * KiB); ~BasicBlock(); void seal(); void dump(Executable const&) const; ReadonlyBytes instruction_stream() const { return ReadonlyBytes { m_buffer, m_buffer_size }; } + size_t size() const { return m_buffer_size; } void* next_slot() { return m_buffer + m_buffer_size; } bool can_grow(size_t additional_size) const { return m_buffer_size + additional_size <= m_buffer_capacity; } @@ -65,7 +66,7 @@ class BasicBlock { String const& name() const { return m_name; } private: - BasicBlock(String name); + BasicBlock(String name, size_t size); u8* m_buffer { nullptr }; size_t m_buffer_capacity { 0 };
7fc770cfacf865af33cdf9449bed15f8f16036b9
2021-12-10 01:58:52
Andreas Kling
libweb: Make DOM::NamedNodeMap forward its ref count to DOM::Element
false
Make DOM::NamedNodeMap forward its ref count to DOM::Element
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/NamedNodeMap.cpp b/Userland/Libraries/LibWeb/DOM/NamedNodeMap.cpp index 2fd5b711174d..fd7d50cb2835 100644 --- a/Userland/Libraries/LibWeb/DOM/NamedNodeMap.cpp +++ b/Userland/Libraries/LibWeb/DOM/NamedNodeMap.cpp @@ -11,16 +11,14 @@ namespace Web::DOM { -NonnullRefPtr<NamedNodeMap> NamedNodeMap::create(Element const& associated_element) +NonnullRefPtr<NamedNodeMap> NamedNodeMap::create(Element& associated_element) { return adopt_ref(*new NamedNodeMap(associated_element)); } -NamedNodeMap::NamedNodeMap(Element const& associated_element) - : m_associated_element(associated_element) +NamedNodeMap::NamedNodeMap(Element& associated_element) + : RefCountForwarder(associated_element) { - // Note: To avoid a reference cycle between Element, NamedNodeMap, and Attribute, do not store a - // strong reference to the associated element. } // https://dom.spec.whatwg.org/#ref-for-dfn-supported-property-indices%E2%91%A3 @@ -32,10 +30,6 @@ bool NamedNodeMap::is_supported_property_index(u32 index) const // https://dom.spec.whatwg.org/#ref-for-dfn-supported-property-names%E2%91%A0 Vector<String> NamedNodeMap::supported_property_names() const { - auto associated_element = m_associated_element.strong_ref(); - if (!associated_element) - return {}; - // 1. Let names be the qualified names of the attributes in this NamedNodeMap object’s attribute list, with duplicates omitted, in order. Vector<String> names; names.ensure_capacity(m_attributes.size()); @@ -47,7 +41,7 @@ Vector<String> NamedNodeMap::supported_property_names() const // 2. If this NamedNodeMap object’s element is in the HTML namespace and its node document is an HTML document, then for each name in names: // FIXME: Handle the second condition, assume it is an HTML document for now. - if (associated_element->namespace_uri() == Namespace::HTML) { + if (associated_element().namespace_uri() == Namespace::HTML) { // 1. Let lowercaseName be name, in ASCII lowercase. // 2. If lowercaseName is not equal to name, remove name from names. names.remove_all_matching([](auto const& name) { return name != name.to_lowercase(); }); @@ -103,16 +97,12 @@ Attribute* NamedNodeMap::get_attribute(StringView qualified_name, size_t* item_i // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name Attribute const* NamedNodeMap::get_attribute(StringView qualified_name, size_t* item_index) const { - auto associated_element = m_associated_element.strong_ref(); - if (!associated_element) - return nullptr; - if (item_index) *item_index = 0; // 1. If element is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase. // FIXME: Handle the second condition, assume it is an HTML document for now. - bool compare_as_lowercase = associated_element->namespace_uri() == Namespace::HTML; + bool compare_as_lowercase = associated_element().namespace_uri() == Namespace::HTML; // 2. Return the first attribute in element’s attribute list whose qualified name is qualifiedName; otherwise null. for (auto const& attribute : m_attributes) { @@ -134,12 +124,8 @@ Attribute const* NamedNodeMap::get_attribute(StringView qualified_name, size_t* // https://dom.spec.whatwg.org/#concept-element-attributes-set ExceptionOr<Attribute const*> NamedNodeMap::set_attribute(Attribute& attribute) { - auto associated_element = m_associated_element.strong_ref(); - if (!associated_element) - return nullptr; - // 1. If attr’s element is neither null nor element, throw an "InUseAttributeError" DOMException. - if ((attribute.owner_element() != nullptr) && (attribute.owner_element() != associated_element)) + if ((attribute.owner_element() != nullptr) && (attribute.owner_element() != &associated_element())) return InUseAttributeError::create("Attribute must not already be in use"sv); // 2. Let oldAttr be the result of getting an attribute given attr’s namespace, attr’s local name, and element. @@ -193,7 +179,7 @@ void NamedNodeMap::append_attribute(Attribute& attribute) m_attributes.append(attribute); // 3. Set attribute’s element to element. - attribute.set_owner_element(m_associated_element); + attribute.set_owner_element(&associated_element()); } // https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name diff --git a/Userland/Libraries/LibWeb/DOM/NamedNodeMap.h b/Userland/Libraries/LibWeb/DOM/NamedNodeMap.h index e6bf62ebfa22..dbcc3f68690f 100644 --- a/Userland/Libraries/LibWeb/DOM/NamedNodeMap.h +++ b/Userland/Libraries/LibWeb/DOM/NamedNodeMap.h @@ -7,6 +7,7 @@ #pragma once #include <AK/NonnullRefPtrVector.h> +#include <AK/RefCountForwarder.h> #include <AK/RefCounted.h> #include <AK/String.h> #include <AK/StringView.h> @@ -19,13 +20,13 @@ namespace Web::DOM { // https://dom.spec.whatwg.org/#interface-namednodemap class NamedNodeMap final - : public RefCounted<NamedNodeMap> + : public RefCountForwarder<Element> , public Bindings::Wrappable { public: using WrapperType = Bindings::NamedNodeMapWrapper; - static NonnullRefPtr<NamedNodeMap> create(Element const& associated_element); + static NonnullRefPtr<NamedNodeMap> create(Element& associated_element); ~NamedNodeMap() = default; bool is_supported_property_index(u32 index) const; @@ -49,9 +50,11 @@ class NamedNodeMap final Attribute const* remove_attribute(StringView qualified_name); private: - explicit NamedNodeMap(Element const& associated_element); + explicit NamedNodeMap(Element& associated_element); + + Element& associated_element() { return ref_count_target(); } + Element const& associated_element() const { return ref_count_target(); } - WeakPtr<Element> m_associated_element; NonnullRefPtrVector<Attribute> m_attributes; };
a8d96df8e0277161e7e3e5db24f265ddbdf995c3
2021-09-08 00:45:15
Nico Weber
kernel: Build MiniStdLib.cpp in aarch64 builds
false
Build MiniStdLib.cpp in aarch64 builds
kernel
diff --git a/Kernel/MiniStdLib.cpp b/Kernel/MiniStdLib.cpp index 2fc5dfbe629c..8995094f7e97 100644 --- a/Kernel/MiniStdLib.cpp +++ b/Kernel/MiniStdLib.cpp @@ -10,24 +10,25 @@ extern "C" { void* memcpy(void* dest_ptr, const void* src_ptr, size_t n) { +#if ARCH(I386) || ARCH(X86_64) size_t dest = (size_t)dest_ptr; size_t src = (size_t)src_ptr; // FIXME: Support starting at an unaligned address. if (!(dest & 0x3) && !(src & 0x3) && n >= 12) { size_t size_ts = n / sizeof(size_t); -#if ARCH(I386) +# if ARCH(I386) asm volatile( "rep movsl\n" : "=S"(src), "=D"(dest) : "S"(src), "D"(dest), "c"(size_ts) : "memory"); -#else +# else asm volatile( "rep movsq\n" : "=S"(src), "=D"(dest) : "S"(src), "D"(dest), "c"(size_ts) : "memory"); -#endif +# endif n -= size_ts * sizeof(size_t); if (n == 0) return dest_ptr; @@ -35,6 +36,12 @@ void* memcpy(void* dest_ptr, const void* src_ptr, size_t n) asm volatile( "rep movsb\n" ::"S"(src), "D"(dest), "c"(n) : "memory"); +#else + u8* pd = (u8*)dest_ptr; + u8 const* ps = (u8 const*)src_ptr; + for (; n--;) + *pd++ = *ps++; +#endif return dest_ptr; } @@ -52,24 +59,25 @@ void* memmove(void* dest, const void* src, size_t n) void* memset(void* dest_ptr, int c, size_t n) { +#if ARCH(I386) || ARCH(X86_64) size_t dest = (size_t)dest_ptr; // FIXME: Support starting at an unaligned address. if (!(dest & 0x3) && n >= 12) { size_t size_ts = n / sizeof(size_t); size_t expanded_c = explode_byte((u8)c); -#if ARCH(I386) +# if ARCH(I386) asm volatile( "rep stosl\n" : "=D"(dest) : "D"(dest), "c"(size_ts), "a"(expanded_c) : "memory"); -#else +# else asm volatile( "rep stosq\n" : "=D"(dest) : "D"(dest), "c"(size_ts), "a"(expanded_c) : "memory"); -#endif +# endif n -= size_ts * sizeof(size_t); if (n == 0) return dest_ptr; @@ -79,6 +87,11 @@ void* memset(void* dest_ptr, int c, size_t n) : "=D"(dest), "=c"(n) : "0"(dest), "1"(n), "a"(c) : "memory"); +#else + u8* pd = (u8*)dest_ptr; + for (; n--;) + *pd++ = c; +#endif return dest_ptr; } diff --git a/Kernel/Prekernel/CMakeLists.txt b/Kernel/Prekernel/CMakeLists.txt index 4c4f2a50e307..9aabfdfb569a 100644 --- a/Kernel/Prekernel/CMakeLists.txt +++ b/Kernel/Prekernel/CMakeLists.txt @@ -1,5 +1,6 @@ set(SOURCES UBSanitizer.cpp + ../MiniStdLib.cpp ) if ("${SERENITY_ARCH}" STREQUAL "aarch64") set(SOURCES @@ -14,7 +15,6 @@ else() Arch/x86/multiboot.S # FIXME: Eventually, some of these should build on aarch64 too. init.cpp - ../MiniStdLib.cpp ../../Userland/Libraries/LibELF/Relocation.cpp ) endif()
e9d2f9a95e91b188a8d062177c1488c21249f0b0
2022-09-14 20:47:19
Jelle Raaijmakers
libsoftgpu: Use `memcpy` instead of a loop to blit the color buffer
false
Use `memcpy` instead of a loop to blit the color buffer
libsoftgpu
diff --git a/Userland/Libraries/LibSoftGPU/Buffer/Typed2DBuffer.h b/Userland/Libraries/LibSoftGPU/Buffer/Typed2DBuffer.h index f8069a19cb3f..dbbe0f3e1fca 100644 --- a/Userland/Libraries/LibSoftGPU/Buffer/Typed2DBuffer.h +++ b/Userland/Libraries/LibSoftGPU/Buffer/Typed2DBuffer.h @@ -42,10 +42,7 @@ class Typed2DBuffer final : public RefCounted<Typed2DBuffer<T>> { for (int y = target.bottom(); y >= target.top(); --y) { auto const* buffer_scanline = scanline(source_y++); auto* bitmap_scanline = bitmap.scanline(y); - - int source_x = 0; - for (int x = target.left(); x <= target.right(); ++x) - bitmap_scanline[x] = buffer_scanline[source_x++]; + memcpy(bitmap_scanline + target.left(), buffer_scanline, sizeof(u32) * target.width()); } }
c355e9692dd0fd417003d9fd42e7fcfe7f6840da
2022-12-16 14:28:03
Andreas Kling
libweb: Add spec links to IDL APIs in HTMLTableElement
false
Add spec links to IDL APIs in HTMLTableElement
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp index b1c89df5d3b1..18a2a70a2713 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp @@ -73,6 +73,7 @@ void HTMLTableElement::set_caption(HTMLTableCaptionElement* caption) MUST(pre_insert(*caption, first_child())); } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-createcaption JS::NonnullGCPtr<HTMLTableCaptionElement> HTMLTableElement::create_caption() { auto maybe_caption = caption(); @@ -85,6 +86,7 @@ JS::NonnullGCPtr<HTMLTableCaptionElement> HTMLTableElement::create_caption() return static_cast<HTMLTableCaptionElement&>(*caption); } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-deletecaption void HTMLTableElement::delete_caption() { auto maybe_caption = caption(); @@ -150,6 +152,7 @@ WebIDL::ExceptionOr<void> HTMLTableElement::set_t_head(HTMLTableSectionElement* return {}; } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-createthead JS::NonnullGCPtr<HTMLTableSectionElement> HTMLTableElement::create_t_head() { auto maybe_thead = t_head(); @@ -181,6 +184,7 @@ JS::NonnullGCPtr<HTMLTableSectionElement> HTMLTableElement::create_t_head() return static_cast<HTMLTableSectionElement&>(*thead); } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-deletethead void HTMLTableElement::delete_t_head() { auto maybe_thead = t_head(); @@ -224,6 +228,7 @@ WebIDL::ExceptionOr<void> HTMLTableElement::set_t_foot(HTMLTableSectionElement* return {}; } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-createtfoot JS::NonnullGCPtr<HTMLTableSectionElement> HTMLTableElement::create_t_foot() { auto maybe_tfoot = t_foot(); @@ -235,6 +240,7 @@ JS::NonnullGCPtr<HTMLTableSectionElement> HTMLTableElement::create_t_foot() return static_cast<HTMLTableSectionElement&>(*tfoot); } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-deletetfoot void HTMLTableElement::delete_t_foot() { auto maybe_tfoot = t_foot(); @@ -256,6 +262,7 @@ JS::NonnullGCPtr<DOM::HTMLCollection> HTMLTableElement::t_bodies() return *m_t_bodies; } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-createtbody JS::NonnullGCPtr<HTMLTableSectionElement> HTMLTableElement::create_t_body() { auto tbody = DOM::create_element(document(), TagNames::tbody, Namespace::HTML); @@ -312,6 +319,7 @@ JS::NonnullGCPtr<DOM::HTMLCollection> HTMLTableElement::rows() return *m_rows; } +// https://html.spec.whatwg.org/multipage/tables.html#dom-table-insertrow WebIDL::ExceptionOr<JS::NonnullGCPtr<HTMLTableRowElement>> HTMLTableElement::insert_row(long index) { auto rows = this->rows();
c6dd8a1f66651e30993c8dda8bd9b2bb9ea98b18
2022-02-21 21:01:45
Adam Hodgen
libweb: Implement `Node.nodeValue` DOM attribute
false
Implement `Node.nodeValue` DOM attribute
libweb
diff --git a/Userland/Libraries/LibWeb/DOM/Node.cpp b/Userland/Libraries/LibWeb/DOM/Node.cpp index d4c5ab747587..dff49806149a 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.cpp +++ b/Userland/Libraries/LibWeb/DOM/Node.cpp @@ -145,6 +145,32 @@ void Node::set_text_content(String const& content) set_needs_style_update(true); } +// https://dom.spec.whatwg.org/#dom-node-nodevalue +String Node::node_value() const +{ + if (is<Attribute>(this)) { + return verify_cast<Attribute>(this)->value(); + } + if (is<CharacterData>(this)) { + return verify_cast<CharacterData>(this)->data(); + } + + return {}; +} + +// https://dom.spec.whatwg.org/#ref-for-dom-node-nodevalue%E2%91%A0 +void Node::set_node_value(const String& value) +{ + + if (is<Attribute>(this)) { + verify_cast<Attribute>(this)->set_value(value); + } else if (is<CharacterData>(this)) { + verify_cast<CharacterData>(this)->set_data(value); + } + + // Otherwise: Do nothing. +} + void Node::invalidate_style() { for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) { diff --git a/Userland/Libraries/LibWeb/DOM/Node.h b/Userland/Libraries/LibWeb/DOM/Node.h index d5076f228ab1..77ebef33f6fd 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.h +++ b/Userland/Libraries/LibWeb/DOM/Node.h @@ -111,6 +111,9 @@ class Node String text_content() const; void set_text_content(String const&); + String node_value() const; + void set_node_value(String const&); + Document& document() { return *m_document; } const Document& document() const { return *m_document; } diff --git a/Userland/Libraries/LibWeb/DOM/Node.idl b/Userland/Libraries/LibWeb/DOM/Node.idl index a25bfb6d81a3..40705aa025f2 100644 --- a/Userland/Libraries/LibWeb/DOM/Node.idl +++ b/Userland/Libraries/LibWeb/DOM/Node.idl @@ -19,6 +19,7 @@ interface Node : EventTarget { readonly attribute Document? ownerDocument; Node getRootNode(optional GetRootNodeOptions options = {}); + [CEReactions] attribute DOMString? nodeValue; // FIXME: [LegacyNullToEmptyString] is not allowed on nullable types as per the Web IDL spec. // However, we only apply it to setters, so this works as a stop gap. // Replace this with something like a special cased [LegacyNullToEmptyString].
949bffdc933a5e992c7ae09fa7d2031abd343276
2020-06-29 21:24:54
Jack Karamanian
libjs: Define the "constructor" property on ScriptFunction's prototype
false
Define the "constructor" property on ScriptFunction's prototype
libjs
diff --git a/Libraries/LibJS/Runtime/ScriptFunction.cpp b/Libraries/LibJS/Runtime/ScriptFunction.cpp index 650d7937da30..11fa9c5da0ed 100644 --- a/Libraries/LibJS/Runtime/ScriptFunction.cpp +++ b/Libraries/LibJS/Runtime/ScriptFunction.cpp @@ -66,8 +66,11 @@ ScriptFunction::ScriptFunction(GlobalObject& global_object, const FlyString& nam void ScriptFunction::initialize(Interpreter& interpreter, GlobalObject& global_object) { Function::initialize(interpreter, global_object); - if (!m_is_arrow_function) - define_property("prototype", Object::create_empty(interpreter, global_object), 0); + if (!is_arrow_function) { + Object* prototype = Object::create_empty(interpreter(), interpreter().global_object()); + prototype->define_property("constructor", this, Attribute::Writable | Attribute::Configurable); + define_property("prototype", prototype, 0); + } define_native_property("length", length_getter, nullptr, Attribute::Configurable); define_native_property("name", name_getter, nullptr, Attribute::Configurable); } diff --git a/Libraries/LibJS/Tests/constructor-basic.js b/Libraries/LibJS/Tests/constructor-basic.js index 9e2e1233ea46..08eb97739d3a 100644 --- a/Libraries/LibJS/Tests/constructor-basic.js +++ b/Libraries/LibJS/Tests/constructor-basic.js @@ -1,7 +1,17 @@ -function Foo() { - this.x = 123; -} +load("test-common.js"); + +try { + function Foo() { + this.x = 123; + } + + assert(Foo.prototype.constructor === Foo); -var foo = new Foo(); -if (foo.x === 123) - console.log("PASS"); + var foo = new Foo(); + assert(foo.constructor === Foo); + assert(foo.x === 123); + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}
370624bc376824c0c9d0966df62e0e1438aca08f
2020-08-16 20:14:09
Andreas Kling
meta: Actually exclude the Build/ directory from QtCreator refresh
false
Actually exclude the Build/ directory from QtCreator refresh
meta
diff --git a/Meta/refresh-serenity-qtcreator.sh b/Meta/refresh-serenity-qtcreator.sh index d8c95ed95a54..cb056335010d 100755 --- a/Meta/refresh-serenity-qtcreator.sh +++ b/Meta/refresh-serenity-qtcreator.sh @@ -11,4 +11,4 @@ fi cd "$SERENITY_ROOT" -find . \( -name Base -o -name Patches -o -name Ports -o -name Root -o -name Toolchain \) -prune -o \( -name '*.ipc' -or -name '*.cpp' -or -name '*.idl' -or -name '*.c' -or -name '*.h' -or -name '*.S' -or -name '*.css' \) -print > serenity.files +find . \( -name Base -o -name Patches -o -name Ports -o -name Root -o -name Toolchain -o -name Build \) -prune -o \( -name '*.ipc' -or -name '*.cpp' -or -name '*.idl' -or -name '*.c' -or -name '*.h' -or -name '*.S' -or -name '*.css' \) -print > serenity.files
f102b5634556471cace818fa62ed385ec5fd45b4
2021-06-23 01:19:28
davidot
libjs: Fix this_value in native setters and getters
false
Fix this_value in native setters and getters
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Object.cpp b/Userland/Libraries/LibJS/Runtime/Object.cpp index 01db33c21c09..e21f067991ac 100644 --- a/Userland/Libraries/LibJS/Runtime/Object.cpp +++ b/Userland/Libraries/LibJS/Runtime/Object.cpp @@ -278,7 +278,7 @@ Value Object::get_own_property(const PropertyName& property_name, Value receiver if (value_here.is_accessor()) return value_here.as_accessor().call_getter(receiver); if (value_here.is_native_property()) - return call_native_property_getter(value_here.as_native_property(), receiver); + return call_native_property_getter(value_here.as_native_property(), this); } return value_here; } @@ -937,9 +937,7 @@ bool Object::put_by_index(u32 property_index, Value value) return true; } if (value_here.value.is_native_property()) { - // FIXME: Why doesn't put_by_index() receive the receiver value from put()?! - auto receiver = this; - call_native_property_setter(value_here.value.as_native_property(), receiver, value); + call_native_property_setter(value_here.value.as_native_property(), this, value); return true; } } @@ -976,7 +974,7 @@ bool Object::put(const PropertyName& property_name, Value value, Value receiver) return true; } if (value_here.is_native_property()) { - call_native_property_setter(value_here.as_native_property(), receiver, value); + call_native_property_setter(value_here.as_native_property(), this, value); return true; } }
4abafbbe3c5bb647e3edd48a201deef0a211d07b
2022-12-26 14:06:16
Timothy Flynn
libipc: Remove requirement that Variant types must begin with Empty
false
Remove requirement that Variant types must begin with Empty
libipc
diff --git a/Userland/Libraries/LibIPC/Encoder.h b/Userland/Libraries/LibIPC/Encoder.h index 1d1696a4a0e6..e8bc3b0606fe 100644 --- a/Userland/Libraries/LibIPC/Encoder.h +++ b/Userland/Libraries/LibIPC/Encoder.h @@ -89,12 +89,9 @@ class Encoder { return *this; } - // Note: We require any encodeable variant to have Empty as its first variant, as only possibly-empty variants can be default constructed. - // The default constructability is required by generated IPC message marshalling code. template<typename... VariantTypes> - Encoder& operator<<(AK::Variant<AK::Empty, VariantTypes...> const& variant) + Encoder& operator<<(AK::Variant<VariantTypes...> const& variant) { - // Note: This might be either u8 or size_t depending on the size of the variant; both are encodeable. *this << variant.index(); variant.visit([this](auto const& underlying_value) { *this << underlying_value; }); return *this;
976d9b32d6c49af942f6f6124b64f685381fcbbe
2023-06-13 09:39:28
MacDue
libgfx: Avoid fill_path() crashes due to rounding errors
false
Avoid fill_path() crashes due to rounding errors
libgfx
diff --git a/Userland/Libraries/LibGfx/EdgeFlagPathRasterizer.cpp b/Userland/Libraries/LibGfx/EdgeFlagPathRasterizer.cpp index 8a0e77b80be4..61f905b07103 100644 --- a/Userland/Libraries/LibGfx/EdgeFlagPathRasterizer.cpp +++ b/Userland/Libraries/LibGfx/EdgeFlagPathRasterizer.cpp @@ -5,6 +5,7 @@ */ #include <AK/Array.h> +#include <AK/Debug.h> #include <AK/IntegralMath.h> #include <AK/Types.h> #include <LibGfx/AntiAliasingPainter.h> @@ -51,14 +52,19 @@ static Vector<Detail::Edge> prepare_edges(ReadonlySpan<FloatLine> lines, unsigne if (p0.y() == p1.y()) continue; - auto dx = p1.x() - p0.x(); - auto dy = p1.y() - p0.y(); - float dxdy = float(dx) / dy; - float x = p0.x(); + auto min_y = static_cast<int>(p0.y()); + auto max_y = static_cast<int>(p1.y()); + float start_x = p0.x(); + float end_x = p1.x(); + + auto dx = end_x - start_x; + auto dy = max_y - min_y; + auto dxdy = dx / dy; + edges.unchecked_append(Detail::Edge { - x, - static_cast<int>(p0.y()), - static_cast<int>(p1.y()), + start_x, + min_y, + max_y, dxdy, winding, nullptr }); @@ -132,18 +138,32 @@ void EdgeFlagPathRasterizer<SamplesPerPixel>::fill_internal(Painter& painter, Pa max_scanline = max(max_scanline, end_scanline); } - Detail::Edge* active_edges = nullptr; - // FIXME: We could probably clip some of the egde plotting if we know it won't be shown. // Though care would have to be taken to ensure the active edges are correct at the first drawn scaline. + + auto for_each_sample = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, auto callback) { + for (int y = start_subpixel_y; y < end_subpixel_y; y++) { + int xi = static_cast<int>(edge.x + SubpixelSample::nrooks_subpixel_offsets[y]); + if (xi < 0 || xi >= (int)m_scanline.size()) { + // FIXME: For very low dxdy values, floating point error can push the sample outside the scanline. + // This does not seem to make a visible difference most of the time (and is more likely from generated + // paths, such as this 3D canvas demo: https://www.kevs3d.co.uk/dev/html5logo/). + dbgln_if(FILL_PATH_DEBUG, "fill_path: Sample out of bounds: {} not in [0, {})", xi, m_scanline.size()); + return; + } + SampleType sample = 1 << y; + callback(xi, y, sample); + edge.x += edge.dxdy; + } + }; + + Detail::Edge* active_edges = nullptr; + if (winding_rule == Painter::WindingRule::EvenOdd) { auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y) { - for (int y = start_subpixel_y; y < end_subpixel_y; y++) { - int xi = static_cast<int>(edge.x + SubpixelSample::nrooks_subpixel_offsets[y]); - SampleType sample = 1 << y; + for_each_sample(edge, start_subpixel_y, end_subpixel_y, [&](int xi, int, SampleType sample) { m_scanline[xi] ^= sample; - edge.x += edge.dxdy; - } + }); }; for (int scanline = min_scanline; scanline <= max_scanline; scanline++) { active_edges = plot_edges_for_scanline(scanline, plot_edge, active_edges); @@ -157,13 +177,10 @@ void EdgeFlagPathRasterizer<SamplesPerPixel>::fill_internal(Painter& painter, Pa m_windings.resize(m_size.width()); auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y) { - for (int y = start_subpixel_y; y < end_subpixel_y; y++) { - int xi = static_cast<int>(edge.x + SubpixelSample::nrooks_subpixel_offsets[y]); - SampleType sample = 1 << y; + for_each_sample(edge, start_subpixel_y, end_subpixel_y, [&](int xi, int y, SampleType sample) { m_scanline[xi] |= sample; m_windings[xi].counts[y] += edge.winding; - edge.x += edge.dxdy; - } + }); }; for (int scanline = min_scanline; scanline <= max_scanline; scanline++) { active_edges = plot_edges_for_scanline(scanline, plot_edge, active_edges);
18ee6e457dda39901d230be7a42b1fee3e3a78d6
2023-05-28 16:35:09
Daniel Bertalan
ci: Update `actions/cache` to v3
false
Update `actions/cache` to v3
ci
diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 575f55225270..51f2c1fc7f1c 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -83,10 +83,8 @@ jobs: message("::set-output name=libc_headers::${{ hashFiles('Userland/Libraries/LibC/**/*.h', 'Userland/Libraries/LibPthread/**/*.h', 'Toolchain/Patches/*.patch', 'Toolchain/Patches/gcc/*.patch', 'Toolchain/BuildIt.sh') }}") - name: Toolchain cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b - env: - CACHE_SKIP_SAVE: ${{ github.event_name == 'pull_request' }} + uses: actions/cache/restore@v3 + id: toolchain-cache with: path: ${{ github.workspace }}/Toolchain/Cache/ # This assumes that *ALL* LibC and LibPthread headers have an impact on the Toolchain. @@ -97,12 +95,19 @@ jobs: - name: Restore or regenerate Toolchain run: TRY_USE_LOCAL_TOOLCHAIN=y ARCH="${{ matrix.arch }}" ${{ github.workspace }}/Toolchain/BuildIt.sh + - name: Update toolchain cache + uses: actions/cache/save@v3 + # Do not waste time and storage space by updating the toolchain cache from a PR, + # as it would be discarded after being merged anyway. + if: ${{ github.event_name != 'pull_request' && !steps.toolchain-cache.outputs.cache-hit }} + with: + path: ${{ github.workspace }}/Toolchain/Cache/ + key: ${{ steps.toolchain-cache.outputs.cache-primary-key }} + - name: ccache(1) cache # Pull the ccache *after* building the toolchain, in case building the Toolchain somehow interferes. - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b - env: - CACHE_SKIP_SAVE: ${{ github.event_name == 'pull_request' }} + uses: actions/cache/restore@v3 + id: ccache with: path: ${{ github.workspace }}/.ccache # If you're here because ccache broke (it never should), increment matrix.ccache-mark. @@ -131,20 +136,17 @@ jobs: mkdir -p ${{ github.workspace }}/Build/caches/UCD mkdir -p ${{ github.workspace }}/Build/caches/CLDR - name: TimeZoneData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/TZDB key: TimeZoneData-${{ hashFiles('Meta/CMake/time_zone_data.cmake') }} - name: UnicodeData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/UCD key: UnicodeData-${{ hashFiles('Meta/CMake/unicode_data.cmake') }} - name: UnicodeLocale Cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/CLDR key: UnicodeLocale-${{ hashFiles('Meta/CMake/locale_data.cmake') }} @@ -185,6 +187,14 @@ jobs: run: cmake --build . - name: Show ccache stats after build run: ccache -s + + - name: Update ccache(1) cache + uses: actions/cache/save@v3 + if: ${{ github.event_name != 'pull_request' }} + with: + path: ${{ github.workspace }}/.ccache + key: ${{ steps.ccache.outputs.cache-primary-key }} + - name: Lint (Phase 2/2) working-directory: ${{ github.workspace }}/Meta env: diff --git a/.github/workflows/libjs-test262.yml b/.github/workflows/libjs-test262.yml index a470fe99f4ef..2569a21fe5bb 100644 --- a/.github/workflows/libjs-test262.yml +++ b/.github/workflows/libjs-test262.yml @@ -77,22 +77,19 @@ jobs: mkdir -p libjs-test262/Build/CLDR - name: TimeZoneData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/libjs-test262/Build/TZDB key: TimeZoneData-${{ hashFiles('Meta/CMake/time_zone_data.cmake') }} - name: UnicodeData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/libjs-test262/Build/UCD key: UnicodeData-${{ hashFiles('Meta/CMake/unicode_data.cmake') }} - name: UnicodeLocale cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/libjs-test262/Build/CLDR key: UnicodeLocale-${{ hashFiles('Meta/CMake/locale_data.cmake') }} diff --git a/.github/workflows/pvs-studio-static-analysis.yml b/.github/workflows/pvs-studio-static-analysis.yml index ed3a175255f0..e03afbf0bb98 100644 --- a/.github/workflows/pvs-studio-static-analysis.yml +++ b/.github/workflows/pvs-studio-static-analysis.yml @@ -46,12 +46,8 @@ jobs: message("::set-output name=libc_headers::${{ hashFiles('Userland/Libraries/LibC/**/*.h', 'Userland/Libraries/LibPthread/**/*.h', 'Toolchain/Patches/*.patch', 'Toolchain/Patches/gcc/*.patch', 'Toolchain/BuildIt.sh') }}") - name: Toolchain cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b - env: - # This job should always read the cache, never populate it. - CACHE_SKIP_SAVE: true - + # This job should always read the cache, never populate it. + uses: actions/cache/restore@v3 with: path: ${{ github.workspace }}/Toolchain/Cache/ # This assumes that *ALL* LibC and LibPthread headers have an impact on the Toolchain. @@ -70,20 +66,17 @@ jobs: mkdir -p ${{ github.workspace }}/Build/caches/CLDR - name: TimeZoneData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/TZDB key: TimeZoneData-${{ hashFiles('Meta/CMake/time_zone_data.cmake') }} - name: UnicodeData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/UCD key: UnicodeData-${{ hashFiles('Meta/CMake/unicode_data.cmake') }} - name: UnicodeLocale Cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/CLDR key: UnicodeLocale-${{ hashFiles('Meta/CMake/locale_data.cmake') }} diff --git a/.github/workflows/serenity-js-artifacts.yml b/.github/workflows/serenity-js-artifacts.yml index e6978733f662..4f4390ad15a6 100644 --- a/.github/workflows/serenity-js-artifacts.yml +++ b/.github/workflows/serenity-js-artifacts.yml @@ -60,22 +60,19 @@ jobs: mkdir -p Build/CLDR - name: TimeZoneData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/libjs-test262/Build/TZDB key: TimeZoneData-${{ hashFiles('Meta/CMake/time_zone_data.cmake') }} - name: UnicodeData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/libjs-test262/Build/UCD key: UnicodeData-${{ hashFiles('Meta/CMake/unicode_data.cmake') }} - name: UnicodeLocale cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/libjs-test262/Build/CLDR key: UnicodeLocale-${{ hashFiles('Meta/CMake/locale_data.cmake') }} diff --git a/.github/workflows/sonar-cloud-static-analysis.yml b/.github/workflows/sonar-cloud-static-analysis.yml index 80b7e59bdf07..d94b3a45b949 100644 --- a/.github/workflows/sonar-cloud-static-analysis.yml +++ b/.github/workflows/sonar-cloud-static-analysis.yml @@ -78,12 +78,8 @@ jobs: message("::set-output name=libc_headers::${{ hashFiles('Userland/Libraries/LibC/**/*.h', 'Userland/Libraries/LibPthread/**/*.h', 'Toolchain/Patches/*.patch', 'Toolchain/Patches/gcc/*.patch', 'Toolchain/BuildIt.sh') }}") - name: Toolchain cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b - env: - # This job should always read the cache, never populate it. - CACHE_SKIP_SAVE: true - + # This job should always read the cache, never populate it. + uses: actions/cache/restore@v3 with: path: ${{ github.workspace }}/Toolchain/Cache/ # This assumes that *ALL* LibC and LibPthread headers have an impact on the Toolchain. @@ -102,20 +98,17 @@ jobs: mkdir -p ${{ github.workspace }}/Build/caches/CLDR - name: TimeZoneData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/TZDB key: TimeZoneData-${{ hashFiles('Meta/CMake/time_zone_data.cmake') }} - name: UnicodeData cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/UCD key: UnicodeData-${{ hashFiles('Meta/CMake/unicode_data.cmake') }} - name: UnicodeLocale Cache - # TODO: Change the version to the released version when https://github.com/actions/cache/pull/489 (or 571) is merged. - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/CLDR key: UnicodeLocale-${{ hashFiles('Meta/CMake/locale_data.cmake') }} diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index a054a40bede5..f4e1b11bb0d1 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -37,17 +37,17 @@ jobs: mkdir -p ${{ github.workspace }}/Build/caches/UCD mkdir -p ${{ github.workspace }}/Build/caches/CLDR - name: "TimeZoneData cache" - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/TZDB key: TimeZoneData-${{ hashFiles('Meta/CMake/time_zone_data.cmake') }} - name: "UnicodeData cache" - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/UCD key: UnicodeData-${{ hashFiles('Meta/CMake/unicode_data.cmake') }} - name: "UnicodeLocale cache" - uses: actions/cache@03e00da99d75a2204924908e1cca7902cafce66b + uses: actions/cache@v3 with: path: ${{ github.workspace }}/Build/caches/CLDR key: UnicodeLocale-${{ hashFiles('Meta/CMake/locale_data.cmake') }}
fb7c7829c2a58ea55b7b0fa058d88c74738d859b
2019-03-27 06:06:33
Andreas Kling
terminal: Export a simple PATH=/bin:/usr/bin to shells.
false
Export a simple PATH=/bin:/usr/bin to shells.
terminal
diff --git a/Applications/Terminal/main.cpp b/Applications/Terminal/main.cpp index 2eb2ddc07918..8cdd1b903902 100644 --- a/Applications/Terminal/main.cpp +++ b/Applications/Terminal/main.cpp @@ -65,7 +65,7 @@ static void make_shell(int ptm_fd) exit(1); } char* args[] = { "/bin/sh", nullptr }; - char* envs[] = { "TERM=xterm", nullptr }; + char* envs[] = { "TERM=xterm", "PATH=/bin:/usr/bin", nullptr }; rc = execve("/bin/sh", args, envs); if (rc < 0) { perror("execve");
7ad8790d803002a193258d65a25452864dc214a3
2019-06-07 15:16:02
Andreas Kling
libgui: Run clang-format on everything.
false
Run clang-format on everything.
libgui
diff --git a/AK/QuickSort.h b/AK/QuickSort.h index 2d196d297702..71611ad7e335 100644 --- a/AK/QuickSort.h +++ b/AK/QuickSort.h @@ -1,5 +1,7 @@ #pragma once +#include <AK/StdLibExtras.h> + namespace AK { template<typename T> diff --git a/LibGUI/GAbstractView.cpp b/LibGUI/GAbstractView.cpp index 654566f24493..36b10818adda 100644 --- a/LibGUI/GAbstractView.cpp +++ b/LibGUI/GAbstractView.cpp @@ -1,9 +1,9 @@ +#include <Kernel/KeyCode.h> #include <LibGUI/GAbstractView.h> #include <LibGUI/GModel.h> -#include <LibGUI/GScrollBar.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GScrollBar.h> #include <LibGUI/GTextBox.h> -#include <Kernel/KeyCode.h> GAbstractView::GAbstractView(GWidget* parent) : GScrollableWidget(parent) @@ -84,7 +84,7 @@ void GAbstractView::begin_editing(const GModelIndex& index) void GAbstractView::stop_editing() { - m_edit_index = { }; + m_edit_index = {}; delete m_edit_widget; m_edit_widget = nullptr; } diff --git a/LibGUI/GAction.cpp b/LibGUI/GAction.cpp index 2eebd748a8b6..3e701d485a09 100644 --- a/LibGUI/GAction.cpp +++ b/LibGUI/GAction.cpp @@ -29,7 +29,6 @@ GAction::GAction(const StringView& text, const GShortcut& shortcut, Function<voi { } - GAction::GAction(const StringView& text, const GShortcut& shortcut, RetainPtr<GraphicsBitmap>&& icon, Function<void(GAction&)> on_activation_callback, GWidget* widget) : on_activation(move(on_activation_callback)) , m_text(text) @@ -99,10 +98,10 @@ void GAction::set_enabled(bool enabled) if (m_enabled == enabled) return; m_enabled = enabled; - for_each_toolbar_button([enabled] (GButton& button) { + for_each_toolbar_button([enabled](GButton& button) { button.set_enabled(enabled); }); - for_each_menu_item([enabled] (GMenuItem& item) { + for_each_menu_item([enabled](GMenuItem& item) { item.set_enabled(enabled); }); } @@ -112,10 +111,10 @@ void GAction::set_checked(bool checked) if (m_checked == checked) return; m_checked = checked; - for_each_toolbar_button([checked] (GButton& button) { + for_each_toolbar_button([checked](GButton& button) { button.set_checked(checked); }); - for_each_menu_item([checked] (GMenuItem& item) { + for_each_menu_item([checked](GMenuItem& item) { item.set_checked(checked); }); } diff --git a/LibGUI/GApplication.cpp b/LibGUI/GApplication.cpp index ef632b4d0ecc..072021eb4a2b 100644 --- a/LibGUI/GApplication.cpp +++ b/LibGUI/GApplication.cpp @@ -1,10 +1,10 @@ +#include <LibGUI/GAction.h> #include <LibGUI/GApplication.h> #include <LibGUI/GEventLoop.h> -#include <LibGUI/GMenuBar.h> -#include <LibGUI/GAction.h> -#include <LibGUI/GWindow.h> #include <LibGUI/GLabel.h> +#include <LibGUI/GMenuBar.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GWindow.h> #include <WindowServer/WSAPITypes.h> static GApplication* s_the; diff --git a/LibGUI/GButton.cpp b/LibGUI/GButton.cpp index ff8bc9172d3e..21b9f3904376 100644 --- a/LibGUI/GButton.cpp +++ b/LibGUI/GButton.cpp @@ -1,9 +1,9 @@ #include "GButton.h" -#include <LibGUI/GPainter.h> -#include <SharedGraphics/StylePainter.h> #include <AK/StringBuilder.h> -#include <LibGUI/GAction.h> #include <Kernel/KeyCode.h> +#include <LibGUI/GAction.h> +#include <LibGUI/GPainter.h> +#include <SharedGraphics/StylePainter.h> GButton::GButton(GWidget* parent) : GAbstractButton(parent) @@ -18,7 +18,7 @@ GButton::GButton(const StringView& text, GWidget* parent) GButton::~GButton() { if (m_action) - m_action->unregister_button({ }, *this); + m_action->unregister_button({}, *this); } void GButton::paint_event(GPaintEvent& event) @@ -67,7 +67,7 @@ void GButton::click() void GButton::set_action(GAction& action) { m_action = action.make_weak_ptr(); - action.register_button({ }, *this); + action.register_button({}, *this); set_enabled(action.is_enabled()); set_checkable(action.is_checkable()); if (action.is_checkable()) diff --git a/LibGUI/GCheckBox.cpp b/LibGUI/GCheckBox.cpp index 7be710fbb3bc..2bd5067bc93f 100644 --- a/LibGUI/GCheckBox.cpp +++ b/LibGUI/GCheckBox.cpp @@ -1,8 +1,8 @@ +#include <Kernel/KeyCode.h> #include <LibGUI/GCheckBox.h> #include <LibGUI/GPainter.h> #include <SharedGraphics/CharacterBitmap.h> #include <SharedGraphics/StylePainter.h> -#include <Kernel/KeyCode.h> static const char* s_checked_bitmap_data = { " " diff --git a/LibGUI/GClipboard.cpp b/LibGUI/GClipboard.cpp index 2c4d38b4dafc..fc02b3b6230e 100644 --- a/LibGUI/GClipboard.cpp +++ b/LibGUI/GClipboard.cpp @@ -1,7 +1,7 @@ +#include <LibC/SharedBuffer.h> #include <LibGUI/GClipboard.h> #include <LibGUI/GEventLoop.h> #include <WindowServer/WSAPITypes.h> -#include <LibC/SharedBuffer.h> GClipboard& GClipboard::the() { @@ -21,15 +21,15 @@ String GClipboard::data() const request.type = WSAPI_ClientMessage::Type::GetClipboardContents; auto response = GEventLoop::current().sync_request(request, WSAPI_ServerMessage::Type::DidGetClipboardContents); if (response.clipboard.shared_buffer_id < 0) - return { }; + return {}; auto shared_buffer = SharedBuffer::create_from_shared_buffer_id(response.clipboard.shared_buffer_id); if (!shared_buffer) { dbgprintf("GClipboard::data() failed to attach to the shared buffer\n"); - return { }; + return {}; } if (response.clipboard.contents_size > shared_buffer->size()) { dbgprintf("GClipboard::data() clipping contents size is greater than shared buffer size\n"); - return { }; + return {}; } return String((const char*)shared_buffer->data(), response.clipboard.contents_size); } diff --git a/LibGUI/GDialog.cpp b/LibGUI/GDialog.cpp index d72b73c19882..4de55f8c95f7 100644 --- a/LibGUI/GDialog.cpp +++ b/LibGUI/GDialog.cpp @@ -1,6 +1,6 @@ +#include <LibGUI/GDesktop.h> #include <LibGUI/GDialog.h> #include <LibGUI/GEventLoop.h> -#include <LibGUI/GDesktop.h> GDialog::GDialog(CObject* parent) : GWindow(parent) diff --git a/LibGUI/GDirectoryModel.cpp b/LibGUI/GDirectoryModel.cpp index e1a9c34d6649..ee5ddcd39bcc 100644 --- a/LibGUI/GDirectoryModel.cpp +++ b/LibGUI/GDirectoryModel.cpp @@ -1,15 +1,15 @@ #include "GDirectoryModel.h" -#include <dirent.h> -#include <stdio.h> -#include <unistd.h> -#include <grp.h> -#include <pwd.h> #include <AK/FileSystemPath.h> #include <AK/StringBuilder.h> -#include <SharedGraphics/GraphicsBitmap.h> -#include <LibGUI/GPainter.h> -#include <LibCore/CLock.h> #include <LibCore/CDirIterator.h> +#include <LibCore/CLock.h> +#include <LibGUI/GPainter.h> +#include <SharedGraphics/GraphicsBitmap.h> +#include <dirent.h> +#include <grp.h> +#include <pwd.h> +#include <stdio.h> +#include <unistd.h> static CLockable<HashMap<String, RetainPtr<GraphicsBitmap>>>& thumbnail_cache() { @@ -94,13 +94,20 @@ int GDirectoryModel::column_count(const GModelIndex&) const String GDirectoryModel::column_name(int column) const { switch (column) { - case Column::Icon: return ""; - case Column::Name: return "Name"; - case Column::Size: return "Size"; - case Column::Owner: return "Owner"; - case Column::Group: return "Group"; - case Column::Permissions: return "Mode"; - case Column::Inode: return "Inode"; + case Column::Icon: + return ""; + case Column::Name: + return "Name"; + case Column::Size: + return "Size"; + case Column::Owner: + return "Owner"; + case Column::Group: + return "Group"; + case Column::Permissions: + return "Mode"; + case Column::Inode: + return "Inode"; } ASSERT_NOT_REACHED(); } @@ -108,13 +115,20 @@ String GDirectoryModel::column_name(int column) const GModel::ColumnMetadata GDirectoryModel::column_metadata(int column) const { switch (column) { - case Column::Icon: return { 16, TextAlignment::Center }; - case Column::Name: return { 120, TextAlignment::CenterLeft }; - case Column::Size: return { 80, TextAlignment::CenterRight }; - case Column::Owner: return { 50, TextAlignment::CenterLeft }; - case Column::Group: return { 50, TextAlignment::CenterLeft }; - case Column::Permissions: return { 80, TextAlignment::CenterLeft }; - case Column::Inode: return { 80, TextAlignment::CenterRight }; + case Column::Icon: + return { 16, TextAlignment::Center }; + case Column::Name: + return { 120, TextAlignment::CenterLeft }; + case Column::Size: + return { 80, TextAlignment::CenterRight }; + case Column::Owner: + return { 50, TextAlignment::CenterLeft }; + case Column::Group: + return { 50, TextAlignment::CenterLeft }; + case Column::Permissions: + return { 80, TextAlignment::CenterLeft }; + case Column::Inode: + return { 80, TextAlignment::CenterRight }; } ASSERT_NOT_REACHED(); } @@ -175,8 +189,7 @@ static String permission_string(mode_t mode) mode & S_IWGRP ? 'w' : '-', mode & S_ISGID ? 's' : (mode & S_IXGRP ? 'x' : '-'), mode & S_IROTH ? 'r' : '-', - mode & S_IWOTH ? 'w' : '-' - ); + mode & S_IWOTH ? 'w' : '-'); if (mode & S_ISVTX) builder.append("t"); @@ -207,31 +220,45 @@ GVariant GDirectoryModel::data(const GModelIndex& index, Role role) const auto& entry = this->entry(index.row()); if (role == Role::Sort) { switch (index.column()) { - case Column::Icon: return entry.is_directory() ? 0 : 1; - case Column::Name: return entry.name; - case Column::Size: return (int)entry.size; - case Column::Owner: return name_for_uid(entry.uid); - case Column::Group: return name_for_gid(entry.gid); - case Column::Permissions: return permission_string(entry.mode); - case Column::Inode: return (int)entry.inode; + case Column::Icon: + return entry.is_directory() ? 0 : 1; + case Column::Name: + return entry.name; + case Column::Size: + return (int)entry.size; + case Column::Owner: + return name_for_uid(entry.uid); + case Column::Group: + return name_for_gid(entry.gid); + case Column::Permissions: + return permission_string(entry.mode); + case Column::Inode: + return (int)entry.inode; } ASSERT_NOT_REACHED(); } if (role == Role::Display) { switch (index.column()) { - case Column::Icon: return icon_for(entry); - case Column::Name: return entry.name; - case Column::Size: return (int)entry.size; - case Column::Owner: return name_for_uid(entry.uid); - case Column::Group: return name_for_gid(entry.gid); - case Column::Permissions: return permission_string(entry.mode); - case Column::Inode: return (int)entry.inode; + case Column::Icon: + return icon_for(entry); + case Column::Name: + return entry.name; + case Column::Size: + return (int)entry.size; + case Column::Owner: + return name_for_uid(entry.uid); + case Column::Group: + return name_for_gid(entry.gid); + case Column::Permissions: + return permission_string(entry.mode); + case Column::Inode: + return (int)entry.inode; } } if (role == Role::Icon) { return icon_for(entry); } - return { }; + return {}; } void GDirectoryModel::update() diff --git a/LibGUI/GEventLoop.cpp b/LibGUI/GEventLoop.cpp index 127adbfeadec..ffa5b02c3be2 100644 --- a/LibGUI/GEventLoop.cpp +++ b/LibGUI/GEventLoop.cpp @@ -1,24 +1,23 @@ -#include <LibCore/CObject.h> #include "GEventLoop.h" #include "GEvent.h" #include "GWindow.h" -#include <LibGUI/GApplication.h> -#include <LibGUI/GAction.h> -#include <LibCore/CNotifier.h> -#include <LibGUI/GMenu.h> -#include <LibGUI/GDesktop.h> -#include <LibGUI/GWidget.h> -#include <LibC/unistd.h> -#include <LibC/stdio.h> +#include <LibC/errno.h> #include <LibC/fcntl.h> +#include <LibC/stdio.h> +#include <LibC/stdlib.h> #include <LibC/string.h> -#include <LibC/time.h> #include <LibC/sys/select.h> #include <LibC/sys/socket.h> #include <LibC/sys/time.h> -#include <LibC/errno.h> -#include <LibC/string.h> -#include <LibC/stdlib.h> +#include <LibC/time.h> +#include <LibC/unistd.h> +#include <LibCore/CNotifier.h> +#include <LibCore/CObject.h> +#include <LibGUI/GAction.h> +#include <LibGUI/GApplication.h> +#include <LibGUI/GDesktop.h> +#include <LibGUI/GMenu.h> +#include <LibGUI/GWidget.h> #include <sys/uio.h> //#define GEVENTLOOP_DEBUG @@ -156,20 +155,42 @@ void GEventLoop::handle_mouse_event(const WSAPI_ServerMessage& event, GWindow& w #endif GMouseEvent::Type type; switch (event.type) { - case WSAPI_ServerMessage::Type::MouseMove: type = GEvent::MouseMove; break; - case WSAPI_ServerMessage::Type::MouseUp: type = GEvent::MouseUp; break; - case WSAPI_ServerMessage::Type::MouseDown: type = GEvent::MouseDown; break; - case WSAPI_ServerMessage::Type::MouseDoubleClick: type = GEvent::MouseDoubleClick; break; - case WSAPI_ServerMessage::Type::MouseWheel: type = GEvent::MouseWheel; break; - default: ASSERT_NOT_REACHED(); break; + case WSAPI_ServerMessage::Type::MouseMove: + type = GEvent::MouseMove; + break; + case WSAPI_ServerMessage::Type::MouseUp: + type = GEvent::MouseUp; + break; + case WSAPI_ServerMessage::Type::MouseDown: + type = GEvent::MouseDown; + break; + case WSAPI_ServerMessage::Type::MouseDoubleClick: + type = GEvent::MouseDoubleClick; + break; + case WSAPI_ServerMessage::Type::MouseWheel: + type = GEvent::MouseWheel; + break; + default: + ASSERT_NOT_REACHED(); + break; } GMouseButton button { GMouseButton::None }; switch (event.mouse.button) { - case WSAPI_MouseButton::NoButton: button = GMouseButton::None; break; - case WSAPI_MouseButton::Left: button = GMouseButton::Left; break; - case WSAPI_MouseButton::Right: button = GMouseButton::Right; break; - case WSAPI_MouseButton::Middle: button = GMouseButton::Middle; break; - default: ASSERT_NOT_REACHED(); break; + case WSAPI_MouseButton::NoButton: + button = GMouseButton::None; + break; + case WSAPI_MouseButton::Left: + button = GMouseButton::Left; + break; + case WSAPI_MouseButton::Right: + button = GMouseButton::Right; + break; + case WSAPI_MouseButton::Middle: + button = GMouseButton::Middle; + break; + default: + ASSERT_NOT_REACHED(); + break; } post_event(window, make<GMouseEvent>(type, event.mouse.position, event.mouse.buttons, button, event.mouse.modifiers, event.mouse.wheel_delta)); } diff --git a/LibGUI/GFilePicker.cpp b/LibGUI/GFilePicker.cpp index 76587d9223a0..a6382cd6951f 100644 --- a/LibGUI/GFilePicker.cpp +++ b/LibGUI/GFilePicker.cpp @@ -57,19 +57,19 @@ GFilePicker::GFilePicker(const StringView& path, CObject* parent) clear_preview(); }; - auto open_parent_directory_action = GAction::create("Open parent directory", { Mod_Alt, Key_Up }, GraphicsBitmap::load_from_file("/res/icons/16x16/open-parent-directory.png"), [this] (const GAction&) { + auto open_parent_directory_action = GAction::create("Open parent directory", { Mod_Alt, Key_Up }, GraphicsBitmap::load_from_file("/res/icons/16x16/open-parent-directory.png"), [this](const GAction&) { m_model->open(String::format("%s/..", m_model->path().characters())); clear_preview(); }); toolbar->add_action(*open_parent_directory_action); - auto mkdir_action = GAction::create("New directory...", GraphicsBitmap::load_from_file("/res/icons/16x16/mkdir.png"), [this] (const GAction&) { + auto mkdir_action = GAction::create("New directory...", GraphicsBitmap::load_from_file("/res/icons/16x16/mkdir.png"), [this](const GAction&) { GInputBox input_box("Enter name:", "New directory", this); if (input_box.exec() == GInputBox::ExecOK && !input_box.text_value().is_empty()) { auto new_dir_path = FileSystemPath(String::format("%s/%s", - m_model->path().characters(), - input_box.text_value().characters() - )).string(); + m_model->path().characters(), + input_box.text_value().characters())) + .string(); int rc = mkdir(new_dir_path.characters(), 0777); if (rc < 0) { GMessageBox::show(String::format("mkdir(\"%s\") failed: %s", new_dir_path.characters(), strerror(errno)), "Error", GMessageBox::Type::Error, this); @@ -96,7 +96,7 @@ GFilePicker::GFilePicker(const StringView& path, CObject* parent) filename_label->set_preferred_size({ 60, 0 }); auto* filename_textbox = new GTextBox(filename_container); - m_view->on_activation = [this, filename_textbox] (auto& index) { + m_view->on_activation = [this, filename_textbox](auto& index) { auto& filter_model = (GSortingProxyModel&)*m_view->model(); auto local_index = filter_model.map_to_target(index); const GDirectoryModel::Entry& entry = m_model->entry(local_index.row()); @@ -125,7 +125,7 @@ GFilePicker::GFilePicker(const StringView& path, CObject* parent) cancel_button->set_size_policy(SizePolicy::Fixed, SizePolicy::Fill); cancel_button->set_preferred_size({ 80, 0 }); cancel_button->set_text("Cancel"); - cancel_button->on_click = [this] (auto&) { + cancel_button->on_click = [this](auto&) { done(ExecCancel); }; @@ -133,7 +133,7 @@ GFilePicker::GFilePicker(const StringView& path, CObject* parent) ok_button->set_size_policy(SizePolicy::Fixed, SizePolicy::Fill); ok_button->set_preferred_size({ 80, 0 }); ok_button->set_text("OK"); - ok_button->on_click = [this, filename_textbox] (auto&) { + ok_button->on_click = [this, filename_textbox](auto&) { FileSystemPath path(String::format("%s/%s", m_model->path().characters(), filename_textbox->text().characters())); m_selected_file = path; done(ExecOK); diff --git a/LibGUI/GFileSystemModel.cpp b/LibGUI/GFileSystemModel.cpp index d56fd4777c66..d39a6ef67c00 100644 --- a/LibGUI/GFileSystemModel.cpp +++ b/LibGUI/GFileSystemModel.cpp @@ -1,17 +1,22 @@ -#include <LibGUI/GFileSystemModel.h> -#include <LibCore/CDirIterator.h> #include <AK/FileSystemPath.h> #include <AK/StringBuilder.h> -#include <sys/stat.h> +#include <LibCore/CDirIterator.h> +#include <LibGUI/GFileSystemModel.h> #include <dirent.h> -#include <unistd.h> #include <stdio.h> +#include <sys/stat.h> +#include <unistd.h> struct GFileSystemModel::Node { String name; Node* parent { nullptr }; Vector<Node*> children; - enum Type { Unknown, Directory, File }; + enum Type + { + Unknown, + Directory, + File + }; Type type { Unknown }; bool has_traversed { false }; @@ -111,15 +116,15 @@ GModelIndex GFileSystemModel::index(const StringView& path) const } } if (!found) - return { }; + return {}; } - return { }; + return {}; } String GFileSystemModel::path(const GModelIndex& index) const { if (!index.is_valid()) - return { }; + return {}; auto& node = *(Node*)index.internal_data(); node.reify_if_needed(*this); return node.full_path(*this); @@ -172,11 +177,11 @@ GModelIndex GFileSystemModel::index(int row, int column, const GModelIndex& pare GModelIndex GFileSystemModel::parent_index(const GModelIndex& index) const { if (!index.is_valid()) - return { }; + return {}; auto& node = *(const Node*)index.internal_data(); if (!node.parent) { ASSERT(&node == m_root); - return { }; + return {}; } return node.parent->index(*this); } @@ -184,7 +189,7 @@ GModelIndex GFileSystemModel::parent_index(const GModelIndex& index) const GVariant GFileSystemModel::data(const GModelIndex& index, Role role) const { if (!index.is_valid()) - return { }; + return {}; auto& node = *(const Node*)index.internal_data(); if (role == GModel::Role::Display) return node.name; @@ -196,7 +201,7 @@ GVariant GFileSystemModel::data(const GModelIndex& index, Role role) const } return m_file_icon; } - return { }; + return {}; } int GFileSystemModel::column_count(const GModelIndex&) const diff --git a/LibGUI/GFontDatabase.cpp b/LibGUI/GFontDatabase.cpp index 7359df09948f..b676c7101669 100644 --- a/LibGUI/GFontDatabase.cpp +++ b/LibGUI/GFontDatabase.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GFontDatabase.h> #include <LibCore/CDirIterator.h> +#include <LibGUI/GFontDatabase.h> #include <SharedGraphics/Font.h> #include <dirent.h> #include <stdio.h> diff --git a/LibGUI/GFrame.cpp b/LibGUI/GFrame.cpp index 8048ce779147..418fe404924b 100644 --- a/LibGUI/GFrame.cpp +++ b/LibGUI/GFrame.cpp @@ -1,6 +1,6 @@ #include <LibGUI/GFrame.h> -#include <SharedGraphics/StylePainter.h> #include <LibGUI/GPainter.h> +#include <SharedGraphics/StylePainter.h> GFrame::GFrame(GWidget* parent) : GWidget(parent) diff --git a/LibGUI/GInputBox.cpp b/LibGUI/GInputBox.cpp index 9474f9161719..089003dbb994 100644 --- a/LibGUI/GInputBox.cpp +++ b/LibGUI/GInputBox.cpp @@ -1,7 +1,7 @@ -#include <LibGUI/GInputBox.h> #include <LibGUI/GBoxLayout.h> -#include <LibGUI/GLabel.h> #include <LibGUI/GButton.h> +#include <LibGUI/GInputBox.h> +#include <LibGUI/GLabel.h> #include <LibGUI/GTextEditor.h> #include <stdio.h> @@ -55,7 +55,7 @@ void GInputBox::build() m_cancel_button->set_size_policy(SizePolicy::Fill, SizePolicy::Fixed); m_cancel_button->set_preferred_size({ 0, 20 }); m_cancel_button->set_text("Cancel"); - m_cancel_button->on_click = [this] (auto&) { + m_cancel_button->on_click = [this](auto&) { dbgprintf("GInputBox: Cancel button clicked\n"); done(ExecCancel); }; @@ -64,7 +64,7 @@ void GInputBox::build() m_ok_button->set_size_policy(SizePolicy::Fill, SizePolicy::Fixed); m_ok_button->set_preferred_size({ 0, 20 }); m_ok_button->set_text("OK"); - m_ok_button->on_click = [this] (auto&) { + m_ok_button->on_click = [this](auto&) { dbgprintf("GInputBox: OK button clicked\n"); m_text_value = m_text_editor->text(); done(ExecOK); diff --git a/LibGUI/GItemView.cpp b/LibGUI/GItemView.cpp index 71b0791f911b..d5d9af0a6c10 100644 --- a/LibGUI/GItemView.cpp +++ b/LibGUI/GItemView.cpp @@ -1,8 +1,8 @@ +#include <Kernel/KeyCode.h> #include <LibGUI/GItemView.h> #include <LibGUI/GModel.h> -#include <LibGUI/GScrollBar.h> #include <LibGUI/GPainter.h> -#include <Kernel/KeyCode.h> +#include <LibGUI/GScrollBar.h> GItemView::GItemView(GWidget* parent) : GAbstractView(parent) @@ -38,7 +38,7 @@ void GItemView::did_update_model() void GItemView::update_content_size() { if (!model()) - return set_content_size({ }); + return set_content_size({}); m_visual_column_count = available_size().width() / effective_item_size().width(); if (m_visual_column_count) @@ -55,7 +55,7 @@ void GItemView::update_content_size() Rect GItemView::item_rect(int item_index) const { if (!m_visual_row_count || !m_visual_column_count) - return { }; + return {}; int visual_row_index = item_index / m_visual_column_count; int visual_column_index = item_index % m_visual_column_count; return { @@ -79,7 +79,7 @@ void GItemView::mousedown_event(GMouseEvent& event) return; } } - model()->set_selected_index({ }); + model()->set_selected_index({}); update(); } } @@ -100,7 +100,7 @@ void GItemView::paint_event(GPaintEvent& event) GPainter painter(*this); painter.add_clip_rect(widget_inner_rect()); - painter.add_clip_rect(event.rect()); + painter.add_clip_rect(event.rect()); painter.fill_rect(event.rect(), Color::White); painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value()); diff --git a/LibGUI/GLayout.cpp b/LibGUI/GLayout.cpp index 1aaa660ecca2..13a547e4c0f4 100644 --- a/LibGUI/GLayout.cpp +++ b/LibGUI/GLayout.cpp @@ -54,7 +54,7 @@ void GLayout::add_widget(GWidget& widget) void GLayout::remove_widget(GWidget& widget) { - m_entries.remove_first_matching([&] (auto& entry) { + m_entries.remove_first_matching([&](auto& entry) { return entry.widget == &widget; }); if (m_owner) diff --git a/LibGUI/GListView.cpp b/LibGUI/GListView.cpp index b3b28a1ce791..bcf33a8fb438 100644 --- a/LibGUI/GListView.cpp +++ b/LibGUI/GListView.cpp @@ -1,7 +1,7 @@ +#include <Kernel/KeyCode.h> #include <LibGUI/GListView.h> -#include <LibGUI/GScrollBar.h> #include <LibGUI/GPainter.h> -#include <Kernel/KeyCode.h> +#include <LibGUI/GScrollBar.h> GListView::GListView(GWidget* parent) : GAbstractView(parent) @@ -18,7 +18,7 @@ GListView::~GListView() void GListView::update_content_size() { if (!model()) - return set_content_size({ }); + return set_content_size({}); int content_width = 0; for (int row = 0, row_count = model()->row_count(); row < row_count; ++row) { @@ -76,7 +76,7 @@ void GListView::mousedown_event(GMouseEvent& event) update(); return; } - model()->set_selected_index({ }); + model()->set_selected_index({}); update(); } diff --git a/LibGUI/GMenu.cpp b/LibGUI/GMenu.cpp index 039ac8ab5c77..cb5902adbafd 100644 --- a/LibGUI/GMenu.cpp +++ b/LibGUI/GMenu.cpp @@ -1,7 +1,7 @@ +#include <AK/HashMap.h> #include <LibGUI/GAction.h> -#include <LibGUI/GMenu.h> #include <LibGUI/GEventLoop.h> -#include <AK/HashMap.h> +#include <LibGUI/GMenu.h> //#define GMENU_DEBUG @@ -81,8 +81,8 @@ int GMenu::realize_menu() ASSERT(m_menu_id > 0); for (int i = 0; i < m_items.size(); ++i) { auto& item = *m_items[i]; - item.set_menu_id({ }, m_menu_id); - item.set_identifier({ }, i); + item.set_menu_id({}, m_menu_id); + item.set_identifier({}, i); if (item.type() == GMenuItem::Separator) { WSAPI_ClientMessage request; request.type = WSAPI_ClientMessage::Type::AddMenuSeparator; diff --git a/LibGUI/GMenuBar.cpp b/LibGUI/GMenuBar.cpp index 1622d09fa0a4..19c736d8bc12 100644 --- a/LibGUI/GMenuBar.cpp +++ b/LibGUI/GMenuBar.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GMenuBar.h> #include <LibGUI/GEventLoop.h> +#include <LibGUI/GMenuBar.h> GMenuBar::GMenuBar() { diff --git a/LibGUI/GMenuItem.cpp b/LibGUI/GMenuItem.cpp index e721d051a557..cfd38e778d1a 100644 --- a/LibGUI/GMenuItem.cpp +++ b/LibGUI/GMenuItem.cpp @@ -1,6 +1,6 @@ -#include <LibGUI/GMenuItem.h> #include <LibGUI/GAction.h> #include <LibGUI/GEventLoop.h> +#include <LibGUI/GMenuItem.h> #include <WindowServer/WSAPITypes.h> GMenuItem::GMenuItem(unsigned menu_id, Type type) @@ -14,7 +14,7 @@ GMenuItem::GMenuItem(unsigned menu_id, Retained<GAction>&& action) , m_menu_id(menu_id) , m_action(move(action)) { - m_action->register_menu_item({ }, *this); + m_action->register_menu_item({}, *this); m_enabled = m_action->is_enabled(); m_checkable = m_action->is_checkable(); if (m_checkable) @@ -24,7 +24,7 @@ GMenuItem::GMenuItem(unsigned menu_id, Retained<GAction>&& action) GMenuItem::~GMenuItem() { if (m_action) - m_action->unregister_menu_item({ }, *this); + m_action->unregister_menu_item({}, *this); } void GMenuItem::set_enabled(bool enabled) diff --git a/LibGUI/GMessageBox.cpp b/LibGUI/GMessageBox.cpp index 6e70771ab1fc..c628997069ad 100644 --- a/LibGUI/GMessageBox.cpp +++ b/LibGUI/GMessageBox.cpp @@ -1,7 +1,7 @@ -#include <LibGUI/GMessageBox.h> #include <LibGUI/GBoxLayout.h> -#include <LibGUI/GLabel.h> #include <LibGUI/GButton.h> +#include <LibGUI/GLabel.h> +#include <LibGUI/GMessageBox.h> #include <stdio.h> void GMessageBox::show(const StringView& text, const StringView& title, Type type, CObject* parent) @@ -73,7 +73,7 @@ void GMessageBox::build() button->set_size_policy(SizePolicy::Fixed, SizePolicy::Fixed); button->set_preferred_size({ 100, 20 }); button->set_text("OK"); - button->on_click = [this] (auto&) { + button->on_click = [this](auto&) { dbgprintf("GMessageBox: OK button clicked\n"); done(0); }; diff --git a/LibGUI/GModel.cpp b/LibGUI/GModel.cpp index 454d9996d5b4..46e1037c2926 100644 --- a/LibGUI/GModel.cpp +++ b/LibGUI/GModel.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GModel.h> #include <LibGUI/GAbstractView.h> +#include <LibGUI/GModel.h> GModel::GModel() { @@ -29,7 +29,7 @@ void GModel::did_update() { if (on_model_update) on_model_update(*this); - for_each_view([] (auto& view) { + for_each_view([](auto& view) { view.did_update_model(); }); } @@ -41,7 +41,7 @@ void GModel::set_selected_index(const GModelIndex& index) m_selected_index = index; if (on_selection_changed) on_selection_changed(index); - for_each_view([] (auto& view) { + for_each_view([](auto& view) { view.did_update_selection(); }); } @@ -54,9 +54,9 @@ GModelIndex GModel::create_index(int row, int column, void* data) const GModelIndex GModel::sibling(int row, int column, const GModelIndex& parent) const { if (!parent.is_valid()) - return { }; + return {}; int row_count = this->row_count(parent); if (row < 0 || row > row_count) - return { }; + return {}; return index(row, column, parent); } diff --git a/LibGUI/GProgressBar.cpp b/LibGUI/GProgressBar.cpp index 1c60904cbab7..72c778242a77 100644 --- a/LibGUI/GProgressBar.cpp +++ b/LibGUI/GProgressBar.cpp @@ -1,6 +1,6 @@ -#include <LibGUI/GProgressBar.h> -#include <LibGUI/GPainter.h> #include <AK/StringBuilder.h> +#include <LibGUI/GPainter.h> +#include <LibGUI/GProgressBar.h> GProgressBar::GProgressBar(GWidget* parent) : GFrame(parent) diff --git a/LibGUI/GRadioButton.cpp b/LibGUI/GRadioButton.cpp index e88954dc9783..59cab6d9047c 100644 --- a/LibGUI/GRadioButton.cpp +++ b/LibGUI/GRadioButton.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GRadioButton.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GRadioButton.h> #include <SharedGraphics/GraphicsBitmap.h> static RetainPtr<GraphicsBitmap> s_unfilled_circle_bitmap; @@ -55,7 +55,7 @@ void GRadioButton::for_each_in_group(Callback callback) { if (!parent()) return; - parent()->for_each_child_of_type<GRadioButton>([&] (auto& child) { + parent()->for_each_child_of_type<GRadioButton>([&](auto& child) { return callback(static_cast<GRadioButton&>(child)); }); } @@ -64,7 +64,7 @@ void GRadioButton::click() { if (!is_enabled()) return; - for_each_in_group([this] (auto& button) { + for_each_in_group([this](auto& button) { if (&button != this) button.set_checked(false); return IterationDecision::Continue; diff --git a/LibGUI/GResizeCorner.cpp b/LibGUI/GResizeCorner.cpp index 91407a509fba..1dfba8b78622 100644 --- a/LibGUI/GResizeCorner.cpp +++ b/LibGUI/GResizeCorner.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GResizeCorner.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GResizeCorner.h> #include <LibGUI/GWindow.h> #include <SharedGraphics/GraphicsBitmap.h> #include <WindowServer/WSAPITypes.h> diff --git a/LibGUI/GScrollBar.cpp b/LibGUI/GScrollBar.cpp index d1834c82f447..dabd4649e981 100644 --- a/LibGUI/GScrollBar.cpp +++ b/LibGUI/GScrollBar.cpp @@ -1,8 +1,8 @@ +#include <LibGUI/GPainter.h> #include <LibGUI/GScrollBar.h> -#include <SharedGraphics/StylePainter.h> #include <SharedGraphics/CharacterBitmap.h> #include <SharedGraphics/GraphicsBitmap.h> -#include <LibGUI/GPainter.h> +#include <SharedGraphics/StylePainter.h> static const char* s_up_arrow_bitmap_data = { " " @@ -28,7 +28,6 @@ static const char* s_down_arrow_bitmap_data = { " " }; - static const char* s_left_arrow_bitmap_data = { " " " # " @@ -146,7 +145,7 @@ Rect GScrollBar::increment_gutter_rect() const { auto scrubber_rect = this->scrubber_rect(); if (orientation() == Orientation::Vertical) - return { 0, scrubber_rect.bottom() + 1, button_width(), height() - button_height() - scrubber_rect.bottom() - 1}; + return { 0, scrubber_rect.bottom() + 1, button_width(), height() - button_height() - scrubber_rect.bottom() - 1 }; else return { scrubber_rect.right() + 1, 0, width() - button_width() - scrubber_rect.right() - 1, button_width() }; } @@ -174,7 +173,7 @@ int GScrollBar::scrubber_size() const Rect GScrollBar::scrubber_rect() const { if (!has_scrubber()) - return { }; + return {}; float x_or_y; if (m_value == m_min) x_or_y = button_size(); diff --git a/LibGUI/GScrollableWidget.cpp b/LibGUI/GScrollableWidget.cpp index 9ae217e79240..906572f26e6f 100644 --- a/LibGUI/GScrollableWidget.cpp +++ b/LibGUI/GScrollableWidget.cpp @@ -1,12 +1,12 @@ -#include <LibGUI/GScrollableWidget.h> #include <LibGUI/GScrollBar.h> +#include <LibGUI/GScrollableWidget.h> GScrollableWidget::GScrollableWidget(GWidget* parent) : GFrame(parent) { m_vertical_scrollbar = new GScrollBar(Orientation::Vertical, this); m_vertical_scrollbar->set_step(4); - m_vertical_scrollbar->on_change = [this] (int) { + m_vertical_scrollbar->on_change = [this](int) { did_scroll(); update(); }; @@ -14,7 +14,7 @@ GScrollableWidget::GScrollableWidget(GWidget* parent) m_horizontal_scrollbar = new GScrollBar(Orientation::Horizontal, this); m_horizontal_scrollbar->set_step(4); m_horizontal_scrollbar->set_big_step(30); - m_horizontal_scrollbar->on_change = [this] (int) { + m_horizontal_scrollbar->on_change = [this](int) { did_scroll(); update(); }; diff --git a/LibGUI/GShortcut.cpp b/LibGUI/GShortcut.cpp index 871bf1c99cb1..07bf1f752462 100644 --- a/LibGUI/GShortcut.cpp +++ b/LibGUI/GShortcut.cpp @@ -1,114 +1,218 @@ -#include <LibGUI/GShortcut.h> #include <AK/StringBuilder.h> +#include <LibGUI/GShortcut.h> static String to_string(KeyCode key) { switch (key) { - case Key_Escape: return "Escape"; - case Key_Tab: return "Tab"; - case Key_Backspace: return "Backspace"; - case Key_Return: return "Return"; - case Key_Insert: return "Insert"; - case Key_Delete: return "Delete"; - case Key_PrintScreen: return "PrintScreen"; - case Key_SysRq: return "SysRq"; - case Key_Home: return "Home"; - case Key_End: return "End"; - case Key_Left: return "Left"; - case Key_Up: return "Up"; - case Key_Right: return "Right"; - case Key_Down: return "Down"; - case Key_PageUp: return "PageUp"; - case Key_PageDown: return "PageDown"; - case Key_Shift: return "Shift"; - case Key_Control: return "Control"; - case Key_Alt: return "Alt"; - case Key_CapsLock: return "CapsLock"; - case Key_NumLock: return "NumLock"; - case Key_ScrollLock: return "ScrollLock"; - case Key_F1: return "F1"; - case Key_F2: return "F2"; - case Key_F3: return "F3"; - case Key_F4: return "F4"; - case Key_F5: return "F5"; - case Key_F6: return "F6"; - case Key_F7: return "F7"; - case Key_F8: return "F8"; - case Key_F9: return "F9"; - case Key_F10: return "F10"; - case Key_F11: return "F11"; - case Key_F12: return "F12"; - case Key_Space: return "Space"; - case Key_ExclamationPoint: return "!"; - case Key_DoubleQuote: return "\""; - case Key_Hashtag: return "#"; - case Key_Dollar: return "$"; - case Key_Percent: return "%"; - case Key_Ampersand: return "&"; - case Key_Apostrophe: return "'"; - case Key_LeftParen: return "("; - case Key_RightParen: return ")"; - case Key_Asterisk: return "*"; - case Key_Plus: return "+"; - case Key_Comma: return ","; - case Key_Minus: return "-"; - case Key_Period: return ","; - case Key_Slash: return "/"; - case Key_0: return "0"; - case Key_1: return "1"; - case Key_2: return "2"; - case Key_3: return "3"; - case Key_4: return "4"; - case Key_5: return "5"; - case Key_6: return "6"; - case Key_7: return "7"; - case Key_8: return "8"; - case Key_9: return "9"; - case Key_Colon: return ":"; - case Key_Semicolon: return ";"; - case Key_LessThan: return "<"; - case Key_Equal: return "="; - case Key_GreaterThan: return ">"; - case Key_QuestionMark: return "?"; - case Key_AtSign: return "@"; - case Key_A: return "A"; - case Key_B: return "B"; - case Key_C: return "C"; - case Key_D: return "D"; - case Key_E: return "E"; - case Key_F: return "F"; - case Key_G: return "G"; - case Key_H: return "H"; - case Key_I: return "I"; - case Key_J: return "J"; - case Key_K: return "K"; - case Key_L: return "L"; - case Key_M: return "M"; - case Key_N: return "N"; - case Key_O: return "O"; - case Key_P: return "P"; - case Key_Q: return "Q"; - case Key_R: return "R"; - case Key_S: return "S"; - case Key_T: return "T"; - case Key_U: return "U"; - case Key_V: return "V"; - case Key_W: return "W"; - case Key_X: return "X"; - case Key_Y: return "Y"; - case Key_Z: return "Z"; - case Key_LeftBracket: return "["; - case Key_RightBracket: return "]"; - case Key_Backslash: return "\\"; - case Key_Circumflex: return "^"; - case Key_Underscore: return "_"; - case Key_LeftBrace: return "{"; - case Key_RightBrace: return "}"; - case Key_Pipe: return "|"; - case Key_Tilde: return "~"; - case Key_Backtick: return "`"; + case Key_Escape: + return "Escape"; + case Key_Tab: + return "Tab"; + case Key_Backspace: + return "Backspace"; + case Key_Return: + return "Return"; + case Key_Insert: + return "Insert"; + case Key_Delete: + return "Delete"; + case Key_PrintScreen: + return "PrintScreen"; + case Key_SysRq: + return "SysRq"; + case Key_Home: + return "Home"; + case Key_End: + return "End"; + case Key_Left: + return "Left"; + case Key_Up: + return "Up"; + case Key_Right: + return "Right"; + case Key_Down: + return "Down"; + case Key_PageUp: + return "PageUp"; + case Key_PageDown: + return "PageDown"; + case Key_Shift: + return "Shift"; + case Key_Control: + return "Control"; + case Key_Alt: + return "Alt"; + case Key_CapsLock: + return "CapsLock"; + case Key_NumLock: + return "NumLock"; + case Key_ScrollLock: + return "ScrollLock"; + case Key_F1: + return "F1"; + case Key_F2: + return "F2"; + case Key_F3: + return "F3"; + case Key_F4: + return "F4"; + case Key_F5: + return "F5"; + case Key_F6: + return "F6"; + case Key_F7: + return "F7"; + case Key_F8: + return "F8"; + case Key_F9: + return "F9"; + case Key_F10: + return "F10"; + case Key_F11: + return "F11"; + case Key_F12: + return "F12"; + case Key_Space: + return "Space"; + case Key_ExclamationPoint: + return "!"; + case Key_DoubleQuote: + return "\""; + case Key_Hashtag: + return "#"; + case Key_Dollar: + return "$"; + case Key_Percent: + return "%"; + case Key_Ampersand: + return "&"; + case Key_Apostrophe: + return "'"; + case Key_LeftParen: + return "("; + case Key_RightParen: + return ")"; + case Key_Asterisk: + return "*"; + case Key_Plus: + return "+"; + case Key_Comma: + return ","; + case Key_Minus: + return "-"; + case Key_Period: + return ","; + case Key_Slash: + return "/"; + case Key_0: + return "0"; + case Key_1: + return "1"; + case Key_2: + return "2"; + case Key_3: + return "3"; + case Key_4: + return "4"; + case Key_5: + return "5"; + case Key_6: + return "6"; + case Key_7: + return "7"; + case Key_8: + return "8"; + case Key_9: + return "9"; + case Key_Colon: + return ":"; + case Key_Semicolon: + return ";"; + case Key_LessThan: + return "<"; + case Key_Equal: + return "="; + case Key_GreaterThan: + return ">"; + case Key_QuestionMark: + return "?"; + case Key_AtSign: + return "@"; + case Key_A: + return "A"; + case Key_B: + return "B"; + case Key_C: + return "C"; + case Key_D: + return "D"; + case Key_E: + return "E"; + case Key_F: + return "F"; + case Key_G: + return "G"; + case Key_H: + return "H"; + case Key_I: + return "I"; + case Key_J: + return "J"; + case Key_K: + return "K"; + case Key_L: + return "L"; + case Key_M: + return "M"; + case Key_N: + return "N"; + case Key_O: + return "O"; + case Key_P: + return "P"; + case Key_Q: + return "Q"; + case Key_R: + return "R"; + case Key_S: + return "S"; + case Key_T: + return "T"; + case Key_U: + return "U"; + case Key_V: + return "V"; + case Key_W: + return "W"; + case Key_X: + return "X"; + case Key_Y: + return "Y"; + case Key_Z: + return "Z"; + case Key_LeftBracket: + return "["; + case Key_RightBracket: + return "]"; + case Key_Backslash: + return "\\"; + case Key_Circumflex: + return "^"; + case Key_Underscore: + return "_"; + case Key_LeftBrace: + return "{"; + case Key_RightBrace: + return "}"; + case Key_Pipe: + return "|"; + case Key_Tilde: + return "~"; + case Key_Backtick: + return "`"; - case Key_Invalid: return "Invalid"; + case Key_Invalid: + return "Invalid"; default: ASSERT_NOT_REACHED(); } diff --git a/LibGUI/GSlider.cpp b/LibGUI/GSlider.cpp index 97546c8f822c..66adb04cf146 100644 --- a/LibGUI/GSlider.cpp +++ b/LibGUI/GSlider.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GSlider.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GSlider.h> #include <SharedGraphics/StylePainter.h> GSlider::GSlider(GWidget* parent) diff --git a/LibGUI/GSortingProxyModel.cpp b/LibGUI/GSortingProxyModel.cpp index 0661fd3e9df5..7897503ffda5 100644 --- a/LibGUI/GSortingProxyModel.cpp +++ b/LibGUI/GSortingProxyModel.cpp @@ -1,13 +1,13 @@ -#include <LibGUI/GSortingProxyModel.h> #include <AK/QuickSort.h> -#include <stdlib.h> +#include <LibGUI/GSortingProxyModel.h> #include <stdio.h> +#include <stdlib.h> GSortingProxyModel::GSortingProxyModel(Retained<GModel>&& target) : m_target(move(target)) , m_key_column(-1) { - m_target->on_model_update = [this] (GModel&) { + m_target->on_model_update = [this](GModel&) { resort(); }; } @@ -29,9 +29,9 @@ int GSortingProxyModel::column_count(const GModelIndex& index) const GModelIndex GSortingProxyModel::map_to_target(const GModelIndex& index) const { if (!index.is_valid()) - return { }; + return {}; if (index.row() >= m_row_mappings.size() || index.column() >= column_count()) - return { }; + return {}; return target().index(m_row_mappings[index.row()], index.column()); } @@ -82,7 +82,7 @@ void GSortingProxyModel::resort() did_update(); return; } - quick_sort(m_row_mappings.begin(), m_row_mappings.end(), [&] (auto row1, auto row2) -> bool { + quick_sort(m_row_mappings.begin(), m_row_mappings.end(), [&](auto row1, auto row2) -> bool { auto data1 = target().data(target().index(row1, m_key_column), GModel::Role::Sort); auto data2 = target().data(target().index(row2, m_key_column), GModel::Role::Sort); if (data1 == data2) diff --git a/LibGUI/GSpinBox.cpp b/LibGUI/GSpinBox.cpp index 891d98a218b7..f7a6d4b38dc2 100644 --- a/LibGUI/GSpinBox.cpp +++ b/LibGUI/GSpinBox.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GSpinBox.h> #include <LibGUI/GButton.h> +#include <LibGUI/GSpinBox.h> #include <LibGUI/GTextEditor.h> GSpinBox::GSpinBox(GWidget* parent) @@ -16,10 +16,10 @@ GSpinBox::GSpinBox(GWidget* parent) }; m_increment_button = new GButton(this); m_increment_button->set_text("\xf6"); - m_increment_button->on_click = [this] (GButton&) { set_value(m_value + 1); }; + m_increment_button->on_click = [this](GButton&) { set_value(m_value + 1); }; m_decrement_button = new GButton(this); m_decrement_button->set_text("\xf7"); - m_decrement_button->on_click = [this] (GButton&) { set_value(m_value - 1); }; + m_decrement_button->on_click = [this](GButton&) { set_value(m_value - 1); }; } GSpinBox::~GSpinBox() diff --git a/LibGUI/GSplitter.cpp b/LibGUI/GSplitter.cpp index 567dfb469325..2544541aef77 100644 --- a/LibGUI/GSplitter.cpp +++ b/LibGUI/GSplitter.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GSplitter.h> #include <LibGUI/GBoxLayout.h> +#include <LibGUI/GSplitter.h> #include <LibGUI/GWindow.h> GSplitter::GSplitter(Orientation orientation, GWidget* parent) @@ -40,7 +40,7 @@ void GSplitter::mousedown_event(GMouseEvent& event) GWidget* first_resizee { nullptr }; GWidget* second_resizee { nullptr }; int fudge = layout()->spacing(); - for_each_child_widget([&] (auto& child) { + for_each_child_widget([&](auto& child) { int child_start = m_orientation == Orientation::Horizontal ? child.relative_rect().left() : child.relative_rect().top(); int child_end = m_orientation == Orientation::Horizontal ? child.relative_rect().right() : child.relative_rect().bottom(); if (x_or_y > child_end && (x_or_y - fudge) <= child_end) @@ -65,7 +65,8 @@ void GSplitter::mousemove_event(GMouseEvent& event) if (!m_first_resizee || !m_second_resizee) { // One or both of the resizees were deleted during an ongoing resize, screw this. m_resizing = false; - return;; + return; + ; } int minimum_size = 0; auto new_first_resizee_size = m_first_resizee_start_size; @@ -112,5 +113,4 @@ void GSplitter::mouseup_event(GMouseEvent& event) m_resizing = false; if (!rect().contains(event.position())) window()->set_override_cursor(GStandardCursor::None); - } diff --git a/LibGUI/GStackWidget.cpp b/LibGUI/GStackWidget.cpp index 312938d66db4..33b6af25ebf4 100644 --- a/LibGUI/GStackWidget.cpp +++ b/LibGUI/GStackWidget.cpp @@ -1,5 +1,5 @@ -#include <LibGUI/GStackWidget.h> #include <LibGUI/GBoxLayout.h> +#include <LibGUI/GStackWidget.h> GStackWidget::GStackWidget(GWidget* parent) : GWidget(parent) @@ -28,7 +28,7 @@ void GStackWidget::resize_event(GResizeEvent& event) { if (!m_active_widget) return; - m_active_widget->set_relative_rect({ { }, event.size() }); + m_active_widget->set_relative_rect({ {}, event.size() }); } void GStackWidget::child_event(CChildEvent& event) @@ -44,7 +44,7 @@ void GStackWidget::child_event(CChildEvent& event) } else if (event.type() == GEvent::ChildRemoved) { if (m_active_widget == &child) { GWidget* new_active_widget = nullptr; - for_each_child_widget([&] (auto& new_child) { + for_each_child_widget([&](auto& new_child) { new_active_widget = &new_child; return IterationDecision::Abort; }); diff --git a/LibGUI/GStatusBar.cpp b/LibGUI/GStatusBar.cpp index 70e25520372f..e219035e32dc 100644 --- a/LibGUI/GStatusBar.cpp +++ b/LibGUI/GStatusBar.cpp @@ -1,9 +1,9 @@ -#include <LibGUI/GStatusBar.h> -#include <LibGUI/GLabel.h> #include <LibGUI/GBoxLayout.h> -#include <SharedGraphics/StylePainter.h> +#include <LibGUI/GLabel.h> #include <LibGUI/GPainter.h> #include <LibGUI/GResizeCorner.h> +#include <LibGUI/GStatusBar.h> +#include <SharedGraphics/StylePainter.h> GStatusBar::GStatusBar(GWidget* parent) : GWidget(parent) diff --git a/LibGUI/GTabWidget.cpp b/LibGUI/GTabWidget.cpp index a465bac9e163..55b1aaa14375 100644 --- a/LibGUI/GTabWidget.cpp +++ b/LibGUI/GTabWidget.cpp @@ -1,6 +1,6 @@ -#include <LibGUI/GTabWidget.h> #include <LibGUI/GBoxLayout.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GTabWidget.h> #include <SharedGraphics/StylePainter.h> GTabWidget::GTabWidget(GWidget* parent) @@ -61,7 +61,7 @@ void GTabWidget::child_event(CChildEvent& event) } else if (event.type() == GEvent::ChildRemoved) { if (m_active_widget == &child) { GWidget* new_active_widget = nullptr; - for_each_child_widget([&] (auto& new_child) { + for_each_child_widget([&](auto& new_child) { new_active_widget = &new_child; return IterationDecision::Abort; }); diff --git a/LibGUI/GTableView.cpp b/LibGUI/GTableView.cpp index e4b49af9e56a..8e096f3b4311 100644 --- a/LibGUI/GTableView.cpp +++ b/LibGUI/GTableView.cpp @@ -1,13 +1,13 @@ -#include <LibGUI/GTableView.h> +#include <AK/StringBuilder.h> +#include <Kernel/KeyCode.h> +#include <LibGUI/GAction.h> +#include <LibGUI/GMenu.h> #include <LibGUI/GModel.h> -#include <LibGUI/GScrollBar.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GScrollBar.h> +#include <LibGUI/GTableView.h> #include <LibGUI/GTextBox.h> #include <LibGUI/GWindow.h> -#include <LibGUI/GMenu.h> -#include <LibGUI/GAction.h> -#include <Kernel/KeyCode.h> -#include <AK/StringBuilder.h> GTableView::GTableView(GWidget* parent) : GAbstractView(parent) @@ -24,7 +24,7 @@ GTableView::~GTableView() void GTableView::update_content_size() { if (!model()) - return set_content_size({ }); + return set_content_size({}); int content_width = 0; int column_count = model()->column_count(); @@ -80,9 +80,9 @@ int GTableView::column_width(int column_index) const Rect GTableView::header_rect(int column_index) const { if (!model()) - return { }; + return {}; if (is_column_hidden(column_index)) - return { }; + return {}; int x_offset = 0; for (int i = 0; i < column_index; ++i) { if (is_column_hidden(i)) @@ -100,7 +100,7 @@ Point GTableView::adjusted_position(const Point& position) Rect GTableView::column_resize_grabbable_rect(int column) const { if (!model()) - return { }; + return {}; auto header_rect = this->header_rect(column); return { header_rect.right() - 1, header_rect.top(), 4, header_rect.height() }; } @@ -148,7 +148,7 @@ void GTableView::mousedown_event(GMouseEvent& event) return; } } - model()->set_selected_index({ }); + model()->set_selected_index({}); update(); } @@ -427,7 +427,7 @@ GMenu& GTableView::ensure_header_context_menu() for (int column = 0; column < model()->column_count(); ++column) { auto& column_data = this->column_data(column); auto name = model()->column_name(column); - column_data.visibility_action = GAction::create(name, [this, column] (GAction& action) { + column_data.visibility_action = GAction::create(name, [this, column](GAction& action) { action.set_checked(!action.is_checked()); set_column_hidden(column, !action.is_checked()); }); diff --git a/LibGUI/GTextEditor.cpp b/LibGUI/GTextEditor.cpp index d06d3e7d4081..a21159c36a00 100644 --- a/LibGUI/GTextEditor.cpp +++ b/LibGUI/GTextEditor.cpp @@ -1,17 +1,17 @@ -#include <LibGUI/GTextEditor.h> -#include <LibGUI/GScrollBar.h> -#include <LibGUI/GFontDatabase.h> +#include <AK/StringBuilder.h> +#include <Kernel/KeyCode.h> +#include <LibGUI/GAction.h> #include <LibGUI/GClipboard.h> +#include <LibGUI/GFontDatabase.h> +#include <LibGUI/GMenu.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GScrollBar.h> +#include <LibGUI/GTextEditor.h> #include <LibGUI/GWindow.h> -#include <LibGUI/GMenu.h> -#include <LibGUI/GAction.h> -#include <Kernel/KeyCode.h> -#include <AK/StringBuilder.h> -#include <unistd.h> +#include <ctype.h> #include <fcntl.h> #include <stdio.h> -#include <ctype.h> +#include <unistd.h> GTextEditor::GTextEditor(Type type, GWidget* parent) : GScrollableWidget(parent) @@ -35,29 +35,35 @@ GTextEditor::~GTextEditor() void GTextEditor::create_actions() { - m_undo_action = GAction::create("Undo", { Mod_Ctrl, Key_Z }, GraphicsBitmap::load_from_file("/res/icons/16x16/undo.png"), [&] (const GAction&) { + m_undo_action = GAction::create("Undo", { Mod_Ctrl, Key_Z }, GraphicsBitmap::load_from_file("/res/icons/16x16/undo.png"), [&](const GAction&) { // FIXME: Undo - }, this); + }, + this); - m_redo_action = GAction::create("Redo", { Mod_Ctrl, Key_Y }, GraphicsBitmap::load_from_file("/res/icons/16x16/redo.png"), [&] (const GAction&) { + m_redo_action = GAction::create("Redo", { Mod_Ctrl, Key_Y }, GraphicsBitmap::load_from_file("/res/icons/16x16/redo.png"), [&](const GAction&) { // FIXME: Redo - }, this); + }, + this); - m_cut_action = GAction::create("Cut", { Mod_Ctrl, Key_X }, GraphicsBitmap::load_from_file("/res/icons/cut16.png"), [&] (const GAction&) { + m_cut_action = GAction::create("Cut", { Mod_Ctrl, Key_X }, GraphicsBitmap::load_from_file("/res/icons/cut16.png"), [&](const GAction&) { cut(); - }, this); + }, + this); - m_copy_action = GAction::create("Copy", { Mod_Ctrl, Key_C }, GraphicsBitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [&] (const GAction&) { + m_copy_action = GAction::create("Copy", { Mod_Ctrl, Key_C }, GraphicsBitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [&](const GAction&) { copy(); - }, this); + }, + this); - m_paste_action = GAction::create("Paste", { Mod_Ctrl, Key_V }, GraphicsBitmap::load_from_file("/res/icons/paste16.png"), [&] (const GAction&) { + m_paste_action = GAction::create("Paste", { Mod_Ctrl, Key_V }, GraphicsBitmap::load_from_file("/res/icons/paste16.png"), [&](const GAction&) { paste(); - }, this); + }, + this); - m_delete_action = GAction::create("Delete", { 0, Key_Delete }, GraphicsBitmap::load_from_file("/res/icons/16x16/delete.png"), [&] (const GAction&) { + m_delete_action = GAction::create("Delete", { 0, Key_Delete }, GraphicsBitmap::load_from_file("/res/icons/16x16/delete.png"), [&](const GAction&) { do_delete(); - }, this); + }, + this); } void GTextEditor::set_text(const StringView& text) @@ -69,7 +75,7 @@ void GTextEditor::set_text(const StringView& text) m_lines.clear(); int start_of_current_line = 0; - auto add_line = [&] (int current_position) { + auto add_line = [&](int current_position) { int line_length = current_position - start_of_current_line; auto line = make<Line>(); if (line_length) @@ -189,7 +195,7 @@ void GTextEditor::mousedown_event(GMouseEvent& event) if (event.modifiers() & Mod_Shift) { if (!has_selection()) - m_selection.set(m_cursor, { }); + m_selection.set(m_cursor, {}); } else { m_selection.clear(); } @@ -200,7 +206,7 @@ void GTextEditor::mousedown_event(GMouseEvent& event) if (!(event.modifiers() & Mod_Shift)) { if (!has_selection()) - m_selection.set(m_cursor, { }); + m_selection.set(m_cursor, {}); } if (m_selection.start().is_valid() && m_selection.start() != m_cursor) @@ -243,7 +249,7 @@ int GTextEditor::ruler_width() const Rect GTextEditor::ruler_content_rect(int line_index) const { if (!m_ruler_visible) - return { }; + return {}; return { 0 - ruler_width() + horizontal_scrollbar().value(), line_index * line_height(), @@ -263,7 +269,7 @@ void GTextEditor::paint_event(GPaintEvent& event) painter.translate(frame_thickness(), frame_thickness()); - Rect ruler_rect { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar()}; + Rect ruler_rect { 0, 0, ruler_width(), height() - height_occupied_by_horizontal_scrollbar() }; if (m_ruler_visible) { painter.fill_rect(ruler_rect, Color::LightGray); @@ -289,8 +295,7 @@ void GTextEditor::paint_event(GPaintEvent& event) String::format("%u", i), is_current_line ? Font::default_bold_font() : font(), TextAlignment::CenterRight, - is_current_line ? Color::DarkGray : Color::MidGray - ); + is_current_line ? Color::DarkGray : Color::MidGray); } } @@ -310,7 +315,8 @@ void GTextEditor::paint_event(GPaintEvent& event) int selection_end_column_on_line = selection.end().line() == i ? selection.end().column() : line.length(); int selection_left = content_x_for_position({ i, selection_start_column_on_line }); - int selection_right = content_x_for_position({ i, selection_end_column_on_line });; + int selection_right = content_x_for_position({ i, selection_end_column_on_line }); + ; Rect selection_rect { selection_left, line_rect.y(), selection_right - selection_left, line_rect.height() }; painter.fill_rect(selection_rect, Color::from_rgb(0x955233)); @@ -325,7 +331,7 @@ void GTextEditor::paint_event(GPaintEvent& event) void GTextEditor::toggle_selection_if_needed_for_event(const GKeyEvent& event) { if (event.shift() && !m_selection.is_valid()) { - m_selection.set(m_cursor, { }); + m_selection.set(m_cursor, {}); did_update_selection(); update(); return; @@ -654,7 +660,7 @@ int GTextEditor::content_x_for_position(const GTextPosition& position) const Rect GTextEditor::cursor_content_rect() const { if (!m_cursor.is_valid()) - return { }; + return {}; ASSERT(!m_lines.is_empty()); ASSERT(m_cursor.column() <= (current_line().length() + 1)); @@ -662,7 +668,7 @@ Rect GTextEditor::cursor_content_rect() const if (is_single_line()) { Rect cursor_rect { cursor_x, 0, 1, font().glyph_height() + 2 }; - cursor_rect.center_vertically_within({ { }, frame_inner_rect().size() }); + cursor_rect.center_vertically_within({ {}, frame_inner_rect().size() }); return cursor_rect; } return { cursor_x, m_cursor.line() * line_height(), 1, line_height() }; @@ -694,7 +700,7 @@ Rect GTextEditor::line_content_rect(int line_index) const auto& line = *m_lines[line_index]; if (is_single_line()) { Rect line_rect = { content_x_for_position({ line_index, 0 }), 0, line.length() * glyph_width(), font().glyph_height() + 2 }; - line_rect.center_vertically_within({ { }, frame_inner_rect().size() }); + line_rect.center_vertically_within({ {}, frame_inner_rect().size() }); return line_rect; } return { @@ -887,7 +893,7 @@ void GTextEditor::clear() String GTextEditor::selected_text() const { if (!has_selection()) - return { }; + return {}; auto selection = normalized_selection(); StringBuilder builder; @@ -1005,7 +1011,7 @@ void GTextEditor::did_change() update_content_size(); if (!m_have_pending_change_notification) { m_have_pending_change_notification = true; - deferred_invoke([this] (auto&) { + deferred_invoke([this](auto&) { if (on_change) on_change(); m_have_pending_change_notification = false; diff --git a/LibGUI/GToolBar.cpp b/LibGUI/GToolBar.cpp index 8b0fa64aaa49..5aa6f469c26a 100644 --- a/LibGUI/GToolBar.cpp +++ b/LibGUI/GToolBar.cpp @@ -1,8 +1,8 @@ -#include <LibGUI/GToolBar.h> +#include <LibGUI/GAction.h> #include <LibGUI/GBoxLayout.h> #include <LibGUI/GButton.h> -#include <LibGUI/GAction.h> #include <LibGUI/GPainter.h> +#include <LibGUI/GToolBar.h> GToolBar::GToolBar(GWidget* parent) : GWidget(parent) @@ -32,7 +32,7 @@ void GToolBar::add_action(Retained<GAction>&& action) button->set_icon(item->action->icon()); else button->set_text(item->action->text()); - button->on_click = [raw_action_ptr] (const GButton&) { + button->on_click = [raw_action_ptr](const GButton&) { raw_action_ptr->activate(); }; @@ -54,7 +54,7 @@ class SeparatorWidget final : public GWidget { set_background_color(Color::White); set_preferred_size({ 8, 22 }); } - virtual ~SeparatorWidget() override { } + virtual ~SeparatorWidget() override {} virtual void paint_event(GPaintEvent& event) override { diff --git a/LibGUI/GTreeView.cpp b/LibGUI/GTreeView.cpp index 0b7203deb543..618b966f077d 100644 --- a/LibGUI/GTreeView.cpp +++ b/LibGUI/GTreeView.cpp @@ -1,6 +1,6 @@ -#include <LibGUI/GTreeView.h> #include <LibGUI/GPainter.h> #include <LibGUI/GScrollBar.h> +#include <LibGUI/GTreeView.h> //#define DEBUG_ITEM_RECTS @@ -39,9 +39,9 @@ GModelIndex GTreeView::index_at_content_position(const Point& position, bool& is { is_toggle = false; if (!model()) - return { }; + return {}; GModelIndex result; - traverse_in_paint_order([&] (const GModelIndex& index, const Rect& rect, const Rect& toggle_rect, int) { + traverse_in_paint_order([&](const GModelIndex& index, const Rect& rect, const Rect& toggle_rect, int) { if (rect.contains(position)) { result = index; return IterationDecision::Abort; @@ -88,7 +88,7 @@ void GTreeView::traverse_in_paint_order(Callback callback) const int indent_level = 0; int y_offset = 0; - Function<IterationDecision(const GModelIndex&)> traverse_index = [&] (const GModelIndex& index) { + Function<IterationDecision(const GModelIndex&)> traverse_index = [&](const GModelIndex& index) { int row_count_at_index = model.row_count(index); if (index.is_valid()) { auto& metadata = ensure_metadata_for_index(index); @@ -139,7 +139,7 @@ void GTreeView::paint_event(GPaintEvent& event) auto& model = *this->model(); auto visible_content_rect = this->visible_content_rect(); - traverse_in_paint_order([&] (const GModelIndex& index, const Rect& rect, const Rect& toggle_rect, int indent_level) { + traverse_in_paint_order([&](const GModelIndex& index, const Rect& rect, const Rect& toggle_rect, int indent_level) { if (!rect.intersects(visible_content_rect)) return IterationDecision::Continue; #ifdef DEBUG_ITEM_RECTS @@ -202,7 +202,7 @@ void GTreeView::scroll_into_view(const GModelIndex& a_index, Orientation orienta if (!a_index.is_valid()) return; Rect found_rect; - traverse_in_paint_order([&] (const GModelIndex& index, const Rect& rect, const Rect&, int) { + traverse_in_paint_order([&](const GModelIndex& index, const Rect& rect, const Rect&, int) { if (index == a_index) { found_rect = rect; return IterationDecision::Abort; @@ -251,7 +251,7 @@ void GTreeView::update_content_size() { int height = 0; int width = 0; - traverse_in_paint_order([&] (const GModelIndex&, const Rect& rect, const Rect&, int) { + traverse_in_paint_order([&](const GModelIndex&, const Rect& rect, const Rect&, int) { width = max(width, rect.right()); height += rect.height(); return IterationDecision::Continue; @@ -267,7 +267,7 @@ void GTreeView::keydown_event(GKeyEvent& event) if (event.key() == KeyCode::Key_Up) { GModelIndex previous_index; GModelIndex found_index; - traverse_in_paint_order([&] (const GModelIndex& index, const Rect&, const Rect&, int) { + traverse_in_paint_order([&](const GModelIndex& index, const Rect&, const Rect&, int) { if (index == cursor_index) { found_index = previous_index; return IterationDecision::Abort; @@ -284,7 +284,7 @@ void GTreeView::keydown_event(GKeyEvent& event) if (event.key() == KeyCode::Key_Down) { GModelIndex previous_index; GModelIndex found_index; - traverse_in_paint_order([&] (const GModelIndex& index, const Rect&, const Rect&, int) { + traverse_in_paint_order([&](const GModelIndex& index, const Rect&, const Rect&, int) { if (previous_index == cursor_index) { found_index = index; return IterationDecision::Abort; diff --git a/LibGUI/GVariant.cpp b/LibGUI/GVariant.cpp index e8c07e98e99a..bad6f9d3b656 100644 --- a/LibGUI/GVariant.cpp +++ b/LibGUI/GVariant.cpp @@ -252,4 +252,3 @@ String GVariant::to_string() const } ASSERT_NOT_REACHED(); } - diff --git a/LibGUI/GWidget.cpp b/LibGUI/GWidget.cpp index 30f4284a4613..d0ac2161b0ec 100644 --- a/LibGUI/GWidget.cpp +++ b/LibGUI/GWidget.cpp @@ -2,13 +2,13 @@ #include "GEvent.h" #include "GEventLoop.h" #include "GWindow.h" -#include <LibGUI/GLayout.h> #include <AK/Assertions.h> -#include <SharedGraphics/GraphicsBitmap.h> #include <LibGUI/GAction.h> -#include <LibGUI/GPainter.h> #include <LibGUI/GApplication.h> +#include <LibGUI/GLayout.h> #include <LibGUI/GMenu.h> +#include <LibGUI/GPainter.h> +#include <SharedGraphics/GraphicsBitmap.h> #include <unistd.h> GWidget::GWidget(GWidget* parent) @@ -116,7 +116,7 @@ void GWidget::handle_paint_event(GPaintEvent& event) #endif } paint_event(event); - for_each_child_widget([&] (auto& child) { + for_each_child_widget([&](auto& child) { if (!child.is_visible()) return IterationDecision::Continue; if (child.relative_rect().intersects(event.rect())) { @@ -418,7 +418,7 @@ void GWidget::invalidate_layout() if (m_layout_dirty) return; m_layout_dirty = true; - deferred_invoke([this] (auto&) { + deferred_invoke([this](auto&) { m_layout_dirty = false; auto* w = window(); if (!w) @@ -472,7 +472,7 @@ void GWidget::move_to_front() return; if (parent->children().size() == 1) return; - parent->children().remove_first_matching([this] (auto& entry) { + parent->children().remove_first_matching([this](auto& entry) { return entry == this; }); parent->children().append(this); @@ -486,7 +486,7 @@ void GWidget::move_to_back() return; if (parent->children().size() == 1) return; - parent->children().remove_first_matching([this] (auto& entry) { + parent->children().remove_first_matching([this](auto& entry) { return entry == this; }); parent->children().prepend(this); diff --git a/LibGUI/GWindow.cpp b/LibGUI/GWindow.cpp index 190f1e9cd29a..13aa292d34db 100644 --- a/LibGUI/GWindow.cpp +++ b/LibGUI/GWindow.cpp @@ -2,12 +2,12 @@ #include "GEvent.h" #include "GEventLoop.h" #include "GWidget.h" -#include <SharedGraphics/GraphicsBitmap.h> -#include <LibGUI/GPainter.h> +#include <AK/HashMap.h> #include <LibC/stdio.h> #include <LibC/stdlib.h> #include <LibC/unistd.h> -#include <AK/HashMap.h> +#include <LibGUI/GPainter.h> +#include <SharedGraphics/GraphicsBitmap.h> //#define UPDATE_COALESCING_DEBUG @@ -235,7 +235,7 @@ void GWindow::event(CEvent& event) auto rect = rects.first(); if (rect.is_empty() || created_new_backing_store) { rects.clear(); - rects.append({ { }, paint_event.window_size() }); + rects.append({ {}, paint_event.window_size() }); } for (auto& rect : rects) @@ -294,10 +294,10 @@ void GWindow::event(CEvent& event) m_back_bitmap = nullptr; if (!m_pending_paint_event_rects.is_empty()) { m_pending_paint_event_rects.clear_with_capacity(); - m_pending_paint_event_rects.append({ { }, new_size }); + m_pending_paint_event_rects.append({ {}, new_size }); } - m_rect_when_windowless = { { }, new_size }; - m_main_widget->set_relative_rect({ { }, new_size }); + m_rect_when_windowless = { {}, new_size }; + m_main_widget->set_relative_rect({ {}, new_size }); return; } @@ -326,7 +326,7 @@ void GWindow::update(const Rect& a_rect) } if (m_pending_paint_event_rects.is_empty()) { - deferred_invoke([this] (auto&) { + deferred_invoke([this](auto&) { auto rects = move(m_pending_paint_event_rects); if (rects.is_empty()) return; @@ -357,7 +357,7 @@ void GWindow::set_main_widget(GWidget* widget) if (m_main_widget->vertical_size_policy() == SizePolicy::Fixed) new_window_rect.set_height(m_main_widget->preferred_size().height()); set_rect(new_window_rect); - m_main_widget->set_relative_rect({ { }, new_window_rect.size() }); + m_main_widget->set_relative_rect({ {}, new_window_rect.size() }); m_main_widget->set_window(this); if (m_main_widget->accepts_focus()) m_main_widget->set_focus(true); @@ -530,14 +530,14 @@ void GWindow::start_wm_resize() Vector<GWidget*> GWindow::focusable_widgets() const { if (!m_main_widget) - return { }; + return {}; Vector<GWidget*> collected_widgets; - Function<void(GWidget&)> collect_focusable_widgets = [&] (GWidget& widget) { + Function<void(GWidget&)> collect_focusable_widgets = [&](GWidget& widget) { if (widget.accepts_focus()) collected_widgets.append(&widget); - widget.for_each_child_widget([&] (auto& child) { + widget.for_each_child_widget([&](auto& child) { if (!child.is_visible()) return IterationDecision::Continue; if (!child.is_enabled())
9620a092dee1c0fed4f26394b12869ac992182a6
2022-11-05 02:42:10
Timothy Flynn
libjs: Publicly expose double_to_string and rename it number_to_string
false
Publicly expose double_to_string and rename it number_to_string
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Value.cpp b/Userland/Libraries/LibJS/Runtime/Value.cpp index bf00d3780e36..7a7a0e375615 100644 --- a/Userland/Libraries/LibJS/Runtime/Value.cpp +++ b/Userland/Libraries/LibJS/Runtime/Value.cpp @@ -71,7 +71,7 @@ ALWAYS_INLINE bool both_bigint(Value const& lhs, Value const& rhs) // 6.1.6.1.20 Number::toString ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-tostring // Implementation for radix = 10 -static String double_to_string(double d) +String number_to_string(double d, NumberToStringMode mode) { auto convert_to_decimal_digits_array = [](auto x, auto& digits, auto& length) { for (; x; x /= 10) @@ -116,8 +116,12 @@ static String double_to_string(double d) if (sign) builder.append('-'); + // Non-standard: Intl needs number-to-string conversions for extremely large numbers without any + // exponential formatting, as it will handle such formatting itself in a locale-aware way. + bool force_no_exponent = mode == NumberToStringMode::WithoutExponent; + // 6. If radix ≠ 10 or n is in the inclusive interval from -5 to 21, then - if (n >= -5 && n <= 21) { + if ((n >= -5 && n <= 21) || force_no_exponent) { // a. If n ≥ k, then if (n >= k) { // i. Return the string-concatenation of: @@ -299,7 +303,7 @@ String Value::typeof() const String Value::to_string_without_side_effects() const { if (is_double()) - return double_to_string(m_value.as_double); + return number_to_string(m_value.as_double); switch (m_value.tag) { case UNDEFINED_TAG: @@ -337,7 +341,7 @@ ThrowCompletionOr<PrimitiveString*> Value::to_primitive_string(VM& vm) ThrowCompletionOr<String> Value::to_string(VM& vm) const { if (is_double()) - return double_to_string(m_value.as_double); + return number_to_string(m_value.as_double); switch (m_value.tag) { case UNDEFINED_TAG: diff --git a/Userland/Libraries/LibJS/Runtime/Value.h b/Userland/Libraries/LibJS/Runtime/Value.h index ef65ca09cc6f..f23c3dc88181 100644 --- a/Userland/Libraries/LibJS/Runtime/Value.h +++ b/Userland/Libraries/LibJS/Runtime/Value.h @@ -564,6 +564,11 @@ ThrowCompletionOr<TriState> is_less_than(VM&, Value lhs, Value rhs, bool left_fi double to_integer_or_infinity(double); +enum class NumberToStringMode { + WithExponent, + WithoutExponent, +}; +String number_to_string(double, NumberToStringMode = NumberToStringMode::WithExponent); Optional<Value> string_to_number(StringView); inline bool Value::operator==(Value const& value) const { return same_value(*this, value); }
4eb5fdcfe0897ebe73baa92682676f15305e503b
2022-01-24 08:32:35
Rummskartoffel
userspaceemulator: Support ioctls TCSETSF and TCSETSW
false
Support ioctls TCSETSF and TCSETSW
userspaceemulator
diff --git a/Userland/DevTools/UserspaceEmulator/Emulator_syscalls.cpp b/Userland/DevTools/UserspaceEmulator/Emulator_syscalls.cpp index 2cc363927b46..b4f05f16f37e 100644 --- a/Userland/DevTools/UserspaceEmulator/Emulator_syscalls.cpp +++ b/Userland/DevTools/UserspaceEmulator/Emulator_syscalls.cpp @@ -1126,7 +1126,7 @@ int Emulator::virt$ioctl([[maybe_unused]] int fd, unsigned request, [[maybe_unus mmu().copy_to_vm(arg, &termios, sizeof(termios)); return rc; } - if (request == TCSETS) { + if (request == TCSETS || request == TCSETSF || request == TCSETSW) { struct termios termios; mmu().copy_from_vm(&termios, arg, sizeof(termios)); return syscall(SC_ioctl, fd, request, &termios);
6d7d9dd3247109b9d730c047d3c85e18000bf81e
2022-01-07 02:58:01
Timothy Flynn
libunicode: Do not assume time zones & meta zones have a 1-to-1 mapping
false
Do not assume time zones & meta zones have a 1-to-1 mapping
libunicode
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp index e2d22afcbd31..102dddd920f1 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibUnicode/GenerateUnicodeDateTimeFormat.cpp @@ -519,7 +519,7 @@ struct UnicodeLocaleData { HashMap<String, HourCycleListIndexType> hour_cycles; Vector<String> hour_cycle_regions; - HashMap<String, String> meta_zones; + HashMap<String, Vector<String>> meta_zones; Vector<String> time_zones { "UTC"sv }; Vector<String> calendars; @@ -618,11 +618,12 @@ static ErrorOr<void> parse_meta_zones(String core_path, UnicodeLocaleData& local auto const& meta_zone = mapping.as_object().get("_other"sv); auto const& golden_zone = mapping.as_object().get("_type"sv); - locale_data.meta_zones.set(meta_zone.as_string(), golden_zone.as_string()); + auto& golden_zones = locale_data.meta_zones.ensure(meta_zone.as_string()); + golden_zones.append(golden_zone.as_string()); }); // UTC does not appear in metaZones.json. Define it for convenience so other parsers don't need to check for its existence. - locale_data.meta_zones.set("UTC"sv, "UTC"sv); + locale_data.meta_zones.set("UTC"sv, { "UTC"sv }); return {}; }; @@ -1402,7 +1403,7 @@ static ErrorOr<void> parse_time_zone_names(String locale_time_zone_names_path, U time_zone_formats.gmt_zero_format = locale_data.unique_strings.ensure(gmt_zero_format_string.as_string()); auto parse_time_zone = [&](StringView meta_zone, JsonObject const& meta_zone_object) { - auto const& golden_zone = locale_data.meta_zones.find(meta_zone)->value; + auto const& golden_zones = locale_data.meta_zones.find(meta_zone)->value; TimeZone time_zone {}; if (auto long_name = parse_name("long"sv, meta_zone_object); long_name.has_value()) @@ -1410,15 +1411,19 @@ static ErrorOr<void> parse_time_zone_names(String locale_time_zone_names_path, U if (auto short_name = parse_name("short"sv, meta_zone_object); short_name.has_value()) time_zone.short_name = short_name.value(); - auto time_zone_index = locale_data.time_zones.find_first_index(golden_zone).value(); - time_zones[time_zone_index] = locale_data.unique_time_zones.ensure(move(time_zone)); + for (auto const& golden_zone : golden_zones) { + auto time_zone_index = locale_data.time_zones.find_first_index(golden_zone).value(); + time_zones[time_zone_index] = locale_data.unique_time_zones.ensure(move(time_zone)); + } }; meta_zone_object.as_object().for_each_member([&](auto const& meta_zone, JsonValue const&) { - auto const& golden_zone = locale_data.meta_zones.find(meta_zone)->value; + auto const& golden_zones = locale_data.meta_zones.find(meta_zone)->value; - if (!locale_data.time_zones.contains_slow(golden_zone)) - locale_data.time_zones.append(golden_zone); + for (auto const& golden_zone : golden_zones) { + if (!locale_data.time_zones.contains_slow(golden_zone)) + locale_data.time_zones.append(golden_zone); + } }); time_zones.resize(locale_data.time_zones.size()); diff --git a/Tests/LibUnicode/CMakeLists.txt b/Tests/LibUnicode/CMakeLists.txt index 416993bb5cd0..42c89a6d804e 100644 --- a/Tests/LibUnicode/CMakeLists.txt +++ b/Tests/LibUnicode/CMakeLists.txt @@ -1,5 +1,6 @@ set(TEST_SOURCES TestUnicodeCharacterTypes.cpp + TestUnicodeDateTimeFormat.cpp TestUnicodeLocale.cpp ) diff --git a/Tests/LibUnicode/TestUnicodeDateTimeFormat.cpp b/Tests/LibUnicode/TestUnicodeDateTimeFormat.cpp new file mode 100644 index 000000000000..8cb76cecfeff --- /dev/null +++ b/Tests/LibUnicode/TestUnicodeDateTimeFormat.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022, Tim Flynn <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibTest/TestCase.h> + +#include <AK/Array.h> +#include <AK/StringView.h> +#include <LibUnicode/DateTimeFormat.h> + +TEST_CASE(time_zone_name) +{ + struct TestData { + StringView locale; + Unicode::CalendarPatternStyle style; + StringView time_zone; + StringView expected_result; + }; + + constexpr auto test_data = Array { + TestData { "en"sv, Unicode::CalendarPatternStyle::Long, "UTC"sv, "Coordinated Universal Time"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::Short, "UTC"sv, "UTC"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::ShortOffset, "UTC"sv, "GMT"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::LongOffset, "UTC"sv, "GMT"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::ShortGeneric, "UTC"sv, "GMT"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::LongGeneric, "UTC"sv, "GMT"sv }, + + TestData { "ar"sv, Unicode::CalendarPatternStyle::Long, "UTC"sv, "التوقيت العالمي المنسق"sv }, + TestData { "ar"sv, Unicode::CalendarPatternStyle::Short, "UTC"sv, "UTC"sv }, + TestData { "ar"sv, Unicode::CalendarPatternStyle::ShortOffset, "UTC"sv, "غرينتش"sv }, + TestData { "ar"sv, Unicode::CalendarPatternStyle::LongOffset, "UTC"sv, "غرينتش"sv }, + TestData { "ar"sv, Unicode::CalendarPatternStyle::ShortGeneric, "UTC"sv, "غرينتش"sv }, + TestData { "ar"sv, Unicode::CalendarPatternStyle::LongGeneric, "UTC"sv, "غرينتش"sv }, + + TestData { "en"sv, Unicode::CalendarPatternStyle::Long, "America/Los_Angeles"sv, "Pacific Daylight Time"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::Short, "America/Los_Angeles"sv, "PDT"sv }, + + TestData { "ar"sv, Unicode::CalendarPatternStyle::Long, "America/Los_Angeles"sv, "توقيت المحيط الهادي الصيفي"sv }, + // The "ar" locale does not have a short name for PDT. LibUnicode will need to fall back to GMT offset when we have that data. + + TestData { "en"sv, Unicode::CalendarPatternStyle::Long, "America/Vancouver"sv, "Pacific Daylight Time"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::Short, "America/Vancouver"sv, "PDT"sv }, + + TestData { "ar"sv, Unicode::CalendarPatternStyle::Long, "America/Vancouver"sv, "توقيت المحيط الهادي الصيفي"sv }, + // The "ar" locale does not have a short name for PDT. LibUnicode will need to fall back to GMT offset when we have that data. + + TestData { "en"sv, Unicode::CalendarPatternStyle::Long, "Europe/London"sv, "Greenwich Mean Time"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::Short, "Europe/London"sv, "GMT"sv }, + + TestData { "ar"sv, Unicode::CalendarPatternStyle::Long, "Europe/London"sv, "توقيت غرينتش"sv }, + // The "ar" locale does not have a short name for GMT. LibUnicode will need to fall back to GMT offset when we have that data. + + TestData { "en"sv, Unicode::CalendarPatternStyle::Long, "Africa/Accra"sv, "Greenwich Mean Time"sv }, + TestData { "en"sv, Unicode::CalendarPatternStyle::Short, "Africa/Accra"sv, "GMT"sv }, + + TestData { "ar"sv, Unicode::CalendarPatternStyle::Long, "Africa/Accra"sv, "توقيت غرينتش"sv }, + // The "ar" locale does not have a short name for GMT. LibUnicode will need to fall back to GMT offset when we have that data. + }; + + for (auto const& test : test_data) { + auto time_zone = Unicode::get_time_zone_name(test.locale, test.time_zone, test.style); + VERIFY(time_zone.has_value()); + EXPECT_EQ(*time_zone, test.expected_result); + } +} diff --git a/Userland/Libraries/LibUnicode/Forward.h b/Userland/Libraries/LibUnicode/Forward.h index 1ad8ffcacc8a..dc093bcd2c25 100644 --- a/Userland/Libraries/LibUnicode/Forward.h +++ b/Userland/Libraries/LibUnicode/Forward.h @@ -35,7 +35,7 @@ enum class ScriptTag : u8; enum class StandardNumberFormatType : u8; enum class Style : u8; enum class Territory : u8; -enum class TimeZone : u8; +enum class TimeZone : u16; enum class Weekday : u8; enum class WordBreakProperty : u8;
2c023157e94f6ef8374ae9245eb3a8f85779c294
2021-07-24 03:36:57
Timothy Flynn
libjs: Implement RegExp.prototype [ @@match ] with UTF-16 code units
false
Implement RegExp.prototype [ @@match ] with UTF-16 code units
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp index 8b900878278d..5373735c0d69 100644 --- a/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/RegExpPrototype.cpp @@ -112,7 +112,7 @@ size_t advance_string_index(String const& string, size_t index, bool unicode) return advance_string_index(utf16_string_view, index, unicode); } -static void increment_last_index(GlobalObject& global_object, Object& regexp_object, String const& string, bool unicode) +static void increment_last_index(GlobalObject& global_object, Object& regexp_object, Utf16View const& string, bool unicode) { auto& vm = global_object.vm(); @@ -127,6 +127,14 @@ static void increment_last_index(GlobalObject& global_object, Object& regexp_obj regexp_object.set(vm.names.lastIndex, Value(last_index), Object::ShouldThrowExceptions::Yes); } +static void increment_last_index(GlobalObject& global_object, Object& regexp_object, String const& string, bool unicode) +{ + auto utf16_string = AK::utf8_to_utf16(string); + Utf16View utf16_string_view { utf16_string }; + + return increment_last_index(global_object, regexp_object, utf16_string_view, unicode); +} + // 1.1.2.1 Match Records, https://tc39.es/proposal-regexp-match-indices/#sec-match-records struct Match { static Match create(regex::Match const& match) @@ -485,9 +493,11 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match) auto* regexp_object = this_object_from(vm, global_object); if (!regexp_object) return {}; - auto s = vm.argument(0).to_string(global_object); + + auto string = vm.argument(0).to_utf16_string(global_object); if (vm.exception()) return {}; + Utf16View string_view { string }; auto global_value = regexp_object->get(vm.names.global); if (vm.exception()) @@ -495,7 +505,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match) bool global = global_value.to_boolean(); if (!global) { - auto result = regexp_exec(global_object, *regexp_object, s); + auto result = regexp_exec(global_object, *regexp_object, string_view); if (vm.exception()) return {}; return result; @@ -517,7 +527,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match) size_t n = 0; while (true) { - auto result = regexp_exec(global_object, *regexp_object, s); + auto result = regexp_exec(global_object, *regexp_object, string_view); if (vm.exception()) return {}; @@ -542,7 +552,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match) return {}; if (match_str.is_empty()) { - increment_last_index(global_object, *regexp_object, s, unicode); + increment_last_index(global_object, *regexp_object, string_view, unicode); if (vm.exception()) return {}; } @@ -558,7 +568,7 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::symbol_match_all) if (!regexp_object) return {}; - auto string = vm.argument(0).to_string(global_object); + auto string = vm.argument(0).to_utf16_string(global_object); if (vm.exception()) return {}; diff --git a/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.cpp b/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.cpp index ed5a0bcdd285..2a6508811e53 100644 --- a/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.cpp +++ b/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.cpp @@ -10,12 +10,12 @@ namespace JS { // 22.2.7.1 CreateRegExpStringIterator ( R, S, global, fullUnicode ), https://tc39.es/ecma262/#sec-createregexpstringiterator -RegExpStringIterator* RegExpStringIterator::create(GlobalObject& global_object, Object& regexp_object, String string, bool global, bool unicode) +RegExpStringIterator* RegExpStringIterator::create(GlobalObject& global_object, Object& regexp_object, Vector<u16> string, bool global, bool unicode) { return global_object.heap().allocate<RegExpStringIterator>(global_object, *global_object.regexp_string_iterator_prototype(), regexp_object, move(string), global, unicode); } -RegExpStringIterator::RegExpStringIterator(Object& prototype, Object& regexp_object, String string, bool global, bool unicode) +RegExpStringIterator::RegExpStringIterator(Object& prototype, Object& regexp_object, Vector<u16> string, bool global, bool unicode) : Object(prototype) , m_regexp_object(regexp_object) , m_string(move(string)) diff --git a/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.h b/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.h index fec3bd44e36b..849d3a0669c3 100644 --- a/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.h +++ b/Userland/Libraries/LibJS/Runtime/RegExpStringIterator.h @@ -6,6 +6,7 @@ #pragma once +#include <AK/Utf16View.h> #include <LibJS/Runtime/Object.h> namespace JS { @@ -14,13 +15,13 @@ class RegExpStringIterator final : public Object { JS_OBJECT(RegExpStringIterator, Object); public: - static RegExpStringIterator* create(GlobalObject&, Object& regexp_object, String string, bool global, bool unicode); + static RegExpStringIterator* create(GlobalObject&, Object& regexp_object, Vector<u16> string, bool global, bool unicode); - explicit RegExpStringIterator(Object& prototype, Object& regexp_object, String string, bool global, bool unicode); + explicit RegExpStringIterator(Object& prototype, Object& regexp_object, Vector<u16> string, bool global, bool unicode); virtual ~RegExpStringIterator() override = default; Object& regexp_object() { return m_regexp_object; } - String const& string() const { return m_string; } + Utf16View string() const { return Utf16View { m_string }; } bool global() const { return m_global; } bool unicode() const { return m_unicode; } @@ -31,7 +32,7 @@ class RegExpStringIterator final : public Object { virtual void visit_edges(Cell::Visitor&) override; Object& m_regexp_object; - String m_string; + Vector<u16> m_string; bool m_global { false }; bool m_unicode { false }; bool m_done { false }; diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp index b6e7a934b404..549d82e5083e 100644 --- a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -839,13 +839,16 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::match) if (vm.exception()) return {}; } - auto s = this_object.to_string(global_object); + + auto string = this_object.to_utf16_string(global_object); if (vm.exception()) return {}; + Utf16View utf16_string_view { string }; + auto rx = regexp_create(global_object, regexp, js_undefined()); if (!rx) return {}; - return rx->invoke(*vm.well_known_symbol_match(), js_string(vm, s)); + return rx->invoke(*vm.well_known_symbol_match(), js_string(vm, utf16_string_view)); } // 22.1.3.12 String.prototype.matchAll ( regexp ), https://tc39.es/ecma262/#sec-string.prototype.matchall @@ -879,13 +882,16 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::match_all) if (vm.exception()) return {}; } - auto s = this_object.to_string(global_object); + + auto string = this_object.to_utf16_string(global_object); if (vm.exception()) return {}; + Utf16View utf16_string_view { string }; + auto rx = regexp_create(global_object, regexp, js_string(vm, "g")); if (!rx) return {}; - return rx->invoke(*vm.well_known_symbol_match_all(), js_string(vm, s)); + return rx->invoke(*vm.well_known_symbol_match_all(), js_string(vm, utf16_string_view)); } // 22.1.3.17 String.prototype.replace ( searchValue, replaceValue ), https://tc39.es/ecma262/#sec-string.prototype.replace diff --git a/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.match.js b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.match.js index da503927aec6..9a04eae26cac 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.match.js +++ b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.match.js @@ -45,3 +45,13 @@ test("override exec with non-function", () => { re.exec = 3; expect("test".match(re)).not.toBeNull(); }); + +test("UTF-16", () => { + expect("😀".match("foo")).toBeNull(); + expect("😀".match("\ud83d")).toEqual(["\ud83d"]); + expect("😀".match("\ude00")).toEqual(["\ude00"]); + expect("😀😀".match("\ud83d")).toEqual(["\ud83d"]); + expect("😀😀".match("\ude00")).toEqual(["\ude00"]); + expect("😀😀".match(/\ud83d/g)).toEqual(["\ud83d", "\ud83d"]); + expect("😀😀".match(/\ude00/g)).toEqual(["\ude00", "\ude00"]); +}); diff --git a/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.matchAll.js b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.matchAll.js index dbc6ccf9647c..a94dbfd94f5f 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.matchAll.js +++ b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.matchAll.js @@ -76,3 +76,63 @@ test("basic functionality", () => { expect(next.value).toBeUndefined(); } }); + +test("UTF-16", () => { + { + var iterator = "😀".matchAll("foo"); + + var next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } + { + var iterator = "😀".matchAll("\ud83d"); + + var next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["\ud83d"]); + expect(next.value.index).toBe(0); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } + { + var iterator = "😀😀".matchAll("\ud83d"); + + var next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["\ud83d"]); + expect(next.value.index).toBe(0); + + next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["\ud83d"]); + expect(next.value.index).toBe(2); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } + { + var iterator = "😀😀".matchAll("\ude00"); + + var next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["\ude00"]); + expect(next.value.index).toBe(1); + + next = iterator.next(); + expect(next.done).toBeFalse(); + expect(next.value).toEqual(["\ude00"]); + expect(next.value.index).toBe(3); + + next = iterator.next(); + expect(next.done).toBeTrue(); + expect(next.value).toBeUndefined(); + } +});
2df4d977e2060358a1b1261dc24804292bc39810
2021-07-16 14:45:30
Luke
kernel: Return ENOMEM on allocation failures in FramebufferDevice::mmap
false
Return ENOMEM on allocation failures in FramebufferDevice::mmap
kernel
diff --git a/Kernel/Graphics/FramebufferDevice.cpp b/Kernel/Graphics/FramebufferDevice.cpp index fad2e4e2c426..182e4ebc3456 100644 --- a/Kernel/Graphics/FramebufferDevice.cpp +++ b/Kernel/Graphics/FramebufferDevice.cpp @@ -43,9 +43,20 @@ KResultOr<Region*> FramebufferDevice::mmap(Process& process, FileDescription&, c m_userspace_real_framebuffer_vmobject = vmobject; m_real_framebuffer_vmobject = AnonymousVMObject::try_create_for_physical_range(m_framebuffer_address, page_round_up(framebuffer_size_in_bytes())); + if (!m_real_framebuffer_vmobject) + return ENOMEM; + m_swapped_framebuffer_vmobject = AnonymousVMObject::try_create_with_size(page_round_up(framebuffer_size_in_bytes()), AllocationStrategy::AllocateNow); + if (!m_swapped_framebuffer_vmobject) + return ENOMEM; + m_real_framebuffer_region = MM.allocate_kernel_region_with_vmobject(*m_real_framebuffer_vmobject, page_round_up(framebuffer_size_in_bytes()), "Framebuffer", Region::Access::Read | Region::Access::Write); + if (!m_real_framebuffer_region) + return ENOMEM; + m_swapped_framebuffer_region = MM.allocate_kernel_region_with_vmobject(*m_swapped_framebuffer_vmobject, page_round_up(framebuffer_size_in_bytes()), "Framebuffer Swap (Blank)", Region::Access::Read | Region::Access::Write); + if (!m_swapped_framebuffer_region) + return ENOMEM; RefPtr<VMObject> chosen_vmobject; if (m_graphical_writes_enabled) {
77a135491e993c1a3fa392e10bea222cd024d54d
2022-08-18 14:29:06
djwisdom
base: Add new globe emojis U+1F30D-U+1F30F
false
Add new globe emojis U+1F30D-U+1F30F
base
diff --git a/Base/home/anon/Documents/emoji.txt b/Base/home/anon/Documents/emoji.txt index 9e50c572f5ac..43681c637745 100644 --- a/Base/home/anon/Documents/emoji.txt +++ b/Base/home/anon/Documents/emoji.txt @@ -27,6 +27,9 @@ Faces & Misc Emoji 🉑 - U+1F251 JAPANESE “ACCEPTABLE” BUTTON 🌈 - U+1F308 RAINBOW 🌋 - U+1F30B VOLCANO +🌍 - U+1F30D GLOBE SHOWING EUROPE-AFRICA +🌎 - U+1F30E GLOBE SHOWING AMERICAS +🌏 - U+1F30F GLOBE SHOWING ASIA-AUSTRALIA 🌑 - U+1F311 NEW MOON 🌒 - U+1F312 WAXING CRESCENT MOON 🌓 - U+1F313 FIRST QUARTER MOON diff --git a/Base/res/emoji/U+1F30D.png b/Base/res/emoji/U+1F30D.png new file mode 100644 index 000000000000..424bdf761a22 Binary files /dev/null and b/Base/res/emoji/U+1F30D.png differ diff --git a/Base/res/emoji/U+1F30E.png b/Base/res/emoji/U+1F30E.png new file mode 100644 index 000000000000..895d1f4be922 Binary files /dev/null and b/Base/res/emoji/U+1F30E.png differ diff --git a/Base/res/emoji/U+1F30F.png b/Base/res/emoji/U+1F30F.png new file mode 100644 index 000000000000..003c8641ee74 Binary files /dev/null and b/Base/res/emoji/U+1F30F.png differ
175cd4d9c2b17ab5d0648c4fe77b5247aceee5e4
2020-02-15 17:58:33
Andreas Kling
ak: Fix broken #include statement
false
Fix broken #include statement
ak
diff --git a/AK/kstdio.h b/AK/kstdio.h index d0d15068ef44..bca1051ba6f1 100644 --- a/AK/kstdio.h +++ b/AK/kstdio.h @@ -27,7 +27,7 @@ #pragma once #ifdef __serenity__ -# include <Libraries/LibBareMetal/Output/kstdio.h> +# include <LibBareMetal/Output/kstdio.h> #else #include <stdio.h> #define kprintf printf
d610aeb5daf17a39533eb10b71d148338edea1d8
2021-04-12 12:27:44
Timothy Flynn
browser: Parse cookie attribute name-value pairs
false
Parse cookie attribute name-value pairs
browser
diff --git a/Userland/Applications/Browser/CookieJar.cpp b/Userland/Applications/Browser/CookieJar.cpp index df58b9d5cd66..85b84bf35625 100644 --- a/Userland/Applications/Browser/CookieJar.cpp +++ b/Userland/Applications/Browser/CookieJar.cpp @@ -88,14 +88,14 @@ Optional<Cookie> CookieJar::parse_cookie(const String& cookie_string) { // https://tools.ietf.org/html/rfc6265#section-5.2 StringView name_value_pair; + StringView unparsed_attributes; // 1. If the set-cookie-string contains a %x3B (";") character: if (auto position = cookie_string.find(';'); position.has_value()) { // The name-value-pair string consists of the characters up to, but not including, the first %x3B (";"), and the unparsed- // attributes consist of the remainder of the set-cookie-string (including the %x3B (";") in question). - - // FIXME: Support optional cookie attributes. For now, ignore those attributes. name_value_pair = cookie_string.substring_view(0, position.value()); + unparsed_attributes = cookie_string.substring_view(position.value()); } else { // The name-value-pair string consists of all the characters contained in the set-cookie-string, and the unparsed- // attributes is the empty string. @@ -126,7 +126,107 @@ Optional<Cookie> CookieJar::parse_cookie(const String& cookie_string) return {}; // 6. The cookie-name is the name string, and the cookie-value is the value string. - return Cookie { name, value }; + Cookie cookie { name, value }; + + parse_attributes(cookie, unparsed_attributes); + return cookie; +} + +void CookieJar::parse_attributes(Cookie& cookie, StringView unparsed_attributes) +{ + // 1. If the unparsed-attributes string is empty, skip the rest of these steps. + if (unparsed_attributes.is_empty()) + return; + + // 2. Discard the first character of the unparsed-attributes (which will be a %x3B (";") character). + unparsed_attributes = unparsed_attributes.substring_view(1); + + StringView cookie_av; + + // 3. If the remaining unparsed-attributes contains a %x3B (";") character: + if (auto position = unparsed_attributes.find(';'); position.has_value()) { + // Consume the characters of the unparsed-attributes up to, but not including, the first %x3B (";") character. + cookie_av = unparsed_attributes.substring_view(0, position.value()); + unparsed_attributes = unparsed_attributes.substring_view(position.value()); + } else { + // Consume the remainder of the unparsed-attributes. + cookie_av = unparsed_attributes; + unparsed_attributes = {}; + } + + StringView attribute_name; + StringView attribute_value; + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (auto position = cookie_av.find('='); position.has_value()) { + // The (possibly empty) attribute-name string consists of the characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string consists of the characters after the first %x3D ("=") character. + attribute_name = cookie_av.substring_view(0, position.value()); + + if (position.value() < cookie_av.length() - 1) + attribute_value = cookie_av.substring_view(position.value() + 1); + } else { + // The attribute-name string consists of the entire cookie-av string, and the attribute-value string is empty. + attribute_name = cookie_av; + } + + // 5. Remove any leading or trailing WSP characters from the attribute-name string and the attribute-value string. + attribute_name = attribute_name.trim_whitespace(); + attribute_value = attribute_value.trim_whitespace(); + + // 6. Process the attribute-name and attribute-value according to the requirements in the following subsections. + // (Notice that attributes with unrecognized attribute-names are ignored.) + process_attribute(cookie, attribute_name, attribute_value); + + // 7. Return to Step 1 of this algorithm. + parse_attributes(cookie, unparsed_attributes); +} + +void CookieJar::process_attribute(Cookie& cookie, StringView attribute_name, StringView attribute_value) +{ + if (attribute_name.equals_ignoring_case("Expires")) { + on_expires_attribute(cookie, attribute_value); + } else if (attribute_name.equals_ignoring_case("Max-Age")) { + on_max_age_attribute(cookie, attribute_value); + } else if (attribute_name.equals_ignoring_case("Domain")) { + on_domain_attribute(cookie, attribute_value); + } else if (attribute_name.equals_ignoring_case("Path")) { + on_path_attribute(cookie, attribute_value); + } else if (attribute_name.equals_ignoring_case("Secure")) { + on_secure_attribute(cookie, attribute_value); + } else if (attribute_name.equals_ignoring_case("HttpOnly")) { + on_http_only_attribute(cookie, attribute_value); + } +} + +void CookieJar::on_expires_attribute([[maybe_unused]] Cookie& cookie, [[maybe_unused]] StringView attribute_value) +{ + // https://tools.ietf.org/html/rfc6265#section-5.2.1 +} + +void CookieJar::on_max_age_attribute([[maybe_unused]] Cookie& cookie, [[maybe_unused]] StringView attribute_value) +{ + // https://tools.ietf.org/html/rfc6265#section-5.2.2 +} + +void CookieJar::on_domain_attribute([[maybe_unused]] Cookie& cookie, [[maybe_unused]] StringView attribute_value) +{ + // https://tools.ietf.org/html/rfc6265#section-5.2.3 +} + +void CookieJar::on_path_attribute([[maybe_unused]] Cookie& cookie, [[maybe_unused]] StringView attribute_value) +{ + // https://tools.ietf.org/html/rfc6265#section-5.2.4 +} + +void CookieJar::on_secure_attribute([[maybe_unused]] Cookie& cookie, [[maybe_unused]] StringView attribute_value) +{ + // https://tools.ietf.org/html/rfc6265#section-5.2.5 +} + +void CookieJar::on_http_only_attribute([[maybe_unused]] Cookie& cookie, [[maybe_unused]] StringView attribute_value) +{ + // https://tools.ietf.org/html/rfc6265#section-5.2.6 } } diff --git a/Userland/Applications/Browser/CookieJar.h b/Userland/Applications/Browser/CookieJar.h index 70a592de9402..cab0ade3a276 100644 --- a/Userland/Applications/Browser/CookieJar.h +++ b/Userland/Applications/Browser/CookieJar.h @@ -46,6 +46,14 @@ class CookieJar { private: static Optional<String> canonicalize_domain(const URL& url); static Optional<Cookie> parse_cookie(const String& cookie_string); + static void parse_attributes(Cookie& cookie, StringView unparsed_attributes); + static void process_attribute(Cookie& cookie, StringView attribute_name, StringView attribute_value); + static void on_expires_attribute(Cookie& cookie, StringView attribute_value); + static void on_max_age_attribute(Cookie& cookie, StringView attribute_value); + static void on_domain_attribute(Cookie& cookie, StringView attribute_value); + static void on_path_attribute(Cookie& cookie, StringView attribute_value); + static void on_secure_attribute(Cookie& cookie, StringView attribute_value); + static void on_http_only_attribute(Cookie& cookie, StringView attribute_value); HashMap<String, Vector<Cookie>> m_cookies; };
a8d39bc0707ffa23d4eaf476767bf891201d4056
2021-10-31 21:50:37
Idan Horowitz
libweb: Convert WebAssemblyObject functions to ThrowCompletionOr
false
Convert WebAssemblyObject functions to ThrowCompletionOr
libweb
diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp index 69d73dbf5d78..18502d1f331a 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.cpp @@ -35,9 +35,9 @@ void WebAssemblyObject::initialize(JS::GlobalObject& global_object) Object::initialize(global_object); u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable; - define_old_native_function("validate", validate, 1, attr); - define_old_native_function("compile", compile, 1, attr); - define_old_native_function("instantiate", instantiate, 1, attr); + define_native_function("validate", validate, 1, attr); + define_native_function("compile", compile, 1, attr); + define_native_function("instantiate", instantiate, 1, attr); auto& vm = global_object.vm(); @@ -87,7 +87,7 @@ void WebAssemblyObject::visit_edges(Visitor& visitor) } } -JS_DEFINE_OLD_NATIVE_FUNCTION(WebAssemblyObject::validate) +JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::validate) { // FIXME: Implement this once module validation is implemented in LibWasm. dbgln("Hit WebAssemblyObject::validate() stub!"); @@ -127,7 +127,7 @@ JS::ThrowCompletionOr<size_t> parse_module(JS::GlobalObject& global_object, JS:: return WebAssemblyObject::s_compiled_modules.size() - 1; } -JS_DEFINE_OLD_NATIVE_FUNCTION(WebAssemblyObject::compile) +JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::compile) { // FIXME: This shouldn't block! auto buffer_or_error = vm.argument(0).to_object(global_object); @@ -291,7 +291,7 @@ JS::ThrowCompletionOr<size_t> WebAssemblyObject::instantiate_module(Wasm::Module return s_instantiated_modules.size() - 1; } -JS_DEFINE_OLD_NATIVE_FUNCTION(WebAssemblyObject::instantiate) +JS_DEFINE_NATIVE_FUNCTION(WebAssemblyObject::instantiate) { // FIXME: This shouldn't block! auto buffer_or_error = vm.argument(0).to_object(global_object); diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.h b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.h index a421643973bc..834c2cc82648 100644 --- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.h +++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyObject.h @@ -60,9 +60,9 @@ class WebAssemblyObject final : public JS::Object { static Wasm::AbstractMachine s_abstract_machine; private: - JS_DECLARE_OLD_NATIVE_FUNCTION(validate); - JS_DECLARE_OLD_NATIVE_FUNCTION(compile); - JS_DECLARE_OLD_NATIVE_FUNCTION(instantiate); + JS_DECLARE_NATIVE_FUNCTION(validate); + JS_DECLARE_NATIVE_FUNCTION(compile); + JS_DECLARE_NATIVE_FUNCTION(instantiate); }; class WebAssemblyMemoryObject final : public JS::Object {
84c4702b104e8d9da93c9552dc26325caf5eff50
2025-01-26 22:00:00
Jelle Raaijmakers
libweb: Handle continuation chain during hit-testing instead of after it
false
Handle continuation chain during hit-testing instead of after it
libweb
diff --git a/Libraries/LibWeb/Painting/PaintableBox.cpp b/Libraries/LibWeb/Painting/PaintableBox.cpp index 63ba7ffe015f..aa943dd4887a 100644 --- a/Libraries/LibWeb/Painting/PaintableBox.cpp +++ b/Libraries/LibWeb/Painting/PaintableBox.cpp @@ -965,12 +965,36 @@ TraversalDecision PaintableBox::hit_test(CSSPixelPoint position, HitTestType typ return TraversalDecision::Break; } + if (!visible_for_hit_testing()) + return TraversalDecision::Continue; + if (!absolute_border_box_rect().contains(position_adjusted_by_scroll_offset)) return TraversalDecision::Continue; + if (hit_test_continuation(callback) == TraversalDecision::Break) + return TraversalDecision::Break; + return callback(HitTestResult { const_cast<PaintableBox&>(*this) }); } +TraversalDecision PaintableBox::hit_test_continuation(Function<TraversalDecision(HitTestResult)> const& callback) const +{ + // If we're hit testing the "middle" part of a continuation chain, we are dealing with an anonymous box that is + // linked to a parent inline node. Since our block element children did not match the hit test, but we did, we + // should walk the continuation chain up to the inline parent and return a hit on that instead. + auto continuation_node = layout_node_with_style_and_box_metrics().continuation_of_node(); + if (!continuation_node || !layout_node().is_anonymous()) + return TraversalDecision::Continue; + + while (continuation_node->continuation_of_node()) + continuation_node = continuation_node->continuation_of_node(); + auto& paintable = *continuation_node->first_paintable(); + if (!paintable.visible_for_hit_testing()) + return TraversalDecision::Continue; + + return callback(HitTestResult { paintable }); +} + Optional<HitTestResult> PaintableBox::hit_test(CSSPixelPoint position, HitTestType type) const { Optional<HitTestResult> result; @@ -985,28 +1009,6 @@ Optional<HitTestResult> PaintableBox::hit_test(CSSPixelPoint position, HitTestTy return TraversalDecision::Break; return TraversalDecision::Continue; }); - - // If our hit-testing has resulted in a hit on a paintable, we know that it is the most specific hit. If that - // paintable turns out to be invisible for hit-testing, we need to traverse up the paintable tree to find the next - // paintable that is visible for hit-testing. This implements the behavior expected for pointer-events. - while (result.has_value() && !result->paintable->visible_for_hit_testing()) { - result->index_in_node = result->paintable->dom_node() ? result->paintable->dom_node()->index() : 0; - result->paintable = result->paintable->parent(); - - // If the new parent is an anonymous box part of a continuation, we need to follow the chain to the inline node - // that spawned the anonymous "middle" part of the continuation, since that inline node is the actual parent. - if (is<PaintableBox>(*result->paintable)) { - auto const& box_layout_node = static_cast<PaintableBox&>(*result->paintable).layout_node_with_style_and_box_metrics(); - if (box_layout_node.is_anonymous() && box_layout_node.continuation_of_node()) { - auto const* original_inline_node = &box_layout_node; - while (original_inline_node->continuation_of_node()) - original_inline_node = original_inline_node->continuation_of_node(); - - result->paintable = const_cast<Paintable*>(original_inline_node->first_paintable()); - } - } - } - return result; } @@ -1048,6 +1050,9 @@ TraversalDecision PaintableWithLines::hit_test(CSSPixelPoint position, HitTestTy return TraversalDecision::Break; } + if (!visible_for_hit_testing()) + return TraversalDecision::Continue; + for (auto const& fragment : fragments()) { if (fragment.paintable().has_stacking_context()) continue; diff --git a/Libraries/LibWeb/Painting/PaintableBox.h b/Libraries/LibWeb/Painting/PaintableBox.h index 6f57db8530a0..e67282fe4601 100644 --- a/Libraries/LibWeb/Painting/PaintableBox.h +++ b/Libraries/LibWeb/Painting/PaintableBox.h @@ -144,6 +144,7 @@ class PaintableBox : public Paintable [[nodiscard]] virtual TraversalDecision hit_test(CSSPixelPoint position, HitTestType type, Function<TraversalDecision(HitTestResult)> const& callback) const override; Optional<HitTestResult> hit_test(CSSPixelPoint, HitTestType) const; + [[nodiscard]] TraversalDecision hit_test_continuation(Function<TraversalDecision(HitTestResult)> const& callback) const; virtual bool handle_mousewheel(Badge<EventHandler>, CSSPixelPoint, unsigned buttons, unsigned modifiers, int wheel_delta_x, int wheel_delta_y) override; diff --git a/Tests/LibWeb/Text/expected/hit_testing/pointer-events-no-parent-extension.txt b/Tests/LibWeb/Text/expected/hit_testing/pointer-events-no-parent-extension.txt new file mode 100644 index 000000000000..a64aa53366cf --- /dev/null +++ b/Tests/LibWeb/Text/expected/hit_testing/pointer-events-no-parent-extension.txt @@ -0,0 +1,2 @@ +<HTML> +<#document> diff --git a/Tests/LibWeb/Text/input/hit_testing/pointer-events-no-parent-extension.html b/Tests/LibWeb/Text/input/hit_testing/pointer-events-no-parent-extension.html new file mode 100644 index 000000000000..93c0f4bb15af --- /dev/null +++ b/Tests/LibWeb/Text/input/hit_testing/pointer-events-no-parent-extension.html @@ -0,0 +1,15 @@ +<script src="../include.js"></script> +<body> + <div> + <!-- this div should not be hit, nor should its parent --> + <div id="a1" style="position: fixed; width: 100px; height: 100px; pointer-events: none"></div> + foobar + </div> +</body> +<script> + test(() => { + const hit = internals.hitTest(a1.offsetLeft + 50, a1.offsetTop + 80); + printElement(hit.node); + printElement(hit.node.parentNode); + }); +</script>
a08292d76c4a616ff00c66299dd24d4be51fd593
2021-09-25 21:21:30
Linus Groh
libjs: Move has_simple_parameter_list to ECMAScriptFunctionObject
false
Move has_simple_parameter_list to ECMAScriptFunctionObject
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp index 2d9f6eef35cd..7a0c6e60672e 100644 --- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp @@ -58,7 +58,7 @@ ECMAScriptFunctionObject::ECMAScriptFunctionObject(GlobalObject& global_object, m_this_mode = ThisMode::Global; // 15.1.3 Static Semantics: IsSimpleParameterList, https://tc39.es/ecma262/#sec-static-semantics-issimpleparameterlist - set_has_simple_parameter_list(all_of(m_formal_parameters, [&](auto& parameter) { + m_has_simple_parameter_list = all_of(m_formal_parameters, [&](auto& parameter) { if (parameter.is_rest) return false; if (parameter.default_value) @@ -66,7 +66,7 @@ ECMAScriptFunctionObject::ECMAScriptFunctionObject(GlobalObject& global_object, if (!parameter.binding.template has<FlyString>()) return false; return true; - })); + }); } void ECMAScriptFunctionObject::initialize(GlobalObject& global_object) diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h index a620e67aa7fd..efca06b07614 100644 --- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h +++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.h @@ -68,6 +68,9 @@ class ECMAScriptFunctionObject final : public FunctionObject { Vector<InstanceField> const& fields() const { return m_fields; } void add_field(StringOrSymbol property_key, ECMAScriptFunctionObject* initializer) { m_fields.empend(property_key, initializer); } + // This is for IsSimpleParameterList (static semantics) + bool has_simple_parameter_list() const { return m_has_simple_parameter_list; } + protected: virtual bool is_strict_mode() const final { return m_strict; } @@ -95,6 +98,7 @@ class ECMAScriptFunctionObject final : public FunctionObject { i32 m_function_length { 0 }; FunctionKind m_kind { FunctionKind::Regular }; bool m_is_arrow_function { false }; + bool m_has_simple_parameter_list { false }; }; } diff --git a/Userland/Libraries/LibJS/Runtime/FunctionObject.h b/Userland/Libraries/LibJS/Runtime/FunctionObject.h index ca41124d646a..ec8bedf6656e 100644 --- a/Userland/Libraries/LibJS/Runtime/FunctionObject.h +++ b/Userland/Libraries/LibJS/Runtime/FunctionObject.h @@ -39,22 +39,16 @@ class FunctionObject : public Object { // [[Realm]] virtual Realm* realm() const { return nullptr; } - // This is for IsSimpleParameterList (static semantics) - bool has_simple_parameter_list() const { return m_has_simple_parameter_list; } - protected: virtual void visit_edges(Visitor&) override; explicit FunctionObject(Object& prototype); FunctionObject(Value bound_this, Vector<Value> bound_arguments, Object& prototype); - void set_has_simple_parameter_list(bool b) { m_has_simple_parameter_list = b; } - private: virtual bool is_function() const override { return true; } Value m_bound_this; Vector<Value> m_bound_arguments; - bool m_has_simple_parameter_list { false }; }; } diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp index 4622e608591b..08ae93bbb3e5 100644 --- a/Userland/Libraries/LibJS/Runtime/VM.cpp +++ b/Userland/Libraries/LibJS/Runtime/VM.cpp @@ -374,7 +374,7 @@ Value VM::get_variable(const FlyString& name, GlobalObject& global_object) if (possible_match.has_value()) return possible_match.value().value; if (!context.arguments_object) { - if (context.function->is_strict_mode() || !context.function->has_simple_parameter_list()) { + if (context.function->is_strict_mode() || (is<ECMAScriptFunctionObject>(context.function) && !static_cast<ECMAScriptFunctionObject*>(context.function)->has_simple_parameter_list())) { context.arguments_object = create_unmapped_arguments_object(global_object, context.arguments.span()); } else { context.arguments_object = create_mapped_arguments_object(global_object, *context.function, verify_cast<ECMAScriptFunctionObject>(context.function)->formal_parameters(), context.arguments.span(), *lexical_environment());
543890c5c97d4b664e629c7252eb9a1db22c65ae
2022-12-11 22:44:54
Ali Mohammad Pur
ak: Add a fallible StringBuilder::create() factory function
false
Add a fallible StringBuilder::create() factory function
ak
diff --git a/AK/StringBuilder.cpp b/AK/StringBuilder.cpp index 932699e208d1..ad161a2e1ea5 100644 --- a/AK/StringBuilder.cpp +++ b/AK/StringBuilder.cpp @@ -36,6 +36,13 @@ inline ErrorOr<void> StringBuilder::will_append(size_t size) return {}; } +ErrorOr<StringBuilder> StringBuilder::create(size_t initial_capacity) +{ + StringBuilder builder; + TRY(builder.m_buffer.try_ensure_capacity(initial_capacity)); + return builder; +} + StringBuilder::StringBuilder(size_t initial_capacity) { m_buffer.ensure_capacity(initial_capacity); diff --git a/AK/StringBuilder.h b/AK/StringBuilder.h index 78790d9c2234..5e28ef030099 100644 --- a/AK/StringBuilder.h +++ b/AK/StringBuilder.h @@ -18,6 +18,8 @@ class StringBuilder { public: using OutputType = DeprecatedString; + static ErrorOr<StringBuilder> create(size_t initial_capacity = inline_capacity); + explicit StringBuilder(size_t initial_capacity = inline_capacity); ~StringBuilder() = default;
c08f059340a32cb517a3bd05e43c23f17f350522
2023-01-19 03:28:42
konrad
kernel: Add CPUFeature enumeration for Aarch64 CPUs
false
Add CPUFeature enumeration for Aarch64 CPUs
kernel
diff --git a/Kernel/Arch/aarch64/CPUID.cpp b/Kernel/Arch/aarch64/CPUID.cpp new file mode 100644 index 000000000000..4dbc3f29f165 --- /dev/null +++ b/Kernel/Arch/aarch64/CPUID.cpp @@ -0,0 +1,1007 @@ +/* + * Copyright (c) 2023, Konrad <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <Kernel/Arch/aarch64/CPUID.h> + +namespace Kernel { + +// https://developer.arm.com/downloads/-/exploration-tools/feature-names-for-a-profile +StringView cpu_feature_to_name(CPUFeature::Type const& feature) +{ + // 2022 Architecture Extensions + if (feature == CPUFeature::ABLE) + return "ABLE"sv; + if (feature == CPUFeature::ADERR) + return "ADERR"sv; + if (feature == CPUFeature::ANERR) + return "ANERR"sv; + if (feature == CPUFeature::AIE) + return "AIE"sv; + if (feature == CPUFeature::B16B16) + return "B16B16"sv; + if (feature == CPUFeature::CLRBHB) + return "CLRBHB"sv; + if (feature == CPUFeature::CHK) + return "CHK"sv; + if (feature == CPUFeature::CSSC) + return "CSSC"sv; + if (feature == CPUFeature::CSV2_2) + return "CSV2_2"sv; + if (feature == CPUFeature::CSV2_3) + return "CSV2_3"sv; + if (feature == CPUFeature::D128) + return "D128"sv; + if (feature == CPUFeature::Debugv8p9) + return "Debugv8p9"sv; + if (feature == CPUFeature::DoubleFault2) + return "DoubleFault2"sv; + if (feature == CPUFeature::EBEP) + return "EBEP"sv; + if (feature == CPUFeature::ECBHB) + return "ECBHB"sv; + if (feature == CPUFeature::ETEv1p3) + return "ETEv1p3"sv; + if (feature == CPUFeature::FGT2) + return "FGT2"sv; + if (feature == CPUFeature::GCS) + return "GCS"sv; + if (feature == CPUFeature::HAFT) + return "HAFT"sv; + if (feature == CPUFeature::ITE) + return "ITE"sv; + if (feature == CPUFeature::LRCPC3) + return "LRCPC3"sv; + if (feature == CPUFeature::LSE128) + return "LSE128"sv; + if (feature == CPUFeature::LVA3) + return "LVA3"sv; + if (feature == CPUFeature::MEC) + return "MEC"sv; + if (feature == CPUFeature::MTE4) + return "MTE4"sv; + if (feature == CPUFeature::MTE_CANONICAL_TAGS) + return "MTE_CANONICAL_TAGS"sv; + if (feature == CPUFeature::MTE_TAGGED_FAR) + return "MTE_TAGGED_FAR"sv; + if (feature == CPUFeature::MTE_STORE_ONLY) + return "MTE_STORE_ONLY"sv; + if (feature == CPUFeature::MTE_NO_ADDRESS_TAGS) + return "MTE_NO_ADDRESS_TAGS"sv; + if (feature == CPUFeature::MTE_ASYM_FAULT) + return "MTE_ASYM_FAULT"sv; + if (feature == CPUFeature::MTE_ASYNC) + return "MTE_ASYNC"sv; + if (feature == CPUFeature::MTE_PERM) + return "MTE_PERM"sv; + if (feature == CPUFeature::PCSRv8p9) + return "PCSRv8p9"sv; + if (feature == CPUFeature::PIE) + return "PIE"sv; + if (feature == CPUFeature::POE) + return "POE"sv; + if (feature == CPUFeature::S1PIE) + return "S1PIE"sv; + if (feature == CPUFeature::S2PIE) + return "S2PIE"sv; + if (feature == CPUFeature::S1POE) + return "S1POE"sv; + if (feature == CPUFeature::S2POE) + return "S2POE"sv; + if (feature == CPUFeature::PMUv3p9) + return "PMUv3p9"sv; + if (feature == CPUFeature::PMUv3_EDGE) + return "PMUv3_EDGE"sv; + if (feature == CPUFeature::PMUv3_ICNTR) + return "PMUv3_ICNTR"sv; + if (feature == CPUFeature::PMUv3_SS) + return "PMUv3_SS"sv; + if (feature == CPUFeature::PRFMSLC) + return "PRFMSLC"sv; + if (feature == CPUFeature::PFAR) + return "PFAR"sv; + if (feature == CPUFeature::RASv2) + return "RASv2"sv; + if (feature == CPUFeature::RPZ) + return "RPZ"sv; + if (feature == CPUFeature::RPRFM) + return "RPRFM"sv; + if (feature == CPUFeature::SCTLR2) + return "SCTLR2"sv; + if (feature == CPUFeature::SEBEP) + return "SEBEP"sv; + if (feature == CPUFeature::SME_F16F16) + return "SME_F16F16"sv; + if (feature == CPUFeature::SME2) + return "SME2"sv; + if (feature == CPUFeature::SME2p1) + return "SME2p1"sv; + if (feature == CPUFeature::SPECRES2) + return "SPECRES2"sv; + if (feature == CPUFeature::SPMU) + return "SPMU"sv; + if (feature == CPUFeature::SPEv1p4) + return "SPEv1p4"sv; + if (feature == CPUFeature::SPE_FDS) + return "SPE_FDS"sv; + if (feature == CPUFeature::SVE2p1) + return "SVE2p1"sv; + if (feature == CPUFeature::SYSINSTR128) + return "SYSINSTR128"sv; + if (feature == CPUFeature::SYSREG128) + return "SYSREG128"sv; + if (feature == CPUFeature::TCR2) + return "TCR2"sv; + if (feature == CPUFeature::THE) + return "THE"sv; + if (feature == CPUFeature::TRBE_EXT) + return "TRBE_EXT"sv; + if (feature == CPUFeature::TRBE_MPAM) + return "TRBE_MPAM"sv; + + // 2021 Architecture Extensions + if (feature == CPUFeature::CMOW) + return "CMOW"sv; + if (feature == CPUFeature::CONSTPACFIELD) + return "CONSTPACFIELD"sv; + if (feature == CPUFeature::Debugv8p8) + return "Debugv8p8"sv; + if (feature == CPUFeature::HBC) + return "HBC"sv; + if (feature == CPUFeature::HPMN0) + return "HPMN0"sv; + if (feature == CPUFeature::NMI) + return "NMI"sv; + if (feature == CPUFeature::GICv3_NMI) + return "GICv3_NMI"sv; + if (feature == CPUFeature::MOPS) + return "MOPS"sv; + if (feature == CPUFeature::PACQARMA3) + return "PACQARMA3"sv; + if (feature == CPUFeature::PMUv3_TH) + return "PMUv3_TH"sv; + if (feature == CPUFeature::PMUv3p8) + return "PMUv3p8"sv; + if (feature == CPUFeature::PMUv3_EXT64) + return "PMUv3_EXT64"sv; + if (feature == CPUFeature::PMUv3_EXT32) + return "PMUv3_EXT32"sv; + if (feature == CPUFeature::RNG_TRAP) + return "RNG_TRAP"sv; + if (feature == CPUFeature::SPEv1p3) + return "SPEv1p3"sv; + if (feature == CPUFeature::TIDCP1) + return "TIDCP1"sv; + if (feature == CPUFeature::BRBEv1p1) + return "BRBEv1p1"sv; + + // 2020 Architecture Extensions + if (feature == CPUFeature::AFP) + return "AFP"sv; + if (feature == CPUFeature::HCX) + return "HCX"sv; + if (feature == CPUFeature::LPA2) + return "LPA2"sv; + if (feature == CPUFeature::LS64) + return "LS64"sv; + if (feature == CPUFeature::LS64_V) + return "LS64_V"sv; + if (feature == CPUFeature::LS64_ACCDATA) + return "LS64_ACCDATA"sv; + if (feature == CPUFeature::MTE3) + return "MTE3"sv; + if (feature == CPUFeature::PAN3) + return "PAN3"sv; + if (feature == CPUFeature::PMUv3p7) + return "PMUv3p7"sv; + if (feature == CPUFeature::RPRES) + return "RPRES"sv; + if (feature == CPUFeature::RME) + return "RME"sv; + if (feature == CPUFeature::SME_FA64) + return "SME_FA64"sv; + if (feature == CPUFeature::SME_F64F64) + return "SME_F64F64"sv; + if (feature == CPUFeature::SME_I16I64) + return "SME_I16I64"sv; + if (feature == CPUFeature::EBF16) + return "EBF16"sv; + if (feature == CPUFeature::SPEv1p2) + return "SPEv1p2"sv; + if (feature == CPUFeature::WFxT) + return "WFxT"sv; + if (feature == CPUFeature::XS) + return "XS"sv; + if (feature == CPUFeature::BRBE) + return "BRBE"sv; + + // Features introduced prior to 2020 + if (feature == CPUFeature::AdvSIMD) + return "AdvSIMD"sv; + if (feature == CPUFeature::AES) + return "AES"sv; + if (feature == CPUFeature::PMULL) + return "PMULL"sv; + if (feature == CPUFeature::CP15SDISABLE2) + return "CP15SDISABLE2"sv; + if (feature == CPUFeature::CSV2) + return "CSV2"sv; + if (feature == CPUFeature::CSV2_1p1) + return "CSV2_1p1"sv; + if (feature == CPUFeature::CSV2_1p2) + return "CSV2_1p2"sv; + if (feature == CPUFeature::CSV2) + return "CSV2"sv; + if (feature == CPUFeature::CSV3) + return "CSV3"sv; + if (feature == CPUFeature::DGH) + return "DGH"sv; + if (feature == CPUFeature::DoubleLock) + return "DoubleLock"sv; + if (feature == CPUFeature::ETS) + return "ETS"sv; + if (feature == CPUFeature::FP) + return "FP"sv; + if (feature == CPUFeature::IVIPT) + return "IVIPT"sv; + if (feature == CPUFeature::PCSRv8) + return "PCSRv8"sv; + if (feature == CPUFeature::SPECRES) + return "SPECRES"sv; + if (feature == CPUFeature::RAS) + return "RAS"sv; + if (feature == CPUFeature::SB) + return "SB"sv; + if (feature == CPUFeature::SHA1) + return "SHA1"sv; + if (feature == CPUFeature::SHA256) + return "SHA256"sv; + if (feature == CPUFeature::SSBS) + return "SSBS2"sv; + if (feature == CPUFeature::SSBS2) + return "SSBS2"sv; + if (feature == CPUFeature::CRC32) + return "CRC32"sv; + if (feature == CPUFeature::nTLBPA) + return "nTLBPA"sv; + if (feature == CPUFeature::Debugv8p1) + return "Debugv8p1"sv; + if (feature == CPUFeature::HPDS) + return "HPDS"sv; + if (feature == CPUFeature::LOR) + return "LOR"sv; + if (feature == CPUFeature::LSE) + return "LSE"sv; + if (feature == CPUFeature::PAN) + return "PAN"sv; + if (feature == CPUFeature::PMUv3p1) + return "PMUv3p1"sv; + if (feature == CPUFeature::RDM) + return "RDM"sv; + if (feature == CPUFeature::HAFDBS) + return "HAFDBS"sv; + if (feature == CPUFeature::VHE) + return "VHE"sv; + if (feature == CPUFeature::VMID16) + return "VMID16"sv; + if (feature == CPUFeature::AA32BF16) + return "AA32BF16"sv; + if (feature == CPUFeature::AA32HPD) + return "AA32HPD"sv; + if (feature == CPUFeature::AA32I8MM) + return "AA32I8MM"sv; + if (feature == CPUFeature::PAN2) + return "PAN2"sv; + if (feature == CPUFeature::BF16) + return "BF16"sv; + if (feature == CPUFeature::DPB2) + return "DPB2"sv; + if (feature == CPUFeature::DPB) + return "DPB"sv; + if (feature == CPUFeature::Debugv8p2) + return "Debugv8p2"sv; + if (feature == CPUFeature::DotProd) + return "DotProd"sv; + if (feature == CPUFeature::EVT) + return "EVT"sv; + if (feature == CPUFeature::F32MM) + return "F32MM"sv; + if (feature == CPUFeature::F64MM) + return "F64MM"sv; + if (feature == CPUFeature::FHM) + return "FHM"sv; + if (feature == CPUFeature::FP16) + return "FP16"sv; + if (feature == CPUFeature::I8MM) + return "I8MM"sv; + if (feature == CPUFeature::IESB) + return "IESB"sv; + if (feature == CPUFeature::LPA) + return "LPA"sv; + if (feature == CPUFeature::LSMAOC) + return "LSMAOC"sv; + if (feature == CPUFeature::LVA) + return "LVA"sv; + if (feature == CPUFeature::MPAM) + return "MPAM"sv; + if (feature == CPUFeature::PCSRv8p2) + return "PCSRv8p2"sv; + if (feature == CPUFeature::SHA3) + return "SHA3"sv; + if (feature == CPUFeature::SHA512) + return "SHA512"sv; + if (feature == CPUFeature::SM3) + return "SM3"sv; + if (feature == CPUFeature::SM4) + return "SM4"sv; + if (feature == CPUFeature::SPE) + return "SPE"sv; + if (feature == CPUFeature::SVE) + return "SVE"sv; + if (feature == CPUFeature::TTCNP) + return "TTCNP"sv; + if (feature == CPUFeature::HPDS2) + return "HPDS2"sv; + if (feature == CPUFeature::XNX) + return "XNX"sv; + if (feature == CPUFeature::UAO) + return "UAO"sv; + if (feature == CPUFeature::VPIPT) + return "VPIPT"sv; + if (feature == CPUFeature::CCIDX) + return "CCIDX"sv; + if (feature == CPUFeature::FCMA) + return "FCMA"sv; + if (feature == CPUFeature::DoPD) + return "DoPD"sv; + if (feature == CPUFeature::EPAC) + return "EPAC"sv; + if (feature == CPUFeature::FPAC) + return "FPAC"sv; + if (feature == CPUFeature::FPACCOMBINE) + return "FPACCOMBINE"sv; + if (feature == CPUFeature::JSCVT) + return "JSCVT"sv; + if (feature == CPUFeature::LRCPC) + return "LRCPC"sv; + if (feature == CPUFeature::NV) + return "NV"sv; + if (feature == CPUFeature::PACQARMA5) + return "PACQARMA5"sv; + if (feature == CPUFeature::PACIMP) + return "PACIMP"sv; + if (feature == CPUFeature::PAuth) + return "PAuth"sv; + if (feature == CPUFeature::PAuth2) + return "PAuth2"sv; + if (feature == CPUFeature::SPEv1p1) + return "SPEv1p1"sv; + if (feature == CPUFeature::AMUv1) + return "AMUv1"sv; + if (feature == CPUFeature::CNTSC) + return "CNTSC"sv; + if (feature == CPUFeature::Debugv8p4) + return "Debugv8p4"sv; + if (feature == CPUFeature::DoubleFault) + return "DoubleFault"sv; + if (feature == CPUFeature::DIT) + return "DIT"sv; + if (feature == CPUFeature::FlagM) + return "FlagM"sv; + if (feature == CPUFeature::IDST) + return "IDST"sv; + if (feature == CPUFeature::LRCPC2) + return "LRCPC2"sv; + if (feature == CPUFeature::LSE2) + return "LSE2"sv; + if (feature == CPUFeature::NV2) + return "NV2"sv; + if (feature == CPUFeature::PMUv3p4) + return "PMUv3p4"sv; + if (feature == CPUFeature::RASv1p1) + return "RASv1p1"sv; + if (feature == CPUFeature::S2FWB) + return "S2FWB"sv; + if (feature == CPUFeature::SEL2) + return "SEL2"sv; + if (feature == CPUFeature::TLBIOS) + return "TLBIOS"sv; + if (feature == CPUFeature::TLBIRANGE) + return "TLBIRANGE"sv; + if (feature == CPUFeature::TRF) + return "TRF"sv; + if (feature == CPUFeature::TTL) + return "TTL"sv; + if (feature == CPUFeature::BBM) + return "BBM"sv; + if (feature == CPUFeature::TTST) + return "TTST"sv; + if (feature == CPUFeature::BTI) + return "BTI"sv; + if (feature == CPUFeature::FlagM2) + return "FlagM2"sv; + if (feature == CPUFeature::ExS) + return "ExS"sv; + if (feature == CPUFeature::E0PD) + return "E0PD"sv; + if (feature == CPUFeature::FRINTTS) + return "FRINTTS"sv; + if (feature == CPUFeature::GTG) + return "GTG"sv; + if (feature == CPUFeature::MTE) + return "MTE"sv; + if (feature == CPUFeature::MTE2) + return "MTE2"sv; + if (feature == CPUFeature::PMUv3p5) + return "PMUv3p5"sv; + if (feature == CPUFeature::RNG) + return "RNG"sv; + if (feature == CPUFeature::AMUv1p1) + return "AMUv1p1"sv; + if (feature == CPUFeature::ECV) + return "ECV"sv; + if (feature == CPUFeature::FGT) + return "FGT"sv; + if (feature == CPUFeature::MPAMv0p1) + return "MPAMv0p1"sv; + if (feature == CPUFeature::MPAMv1p1) + return "MPAMv1p1"sv; + if (feature == CPUFeature::MTPMU) + return "MTPMU"sv; + if (feature == CPUFeature::TWED) + return "TWED"sv; + if (feature == CPUFeature::ETMv4) + return "ETMv4"sv; + if (feature == CPUFeature::ETMv4p1) + return "ETMv4p1"sv; + if (feature == CPUFeature::ETMv4p2) + return "ETMv4p2"sv; + if (feature == CPUFeature::ETMv4p3) + return "ETMv4p3"sv; + if (feature == CPUFeature::ETMv4p4) + return "ETMv4p4"sv; + if (feature == CPUFeature::ETMv4p5) + return "ETMv4p5"sv; + if (feature == CPUFeature::ETMv4p6) + return "ETMv4p6"sv; + if (feature == CPUFeature::GICv3) + return "GICv3"sv; + if (feature == CPUFeature::GICv3p1) + return "GICv3p1"sv; + if (feature == CPUFeature::GICv3_LEGACY) + return "GICv3_LEGACY"sv; + if (feature == CPUFeature::GICv3_TDIR) + return "GICv3_TDIR"sv; + if (feature == CPUFeature::GICv4) + return "GICv4"sv; + if (feature == CPUFeature::GICv4p1) + return "GICv4p1"sv; + if (feature == CPUFeature::PMUv3) + return "PMUv3"sv; + if (feature == CPUFeature::ETE) + return "ETE"sv; + if (feature == CPUFeature::ETEv1p1) + return "ETEv1p1"sv; + if (feature == CPUFeature::SVE2) + return "SVE2"sv; + if (feature == CPUFeature::SVE_AES) + return "SVE_AES"sv; + if (feature == CPUFeature::SVE_PMULL128) + return "SVE_PMULL128"sv; + if (feature == CPUFeature::SVE_BitPerm) + return "SVE_BitPerm"sv; + if (feature == CPUFeature::SVE_SHA3) + return "SVE_SHA3"sv; + if (feature == CPUFeature::SVE_SM4) + return "SVE_SM4"sv; + if (feature == CPUFeature::TME) + return "TME"sv; + if (feature == CPUFeature::TRBE) + return "TRBE"sv; + if (feature == CPUFeature::SME) + return "SME"sv; + + VERIFY_NOT_REACHED(); +} + +// https://developer.arm.com/downloads/-/exploration-tools/feature-names-for-a-profile +StringView cpu_feature_to_description(CPUFeature::Type const& feature) +{ + // 2022 Architecture Extensions + if (feature == CPUFeature::ABLE) + return "Address Breakpoint Linking extension"sv; + if (feature == CPUFeature::ADERR) + return "RASv2 Additional Error syndrome reporting, for Device memory"sv; + if (feature == CPUFeature::ANERR) + return "RASv2 Additional Error syndrome reporting, for Normal memory"sv; + if (feature == CPUFeature::AIE) + return "Memory Attribute Index Enhancement"sv; + if (feature == CPUFeature::B16B16) + return "Non-widening BFloat16 to BFloat16 arithmetic for SVE2.1 and SME2.1"sv; + if (feature == CPUFeature::CLRBHB) + return "A new instruction CLRBHB is added in HINT space"sv; + if (feature == CPUFeature::CHK) + return "Detect when Guarded Control Stacks are implemented"sv; + if (feature == CPUFeature::CSSC) + return "Common Short Sequence Compression scalar integer instructions"sv; + if (feature == CPUFeature::CSV2_3) + return "New identification mechanism for Branch History information"sv; + if (feature == CPUFeature::D128) + return "128-bit Translation Tables, 56 bit PA"sv; + if (feature == CPUFeature::Debugv8p9) + return "Debug 2022"sv; + if (feature == CPUFeature::DoubleFault2) + return "Error exception routing extensions"sv; // NOTE: removed trailing dot compared to source! + if (feature == CPUFeature::EBEP) + return "Exception-based event profiling"sv; + if (feature == CPUFeature::ECBHB) + return "Imposes restrictions on branch history speculation around exceptions"sv; + if (feature == CPUFeature::ETEv1p3) + return "ETE support for v9.3"sv; + if (feature == CPUFeature::FGT2) + return "Fine-grained traps 2"sv; + if (feature == CPUFeature::GCS) + return "Guarded Control Stack Extension"sv; + if (feature == CPUFeature::HAFT) + return "Hardware managed Access Flag for Table descriptors"sv; + if (feature == CPUFeature::ITE) + return "Instrumentation trace extension"sv; + if (feature == CPUFeature::LRCPC3) + return "Load-Acquire RCpc instructions version 3"sv; + if (feature == CPUFeature::LSE128) + return "128-bit Atomics"sv; + if (feature == CPUFeature::LVA3) + return "56-bit VA"sv; + if (feature == CPUFeature::MEC) + return "Memory Encryption Contexts"sv; + if (feature == CPUFeature::MTE4) + return "Support for Canonical tag checking, reporting of all non-address bits on a fault, Store-only Tag checking, Memory tagging with Address tagging disabled"sv; + if (feature == CPUFeature::MTE_CANONICAL_TAGS) + return "Support for Canonical tag checking"sv; + if (feature == CPUFeature::MTE_TAGGED_FAR) + return "Support for reporting of all non-address bits on a fault"sv; + if (feature == CPUFeature::MTE_STORE_ONLY) + return "Support for Store-only Tag checking"sv; + if (feature == CPUFeature::MTE_NO_ADDRESS_TAGS) + return "Support for Memory tagging with Address tagging disabled"sv; + if (feature == CPUFeature::MTE_ASYM_FAULT) + return "Asymmetric Tag Check Fault handling"sv; + if (feature == CPUFeature::MTE_ASYNC) + return "Asynchronous Tag Check Fault handling"sv; + if (feature == CPUFeature::MTE_PERM) + return "Allocation tag access permission"sv; + if (feature == CPUFeature::PCSRv8p9) + return "PCSR disable control"sv; + if (feature == CPUFeature::PIE) + return "Permission model enhancements"sv; + if (feature == CPUFeature::POE) + return "Permission model enhancements"sv; + if (feature == CPUFeature::S1PIE) + return "Permission model enhancements"sv; + if (feature == CPUFeature::S2PIE) + return "Permission model enhancements"sv; + if (feature == CPUFeature::S1POE) + return "Permission model enhancements"sv; + if (feature == CPUFeature::S2POE) + return "Permission model enhancements"sv; + if (feature == CPUFeature::PMUv3p9) + return "EL0 access controls for PMU event counters"sv; + if (feature == CPUFeature::PMUv3_EDGE) + return "PMU event edge detection"sv; + if (feature == CPUFeature::PMUv3_ICNTR) + return "PMU instruction counter"sv; + if (feature == CPUFeature::PMUv3_SS) + return "PMU snapshot"sv; + if (feature == CPUFeature::PRFMSLC) + return "Prefetching enhancements"sv; + if (feature == CPUFeature::PFAR) + // https://developer.arm.com/documentation/ddi0602/2022-12/Shared-Pseudocode/Shared-Functions?lang=en + // Library pseudocode for shared/functions/extension/HavePFAR + return "Physical Fault Address Extension (RASv2)"sv; + if (feature == CPUFeature::RASv2) + return "Reliability, Availability, and Serviceability (RAS) Extension version 2"sv; + if (feature == CPUFeature::RPZ) + return "RPZ (RASv2)"sv; // Note: not really known + if (feature == CPUFeature::RPRFM) + return "RPRFM range prefetch hint instruction"sv; + if (feature == CPUFeature::SCTLR2) + return "Extension to SCTLR_ELx"sv; + if (feature == CPUFeature::SEBEP) + return "Synchronous Exception-based event profiling"sv; + if (feature == CPUFeature::SME_F16F16) + return "Non-widening half-precision FP16 to FP16 arithmetic for SME2.1"sv; + if (feature == CPUFeature::SME2) + return "Scalable Matrix Extension version 2"sv; + if (feature == CPUFeature::SME2p1) + return "Scalable Matrix Extension version 2.1"sv; + if (feature == CPUFeature::SPECRES2) + return "Adds new Clear Other Speculative Predictions instruction"sv; + if (feature == CPUFeature::SPMU) + return "System PMU"sv; + if (feature == CPUFeature::SPEv1p4) + return "Additional SPE events"sv; + if (feature == CPUFeature::SPE_FDS) + return "SPE filtering by data source"sv; + if (feature == CPUFeature::SVE2p1) + return "Scalable Vector Extension version SVE2.1"sv; + if (feature == CPUFeature::SYSINSTR128) + return "128-bit System instructions"sv; + if (feature == CPUFeature::SYSREG128) + return "128-bit System registers"sv; + if (feature == CPUFeature::TCR2) + return "Extension to TCR_ELx"sv; + if (feature == CPUFeature::THE) + return "Translation Hardening Extension"sv; + if (feature == CPUFeature::TRBE_EXT) + return "Represents TRBE external mode"sv; + if (feature == CPUFeature::TRBE_MPAM) + return "Trace Buffer MPAM extensions"sv; + + // 2021 Architecture Extensions + if (feature == CPUFeature::CMOW) + return "Control for cache maintenance permission"sv; + if (feature == CPUFeature::CONSTPACFIELD) + return "PAC Algorithm enhancement"sv; + if (feature == CPUFeature::Debugv8p8) + return "Debug v8.8"sv; + if (feature == CPUFeature::HBC) + return "Hinted conditional branches"sv; + if (feature == CPUFeature::HPMN0) + return "Setting of MDCR_EL2.HPMN to zero"sv; + if (feature == CPUFeature::NMI) + return "Non-maskable Interrupts"sv; + if (feature == CPUFeature::GICv3_NMI) + return "Non-maskable Interrupts"sv; + if (feature == CPUFeature::MOPS) + return "Standardization of memory operations"sv; + if (feature == CPUFeature::PACQARMA3) + return "Pointer authentication - QARMA3 algorithm"sv; + if (feature == CPUFeature::PMUv3_TH) + return "Event counting threshold"sv; + if (feature == CPUFeature::PMUv3p8) + return "Armv8.8 PMU Extensions"sv; + if (feature == CPUFeature::PMUv3_EXT64) + return "Optional 64-bit external interface to the Performance Monitors"sv; + if (feature == CPUFeature::PMUv3_EXT32) + return "Represents the original mostly 32-bit external interface to the Performance Monitors"sv; + if (feature == CPUFeature::RNG_TRAP) + return "Trapping support for RNDR and RNDRRS"sv; + if (feature == CPUFeature::SPEv1p3) + return "Armv8.8 Statistical Profiling Extensions"sv; + if (feature == CPUFeature::TIDCP1) + return "EL0 use of IMPLEMENTATION DEFINED functionality"sv; + if (feature == CPUFeature::BRBEv1p1) + return "Branch Record Buffer Extensions version 1.1"sv; + + // 2020 Architecture Extensions + if (feature == CPUFeature::AFP) + return "Alternate floating-point behavior"sv; + if (feature == CPUFeature::HCX) + return "Support for the HCRX_EL2 register"sv; + if (feature == CPUFeature::LPA2) + return "Larger physical address for 4KB and 16KB translation granules"sv; + if (feature == CPUFeature::LS64) + return "Support for 64 byte loads/stores without return"sv; + if (feature == CPUFeature::LS64_V) + return "Support for 64-byte stores with return"sv; + if (feature == CPUFeature::LS64_ACCDATA) + return "Support for 64-byte EL0 stores with return"sv; + if (feature == CPUFeature::MTE3) + return "MTE Asymmetric Fault Handling"sv; + if (feature == CPUFeature::PAN3) + return "Support for SCTLR_ELx.EPAN"sv; + if (feature == CPUFeature::PMUv3p7) + return "Armv8.7 PMU Extensions"sv; + if (feature == CPUFeature::RPRES) + return "Increased precision of Reciprocal Estimate and Reciprocal Square Root Estimate"sv; + if (feature == CPUFeature::RME) + return "Realm Management Extension"sv; + if (feature == CPUFeature::SME_FA64) + return "Additional instructions for the SME Extension"sv; + if (feature == CPUFeature::SME_F64F64) + return "Additional instructions for the SME Extension"sv; + if (feature == CPUFeature::SME_I16I64) + return "Additional instructions for the SME Extension"sv; + if (feature == CPUFeature::EBF16) + return "Additional instructions for the SME Extension"sv; + if (feature == CPUFeature::SPEv1p2) + return "Armv8.7 SPE"sv; + if (feature == CPUFeature::WFxT) + return "WFE and WFI instructions with timeout"sv; + if (feature == CPUFeature::XS) + return "XS attribute"sv; + if (feature == CPUFeature::BRBE) + return "Branch Record Buffer Extensions"sv; + + // Features introduced prior to 2020 + if (feature == CPUFeature::AdvSIMD) + return "Advanced SIMD Extension"sv; + if (feature == CPUFeature::AES) + return "Advanced SIMD AES instructions"sv; + if (feature == CPUFeature::PMULL) + return "Advanced SIMD PMULL instructions"sv; // ARMv8.0-AES is split into AES and PMULL + if (feature == CPUFeature::CP15SDISABLE2) + return "CP15DISABLE2"sv; + if (feature == CPUFeature::CSV2) + return "Cache Speculation Variant 2"sv; + if (feature == CPUFeature::CSV2_1p1) + return "Cache Speculation Variant 2 version 1.1"sv; + if (feature == CPUFeature::CSV2_1p2) + return "Cache Speculation Variant 2 version 1.2"sv; + if (feature == CPUFeature::CSV2_2) + return "Cache Speculation Variant 2 version 2"sv; // NOTE: name mistake in source! + if (feature == CPUFeature::CSV3) + return "Cache Speculation Variant 3"sv; + if (feature == CPUFeature::DGH) + return "Data Gathering Hint"sv; + if (feature == CPUFeature::DoubleLock) + return "Double Lock"sv; + if (feature == CPUFeature::ETS) + return "Enhanced Translation Synchronization"sv; + if (feature == CPUFeature::FP) + return "Floating point extension"sv; + if (feature == CPUFeature::IVIPT) + return "The IVIPT Extension"sv; + if (feature == CPUFeature::PCSRv8) + return "PC Sample-base Profiling extension (not EL3 and EL2)"sv; + if (feature == CPUFeature::SPECRES) + return "Speculation restriction instructions"sv; + if (feature == CPUFeature::RAS) + return "Reliability, Availability, and Serviceability (RAS) Extension"sv; + if (feature == CPUFeature::SB) + return "Speculation barrier"sv; + if (feature == CPUFeature::SHA1) + return "Advanced SIMD SHA1 instructions"sv; + if (feature == CPUFeature::SHA256) + return "Advanced SIMD SHA256 instructions"sv; // ARMv8.2-SHA is split into SHA-256, SHA-512 and SHA-3 + if (feature == CPUFeature::SSBS) + return "Speculative Store Bypass Safe Instruction"sv; // ARMv8.0-SSBS is split into SSBS and SSBS2 + if (feature == CPUFeature::SSBS2) + return "MRS and MSR instructions for SSBS"sv; // ARMv8.0-SSBS is split into SSBS and SSBS2 + if (feature == CPUFeature::CRC32) + return "CRC32 instructions"sv; + if (feature == CPUFeature::nTLBPA) + return "No intermediate caching by output address in TLB"sv; + if (feature == CPUFeature::Debugv8p1) + return "Debug with VHE"sv; + if (feature == CPUFeature::HPDS) + return "Hierarchical permission disables in translation tables"sv; + if (feature == CPUFeature::LOR) + return "Limited ordering regions"sv; + if (feature == CPUFeature::LSE) + return "Large System Extensions"sv; + if (feature == CPUFeature::PAN) + return "Privileged access-never"sv; + if (feature == CPUFeature::PMUv3p1) + return "PMU extensions version 3.1"sv; + if (feature == CPUFeature::RDM) + return "Rounding double multiply accumulate"sv; + if (feature == CPUFeature::HAFDBS) + return "Hardware updates to access flag and dirty state in translation tables"sv; + if (feature == CPUFeature::VHE) + return "Virtualization Host Extensions"sv; + if (feature == CPUFeature::VMID16) + return "16-bit VMID"sv; + if (feature == CPUFeature::AA32BF16) + return "AArch32 BFloat16 instructions"sv; + if (feature == CPUFeature::AA32HPD) + return "AArch32 Hierarchical permission disables"sv; + if (feature == CPUFeature::AA32I8MM) + return "AArch32 Int8 Matrix Multiplication"sv; + if (feature == CPUFeature::PAN2) + return "AT S1E1R and AT S1E1W instruction variants for PAN"sv; + if (feature == CPUFeature::BF16) + return "AArch64 BFloat16 instructions"sv; // NOTE: typo in source! + if (feature == CPUFeature::DPB2) + return "DC CVADP instruction"sv; + if (feature == CPUFeature::DPB) + return "DC CVAP instruction"sv; + if (feature == CPUFeature::Debugv8p2) + return "ARMv8.2 Debug"sv; + if (feature == CPUFeature::DotProd) + return "Advanced SIMD Int8 dot product instructions"sv; + if (feature == CPUFeature::EVT) + return "Enhanced Virtualization Traps"sv; + if (feature == CPUFeature::F32MM) + return "SVE single-precision floating-point matrix multiply instruction"sv; + if (feature == CPUFeature::F64MM) + return "SVE double-precision floating-point matrix multiply instruction"sv; + if (feature == CPUFeature::FHM) + return "Half-precision floating-point FMLAL instructions"sv; + if (feature == CPUFeature::FP16) + return "Half-precision floating-point data processing"sv; + if (feature == CPUFeature::I8MM) + return "Int8 Matrix Multiplication"sv; + if (feature == CPUFeature::IESB) + return "Implicit Error synchronization event"sv; + if (feature == CPUFeature::LPA) + return "Large PA and IPA support"sv; + if (feature == CPUFeature::LSMAOC) + return "Load/Store instruction multiple atomicity and ordering controls"sv; + if (feature == CPUFeature::LVA) + return "Large VA support"sv; + if (feature == CPUFeature::MPAM) + return "Memory Partitioning and Monitoring"sv; + if (feature == CPUFeature::PCSRv8p2) + return "PC Sample-based profiling version 8.2"sv; + if (feature == CPUFeature::SHA3) + return "Advanced SIMD EOR3, RAX1, XAR, and BCAX instructions"sv; // ARMv8.2-SHA is split into SHA-256, SHA-512 and SHA-3 + if (feature == CPUFeature::SHA512) + return "Advanced SIMD SHA512 instructions"sv; // ARMv8.2-SHA is split into SHA-256, SHA-512 and SHA-3 + if (feature == CPUFeature::SM3) + return "Advanced SIMD SM3 instructions"sv; // Split into SM3 and SM4 + if (feature == CPUFeature::SM4) + return "Advanced SIMD SM4 instructions"sv; // Split into SM3 and SM4 + if (feature == CPUFeature::SPE) + return "Statistical Profiling Extension"sv; + if (feature == CPUFeature::SVE) + return "Scalable Vector Extension"sv; + if (feature == CPUFeature::TTCNP) + return "Common not private translations"sv; + if (feature == CPUFeature::HPDS2) + return "Heirarchical permission disables in translation tables 2"sv; + if (feature == CPUFeature::XNX) + return "Execute-never control distinction by Exception level at stage 2"sv; + if (feature == CPUFeature::UAO) + return "Unprivileged Access Override control"sv; + if (feature == CPUFeature::VPIPT) + return "VMID-aware PIPT instruction cache"sv; + if (feature == CPUFeature::CCIDX) + return "Extended cache index"sv; + if (feature == CPUFeature::FCMA) + return "Floating-point FCMLA and FCADD instructions"sv; + if (feature == CPUFeature::DoPD) + return "Debug over Powerdown"sv; + if (feature == CPUFeature::EPAC) + return "Enhanced Pointer authentication"sv; + if (feature == CPUFeature::FPAC) + return "Faulting on pointer authentication instructions"sv; + if (feature == CPUFeature::FPACCOMBINE) + return "Faulting on combined pointer authentication instructions"sv; + if (feature == CPUFeature::JSCVT) + return "JavaScript FJCVTS conversion instruction"sv; + if (feature == CPUFeature::LRCPC) + return "Load-acquire RCpc instructions"sv; + if (feature == CPUFeature::NV) + return "Nested virtualization"sv; + if (feature == CPUFeature::PACQARMA5) + return "Pointer authentication - QARMA5 algorithm"sv; + if (feature == CPUFeature::PACIMP) + return "Pointer authentication - IMPLEMENTATION DEFINED algorithm"sv; + if (feature == CPUFeature::PAuth) + return "Pointer authentication"sv; + if (feature == CPUFeature::PAuth2) + return "Enhancements to pointer authentication"sv; + if (feature == CPUFeature::SPEv1p1) + return "Statistical Profiling Extensions version 1.1"sv; + if (feature == CPUFeature::AMUv1) + return "Activity Monitors Extension"sv; + if (feature == CPUFeature::CNTSC) + return "Generic Counter Scaling"sv; + if (feature == CPUFeature::Debugv8p4) + return "Debug relaxations and extensions version 8.4"sv; + if (feature == CPUFeature::DoubleFault) + return "Double Fault Extension"sv; + if (feature == CPUFeature::DIT) + return "Data Independent Timing instructions"sv; + if (feature == CPUFeature::FlagM) + return "Condition flag manipulation"sv; + if (feature == CPUFeature::IDST) + return "ID space trap handling"sv; + if (feature == CPUFeature::LRCPC2) + return "Load-acquire RCpc instructions version 2"sv; + if (feature == CPUFeature::LSE2) + return "Large System Extensions version 2"sv; + if (feature == CPUFeature::NV2) + return "Enhanced support for nested virtualization"sv; + if (feature == CPUFeature::PMUv3p4) + return "PMU extension version 3.4"sv; + if (feature == CPUFeature::RASv1p1) + return "Reliability, Availability, and Serviceability (RAS) Extension version 1.1"sv; + if (feature == CPUFeature::S2FWB) + return "Stage 2 forced write-back"sv; + if (feature == CPUFeature::SEL2) + return "Secure EL2"sv; + if (feature == CPUFeature::TLBIOS) + return "TLB invalidate outer-shared instructions"sv; // Split into TLBIOS and TLBIRANGE + if (feature == CPUFeature::TLBIRANGE) + return "TLB range invalidate range instructions"sv; // Split into TLBIOS and TLBIRANGE + if (feature == CPUFeature::TRF) + return "Self hosted Trace Extensions"sv; + if (feature == CPUFeature::TTL) + return "Translation Table Level"sv; + if (feature == CPUFeature::BBM) + return "Translation table break before make levels"sv; + if (feature == CPUFeature::TTST) + return "Small translation tables"sv; + if (feature == CPUFeature::BTI) + return "Branch target identification"sv; + if (feature == CPUFeature::FlagM2) + return "Condition flag manipulation version 2"sv; + if (feature == CPUFeature::ExS) + return "Disabling context synchronizing exception entry and exit"sv; + if (feature == CPUFeature::E0PD) + return "Preventing EL0 access to halves of address maps"sv; + if (feature == CPUFeature::FRINTTS) + return "FRINT32Z, FRINT32X, FRINT64Z, and FRINT64X instructions"sv; + if (feature == CPUFeature::GTG) + return "Guest translation granule size"sv; + if (feature == CPUFeature::MTE) + return "Instruction-only Memory Tagging Extension"sv; + if (feature == CPUFeature::MTE2) + return "Full Memory Tagging Extension"sv; + if (feature == CPUFeature::PMUv3p5) + return "PMU Extension version 3.5"sv; + if (feature == CPUFeature::RNG) + return "Random number generator"sv; + if (feature == CPUFeature::AMUv1p1) + return "Activity Monitors Extension version 1.1"sv; + if (feature == CPUFeature::ECV) + return "Enhanced counter virtualization"sv; + if (feature == CPUFeature::FGT) + return "Fine Grain Traps"sv; + if (feature == CPUFeature::MPAMv0p1) + return "Memory Partitioning and Monitoring version 0.1"sv; + if (feature == CPUFeature::MPAMv1p1) + return "Memory Partitioning and Monitoring version 1.1"sv; + if (feature == CPUFeature::MTPMU) + return "Multi-threaded PMU Extensions"sv; + if (feature == CPUFeature::TWED) + return "Delayed trapping of WFE"sv; + if (feature == CPUFeature::ETMv4) + return "Embedded Trace Macrocell version4"sv; + if (feature == CPUFeature::ETMv4p1) + return "Embedded Trace Macrocell version 4.1"sv; + if (feature == CPUFeature::ETMv4p2) + return "Embedded Trace Macrocell version 4.2"sv; + if (feature == CPUFeature::ETMv4p3) + return "Embedded Trace Macrocell version 4.3"sv; + if (feature == CPUFeature::ETMv4p4) + return "Embedded Trace Macrocell version 4.3"sv; + if (feature == CPUFeature::ETMv4p5) + return "Embedded Trace Macrocell version 4.4"sv; + if (feature == CPUFeature::ETMv4p6) + return "Embedded Trace Macrocell version 4.5"sv; + if (feature == CPUFeature::GICv3) + return "Generic Interrupt Controller version 3"sv; + if (feature == CPUFeature::GICv3p1) + return "Generic Interrupt Controller version 3.1"sv; + if (feature == CPUFeature::GICv3_LEGACY) + return "Support for GICv2 legacy operation"sv; // Note: missing in source + if (feature == CPUFeature::GICv3_TDIR) + return "Trapping Non-secure EL1 writes to ICV_DIR"sv; + if (feature == CPUFeature::GICv4) + return "Generic Interrupt Controller version 4"sv; + if (feature == CPUFeature::GICv4p1) + return "Generic Interrupt Controller version 4.1"sv; + if (feature == CPUFeature::PMUv3) + return "PMU extension version 3"sv; + if (feature == CPUFeature::ETE) + return "Embedded Trace Extension"sv; + if (feature == CPUFeature::ETEv1p1) + return "Embedded Trace Extension, version 1.1"sv; + if (feature == CPUFeature::SVE2) + return "SVE version 2"sv; + if (feature == CPUFeature::SVE_AES) + return "SVE AES instructions"sv; + if (feature == CPUFeature::SVE_PMULL128) + return "SVE PMULL instructions"sv; // SVE2-AES is split into AES and PMULL support + if (feature == CPUFeature::SVE_BitPerm) + return "SVE Bit Permute"sv; + if (feature == CPUFeature::SVE_SHA3) + return "SVE SHA-3 instructions"sv; + if (feature == CPUFeature::SVE_SM4) + return "SVE SM4 instructions"sv; + if (feature == CPUFeature::TME) + return "Transactional Memory Extension"sv; + if (feature == CPUFeature::TRBE) + return "Trace Buffer Extension"sv; + if (feature == CPUFeature::SME) + return "Scalable Matrix Extension"sv; + + VERIFY_NOT_REACHED(); +} + +} diff --git a/Kernel/Arch/aarch64/CPUID.h b/Kernel/Arch/aarch64/CPUID.h new file mode 100644 index 000000000000..d82c7e4b7885 --- /dev/null +++ b/Kernel/Arch/aarch64/CPUID.h @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2023, Konrad <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/ArbitrarySizedEnum.h> +#include <AK/Types.h> +#include <AK/UFixedBigInt.h> + +#include <AK/Platform.h> +VALIDATE_IS_AARCH64() + +namespace Kernel { + +// https://developer.arm.com/downloads/-/exploration-tools/feature-names-for-a-profile +AK_MAKE_ARBITRARY_SIZED_ENUM(CPUFeature, u256, + // 2022 Architecture Extensions + ABLE = CPUFeature(1u) << 0u, // Address Breakpoint Linking extension + ADERR = CPUFeature(1u) << 1u, // RASv2 Additional Error syndrome reporting, for Device memory + ANERR = CPUFeature(1u) << 2u, // RASv2 Additional Error syndrome reporting, for Normal memory + AIE = CPUFeature(1u) << 3u, // Memory Attribute Index Enhancement + B16B16 = CPUFeature(1u) << 4u, // Non-widening BFloat16 to BFloat16 arithmetic for SVE2.1 and SME2.1 + CLRBHB = CPUFeature(1u) << 5u, // A new instruction CLRBHB is added in HINT space + CHK = CPUFeature(1u) << 6u, // Detect when Guarded Control Stacks are implemented + CSSC = CPUFeature(1u) << 7u, // Common Short Sequence Compression scalar integer instructions + CSV2_3 = CPUFeature(1u) << 8u, // New identification mechanism for Branch History information + D128 = CPUFeature(1u) << 9u, // 128-bit Translation Tables, 56 bit PA + Debugv8p9 = CPUFeature(1u) << 10u, // Debug 2022 + DoubleFault2 = CPUFeature(1u) << 11u, // Error exception routing extensions. + EBEP = CPUFeature(1u) << 12u, // Exception-based event profiling + ECBHB = CPUFeature(1u) << 13u, // Imposes restrictions on branch history speculation around exceptions + ETEv1p3 = CPUFeature(1u) << 14u, // ETE support for v9.3 + FGT2 = CPUFeature(1u) << 15u, // Fine-grained traps 2 + GCS = CPUFeature(1u) << 16u, // Guarded Control Stack Extension + HAFT = CPUFeature(1u) << 17u, // Hardware managed Access Flag for Table descriptors + ITE = CPUFeature(1u) << 18u, // Instrumentation trace extension + LRCPC3 = CPUFeature(1u) << 19u, // Load-Acquire RCpc instructions version 3 + LSE128 = CPUFeature(1u) << 20u, // 128-bit Atomics + LVA3 = CPUFeature(1u) << 21u, // 56-bit VA + MEC = CPUFeature(1u) << 22u, // Memory Encryption Contexts + MTE4 = CPUFeature(1u) << 23u, // Support for Canonical tag checking, reporting of all non-address bits on a fault, Store-only Tag checking, Memory tagging with Address tagging disabled + MTE_CANONICAL_TAGS = CPUFeature(1u) << 24u, // Support for Canonical tag checking + MTE_TAGGED_FAR = CPUFeature(1u) << 25u, // Support for reporting of all non-address bits on a fault + MTE_STORE_ONLY = CPUFeature(1u) << 26u, // Support for Store-only Tag checking + MTE_NO_ADDRESS_TAGS = CPUFeature(1u) << 27u, // Support for Memory tagging with Address tagging disabled + MTE_ASYM_FAULT = CPUFeature(1u) << 28u, // Asymmetric Tag Check Fault handling + MTE_ASYNC = CPUFeature(1u) << 29u, // Asynchronous Tag Check Fault handling + MTE_PERM = CPUFeature(1u) << 30u, // Allocation tag access permission + PCSRv8p9 = CPUFeature(1u) << 31u, // PCSR disable control + PIE = CPUFeature(1u) << 32u, // Permission model enhancements + POE = CPUFeature(1u) << 33u, // Permission model enhancements + S1PIE = CPUFeature(1u) << 34u, // Permission model enhancements + S2PIE = CPUFeature(1u) << 35u, // Permission model enhancements + S1POE = CPUFeature(1u) << 36u, // Permission model enhancements + S2POE = CPUFeature(1u) << 37u, // Permission model enhancements + PMUv3p9 = CPUFeature(1u) << 38u, // EL0 access controls for PMU event counters + PMUv3_EDGE = CPUFeature(1u) << 39u, // PMU event edge detection + PMUv3_ICNTR = CPUFeature(1u) << 40u, // PMU instruction counter + PMUv3_SS = CPUFeature(1u) << 41u, // PMU snapshot + PRFMSLC = CPUFeature(1u) << 42u, // Prefetching enhancements + PFAR = CPUFeature(1u) << 43u, // Physical Fault Address Extension [NOTE: not yet listed] + RASv2 = CPUFeature(1u) << 44u, // Reliability, Availability, and Serviceability (RAS) Extension version 2 + RPZ = CPUFeature(1u) << 45u, // ? [NOTE: not yet listed] + RPRFM = CPUFeature(1u) << 46u, // RPRFM range prefetch hint instruction + SCTLR2 = CPUFeature(1u) << 47u, // Extension to SCTLR_ELx + SEBEP = CPUFeature(1u) << 48u, // Synchronous Exception-based event profiling + SME_F16F16 = CPUFeature(1u) << 49u, // Non-widening half-precision FP16 to FP16 arithmetic for SME2.1 + SME2 = CPUFeature(1u) << 50u, // Scalable Matrix Extension version 2 + SME2p1 = CPUFeature(1u) << 51u, // Scalable Matrix Extension version 2.1 + SPECRES2 = CPUFeature(1u) << 52u, // Adds new Clear Other Speculative Predictions instruction + SPMU = CPUFeature(1u) << 53u, // System PMU + SPEv1p4 = CPUFeature(1u) << 54u, // Additional SPE events + SPE_FDS = CPUFeature(1u) << 55u, // SPE filtering by data source + SVE2p1 = CPUFeature(1u) << 56u, // Scalable Vector Extension version SVE2.1 + SYSINSTR128 = CPUFeature(1u) << 57u, // 128-bit System instructions + SYSREG128 = CPUFeature(1u) << 58u, // 128-bit System registers + TCR2 = CPUFeature(1u) << 59u, // Extension to TCR_ELx + THE = CPUFeature(1u) << 60u, // Translation Hardening Extension + TRBE_EXT = CPUFeature(1u) << 61u, // Represents TRBE external mode + TRBE_MPAM = CPUFeature(1u) << 62u, // Trace Buffer MPAM extensions + + // 2021 Architecture Extensions + CMOW = CPUFeature(1u) << 63u, // Control for cache maintenance permission + CONSTPACFIELD = CPUFeature(1u) << 64u, // PAC Algorithm enhancement + Debugv8p8 = CPUFeature(1u) << 65u, // Debug v8.8 + HBC = CPUFeature(1u) << 66u, // Hinted conditional branches + HPMN0 = CPUFeature(1u) << 67u, // Setting of MDCR_EL2.HPMN to zero + NMI = CPUFeature(1u) << 68u, // Non-maskable Interrupts + GICv3_NMI = CPUFeature(1u) << 69u, // Non-maskable Interrupts + MOPS = CPUFeature(1u) << 70u, // Standardization of memory operations + PACQARMA3 = CPUFeature(1u) << 71u, // Pointer authentication - QARMA3 algorithm + PMUv3_TH = CPUFeature(1u) << 72u, // Event counting threshold + PMUv3p8 = CPUFeature(1u) << 73u, // Armv8.8 PMU Extensions + PMUv3_EXT64 = CPUFeature(1u) << 74u, // Optional 64-bit external interface to the Performance Monitors + PMUv3_EXT32 = CPUFeature(1u) << 75u, // Represents the original mostly 32-bit external interface to the Performance Monitors + RNG_TRAP = CPUFeature(1u) << 76u, // Trapping support for RNDR and RNDRRS + SPEv1p3 = CPUFeature(1u) << 77u, // Armv8.8 Statistical Profiling Extensions + TIDCP1 = CPUFeature(1u) << 78u, // EL0 use of IMPLEMENTATION DEFINED functionality + BRBEv1p1 = CPUFeature(1u) << 79u, // Branch Record Buffer Extensions version 1.1 + + // 2020 Architecture Extensions + AFP = CPUFeature(1u) << 80u, // Alternate floating-point behavior + HCX = CPUFeature(1u) << 81u, // Support for the HCRX_EL2 register + LPA2 = CPUFeature(1u) << 82u, // Larger physical address for 4KB and 16KB translation granules + LS64 = CPUFeature(1u) << 83u, // Support for 64 byte loads/stores without return + LS64_V = CPUFeature(1u) << 84u, // Support for 64-byte stores with return + LS64_ACCDATA = CPUFeature(1u) << 85u, // Support for 64-byte EL0 stores with return + MTE3 = CPUFeature(1u) << 86u, // MTE Asymmetric Fault Handling + PAN3 = CPUFeature(1u) << 87u, // Support for SCTLR_ELx.EPAN + PMUv3p7 = CPUFeature(1u) << 88u, // Armv8.7 PMU Extensions + RPRES = CPUFeature(1u) << 89u, // Increased precision of Reciprocal Estimate and Reciprocal Square Root Estimate + RME = CPUFeature(1u) << 90u, // Realm Management Extension + SME_FA64 = CPUFeature(1u) << 91u, // Additional instructions for the SME Extension + SME_F64F64 = CPUFeature(1u) << 92u, // Additional instructions for the SME Extension + SME_I16I64 = CPUFeature(1u) << 93u, // Additional instructions for the SME Extension + EBF16 = CPUFeature(1u) << 94u, // Additional instructions for the SME Extension + SPEv1p2 = CPUFeature(1u) << 95u, // Armv8.7 SPE + WFxT = CPUFeature(1u) << 96u, // WFE and WFI instructions with timeout + XS = CPUFeature(1u) << 97u, // XS attribute + BRBE = CPUFeature(1u) << 98u, // Branch Record Buffer Extensions + + // Features introduced prior to 2020 + AdvSIMD = CPUFeature(1u) << 99u, // Advanced SIMD Extension + AES = CPUFeature(1u) << 100u, // Advanced SIMD AES instructions + PMULL = CPUFeature(1u) << 101u, // Advanced SIMD PMULL instructions; ARMv8.0-AES is split into AES and PMULL + CP15SDISABLE2 = CPUFeature(1u) << 102u, // CP15DISABLE2 + CSV2 = CPUFeature(1u) << 103u, // Cache Speculation Variant 2 + CSV2_1p1 = CPUFeature(1u) << 104u, // Cache Speculation Variant 2 version 1.1 + CSV2_1p2 = CPUFeature(1u) << 105u, // Cache Speculation Variant 2 version 1.2 + CSV2_2 = CPUFeature(1u) << 106u, // Cache Speculation Variant 2 version 2 [NOTE: name mistake in source!] + CSV3 = CPUFeature(1u) << 107u, // Cache Speculation Variant 3 + DGH = CPUFeature(1u) << 108u, // Data Gathering Hint + DoubleLock = CPUFeature(1u) << 109u, // Double Lock + ETS = CPUFeature(1u) << 110u, // Enhanced Translation Synchronization + FP = CPUFeature(1u) << 111u, // Floating point extension + IVIPT = CPUFeature(1u) << 112u, // The IVIPT Extension + PCSRv8 = CPUFeature(1u) << 113u, // PC Sample-base Profiling extension (not EL3 and EL2) + SPECRES = CPUFeature(1u) << 114u, // Speculation restriction instructions + RAS = CPUFeature(1u) << 115u, // Reliability, Availability, and Serviceability (RAS) Extension + SB = CPUFeature(1u) << 116u, // Speculation barrier + SHA1 = CPUFeature(1u) << 117u, // Advanced SIMD SHA1 instructions + SHA256 = CPUFeature(1u) << 118u, // Advanced SIMD SHA256 instructions; Split ARMv8.2-SHA into SHA-256, SHA-512 and SHA-3 + SSBS = CPUFeature(1u) << 119u, // Speculative Store Bypass Safe Instruction; ARMv8.0-SSBS is split into SSBS and SSBS2 + SSBS2 = CPUFeature(1u) << 120u, // MRS and MSR instructions for SSBS; ARMv8.0-SSBS is split into SSBS and SSBS2 + CRC32 = CPUFeature(1u) << 121u, // CRC32 instructions + nTLBPA = CPUFeature(1u) << 122u, // No intermediate caching by output address in TLB + Debugv8p1 = CPUFeature(1u) << 123u, // Debug with VHE + HPDS = CPUFeature(1u) << 124u, // Hierarchical permission disables in translation tables + LOR = CPUFeature(1u) << 125u, // Limited ordering regions + LSE = CPUFeature(1u) << 126u, // Large System Extensions + PAN = CPUFeature(1u) << 127u, // Privileged access-never + PMUv3p1 = CPUFeature(1u) << 128u, // PMU extensions version 3.1 + RDM = CPUFeature(1u) << 129u, // Rounding double multiply accumulate + HAFDBS = CPUFeature(1u) << 130u, // Hardware updates to access flag and dirty state in translation tables + VHE = CPUFeature(1u) << 131u, // Virtualization Host Extensions + VMID16 = CPUFeature(1u) << 132u, // 16-bit VMID + AA32BF16 = CPUFeature(1u) << 133u, // AArch32 BFloat16 instructions + AA32HPD = CPUFeature(1u) << 134u, // AArch32 Hierarchical permission disables + AA32I8MM = CPUFeature(1u) << 135u, // AArch32 Int8 Matrix Multiplication + PAN2 = CPUFeature(1u) << 136u, // AT S1E1R and AT S1E1W instruction variants for PAN + BF16 = CPUFeature(1u) << 137u, // AARch64 BFloat16 instructions + DPB2 = CPUFeature(1u) << 138u, // DC CVADP instruction + DPB = CPUFeature(1u) << 139u, // DC CVAP instruction + Debugv8p2 = CPUFeature(1u) << 140u, // ARMv8.2 Debug + DotProd = CPUFeature(1u) << 141u, // Advanced SIMD Int8 dot product instructions + EVT = CPUFeature(1u) << 142u, // Enhanced Virtualization Traps + F32MM = CPUFeature(1u) << 143u, // SVE single-precision floating-point matrix multiply instruction + F64MM = CPUFeature(1u) << 144u, // SVE double-precision floating-point matrix multiply instruction + FHM = CPUFeature(1u) << 145u, // Half-precision floating-point FMLAL instructions + FP16 = CPUFeature(1u) << 146u, // Half-precision floating-point data processing + I8MM = CPUFeature(1u) << 147u, // Int8 Matrix Multiplication + IESB = CPUFeature(1u) << 148u, // Implicit Error synchronization event + LPA = CPUFeature(1u) << 149u, // Large PA and IPA support + LSMAOC = CPUFeature(1u) << 150u, // Load/Store instruction multiple atomicity and ordering controls + LVA = CPUFeature(1u) << 151u, // Large VA support + MPAM = CPUFeature(1u) << 152u, // Memory Partitioning and Monitoring + PCSRv8p2 = CPUFeature(1u) << 153u, // PC Sample-based profiling version 8.2 + SHA3 = CPUFeature(1u) << 154u, // Advanced SIMD EOR3, RAX1, XAR, and BCAX instructions; Split ARMv8.2-SHA into SHA-256, SHA-512 and SHA-3 + SHA512 = CPUFeature(1u) << 155u, // Advanced SIMD SHA512 instructions; Split ARMv8.2-SHA into SHA-256, SHA-512 and SHA-3 + SM3 = CPUFeature(1u) << 156u, // Advanced SIMD SM3 instructions; Split into SM3 and SM4 + SM4 = CPUFeature(1u) << 157u, // Advanced SIMD SM4 instructions; Split into SM3 and SM4 + SPE = CPUFeature(1u) << 158u, // Statistical Profiling Extension + SVE = CPUFeature(1u) << 159u, // Scalable Vector Extension + TTCNP = CPUFeature(1u) << 160u, // Common not private translations + HPDS2 = CPUFeature(1u) << 161u, // Heirarchical permission disables in translation tables 2 + XNX = CPUFeature(1u) << 162u, // Execute-never control distinction by Exception level at stage 2 + UAO = CPUFeature(1u) << 163u, // Unprivileged Access Override control + VPIPT = CPUFeature(1u) << 164u, // VMID-aware PIPT instruction cache + CCIDX = CPUFeature(1u) << 165u, // Extended cache index + FCMA = CPUFeature(1u) << 166u, // Floating-point FCMLA and FCADD instructions + DoPD = CPUFeature(1u) << 167u, // Debug over Powerdown + EPAC = CPUFeature(1u) << 168u, // Enhanced Pointer authentication + FPAC = CPUFeature(1u) << 169u, // Faulting on pointer authentication instructions + FPACCOMBINE = CPUFeature(1u) << 170u, // Faulting on combined pointer authentication instructions + JSCVT = CPUFeature(1u) << 171u, // JavaScript FJCVTS conversion instruction + LRCPC = CPUFeature(1u) << 172u, // Load-acquire RCpc instructions + NV = CPUFeature(1u) << 173u, // Nested virtualization + PACQARMA5 = CPUFeature(1u) << 174u, // Pointer authentication - QARMA5 algorithm + PACIMP = CPUFeature(1u) << 175u, // Pointer authentication - IMPLEMENTATION DEFINED algorithm + PAuth = CPUFeature(1u) << 176u, // Pointer authentication + PAuth2 = CPUFeature(1u) << 177u, // Enhancements to pointer authentication + SPEv1p1 = CPUFeature(1u) << 178u, // Statistical Profiling Extensions version 1.1 + AMUv1 = CPUFeature(1u) << 179u, // Activity Monitors Extension + CNTSC = CPUFeature(1u) << 180u, // Generic Counter Scaling + Debugv8p4 = CPUFeature(1u) << 181u, // Debug relaxations and extensions version 8.4 + DoubleFault = CPUFeature(1u) << 182u, // Double Fault Extension + DIT = CPUFeature(1u) << 183u, // Data Independent Timing instructions + FlagM = CPUFeature(1u) << 184u, // Condition flag manipulation + IDST = CPUFeature(1u) << 185u, // ID space trap handling + LRCPC2 = CPUFeature(1u) << 186u, // Load-acquire RCpc instructions version 2 + LSE2 = CPUFeature(1u) << 187u, // Large System Extensions version 2 + NV2 = CPUFeature(1u) << 188u, // Enhanced support for nested virtualization + PMUv3p4 = CPUFeature(1u) << 189u, // PMU extension version 3.4 + RASv1p1 = CPUFeature(1u) << 190u, // Reliability, Availability, and Serviceability (RAS) Extension version 1.1 + S2FWB = CPUFeature(1u) << 191u, // Stage 2 forced write-back + SEL2 = CPUFeature(1u) << 192u, // Secure EL2 + TLBIOS = CPUFeature(1u) << 193u, // TLB invalidate outer-shared instructions; Split into TLBIOS and TLBIRANGE + TLBIRANGE = CPUFeature(1u) << 194u, // TLB range invalidate range instructions; Split into TLBIOS and TLBIRANGE + TRF = CPUFeature(1u) << 195u, // Self hosted Trace Extensions + TTL = CPUFeature(1u) << 196u, // Translation Table Level + BBM = CPUFeature(1u) << 197u, // Translation table break before make levels + TTST = CPUFeature(1u) << 198u, // Small translation tables + BTI = CPUFeature(1u) << 199u, // Branch target identification + FlagM2 = CPUFeature(1u) << 200u, // Condition flag manipulation version 2 + ExS = CPUFeature(1u) << 201u, // Disabling context synchronizing exception entry and exit + E0PD = CPUFeature(1u) << 202u, // Preventing EL0 access to halves of address maps + FRINTTS = CPUFeature(1u) << 203u, // FRINT32Z, FRINT32X, FRINT64Z, and FRINT64X instructions + GTG = CPUFeature(1u) << 204u, // Guest translation granule size + MTE = CPUFeature(1u) << 205u, // Instruction-only Memory Tagging Extension + MTE2 = CPUFeature(1u) << 206u, // Full Memory Tagging Extension + PMUv3p5 = CPUFeature(1u) << 207u, // PMU Extension version 3.5 + RNG = CPUFeature(1u) << 208u, // Random number generator + AMUv1p1 = CPUFeature(1u) << 209u, // Activity Monitors Extension version 1.1 + ECV = CPUFeature(1u) << 210u, // Enhanced counter virtualization + FGT = CPUFeature(1u) << 211u, // Fine Grain Traps + MPAMv0p1 = CPUFeature(1u) << 212u, // Memory Partitioning and Monitoring version 0.1 + MPAMv1p1 = CPUFeature(1u) << 213u, // Memory Partitioning and Monitoring version 1.1 + MTPMU = CPUFeature(1u) << 214u, // Multi-threaded PMU Extensions + TWED = CPUFeature(1u) << 215u, // Delayed trapping of WFE + ETMv4 = CPUFeature(1u) << 216u, // Embedded Trace Macrocell version4 + ETMv4p1 = CPUFeature(1u) << 217u, // Embedded Trace Macrocell version 4.1 + ETMv4p2 = CPUFeature(1u) << 218u, // Embedded Trace Macrocell version 4.2 + ETMv4p3 = CPUFeature(1u) << 219u, // Embedded Trace Macrocell version 4.3 + ETMv4p4 = CPUFeature(1u) << 220u, // Embedded Trace Macrocell version 4.3 + ETMv4p5 = CPUFeature(1u) << 221u, // Embedded Trace Macrocell version 4.4 + ETMv4p6 = CPUFeature(1u) << 222u, // Embedded Trace Macrocell version 4.5 + GICv3 = CPUFeature(1u) << 223u, // Generic Interrupt Controller version 3 + GICv3p1 = CPUFeature(1u) << 224u, // Generic Interrupt Controller version 3.1 + // Note: cf. https://developer.arm.com/documentation/ihi0069/h/?lang=en + GICv3_LEGACY = CPUFeature(1u) << 225u, // Support for GICv2 legacy operation + GICv3_TDIR = CPUFeature(1u) << 226u, // Trapping Non-secure EL1 writes to ICV_DIR + GICv4 = CPUFeature(1u) << 227u, // Generic Interrupt Controller version 4 + GICv4p1 = CPUFeature(1u) << 228u, // Generic Interrupt Controller version 4.1 + PMUv3 = CPUFeature(1u) << 229u, // PMU extension version 3 + ETE = CPUFeature(1u) << 230u, // Embedded Trace Extension + ETEv1p1 = CPUFeature(1u) << 231u, // Embedded Trace Extension, version 1.1 + SVE2 = CPUFeature(1u) << 232u, // SVE version 2 + SVE_AES = CPUFeature(1u) << 233u, // SVE AES instructions + SVE_PMULL128 = CPUFeature(1u) << 234u, // SVE PMULL instructions; SVE2-AES is split into AES and PMULL support + SVE_BitPerm = CPUFeature(1u) << 235u, // SVE Bit Permute + SVE_SHA3 = CPUFeature(1u) << 236u, // SVE SHA-3 instructions + SVE_SM4 = CPUFeature(1u) << 237u, // SVE SM4 instructions + TME = CPUFeature(1u) << 238u, // Transactional Memory Extension + TRBE = CPUFeature(1u) << 239u, // Trace Buffer Extension + SME = CPUFeature(1u) << 240u, // Scalable Matrix Extension + + __End = CPUFeature(1u) << 255u); + +StringView cpu_feature_to_name(CPUFeature::Type const&); +StringView cpu_feature_to_description(CPUFeature::Type const&); + +} diff --git a/Kernel/CMakeLists.txt b/Kernel/CMakeLists.txt index 7891f4250488..0f8e39a79a51 100644 --- a/Kernel/CMakeLists.txt +++ b/Kernel/CMakeLists.txt @@ -449,6 +449,7 @@ elseif("${SERENITY_ARCH}" STREQUAL "aarch64") Arch/aarch64/boot.S Arch/aarch64/BootPPMParser.cpp + Arch/aarch64/CPUID.cpp Arch/aarch64/CrashHandler.cpp Arch/aarch64/CurrentTime.cpp Arch/aarch64/Dummy.cpp
a8ef84f8c3afeed083f49828d881f2d219fbbe34
2024-05-26 01:49:47
Matthew Olsson
libweb: Use LengthPercentage for calc values in Transformation matrix
false
Use LengthPercentage for calc values in Transformation matrix
libweb
diff --git a/Tests/LibWeb/Text/expected/css/animating-transform-with-calc-crash.txt b/Tests/LibWeb/Text/expected/css/animating-transform-with-calc-crash.txt new file mode 100644 index 000000000000..be36d109cd5f --- /dev/null +++ b/Tests/LibWeb/Text/expected/css/animating-transform-with-calc-crash.txt @@ -0,0 +1 @@ + PASS! (Didn't crash) diff --git a/Tests/LibWeb/Text/input/css/animating-transform-with-calc-crash.html b/Tests/LibWeb/Text/input/css/animating-transform-with-calc-crash.html new file mode 100644 index 000000000000..f3009811589e --- /dev/null +++ b/Tests/LibWeb/Text/input/css/animating-transform-with-calc-crash.html @@ -0,0 +1,21 @@ +<!-- https://github.com/SerenityOS/serenity/issues/23633 --> +<style> + div { + --some-var: -100px; + animation: anim 1s infinite; + } + + @keyframes anim { + to { + transform: translateX(calc(var(--some-var) * -1)); + } + } +</style> +<div></div> +<script src="../include.js"></script> +<script> + promiseTest(async () => { + await animationFrame(); + println("PASS! (Didn't crash)"); + }); +</script> diff --git a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp index 9f00538ff4cc..791c47d11190 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleComputer.cpp @@ -870,7 +870,7 @@ static RefPtr<StyleValue const> interpolate_transform(DOM::Element& element, Sty values.append(AngleOrCalculated { value->as_angle().angle() }); break; case StyleValue::Type::Calculated: - values.append(AngleOrCalculated { value->as_calculated() }); + values.append(LengthPercentage { value->as_calculated() }); break; case StyleValue::Type::Length: values.append(LengthPercentage { value->as_length().length() });
546cdde776e88635b9faf9996d753a5eccaf9bfa
2021-02-13 05:10:31
Ben Wiederhake
kernel: clock_nanosleep's 'flags' is not a bitset
false
clock_nanosleep's 'flags' is not a bitset
kernel
diff --git a/Kernel/Syscalls/clock.cpp b/Kernel/Syscalls/clock.cpp index c28552953d71..557d9376ce20 100644 --- a/Kernel/Syscalls/clock.cpp +++ b/Kernel/Syscalls/clock.cpp @@ -76,7 +76,17 @@ int Process::sys$clock_nanosleep(Userspace<const Syscall::SC_clock_nanosleep_par if (!copy_from_user(&requested_sleep, params.requested_sleep)) return -EFAULT; - bool is_absolute = params.flags & TIMER_ABSTIME; + bool is_absolute; + switch (params.flags) { + case 0: + is_absolute = false; + break; + case TIMER_ABSTIME: + is_absolute = true; + break; + default: + return -EINVAL; + } if (!TimeManagement::is_valid_clock_id(params.clock_id)) return -EINVAL;
31289a8d57bca2ed86d750bad6a4ab36f26ac6f1
2023-04-25 18:18:40
Andreas Kling
libcore: Add a hook for custom construction of EventLoopImplementation
false
Add a hook for custom construction of EventLoopImplementation
libcore
diff --git a/Userland/Libraries/LibCore/EventLoop.cpp b/Userland/Libraries/LibCore/EventLoop.cpp index 6a71f584d084..c45e99f67bfe 100644 --- a/Userland/Libraries/LibCore/EventLoop.cpp +++ b/Userland/Libraries/LibCore/EventLoop.cpp @@ -30,8 +30,10 @@ bool has_event_loop() } } +Function<NonnullOwnPtr<EventLoopImplementation>()> EventLoop::make_implementation = EventLoopImplementationUnix::create; + EventLoop::EventLoop() - : m_impl(make<EventLoopImplementationUnix>()) + : m_impl(make_implementation()) { if (event_loop_stack().is_empty()) { event_loop_stack().append(*this); diff --git a/Userland/Libraries/LibCore/EventLoop.h b/Userland/Libraries/LibCore/EventLoop.h index fbcd32515a7b..759a4a695094 100644 --- a/Userland/Libraries/LibCore/EventLoop.h +++ b/Userland/Libraries/LibCore/EventLoop.h @@ -93,6 +93,8 @@ class EventLoop { static EventLoop& current(); + static Function<NonnullOwnPtr<EventLoopImplementation>()> make_implementation; + private: void wait_for_event(WaitMode); Optional<Time> get_next_timer_expiration(); diff --git a/Userland/Libraries/LibCore/EventLoopImplementationUnix.h b/Userland/Libraries/LibCore/EventLoopImplementationUnix.h index a44714a6781a..c1ab8f9cd6e5 100644 --- a/Userland/Libraries/LibCore/EventLoopImplementationUnix.h +++ b/Userland/Libraries/LibCore/EventLoopImplementationUnix.h @@ -12,6 +12,8 @@ namespace Core { class EventLoopImplementationUnix final : public EventLoopImplementation { public: + static NonnullOwnPtr<EventLoopImplementationUnix> create() { return make<EventLoopImplementationUnix>(); } + EventLoopImplementationUnix(); virtual ~EventLoopImplementationUnix();
84b15cc7b196375dc7e1a9d7deaee7d8df87bb06
2021-10-28 16:23:31
Andreas Kling
libweb: Remove StyleProperties::set_property(PropertyID, StringView)
false
Remove StyleProperties::set_property(PropertyID, StringView)
libweb
diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp index 31e45961acf5..c060f9de5dde 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp +++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.cpp @@ -39,11 +39,6 @@ void StyleProperties::set_property(CSS::PropertyID id, NonnullRefPtr<StyleValue> m_property_values.set(id, move(value)); } -void StyleProperties::set_property(CSS::PropertyID id, const StringView& value) -{ - m_property_values.set(id, StringStyleValue::create(value)); -} - Optional<NonnullRefPtr<StyleValue>> StyleProperties::property(CSS::PropertyID property_id) const { auto it = m_property_values.find(property_id); diff --git a/Userland/Libraries/LibWeb/CSS/StyleProperties.h b/Userland/Libraries/LibWeb/CSS/StyleProperties.h index 5115f931a765..6472f87208eb 100644 --- a/Userland/Libraries/LibWeb/CSS/StyleProperties.h +++ b/Userland/Libraries/LibWeb/CSS/StyleProperties.h @@ -37,7 +37,6 @@ class StyleProperties : public RefCounted<StyleProperties> { HashMap<CSS::PropertyID, NonnullRefPtr<StyleValue>> const& properties() const { return m_property_values; } void set_property(CSS::PropertyID, NonnullRefPtr<StyleValue> value); - void set_property(CSS::PropertyID, const StringView&); Optional<NonnullRefPtr<StyleValue>> property(CSS::PropertyID) const; Length length_or_fallback(CSS::PropertyID, const Length& fallback) const;
59f87d12d03c6794eb3101d1755d697bbbe35c8f
2020-04-27 01:01:41
Hüseyin ASLITÜRK
base: 32x32 icons for cplusplus and header file types
false
32x32 icons for cplusplus and header file types
base
diff --git a/Base/res/icons/32x32/filetype-cplusplus.png b/Base/res/icons/32x32/filetype-cplusplus.png new file mode 100644 index 000000000000..cc67bd7a9f05 Binary files /dev/null and b/Base/res/icons/32x32/filetype-cplusplus.png differ diff --git a/Base/res/icons/32x32/filetype-header.png b/Base/res/icons/32x32/filetype-header.png new file mode 100644 index 000000000000..39b0ffd1e0da Binary files /dev/null and b/Base/res/icons/32x32/filetype-header.png differ
6bb6176762d6791e1e8355c7688d813c93fe5d74
2019-09-01 16:14:33
Conrad Pankoff
shell: Support semicolons for separating commands
false
Support semicolons for separating commands
shell
diff --git a/Shell/Parser.cpp b/Shell/Parser.cpp index dd85237fdacd..31ce752f9b9d 100644 --- a/Shell/Parser.cpp +++ b/Shell/Parser.cpp @@ -22,6 +22,13 @@ void Parser::commit_subcommand() m_subcommands.append({ move(m_tokens), move(m_redirections), {} }); } +void Parser::commit_command() +{ + if (m_subcommands.is_empty()) + return; + m_commands.append({ move(m_subcommands) }); +} + void Parser::do_pipe() { m_redirections.append({ Redirection::Pipe, STDOUT_FILENO }); @@ -38,7 +45,7 @@ void Parser::begin_redirect_write(int fd) m_redirections.append({ Redirection::FileWrite, fd }); } -Vector<Subcommand> Parser::parse() +Vector<Command> Parser::parse() { for (int i = 0; i < m_input.length(); ++i) { char ch = m_input.characters()[i]; @@ -48,6 +55,12 @@ Vector<Subcommand> Parser::parse() commit_token(); break; } + if (ch == ';') { + commit_token(); + commit_subcommand(); + commit_command(); + break; + } if (ch == '|') { commit_token(); if (m_tokens.is_empty()) { @@ -140,6 +153,7 @@ Vector<Subcommand> Parser::parse() } commit_token(); commit_subcommand(); + commit_command(); if (!m_subcommands.is_empty()) { for (auto& redirection : m_subcommands.last().redirections) { @@ -150,5 +164,5 @@ Vector<Subcommand> Parser::parse() } } - return move(m_subcommands); + return move(m_commands); } diff --git a/Shell/Parser.h b/Shell/Parser.h index 294a7ec63acf..5008046a00fc 100644 --- a/Shell/Parser.h +++ b/Shell/Parser.h @@ -27,6 +27,10 @@ struct Subcommand { Vector<Rewiring> rewirings; }; +struct Command { + Vector<Subcommand> subcommands; +}; + class Parser { public: explicit Parser(const String& input) @@ -34,11 +38,12 @@ class Parser { { } - Vector<Subcommand> parse(); + Vector<Command> parse(); private: void commit_token(); void commit_subcommand(); + void commit_command(); void do_pipe(); void begin_redirect_read(int fd); void begin_redirect_write(int fd); @@ -53,6 +58,7 @@ class Parser { State m_state { Free }; String m_input; + Vector<Command> m_commands; Vector<Subcommand> m_subcommands; Vector<String> m_tokens; Vector<Redirection> m_redirections; diff --git a/Shell/main.cpp b/Shell/main.cpp index 150d373618a0..67b4942e11e5 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -20,7 +20,7 @@ #include <termios.h> #include <unistd.h> -//#define SH_DEBUG +#define SH_DEBUG GlobalState g; static LineEditor editor; @@ -320,96 +320,42 @@ static int run_command(const String& cmd) if (cmd.is_empty()) return 0; - auto subcommands = Parser(cmd).parse(); + auto commands = Parser(cmd).parse(); #ifdef SH_DEBUG - for (int i = 0; i < subcommands.size(); ++i) { - for (int j = 0; j < i; ++j) - dbgprintf(" "); - for (auto& arg : subcommands[i].args) { - dbgprintf("<%s> ", arg.characters()); - } - dbgprintf("\n"); - for (auto& redirecton : subcommands[i].redirections) { + for (auto& command : commands) { + for (int i = 0; i < command.subcommands.size(); ++i) { for (int j = 0; j < i; ++j) dbgprintf(" "); - dbgprintf(" "); - switch (redirecton.type) { - case Redirection::Pipe: - dbgprintf("Pipe\n"); - break; - case Redirection::FileRead: - dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters()); - break; - case Redirection::FileWrite: - dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters()); - break; - case Redirection::FileWriteAppend: - dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.characters()); - break; - default: - break; - } - } - } -#endif - - if (subcommands.is_empty()) - return 0; - - FileDescriptionCollector fds; - - for (int i = 0; i < subcommands.size(); ++i) { - auto& subcommand = subcommands[i]; - for (auto& redirection : subcommand.redirections) { - switch (redirection.type) { - case Redirection::Pipe: { - int pipefd[2]; - int rc = pipe(pipefd); - if (rc < 0) { - perror("pipe"); - return 1; - } - subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] }); - auto& next_command = subcommands[i + 1]; - next_command.rewirings.append({ STDIN_FILENO, pipefd[0] }); - fds.add(pipefd[0]); - fds.add(pipefd[1]); - break; - } - case Redirection::FileWriteAppend: { - int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666); - if (fd < 0) { - perror("open"); - return 1; - } - subcommand.rewirings.append({ redirection.fd, fd }); - fds.add(fd); - break; + for (auto& arg : command.subcommands[i].args) { + dbgprintf("<%s> ", arg.characters()); } - case Redirection::FileWrite: { - int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666); - if (fd < 0) { - perror("open"); - return 1; + dbgprintf("\n"); + for (auto& redirecton : command.subcommands[i].redirections) { + for (int j = 0; j < i; ++j) + dbgprintf(" "); + dbgprintf(" "); + switch (redirecton.type) { + case Redirection::Pipe: + dbgprintf("Pipe\n"); + break; + case Redirection::FileRead: + dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters()); + break; + case Redirection::FileWrite: + dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters()); + break; + case Redirection::FileWriteAppend: + dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.characters()); + break; + default: + break; } - subcommand.rewirings.append({ redirection.fd, fd }); - fds.add(fd); - break; - } - case Redirection::FileRead: { - int fd = open(redirection.path.characters(), O_RDONLY); - if (fd < 0) { - perror("open"); - return 1; - } - subcommand.rewirings.append({ redirection.fd, fd }); - fds.add(fd); - break; - } } } + dbgprintf("\n"); } +#endif struct termios trm; tcgetattr(0, &trm); @@ -419,99 +365,159 @@ static int run_command(const String& cmd) pid_t pid; }; - Vector<SpawnedProcess> children; + int return_value = 0; - CommandTimer timer; + for (auto& command : commands) { + if (command.subcommands.is_empty()) + continue; - for (int i = 0; i < subcommands.size(); ++i) { - auto& subcommand = subcommands[i]; - Vector<String> argv_string = process_arguments(subcommand.args); - Vector<const char*> argv; - argv.ensure_capacity(argv_string.size()); - for (const auto& s : argv_string) { - argv.append(s.characters()); + FileDescriptionCollector fds; + + for (int i = 0; i < command.subcommands.size(); ++i) { + auto& subcommand = command.subcommands[i]; + for (auto& redirection : subcommand.redirections) { + switch (redirection.type) { + case Redirection::Pipe: { + int pipefd[2]; + int rc = pipe(pipefd); + if (rc < 0) { + perror("pipe"); + return 1; + } + subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] }); + auto& next_command = command.subcommands[i + 1]; + next_command.rewirings.append({ STDIN_FILENO, pipefd[0] }); + fds.add(pipefd[0]); + fds.add(pipefd[1]); + break; + } + case Redirection::FileWriteAppend: { + int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666); + if (fd < 0) { + perror("open"); + return 1; + } + subcommand.rewirings.append({ redirection.fd, fd }); + fds.add(fd); + break; + } + case Redirection::FileWrite: { + int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (fd < 0) { + perror("open"); + return 1; + } + subcommand.rewirings.append({ redirection.fd, fd }); + fds.add(fd); + break; + } + case Redirection::FileRead: { + int fd = open(redirection.path.characters(), O_RDONLY); + if (fd < 0) { + perror("open"); + return 1; + } + subcommand.rewirings.append({ redirection.fd, fd }); + fds.add(fd); + break; + } + } + } } - argv.append(nullptr); + + Vector<SpawnedProcess> children; + + CommandTimer timer; + + for (int i = 0; i < command.subcommands.size(); ++i) { + auto& subcommand = command.subcommands[i]; + Vector<String> argv_string = process_arguments(subcommand.args); + Vector<const char*> argv; + argv.ensure_capacity(argv_string.size()); + for (const auto& s : argv_string) { + argv.append(s.characters()); + } + argv.append(nullptr); #ifdef SH_DEBUG - for (auto& arg : argv) { - dbgprintf("<%s> ", arg); - } - dbgprintf("\n"); + for (auto& arg : argv) { + dbgprintf("<%s> ", arg); + } + dbgprintf("\n"); #endif - int retval = 0; - if (handle_builtin(argv.size() - 1, const_cast<char**>(argv.data()), retval)) - return retval; + int retval = 0; + if (handle_builtin(argv.size() - 1, const_cast<char**>(argv.data()), retval)) + return retval; - pid_t child = fork(); - if (!child) { - setpgid(0, 0); - tcsetpgrp(0, getpid()); - for (auto& rewiring : subcommand.rewirings) { + pid_t child = fork(); + if (!child) { + setpgid(0, 0); + tcsetpgrp(0, getpid()); + for (auto& rewiring : subcommand.rewirings) { #ifdef SH_DEBUG - dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), redirection.rewire_fd, redirection.fd); + dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.rewire_fd, rewiring.fd); #endif - int rc = dup2(rewiring.rewire_fd, rewiring.fd); - if (rc < 0) { - perror("dup2"); - return 1; + int rc = dup2(rewiring.rewire_fd, rewiring.fd); + if (rc < 0) { + perror("dup2"); + return 1; + } } - } - fds.collect(); + fds.collect(); - int rc = execvp(argv[0], const_cast<char* const*>(argv.data())); - if (rc < 0) { - if (errno == ENOENT) - fprintf(stderr, "%s: Command not found.\n", argv[0]); - else - fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno)); - exit(1); + int rc = execvp(argv[0], const_cast<char* const*>(argv.data())); + if (rc < 0) { + if (errno == ENOENT) + fprintf(stderr, "%s: Command not found.\n", argv[0]); + else + fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno)); + exit(1); + } + ASSERT_NOT_REACHED(); } - ASSERT_NOT_REACHED(); + children.append({ argv[0], child }); } - children.append({ argv[0], child }); - } #ifdef SH_DEBUG - dbgprintf("Closing fds in shell process:\n"); + dbgprintf("Closing fds in shell process:\n"); #endif - fds.collect(); + fds.collect(); #ifdef SH_DEBUG - dbgprintf("Now we gotta wait on children:\n"); - for (auto& child : children) - dbgprintf(" %d\n", child); + dbgprintf("Now we gotta wait on children:\n"); + for (auto& child : children) + dbgprintf(" %d\n", child); #endif - int wstatus = 0; - int return_value = 0; + int wstatus = 0; - for (int i = 0; i < children.size(); ++i) { - auto& child = children[i]; - do { - int rc = waitpid(child.pid, &wstatus, WEXITED | WSTOPPED); - if (rc < 0 && errno != EINTR) { - if (errno != ECHILD) - perror("waitpid"); - break; - } - if (WIFEXITED(wstatus)) { - if (WEXITSTATUS(wstatus) != 0) - dbg() << "Shell: " << child.name << ":" << child.pid << " exited with status " << WEXITSTATUS(wstatus); - if (i == 0) - return_value = WEXITSTATUS(wstatus); - } else if (WIFSTOPPED(wstatus)) { - printf("Shell: %s(%d) stopped.\n", child.name.characters(), child.pid); - } else { - if (WIFSIGNALED(wstatus)) { - printf("Shell: %s(%d) exited due to signal '%s'\n", child.name.characters(), child.pid, strsignal(WTERMSIG(wstatus))); + for (int i = 0; i < children.size(); ++i) { + auto& child = children[i]; + do { + int rc = waitpid(child.pid, &wstatus, WEXITED | WSTOPPED); + if (rc < 0 && errno != EINTR) { + if (errno != ECHILD) + perror("waitpid"); + break; + } + if (WIFEXITED(wstatus)) { + if (WEXITSTATUS(wstatus) != 0) + dbg() << "Shell: " << child.name << ":" << child.pid << " exited with status " << WEXITSTATUS(wstatus); + if (i == 0) + return_value = WEXITSTATUS(wstatus); + } else if (WIFSTOPPED(wstatus)) { + printf("Shell: %s(%d) stopped.\n", child.name.characters(), child.pid); } else { - printf("Shell: %s(%d) exited abnormally\n", child.name.characters(), child.pid); + if (WIFSIGNALED(wstatus)) { + printf("Shell: %s(%d) exited due to signal '%s'\n", child.name.characters(), child.pid, strsignal(WTERMSIG(wstatus))); + } else { + printf("Shell: %s(%d) exited abnormally\n", child.name.characters(), child.pid); + } } - } - } while (errno == EINTR); + } while (errno == EINTR); + } } // FIXME: Should I really have to tcsetpgrp() after my child has exited?
ae4d7076841cf5091e015871335043b62d71a613
2019-08-02 22:52:48
Andreas Kling
kernel: Align the KResult value storage appropriately.
false
Align the KResult value storage appropriately.
kernel
diff --git a/Kernel/KResult.h b/Kernel/KResult.h index b0c7a67f37ca..c631b226fcc3 100644 --- a/Kernel/KResult.h +++ b/Kernel/KResult.h @@ -94,7 +94,7 @@ class alignas(T) KResultOr { } private: - char m_storage[sizeof(T)] __attribute__((aligned(sizeof(T)))); + alignas (T) char m_storage[sizeof(T)]; KResult m_error; bool m_is_error { false }; };
4d5bd092ea2589621db1dd77f61b2fd7df800c23
2021-10-04 00:44:03
Linus Groh
libjs: Use MUST() where applicable
false
Use MUST() where applicable
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp index db880add23bd..7660e286ff53 100644 --- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.cpp @@ -393,7 +393,7 @@ Object* get_super_constructor(VM& vm) auto& active_function = verify_cast<FunctionEnvironment>(env).function_object(); // 5. Let superConstructor be ! activeFunction.[[GetPrototypeOf]](). - auto* super_constructor = active_function.internal_get_prototype_of().release_value(); + auto* super_constructor = MUST(active_function.internal_get_prototype_of()); // 6. Return superConstructor. return super_constructor; diff --git a/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp b/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp index 4c680cc0c43e..f5e500c9f28b 100644 --- a/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ArgumentsObject.cpp @@ -95,7 +95,7 @@ ThrowCompletionOr<bool> ArgumentsObject::internal_delete(PropertyName const& pro // 4. If result is true and isMapped is true, then if (result && is_mapped) { // a. Call map.[[Delete]](P). - (void)map.internal_delete(property_name); + MUST(map.internal_delete(property_name)); } // 5. Return result. @@ -106,7 +106,8 @@ ThrowCompletionOr<bool> ArgumentsObject::internal_delete(PropertyName const& pro ThrowCompletionOr<Optional<PropertyDescriptor>> ArgumentsObject::internal_get_own_property(PropertyName const& property_name) const { // 1. Let desc be OrdinaryGetOwnProperty(args, P). - auto desc = Object::internal_get_own_property(property_name).release_value(); + auto desc = MUST(Object::internal_get_own_property(property_name)); + // 2. If desc is undefined, return desc. if (!desc.has_value()) return desc; @@ -157,7 +158,7 @@ ThrowCompletionOr<bool> ArgumentsObject::internal_define_own_property(PropertyNa // a. If IsAccessorDescriptor(Desc) is true, then if (descriptor.is_accessor_descriptor()) { // i. Call map.[[Delete]](P). - (void)map.internal_delete(property_name); + MUST(map.internal_delete(property_name)); } else { // i. If Desc.[[Value]] is present, then if (descriptor.value.has_value()) { @@ -169,7 +170,7 @@ ThrowCompletionOr<bool> ArgumentsObject::internal_define_own_property(PropertyNa // ii. If Desc.[[Writable]] is present and its value is false, then if (descriptor.writable == false) { // 1. Call map.[[Delete]](P). - (void)map.internal_delete(property_name); + MUST(map.internal_delete(property_name)); } } } diff --git a/Userland/Libraries/LibJS/Runtime/Array.cpp b/Userland/Libraries/LibJS/Runtime/Array.cpp index 4c6435e9ebc7..a62a6934c7c1 100644 --- a/Userland/Libraries/LibJS/Runtime/Array.cpp +++ b/Userland/Libraries/LibJS/Runtime/Array.cpp @@ -24,7 +24,7 @@ Array* Array::create(GlobalObject& global_object, size_t length, Object* prototy if (!prototype) prototype = global_object.array_prototype(); auto* array = global_object.heap().allocate<Array>(global_object, *prototype); - (void)array->internal_define_own_property(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = false }); + MUST(array->internal_define_own_property(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = false })); return array; } @@ -198,7 +198,8 @@ ThrowCompletionOr<bool> Array::internal_define_own_property(PropertyName const& return false; // h. Let succeeded be ! OrdinaryDefineOwnProperty(A, P, Desc). - auto succeeded = Object::internal_define_own_property(property_name, property_descriptor).release_value(); + auto succeeded = MUST(Object::internal_define_own_property(property_name, property_descriptor)); + // i. If succeeded is false, return false. if (!succeeded) return false; diff --git a/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp b/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp index d348b2851cbb..905052fd0dd4 100644 --- a/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp @@ -861,7 +861,7 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::to_temporal_instant) ns = js_bigint(vm, ns->big_integer().multiplied_by(Crypto::UnsignedBigInteger { 1'000'000 })); // 3. Return ! CreateTemporalInstant(ns). - return Temporal::create_temporal_instant(global_object, *ns).release_value(); + return MUST(Temporal::create_temporal_instant(global_object, *ns)); } // 21.4.4.45 Date.prototype [ @@toPrimitive ] ( hint ), https://tc39.es/ecma262/#sec-date.prototype-@@toprimitive diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp index 5f42447e4fae..2a2b7791d757 100644 --- a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp @@ -203,7 +203,7 @@ void GlobalObject::initialize_global_object() }); m_throw_type_error_function->define_direct_property(vm.names.length, Value(0), 0); m_throw_type_error_function->define_direct_property(vm.names.name, js_string(vm, ""), 0); - (void)m_throw_type_error_function->internal_prevent_extensions(); + MUST(m_throw_type_error_function->internal_prevent_extensions()); // 10.2.4 AddRestrictedFunctionProperties ( F, realm ), https://tc39.es/ecma262/#sec-addrestrictedfunctionproperties m_function_prototype->define_direct_accessor(vm.names.caller, m_throw_type_error_function, m_throw_type_error_function, Attribute::Configurable); diff --git a/Userland/Libraries/LibJS/Runtime/StringObject.cpp b/Userland/Libraries/LibJS/Runtime/StringObject.cpp index 50270ab1e2d5..f061abedbf87 100644 --- a/Userland/Libraries/LibJS/Runtime/StringObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringObject.cpp @@ -97,7 +97,7 @@ ThrowCompletionOr<Optional<PropertyDescriptor>> StringObject::internal_get_own_p // Assert: IsPropertyKey(P) is true. // 2. Let desc be OrdinaryGetOwnProperty(S, P). - auto descriptor = Object::internal_get_own_property(property_name).release_value(); + auto descriptor = MUST(Object::internal_get_own_property(property_name)); // 3. If desc is not undefined, return desc. if (descriptor.has_value()) diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp index 3a5a73c5676d..4cb9c744c5a1 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp @@ -805,7 +805,7 @@ ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(GlobalObject& g // TODO // 3. Let result be ! ParseISODateTime(isoString). - auto result = parse_iso_date_time(global_object, iso_string).release_value(); + auto result = MUST(parse_iso_date_time(global_object, iso_string)); // 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString). auto time_zone_result = TRY(parse_temporal_time_zone_string(global_object, iso_string)); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp index 790ca80e274f..1d060ae77acd 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.cpp @@ -81,7 +81,7 @@ ThrowCompletionOr<Calendar*> get_builtin_calendar(GlobalObject& global_object, S Calendar* get_iso8601_calendar(GlobalObject& global_object) { // 1. Return ! GetBuiltinCalendar("iso8601"). - return get_builtin_calendar(global_object, "iso8601").release_value(); + return MUST(get_builtin_calendar(global_object, "iso8601")); } // 12.1.5 CalendarFields ( calendar, fieldNames ), https://tc39.es/proposal-temporal/#sec-temporal-calendarfields @@ -358,7 +358,7 @@ ThrowCompletionOr<Object*> to_temporal_calendar(GlobalObject& global_object, Val } // 4. Return ! CreateTemporalCalendar(identifier). - return create_temporal_calendar(global_object, identifier).release_value(); + return MUST(create_temporal_calendar(global_object, identifier)); } // 12.1.22 ToTemporalCalendarWithISODefault ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendarwithisodefault diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp index 5f579299a8a7..9cd2d314e88c 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/CalendarPrototype.cpp @@ -190,7 +190,7 @@ JS_DEFINE_NATIVE_FUNCTION(CalendarPrototype::date_add) auto* nanoseconds = js_bigint(vm, Crypto::SignedBigInteger::create_from(duration->nanoseconds())); // 8. Let balanceResult be ! BalanceDuration(duration.[[Days]], duration.[[Hours]], duration.[[Minutes]], duration.[[Seconds]], duration.[[Milliseconds]], duration.[[Microseconds]], duration.[[Nanoseconds]], "day"). - auto balance_result = balance_duration(global_object, duration->days(), duration->hours(), duration->minutes(), duration->seconds(), duration->milliseconds(), duration->microseconds(), *nanoseconds, "day"sv).release_value(); + auto balance_result = MUST(balance_duration(global_object, duration->days(), duration->hours(), duration->minutes(), duration->seconds(), duration->milliseconds(), duration->microseconds(), *nanoseconds, "day"sv)); // 9. Let result be ? AddISODate(date.[[ISOYear]], date.[[ISOMonth]], date.[[ISODay]], duration.[[Years]], duration.[[Months]], duration.[[Weeks]], balanceResult.[[Days]], overflow). auto result = TRY_OR_DISCARD(add_iso_date(global_object, date->iso_year(), date->iso_month(), date->iso_day(), duration->years(), duration->months(), duration->weeks(), balance_result.days, overflow)); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp index b6b155b480a2..f045bad40e86 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp @@ -266,7 +266,7 @@ Duration* create_negated_temporal_duration(GlobalObject& global_object, Duration // 2. Assert: duration has an [[InitializedTemporalDuration]] internal slot. // 3. Return ! CreateTemporalDuration(−duration.[[Years]], −duration.[[Months]], −duration.[[Weeks]], −duration.[[Days]], −duration.[[Hours]], −duration.[[Minutes]], −duration.[[Seconds]], −duration.[[Milliseconds]], −duration.[[Microseconds]], −duration.[[Nanoseconds]]). - return create_temporal_duration(global_object, -duration.years(), -duration.months(), -duration.weeks(), -duration.days(), -duration.hours(), -duration.minutes(), -duration.seconds(), -duration.milliseconds(), -duration.microseconds(), -duration.nanoseconds()).release_value(); + return MUST(create_temporal_duration(global_object, -duration.years(), -duration.months(), -duration.weeks(), -duration.days(), -duration.hours(), -duration.minutes(), -duration.seconds(), -duration.milliseconds(), -duration.microseconds(), -duration.nanoseconds())); } // 7.5.10 TotalDurationNanoseconds ( days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, offsetShift ), https://tc39.es/proposal-temporal/#sec-temporal-totaldurationnanoseconds diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/InstantConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/InstantConstructor.cpp index b498197da165..2be83e83a23a 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/InstantConstructor.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/InstantConstructor.cpp @@ -78,7 +78,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from) // 1. If Type(item) is Object and item has an [[InitializedTemporalInstant]] internal slot, then if (item.is_object() && is<Instant>(item.as_object())) { // a. Return ! CreateTemporalInstant(item.[[Nanoseconds]]). - return create_temporal_instant(global_object, *js_bigint(vm, static_cast<Instant&>(item.as_object()).nanoseconds().big_integer())).release_value(); + return MUST(create_temporal_instant(global_object, *js_bigint(vm, static_cast<Instant&>(item.as_object()).nanoseconds().big_integer()))); } // 2. Return ? ToTemporalInstant(item). @@ -108,7 +108,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_seconds) } // 5. Return ! CreateTemporalInstant(epochNanoseconds). - return create_temporal_instant(global_object, *epoch_nanoseconds).release_value(); + return MUST(create_temporal_instant(global_object, *epoch_nanoseconds)); } // 8.2.4 Temporal.Instant.fromEpochMilliseconds ( epochMilliseconds ), https://tc39.es/proposal-temporal/#sec-temporal.instant.fromepochmilliseconds @@ -134,7 +134,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_milliseconds) } // 5. Return ! CreateTemporalInstant(epochNanoseconds). - return create_temporal_instant(global_object, *epoch_nanoseconds).release_value(); + return MUST(create_temporal_instant(global_object, *epoch_nanoseconds)); } // 8.2.5 Temporal.Instant.fromEpochMicroseconds ( epochMicroseconds ), https://tc39.es/proposal-temporal/#sec-temporal.instant.fromepochmicroseconds @@ -155,7 +155,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_microseconds) } // 4. Return ! CreateTemporalInstant(epochNanoseconds). - return create_temporal_instant(global_object, *epoch_nanoseconds).release_value(); + return MUST(create_temporal_instant(global_object, *epoch_nanoseconds)); } // 8.2.6 Temporal.Instant.fromEpochNanoseconds ( epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal.instant.fromepochnanoseconds @@ -173,7 +173,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantConstructor::from_epoch_nanoseconds) } // 3. Return ! CreateTemporalInstant(epochNanoseconds). - return create_temporal_instant(global_object, *epoch_nanoseconds).release_value(); + return MUST(create_temporal_instant(global_object, *epoch_nanoseconds)); } // 8.2.7 Temporal.Instant.compare ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal.instant.compare diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp index e7236155a960..d1007bba053c 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/InstantPrototype.cpp @@ -145,7 +145,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::add) return {}; // 5. Return ! CreateTemporalInstant(ns). - return create_temporal_instant(global_object, *ns).release_value(); + return MUST(create_temporal_instant(global_object, *ns)); } // 8.3.8 Temporal.Instant.prototype.subtract ( temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal.instant.prototype.subtract @@ -166,7 +166,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::subtract) auto* ns = TRY_OR_DISCARD(add_instant(global_object, instant->nanoseconds(), -duration.hours, -duration.minutes, -duration.seconds, -duration.milliseconds, -duration.microseconds, -duration.nanoseconds)); // 5. Return ! CreateTemporalInstant(ns). - return create_temporal_instant(global_object, *ns).release_value(); + return MUST(create_temporal_instant(global_object, *ns)); } // 8.3.9 Temporal.Instant.prototype.until ( other [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal.instant.prototype.until @@ -209,7 +209,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::until) auto rounded_ns = difference_instant(global_object, instant->nanoseconds(), other->nanoseconds(), rounding_increment, *smallest_unit, rounding_mode); // 13. Let result be ! BalanceDuration(0, 0, 0, 0, 0, 0, roundedNs, largestUnit). - auto result = balance_duration(global_object, 0, 0, 0, 0, 0, 0, *rounded_ns, largest_unit).release_value(); + auto result = MUST(balance_duration(global_object, 0, 0, 0, 0, 0, 0, *rounded_ns, largest_unit)); // 14. Return ? CreateTemporalDuration(0, 0, 0, 0, result.[[Hours]], result.[[Minutes]], result.[[Seconds]], result.[[Milliseconds]], result.[[Microseconds]], result.[[Nanoseconds]]). return TRY_OR_DISCARD(create_temporal_duration(global_object, 0, 0, 0, 0, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds)); @@ -255,7 +255,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::since) auto rounded_ns = difference_instant(global_object, other->nanoseconds(), instant->nanoseconds(), rounding_increment, *smallest_unit, rounding_mode); // 13. Let result be ! BalanceDuration(0, 0, 0, 0, 0, 0, roundedNs, largestUnit). - auto result = balance_duration(global_object, 0, 0, 0, 0, 0, 0, *rounded_ns, largest_unit).release_value(); + auto result = MUST(balance_duration(global_object, 0, 0, 0, 0, 0, 0, *rounded_ns, largest_unit)); // 14. Return ? CreateTemporalDuration(0, 0, 0, 0, result.[[Hours]], result.[[Minutes]], result.[[Seconds]], result.[[Milliseconds]], result.[[Microseconds]], result.[[Nanoseconds]]). return TRY_OR_DISCARD(create_temporal_duration(global_object, 0, 0, 0, 0, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds)); @@ -337,7 +337,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::round) return {}; // 16. Return ! CreateTemporalInstant(roundedNs). - return create_temporal_instant(global_object, *rounded_ns).release_value(); + return MUST(create_temporal_instant(global_object, *rounded_ns)); } // 8.3.12 Temporal.Instant.prototype.equals ( other ), https://tc39.es/proposal-temporal/#sec-temporal.instant.prototype.equals @@ -395,7 +395,7 @@ JS_DEFINE_NATIVE_FUNCTION(InstantPrototype::to_string) return {}; // 9. Let roundedInstant be ! CreateTemporalInstant(roundedNs). - auto* rounded_instant = create_temporal_instant(global_object, *rounded_ns).release_value(); + auto* rounded_instant = MUST(create_temporal_instant(global_object, *rounded_ns)); // 10. Return ? TemporalInstantToString(roundedInstant, timeZone, precision.[[Precision]]). return js_string(vm, TRY_OR_DISCARD(temporal_instant_to_string(global_object, *rounded_instant, time_zone, precision.precision))); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp index 8effb37e6fd8..afc15ee0e4c8 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/Now.cpp @@ -187,7 +187,7 @@ Instant* system_instant(GlobalObject& global_object) auto* ns = system_utc_epoch_nanoseconds(global_object); // 2. Return ! CreateTemporalInstant(ns). - return create_temporal_instant(global_object, *ns).release_value(); + return MUST(create_temporal_instant(global_object, *ns)); } // 2.3.4 SystemDateTime ( temporalTimeZoneLike, calendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-systemdatetime diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp index cbc3f7418bb0..45812eac3c6d 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTimePrototype.cpp @@ -112,7 +112,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::year_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -137,7 +137,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::month_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -162,7 +162,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::month_code_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -187,7 +187,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::day_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -212,7 +212,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::hour_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -237,7 +237,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::minute_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -262,7 +262,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::second_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -287,7 +287,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::millisecond_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -312,7 +312,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::microsecond_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -337,7 +337,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::nanosecond_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -432,7 +432,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::day_of_week_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -457,7 +457,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::day_of_year_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -482,7 +482,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::week_of_year_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -507,7 +507,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::days_in_week_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -532,7 +532,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::days_in_month_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -557,7 +557,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::days_in_year_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -582,7 +582,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::months_in_year_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -607,7 +607,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::in_leap_year_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -632,7 +632,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::offset_nanoseconds_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Return 𝔽(? GetOffsetNanosecondsFor(timeZone, instant)). return Value(TRY_OR_DISCARD(get_offset_nanoseconds_for(global_object, &time_zone, *instant))); @@ -648,7 +648,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::offset_getter) return {}; // 3. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 4. Return ? BuiltinTimeZoneGetOffsetStringFor(zonedDateTime.[[TimeZone]], instant). auto offset_string = TRY_OR_DISCARD(builtin_time_zone_get_offset_string_for(global_object, &zoned_date_time->time_zone(), *instant)); @@ -668,7 +668,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::era_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -693,7 +693,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::era_year_getter) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -723,7 +723,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_instant) return {}; // 3. Return ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - return create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + return MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); } // 6.3.47 Temporal.ZonedDateTime.prototype.toPlainDate ( ), https://tc39.es/proposal-temporal/#sec-temporal.zoneddatetime.prototype.toplaindate @@ -739,7 +739,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_plain_date) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -764,7 +764,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_plain_time) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -789,7 +789,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_plain_date_time) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Return ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, zonedDateTime.[[Calendar]]). return TRY_OR_DISCARD(builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *instant, zoned_date_time->calendar())); @@ -808,7 +808,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_plain_year_month) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -839,7 +839,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::to_plain_month_day) auto& time_zone = zoned_date_time->time_zone(); // 4. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 5. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar(); @@ -875,7 +875,7 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::get_iso_fields) auto& time_zone = zoned_date_time->time_zone(); // 5. Let instant be ! CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). - auto* instant = create_temporal_instant(global_object, zoned_date_time->nanoseconds()).release_value(); + auto* instant = MUST(create_temporal_instant(global_object, zoned_date_time->nanoseconds())); // 6. Let calendar be zonedDateTime.[[Calendar]]. auto& calendar = zoned_date_time->calendar();
adc5ac35b79834bd0551a317e7230cea49d35c4b
2022-08-27 02:56:03
Linus Groh
libjs: Remove InvalidCharacterError
false
Remove InvalidCharacterError
libjs
diff --git a/Userland/Libraries/LibJS/Forward.h b/Userland/Libraries/LibJS/Forward.h index 072f529d945e..740a978e38fe 100644 --- a/Userland/Libraries/LibJS/Forward.h +++ b/Userland/Libraries/LibJS/Forward.h @@ -46,14 +46,13 @@ JS_ENUMERATE_NATIVE_OBJECTS_EXCLUDING_TEMPLATES \ __JS_ENUMERATE(TypedArray, typed_array, TypedArrayPrototype, TypedArrayConstructor, void) -#define JS_ENUMERATE_NATIVE_ERRORS \ - __JS_ENUMERATE(EvalError, eval_error, EvalErrorPrototype, EvalErrorConstructor, void) \ - __JS_ENUMERATE(InternalError, internal_error, InternalErrorPrototype, InternalErrorConstructor, void) \ - __JS_ENUMERATE(InvalidCharacterError, invalid_character_error, InvalidCharacterErrorPrototype, InvalidCharacterErrorConstructor, void) \ - __JS_ENUMERATE(RangeError, range_error, RangeErrorPrototype, RangeErrorConstructor, void) \ - __JS_ENUMERATE(ReferenceError, reference_error, ReferenceErrorPrototype, ReferenceErrorConstructor, void) \ - __JS_ENUMERATE(SyntaxError, syntax_error, SyntaxErrorPrototype, SyntaxErrorConstructor, void) \ - __JS_ENUMERATE(TypeError, type_error, TypeErrorPrototype, TypeErrorConstructor, void) \ +#define JS_ENUMERATE_NATIVE_ERRORS \ + __JS_ENUMERATE(EvalError, eval_error, EvalErrorPrototype, EvalErrorConstructor, void) \ + __JS_ENUMERATE(InternalError, internal_error, InternalErrorPrototype, InternalErrorConstructor, void) \ + __JS_ENUMERATE(RangeError, range_error, RangeErrorPrototype, RangeErrorConstructor, void) \ + __JS_ENUMERATE(ReferenceError, reference_error, ReferenceErrorPrototype, ReferenceErrorConstructor, void) \ + __JS_ENUMERATE(SyntaxError, syntax_error, SyntaxErrorPrototype, SyntaxErrorConstructor, void) \ + __JS_ENUMERATE(TypeError, type_error, TypeErrorPrototype, TypeErrorConstructor, void) \ __JS_ENUMERATE(URIError, uri_error, URIErrorPrototype, URIErrorConstructor, void) #define JS_ENUMERATE_TYPED_ARRAYS \
74748277477d34ef221dd2ed228404788065fa27
2022-11-06 17:53:33
martinfalisse
libweb: Use AvailableSpace when referring to the grid width
false
Use AvailableSpace when referring to the grid width
libweb
diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp index 2a75b4499680..4bd495923e82 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp @@ -45,9 +45,9 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const if (grid_size.length().is_auto()) break; return grid_size.length().to_px(box); - break; case CSS::GridSize::Type::Percentage: - return grid_size.percentage().as_fraction() * box_state.content_width(); + if (available_space.width.is_definite()) + return grid_size.percentage().as_fraction() * available_space.width.to_px(); break; default: VERIFY_NOT_REACHED(); @@ -124,7 +124,7 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const sum_of_grid_track_sizes += min(resolve_definite_track_size(track_sizing_function.grid_size()), resolve_definite_track_size(track_sizing_function.grid_size())); } } - column_count = max(1, static_cast<int>(get_free_space_x(box) / sum_of_grid_track_sizes)); + column_count = max(1, static_cast<int>(get_free_space_x(available_space) / sum_of_grid_track_sizes)); // For the purpose of finding the number of auto-repeated tracks in a standalone axis, the UA must // floor the track size to a UA-specified value to avoid division by zero. It is suggested that this @@ -795,7 +795,8 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const grid_column.base_size = grid_column.min_track_sizing_function.length().to_px(box); break; case CSS::GridSize::Type::Percentage: - grid_column.base_size = grid_column.min_track_sizing_function.percentage().as_fraction() * box_state.content_width(); + if (available_space.width.is_definite()) + grid_column.base_size = grid_column.min_track_sizing_function.percentage().as_fraction() * available_space.width.to_px(); break; // - An intrinsic sizing function // Use an initial base size of zero. @@ -818,7 +819,8 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const grid_column.growth_limit = -1; break; case CSS::GridSize::Type::Percentage: - grid_column.growth_limit = grid_column.max_track_sizing_function.percentage().as_fraction() * box_state.content_width(); + if (available_space.width.is_definite()) + grid_column.growth_limit = grid_column.max_track_sizing_function.percentage().as_fraction() * available_space.width.to_px(); break; // - A flexible sizing function // Use an initial growth limit of infinity. @@ -1017,7 +1019,7 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const for (auto& grid_column : m_grid_columns) grid_column.space_to_distribute = max(0, (grid_column.growth_limit == -1 ? grid_column.base_size : grid_column.growth_limit) - grid_column.base_size); - auto remaining_free_space = box_state.content_width() - sum_of_track_sizes; + auto remaining_free_space = available_space.width.is_definite() ? available_space.width.to_px() - sum_of_track_sizes : 0; // 2.2. Distribute space up to limits: Find the item-incurred increase for each spanned track with an // affected size by: distributing the space equally among such tracks, freezing a track’s // item-incurred increase as its affected size + item-incurred increase reaches its limit (and @@ -1088,7 +1090,7 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const // If the free space is positive, distribute it equally to the base sizes of all tracks, freezing // tracks as they reach their growth limits (and continuing to grow the unfrozen tracks as needed). - auto free_space = get_free_space_x(box); + auto free_space = get_free_space_x(available_space); while (free_space > 0) { auto free_space_to_distribute_per_track = free_space / m_grid_columns.size(); for (auto& grid_column : m_grid_columns) { @@ -1097,9 +1099,9 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const else grid_column.base_size = grid_column.base_size + free_space_to_distribute_per_track; } - if (get_free_space_x(box) == free_space) + if (get_free_space_x(available_space) == free_space) break; - free_space = get_free_space_x(box); + free_space = get_free_space_x(available_space); } // For the purpose of this step: if sizing the grid container under a max-content constraint, the @@ -1133,7 +1135,7 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const sized_column_widths += grid_column.base_size; } // Let leftover space be the space to fill minus the base sizes of the non-flexible grid tracks. - double free_horizontal_space = box_state.content_width() - sized_column_widths; + double free_horizontal_space = available_space.width.is_definite() ? available_space.width.to_px() - sized_column_widths : 0; // If the free space is zero or if sizing the grid container under a min-content constraint: // The used flex fraction is zero. @@ -1206,7 +1208,7 @@ void GridFormattingContext::run(Box const& box, LayoutMode, AvailableSpace const used_horizontal_space += grid_column.base_size; } - float remaining_horizontal_space = box_state.content_width() - used_horizontal_space; + float remaining_horizontal_space = available_space.width.is_definite() ? available_space.width.to_px() - used_horizontal_space : 0; auto count_of_auto_max_column_tracks = 0; for (auto& grid_column : m_grid_columns) { if (grid_column.max_track_sizing_function.is_length() && grid_column.max_track_sizing_function.length().is_auto()) @@ -1717,18 +1719,19 @@ bool GridFormattingContext::is_auto_positioned_track(CSS::GridTrackPlacement con return grid_track_start.is_auto_positioned() && grid_track_end.is_auto_positioned(); } -float GridFormattingContext::get_free_space_x(Box const& box) +float GridFormattingContext::get_free_space_x(AvailableSpace const& available_space) { // https://www.w3.org/TR/css-grid-2/#algo-terms // free space: Equal to the available grid space minus the sum of the base sizes of all the grid // tracks (including gutters), floored at zero. If available grid space is indefinite, the free // space is indefinite as well. // FIXME: do indefinite space + if (!available_space.width.is_definite()) + return 0; auto sum_base_sizes = 0; for (auto& grid_column : m_grid_columns) sum_base_sizes += grid_column.base_size; - auto& box_state = m_state.get_mutable(box); - return max(0, box_state.content_width() - sum_base_sizes); + return max(0, available_space.width.to_px() - sum_base_sizes); } float GridFormattingContext::get_free_space_y(Box const& box) diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h index d38666f39839..43c797eb0bfa 100644 --- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h +++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h @@ -38,7 +38,7 @@ class GridFormattingContext final : public BlockFormattingContext { Vector<GridTrackSizeConstraints> m_grid_rows; Vector<GridTrackSizeConstraints> m_grid_columns; - float get_free_space_x(Box const&); + float get_free_space_x(AvailableSpace const& available_space); float get_free_space_y(Box const&); int get_line_index_by_line_name(String const& line_name, CSS::GridTrackSizeList);
f866c80222da84dda3917e56b6d1b14beeeedb6c
2023-05-20 02:03:57
Ben Wiederhake
libpdf: Avoid unnecessary HashMap copy, mark other copies
false
Avoid unnecessary HashMap copy, mark other copies
libpdf
diff --git a/Userland/Libraries/LibPDF/Encoding.cpp b/Userland/Libraries/LibPDF/Encoding.cpp index de4a826d7d38..549c71d4c9a4 100644 --- a/Userland/Libraries/LibPDF/Encoding.cpp +++ b/Userland/Libraries/LibPDF/Encoding.cpp @@ -43,8 +43,8 @@ PDFErrorOr<NonnullRefPtr<Encoding>> Encoding::from_object(Document* document, No auto encoding = adopt_ref(*new Encoding()); - encoding->m_descriptors = base_encoding->m_descriptors; - encoding->m_name_mapping = base_encoding->m_name_mapping; + encoding->m_descriptors = TRY(base_encoding->m_descriptors.clone()); + encoding->m_name_mapping = TRY(base_encoding->m_name_mapping.clone()); auto differences_array = TRY(dict->get_array(document, CommonNames::Differences)); diff --git a/Userland/Libraries/LibPDF/Parser.cpp b/Userland/Libraries/LibPDF/Parser.cpp index 4f90d0647174..3f878bd8c59c 100644 --- a/Userland/Libraries/LibPDF/Parser.cpp +++ b/Userland/Libraries/LibPDF/Parser.cpp @@ -432,7 +432,7 @@ PDFErrorOr<NonnullRefPtr<DictObject>> Parser::parse_dict() return error("Expected dict to end with \">>\""); m_reader.consume_whitespace(); - return make_object<DictObject>(map); + return make_object<DictObject>(move(map)); } PDFErrorOr<NonnullRefPtr<StreamObject>> Parser::parse_stream(NonnullRefPtr<DictObject> dict)
6cf89e46c9d09bcdc1cacbd5f7556c7c5c7083cc
2024-11-27 15:29:48
devgianlu
libcrypto: Parse EC private key when parsing an ASN.1 `PrivateKeyInfo`
false
Parse EC private key when parsing an ASN.1 `PrivateKeyInfo`
libcrypto
diff --git a/Libraries/LibCrypto/Certificate/Certificate.cpp b/Libraries/LibCrypto/Certificate/Certificate.cpp index 537f99e8b245..e43302f61ddc 100644 --- a/Libraries/LibCrypto/Certificate/Certificate.cpp +++ b/Libraries/LibCrypto/Certificate/Certificate.cpp @@ -12,6 +12,7 @@ #include <LibCrypto/ASN1/ASN1.h> #include <LibCrypto/ASN1/DER.h> #include <LibCrypto/ASN1/PEM.h> +#include <LibCrypto/PK/EC.h> namespace { static String s_error_string; @@ -436,6 +437,17 @@ ErrorOr<PrivateKey> parse_private_key_info(Crypto::ASN1::Decoder& decoder, Vecto EXIT_SCOPE(); return private_key; } + if (private_key.algorithm.identifier.span() == ec_public_key_encryption_oid.span()) { + auto maybe_key = Crypto::PK::EC::parse_ec_key(value.bytes()); + if (maybe_key.is_error()) { + ERROR_WITH_SCOPE(TRY(String::formatted("Invalid EC key at {}: {}", current_scope, maybe_key.release_error()))); + } + + private_key.ec = move(maybe_key.release_value().private_key); + + EXIT_SCOPE(); + return private_key; + } // https://datatracker.ietf.org/doc/html/rfc8410#section-9 // For all of the OIDs, the parameters MUST be absent. diff --git a/Libraries/LibCrypto/Certificate/Certificate.h b/Libraries/LibCrypto/Certificate/Certificate.h index baefb4e831b9..7a07f567eafb 100644 --- a/Libraries/LibCrypto/Certificate/Certificate.h +++ b/Libraries/LibCrypto/Certificate/Certificate.h @@ -14,6 +14,7 @@ #include <LibCore/ConfigFile.h> #include <LibCrypto/ASN1/DER.h> #include <LibCrypto/BigInt/UnsignedBigInteger.h> +#include <LibCrypto/PK/EC.h> #include <LibCrypto/PK/RSA.h> namespace Crypto::Certificate { @@ -262,6 +263,7 @@ ErrorOr<SubjectPublicKey> parse_subject_public_key_info(Crypto::ASN1::Decoder& d class PrivateKey { public: Crypto::PK::RSAPrivateKey<Crypto::UnsignedBigInteger> rsa; + Crypto::PK::ECPrivateKey<Crypto::UnsignedBigInteger> ec; AlgorithmIdentifier algorithm; ByteBuffer raw_key;
6024617df383bda00241c62d5cf3507a9c7c846c
2021-05-06 17:07:46
Andreas Kling
lookupserver: Remove some unnecessary "rc" temporaries
false
Remove some unnecessary "rc" temporaries
lookupserver
diff --git a/Userland/Services/LookupServer/MulticastDNS.cpp b/Userland/Services/LookupServer/MulticastDNS.cpp index 99293e0c7d62..768679af1a81 100644 --- a/Userland/Services/LookupServer/MulticastDNS.cpp +++ b/Userland/Services/LookupServer/MulticastDNS.cpp @@ -23,24 +23,21 @@ MulticastDNS::MulticastDNS(Object* parent) , m_hostname("courage.local") { char buffer[HOST_NAME_MAX]; - int rc = gethostname(buffer, sizeof(buffer)); - if (rc < 0) { + if (gethostname(buffer, sizeof(buffer)) < 0) { perror("gethostname"); } else { m_hostname = String::formatted("{}.local", buffer); } u8 zero = 0; - rc = setsockopt(fd(), IPPROTO_IP, IP_MULTICAST_LOOP, &zero, 1); - if (rc < 0) + if (setsockopt(fd(), IPPROTO_IP, IP_MULTICAST_LOOP, &zero, 1) < 0) perror("setsockopt(IP_MULTICAST_LOOP)"); ip_mreq mreq = { mdns_addr.sin_addr, { htonl(INADDR_ANY) }, }; - rc = setsockopt(fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); - if (rc < 0) - perror("setsockopt(IP_ADD_MEMBESHIP)"); + if (setsockopt(fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) + perror("setsockopt(IP_ADD_MEMBERSHIP)"); bind(IPv4Address(), 5353); @@ -98,8 +95,7 @@ void MulticastDNS::announce() response.add_answer(answer); } - int rc = emit_packet(response); - if (rc < 0) + if (emit_packet(response) < 0) perror("Failed to emit response packet"); } @@ -147,8 +143,7 @@ Vector<DNSAnswer> MulticastDNS::lookup(const DNSName& name, unsigned short recor request.set_is_query(); request.add_question({ name, record_type, C_IN }); - int rc = emit_packet(request); - if (rc < 0) { + if (emit_packet(request) < 0) { perror("failed to emit request packet"); return {}; } @@ -159,7 +154,7 @@ Vector<DNSAnswer> MulticastDNS::lookup(const DNSName& name, unsigned short recor // the main loop while we wait for a response. while (true) { pollfd pfd { fd(), POLLIN, 0 }; - rc = poll(&pfd, 1, 1000); + auto rc = poll(&pfd, 1, 1000); if (rc < 0) { perror("poll"); } else if (rc == 0) {
9cc3e7d32d150dd30d683c1a8cf0bd59676f14ab
2024-07-25 02:53:09
Diego Frias
libwasm: Fix SIMD shuffle and swizzle
false
Fix SIMD shuffle and swizzle
libwasm
diff --git a/AK/SIMDExtras.h b/AK/SIMDExtras.h index 3147f2fb3a8d..081ab2cf7862 100644 --- a/AK/SIMDExtras.h +++ b/AK/SIMDExtras.h @@ -220,13 +220,14 @@ ALWAYS_INLINE static T shuffle_or_0_impl(T a, Control control, IndexSequence<Idx if constexpr (__has_builtin(__builtin_shuffle)) { // GCC does a very bad job at optimizing the masking, while not recognizing the shuffle idiom // So we jinx its __builtin_shuffle to work with out of bounds indices + // TODO: verify that this masking logic is correct (for machines with __builtin_shuffle) auto mask = (control >= 0) | (control < N); return __builtin_shuffle(a, control & mask) & ~mask; } // 1. Set all out of bounds values to ~0 // Note: This is done so that the optimization mentioned down below works // Note: Vector compares result in bitmasks, aka all 1s or all 0s per element - control |= ~((control > 0) | (control < N)); + control |= ~((control >= 0) & (control < N)); // 2. Selectively set out of bounds values to 0 // Note: Clang successfully optimizes this to a few instructions on x86-ssse3, GCC does not // Vector Optimizations/Instruction-Selection on ArmV8 seem to not be as powerful as of Clang18 diff --git a/Userland/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.cpp b/Userland/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.cpp index bf6cf86d7087..28dd42b8216a 100644 --- a/Userland/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.cpp +++ b/Userland/Libraries/LibWasm/AbstractMachine/BytecodeInterpreter.cpp @@ -1289,12 +1289,17 @@ void BytecodeInterpreter::interpret(Configuration& configuration, InstructionPoi case Instructions::f64x2_splat.value(): return pop_and_push_m_splat<64, NativeFloatingType>(configuration, instruction); case Instructions::i8x16_shuffle.value(): { - auto indices = pop_vector<u8, MakeSigned>(configuration); - TRAP_IF_NOT(indices.has_value()); - auto vector = peek_vector<u8, MakeSigned>(configuration); - TRAP_IF_NOT(vector.has_value()); - auto result = shuffle_vector(vector.value(), indices.value()); - configuration.stack().peek() = Value(result); + auto& arg = instruction.arguments().get<Instruction::ShuffleArgument>(); + auto b = *pop_vector<u8, MakeUnsigned>(configuration); + auto a = *pop_vector<u8, MakeUnsigned>(configuration); + using VectorType = Native128ByteVectorOf<u8, MakeUnsigned>; + VectorType result; + for (size_t i = 0; i < 16; ++i) + if (arg.lanes[i] < 16) + result[i] = a[arg.lanes[i]]; + else + result[i] = b[arg.lanes[i] - 16]; + configuration.stack().push(Value(bit_cast<u128>(result))); return; } case Instructions::v128_store.value(): diff --git a/Userland/Libraries/LibWasm/AbstractMachine/Operators.h b/Userland/Libraries/LibWasm/AbstractMachine/Operators.h index e421cf8af115..ad9843e03a92 100644 --- a/Userland/Libraries/LibWasm/AbstractMachine/Operators.h +++ b/Userland/Libraries/LibWasm/AbstractMachine/Operators.h @@ -239,8 +239,8 @@ struct VectorSwizzle { auto operator()(u128 c1, u128 c2) const { // https://webassembly.github.io/spec/core/bikeshed/#-mathsfi8x16hrefsyntax-instr-vecmathsfswizzle%E2%91%A0 - auto i = bit_cast<Native128ByteVectorOf<i8, MakeSigned>>(c2); - auto j = bit_cast<Native128ByteVectorOf<i8, MakeSigned>>(c1); + auto i = bit_cast<Native128ByteVectorOf<i8, MakeSigned>>(c1); + auto j = bit_cast<Native128ByteVectorOf<i8, MakeSigned>>(c2); auto result = shuffle_or_0(i, j); return bit_cast<u128>(result); }
afb19a2cff861d5abeab561d438db0c982f6ca7d
2023-08-11 13:13:46
Gurkirat Singh
ports: Fix `clean_dist` function in .port_include.sh
false
Fix `clean_dist` function in .port_include.sh
ports
diff --git a/Ports/.port_include.sh b/Ports/.port_include.sh index 0b4cac92f24a..f9fa23a819ae 100755 --- a/Ports/.port_include.sh +++ b/Ports/.port_include.sh @@ -422,7 +422,8 @@ clean() { } clean_dist() { for f in "${files[@]}"; do - read url filename hash <<< $(echo "$f") + read url hash <<< "$f" + filename=$(basename "$url") rm -f "${PORT_META_DIR}/${filename}" done }
95e011e2a0b7c9b4c50d18d37a3d64d0e751c77c
2022-08-05 16:16:42
Andreas Kling
libweb: Support assigning to window.location
false
Support assigning to window.location
libweb
diff --git a/Userland/Libraries/LibWeb/Bindings/WindowObject.cpp b/Userland/Libraries/LibWeb/Bindings/WindowObject.cpp index 97197a26988b..ac97550c31f6 100644 --- a/Userland/Libraries/LibWeb/Bindings/WindowObject.cpp +++ b/Userland/Libraries/LibWeb/Bindings/WindowObject.cpp @@ -133,7 +133,7 @@ void WindowObject::initialize_global_object() define_direct_property("clientInformation", m_navigator_object, JS::Attribute::Enumerable | JS::Attribute::Configurable); // NOTE: location is marked as [LegacyUnforgeable], meaning it isn't configurable. - define_direct_property("location", m_location_object, JS::Attribute::Enumerable); + define_native_accessor("location", location_getter, location_setter, JS::Attribute::Enumerable); // WebAssembly "namespace" define_direct_property("WebAssembly", heap().allocate<WebAssemblyObject>(*this, *this), JS::Attribute::Enumerable | JS::Attribute::Configurable); @@ -184,7 +184,7 @@ static JS::ThrowCompletionOr<HTML::Window*> impl_from(JS::VM& vm, JS::GlobalObje auto* this_object = MUST(this_value.to_object(global_object)); - if ("WindowObject"sv != this_object->class_name()) + if (!is<WindowObject>(*this_object)) return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "WindowObject"); return &static_cast<WindowObject*>(this_object)->impl(); } @@ -453,6 +453,21 @@ JS_DEFINE_NATIVE_FUNCTION(WindowObject::event_setter) REPLACEABLE_PROPERTY_SETTER(WindowObject, event); } +JS_DEFINE_NATIVE_FUNCTION(WindowObject::location_getter) +{ + auto* impl = TRY(impl_from(vm, global_object)); + VERIFY(impl->wrapper()); + return impl->wrapper()->m_location_object; +} + +JS_DEFINE_NATIVE_FUNCTION(WindowObject::location_setter) +{ + auto* impl = TRY(impl_from(vm, global_object)); + VERIFY(impl->wrapper()); + TRY(impl->wrapper()->m_location_object->set(JS::PropertyKey("href"), vm.argument(0), JS::Object::ShouldThrowExceptions::Yes)); + return JS::js_undefined(); +} + JS_DEFINE_NATIVE_FUNCTION(WindowObject::crypto_getter) { auto* impl = TRY(impl_from(vm, global_object)); diff --git a/Userland/Libraries/LibWeb/Bindings/WindowObject.h b/Userland/Libraries/LibWeb/Bindings/WindowObject.h index 383280ae86fe..85797c0a1785 100644 --- a/Userland/Libraries/LibWeb/Bindings/WindowObject.h +++ b/Userland/Libraries/LibWeb/Bindings/WindowObject.h @@ -82,6 +82,9 @@ class WindowObject JS_DECLARE_NATIVE_FUNCTION(document_getter); + JS_DECLARE_NATIVE_FUNCTION(location_getter); + JS_DECLARE_NATIVE_FUNCTION(location_setter); + JS_DECLARE_NATIVE_FUNCTION(name_getter); JS_DECLARE_NATIVE_FUNCTION(name_setter);
522119ab9553194db0a881258dfedec3c34b90c9
2021-09-17 01:59:21
Marcus Nilsson
libgui: Implement is_min() & is_max() helpers to AbstractSlider
false
Implement is_min() & is_max() helpers to AbstractSlider
libgui
diff --git a/Userland/Libraries/LibGUI/AbstractSlider.h b/Userland/Libraries/LibGUI/AbstractSlider.h index aec489c875cc..f3a199198282 100644 --- a/Userland/Libraries/LibGUI/AbstractSlider.h +++ b/Userland/Libraries/LibGUI/AbstractSlider.h @@ -26,6 +26,9 @@ class AbstractSlider : public Widget { int page_step() const { return m_page_step; } bool jump_to_cursor() const { return m_jump_to_cursor; } + bool is_min() const { return m_value == m_min; } + bool is_max() const { return m_value == m_max; } + void set_range(int min, int max); virtual void set_value(int);
06f93950568b8e5167f64007fa4980a3050904a2
2021-09-29 22:27:48
Sam Atkins
libweb: Add CSSGroupingRule
false
Add CSSGroupingRule
libweb
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt index 5453182e4f37..12e3941df54e 100644 --- a/Userland/Libraries/LibWeb/CMakeLists.txt +++ b/Userland/Libraries/LibWeb/CMakeLists.txt @@ -12,6 +12,7 @@ set(SOURCES Bindings/ScriptExecutionContext.cpp Bindings/WindowObject.cpp Bindings/Wrappable.cpp + CSS/CSSGroupingRule.cpp CSS/CSSImportRule.cpp CSS/CSSRule.cpp CSS/CSSRuleList.cpp diff --git a/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.cpp b/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.cpp new file mode 100644 index 000000000000..59cc281c69ba --- /dev/null +++ b/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/CSS/CSSGroupingRule.h> +#include <LibWeb/CSS/CSSRuleList.h> + +namespace Web::CSS { + +CSSGroupingRule::CSSGroupingRule(NonnullRefPtrVector<CSSRule>&& rules) + : m_rules(CSSRuleList { move(rules) }) +{ +} + +CSSGroupingRule::~CSSGroupingRule() +{ +} + +size_t CSSGroupingRule::insert_rule(StringView const&, size_t) +{ + // https://www.w3.org/TR/cssom-1/#insert-a-css-rule + TODO(); +} + +void CSSGroupingRule::delete_rule(size_t) +{ + // https://www.w3.org/TR/cssom-1/#remove-a-css-rule + TODO(); +} + +} diff --git a/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.h b/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.h new file mode 100644 index 000000000000..e60a7ff8a370 --- /dev/null +++ b/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021, Sam Atkins <[email protected]> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/NonnullRefPtr.h> +#include <LibWeb/CSS/CSSRule.h> +#include <LibWeb/CSS/CSSRuleList.h> +#include <LibWeb/Forward.h> + +namespace Web::CSS { + +class CSSGroupingRule : public CSSRule { + AK_MAKE_NONCOPYABLE(CSSGroupingRule); + AK_MAKE_NONMOVABLE(CSSGroupingRule); + +public: + ~CSSGroupingRule(); + + CSSRuleList const& css_rules() const { return m_rules; } + size_t insert_rule(StringView const& rule, size_t index = 0); + void delete_rule(size_t index); + +protected: + explicit CSSGroupingRule(NonnullRefPtrVector<CSSRule>&&); + +private: + CSSRuleList m_rules; +}; + +} diff --git a/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.idl b/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.idl new file mode 100644 index 000000000000..6c904e0f7495 --- /dev/null +++ b/Userland/Libraries/LibWeb/CSS/CSSGroupingRule.idl @@ -0,0 +1,6 @@ +interface CSSGroupingRule : CSSRule { + [SameObject] readonly attribute CSSRuleList cssRules; + unsigned long insertRule(CSSOMString rule, optional unsigned long index = 0); + undefined deleteRule(unsigned long index); +}; +
63670f27decddf7f73d0301bb3ce8b696c57bbc8
2023-07-12 09:58:15
Nico Weber
libpdf: Rename m_disable_encryption to m_enable_encryption
false
Rename m_disable_encryption to m_enable_encryption
libpdf
diff --git a/Userland/Libraries/LibPDF/Parser.cpp b/Userland/Libraries/LibPDF/Parser.cpp index 3cc22ece2d65..5897846de242 100644 --- a/Userland/Libraries/LibPDF/Parser.cpp +++ b/Userland/Libraries/LibPDF/Parser.cpp @@ -17,7 +17,7 @@ namespace PDF { PDFErrorOr<Vector<Operator>> Parser::parse_operators(Document* document, ReadonlyBytes bytes) { Parser parser(document, bytes); - parser.m_disable_encryption = true; + parser.m_enable_encryption = false; return parser.parse_operators(); } @@ -260,7 +260,7 @@ NonnullRefPtr<StringObject> Parser::parse_string() auto string_object = make_object<StringObject>(string, is_binary_string); - if (m_document->security_handler() && !m_disable_encryption) + if (m_document->security_handler() && m_enable_encryption) m_document->security_handler()->decrypt(string_object, m_current_reference_stack.last()); auto unencrypted_string = string_object->string(); @@ -471,7 +471,7 @@ PDFErrorOr<NonnullRefPtr<StreamObject>> Parser::parse_stream(NonnullRefPtr<DictO auto stream_object = make_object<StreamObject>(dict, MUST(ByteBuffer::copy(bytes))); - if (m_document->security_handler() && !m_disable_encryption) + if (m_document->security_handler() && m_enable_encryption) m_document->security_handler()->decrypt(stream_object, m_current_reference_stack.last()); if (dict->contains(CommonNames::Filter)) { diff --git a/Userland/Libraries/LibPDF/Parser.h b/Userland/Libraries/LibPDF/Parser.h index f1205af6cc50..a65dbd449159 100644 --- a/Userland/Libraries/LibPDF/Parser.h +++ b/Userland/Libraries/LibPDF/Parser.h @@ -72,7 +72,7 @@ class Parser { Reader m_reader; WeakPtr<Document> m_document; Vector<Reference> m_current_reference_stack; - bool m_disable_encryption { false }; + bool m_enable_encryption { true }; }; };
6b39c6b1bf62218edf6478c8f55a543e069ea51a
2021-12-30 18:56:29
Daniel Bertalan
shell: Avoid many single byte write() syscalls when printing the prompt
false
Avoid many single byte write() syscalls when printing the prompt
shell
diff --git a/Userland/Shell/Shell.cpp b/Userland/Shell/Shell.cpp index 0b31ed99f61a..d0630ffe7dbe 100644 --- a/Userland/Shell/Shell.cpp +++ b/Userland/Shell/Shell.cpp @@ -1660,8 +1660,11 @@ void Shell::bring_cursor_to_beginning_of_a_line() const fputs(eol_mark.characters(), stderr); - for (auto i = eol_mark_length; i < ws.ws_col; ++i) - putc(' ', stderr); + // We write a line's worth of whitespace to the terminal. This way, we ensure that + // the prompt ends up on a new line even if there is dangling output on the current line. + size_t fill_count = ws.ws_col - eol_mark_length; + auto fill_buffer = String::repeated(' ', fill_count); + fwrite(fill_buffer.characters(), 1, fill_count, stderr); putc('\r', stderr); }
aeb5a0d9e8cb65f7de5a0146c6993353df55b3b9
2024-03-02 13:39:10
Aliaksandr Kalenik
libweb: Remove glyph run allocation in RecordingPainter::draw_text_run
false
Remove glyph run allocation in RecordingPainter::draw_text_run
libweb
diff --git a/Userland/Libraries/LibWeb/Painting/Command.h b/Userland/Libraries/LibWeb/Painting/Command.h index f75d00bdc9f5..3175e7f1266f 100644 --- a/Userland/Libraries/LibWeb/Painting/Command.h +++ b/Userland/Libraries/LibWeb/Painting/Command.h @@ -41,6 +41,7 @@ struct DrawGlyphRun { Vector<Gfx::DrawGlyphOrEmoji> glyph_run; Color color; Gfx::IntRect rect; + Gfx::FloatPoint translation; [[nodiscard]] Gfx::IntRect bounding_rect() const { return rect; } diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp index 888e5f42b4bc..fa774b5cd1f6 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.cpp @@ -24,15 +24,17 @@ CommandExecutorCPU::CommandExecutorCPU(Gfx::Bitmap& bitmap) .scaling_mode = {} }); } -CommandResult CommandExecutorCPU::draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const& color) +CommandResult CommandExecutorCPU::draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const& color, Gfx::FloatPoint translation) { auto& painter = this->painter(); for (auto& glyph_or_emoji : glyph_run) { + auto transformed_glyph = glyph_or_emoji; + transformed_glyph.visit([&](auto& glyph) { glyph.position.translate_by(translation); }); if (glyph_or_emoji.has<Gfx::DrawGlyph>()) { - auto& glyph = glyph_or_emoji.get<Gfx::DrawGlyph>(); + auto& glyph = transformed_glyph.get<Gfx::DrawGlyph>(); painter.draw_glyph(glyph.position, glyph.code_point, *glyph.font, color); } else { - auto& emoji = glyph_or_emoji.get<Gfx::DrawEmoji>(); + auto& emoji = transformed_glyph.get<Gfx::DrawEmoji>(); painter.draw_emoji(emoji.position.to_type<int>(), *emoji.emoji, *emoji.font); } } diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h index f59f55758117..a6806d7f3aac 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorCPU.h @@ -13,7 +13,7 @@ namespace Web::Painting { class CommandExecutorCPU : public CommandExecutor { public: - CommandResult draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const&) override; + CommandResult draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const&, Gfx::FloatPoint translation) override; CommandResult draw_text(Gfx::IntRect const& rect, String const& raw_text, Gfx::TextAlignment alignment, Color const&, Gfx::TextElision, Gfx::TextWrapping, Optional<NonnullRefPtr<Gfx::Font>> const&) override; CommandResult fill_rect(Gfx::IntRect const& rect, Color const&) override; CommandResult draw_scaled_bitmap(Gfx::IntRect const& dst_rect, Gfx::Bitmap const& bitmap, Gfx::IntRect const& src_rect, Gfx::Painter::ScalingMode scaling_mode) override; diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.cpp b/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.cpp index d62ac40c2dfa..d1ca02f10fff 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.cpp +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.cpp @@ -31,9 +31,16 @@ CommandExecutorGPU::~CommandExecutorGPU() painter().flush(m_target_bitmap); } -CommandResult CommandExecutorGPU::draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const& color) -{ - painter().draw_glyph_run(glyph_run, color); +CommandResult CommandExecutorGPU::draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const& color, Gfx::FloatPoint translation) +{ + Vector<Gfx::DrawGlyphOrEmoji> transformed_glyph_run; + transformed_glyph_run.ensure_capacity(glyph_run.size()); + for (auto& glyph : glyph_run) { + auto transformed_glyph = glyph; + transformed_glyph.visit([&](auto& glyph) { glyph.position.translate_by(translation); }); + transformed_glyph_run.append(transformed_glyph); + } + painter().draw_glyph_run(transformed_glyph_run, color); return CommandResult::Continue; } diff --git a/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h b/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h index dcc610212a5a..a2a938d2f3d4 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h +++ b/Userland/Libraries/LibWeb/Painting/CommandExecutorGPU.h @@ -14,7 +14,7 @@ namespace Web::Painting { class CommandExecutorGPU : public CommandExecutor { public: - CommandResult draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const&) override; + CommandResult draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const&, Gfx::FloatPoint translation) override; CommandResult draw_text(Gfx::IntRect const& rect, String const& raw_text, Gfx::TextAlignment alignment, Color const&, Gfx::TextElision, Gfx::TextWrapping, Optional<NonnullRefPtr<Gfx::Font>> const&) override; CommandResult fill_rect(Gfx::IntRect const& rect, Color const&) override; CommandResult draw_scaled_bitmap(Gfx::IntRect const& dst_rect, Gfx::Bitmap const& bitmap, Gfx::IntRect const& src_rect, Gfx::Painter::ScalingMode scaling_mode) override; diff --git a/Userland/Libraries/LibWeb/Painting/CommandList.cpp b/Userland/Libraries/LibWeb/Painting/CommandList.cpp index bee31bf9021a..e9779ba65001 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandList.cpp +++ b/Userland/Libraries/LibWeb/Painting/CommandList.cpp @@ -87,7 +87,7 @@ void CommandList::execute(CommandExecutor& executor) auto result = command.visit( [&](DrawGlyphRun const& command) { - return executor.draw_glyph_run(command.glyph_run, command.color); + return executor.draw_glyph_run(command.glyph_run, command.color, command.translation); }, [&](DrawText const& command) { return executor.draw_text(command.rect, command.raw_text, command.alignment, command.color, diff --git a/Userland/Libraries/LibWeb/Painting/CommandList.h b/Userland/Libraries/LibWeb/Painting/CommandList.h index 01c6803244a3..06dd9155202c 100644 --- a/Userland/Libraries/LibWeb/Painting/CommandList.h +++ b/Userland/Libraries/LibWeb/Painting/CommandList.h @@ -47,7 +47,7 @@ class CommandExecutor { public: virtual ~CommandExecutor() = default; - virtual CommandResult draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const&) = 0; + virtual CommandResult draw_glyph_run(Vector<Gfx::DrawGlyphOrEmoji> const& glyph_run, Color const&, Gfx::FloatPoint translation) = 0; virtual CommandResult draw_text(Gfx::IntRect const&, String const&, Gfx::TextAlignment alignment, Color const&, Gfx::TextElision, Gfx::TextWrapping, Optional<NonnullRefPtr<Gfx::Font>> const&) = 0; virtual CommandResult fill_rect(Gfx::IntRect const&, Color const&) = 0; virtual CommandResult draw_scaled_bitmap(Gfx::IntRect const& dst_rect, Gfx::Bitmap const& bitmap, Gfx::IntRect const& src_rect, Gfx::Painter::ScalingMode scaling_mode) = 0; diff --git a/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp b/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp index 3faa2a4a381e..a0757da515c1 100644 --- a/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp +++ b/Userland/Libraries/LibWeb/Painting/RecordingPainter.cpp @@ -209,16 +209,11 @@ void RecordingPainter::draw_signed_distance_field(Gfx::IntRect const& dst_rect, void RecordingPainter::draw_text_run(Gfx::IntPoint baseline_start, Span<Gfx::DrawGlyphOrEmoji const> glyph_run, Color color, Gfx::IntRect const& rect) { auto transformed_baseline_start = state().translation.map(baseline_start).to_type<float>(); - Vector<Gfx::DrawGlyphOrEmoji> translated_glyph_run; - translated_glyph_run.ensure_capacity(glyph_run.size()); - for (auto glyph : glyph_run) { - glyph.visit([&](auto& glyph) { glyph.position.translate_by(transformed_baseline_start); }); - translated_glyph_run.append(glyph); - } append(DrawGlyphRun { - .glyph_run = move(translated_glyph_run), + .glyph_run = Vector<Gfx::DrawGlyphOrEmoji> { glyph_run }, .color = color, .rect = state().translation.map(rect), + .translation = transformed_baseline_start, }); }
7768f97333baa850905df1561feceaf3dcd16845
2023-12-14 21:32:15
Sönke Holz
meta: Force signed char on all architectures
false
Force signed char on all architectures
meta
diff --git a/Meta/CMake/serenity_compile_options.cmake b/Meta/CMake/serenity_compile_options.cmake index ecb5ef132f92..e43597012fc9 100644 --- a/Meta/CMake/serenity_compile_options.cmake +++ b/Meta/CMake/serenity_compile_options.cmake @@ -20,6 +20,7 @@ add_compile_options(-Wwrite-strings) add_compile_options(-fno-delete-null-pointer-checks) add_compile_options(-ffile-prefix-map=${SerenityOS_SOURCE_DIR}=.) add_compile_options(-fno-omit-frame-pointer) +add_compile_options(-fsigned-char) add_compile_options(-fsized-deallocation) add_compile_options(-fstack-clash-protection) add_compile_options(-fstack-protector-strong)
6aa82f8b0b17e07a4228110ea6369b4398a56a3c
2022-10-03 00:44:02
Andreas Kling
libweb: Report the current OS instead of always saying SerenityOS
false
Report the current OS instead of always saying SerenityOS
libweb
diff --git a/Userland/Libraries/LibWeb/Loader/ResourceLoader.h b/Userland/Libraries/LibWeb/Loader/ResourceLoader.h index 40454db13cd8..1db16862d227 100644 --- a/Userland/Libraries/LibWeb/Loader/ResourceLoader.h +++ b/Userland/Libraries/LibWeb/Loader/ResourceLoader.h @@ -26,7 +26,25 @@ namespace Web { # define CPU_STRING "AArch64" #endif -constexpr auto default_user_agent = "Mozilla/5.0 (SerenityOS; " CPU_STRING ") LibWeb+LibJS/1.0 Browser/1.0"; +#if defined(AK_OS_SERENITY) +# define OS_STRING "SerenityOS" +#elif defined(AK_OS_LINUX) +# define OS_STRING "Linux" +#elif defined(AK_OS_MAC) +# define OS_STRING "macOS" +#elif defined(AK_OS_WINDOWS) +# define OS_STRING "Windows" +#elif defined(AK_OS_FREEBSD) +# define OS_STRING "FreeBSD" +#elif defined(AK_OS_OPENBSD) +# define OS_STRING "OpenBSD" +#elif defined(AK_OS_NETBSD) +# define OS_STRING "NetBSD" +#else +# error Unknown OS +#endif + +constexpr auto default_user_agent = "Mozilla/5.0 (" OS_STRING "; " CPU_STRING ") LibWeb+LibJS/1.0 Browser/1.0"; class ResourceLoaderConnectorRequest : public RefCounted<ResourceLoaderConnectorRequest> { public:
8449f0a15bca9cfd0c1a727a9319cb08d83a6426
2020-05-31 02:01:08
Sergey Bugaev
libipc: Fix server crashes on client disconnects
false
Fix server crashes on client disconnects
libipc
diff --git a/Libraries/LibIPC/ClientConnection.h b/Libraries/LibIPC/ClientConnection.h index d1a78034254a..0a821cd2963c 100644 --- a/Libraries/LibIPC/ClientConnection.h +++ b/Libraries/LibIPC/ClientConnection.h @@ -121,7 +121,8 @@ class ClientConnection : public Core::Object { return; default: perror("Connection::post_message write"); - ASSERT_NOT_REACHED(); + shutdown(); + return; } } @@ -130,6 +131,9 @@ class ClientConnection : public Core::Object { void drain_messages_from_client() { + if (!m_socket->is_open()) + return; + Vector<u8> bytes; for (;;) { u8 buffer[4096]; @@ -143,7 +147,8 @@ class ClientConnection : public Core::Object { } if (nread < 0) { perror("recv"); - ASSERT_NOT_REACHED(); + shutdown(); + return; } bytes.append(buffer, nread); }
29d90ccf3b1cb1146573a7ff3b5e5dbe42863ce3
2023-05-12 09:17:36
Timothy Flynn
libweb: Implement the legacy extracting an encoding AO
false
Implement the legacy extracting an encoding AO
libweb
diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.cpp b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.cpp index c09c3dffb604..628fad1f746b 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.cpp +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.cpp @@ -15,6 +15,7 @@ #include <LibJS/Heap/Heap.h> #include <LibJS/Runtime/VM.h> #include <LibRegex/Regex.h> +#include <LibTextCodec/Decoder.h> #include <LibWeb/Fetch/Infrastructure/HTTP.h> #include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h> #include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h> @@ -392,6 +393,29 @@ ErrorOr<Optional<MimeSniff::MimeType>> HeaderList::extract_mime_type() const return mime_type; } +// https://fetch.spec.whatwg.org/#legacy-extract-an-encoding +StringView legacy_extract_an_encoding(Optional<MimeSniff::MimeType> const& mime_type, StringView fallback_encoding) +{ + // 1. If mimeType is failure, then return fallbackEncoding. + if (!mime_type.has_value()) + return fallback_encoding; + + // 2. If mimeType["charset"] does not exist, then return fallbackEncoding. + auto charset = mime_type->parameters().get("charset"sv); + if (!charset.has_value()) + return fallback_encoding; + + // 3. Let tentativeEncoding be the result of getting an encoding from mimeType["charset"]. + auto tentative_encoding = TextCodec::get_standardized_encoding(*charset); + + // 4. If tentativeEncoding is failure, then return fallbackEncoding. + if (!tentative_encoding.has_value()) + return fallback_encoding; + + // 5. Return tentativeEncoding. + return *tentative_encoding; +} + // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set ErrorOr<OrderedHashTable<ByteBuffer>> convert_header_names_to_a_sorted_lowercase_set(Span<ReadonlyBytes> header_names) { diff --git a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h index 23723ddac2fe..3d778c20ec26 100644 --- a/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h +++ b/Userland/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Headers.h @@ -70,6 +70,7 @@ struct RangeHeaderValue { struct ExtractHeaderParseFailure { }; +[[nodiscard]] StringView legacy_extract_an_encoding(Optional<MimeSniff::MimeType> const& mime_type, StringView fallback_encoding); [[nodiscard]] ErrorOr<Optional<Vector<String>>> get_decode_and_split_header_value(ReadonlyBytes); [[nodiscard]] ErrorOr<OrderedHashTable<ByteBuffer>> convert_header_names_to_a_sorted_lowercase_set(Span<ReadonlyBytes>); [[nodiscard]] bool is_header_name(ReadonlyBytes);
fdfdb5bd1c42581e48b63c9c23b8f048aa47557c
2022-01-21 20:57:21
Idan Horowitz
kernel: Make ACPI reboot OOM-fallible
false
Make ACPI reboot OOM-fallible
kernel
diff --git a/Kernel/Firmware/ACPI/Parser.cpp b/Kernel/Firmware/ACPI/Parser.cpp index aed9950dc36c..22dc88f5fa24 100644 --- a/Kernel/Firmware/ACPI/Parser.cpp +++ b/Kernel/Firmware/ACPI/Parser.cpp @@ -199,8 +199,10 @@ UNMAP_AFTER_INIT void Parser::process_fadt_data() bool Parser::can_reboot() { - auto fadt = Memory::map_typed<Structures::FADT>(m_fadt).release_value_but_fixme_should_propagate_errors(); - if (fadt->h.revision < 2) + auto fadt_or_error = Memory::map_typed<Structures::FADT>(m_fadt); + if (fadt_or_error.is_error()) + return false; + if (fadt_or_error.value()->h.revision < 2) return false; return m_hardware_flags.reset_register_supported; } @@ -272,11 +274,10 @@ void Parser::access_generic_address(const Structures::GenericAddressStructure& s VERIFY_NOT_REACHED(); } -bool Parser::validate_reset_register() +bool Parser::validate_reset_register(Memory::TypedMapping<Structures::FADT> const& fadt) { // According to https://uefi.org/specs/ACPI/6.4/04_ACPI_Hardware_Specification/ACPI_Hardware_Specification.html#reset-register, // the reset register can only be located in I/O bus, PCI bus or memory-mapped. - auto fadt = Memory::map_typed<Structures::FADT>(m_fadt).release_value_but_fixme_should_propagate_errors(); return (fadt->reset_reg.address_space == (u8)GenericAddressStructure::AddressSpace::PCIConfigurationSpace || fadt->reset_reg.address_space == (u8)GenericAddressStructure::AddressSpace::SystemMemory || fadt->reset_reg.address_space == (u8)GenericAddressStructure::AddressSpace::SystemIO); } @@ -289,8 +290,13 @@ void Parser::try_acpi_reboot() } dbgln_if(ACPI_DEBUG, "ACPI: Rebooting, probing FADT ({})", m_fadt); - auto fadt = Memory::map_typed<Structures::FADT>(m_fadt).release_value_but_fixme_should_propagate_errors(); - VERIFY(validate_reset_register()); + auto fadt_or_error = Memory::map_typed<Structures::FADT>(m_fadt); + if (fadt_or_error.is_error()) { + dmesgln("ACPI: Failed probing FADT {}", fadt_or_error.error()); + return; + } + auto fadt = fadt_or_error.release_value(); + VERIFY(validate_reset_register(fadt)); access_generic_address(fadt->reset_reg, fadt->reset_value); Processor::halt(); } diff --git a/Kernel/Firmware/ACPI/Parser.h b/Kernel/Firmware/ACPI/Parser.h index ee300cf9c314..77ba39b59040 100644 --- a/Kernel/Firmware/ACPI/Parser.h +++ b/Kernel/Firmware/ACPI/Parser.h @@ -15,6 +15,7 @@ #include <Kernel/Firmware/SysFSFirmware.h> #include <Kernel/Interrupts/IRQHandler.h> #include <Kernel/Memory/Region.h> +#include <Kernel/Memory/TypedMapping.h> #include <Kernel/PhysicalAddress.h> #include <Kernel/VirtualAddress.h> @@ -89,7 +90,7 @@ class Parser final : public IRQHandler { u8 get_table_revision(PhysicalAddress); void process_fadt_data(); - bool validate_reset_register(); + bool validate_reset_register(Memory::TypedMapping<Structures::FADT> const&); void access_generic_address(const Structures::GenericAddressStructure&, u32 value); PhysicalAddress m_rsdp;
f2efb97578ce8073e063d4c4a486f53e6817f492
2023-04-08 22:54:13
Nico Weber
tests: Add webp lossless test with color index and < 16 colors
false
Add webp lossless test with color index and < 16 colors
tests
diff --git a/Tests/LibGfx/TestImageDecoder.cpp b/Tests/LibGfx/TestImageDecoder.cpp index 74d395fb0a02..c8e2ced9a38f 100644 --- a/Tests/LibGfx/TestImageDecoder.cpp +++ b/Tests/LibGfx/TestImageDecoder.cpp @@ -380,6 +380,46 @@ TEST_CASE(test_webp_simple_lossless_color_index_transform) EXPECT_EQ(frame.image->get_pixel(100, 100), Gfx::Color(0x73, 0x37, 0x23, 0xff)); } +TEST_CASE(test_webp_simple_lossless_color_index_transform_pixel_bundling) +{ + struct TestCase { + StringView file_name; + Gfx::Color line_color; + Gfx::Color background_color; + }; + + // The number after the dash is the number of colors in each file's color index bitmap. + // catdog-alert-2 tests the 1-bit-per-pixel case, + // catdog-alert-3 tests the 2-bit-per-pixel case, + // catdog-alert-8 and catdog-alert-13 both test the 4-bits-per-pixel case. + TestCase test_cases[] = { + { "catdog-alert-2.webp"sv, Gfx::Color(0x35, 0x12, 0x0a, 0xff), Gfx::Color(0xf3, 0xe6, 0xd8, 0xff) }, + { "catdog-alert-3.webp"sv, Gfx::Color(0x35, 0x12, 0x0a, 0xff), Gfx::Color(0, 0, 0, 0) }, + { "catdog-alert-8.webp"sv, Gfx::Color(0, 0, 0, 255), Gfx::Color(0, 0, 0, 0) }, + { "catdog-alert-13.webp"sv, Gfx::Color(0, 0, 0, 255), Gfx::Color(0, 0, 0, 0) }, + }; + + for (auto test_case : test_cases) { + auto file = MUST(Core::MappedFile::map(MUST(String::formatted("{}{}", TEST_INPUT(""), test_case.file_name)))); + EXPECT(Gfx::WebPImageDecoderPlugin::sniff(file->bytes())); + auto plugin_decoder = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); + EXPECT(plugin_decoder->initialize()); + + EXPECT_EQ(plugin_decoder->frame_count(), 1u); + EXPECT_EQ(plugin_decoder->size(), Gfx::IntSize(32, 32)); + + auto frame = MUST(plugin_decoder->frame(0)); + EXPECT_EQ(frame.image->size(), Gfx::IntSize(32, 32)); + + EXPECT_EQ(frame.image->get_pixel(4, 0), test_case.background_color); + EXPECT_EQ(frame.image->get_pixel(5, 0), test_case.line_color); + + EXPECT_EQ(frame.image->get_pixel(9, 5), test_case.background_color); + EXPECT_EQ(frame.image->get_pixel(10, 5), test_case.line_color); + EXPECT_EQ(frame.image->get_pixel(11, 5), test_case.background_color); + } +} + TEST_CASE(test_webp_extended_lossless_animated) { auto file = MUST(Core::MappedFile::map(TEST_INPUT("extended-lossless-animated.webp"sv))); diff --git a/Tests/LibGfx/test-inputs/catdog-alert-13.webp b/Tests/LibGfx/test-inputs/catdog-alert-13.webp new file mode 100644 index 000000000000..3c3254d3e2b4 Binary files /dev/null and b/Tests/LibGfx/test-inputs/catdog-alert-13.webp differ diff --git a/Tests/LibGfx/test-inputs/catdog-alert-2.webp b/Tests/LibGfx/test-inputs/catdog-alert-2.webp new file mode 100644 index 000000000000..5a675b94503e Binary files /dev/null and b/Tests/LibGfx/test-inputs/catdog-alert-2.webp differ diff --git a/Tests/LibGfx/test-inputs/catdog-alert-3.webp b/Tests/LibGfx/test-inputs/catdog-alert-3.webp new file mode 100644 index 000000000000..c6a178d49967 Binary files /dev/null and b/Tests/LibGfx/test-inputs/catdog-alert-3.webp differ diff --git a/Tests/LibGfx/test-inputs/catdog-alert-8.webp b/Tests/LibGfx/test-inputs/catdog-alert-8.webp new file mode 100644 index 000000000000..2d355dc0b89d Binary files /dev/null and b/Tests/LibGfx/test-inputs/catdog-alert-8.webp differ
1acd67977586d19a124aaf97a69b86b0df5ef7f1
2023-02-19 13:43:04
Liav A
kernel: Remove unnecessary include from SysFS PowerStateSwitch code
false
Remove unnecessary include from SysFS PowerStateSwitch code
kernel
diff --git a/Kernel/FileSystem/SysFS/Subsystems/Kernel/PowerStateSwitch.cpp b/Kernel/FileSystem/SysFS/Subsystems/Kernel/PowerStateSwitch.cpp index 3f469634eabc..e2756b48a710 100644 --- a/Kernel/FileSystem/SysFS/Subsystems/Kernel/PowerStateSwitch.cpp +++ b/Kernel/FileSystem/SysFS/Subsystems/Kernel/PowerStateSwitch.cpp @@ -16,7 +16,6 @@ #include <Kernel/Process.h> #include <Kernel/Sections.h> #include <Kernel/TTY/ConsoleManagement.h> -#include <Kernel/WorkQueue.h> namespace Kernel {
66f8ea92cbd200894370d3c7a58024257a2c3167
2019-07-29 01:24:34
Andreas Kling
libaudio: Silence some debug spam in the WAV loader.
false
Silence some debug spam in the WAV loader.
libaudio
diff --git a/Libraries/LibAudio/AWavLoader.cpp b/Libraries/LibAudio/AWavLoader.cpp index f4078cd4dc10..46371d88415d 100644 --- a/Libraries/LibAudio/AWavLoader.cpp +++ b/Libraries/LibAudio/AWavLoader.cpp @@ -242,7 +242,9 @@ RefPtr<ABuffer> ABuffer::from_pcm_data(ByteBuffer& data, int num_channels, int b Vector<ASample> fdata; fdata.ensure_capacity(data.size() * 2); +#ifdef AWAVLOADER_DEBUG dbg() << "Reading " << bits_per_sample << " bits and " << num_channels << " channels, total bytes: " << data.size(); +#endif switch (bits_per_sample) { case 8:
bb31b682a58a2c2f9dca6966957b8658b85df0e5
2024-11-26 19:20:27
stelar7
libweb: Implement IDBDatabase::close()
false
Implement IDBDatabase::close()
libweb
diff --git a/Libraries/LibWeb/IndexedDB/IDBDatabase.h b/Libraries/LibWeb/IndexedDB/IDBDatabase.h index cc02d21c4ed7..e1085f890d29 100644 --- a/Libraries/LibWeb/IndexedDB/IDBDatabase.h +++ b/Libraries/LibWeb/IndexedDB/IDBDatabase.h @@ -10,6 +10,7 @@ #include <LibWeb/DOM/EventTarget.h> #include <LibWeb/HTML/DOMStringList.h> #include <LibWeb/IndexedDB/IDBRequest.h> +#include <LibWeb/IndexedDB/Internal/Algorithms.h> #include <LibWeb/IndexedDB/Internal/Database.h> #include <LibWeb/StorageAPI/StorageKey.h> @@ -35,6 +36,7 @@ class IDBDatabase : public DOM::EventTarget { void set_version(u64 version) { m_version = version; } void set_close_pending(bool close_pending) { m_close_pending = close_pending; } + void set_state(ConnectionState state) { m_state = state; } [[nodiscard]] GC::Ref<HTML::DOMStringList> object_store_names() { return m_object_store_names; } [[nodiscard]] String name() const { return m_name; } @@ -43,6 +45,13 @@ class IDBDatabase : public DOM::EventTarget { [[nodiscard]] ConnectionState state() const { return m_state; } [[nodiscard]] GC::Ref<Database> associated_database() { return m_associated_database; } + // https://w3c.github.io/IndexedDB/#dom-idbdatabase-close + void close() + { + // 1. Run close a database connection with this connection. + close_a_database_connection(*this); + } + void set_onabort(WebIDL::CallbackType*); WebIDL::CallbackType* onabort(); void set_onclose(WebIDL::CallbackType*); diff --git a/Libraries/LibWeb/IndexedDB/IDBDatabase.idl b/Libraries/LibWeb/IndexedDB/IDBDatabase.idl index 2b3960575147..917441e482fa 100644 --- a/Libraries/LibWeb/IndexedDB/IDBDatabase.idl +++ b/Libraries/LibWeb/IndexedDB/IDBDatabase.idl @@ -8,7 +8,7 @@ interface IDBDatabase : EventTarget { readonly attribute DOMStringList objectStoreNames; [FIXME, NewObject] IDBTransaction transaction((DOMString or sequence<DOMString>) storeNames, optional IDBTransactionMode mode = "readonly", optional IDBTransactionOptions options = {}); - [FIXME] undefined close(); + undefined close(); [FIXME, NewObject] IDBObjectStore createObjectStore(DOMString name, optional IDBObjectStoreParameters options = {}); [FIXME] undefined deleteObjectStore(DOMString name); diff --git a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp index 097a822eb05b..9a35879d97fa 100644 --- a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp +++ b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.cpp @@ -13,6 +13,7 @@ #include <LibJS/Runtime/VM.h> #include <LibWeb/DOM/EventDispatcher.h> #include <LibWeb/HTML/EventNames.h> +#include <LibWeb/IndexedDB/IDBDatabase.h> #include <LibWeb/IndexedDB/IDBRequest.h> #include <LibWeb/IndexedDB/IDBVersionChangeEvent.h> #include <LibWeb/IndexedDB/Internal/Algorithms.h> @@ -266,4 +267,19 @@ ErrorOr<Key> convert_a_value_to_a_key(JS::Realm& realm, JS::Value input, Vector< return Error::from_string_literal("Unknown key type"); } +// https://w3c.github.io/IndexedDB/#close-a-database-connection +void close_a_database_connection(IDBDatabase& connection, bool forced) +{ + // 1. Set connection’s close pending flag to true. + connection.set_close_pending(true); + + // FIXME: 2. If the forced flag is true, then for each transaction created using connection run abort a transaction with transaction and newly created "AbortError" DOMException. + // FIXME: 3. Wait for all transactions created using connection to complete. Once they are complete, connection is closed. + connection.set_state(IDBDatabase::ConnectionState::Closed); + + // 4. If the forced flag is true, then fire an event named close at connection. + if (forced) + connection.dispatch_event(DOM::Event::create(connection.realm(), HTML::EventNames::close)); +} + } diff --git a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h index 22562eafa84f..175ba0311fbf 100644 --- a/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h +++ b/Libraries/LibWeb/IndexedDB/Internal/Algorithms.h @@ -16,5 +16,6 @@ namespace Web::IndexedDB { WebIDL::ExceptionOr<GC::Ref<IDBDatabase>> open_a_database_connection(JS::Realm&, StorageAPI::StorageKey, String, Optional<u64>, GC::Ref<IDBRequest>); bool fire_a_version_change_event(JS::Realm&, FlyString const&, GC::Ref<DOM::EventTarget>, u64, Optional<u64>); ErrorOr<Key> convert_a_value_to_a_key(JS::Realm&, JS::Value, Vector<JS::Value> = {}); +void close_a_database_connection(IDBDatabase&, bool forced = false); }
a89e95f57cbbff776219550286764ef1145f0f6e
2023-08-03 21:22:54
Sebastian Zaha
meta: Port GCC compile option from cmake to gn
false
Port GCC compile option from cmake to gn
meta
diff --git a/Meta/gn/build/BUILD.gn b/Meta/gn/build/BUILD.gn index 4d149e4161d8..b82cf38bad5e 100644 --- a/Meta/gn/build/BUILD.gn +++ b/Meta/gn/build/BUILD.gn @@ -111,6 +111,8 @@ config("compiler_defaults") { # instead) on clang<=3.8. Clang also has a -Wredundant-move, but it # only fires when the types match exactly, so we can keep it here. "-Wno-redundant-move", + + "-Wno-literal-suffix", ] }
b521badbefd7e9427583819c165684f5cc8b7913
2024-12-05 21:23:28
Pavel Shliak
ak: Remove QuickSelect
false
Remove QuickSelect
ak
diff --git a/AK/QuickSelect.h b/AK/QuickSelect.h deleted file mode 100644 index bd11c11dedc9..000000000000 --- a/AK/QuickSelect.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2023, the SerenityOS developers. - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include <AK/Math.h> -#include <AK/Random.h> -#include <AK/StdLibExtras.h> - -namespace AK { - -static constexpr int MEDIAN_OF_MEDIAN_CUTOFF = 4500; - -// FIXME: Stole and adapted these two functions from `Userland/Demos/Tubes/Tubes.cpp` we really need something like this in `AK/Random.h` -static inline double random_double() -{ - return get_random<u32>() / static_cast<double>(NumericLimits<u32>::max()); -} - -static inline size_t random_int(size_t min, size_t max) -{ - return min + round_to<size_t>(random_double() * (max - min)); -} - -// Implementations of common pivot functions -namespace PivotFunctions { - -// Just use the first element of the range as the pivot -// Mainly used to debug the quick select algorithm -// Good with random data since it has nearly no overhead -// Attention: Turns the algorithm quadratic if used with already (partially) sorted data -template<typename Collection, typename LessThan> -size_t first_element([[maybe_unused]] Collection& collection, size_t left, [[maybe_unused]] size_t right, [[maybe_unused]] LessThan less_than) -{ - return left; -} - -// Just use the middle element of the range as the pivot -// This is what is used in AK::single_pivot_quick_sort in quicksort.h -// Works fairly well with random Data -// Works incredibly well with sorted data since the pivot is always a perfect split -template<typename Collection, typename LessThan> -size_t middle_element([[maybe_unused]] Collection& collection, size_t left, size_t right, [[maybe_unused]] LessThan less_than) -{ - return (left + right) / 2; -} - -// Pick a random Pivot -// This is the "Traditional" implementation of both quicksort and quick select -// Performs fairly well both with random and sorted data -template<typename Collection, typename LessThan> -size_t random_element([[maybe_unused]] Collection& collection, size_t left, size_t right, [[maybe_unused]] LessThan less_than) -{ - return random_int(left, right); -} - -// Implementation detail of median_of_medians -// Whilst this looks quadratic in runtime, it always gets called with 5 or fewer elements so can be considered constant runtime -template<typename Collection, typename LessThan> -size_t partition5(Collection& collection, size_t left, size_t right, LessThan less_than) -{ - VERIFY((right - left) <= 5); - for (size_t i = left + 1; i <= right; i++) { - for (size_t j = i; j > left && less_than(collection.at(j), collection.at(j - 1)); j--) { - swap(collection.at(j), collection.at(j - 1)); - } - } - return (left + right) / 2; -} - -// https://en.wikipedia.org/wiki/Median_of_medians -// Use the median of medians algorithm to pick a really good pivot -// This makes quick select run in linear time but comes with a lot of overhead that only pays off with very large inputs -template<typename Collection, typename LessThan> -size_t median_of_medians(Collection& collection, size_t left, size_t right, LessThan less_than) -{ - if ((right - left) < 5) - return partition5(collection, left, right, less_than); - - for (size_t i = left; i <= right; i += 5) { - size_t sub_right = i + 4; - if (sub_right > right) - sub_right = right; - - size_t median5 = partition5(collection, i, sub_right, less_than); - swap(collection.at(median5), collection.at(left + (i - left) / 5)); - } - size_t mid = (right - left) / 10 + left + 1; - - // We're using mutual recursion here, using quickselect_inplace to find the pivot for quickselect_inplace. - // Whilst this achieves True linear Runtime, it is a lot of overhead, so use only this variant with very large inputs - return quickselect_inplace( - collection, left, left + ((right - left) / 5), mid, [](auto collection, size_t left, size_t right, auto less_than) { return AK::PivotFunctions::median_of_medians(collection, left, right, less_than); }, less_than); -} - -} - -// This is the Lomuto Partition scheme which is simpler but less efficient than Hoare's partitioning scheme that is traditionally used with quicksort -// https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme -template<typename Collection, typename PivotFn, typename LessThan> -static size_t partition(Collection& collection, size_t left, size_t right, PivotFn pivot_fn, LessThan less_than) -{ - auto pivot_index = pivot_fn(collection, left, right, less_than); - auto pivot_value = collection.at(pivot_index); - swap(collection.at(pivot_index), collection.at(right)); - auto store_index = left; - - for (size_t i = left; i < right; i++) { - if (less_than(collection.at(i), pivot_value)) { - swap(collection.at(store_index), collection.at(i)); - store_index++; - } - } - - swap(collection.at(right), collection.at(store_index)); - return store_index; -} - -template<typename Collection, typename PivotFn, typename LessThan> -size_t quickselect_inplace(Collection& collection, size_t left, size_t right, size_t k, PivotFn pivot_fn, LessThan less_than) -{ - // Bail if left is somehow bigger than right and return default constructed result - // FIXME: This can also occur when the collection is empty maybe propagate this error somehow? - // returning 0 would be a really bad thing since this returns and index and that might lead to memory errors - // returning in ErrorOr<size_t> here might be a good option but this is a very specific error that in nearly all circumstances should be considered a bug on the callers site - VERIFY(left <= right); - - // If there's only one element, return that element - if (left == right) - return left; - - auto pivot_index = partition(collection, left, right, pivot_fn, less_than); - - // we found the thing we were searching for - if (k == pivot_index) - return k; - - // Recurse on the left side - if (k < pivot_index) - return quickselect_inplace(collection, left, pivot_index - 1, k, pivot_fn, less_than); - - // recurse on the right side - return quickselect_inplace(collection, pivot_index + 1, right, k, pivot_fn, less_than); -} - -// -template<typename Collection, typename PivotFn, typename LessThan> -size_t quickselect_inplace(Collection& collection, size_t k, PivotFn pivot_fn, LessThan less_than) -{ - return quickselect_inplace(collection, 0, collection.size() - 1, k, pivot_fn, less_than); -} - -template<typename Collection, typename PivotFn> -size_t quickselect_inplace(Collection& collection, size_t k, PivotFn pivot_fn) -{ - return quickselect_inplace(collection, 0, collection.size() - 1, k, pivot_fn, [](auto& a, auto& b) { return a < b; }); -} - -// All of these quick select implementation versions return the `index` of the resulting element, after the algorithm has run, not the element itself! -// As Part of the Algorithm, they all modify the collection in place, partially sorting it in the process. -template<typename Collection> -size_t quickselect_inplace(Collection& collection, size_t k) -{ - if (collection.size() >= MEDIAN_OF_MEDIAN_CUTOFF) - return quickselect_inplace( - collection, 0, collection.size() - 1, k, [](auto collection, size_t left, size_t right, auto less_than) { return PivotFunctions::median_of_medians(collection, left, right, less_than); }, [](auto& a, auto& b) { return a < b; }); - - else - return quickselect_inplace( - collection, 0, collection.size() - 1, k, [](auto collection, size_t left, size_t right, auto less_than) { return PivotFunctions::random_element(collection, left, right, less_than); }, [](auto& a, auto& b) { return a < b; }); -} - -} diff --git a/Tests/AK/CMakeLists.txt b/Tests/AK/CMakeLists.txt index 1cc52d90529e..898d483988ca 100644 --- a/Tests/AK/CMakeLists.txt +++ b/Tests/AK/CMakeLists.txt @@ -55,7 +55,6 @@ set(AK_TEST_SOURCES TestOwnPtr.cpp TestPrint.cpp TestQueue.cpp - TestQuickSelect.cpp TestQuickSort.cpp TestRedBlackTree.cpp TestRefPtr.cpp diff --git a/Tests/AK/TestQuickSelect.cpp b/Tests/AK/TestQuickSelect.cpp deleted file mode 100644 index 56bf7b716964..000000000000 --- a/Tests/AK/TestQuickSelect.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2023, the SerenityOS developers. - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include <LibTest/TestCase.h> - -#include <AK/QuickSelect.h> -#include <AK/QuickSort.h> - -template<typename Collection> -int naive_select(Collection& a, int k) -{ - quick_sort(a); - return k; -} - -TEST_CASE(quickselect_inplace) -{ - - // Test the various Quickselect Pivot methods against the naive select - Array<int, 64> array; - Array<int, 64> naive_results; - - auto reset_array = [&]() { - for (size_t i = 0; i < 64; ++i) - array[i] = (64 - i) % 32 + 32; - }; - - // Populate naive results - reset_array(); - for (size_t k = 0; k < 64; ++k) { - naive_results[k] = array.at(naive_select(array, k)); - } - - // Default configuration of `quick_select` - reset_array(); - for (size_t k = 0; k < 64; ++k) { - EXPECT(naive_results[k] == array.at(AK::quickselect_inplace(array, k))); - } - - // first_element pivot function - reset_array(); - for (size_t k = 0; k < 64; ++k) { - EXPECT(naive_results[k] == array.at(AK::quickselect_inplace(array, k, [](auto collection, size_t left, size_t right, auto less_than) { return AK::PivotFunctions::first_element(collection, left, right, less_than); }))); - } - - // middle_element pivot function - reset_array(); - for (size_t k = 0; k < 64; ++k) { - EXPECT(naive_results[k] == array.at(AK::quickselect_inplace(array, k, [](auto collection, size_t left, size_t right, auto less_than) { return AK::PivotFunctions::middle_element(collection, left, right, less_than); }))); - } - - // random_element pivot function - reset_array(); - for (size_t k = 0; k < 64; ++k) { - EXPECT(naive_results[k] == array.at(AK::quickselect_inplace(array, k, [](auto collection, size_t left, size_t right, auto less_than) { return AK::PivotFunctions::random_element(collection, left, right, less_than); }))); - } - - // median_of_medians pivot function - reset_array(); - for (size_t k = 0; k < 64; ++k) { - EXPECT(naive_results[k] == array.at(AK::quickselect_inplace(array, k, [](auto collection, size_t left, size_t right, auto less_than) { return AK::PivotFunctions::median_of_medians(collection, left, right, less_than); }))); - } -}
9884cd0628375700f82273a67f4e192ff10d611e
2025-01-05 20:32:32
stasoid
ak: Stub out AK::demangle on Windows
false
Stub out AK::demangle on Windows
ak
diff --git a/AK/Demangle.h b/AK/Demangle.h index 564ffa896d90..290d3c3753fb 100644 --- a/AK/Demangle.h +++ b/AK/Demangle.h @@ -8,10 +8,14 @@ #include <AK/ByteString.h> #include <AK/StringView.h> -#include <cxxabi.h> + +#ifndef AK_OS_WINDOWS +# include <cxxabi.h> +#endif namespace AK { +#ifndef AK_OS_WINDOWS inline ByteString demangle(StringView name) { int status = 0; @@ -21,6 +25,13 @@ inline ByteString demangle(StringView name) free(demangled_name); return string; } +#else +inline ByteString demangle(StringView name) +{ + // FIXME: Implement AK::demangle on Windows + return name; +} +#endif }
657bbd1542ce8fcd3357e5b4dada895229faf834
2024-07-30 13:11:35
Timothy Flynn
libweb: Append attributes to the correct element
false
Append attributes to the correct element
libweb
diff --git a/Tests/LibWeb/Text/expected/unclosed-html-element.txt b/Tests/LibWeb/Text/expected/unclosed-html-element.txt index aaecaf93c4a5..72ef5add63fd 100644 --- a/Tests/LibWeb/Text/expected/unclosed-html-element.txt +++ b/Tests/LibWeb/Text/expected/unclosed-html-element.txt @@ -1 +1 @@ -PASS (didn't crash) +HTML element has '<head' attribute: true diff --git a/Tests/LibWeb/Text/input/unclosed-html-element.html b/Tests/LibWeb/Text/input/unclosed-html-element.html index c1bab5c6f6e0..ca3860248f69 100644 --- a/Tests/LibWeb/Text/input/unclosed-html-element.html +++ b/Tests/LibWeb/Text/input/unclosed-html-element.html @@ -5,6 +5,6 @@ <script src="include.js"></script> <script> test(() => { - println("PASS (didn't crash)"); + println(`HTML element has '<head' attribute: ${document.documentElement.hasAttribute('<head')}`); }); </script> diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp index 235395789353..bba2efa66446 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp @@ -1719,9 +1719,10 @@ void HTMLParser::handle_in_body(HTMLToken& token) // Otherwise, for each attribute on the token, check to see if the attribute is already present on the top element of the stack of open elements. // If it is not, add the attribute and its corresponding value to that element. + auto& top_element = m_stack_of_open_elements.first(); token.for_each_attribute([&](auto& attribute) { - if (!current_node().has_attribute(attribute.local_name)) - current_node().append_attribute(attribute.local_name, attribute.value); + if (!top_element.has_attribute(attribute.local_name)) + top_element.append_attribute(attribute.local_name, attribute.value); return IterationDecision::Continue; }); return;
28dc076764d1e11e242d6e4da5a32dc5e15fb7fb
2024-03-26 04:31:23
Andrew Kaster
libweb: Use a forgiving base64url encoding for JWK export
false
Use a forgiving base64url encoding for JWK export
libweb
diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp index a66507a78c84..3577834888e4 100644 --- a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp +++ b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp @@ -83,7 +83,12 @@ ErrorOr<String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer) for (size_t i = 0; i < data_size; ++i) byte_swapped_data.append(data_slice[data_size - i - 1]); - return encode_base64(byte_swapped_data); + auto encoded = TRY(encode_base64url(byte_swapped_data)); + + // FIXME: create a version of encode_base64url that omits padding bytes + if (auto first_padding_byte = encoded.find_byte_offset('='); first_padding_byte.has_value()) + return encoded.substring_from_byte_offset(0, first_padding_byte.value()); + return encoded; } AlgorithmParams::~AlgorithmParams() = default;
aa07c232f14da81b4fd9f5f0f26f6f5b73d5749c
2024-01-31 05:04:49
Sam Atkins
hexeditor: Optionally display annotations in the side panel
false
Optionally display annotations in the side panel
hexeditor
diff --git a/Userland/Applications/HexEditor/HexEditorWidget.cpp b/Userland/Applications/HexEditor/HexEditorWidget.cpp index 8140dd68cd2a..33fbbc313668 100644 --- a/Userland/Applications/HexEditor/HexEditorWidget.cpp +++ b/Userland/Applications/HexEditor/HexEditorWidget.cpp @@ -3,6 +3,7 @@ * Copyright (c) 2021, Mustafa Quraish <[email protected]> * Copyright (c) 2022, the SerenityOS developers. * Copyright (c) 2022, Timothy Slater <[email protected]> + * Copyright (c) 2024, Sam Atkins <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -27,6 +28,7 @@ #include <LibGUI/Menubar.h> #include <LibGUI/MessageBox.h> #include <LibGUI/Model.h> +#include <LibGUI/SortingProxyModel.h> #include <LibGUI/Statusbar.h> #include <LibGUI/TableView.h> #include <LibGUI/TextBox.h> @@ -50,6 +52,8 @@ ErrorOr<void> HexEditorWidget::setup() m_toolbar_container = *find_descendant_of_type_named<GUI::ToolbarContainer>("toolbar_container"); m_editor = *find_descendant_of_type_named<::HexEditor::HexEditor>("editor"); m_statusbar = *find_descendant_of_type_named<GUI::Statusbar>("statusbar"); + m_annotations = *find_descendant_of_type_named<GUI::TableView>("annotations"); + m_annotations_container = *find_descendant_of_type_named<GUI::Widget>("annotations_container"); m_search_results = *find_descendant_of_type_named<GUI::TableView>("search_results"); m_search_results_container = *find_descendant_of_type_named<GUI::Widget>("search_results_container"); m_side_panel_container = *find_descendant_of_type_named<GUI::Widget>("side_panel_container"); @@ -92,6 +96,16 @@ ErrorOr<void> HexEditorWidget::setup() m_redo_action->set_enabled(m_editor->undo_stack().can_redo()); }; + initialize_annotations_model(); + m_annotations->set_activates_on_selection(true); + m_annotations->on_activation = [this](GUI::ModelIndex const& index) { + if (!index.is_valid()) + return; + auto start_offset = m_annotations->model()->data(index, (GUI::ModelRole)AnnotationsModel::CustomRole::StartOffset).to_integer<size_t>(); + m_editor->set_position(start_offset); + m_editor->update(); + }; + m_search_results->set_activates_on_selection(true); m_search_results->on_activation = [this](const GUI::ModelIndex& index) { if (!index.is_valid()) @@ -117,6 +131,7 @@ ErrorOr<void> HexEditorWidget::setup() } set_path({}); + initialize_annotations_model(); window()->set_modified(false); } }); @@ -226,6 +241,11 @@ ErrorOr<void> HexEditorWidget::setup() Config::write_bool("HexEditor"sv, "Layout"sv, "ShowToolbar"sv, action.is_checked()); }); + m_layout_annotations_action = GUI::Action::create_checkable("&Annotations", [&](auto& action) { + set_annotations_visible(action.is_checked()); + Config::write_bool("HexEditor"sv, "Layout"sv, "ShowAnnotations"sv, action.is_checked()); + }); + m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) { set_search_results_visible(action.is_checked()); Config::write_bool("HexEditor"sv, "Layout"sv, "ShowSearchResults"sv, action.is_checked()); @@ -500,6 +520,9 @@ ErrorOr<void> HexEditorWidget::initialize_menubar(GUI::Window& window) m_layout_toolbar_action->set_checked(show_toolbar); m_toolbar_container->set_visible(show_toolbar); + auto show_annotations = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowAnnotations"sv, false); + set_annotations_visible(show_annotations); + auto show_search_results = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowSearchResults"sv, false); set_search_results_visible(show_search_results); @@ -507,6 +530,7 @@ ErrorOr<void> HexEditorWidget::initialize_menubar(GUI::Window& window) set_value_inspector_visible(show_value_inspector); view_menu->add_action(*m_layout_toolbar_action); + view_menu->add_action(*m_layout_annotations_action); view_menu->add_action(*m_layout_search_results_action); view_menu->add_action(*m_layout_value_inspector_action); view_menu->add_separator(); @@ -601,6 +625,7 @@ void HexEditorWidget::open_file(ByteString const& filename, NonnullOwnPtr<Core:: window()->set_modified(false); m_editor->open_file(move(file)); set_path(filename); + initialize_annotations_model(); GUI::Application::the()->set_most_recently_open_file(filename); } @@ -617,13 +642,34 @@ bool HexEditorWidget::request_close() return result == GUI::MessageBox::ExecResult::No; } +void HexEditorWidget::update_side_panel_visibility() +{ + m_side_panel_container->set_visible( + m_annotations_container->is_visible() + || m_search_results_container->is_visible() + || m_value_inspector_container->is_visible()); +} + +void HexEditorWidget::set_annotations_visible(bool visible) +{ + m_layout_annotations_action->set_checked(visible); + m_annotations_container->set_visible(visible); + update_side_panel_visibility(); +} + +void HexEditorWidget::initialize_annotations_model() +{ + auto sorting_model = MUST(GUI::SortingProxyModel::create(m_editor->document().annotations())); + sorting_model->set_sort_role((GUI::ModelRole)AnnotationsModel::CustomRole::StartOffset); + sorting_model->sort(AnnotationsModel::Column::Start, GUI::SortOrder::Ascending); + m_annotations->set_model(sorting_model); +} + void HexEditorWidget::set_search_results_visible(bool visible) { m_layout_search_results_action->set_checked(visible); m_search_results_container->set_visible(visible); - - // Ensure side panel container is visible if either search result or value inspector are turned on - m_side_panel_container->set_visible(visible || m_value_inspector_container->is_visible()); + update_side_panel_visibility(); } void HexEditorWidget::set_value_inspector_visible(bool visible) @@ -633,9 +679,7 @@ void HexEditorWidget::set_value_inspector_visible(bool visible) m_layout_value_inspector_action->set_checked(visible); m_value_inspector_container->set_visible(visible); - - // Ensure side panel container is visible if either search result or value inspector are turned on - m_side_panel_container->set_visible(visible || m_search_results_container->is_visible()); + update_side_panel_visibility(); } void HexEditorWidget::drag_enter_event(GUI::DragEvent& event) diff --git a/Userland/Applications/HexEditor/HexEditorWidget.gml b/Userland/Applications/HexEditor/HexEditorWidget.gml index 9aaedf335ec2..f9faaf5fe987 100644 --- a/Userland/Applications/HexEditor/HexEditorWidget.gml +++ b/Userland/Applications/HexEditor/HexEditorWidget.gml @@ -44,6 +44,16 @@ activates_on_selection: true } } + + @GUI::Widget { + name: "annotations_container" + visible: false + layout: @GUI::VerticalBoxLayout {} + + @GUI::TableView { + name: "annotations" + } + } } } diff --git a/Userland/Applications/HexEditor/HexEditorWidget.h b/Userland/Applications/HexEditor/HexEditorWidget.h index 52a66b7d7e3e..9227647e7346 100644 --- a/Userland/Applications/HexEditor/HexEditorWidget.h +++ b/Userland/Applications/HexEditor/HexEditorWidget.h @@ -3,6 +3,7 @@ * Copyright (c) 2021, Mustafa Quraish <[email protected]> * Copyright (c) 2022, the SerenityOS developers. * Copyright (c) 2022, Timothy Slater <[email protected]> + * Copyright (c) 2024, Sam Atkins <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -38,6 +39,9 @@ class HexEditorWidget final : public GUI::Widget { HexEditorWidget() = default; void set_path(StringView); void update_title(); + void update_side_panel_visibility(); + void set_annotations_visible(bool visible); + void initialize_annotations_model(); void set_search_results_visible(bool visible); void set_value_inspector_visible(bool visible); void update_inspector_values(size_t position); @@ -67,6 +71,7 @@ class HexEditorWidget final : public GUI::Widget { RefPtr<GUI::Action> m_find_action; RefPtr<GUI::Action> m_goto_offset_action; RefPtr<GUI::Action> m_layout_toolbar_action; + RefPtr<GUI::Action> m_layout_annotations_action; RefPtr<GUI::Action> m_layout_search_results_action; RefPtr<GUI::Action> m_layout_value_inspector_action; @@ -86,6 +91,8 @@ class HexEditorWidget final : public GUI::Widget { RefPtr<GUI::Widget> m_side_panel_container; RefPtr<GUI::Widget> m_value_inspector_container; RefPtr<GUI::TableView> m_value_inspector; + RefPtr<GUI::Widget> m_annotations_container; + RefPtr<GUI::TableView> m_annotations; bool m_value_inspector_little_endian { true }; bool m_selecting_from_inspector { false };
dc15cacfc3d0b26923659b619f74d02a4e6516bd
2022-10-20 18:46:23
Andreas Kling
libweb: Use OrderedHashMap to store pending idle callbacks
false
Use OrderedHashMap to store pending idle callbacks
libweb
diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index 8dad5e1d6a06..9979affa14a7 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -60,23 +60,6 @@ void run_animation_frame_callbacks(DOM::Document& document, double) document.window().animation_frame_callback_driver().run(); } -class IdleCallback : public RefCounted<IdleCallback> { -public: - explicit IdleCallback(Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> handler, u32 handle) - : m_handler(move(handler)) - , m_handle(handle) - { - } - ~IdleCallback() = default; - - JS::Completion invoke(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(deadline); } - u32 handle() const { return m_handle; } - -private: - Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> m_handler; - u32 m_handle { 0 }; -}; - JS::NonnullGCPtr<Window> Window::create(JS::Realm& realm) { return *realm.heap().allocate<Window>(realm, realm); @@ -99,6 +82,10 @@ void Window::visit_edges(JS::Cell::Visitor& visitor) visitor.visit(m_navigator); for (auto& it : m_timers) visitor.visit(it.value.ptr()); + for (auto& it : m_idle_request_callbacks) + visitor.visit(it.value); + for (auto& it : m_runnable_idle_callbacks) + visitor.visit(it.value); } Window::~Window() = default; @@ -609,21 +596,23 @@ bool Window::has_transient_activation() const // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm void Window::start_an_idle_period() { - // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm. + // FIXME: 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm. // 2. Let pending_list be window's list of idle request callbacks. auto& pending_list = m_idle_request_callbacks; // 3. Let run_list be window's list of runnable idle callbacks. auto& run_list = m_runnable_idle_callbacks; - run_list.extend(pending_list); - // 4. Clear pending_list. + // 4. Append all entries from pending_list into run_list preserving order. + for (auto& it : pending_list) + run_list.set(it.key, move(it.value)); + // 5. Clear pending_list. pending_list.clear(); // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks if (run_list.is_empty()) return; - // 5. Queue a task on the queue associated with the idle-task task source, + // 6. Queue a task on the queue associated with the idle-task task source, // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters. HTML::queue_global_task(HTML::Task::Source::IdleTask, *this, [this]() mutable { invoke_idle_callbacks(); @@ -640,11 +629,12 @@ void Window::invoke_idle_callbacks() // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty: if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) { // 1. Pop the top callback from window's list of runnable idle callbacks. - auto callback = m_runnable_idle_callbacks.take_first(); + auto callback = (*m_runnable_idle_callbacks.begin()).value; + m_runnable_idle_callbacks.remove(m_runnable_idle_callbacks.begin()); // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline. auto deadline_arg = RequestIdleCallback::IdleDeadline::create(realm()); // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception. - auto result = callback->invoke(deadline_arg); + auto result = WebIDL::invoke_callback(*callback, {}, deadline_arg); if (result.is_error()) HTML::report_exception(result, realm()); // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps @@ -665,10 +655,7 @@ u32 Window::request_idle_callback_impl(WebIDL::CallbackType& callback) // 3. Let handle be the current value of window's idle callback identifier. auto handle = window.m_idle_callback_identifier; // 4. Push callback to the end of window's list of idle request callbacks, associated with handle. - auto handler = [callback = JS::make_handle(callback)](JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion { - return WebIDL::invoke_callback(const_cast<WebIDL::CallbackType&>(*callback), {}, deadline.ptr()); - }; - window.m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle))); + window.m_idle_request_callbacks.set(handle, callback); // 5. Return handle and then continue running this algorithm asynchronously. return handle; // FIXME: 6. If the timeout property is present in options and has a positive value: @@ -686,12 +673,8 @@ void Window::cancel_idle_callback_impl(u32 handle) // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks // that is associated with the value handle. // 3. If there is such an entry, remove it from both window's list of idle request callbacks and the list of runnable idle callbacks. - window.m_idle_request_callbacks.remove_first_matching([handle](auto& callback) { - return callback->handle() == handle; - }); - window.m_runnable_idle_callbacks.remove_first_matching([handle](auto& callback) { - return callback->handle() == handle; - }); + window.m_idle_request_callbacks.remove(handle); + window.m_runnable_idle_callbacks.remove(handle); } void Window::set_associated_document(DOM::Document& document) diff --git a/Userland/Libraries/LibWeb/HTML/Window.h b/Userland/Libraries/LibWeb/HTML/Window.h index ddc70c09c087..ec97b988cb46 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.h +++ b/Userland/Libraries/LibWeb/HTML/Window.h @@ -161,9 +161,9 @@ class Window final AnimationFrameCallbackDriver m_animation_frame_callback_driver; // https://w3c.github.io/requestidlecallback/#dfn-list-of-idle-request-callbacks - NonnullRefPtrVector<IdleCallback> m_idle_request_callbacks; + OrderedHashMap<u32, JS::NonnullGCPtr<WebIDL::CallbackType>> m_idle_request_callbacks; // https://w3c.github.io/requestidlecallback/#dfn-list-of-runnable-idle-callbacks - NonnullRefPtrVector<IdleCallback> m_runnable_idle_callbacks; + OrderedHashMap<u32, JS::NonnullGCPtr<WebIDL::CallbackType>> m_runnable_idle_callbacks; // https://w3c.github.io/requestidlecallback/#dfn-idle-callback-identifier u32 m_idle_callback_identifier = 0;
f6576c4b7c6834e038c1518574ce2c5fcf5c976d
2019-11-11 02:33:39
Andreas Kling
hackstudio: Start implementing basic widget selection in CursorTool
false
Start implementing basic widget selection in CursorTool
hackstudio
diff --git a/DevTools/HackStudio/CursorTool.cpp b/DevTools/HackStudio/CursorTool.cpp index 9eff4102dec2..77f047670380 100644 --- a/DevTools/HackStudio/CursorTool.cpp +++ b/DevTools/HackStudio/CursorTool.cpp @@ -1,10 +1,21 @@ #include "CursorTool.h" +#include "FormEditorWidget.h" +#include "FormWidget.h" #include <AK/LogStream.h> void CursorTool::on_mousedown(GMouseEvent& event) { - (void)event; dbg() << "CursorTool::on_mousedown"; + auto& form_widget = m_editor.form_widget(); + auto result = form_widget.hit_test(event.position(), GWidget::ShouldRespectGreediness::No); + if (result.widget && result.widget != &form_widget) { + if (event.modifiers() & Mod_Ctrl) + m_editor.selection().toggle(*result.widget); + else + m_editor.selection().set(*result.widget); + // FIXME: Do we need to update any part of the FormEditorWidget outside the FormWidget? + form_widget.update(); + } } void CursorTool::on_mouseup(GMouseEvent& event) diff --git a/DevTools/HackStudio/FormEditorWidget.h b/DevTools/HackStudio/FormEditorWidget.h index f760031da7e7..ef0bbed234c5 100644 --- a/DevTools/HackStudio/FormEditorWidget.h +++ b/DevTools/HackStudio/FormEditorWidget.h @@ -18,12 +18,61 @@ class FormEditorWidget final : public GScrollableWidget { void set_tool(NonnullOwnPtr<Tool>); + class WidgetSelection { + public: + bool is_empty() const + { + return m_widgets.is_empty(); + } + + bool contains(GWidget& widget) const + { + return m_widgets.contains(&widget); + } + + void toggle(GWidget& widget) + { + if (contains(widget)) + remove(widget); + else + add(widget); + } + + void set(GWidget& widget) + { + clear(); + add(widget); + } + + void remove(GWidget& widget) + { + ASSERT(m_widgets.contains(&widget)); + m_widgets.remove(&widget); + } + + void add(GWidget& widget) + { + m_widgets.set(&widget); + } + + void clear() + { + m_widgets.clear(); + } + + WidgetSelection() {} + private: + HashTable<GWidget*> m_widgets; + }; + + WidgetSelection& selection() { return m_selection; } + private: virtual void paint_event(GPaintEvent&) override; explicit FormEditorWidget(GWidget* parent); RefPtr<FormWidget> m_form_widget; - NonnullOwnPtr<Tool> m_tool; + WidgetSelection m_selection; }; diff --git a/DevTools/HackStudio/FormWidget.cpp b/DevTools/HackStudio/FormWidget.cpp index a79868090911..985e758dec1c 100644 --- a/DevTools/HackStudio/FormWidget.cpp +++ b/DevTools/HackStudio/FormWidget.cpp @@ -39,6 +39,21 @@ void FormWidget::paint_event(GPaintEvent& event) } } +void FormWidget::second_paint_event(GPaintEvent& event) +{ + if (editor().selection().is_empty()) + return; + + GPainter painter(*this); + painter.add_clip_rect(event.rect()); + for_each_child_widget([&](auto& child) { + if (editor().selection().contains(child)) { + painter.draw_rect(child.relative_rect(), Color::Blue); + } + return IterationDecision::Continue; + }); +} + void FormWidget::mousedown_event(GMouseEvent& event) { editor().tool().on_mousedown(event); diff --git a/DevTools/HackStudio/FormWidget.h b/DevTools/HackStudio/FormWidget.h index cb60006fc505..6ac2eb3df9bd 100644 --- a/DevTools/HackStudio/FormWidget.h +++ b/DevTools/HackStudio/FormWidget.h @@ -14,6 +14,7 @@ class FormWidget final : public GWidget { private: virtual void paint_event(GPaintEvent&) override; + virtual void second_paint_event(GPaintEvent&) override; virtual void mousedown_event(GMouseEvent&) override; virtual void mouseup_event(GMouseEvent&) override; virtual void mousemove_event(GMouseEvent&) override;
8458f477a4c72d0382771e2a66afe1e9a6577027
2021-09-01 18:44:47
Timothy Flynn
libunicode: Canonicalize timezone subtags
false
Canonicalize timezone subtags
libunicode
diff --git a/Tests/LibUnicode/TestUnicodeLocale.cpp b/Tests/LibUnicode/TestUnicodeLocale.cpp index 85bf18dac2c8..878c6c2731ba 100644 --- a/Tests/LibUnicode/TestUnicodeLocale.cpp +++ b/Tests/LibUnicode/TestUnicodeLocale.cpp @@ -316,6 +316,10 @@ TEST_CASE(canonicalize_unicode_locale_id) test("EN-U-MS-IMPERIAL"sv, "en-u-ms-uksystem"sv); test("en-u-ma-imperial"sv, "en-u-ma-imperial"sv); test("EN-U-MA-IMPERIAL"sv, "en-u-ma-imperial"sv); + test("en-u-tz-hongkong"sv, "en-u-tz-hkhkg"sv); + test("EN-U-TZ-HONGKONG"sv, "en-u-tz-hkhkg"sv); + test("en-u-ta-hongkong"sv, "en-u-ta-hongkong"sv); + test("EN-U-TA-HONGKONG"sv, "en-u-ta-hongkong"sv); test("en-t-en"sv, "en-t-en"sv); test("EN-T-EN"sv, "en-t-en"sv); @@ -339,6 +343,8 @@ TEST_CASE(canonicalize_unicode_locale_id) test("EN-T-K1-PRIMARY"sv, "en-t-k1-primary"sv); test("en-t-k1-imperial"sv, "en-t-k1-imperial"sv); test("EN-T-K1-IMPERIAL"sv, "en-t-k1-imperial"sv); + test("en-t-k1-hongkong"sv, "en-t-k1-hongkong"sv); + test("EN-T-K1-HONGKONG"sv, "en-t-k1-hongkong"sv); test("en-0-aaa"sv, "en-0-aaa"sv); test("EN-0-AAA"sv, "en-0-aaa"sv); diff --git a/Userland/Libraries/LibUnicode/Locale.cpp b/Userland/Libraries/LibUnicode/Locale.cpp index 5815f3678ebd..e91561c5ea0c 100644 --- a/Userland/Libraries/LibUnicode/Locale.cpp +++ b/Userland/Libraries/LibUnicode/Locale.cpp @@ -485,6 +485,7 @@ static void perform_hard_coded_key_value_substitutions(String& key, String& valu // FIXME: In the XML export of CLDR, there are some aliases defined in the following files: // https://github.com/unicode-org/cldr-staging/blob/master/production/common/bcp47/collation.xml // https://github.com/unicode-org/cldr-staging/blob/master/production/common/bcp47/measure.xml + // https://github.com/unicode-org/cldr-staging/blob/master/production/common/bcp47/timezone.xml // https://github.com/unicode-org/cldr-staging/blob/master/production/common/bcp47/transform.xml // // There doesn't seem to be a counterpart in the JSON export. Since there aren't many such @@ -502,6 +503,40 @@ static void perform_hard_coded_key_value_substitutions(String& key, String& valu value = "prprname"sv; } else if ((key == "ms"sv) && (value == "imperial"sv)) { value = "uksystem"sv; + } else if (key == "tz"sv) { + // Formatter disabled because this block is easier to read / check against timezone.xml as one-liners. + // clang-format off + if (value == "aqams"sv) value = "nzakl"sv; + else if (value == "cnckg"sv) value = "cnsha"sv; + else if (value == "cnhrb"sv) value = "cnsha"sv; + else if (value == "cnkhg"sv) value = "cnurc"sv; + else if (value == "cuba"sv) value = "cuhav"sv; + else if (value == "egypt"sv) value = "egcai"sv; + else if (value == "eire"sv) value = "iedub"sv; + else if (value == "est"sv) value = "utcw05"sv; + else if (value == "gmt0"sv) value = "gmt"sv; + else if (value == "hongkong"sv) value = "hkhkg"sv; + else if (value == "hst"sv) value = "utcw10"sv; + else if (value == "iceland"sv) value = "isrey"sv; + else if (value == "iran"sv) value = "irthr"sv; + else if (value == "israel"sv) value = "jeruslm"sv; + else if (value == "jamaica"sv) value = "jmkin"sv; + else if (value == "japan"sv) value = "jptyo"sv; + else if (value == "kwajalein"sv) value = "mhkwa"sv; + else if (value == "libya"sv) value = "lytip"sv; + else if (value == "mst"sv) value = "utcw07"sv; + else if (value == "navajo"sv) value = "usden"sv; + else if (value == "poland"sv) value = "plwaw"sv; + else if (value == "portugal"sv) value = "ptlis"sv; + else if (value == "prc"sv) value = "cnsha"sv; + else if (value == "roc"sv) value = "twtpe"sv; + else if (value == "rok"sv) value = "krsel"sv; + else if (value == "singapore"sv) value = "sgsin"sv; + else if (value == "turkey"sv) value = "trist"sv; + else if (value == "uct"sv) value = "utc"sv; + else if (value == "usnavajo"sv) value = "usden"sv; + else if (value == "zulu"sv) value = "utc"sv; + // clang-format on } }
b87b1472e14816db5d6539351de8a4e2c0b166f6
2023-02-27 18:09:40
Patryk Pilipczuk
hexeditor: Add BE decoding for UTF16String column in ValueInspector
false
Add BE decoding for UTF16String column in ValueInspector
hexeditor
diff --git a/Userland/Applications/HexEditor/HexEditorWidget.cpp b/Userland/Applications/HexEditor/HexEditorWidget.cpp index 2869195bc40e..4d4ef49bd1f9 100644 --- a/Userland/Applications/HexEditor/HexEditorWidget.cpp +++ b/Userland/Applications/HexEditor/HexEditorWidget.cpp @@ -392,7 +392,9 @@ void HexEditorWidget::update_inspector_values(size_t position) // FIXME: Parse as other values like Timestamp etc - DeprecatedString utf16_string = TextCodec::decoder_for("utf-16le"sv)->to_utf8(StringView(selected_bytes.span())).release_value_but_fixme_should_propagate_errors().to_deprecated_string(); + auto decoder = TextCodec::decoder_for(m_value_inspector_little_endian ? "utf-16le"sv : "utf-16be"sv); + DeprecatedString utf16_string = decoder->to_utf8(StringView(selected_bytes.span())).release_value_but_fixme_should_propagate_errors().to_deprecated_string(); + value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16String, utf16_string); m_value_inspector->set_model(value_inspector_model);
bb9cd13a568a49089f781c2268f18cbd4dab32aa
2021-04-07 01:54:05
thankyouverycool
fonteditor: Convert to GML and add new edit commands to GlyphEditor
false
Convert to GML and add new edit commands to GlyphEditor
fonteditor
diff --git a/Userland/Applications/FontEditor/CMakeLists.txt b/Userland/Applications/FontEditor/CMakeLists.txt index 569ab9a9bd45..eb760d4401f2 100644 --- a/Userland/Applications/FontEditor/CMakeLists.txt +++ b/Userland/Applications/FontEditor/CMakeLists.txt @@ -1,7 +1,9 @@ include_directories(${CMAKE_CURRENT_BINARY_DIR}) +compile_gml(FontEditorWindow.gml FontEditorWindowGML.h font_editor_window_gml) set(SOURCES FontEditor.cpp + FontEditorWindowGML.h GlyphEditorWidget.cpp GlyphMapWidget.cpp main.cpp diff --git a/Userland/Applications/FontEditor/FontEditor.cpp b/Userland/Applications/FontEditor/FontEditor.cpp index 7a43db43e8f6..7a6babc59c6a 100644 --- a/Userland/Applications/FontEditor/FontEditor.cpp +++ b/Userland/Applications/FontEditor/FontEditor.cpp @@ -28,246 +28,146 @@ #include "GlyphEditorWidget.h" #include "GlyphMapWidget.h" #include <AK/StringBuilder.h> +#include <Applications/FontEditor/FontEditorWindowGML.h> +#include <LibGUI/Action.h> #include <LibGUI/BoxLayout.h> #include <LibGUI/Button.h> #include <LibGUI/CheckBox.h> +#include <LibGUI/FilePicker.h> #include <LibGUI/GroupBox.h> #include <LibGUI/Label.h> #include <LibGUI/MessageBox.h> #include <LibGUI/Painter.h> #include <LibGUI/SpinBox.h> +#include <LibGUI/StatusBar.h> #include <LibGUI/TextBox.h> +#include <LibGUI/ToolBarContainer.h> #include <LibGUI/Window.h> #include <LibGfx/BitmapFont.h> #include <LibGfx/Palette.h> #include <stdlib.h> -FontEditorWidget::FontEditorWidget(const String& path, RefPtr<Gfx::BitmapFont>&& edited_font) - : m_edited_font(move(edited_font)) - , m_path(path) +static RefPtr<GUI::Window> create_font_preview_window(FontEditorWidget& editor) { - set_fill_with_background_color(true); - set_layout<GUI::VerticalBoxLayout>(); - - // Top - auto& main_container = add<GUI::Widget>(); - main_container.set_layout<GUI::HorizontalBoxLayout>(); - main_container.layout()->set_margins({ 4, 4, 4, 4 }); - main_container.set_background_role(Gfx::ColorRole::SyntaxKeyword); - - // Top-Left Glyph Editor and info - auto& editor_container = main_container.add<GUI::Widget>(); - editor_container.set_layout<GUI::VerticalBoxLayout>(); - editor_container.layout()->set_margins({ 4, 4, 4, 4 }); - editor_container.set_background_role(Gfx::ColorRole::SyntaxKeyword); - - m_glyph_editor_widget = editor_container.add<GlyphEditorWidget>(*m_edited_font); - m_glyph_editor_widget->set_fixed_size(m_glyph_editor_widget->preferred_width(), m_glyph_editor_widget->preferred_height()); - - editor_container.set_fixed_width(m_glyph_editor_widget->preferred_width()); - - auto& glyph_width_label = editor_container.add<GUI::Label>(); - glyph_width_label.set_fixed_height(22); - glyph_width_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - glyph_width_label.set_text("Glyph width:"); - - auto& glyph_width_spinbox = editor_container.add<GUI::SpinBox>(); - glyph_width_spinbox.set_min(0); - glyph_width_spinbox.set_max(32); - glyph_width_spinbox.set_value(0); - glyph_width_spinbox.set_enabled(!m_edited_font->is_fixed_width()); - - auto& info_label = editor_container.add<GUI::Label>(); - info_label.set_fixed_height(22); - info_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - info_label.set_text("info_label"); - - /// Top-Right glyph map and font meta data - - auto& map_and_test_container = main_container.add<GUI::Widget>(); - map_and_test_container.set_layout<GUI::VerticalBoxLayout>(); - map_and_test_container.layout()->set_margins({ 4, 4, 4, 4 }); - - m_glyph_map_widget = map_and_test_container.add<GlyphMapWidget>(*m_edited_font); - m_glyph_map_widget->set_fixed_size(m_glyph_map_widget->preferred_width(), m_glyph_map_widget->preferred_height()); - - auto& font_mtest_group_box = map_and_test_container.add<GUI::GroupBox>(); - font_mtest_group_box.set_layout<GUI::VerticalBoxLayout>(); - font_mtest_group_box.layout()->set_margins({ 5, 15, 5, 5 }); - font_mtest_group_box.set_fixed_height(2 * m_edited_font->glyph_height() + 50); - font_mtest_group_box.set_title("Test"); - - auto& demo_label_1 = font_mtest_group_box.add<GUI::Label>(); - demo_label_1.set_font(m_edited_font); - demo_label_1.set_text("quick fox jumps nightly above wizard."); - - auto& demo_label_2 = font_mtest_group_box.add<GUI::Label>(); - demo_label_2.set_font(m_edited_font); - demo_label_2.set_text("QUICK FOX JUMPS NIGHTLY ABOVE WIZARD!"); - - auto& font_metadata_group_box = map_and_test_container.add<GUI::GroupBox>(); - font_metadata_group_box.set_layout<GUI::VerticalBoxLayout>(); - font_metadata_group_box.layout()->set_margins({ 5, 15, 5, 5 }); - font_metadata_group_box.set_fixed_height(275); - font_metadata_group_box.set_title("Font metadata"); - - //// Name Row - auto& namecontainer = font_metadata_group_box.add<GUI::Widget>(); - namecontainer.set_layout<GUI::HorizontalBoxLayout>(); - namecontainer.set_fixed_height(22); - - auto& name_label = namecontainer.add<GUI::Label>(); - name_label.set_fixed_width(100); - name_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - name_label.set_text("Name:"); - - auto& name_textbox = namecontainer.add<GUI::TextBox>(); - name_textbox.set_text(m_edited_font->name()); - name_textbox.on_change = [&] { - m_edited_font->set_name(name_textbox.text()); + auto window = GUI::Window::construct(); + window->set_window_type(GUI::WindowType::ToolWindow); + window->set_title("Font preview"); + window->resize(400, 150); + window->set_minimum_size(200, 100); + window->center_within(*editor.window()); + + auto& main_widget = window->set_main_widget<GUI::Widget>(); + main_widget.set_fill_with_background_color(true); + main_widget.set_layout<GUI::VerticalBoxLayout>(); + main_widget.layout()->set_margins({ 2, 2, 2, 2 }); + main_widget.layout()->set_spacing(4); + + auto& preview_box = main_widget.add<GUI::GroupBox>(); + preview_box.set_layout<GUI::VerticalBoxLayout>(); + preview_box.layout()->set_margins({ 8, 8, 8, 8 }); + + auto& preview_label = preview_box.add<GUI::Label>(); + preview_label.set_text("Five quacking zephyrs jolt my wax bed!"); + preview_label.set_font(editor.edited_font()); + + editor.on_initialize = [&] { + preview_label.set_font(editor.edited_font()); }; - //// Family Row - auto& family_container = font_metadata_group_box.add<GUI::Widget>(); - family_container.set_layout<GUI::HorizontalBoxLayout>(); - family_container.set_fixed_height(22); - - auto& family_label = family_container.add<GUI::Label>(); - family_label.set_fixed_width(100); - family_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - family_label.set_text("Family:"); + auto& preview_textbox = main_widget.add<GUI::TextBox>(); + preview_textbox.set_text("Five quacking zephyrs jolt my wax bed!"); - auto& family_textbox = family_container.add<GUI::TextBox>(); - family_textbox.set_text(m_edited_font->family()); - family_textbox.on_change = [&] { - m_edited_font->set_family(family_textbox.text()); + preview_textbox.on_change = [&] { + preview_label.set_text(preview_textbox.text()); }; - //// Presentation size Row - auto& presentation_size_container = font_metadata_group_box.add<GUI::Widget>(); - presentation_size_container.set_layout<GUI::HorizontalBoxLayout>(); - presentation_size_container.set_fixed_height(22); - - auto& presentation_size_label = presentation_size_container.add<GUI::Label>(); - presentation_size_label.set_fixed_width(100); - presentation_size_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - presentation_size_label.set_text("Presentation size:"); - - auto& presentation_size_spinbox = presentation_size_container.add<GUI::SpinBox>(); - presentation_size_spinbox.set_min(0); - presentation_size_spinbox.set_max(255); - presentation_size_spinbox.set_value(m_edited_font->presentation_size()); - - //// Weight Row - auto& weight_container = font_metadata_group_box.add<GUI::Widget>(); - weight_container.set_layout<GUI::HorizontalBoxLayout>(); - weight_container.set_fixed_height(22); - - auto& weight_label = weight_container.add<GUI::Label>(); - weight_label.set_fixed_width(100); - weight_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - weight_label.set_text("Weight:"); - - auto& weight_spinbox = weight_container.add<GUI::SpinBox>(); - weight_spinbox.set_min(0); - weight_spinbox.set_max(65535); - weight_spinbox.set_value(m_edited_font->weight()); - - //// Glyph spacing Row - auto& glyph_spacing_container = font_metadata_group_box.add<GUI::Widget>(); - glyph_spacing_container.set_layout<GUI::HorizontalBoxLayout>(); - glyph_spacing_container.set_fixed_height(22); - - auto& glyph_spacing = glyph_spacing_container.add<GUI::Label>(); - glyph_spacing.set_fixed_width(100); - glyph_spacing.set_text_alignment(Gfx::TextAlignment::CenterLeft); - glyph_spacing.set_text("Glyph spacing:"); - - auto& spacing_spinbox = glyph_spacing_container.add<GUI::SpinBox>(); - spacing_spinbox.set_min(0); - spacing_spinbox.set_max(255); - spacing_spinbox.set_value(m_edited_font->glyph_spacing()); - - //// Glyph Height Row - auto& glyph_height_container = font_metadata_group_box.add<GUI::Widget>(); - glyph_height_container.set_layout<GUI::HorizontalBoxLayout>(); - glyph_height_container.set_fixed_height(22); - - auto& glyph_height = glyph_height_container.add<GUI::Label>(); - glyph_height.set_fixed_width(100); - glyph_height.set_text_alignment(Gfx::TextAlignment::CenterLeft); - glyph_height.set_text("Glyph height:"); - - auto& glyph_height_spinbox = glyph_height_container.add<GUI::SpinBox>(); - glyph_height_spinbox.set_min(0); - glyph_height_spinbox.set_max(255); - glyph_height_spinbox.set_value(m_edited_font->glyph_height()); - glyph_height_spinbox.set_enabled(false); - - //// Glyph width Row - auto& glyph_weight_container = font_metadata_group_box.add<GUI::Widget>(); - glyph_weight_container.set_layout<GUI::HorizontalBoxLayout>(); - glyph_weight_container.set_fixed_height(22); - - auto& glyph_header_width_label = glyph_weight_container.add<GUI::Label>(); - glyph_header_width_label.set_fixed_width(100); - glyph_header_width_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - glyph_header_width_label.set_text("Glyph width:"); - - auto& glyph_header_width_spinbox = glyph_weight_container.add<GUI::SpinBox>(); - glyph_header_width_spinbox.set_min(0); - glyph_header_width_spinbox.set_max(255); - glyph_header_width_spinbox.set_value(m_edited_font->glyph_fixed_width()); - glyph_header_width_spinbox.set_enabled(false); - - //// Mean line Row - auto& mean_line_container = font_metadata_group_box.add<GUI::Widget>(); - mean_line_container.set_layout<GUI::HorizontalBoxLayout>(); - mean_line_container.set_fixed_height(22); - - auto& mean_line_label = mean_line_container.add<GUI::Label>(); - mean_line_label.set_fixed_width(100); - mean_line_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - mean_line_label.set_text("Mean line:"); - - auto& mean_line_spinbox = mean_line_container.add<GUI::SpinBox>(); - mean_line_spinbox.set_min(0); - mean_line_spinbox.set_max(m_edited_font->glyph_height() - 1); - mean_line_spinbox.set_value(m_edited_font->mean_line()); - - //// Baseline Row - auto& baseline_container = font_metadata_group_box.add<GUI::Widget>(); - baseline_container.set_layout<GUI::HorizontalBoxLayout>(); - baseline_container.set_fixed_height(22); - - auto& baseline_label = baseline_container.add<GUI::Label>(); - baseline_label.set_fixed_width(100); - baseline_label.set_text_alignment(Gfx::TextAlignment::CenterLeft); - baseline_label.set_text("Baseline:"); - - auto& baseline_spinbox = baseline_container.add<GUI::SpinBox>(); - baseline_spinbox.set_min(0); - baseline_spinbox.set_max(m_edited_font->glyph_height() - 1); - baseline_spinbox.set_value(m_edited_font->baseline()); - - //// Fixed checkbox Row - auto& fixed_width_checkbox = font_metadata_group_box.add<GUI::CheckBox>(); - fixed_width_checkbox.set_text("Fixed width"); - fixed_width_checkbox.set_checked(m_edited_font->is_fixed_width()); - - // Event handlers + return window; +} + +FontEditorWidget::FontEditorWidget(const String& path, RefPtr<Gfx::BitmapFont>&& edited_font) +{ + load_from_gml(font_editor_window_gml); + + auto& toolbar = *find_descendant_of_type_named<GUI::ToolBar>("toolbar"); + auto& status_bar = *find_descendant_of_type_named<GUI::StatusBar>("status_bar"); + auto& glyph_map_container = *find_descendant_of_type_named<GUI::Widget>("glyph_map_container"); + m_glyph_editor_container = *find_descendant_of_type_named<GUI::Widget>("glyph_editor_container"); + m_left_column_container = *find_descendant_of_type_named<GUI::Widget>("left_column_container"); + m_glyph_editor_width_spinbox = *find_descendant_of_type_named<GUI::SpinBox>("glyph_editor_width_spinbox"); + m_name_textbox = *find_descendant_of_type_named<GUI::TextBox>("name_textbox"); + m_family_textbox = *find_descendant_of_type_named<GUI::TextBox>("family_textbox"); + m_presentation_spinbox = *find_descendant_of_type_named<GUI::SpinBox>("presentation_spinbox"); + m_weight_spinbox = *find_descendant_of_type_named<GUI::SpinBox>("weight_spinbox"); + m_spacing_spinbox = *find_descendant_of_type_named<GUI::SpinBox>("spacing_spinbox"); + m_mean_line_spinbox = *find_descendant_of_type_named<GUI::SpinBox>("mean_line_spinbox"); + m_baseline_spinbox = *find_descendant_of_type_named<GUI::SpinBox>("baseline_spinbox"); + m_fixed_width_checkbox = *find_descendant_of_type_named<GUI::CheckBox>("fixed_width_checkbox"); + m_font_metadata_groupbox = *find_descendant_of_type_named<GUI::GroupBox>("font_metadata_groupbox"); + + m_glyph_editor_widget = m_glyph_editor_container->add<GlyphEditorWidget>(); + m_glyph_map_widget = glyph_map_container.add<GlyphMapWidget>(); + auto update_demo = [&] { - demo_label_1.update(); - demo_label_2.update(); + if (m_font_preview_window) + m_font_preview_window->update(); }; - auto calculate_prefed_sizes = [&] { - int right_side_width = m_edited_font->width("QUICK FOX JUMPS NIGHTLY ABOVE WIZARD!") + 20; - right_side_width = max(right_side_width, m_glyph_map_widget->preferred_width()); + auto open_action = GUI::CommonActions::make_open_action([&](auto&) { + Optional<String> open_path = GUI::FilePicker::get_open_filepath(window(), {}, "/res/fonts/"); + if (!open_path.has_value()) + return; - m_preferred_width = m_glyph_editor_widget->width() + right_side_width + 12; - m_preferred_height = m_glyph_map_widget->relative_rect().height() + 2 * m_edited_font->glyph_height() + 346; - }; + auto bitmap_font = Gfx::BitmapFont::load_from_file(open_path.value()); + if (!bitmap_font) { + String message = String::formatted("Couldn't load font: {}\n", open_path.value()); + GUI::MessageBox::show(window(), message, "Font Editor", GUI::MessageBox::Type::Error); + return; + } + RefPtr<Gfx::BitmapFont> new_font = static_ptr_cast<Gfx::BitmapFont>(bitmap_font->clone()); + if (!new_font) { + String message = String::formatted("Couldn't load font: {}\n", open_path.value()); + GUI::MessageBox::show(window(), message, "Font Editor", GUI::MessageBox::Type::Error); + return; + } + window()->set_title(String::formatted("{} - Font Editor", open_path.value())); + initialize(open_path.value(), move(new_font)); + }); + auto save_action = GUI::CommonActions::make_save_action([&](auto&) { + save_as(m_path); + }); + auto cut_action = GUI::CommonActions::make_cut_action([&](auto&) { + m_glyph_editor_widget->cut_glyph(); + }); + auto copy_action = GUI::CommonActions::make_copy_action([&](auto&) { + m_glyph_editor_widget->copy_glyph(); + }); + auto paste_action = GUI::CommonActions::make_paste_action([&](auto&) { + m_glyph_editor_widget->paste_glyph(); + m_glyph_map_widget->update_glyph(m_glyph_map_widget->selected_glyph()); + }); + auto delete_action = GUI::CommonActions::make_delete_action([&](auto&) { + m_edited_font->set_glyph_width(m_glyph_map_widget->selected_glyph(), m_edited_font->max_glyph_width()); + m_glyph_editor_widget->delete_glyph(); + m_glyph_map_widget->update_glyph(m_glyph_map_widget->selected_glyph()); + m_glyph_editor_width_spinbox->set_value(m_edited_font->glyph_width(m_glyph_map_widget->selected_glyph())); + }); + auto open_preview_action = GUI::Action::create("Preview", Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](auto&) { + if (!m_font_preview_window) + m_font_preview_window = create_font_preview_window(*this); + m_font_preview_window->show(); + m_font_preview_window->move_to_front(); + }); + open_preview_action->set_checked(false); + + toolbar.add_action(*open_action); + toolbar.add_action(*save_action); + toolbar.add_separator(); + toolbar.add_action(*cut_action); + toolbar.add_action(*copy_action); + toolbar.add_action(*paste_action); + toolbar.add_action(*delete_action); + toolbar.add_separator(); + toolbar.add_action(*open_preview_action); m_glyph_editor_widget->on_glyph_altered = [this, update_demo](u8 glyph) { m_glyph_map_widget->update_glyph(glyph); @@ -276,7 +176,7 @@ FontEditorWidget::FontEditorWidget(const String& path, RefPtr<Gfx::BitmapFont>&& m_glyph_map_widget->on_glyph_selected = [&](size_t glyph) { m_glyph_editor_widget->set_glyph(glyph); - glyph_width_spinbox.set_value(m_edited_font->glyph_width(m_glyph_map_widget->selected_glyph())); + m_glyph_editor_width_spinbox->set_value(m_edited_font->glyph_width(m_glyph_map_widget->selected_glyph())); StringBuilder builder; builder.appendff("{:#02x} (", glyph); if (glyph < 128) { @@ -286,60 +186,97 @@ FontEditorWidget::FontEditorWidget(const String& path, RefPtr<Gfx::BitmapFont>&& builder.append(128 | (glyph % 64)); } builder.append(')'); - info_label.set_text(builder.to_string()); + status_bar.set_text(builder.to_string()); + }; + + m_name_textbox->on_change = [&] { + m_edited_font->set_name(m_name_textbox->text()); + }; + + m_family_textbox->on_change = [&] { + m_edited_font->set_family(m_family_textbox->text()); }; - fixed_width_checkbox.on_checked = [&, update_demo](bool checked) { + m_fixed_width_checkbox->on_checked = [&, update_demo](bool checked) { m_edited_font->set_fixed_width(checked); - glyph_width_spinbox.set_enabled(!m_edited_font->is_fixed_width()); - glyph_width_spinbox.set_value(m_edited_font->glyph_width(m_glyph_map_widget->selected_glyph())); + m_glyph_editor_width_spinbox->set_enabled(!m_edited_font->is_fixed_width()); + m_glyph_editor_width_spinbox->set_value(m_edited_font->glyph_width(m_glyph_map_widget->selected_glyph())); m_glyph_editor_widget->update(); update_demo(); }; - glyph_width_spinbox.on_change = [this, update_demo](int value) { + m_glyph_editor_width_spinbox->on_change = [this, update_demo](int value) { m_edited_font->set_glyph_width(m_glyph_map_widget->selected_glyph(), value); m_glyph_editor_widget->update(); m_glyph_map_widget->update_glyph(m_glyph_map_widget->selected_glyph()); update_demo(); }; - weight_spinbox.on_change = [this, update_demo](int value) { + m_weight_spinbox->on_change = [this, update_demo](int value) { m_edited_font->set_weight(value); update_demo(); }; - presentation_size_spinbox.on_change = [this, update_demo](int value) { + m_presentation_spinbox->on_change = [this, update_demo](int value) { m_edited_font->set_presentation_size(value); update_demo(); }; - spacing_spinbox.on_change = [this, update_demo](int value) { + m_spacing_spinbox->on_change = [this, update_demo](int value) { m_edited_font->set_glyph_spacing(value); update_demo(); }; - baseline_spinbox.on_change = [this, update_demo](int value) { + m_baseline_spinbox->on_change = [this, update_demo](int value) { m_edited_font->set_baseline(value); m_glyph_editor_widget->update(); update_demo(); }; - mean_line_spinbox.on_change = [this, update_demo](int value) { + m_mean_line_spinbox->on_change = [this, update_demo](int value) { m_edited_font->set_mean_line(value); m_glyph_editor_widget->update(); update_demo(); }; - // init widget - calculate_prefed_sizes(); - m_glyph_map_widget->set_selected_glyph('A'); + initialize(path, move(edited_font)); } FontEditorWidget::~FontEditorWidget() { } +void FontEditorWidget::initialize(const String& path, RefPtr<Gfx::BitmapFont>&& edited_font) +{ + if (m_edited_font == edited_font) + return; + m_path = path; + m_edited_font = edited_font; + + m_glyph_editor_widget->initialize(*m_edited_font); + m_glyph_editor_container->set_fixed_size(m_glyph_editor_widget->preferred_width(), m_glyph_editor_widget->preferred_height()); + m_left_column_container->set_fixed_width(m_glyph_editor_widget->preferred_width()); + m_glyph_editor_width_spinbox->set_enabled(!m_edited_font->is_fixed_width()); + m_glyph_editor_width_spinbox->set_max(m_edited_font->max_glyph_width()); + + m_glyph_map_widget->initialize(*m_edited_font); + m_glyph_map_widget->set_selected_glyph('A'); + + m_name_textbox->set_text(m_edited_font->name()); + m_family_textbox->set_text(m_edited_font->family()); + + m_presentation_spinbox->set_value(m_edited_font->presentation_size()); + m_weight_spinbox->set_value(m_edited_font->weight()); + m_spacing_spinbox->set_value(m_edited_font->glyph_spacing()); + m_mean_line_spinbox->set_value(m_edited_font->mean_line()); + m_baseline_spinbox->set_value(m_edited_font->baseline()); + + m_fixed_width_checkbox->set_checked(m_edited_font->is_fixed_width()); + + if (on_initialize) + on_initialize(); +} + bool FontEditorWidget::save_as(const String& path) { auto ret_val = m_edited_font->write_to_file(path); @@ -350,3 +287,11 @@ bool FontEditorWidget::save_as(const String& path) m_path = path; return true; } + +void FontEditorWidget::set_show_font_metadata(bool show) +{ + if (m_font_metadata == show) + return; + m_font_metadata = show; + m_font_metadata_groupbox->set_visible(m_font_metadata); +} diff --git a/Userland/Applications/FontEditor/FontEditor.h b/Userland/Applications/FontEditor/FontEditor.h index ed904e8e7d17..0f2a55041cc0 100644 --- a/Userland/Applications/FontEditor/FontEditor.h +++ b/Userland/Applications/FontEditor/FontEditor.h @@ -26,7 +26,6 @@ #pragma once -#include <AK/Function.h> #include <LibGUI/Widget.h> #include <LibGfx/BitmapFont.h> @@ -38,12 +37,16 @@ class FontEditorWidget final : public GUI::Widget { public: virtual ~FontEditorWidget() override; - int preferred_width() { return m_preferred_width; } - int preferred_height() { return m_preferred_height; } - bool save_as(const String&); const String& path() { return m_path; } + const Gfx::BitmapFont& edited_font() { return *m_edited_font; } + void initialize(const String& path, RefPtr<Gfx::BitmapFont>&&); + + bool is_showing_font_metadata() { return m_font_metadata; } + void set_show_font_metadata(bool b); + + Function<void()> on_initialize; private: FontEditorWidget(const String& path, RefPtr<Gfx::BitmapFont>&&); @@ -52,7 +55,20 @@ class FontEditorWidget final : public GUI::Widget { RefPtr<GlyphMapWidget> m_glyph_map_widget; RefPtr<GlyphEditorWidget> m_glyph_editor_widget; + RefPtr<GUI::Window> m_font_preview_window; + RefPtr<GUI::Widget> m_left_column_container; + RefPtr<GUI::Widget> m_glyph_editor_container; + RefPtr<GUI::SpinBox> m_weight_spinbox; + RefPtr<GUI::SpinBox> m_spacing_spinbox; + RefPtr<GUI::SpinBox> m_baseline_spinbox; + RefPtr<GUI::SpinBox> m_mean_line_spinbox; + RefPtr<GUI::SpinBox> m_presentation_spinbox; + RefPtr<GUI::SpinBox> m_glyph_editor_width_spinbox; + RefPtr<GUI::TextBox> m_name_textbox; + RefPtr<GUI::TextBox> m_family_textbox; + RefPtr<GUI::CheckBox> m_fixed_width_checkbox; + RefPtr<GUI::GroupBox> m_font_metadata_groupbox; + String m_path; - int m_preferred_width; - int m_preferred_height; + bool m_font_metadata { true }; }; diff --git a/Userland/Applications/FontEditor/FontEditorWindow.gml b/Userland/Applications/FontEditor/FontEditorWindow.gml new file mode 100644 index 000000000000..c6500eca0db2 --- /dev/null +++ b/Userland/Applications/FontEditor/FontEditorWindow.gml @@ -0,0 +1,206 @@ +@GUI::Widget { + fill_with_background_color: true + layout: @GUI::VerticalBoxLayout { + } + + @GUI::ToolBarContainer { + name: "toolbar_container" + + @GUI::ToolBar { + name: "toolbar" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Widget { + name: "left_column_container" + layout: @GUI::VerticalBoxLayout { + } + + @GUI::Widget { + name: "glyph_editor_container" + layout: @GUI::VerticalBoxLayout { + } + } + + @GUI::Widget { + fixed_height: 22 + layout: @GUI::VerticalBoxLayout { + } + + @GUI::SpinBox { + name: "glyph_editor_width_spinbox" + } + } + + @GUI::Widget { + } + } + + @GUI::Widget { + name: "right_column_container" + layout: @GUI::VerticalBoxLayout { + spacing: 6 + } + + @GUI::Widget { + name: "glyph_map_container" + layout: @GUI::VerticalBoxLayout { + } + } + + @GUI::GroupBox { + name: "font_metadata_groupbox" + title: "Font metadata" + fixed_height: 220 + layout: @GUI::VerticalBoxLayout { + margins: [8, 16, 8, 4] + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Label { + name: "name_label" + fixed_width: 100 + text_alignment: "CenterLeft" + text: "Name:" + } + + @GUI::TextBox { + name: "name_textbox" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Label { + name: "family_label" + fixed_width: 100 + text_alignment: "CenterLeft" + text: "Family:" + } + + @GUI::TextBox { + name: "family_textbox" + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Label { + name: "presentation_label" + fixed_width: 100 + text_alignment: "CenterLeft" + text: "Presentation size:" + } + + @GUI::SpinBox { + name: "presentation_spinbox" + min: 0 + max: 255 + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Label { + name: "weight_label" + fixed_width: 100 + text_alignment: "CenterLeft" + text: "Weight:" + } + + @GUI::SpinBox { + name: "weight_spinbox" + min: 0 + max: 65535 + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Label { + name: "spacing_label" + fixed_width: 100 + text_alignment: "CenterLeft" + text: "Glyph spacing:" + } + + @GUI::SpinBox { + name: "spacing_spinbox" + min: 0 + max: 255 + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Label { + name: "mean_line_label" + fixed_width: 100 + text_alignment: "CenterLeft" + text: "Mean line:" + } + + @GUI::SpinBox { + name: "mean_line_spinbox" + min: 0 + max: 32 + } + } + + @GUI::Widget { + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::Label { + name: "baseline_label" + fixed_width: 100 + text_alignment: "CenterLeft" + text: "Baseline:" + } + + @GUI::SpinBox { + name: "baseline_spinbox" + min: 0 + max: 32 + } + } + + @GUI::Widget { + fixed_height: 22 + layout: @GUI::HorizontalBoxLayout { + } + + @GUI::CheckBox { + name: "fixed_width_checkbox" + text: "Fixed width" + autosize: true + } + + @GUI::Widget { + } + } + } + } + } + + @GUI::StatusBar { + name: "status_bar" + } +} diff --git a/Userland/Applications/FontEditor/GlyphEditorWidget.cpp b/Userland/Applications/FontEditor/GlyphEditorWidget.cpp index aeabe6a03dfc..3d70e9827754 100644 --- a/Userland/Applications/FontEditor/GlyphEditorWidget.cpp +++ b/Userland/Applications/FontEditor/GlyphEditorWidget.cpp @@ -29,14 +29,19 @@ #include <LibGfx/BitmapFont.h> #include <LibGfx/Palette.h> -GlyphEditorWidget::GlyphEditorWidget(Gfx::BitmapFont& mutable_font) - : m_font(mutable_font) +GlyphEditorWidget::~GlyphEditorWidget() { - set_relative_rect({ 0, 0, preferred_width(), preferred_height() }); } -GlyphEditorWidget::~GlyphEditorWidget() +void GlyphEditorWidget::initialize(Gfx::BitmapFont& mutable_font) { + if (m_font == mutable_font) + return; + m_font = mutable_font; + set_relative_rect({ 0, 0, preferred_width(), preferred_height() }); + m_clipboard_font = m_font->clone(); + m_clipboard_glyph = m_clipboard_font->glyph(0).glyph_bitmap(); + clear_clipboard_glyph(); } void GlyphEditorWidget::set_glyph(int glyph) @@ -47,6 +52,50 @@ void GlyphEditorWidget::set_glyph(int glyph) update(); } +void GlyphEditorWidget::delete_glyph() +{ + auto bitmap = font().glyph(m_glyph).glyph_bitmap(); + for (int x = 0; x < bitmap.width(); x++) + for (int y = 0; y < bitmap.height(); y++) + bitmap.set_bit_at(x, y, false); + if (on_glyph_altered) + on_glyph_altered(m_glyph); + update(); +} + +void GlyphEditorWidget::cut_glyph() +{ + copy_glyph(); + delete_glyph(); +} + +void GlyphEditorWidget::copy_glyph() +{ + clear_clipboard_glyph(); + auto bitmap = font().glyph(m_glyph).glyph_bitmap(); + for (int x = 0; x < bitmap.width(); x++) + for (int y = 0; y < bitmap.height(); y++) + m_clipboard_glyph.set_bit_at(x, y, bitmap.bit_at(x, y)); +} + +void GlyphEditorWidget::paste_glyph() +{ + auto bitmap = font().glyph(m_glyph).glyph_bitmap(); + for (int x = 0; x < bitmap.width(); x++) + for (int y = 0; y < bitmap.height(); y++) + bitmap.set_bit_at(x, y, m_clipboard_glyph.bit_at(x, y)); + if (on_glyph_altered) + on_glyph_altered(m_glyph); + update(); +} + +void GlyphEditorWidget::clear_clipboard_glyph() +{ + for (int x = 0; x < m_clipboard_glyph.width(); x++) + for (int y = 0; y < m_clipboard_glyph.height(); y++) + m_clipboard_glyph.set_bit_at(x, y, false); +} + void GlyphEditorWidget::paint_event(GUI::PaintEvent& event) { GUI::Frame::paint_event(event); diff --git a/Userland/Applications/FontEditor/GlyphEditorWidget.h b/Userland/Applications/FontEditor/GlyphEditorWidget.h index a54c5516423b..045e15df6c41 100644 --- a/Userland/Applications/FontEditor/GlyphEditorWidget.h +++ b/Userland/Applications/FontEditor/GlyphEditorWidget.h @@ -35,9 +35,17 @@ class GlyphEditorWidget final : public GUI::Frame { public: virtual ~GlyphEditorWidget() override; + void initialize(Gfx::BitmapFont&); + int glyph() const { return m_glyph; } void set_glyph(int); + void cut_glyph(); + void copy_glyph(); + void paste_glyph(); + void delete_glyph(); + void clear_clipboard_glyph(); + int preferred_width() const; int preferred_height() const; @@ -47,7 +55,7 @@ class GlyphEditorWidget final : public GUI::Frame { Function<void(u8)> on_glyph_altered; private: - GlyphEditorWidget(Gfx::BitmapFont&); + GlyphEditorWidget() {}; virtual void paint_event(GUI::PaintEvent&) override; virtual void mousedown_event(GUI::MouseEvent&) override; virtual void mousemove_event(GUI::MouseEvent&) override; @@ -55,6 +63,8 @@ class GlyphEditorWidget final : public GUI::Frame { void draw_at_mouse(const GUI::MouseEvent&); RefPtr<Gfx::BitmapFont> m_font; + RefPtr<Gfx::Font> m_clipboard_font; + Gfx::GlyphBitmap m_clipboard_glyph; int m_glyph { 0 }; int m_scale { 10 }; }; diff --git a/Userland/Applications/FontEditor/main.cpp b/Userland/Applications/FontEditor/main.cpp index db91ce1c5162..c18a0a14d92f 100644 --- a/Userland/Applications/FontEditor/main.cpp +++ b/Userland/Applications/FontEditor/main.cpp @@ -98,23 +98,24 @@ int main(int argc, char** argv) auto window = GUI::Window::construct(); window->set_icon(app_icon.bitmap_for_size(16)); + window->resize(440, 470); + window->set_main_widget<FontEditorWidget>(path, move(edited_font)); + window->set_title(String::formatted("{} - Font Editor", path)); - auto set_edited_font = [&](const String& path, RefPtr<Gfx::BitmapFont>&& font, Gfx::IntPoint point) { + auto set_edited_font = [&](const String& path, RefPtr<Gfx::BitmapFont>&& font) { // Convert 256 char font to 384 char font. if (font->type() == Gfx::FontTypes::Default) font->set_type(Gfx::FontTypes::LatinExtendedA); window->set_title(String::formatted("{} - Font Editor", path)); - auto& font_editor_widget = window->set_main_widget<FontEditorWidget>(path, move(font)); - window->set_rect({ point, { font_editor_widget.preferred_width(), font_editor_widget.preferred_height() } }); + static_cast<FontEditorWidget*>(window->main_widget())->initialize(path, move(font)); }; - set_edited_font(path, move(edited_font), window->position()); auto menubar = GUI::MenuBar::construct(); auto& app_menu = menubar->add_menu("File"); app_menu.add_action(GUI::CommonActions::make_open_action([&](auto&) { - Optional<String> open_path = GUI::FilePicker::get_open_filepath(window); + Optional<String> open_path = GUI::FilePicker::get_open_filepath(window, {}, "/res/fonts/"); if (!open_path.has_value()) return; @@ -131,7 +132,7 @@ int main(int argc, char** argv) return; } - set_edited_font(open_path.value(), move(new_font), window->position()); + set_edited_font(open_path.value(), move(new_font)); })); app_menu.add_action(GUI::CommonActions::make_save_action([&](auto&) { FontEditorWidget* editor = static_cast<FontEditorWidget*>(window->main_widget()); @@ -152,6 +153,13 @@ int main(int argc, char** argv) app->quit(); })); + auto& view_menu = menubar->add_menu("View"); + auto set_font_metadata = GUI::Action::create_checkable("Font metadata", { Mod_Ctrl, Key_M }, [&](auto& action) { + static_cast<FontEditorWidget*>(window->main_widget())->set_show_font_metadata(action.is_checked()); + }); + set_font_metadata->set_checked(true); + view_menu.add_action(*set_font_metadata); + auto& help_menu = menubar->add_menu("Help"); help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) { Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/FontEditor.md"), "/bin/Help");
2c41e89d08ad6b41eb960e53b06dafe1f5d905cc
2021-07-14 02:49:33
Gunnar Beutner
libdebug: Implement symbolication for x86_64
false
Implement symbolication for x86_64
libdebug
diff --git a/Userland/Libraries/LibCoreDump/Backtrace.cpp b/Userland/Libraries/LibCoreDump/Backtrace.cpp index f13d415f9466..9ce5c64695e1 100644 --- a/Userland/Libraries/LibCoreDump/Backtrace.cpp +++ b/Userland/Libraries/LibCoreDump/Backtrace.cpp @@ -35,10 +35,6 @@ ELFObjectInfo const* Backtrace::object_info_for_region(ELF::Core::MemoryRegionIn return nullptr; auto image = make<ELF::Image>(file_or_error.value()->bytes()); -#if !ARCH(I386) - // FIXME: Fix LibDebug - return nullptr; -#endif auto info = make<ELFObjectInfo>(file_or_error.release_value(), make<Debug::DebugInfo>(move(image))); auto* info_ptr = info.ptr(); m_debug_info_cache.set(path, move(info)); @@ -81,11 +77,11 @@ Backtrace::~Backtrace() { } -void Backtrace::add_entry(const Reader& coredump, FlatPtr eip) +void Backtrace::add_entry(const Reader& coredump, FlatPtr ip) { - auto* region = coredump.region_containing((FlatPtr)eip); + auto* region = coredump.region_containing((FlatPtr)ip); if (!region) { - m_entries.append({ eip, {}, {}, {} }); + m_entries.append({ ip, {}, {}, {} }); return; } auto object_name = region->object_name(); @@ -95,15 +91,9 @@ void Backtrace::add_entry(const Reader& coredump, FlatPtr eip) if (!object_info) return; -#if ARCH(I386) - auto function_name = object_info->debug_info->elf().symbolicate(eip - region->region_start); - auto source_position = object_info->debug_info->get_source_position_with_inlines(eip - region->region_start); -#else - // FIXME: Fix symbolication. - auto function_name = ""; - Debug::DebugInfo::SourcePositionWithInlines source_position; -#endif - m_entries.append({ eip, object_name, function_name, source_position }); + auto function_name = object_info->debug_info->elf().symbolicate(ip - region->region_start); + auto source_position = object_info->debug_info->get_source_position_with_inlines(ip - region->region_start); + m_entries.append({ ip, object_name, function_name, source_position }); } String Backtrace::Entry::to_string(bool color) const diff --git a/Userland/Libraries/LibCoreDump/Backtrace.h b/Userland/Libraries/LibCoreDump/Backtrace.h index 769bddd47ad2..722b2d0a479d 100644 --- a/Userland/Libraries/LibCoreDump/Backtrace.h +++ b/Userland/Libraries/LibCoreDump/Backtrace.h @@ -42,7 +42,7 @@ class Backtrace { const Vector<Entry> entries() const { return m_entries; } private: - void add_entry(const Reader&, FlatPtr eip); + void add_entry(const Reader&, FlatPtr ip); ELFObjectInfo const* object_info_for_region(ELF::Core::MemoryRegionInfo const&); ELF::Core::ThreadInfo m_thread_info; diff --git a/Userland/Libraries/LibDebug/DebugInfo.cpp b/Userland/Libraries/LibDebug/DebugInfo.cpp index e84bf569a767..3047bba9c95f 100644 --- a/Userland/Libraries/LibDebug/DebugInfo.cpp +++ b/Userland/Libraries/LibDebug/DebugInfo.cpp @@ -60,9 +60,9 @@ void DebugInfo::parse_scopes_impl(Dwarf::DIE const& die) dbgln_if(SPAM_DEBUG, "DWARF: Couldn't find attribute LowPc for scope"); return; } - scope.address_low = child.get_attribute(Dwarf::Attribute::LowPc).value().data.as_u32; + scope.address_low = child.get_attribute(Dwarf::Attribute::LowPc).value().data.as_addr; // The attribute name HighPc is confusing. In this context, it seems to actually be a positive offset from LowPc - scope.address_high = scope.address_low + child.get_attribute(Dwarf::Attribute::HighPc).value().data.as_u32; + scope.address_high = scope.address_low + child.get_attribute(Dwarf::Attribute::HighPc).value().data.as_addr; child.for_each_child([&](Dwarf::DIE const& variable_entry) { if (!(variable_entry.tag() == Dwarf::EntryTag::Variable @@ -78,7 +78,6 @@ void DebugInfo::parse_scopes_impl(Dwarf::DIE const& die) void DebugInfo::prepare_lines() { - Vector<Dwarf::LineProgram::LineInfo> all_lines; m_dwarf_info.for_each_compilation_unit([&all_lines](Dwarf::CompilationUnit const& unit) { all_lines.extend(unit.line_program().lines()); @@ -115,7 +114,7 @@ void DebugInfo::prepare_lines() }); } -Optional<DebugInfo::SourcePosition> DebugInfo::get_source_position(u32 target_address) const +Optional<DebugInfo::SourcePosition> DebugInfo::get_source_position(FlatPtr target_address) const { if (m_sorted_lines.is_empty()) return {}; @@ -219,7 +218,7 @@ static void parse_variable_location(Dwarf::DIE const& variable_die, DebugInfo::V switch (location_info.value().type) { case Dwarf::AttributeValue::Type::UnsignedNumber: variable_info.location_type = DebugInfo::VariableInfo::LocationType::Address; - variable_info.location_data.address = location_info.value().data.as_u32; + variable_info.location_data.address = location_info.value().data.as_addr; break; case Dwarf::AttributeValue::Type::DwarfExpression: { auto expression_bytes = ReadonlyBytes { location_info.value().data.as_raw_bytes.bytes, location_info.value().data.as_raw_bytes.length }; @@ -228,7 +227,7 @@ static void parse_variable_location(Dwarf::DIE const& variable_die, DebugInfo::V if (value.type != Dwarf::Expression::Type::None) { VERIFY(value.type == Dwarf::Expression::Type::UnsignedInteger); variable_info.location_type = DebugInfo::VariableInfo::LocationType::Address; - variable_info.location_data.address = value.data.as_u32; + variable_info.location_data.address = value.data.as_addr; } break; } @@ -349,7 +348,7 @@ bool DebugInfo::is_variable_tag_supported(Dwarf::EntryTag const& tag) || tag == Dwarf::EntryTag::ArrayType; } -String DebugInfo::name_of_containing_function(u32 address) const +String DebugInfo::name_of_containing_function(FlatPtr address) const { auto function = get_containing_function(address); if (!function.has_value()) @@ -357,7 +356,7 @@ String DebugInfo::name_of_containing_function(u32 address) const return function.value().name; } -Optional<DebugInfo::VariablesScope> DebugInfo::get_containing_function(u32 address) const +Optional<DebugInfo::VariablesScope> DebugInfo::get_containing_function(FlatPtr address) const { for (const auto& scope : m_scopes) { if (!scope.is_function || address < scope.address_low || address >= scope.address_high) @@ -386,7 +385,7 @@ DebugInfo::SourcePosition DebugInfo::SourcePosition::from_line_info(Dwarf::LineP return { line.file, line.line, line.address }; } -DebugInfo::SourcePositionWithInlines DebugInfo::get_source_position_with_inlines(u32 address) const +DebugInfo::SourcePositionWithInlines DebugInfo::get_source_position_with_inlines(FlatPtr address) const { // If the address is in an "inline chain", this is the inner-most inlined position. auto inner_source_position = get_source_position(address); diff --git a/Userland/Libraries/LibDebug/DebugInfo.h b/Userland/Libraries/LibDebug/DebugInfo.h index d920a74851ae..c238ff63cf71 100644 --- a/Userland/Libraries/LibDebug/DebugInfo.h +++ b/Userland/Libraries/LibDebug/DebugInfo.h @@ -31,7 +31,7 @@ class DebugInfo { struct SourcePosition { FlyString file_path; size_t line_number { 0 }; - Optional<u32> address_of_first_statement; + Optional<FlatPtr> address_of_first_statement; SourcePosition() : SourcePosition(String::empty(), 0) @@ -42,7 +42,7 @@ class DebugInfo { , line_number(line_number) { } - SourcePosition(String file_path, size_t line_number, u32 address_of_first_statement) + SourcePosition(String file_path, size_t line_number, FlatPtr address_of_first_statement) : file_path(file_path) , line_number(line_number) , address_of_first_statement(address_of_first_statement) @@ -65,7 +65,7 @@ class DebugInfo { String type_name; LocationType location_type { LocationType::None }; union { - u32 address; + FlatPtr address; } location_data { 0 }; union { @@ -86,20 +86,20 @@ class DebugInfo { struct VariablesScope { bool is_function { false }; String name; - u32 address_low { 0 }; - u32 address_high { 0 }; // Non-inclusive - the lowest address after address_low that's not in this scope + FlatPtr address_low { 0 }; + FlatPtr address_high { 0 }; // Non-inclusive - the lowest address after address_low that's not in this scope Vector<Dwarf::DIE> dies_of_variables; }; NonnullOwnPtrVector<VariableInfo> get_variables_in_current_scope(PtraceRegisters const&) const; - Optional<SourcePosition> get_source_position(u32 address) const; + Optional<SourcePosition> get_source_position(FlatPtr address) const; struct SourcePositionWithInlines { Optional<SourcePosition> source_position; Vector<SourcePosition> inline_chain; }; - SourcePositionWithInlines get_source_position_with_inlines(u32 address) const; + SourcePositionWithInlines get_source_position_with_inlines(FlatPtr address) const; struct SourcePositionAndAddress { String file; @@ -109,9 +109,9 @@ class DebugInfo { Optional<SourcePositionAndAddress> get_address_from_source_position(const String& file, size_t line) const; - String name_of_containing_function(u32 address) const; + String name_of_containing_function(FlatPtr address) const; Vector<SourcePosition> source_lines_in_scope(const VariablesScope&) const; - Optional<VariablesScope> get_containing_function(u32 address) const; + Optional<VariablesScope> get_containing_function(FlatPtr address) const; private: void prepare_variable_scopes(); diff --git a/Userland/Libraries/LibDebug/Dwarf/AttributeValue.h b/Userland/Libraries/LibDebug/Dwarf/AttributeValue.h index d2a5e045e07d..258f60e55ba5 100644 --- a/Userland/Libraries/LibDebug/Dwarf/AttributeValue.h +++ b/Userland/Libraries/LibDebug/Dwarf/AttributeValue.h @@ -25,6 +25,7 @@ struct AttributeValue { } type; union { + FlatPtr as_addr; u32 as_u32; i32 as_i32; u64 as_u64; diff --git a/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp b/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp index e912740bd717..a2364b3d7e01 100644 --- a/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp +++ b/Userland/Libraries/LibDebug/Dwarf/DwarfInfo.cpp @@ -47,7 +47,7 @@ void DwarfInfo::populate_compilation_units() debug_info_stream >> compilation_unit_header; VERIFY(compilation_unit_header.common.version <= 5); - VERIFY(compilation_unit_header.address_size() == sizeof(u32)); + VERIFY(compilation_unit_header.address_size() == sizeof(FlatPtr)); u32 length_after_header = compilation_unit_header.length() - (compilation_unit_header.header_size() - offsetof(CompilationUnitHeader, common.version)); @@ -102,11 +102,11 @@ AttributeValue DwarfInfo::get_attribute_value(AttributeDataForm form, ssize_t im break; } case AttributeDataForm::Addr: { - u32 address; + FlatPtr address; debug_info_stream >> address; VERIFY(!debug_info_stream.has_any_error()); value.type = AttributeValue::Type::UnsignedNumber; - value.data.as_u32 = address; + value.data.as_addr = address; break; } case AttributeDataForm::SData: { @@ -250,7 +250,6 @@ void DwarfInfo::build_cached_dies() const if (!start.has_value() || !end.has_value()) return {}; - VERIFY(sizeof(FlatPtr) == sizeof(u32)); VERIFY(start->type == Dwarf::AttributeValue::Type::UnsignedNumber); // DW_AT_high_pc attribute can have different meanings depending on the attribute form. @@ -258,7 +257,7 @@ void DwarfInfo::build_cached_dies() const uint32_t range_end = 0; if (end->form == Dwarf::AttributeDataForm::Addr) - range_end = end->data.as_u32; + range_end = end->data.as_addr; else range_end = start->data.as_u32 + end->data.as_u32; diff --git a/Userland/Libraries/LibDebug/Dwarf/Expression.h b/Userland/Libraries/LibDebug/Dwarf/Expression.h index 0355a0a648fc..90f0737e8dcb 100644 --- a/Userland/Libraries/LibDebug/Dwarf/Expression.h +++ b/Userland/Libraries/LibDebug/Dwarf/Expression.h @@ -22,6 +22,7 @@ enum class Type { struct Value { Type type; union { + FlatPtr as_addr; u32 as_u32; } data { 0 }; }; diff --git a/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp b/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp index e1d6da2406c6..86106dfb1479 100644 --- a/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp +++ b/Userland/Libraries/LibDebug/Dwarf/LineProgram.cpp @@ -174,7 +174,7 @@ void LineProgram::handle_extended_opcode() break; } default: - dbgln_if(DWARF_DEBUG, "offset: {:p}", m_stream.offset()); + dbgln("Encountered unknown sub opcode {} at stream offset {:p}", sub_opcode, m_stream.offset()); VERIFY_NOT_REACHED(); } } diff --git a/Userland/Libraries/LibDebug/Dwarf/LineProgram.h b/Userland/Libraries/LibDebug/Dwarf/LineProgram.h index 8eecbff86a99..d5fc9cacc20d 100644 --- a/Userland/Libraries/LibDebug/Dwarf/LineProgram.h +++ b/Userland/Libraries/LibDebug/Dwarf/LineProgram.h @@ -109,7 +109,7 @@ class LineProgram { explicit LineProgram(DwarfInfo& dwarf_info, InputMemoryStream& stream); struct LineInfo { - u32 address { 0 }; + FlatPtr address { 0 }; FlyString file; size_t line { 0 }; }; @@ -176,7 +176,7 @@ class LineProgram { Vector<FileEntry> m_source_files; // The registers of the "line program" virtual machine - u32 m_address { 0 }; + FlatPtr m_address { 0 }; size_t m_line { 0 }; size_t m_file_index { 0 }; bool m_is_statement { false };
bc75ca4fe55b0a19852c20e677bb4008156ceaff
2021-08-07 16:18:22
Timothy
ak: Add method to create MappedFile from fd
false
Add method to create MappedFile from fd
ak
diff --git a/AK/MappedFile.cpp b/AK/MappedFile.cpp index 3957d042a3b5..6323c1bb93fa 100644 --- a/AK/MappedFile.cpp +++ b/AK/MappedFile.cpp @@ -21,6 +21,15 @@ Result<NonnullRefPtr<MappedFile>, OSError> MappedFile::map(const String& path) if (fd < 0) return OSError(errno); + return map_from_fd_and_close(fd, path); +} + +Result<NonnullRefPtr<MappedFile>, OSError> MappedFile::map_from_fd_and_close(int fd, [[maybe_unused]] String const& path) +{ + if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) { + return OSError(errno); + } + ScopeGuard fd_close_guard = [fd] { close(fd); }; diff --git a/AK/MappedFile.h b/AK/MappedFile.h index 23a8eeccd6ee..9002d8beb1a6 100644 --- a/AK/MappedFile.h +++ b/AK/MappedFile.h @@ -20,6 +20,7 @@ class MappedFile : public RefCounted<MappedFile> { public: static Result<NonnullRefPtr<MappedFile>, OSError> map(const String& path); + static Result<NonnullRefPtr<MappedFile>, OSError> map_from_fd_and_close(int fd, String const& path); ~MappedFile(); void* data() { return m_data; }
eb11ab2480e113d6d1b836f7924de1fd2c7014a7
2020-06-13 23:17:43
Paul Roukema
base: Add some interlaced PNGs to the local copies of the pngsuite tests
false
Add some interlaced PNGs to the local copies of the pngsuite tests
base
diff --git a/Base/home/anon/www/pngsuite_int_png.html b/Base/home/anon/www/pngsuite_int_png.html new file mode 100644 index 000000000000..855c19a66c5d --- /dev/null +++ b/Base/home/anon/www/pngsuite_int_png.html @@ -0,0 +1,26 @@ +<HTML> +<HEAD> +<TITLE>PngSuite - Interlacing / PNG-files</TITLE> +</HEAD> +<BODY BGCOLOR="#ede"> + +<!-- Modified version of http://schaik.com/pngsuite/pngsuite_bas_png.html --> + +<BR><IMG SRC="http://schaik.com/pngsuite/basi0g01.png" WIDTH="32" HEIGHT="32"> --- basi0g01 - black & white +<BR><IMG SRC="http://schaik.com/pngsuite/basi0g02.png" WIDTH="32" HEIGHT="32"> --- basi0g02 - 2 bit (4 level) grayscale +<BR><IMG SRC="http://schaik.com/pngsuite/basi0g04.png" WIDTH="32" HEIGHT="32"> --- basi0g04 - 4 bit (16 level) grayscale +<BR><IMG SRC="http://schaik.com/pngsuite/basi0g08.png" WIDTH="32" HEIGHT="32"> --- basi0g08 - 8 bit (256 level) grayscale +<BR><IMG SRC="http://schaik.com/pngsuite/basi0g16.png" WIDTH="32" HEIGHT="32"> --- basi0g16 - 16 bit (64k level) grayscale +<BR><IMG SRC="http://schaik.com/pngsuite/basi2c08.png" WIDTH="32" HEIGHT="32"> --- basi2c08 - 3x8 bits rgb color +<BR><IMG SRC="http://schaik.com/pngsuite/basi2c16.png" WIDTH="32" HEIGHT="32"> --- basi2c16 - 3x16 bits rgb color +<BR><IMG SRC="http://schaik.com/pngsuite/basi3p01.png" WIDTH="32" HEIGHT="32"> --- basi3p01 - 1 bit (2 color) paletted +<BR><IMG SRC="http://schaik.com/pngsuite/basi3p02.png" WIDTH="32" HEIGHT="32"> --- basi3p02 - 2 bit (4 color) paletted +<BR><IMG SRC="http://schaik.com/pngsuite/basi3p04.png" WIDTH="32" HEIGHT="32"> --- basi3p04 - 4 bit (16 color) paletted +<BR><IMG SRC="http://schaik.com/pngsuite/basi3p08.png" WIDTH="32" HEIGHT="32"> --- basi3p08 - 8 bit (256 color) paletted +<BR><IMG SRC="http://schaik.com/pngsuite/basi4a08.png" WIDTH="32" HEIGHT="32"> --- basi4a08 - 8 bit grayscale + 8 bit alpha-channel +<BR><IMG SRC="http://schaik.com/pngsuite/basi4a16.png" WIDTH="32" HEIGHT="32"> --- basi4a16 - 16 bit grayscale + 16 bit alpha-channel +<BR><IMG SRC="http://schaik.com/pngsuite/basi6a08.png" WIDTH="32" HEIGHT="32"> --- basi6a08 - 3x8 bits rgb color + 8 bit alpha-channel +<BR><IMG SRC="http://schaik.com/pngsuite/basi6a16.png" WIDTH="32" HEIGHT="32"> --- basi6a16 - 3x16 bits rgb color + 16 bit alpha-channel + +</BODY> +</HTML> diff --git a/Base/home/anon/www/pngsuite_siz_png.html b/Base/home/anon/www/pngsuite_siz_png.html index 1ed2d0720855..93721eea5445 100644 --- a/Base/home/anon/www/pngsuite_siz_png.html +++ b/Base/home/anon/www/pngsuite_siz_png.html @@ -7,23 +7,41 @@ <!-- Modified version of http://schaik.com/pngsuite/pngsuite_siz_png.html --> <BR><IMG SRC="http://schaik.com/pngsuite/s01n3p01.png" WIDTH="1" HEIGHT="1"> --- s01n3p01 - 1x1 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s01i3p01.png" WIDTH="1" HEIGHT="1"> --- s01i3p01 - 1x1 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s02n3p01.png" WIDTH="2" HEIGHT="2"> --- s02n3p01 - 2x2 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s02i3p01.png" WIDTH="2" HEIGHT="2"> --- s02i3p01 - 2x2 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s03n3p01.png" WIDTH="3" HEIGHT="3"> --- s03n3p01 - 3x3 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s03i3p01.png" WIDTH="3" HEIGHT="3"> --- s03i3p01 - 3x3 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s04n3p01.png" WIDTH="4" HEIGHT="4"> --- s04n3p01 - 4x4 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s04i3p01.png" WIDTH="4" HEIGHT="4"> --- s04i3p01 - 4x4 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s05n3p02.png" WIDTH="5" HEIGHT="5"> --- s05n3p02 - 5x5 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s05i3p02.png" WIDTH="5" HEIGHT="5"> --- s05i3p02 - 5x5 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s06n3p02.png" WIDTH="6" HEIGHT="6"> --- s06n3p02 - 6x6 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s06i3p02.png" WIDTH="6" HEIGHT="6"> --- s06i3p02 - 6x6 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s07n3p02.png" WIDTH="7" HEIGHT="7"> --- s07n3p02 - 7x7 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s07i3p02.png" WIDTH="7" HEIGHT="7"> --- s07i3p02 - 7x7 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s08n3p02.png" WIDTH="8" HEIGHT="8"> --- s08n3p02 - 8x8 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s08i3p02.png" WIDTH="8" HEIGHT="8"> --- s08i3p02 - 8x8 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s09n3p02.png" WIDTH="9" HEIGHT="9"> --- s09n3p02 - 9x9 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s09i3p02.png" WIDTH="9" HEIGHT="9"> --- s09i3p02 - 9x9 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s32n3p04.png" WIDTH="32" HEIGHT="32"> --- s32n3p04 - 32x32 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s32i3p04.png" WIDTH="32" HEIGHT="32"> --- s32i3p04 - 32x32 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s33n3p04.png" WIDTH="33" HEIGHT="33"> --- s33n3p04 - 33x33 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s33i3p04.png" WIDTH="33" HEIGHT="33"> --- s33i3p04 - 33x33 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s34n3p04.png" WIDTH="34" HEIGHT="34"> --- s34n3p04 - 34x34 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s34i3p04.png" WIDTH="34" HEIGHT="34"> --- s34i3p04 - 34x34 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s35n3p04.png" WIDTH="35" HEIGHT="35"> --- s35n3p04 - 35x35 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s35i3p04.png" WIDTH="35" HEIGHT="35"> --- s35i3p04 - 35x35 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s36n3p04.png" WIDTH="36" HEIGHT="36"> --- s36n3p04 - 36x36 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s36i3p04.png" WIDTH="36" HEIGHT="36"> --- s36i3p04 - 36x36 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s37n3p04.png" WIDTH="37" HEIGHT="37"> --- s37n3p04 - 37x37 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s37i3p04.png" WIDTH="37" HEIGHT="37"> --- s37i3p04 - 37x37 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s38n3p04.png" WIDTH="38" HEIGHT="38"> --- s38n3p04 - 38x38 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s38i3p04.png" WIDTH="38" HEIGHT="38"> --- s38i3p04 - 38x38 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s39n3p04.png" WIDTH="39" HEIGHT="39"> --- s39n3p04 - 39x39 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s39i3p04.png" WIDTH="39" HEIGHT="39"> --- s39i3p04 - 39x39 paletted file, interlaced <BR><IMG SRC="http://schaik.com/pngsuite/s40n3p04.png" WIDTH="40" HEIGHT="40"> --- s40n3p04 - 40x40 paletted file, no interlacing +<BR><IMG SRC="http://schaik.com/pngsuite/s40i3p04.png" WIDTH="40" HEIGHT="40"> --- s40i3p04 - 40x40 paletted file, interlaced </BODY> </HTML> diff --git a/Base/home/anon/www/welcome.html b/Base/home/anon/www/welcome.html index 42e2e6865ff7..1a85077a1f31 100644 --- a/Base/home/anon/www/welcome.html +++ b/Base/home/anon/www/welcome.html @@ -43,6 +43,7 @@ <h1>Welcome to the Serenity Browser!</h1> <li><a href="canvas-path-quadratic-curve.html">canvas path quadratic curve test</a></li> <li><a href="pngsuite_siz_png.html">pngsuite odd sizes test</a></li> <li><a href="pngsuite_bas_png.html">pngsuite basic formats test</a></li> + <li><a href="pngsuite_int_png.html">pngsuite interlacing test</a></li> <li><a href="canvas-path.html">canvas path house!</a></li> <li><a href="img-canvas.html">canvas drawImage() test</a></li> <li><a href="trigonometry.html">canvas + trigonometry functions</a></li>
af7003ebd24cf4f3a4d083f62bc1caff564b6128
2022-02-09 17:55:27
Linus Groh
libjs: Convert 'possible instants' AOs to MarkedVector<Instant*>
false
Convert 'possible instants' AOs to MarkedVector<Instant*>
libjs
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp index 37a68e0224ce..71da4456bbc0 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.cpp @@ -529,10 +529,8 @@ ThrowCompletionOr<Instant*> builtin_time_zone_get_instant_for(GlobalObject& glob } // 11.6.15 DisambiguatePossibleInstants ( possibleInstants, timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-disambiguatepossibleinstants -ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_object, Vector<Value> const& possible_instants, Value time_zone, PlainDateTime& date_time, StringView disambiguation) +ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_object, MarkedVector<Instant*> const& possible_instants, Value time_zone, PlainDateTime& date_time, StringView disambiguation) { - // TODO: MarkedValueList<T> would be nice, then we could pass a Vector<Instant*> here and wouldn't need the casts... - auto& vm = global_object.vm(); // 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot. @@ -543,8 +541,7 @@ ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_ // 3. If n = 1, then if (n == 1) { // a. Return possibleInstants[0]. - auto& instant = possible_instants[0]; - return &static_cast<Instant&>(const_cast<Object&>(instant.as_object())); + return possible_instants[0]; } // 4. If n ≠ 0, then @@ -552,15 +549,13 @@ ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_ // a. If disambiguation is "earlier" or "compatible", then if (disambiguation.is_one_of("earlier"sv, "compatible"sv)) { // i. Return possibleInstants[0]. - auto& instant = possible_instants[0]; - return &static_cast<Instant&>(const_cast<Object&>(instant.as_object())); + return possible_instants[0]; } // b. If disambiguation is "later", then if (disambiguation == "later"sv) { // i. Return possibleInstants[n − 1]. - auto& instant = possible_instants[n - 1]; - return &static_cast<Instant&>(const_cast<Object&>(instant.as_object())); + return possible_instants[n - 1]; } // c. Assert: disambiguation is "reject". @@ -606,15 +601,14 @@ ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_ auto* earlier_date_time = MUST(create_temporal_date_time(global_object, earlier.year, earlier.month, earlier.day, earlier.hour, earlier.minute, earlier.second, earlier.millisecond, earlier.microsecond, earlier.nanosecond, date_time.calendar())); // c. Set possibleInstants to ? GetPossibleInstantsFor(timeZone, earlierDateTime). - auto possible_instants_mvl = TRY(get_possible_instants_for(global_object, time_zone, *earlier_date_time)); + auto possible_instants_ = TRY(get_possible_instants_for(global_object, time_zone, *earlier_date_time)); // d. If possibleInstants is empty, throw a RangeError exception. - if (possible_instants_mvl.is_empty()) + if (possible_instants_.is_empty()) return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDisambiguatePossibleInstantsEarlierZero); // e. Return possibleInstants[0]. - auto& instant = possible_instants_mvl[0]; - return &static_cast<Instant&>(const_cast<Object&>(instant.as_object())); + return possible_instants_[0]; } // 14. Assert: disambiguation is "compatible" or "later". @@ -627,22 +621,21 @@ ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_ auto* later_date_time = MUST(create_temporal_date_time(global_object, later.year, later.month, later.day, later.hour, later.minute, later.second, later.millisecond, later.microsecond, later.nanosecond, date_time.calendar())); // 17. Set possibleInstants to ? GetPossibleInstantsFor(timeZone, laterDateTime). - auto possible_instants_mvl = TRY(get_possible_instants_for(global_object, time_zone, *later_date_time)); + auto possible_instants_ = TRY(get_possible_instants_for(global_object, time_zone, *later_date_time)); // 18. Set n to possibleInstants's length. - n = possible_instants_mvl.size(); + n = possible_instants_.size(); // 19. If n = 0, throw a RangeError exception. if (n == 0) return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDisambiguatePossibleInstantsZero); // 20. Return possibleInstants[n − 1]. - auto& instant = possible_instants_mvl[n - 1]; - return &static_cast<Instant&>(const_cast<Object&>(instant.as_object())); + return possible_instants_[n - 1]; } // 11.6.16 GetPossibleInstantsFor ( timeZone, dateTime ), https://tc39.es/proposal-temporal/#sec-temporal-getpossibleinstantsfor -ThrowCompletionOr<MarkedValueList> get_possible_instants_for(GlobalObject& global_object, Value time_zone, PlainDateTime& date_time) +ThrowCompletionOr<MarkedVector<Instant*>> get_possible_instants_for(GlobalObject& global_object, Value time_zone, PlainDateTime& date_time) { auto& vm = global_object.vm(); @@ -655,7 +648,7 @@ ThrowCompletionOr<MarkedValueList> get_possible_instants_for(GlobalObject& globa auto iterator = TRY(get_iterator(global_object, possible_instants, IteratorHint::Sync)); // 4. Let list be a new empty List. - auto list = MarkedValueList { vm.heap() }; + auto list = MarkedVector<Instant*> { vm.heap() }; // 5. Let next be true. Object* next = nullptr; @@ -680,7 +673,7 @@ ThrowCompletionOr<MarkedValueList> get_possible_instants_for(GlobalObject& globa } // iii. Append nextValue to the end of the List list. - list.append(next_value); + list.append(static_cast<Instant*>(&next_value.as_object())); } } while (next != nullptr); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h index cc932facecce..2b800e87ca7f 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h +++ b/Userland/Libraries/LibJS/Runtime/Temporal/TimeZone.h @@ -7,6 +7,7 @@ #pragma once #include <AK/Optional.h> +#include <LibJS/Heap/MarkedVector.h> #include <LibJS/Runtime/MarkedValueList.h> #include <LibJS/Runtime/Object.h> #include <LibJS/Runtime/Temporal/AbstractOperations.h> @@ -53,8 +54,8 @@ ThrowCompletionOr<double> get_offset_nanoseconds_for(GlobalObject&, Value time_z ThrowCompletionOr<String> builtin_time_zone_get_offset_string_for(GlobalObject&, Value time_zone, Instant&); ThrowCompletionOr<PlainDateTime*> builtin_time_zone_get_plain_date_time_for(GlobalObject&, Value time_zone, Instant&, Object& calendar); ThrowCompletionOr<Instant*> builtin_time_zone_get_instant_for(GlobalObject&, Value time_zone, PlainDateTime&, StringView disambiguation); -ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject&, Vector<Value> const& possible_instants, Value time_zone, PlainDateTime&, StringView disambiguation); -ThrowCompletionOr<MarkedValueList> get_possible_instants_for(GlobalObject&, Value time_zone, PlainDateTime&); +ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject&, MarkedVector<Instant*> const& possible_instants, Value time_zone, PlainDateTime&, StringView disambiguation); +ThrowCompletionOr<MarkedVector<Instant*>> get_possible_instants_for(GlobalObject&, Value time_zone, PlainDateTime&); ThrowCompletionOr<bool> time_zone_equals(GlobalObject&, Object& one, Object& two); bool is_valid_time_zone_numeric_utc_offset_syntax(String const&); diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp index cc5fd3f0cbec..66a9eeef45f6 100644 --- a/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp +++ b/Userland/Libraries/LibJS/Runtime/Temporal/ZonedDateTime.cpp @@ -79,17 +79,14 @@ ThrowCompletionOr<BigInt const*> interpret_iso_date_time_offset(GlobalObject& gl auto possible_instants = TRY(get_possible_instants_for(global_object, time_zone, *date_time)); // 9. For each element candidate of possibleInstants, do - for (auto& candidate_value : possible_instants) { - // TODO: As per the comment in disambiguate_possible_instants, having a MarkedValueList<T> would allow us to remove this cast. - auto& candidate = static_cast<Instant&>(candidate_value.as_object()); - + for (auto* candidate : possible_instants) { // a. Let candidateNanoseconds be ? GetOffsetNanosecondsFor(timeZone, candidate). - auto candidate_nanoseconds = TRY(get_offset_nanoseconds_for(global_object, time_zone, candidate)); + auto candidate_nanoseconds = TRY(get_offset_nanoseconds_for(global_object, time_zone, *candidate)); // b. If candidateNanoseconds = offsetNanoseconds, then if (candidate_nanoseconds == offset_nanoseconds) { // i. Return candidate.[[Nanoseconds]]. - return &candidate.nanoseconds(); + return &candidate->nanoseconds(); } // c. If matchBehaviour is match minutes, then @@ -100,7 +97,7 @@ ThrowCompletionOr<BigInt const*> interpret_iso_date_time_offset(GlobalObject& gl // ii. If roundedCandidateNanoseconds = offsetNanoseconds, then if (rounded_candidate_nanoseconds == offset_nanoseconds) { // 1. Return candidate.[[Nanoseconds]]. - return &candidate.nanoseconds(); + return &candidate->nanoseconds(); } } }
e33037ad52cc79b59d05c4533af39cdc8f0df065
2025-01-29 14:00:18
Aliaksandr Kalenik
libweb: Add method to check if element affected by invalidation set
false
Add method to check if element affected by invalidation set
libweb
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp index 3a21331c0de8..b37b295a03bc 100644 --- a/Libraries/LibWeb/DOM/Element.cpp +++ b/Libraries/LibWeb/DOM/Element.cpp @@ -1149,52 +1149,64 @@ bool Element::affected_by_hover() const return false; } -bool Element::affected_by_invalidation_property(CSS::InvalidationSet::Property const& property) const -{ - switch (property.type) { - case CSS::InvalidationSet::Property::Type::Class: - return m_classes.contains_slow(property.name()); - case CSS::InvalidationSet::Property::Type::Id: - return m_id == property.name(); - case CSS::InvalidationSet::Property::Type::TagName: - return local_name() == property.name(); - case CSS::InvalidationSet::Property::Type::Attribute: { - if (property.name() == HTML::AttributeNames::id || property.name() == HTML::AttributeNames::class_) - return true; - return has_attribute(property.name()); - } - case CSS::InvalidationSet::Property::Type::PseudoClass: { - switch (property.value.get<CSS::PseudoClass>()) { - case CSS::PseudoClass::Enabled: { - return (is<HTML::HTMLButtonElement>(*this) || is<HTML::HTMLInputElement>(*this) || is<HTML::HTMLSelectElement>(*this) || is<HTML::HTMLTextAreaElement>(*this) || is<HTML::HTMLOptGroupElement>(*this) || is<HTML::HTMLOptionElement>(*this) || is<HTML::HTMLFieldSetElement>(*this)) - && !is_actually_disabled(); - } - case CSS::PseudoClass::Disabled: { - return is_actually_disabled(); - } - case CSS::PseudoClass::Checked: { - // FIXME: This could be narrowed down to return true only if element is actually checked. - return is<HTML::HTMLInputElement>(*this) || is<HTML::HTMLOptionElement>(*this); +bool Element::includes_properties_from_invalidation_set(CSS::InvalidationSet const& set) const +{ + auto includes_property = [&](CSS::InvalidationSet::Property const& property) { + switch (property.type) { + case CSS::InvalidationSet::Property::Type::Class: + return m_classes.contains_slow(property.name()); + case CSS::InvalidationSet::Property::Type::Id: + return m_id == property.name(); + case CSS::InvalidationSet::Property::Type::TagName: + return local_name() == property.name(); + case CSS::InvalidationSet::Property::Type::Attribute: { + if (property.name() == HTML::AttributeNames::id || property.name() == HTML::AttributeNames::class_) + return true; + return has_attribute(property.name()); } - case CSS::PseudoClass::PlaceholderShown: { - if (is<HTML::HTMLInputElement>(*this) && has_attribute(HTML::AttributeNames::placeholder)) { - auto const& input_element = static_cast<HTML::HTMLInputElement const&>(*this); - return input_element.placeholder_element() && input_element.placeholder_value().has_value(); + case CSS::InvalidationSet::Property::Type::PseudoClass: { + switch (property.value.get<CSS::PseudoClass>()) { + case CSS::PseudoClass::Enabled: { + return (is<HTML::HTMLButtonElement>(*this) || is<HTML::HTMLInputElement>(*this) || is<HTML::HTMLSelectElement>(*this) || is<HTML::HTMLTextAreaElement>(*this) || is<HTML::HTMLOptGroupElement>(*this) || is<HTML::HTMLOptionElement>(*this) || is<HTML::HTMLFieldSetElement>(*this)) + && !is_actually_disabled(); + } + case CSS::PseudoClass::Disabled: { + return is_actually_disabled(); + } + case CSS::PseudoClass::Checked: { + // FIXME: This could be narrowed down to return true only if element is actually checked. + return is<HTML::HTMLInputElement>(*this) || is<HTML::HTMLOptionElement>(*this); + } + case CSS::PseudoClass::PlaceholderShown: { + if (is<HTML::HTMLInputElement>(*this) && has_attribute(HTML::AttributeNames::placeholder)) { + auto const& input_element = static_cast<HTML::HTMLInputElement const&>(*this); + return input_element.placeholder_element() && input_element.placeholder_value().has_value(); + } + // - FIXME: textarea elements that have a placeholder attribute whose value is currently being presented to the user. + return false; + } + default: + VERIFY_NOT_REACHED(); } - // - FIXME: textarea elements that have a placeholder attribute whose value is currently being presented to the user. - return false; } + case CSS::InvalidationSet::Property::Type::InvalidateSelf: + return false; + case CSS::InvalidationSet::Property::Type::InvalidateWholeSubtree: + return true; default: VERIFY_NOT_REACHED(); } - } - case CSS::InvalidationSet::Property::Type::InvalidateSelf: - return false; - case CSS::InvalidationSet::Property::Type::InvalidateWholeSubtree: - return true; - default: - VERIFY_NOT_REACHED(); - } + }; + + bool includes_any = false; + set.for_each_property([&](auto const& property) { + if (includes_property(property)) { + includes_any = true; + return IterationDecision::Break; + } + return IterationDecision::Continue; + }); + return includes_any; } bool Element::has_pseudo_elements() const diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h index 3c785a79924f..130fec9aa730 100644 --- a/Libraries/LibWeb/DOM/Element.h +++ b/Libraries/LibWeb/DOM/Element.h @@ -266,7 +266,7 @@ class Element static GC::Ptr<Layout::NodeWithStyle> create_layout_node_for_display_type(DOM::Document&, CSS::Display const&, GC::Ref<CSS::ComputedProperties>, Element*); bool affected_by_hover() const; - bool affected_by_invalidation_property(CSS::InvalidationSet::Property const&) const; + bool includes_properties_from_invalidation_set(CSS::InvalidationSet const&) const; void set_pseudo_element_node(Badge<Layout::TreeBuilder>, CSS::Selector::PseudoElement::Type, GC::Ptr<Layout::NodeWithStyle>); GC::Ptr<Layout::NodeWithStyle> get_pseudo_element_node(CSS::Selector::PseudoElement::Type) const; diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp index ec8df229f3fd..be1919c630ae 100644 --- a/Libraries/LibWeb/DOM/Node.cpp +++ b/Libraries/LibWeb/DOM/Node.cpp @@ -486,18 +486,6 @@ void Node::invalidate_style(StyleInvalidationReason reason, Vector<CSS::Invalida set_needs_style_update(true); } - auto element_has_properties_from_invalidation_set = [&](Element& element) { - bool result = false; - invalidation_set.for_each_property([&](auto const& property) { - if (element.affected_by_invalidation_property(property)) { - result = true; - return IterationDecision::Break; - } - return IterationDecision::Continue; - }); - return result; - }; - auto invalidate_entire_subtree = [&](Node& subtree_root) { subtree_root.for_each_shadow_including_inclusive_descendant([&](Node& node) { if (!node.is_element()) @@ -506,7 +494,7 @@ void Node::invalidate_style(StyleInvalidationReason reason, Vector<CSS::Invalida bool needs_style_recalculation = false; if (invalidation_set.needs_invalidate_whole_subtree()) { needs_style_recalculation = true; - } else if (element_has_properties_from_invalidation_set(element)) { + } else if (element.includes_properties_from_invalidation_set(invalidation_set)) { needs_style_recalculation = true; } else if (options.invalidate_elements_that_use_css_custom_properties && element.style_uses_css_custom_properties()) { needs_style_recalculation = true;
18abba2c4d57485072254fb02e039f36aedeef47
2022-08-21 16:59:36
Andreas Kling
kernel: Make sys$getppid() not take the big lock
false
Make sys$getppid() not take the big lock
kernel
diff --git a/Kernel/API/Syscall.h b/Kernel/API/Syscall.h index cf53d789f9bf..dd88bddd83cf 100644 --- a/Kernel/API/Syscall.h +++ b/Kernel/API/Syscall.h @@ -92,7 +92,7 @@ enum class NeedsBigProcessLock { S(getpgid, NeedsBigProcessLock::Yes) \ S(getpgrp, NeedsBigProcessLock::Yes) \ S(getpid, NeedsBigProcessLock::No) \ - S(getppid, NeedsBigProcessLock::Yes) \ + S(getppid, NeedsBigProcessLock::No) \ S(getrandom, NeedsBigProcessLock::No) \ S(getresgid, NeedsBigProcessLock::No) \ S(getresuid, NeedsBigProcessLock::No) \ diff --git a/Kernel/Syscalls/process.cpp b/Kernel/Syscalls/process.cpp index 338e05b41342..612e8d8e67c3 100644 --- a/Kernel/Syscalls/process.cpp +++ b/Kernel/Syscalls/process.cpp @@ -18,9 +18,9 @@ ErrorOr<FlatPtr> Process::sys$getpid() ErrorOr<FlatPtr> Process::sys$getppid() { - VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this); + VERIFY_NO_PROCESS_BIG_LOCK(this); TRY(require_promise(Pledge::stdio)); - return with_protected_data([](auto& protected_data) { return protected_data.ppid.value(); }); + return ppid().value(); } ErrorOr<FlatPtr> Process::sys$get_process_name(Userspace<char*> buffer, size_t buffer_size)